diff --git a/Assets/Content/Prefabs/ShipModTemplate.prefab b/Assets/Content/Prefabs/ShipModTemplate.prefab new file mode 100644 index 000000000..7ed600cb6 --- /dev/null +++ b/Assets/Content/Prefabs/ShipModTemplate.prefab @@ -0,0 +1,51 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &4001 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 4002} + - component: {fileID: 4003} + m_Layer: 0 + m_Name: ShipModTemplate + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &4002 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 4001} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &4003 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 4001} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 7c3e9a52d8b14f0e8a6d2b1f4c95e703, type: 3} + m_Name: + m_EditorClassIdentifier: + Shield: {fileID: 8402070500206635106, guid: 897fa55d98f1f7f40b889f93ce9146f4, type: 3} + TractorBeam: {fileID: 2009124798951080406, guid: 1df59848be1db8547bc662080d0d6000, type: 3} + Ping: {fileID: 3496685214803260731, guid: bfcaa66e173f6a44cb640aabbcb5e429, type: 3} + DestroyEffect: {fileID: 1121192042590650, guid: e1b08032bec16ba4eb1ae23cbd572664, type: 3} + Invisible: {fileID: 2100000, guid: c94a225de88e5ce42af01c34df3521e6, type: 2} + MapIcon: {fileID: 2100000, guid: 64d1c3f8a4422884b88363be07521fb0, type: 2} diff --git a/Assets/Content/Prefabs/ShipModTemplate.prefab.meta b/Assets/Content/Prefabs/ShipModTemplate.prefab.meta new file mode 100644 index 000000000..d2ea9f827 --- /dev/null +++ b/Assets/Content/Prefabs/ShipModTemplate.prefab.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 5d1f3a8c7e2b4f60a9c4b7e1d3f2a860 +PrefabImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Editor/ShipModPlaySmoke.cs b/Assets/Scripts/Editor/ShipModPlaySmoke.cs new file mode 100644 index 000000000..a4fb708b5 --- /dev/null +++ b/Assets/Scripts/Editor/ShipModPlaySmoke.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEngine; + +// Batch proof that a mod ship survives the game's own path into a zone, without a scene: the derived catalog composed +// with one package, ShipModShips.Preload over it, then ShipModShips.Instantiate, which is what ZoneRenderer.LoadEntity's +// Body() calls for a hull with a Visual. A plain parent transform stands in for ZoneRoot; nothing else in LoadEntity +// touches the body before it takes its ShipInstance. +// +// Unity -batchmode -nographics -projectPath -executeMethod ShipModPlaySmoke.Run +// -shipModPath //ship.cc [-shippedCatalog GameData/Aetheria.cc] -logFile +// +// Do not pass -quit: the method is async and exits the Editor itself, 0 on success and 1 on any failure. +public static class ShipModPlaySmoke +{ + public static async void Run() + { + var args = Environment.GetCommandLineArgs(); + string Option(string name, string fallback = null) + { + var at = Array.IndexOf(args, name); + return at >= 0 && at + 1 < args.Length ? args[at + 1] : fallback; + } + var packagePath = Option("-shipModPath"); + var derived = Path.Combine(Path.GetTempPath(), $"ship-mod-play-smoke-{Guid.NewGuid():N}.cc"); + GameObject zone = null; + try + { + if (packagePath == null) throw new InvalidOperationException("-shipModPath is required"); + var package = ShipModCatalog.ReadPackage(packagePath); + var modsRoot = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetFullPath(packagePath))); + var composition = ShipModCatalog.Compose(Path.GetFullPath(Option("-shippedCatalog", "GameData/Aetheria.cc")), derived, modsRoot); + if (!composition.Included.Contains(package.Visual.Id)) + throw new InvalidOperationException($"{package.Visual.Id} was not composed into the catalog: " + + string.Join("; ", composition.Excluded.Select(excluded => $"{excluded.Package}: {excluded.Reason}"))); + + using (var catalog = AetheriaStores.Open(derived)) + { + await ShipModShips.Preload(catalog, modsRoot); + var hull = catalog.GetAll().Single(candidate => candidate.Visual.IsSet() && candidate.Name == package.Hull.Name); + + zone = new GameObject("Play Smoke Zone"); + var ship = ShipModShips.Instantiate(hull, zone.transform).GetComponent(); + if (ship == null) throw new InvalidOperationException("The mod ship body has no ShipInstance."); + var thrusters = ship.ThrusterHardpoints?.Length ?? 0; + var weapons = ship.WeaponHardpoints?.Length ?? 0; + if (thrusters == 0) throw new InvalidOperationException("ThrusterHardpoints is empty."); + if (weapons == 0 || ship.WeaponHardpoints.Any(node => node.FiringPoint == null || node.FiringPoint.Length == 0)) + throw new InvalidOperationException("WeaponHardpoints is empty or a weapon has no muzzle."); + if (ship.HullColliders == null || ship.HullColliders.Length != 1) + throw new InvalidOperationException("The ship needs exactly one hull collider."); + var collider = ship.HullColliders[0].GetComponent(); + if (collider == null || collider.sharedMesh == null || !collider.sharedMesh.isReadable || collider.sharedMesh.vertexCount == 0) + throw new InvalidOperationException("The hull collider is not a MeshCollider over a readable mesh."); + if (ship.MapIcon == null || ship.MapIcon.sharedMaterial == null || ship.MapIcon.gameObject.layer != LayerMask.NameToLayer("Minimap")) + throw new InvalidOperationException("The map icon is missing its renderer, material or Minimap layer."); + Debug.Log($"SHIP_MOD_PLAY_SMOKE thrusters={thrusters} weapons={weapons} collider=ok mapicon=ok"); + } + if (zone != null) UnityEngine.Object.DestroyImmediate(zone); + EditorApplication.Exit(0); + } + catch (Exception exception) + { + Debug.LogException(exception); + if (zone != null) UnityEngine.Object.DestroyImmediate(zone); + EditorApplication.Exit(1); + } + } +} diff --git a/Assets/Scripts/Editor/ShipModPlaySmoke.cs.meta b/Assets/Scripts/Editor/ShipModPlaySmoke.cs.meta new file mode 100644 index 000000000..c6bb5936a --- /dev/null +++ b/Assets/Scripts/Editor/ShipModPlaySmoke.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a1f2b276e4d6582479c3216cc97a5164 \ No newline at end of file diff --git a/Assets/Scripts/Editor/ShipModPreview.cs b/Assets/Scripts/Editor/ShipModPreview.cs new file mode 100644 index 000000000..3cd6a05d0 --- /dev/null +++ b/Assets/Scripts/Editor/ShipModPreview.cs @@ -0,0 +1,94 @@ +using System; +using System.Linq; +using UnityEditor; +using UnityEngine; + +public static class ShipModPreview +{ + private const string TemplatePath = "Assets/Content/Prefabs/ShipModTemplate.prefab"; + + // Batch proof: -executeMethod ShipModPreview.Smoke -shipModPath [-assemble] + // -assemble also builds the game's ShipInstance from the package (ShipModShips.Assemble) and checks it against the + // plan and against a clone, the way Instantiate makes one. That needs a GLB with real meshes on the map-icon, + // hull-collider and emitter anchors; a nodes-only fixture fails it on purpose. + public static async void Smoke() + { + var args = Environment.GetCommandLineArgs(); + var option = Array.IndexOf(args, "-shipModPath"); + if (option < 0 || option + 1 >= args.Length) + { + Debug.LogError("-shipModPath is required"); + EditorApplication.Exit(1); + return; + } + ShipModVisual.Instance visual = null; + try + { + var package = ShipModCatalog.ReadPackage(args[option + 1]); + visual = await ShipModVisual.LoadAsync(package, null); + if (visual.Anchors.Count == 0 || visual.LineMesh == null || visual.LineMesh.vertexCount == 0) + throw new InvalidOperationException("Mod visual did not import anchors and line points."); + Debug.Log($"SHIP_MOD_VISUAL_SMOKE anchors={visual.Anchors.Count} points={visual.LineMesh.vertexCount} segments={visual.LineMesh.GetIndexCount(0) / 2}"); + if (Array.IndexOf(args, "-assemble") >= 0) CheckAssembly(visual, package); + visual.Destroy(); + EditorApplication.Exit(0); + } + catch (Exception exception) + { + Debug.LogException(exception); + visual?.Destroy(); + EditorApplication.Exit(1); + } + } + + private static void CheckAssembly(ShipModVisual.Instance visual, ShipModCatalog.Package package) + { + var template = AssetDatabase.LoadAssetAtPath(TemplatePath); + if (template == null) throw new InvalidOperationException($"{TemplatePath} is missing or has no ShipModTemplate."); + var plan = ShipModPlan.Build(package.Hull, package.Visual); + var ship = ShipModShips.Assemble(visual, package.Hull, package.Visual, template); + CheckShip(ship, plan, "assembled"); + + // Instantiate clones the assembled root, and Unity must remap every array reference into the clone. + var clone = UnityEngine.Object.Instantiate(ship.gameObject).GetComponent(); + try { CheckShip(clone, plan, "clone"); } + finally { UnityEngine.Object.DestroyImmediate(clone.gameObject); } + Debug.Log($"SHIP_MOD_ASSEMBLY_SMOKE equipment={plan.Equipment.Length} thrusters={plan.Thrusters.Length} " + + $"weapons={plan.Weapons.Length} radiators={plan.Radiators.Length}"); + } + + private static void CheckShip(ShipInstance ship, ShipModPlan plan, string what) + { + void Require(bool ok, string claim) { if (!ok) throw new InvalidOperationException($"{what}: {claim}"); } + bool Inside(Component part) => part != null && part.transform.IsChildOf(ship.transform); + Require(ship.HullColliders.Length == 1 && Inside(ship.HullColliders[0]) && + ship.HullColliders[0].GetComponent() != null, "one hull collider with a MeshCollider"); + Require(Inside(ship.MapIcon) && Inside(ship.Shield) && Inside(ship.TractorBeam), "map icon, shield and tractor inside the ship"); + Require(ship.EquipmentHardpoints.Select(node => node.name).SequenceEqual(plan.Equipment) && + ship.EquipmentHardpoints.All(Inside), "equipment hardpoints named by the plan"); + Require(ship.ThrusterHardpoints.Select(node => node.name).SequenceEqual(plan.Thrusters) && + ship.ThrusterHardpoints.All(node => Inside(node) && Inside(node.Emitter)), "thruster hardpoints with emitters"); + Require(ship.RadiatorHardpoints.Select(node => node.name).SequenceEqual(plan.Radiators) && + ship.RadiatorHardpoints.All(node => Inside(node) && Inside(node.Mesh)), "radiator hardpoints with meshes"); + Require(ship.WeaponHardpoints.Select(node => node.name).SequenceEqual(plan.Weapons.Select(weapon => weapon.Mount)) && + ship.WeaponHardpoints.Zip(plan.Weapons, (node, weapon) => + Inside(node) && node.FiringPoint.Select(point => point.name).SequenceEqual(weapon.Muzzles) && + node.FiringPoint.All(Inside)).All(ok => ok), "weapon hardpoints with their muzzles in order"); + } + + [MenuItem("Aetheria/Preview Mod Ship Package")] + private static async void Open() + { + var path = EditorUtility.OpenFilePanel("Ship authoring record", "GameData/Mods", "cc"); + if (string.IsNullOrEmpty(path)) return; + try + { + var visual = await ShipModVisual.LoadAsync(ShipModCatalog.ReadPackage(path), null); + Undo.RegisterCreatedObjectUndo(visual.Root, "Preview mod ship"); + Selection.activeGameObject = visual.Root; + SceneView.FrameLastActiveSceneView(); + Debug.Log($"Previewed {path}: {visual.Anchors.Count} anchors, {visual.LineMesh?.vertexCount ?? 0} line points."); + } + catch (Exception exception) { Debug.LogException(exception); } + } +} diff --git a/Assets/Scripts/Editor/ShipModPreview.cs.meta b/Assets/Scripts/Editor/ShipModPreview.cs.meta new file mode 100644 index 000000000..2e8ea6b35 --- /dev/null +++ b/Assets/Scripts/Editor/ShipModPreview.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4d32248a66f6454a9be20458fa43f3ef diff --git a/Assets/Scripts/Gameplay/ActionGameManager.cs b/Assets/Scripts/Gameplay/ActionGameManager.cs index 41165eae2..1576e88b9 100644 --- a/Assets/Scripts/Gameplay/ActionGameManager.cs +++ b/Assets/Scripts/Gameplay/ActionGameManager.cs @@ -42,7 +42,13 @@ public class ActionGameManager : MonoBehaviour private static CultCache _cultCache; + // Mod packages left out of this boot (a bad package, or a name collision), for the main menu to name. + public static ShipModCatalog.Exclusion[] ModExclusions { get; private set; } = Array.Empty(); + private static string CatalogPath => Path.Combine(GameDataDirectory.FullName, "Aetheria.cc"); + private static string ModsPath => Path.Combine(GameDataDirectory.FullName, "Mods"); + // Disposable: composed at every boot from the shipped catalog and the mod packages, never authored. + private static string DerivedCatalogPath => Path.Combine(Application.persistentDataPath, "Aetheria.modded.cc"); public static CultCache CultCache { @@ -52,12 +58,18 @@ public class ActionGameManager : MonoBehaviour // All three stores attach once and stay attached until the process exits. The run lifecycle is record-level // inside this cache; reopening would replace the catalog instances the galaxy and live entities hold. - // The catalog is read-only in every build; capturepreset writes through its own cache (Loadouts.Commit). + // The catalog is read-only in every build; capturepreset writes through its own cache (Loadouts.Commit) to the + // shipped file. With mod packages installed the game reads the derived catalog instead. + var (catalog, excluded) = ShipModCatalog.ResolveCatalog(CatalogPath, DerivedCatalogPath, ModsPath); + ModExclusions = excluded; _cultCache = AetheriaStores.Open( - CatalogPath, + catalog, runPath: Path.Combine(GameDataDirectory.FullName, "run.cc"), playerPath: Path.Combine(GameDataDirectory.FullName, "player.cc")); + // Mod ship prototypes import asynchronously from here; entering a game waits on ShipModShips.Loading. + ShipModShips.Preload(_cultCache, ModsPath); + return _cultCache; } } diff --git a/Assets/Scripts/Gameplay/ShipModShips.cs b/Assets/Scripts/Gameplay/ShipModShips.cs new file mode 100644 index 000000000..26761ad11 --- /dev/null +++ b/Assets/Scripts/Gameplay/ShipModShips.cs @@ -0,0 +1,170 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using GameCult.Caching; +using UnityEngine; +using Object = UnityEngine.Object; + +// Mod ships in the running game. Preload imports each catalog hull's GLB once, at boot, into an inactive assembled +// prototype keyed by the hull's record key; Instantiate then clones it synchronously, so LoadEntity never loads async. +// The prototypes are cache-only: rebuilt every boot from the catalog, the mod GLBs and the template. +public static class ShipModShips +{ + private static readonly Dictionary Prototypes = new Dictionary(); + private static CultCache _catalog; + + // Set by Preload; complete when every prototype is ready, faulted when any mod ship failed to import or assemble. + public static Task Loading { get; private set; } = Task.CompletedTask; + + public static Task Preload(CultCache catalog, string modsRoot) + { + Loading = PreloadAsync(catalog, modsRoot); + Loading.ContinueWith(task => Debug.LogException(task.Exception), TaskContinuationOptions.OnlyOnFaulted); + return Loading; + } + + private static async Task PreloadAsync(CultCache catalog, string modsRoot) + { + _catalog = catalog; + var hulls = catalog.GetAll().Where(hull => hull.Visual.IsSet()).ToArray(); + if (hulls.Length == 0) return; + var template = EngineAssets.Load(ShipModTemplate.Key); + if (template == null) + throw new InvalidOperationException($"The ship mod template prefab ({ShipModTemplate.Key}) is not loadable."); + var root = new GameObject("Mod Ship Prototypes"); + root.SetActive(false); + // DontDestroyOnLoad is play-mode only; the edit-mode play smoke builds the same prototypes + // without it, and nothing there loads scenes. + if (Application.isPlaying) Object.DontDestroyOnLoad(root); + foreach (var hull in hulls) + { + var package = ShipModCatalog.PackageOf(catalog, hull, modsRoot); + var visual = await ShipModVisual.LoadAsync(package, root.transform); + try + { + visual.Root.SetActive(false); + Assemble(visual, package.Hull, package.Visual, template); + Prototypes[catalog.RefOf(hull).Key] = visual.Root; + } + catch + { + visual.Destroy(); + throw; + } + } + } + + // A live ship body for a mod hull. Refuses loudly when the prototype is missing: nothing is loaded here. + public static GameObject Instantiate(HullData hull, Transform parent) + { + if (!Loading.IsCompletedSuccessfully) + throw new InvalidOperationException($"{hull.Name}: mod ships are not preloaded ({Loading.Status})."); + if (!Prototypes.TryGetValue(_catalog.RefOf(hull).Key, out var prototype)) + throw new InvalidOperationException($"{hull.Name}: no mod ship prototype for this hull."); + var body = Object.Instantiate(prototype, parent, false); + body.SetActive(true); + return body; + } + + // Fills a ShipInstance on the visual's root from its anchors, as ShipModPlan says; the shared effects come from the + // template. Nothing here decides a slot: the plan does. The schematic lines stay in the prototype but are hidden in + // world; the in-world ship is the GLB. + public static ShipInstance Assemble(ShipModVisual.Instance visual, HullData hull, ShipAuthoring ship, ShipModTemplate template) + { + var plan = ShipModPlan.Build(hull, ship); + var minimap = LayerMask.NameToLayer("Minimap"); + var combat = LayerMask.NameToLayer("Combat"); + if (minimap < 0 || combat < 0) throw new InvalidOperationException("Minimap or Combat layer is missing"); + + // The name a catalog hardpoint matches at runtime is its anchor id. + Transform Node(string id) + { + var node = visual.Anchors[id]; + node.name = id; + return node; + } + MeshRenderer Renderer(string id) + { + var found = Node(id).GetComponentInChildren(true); + if (found == null) throw new InvalidOperationException($"{ship.Id}: anchor {id} needs a mesh in its GLB node."); + return found; + } + + var mapIcon = Renderer(plan.MapIcon); + mapIcon.sharedMaterial = template.MapIcon; + mapIcon.gameObject.layer = minimap; + + var hullNode = Node(plan.HullCollider); + var hullFilter = hullNode.GetComponent(); + var hullMesh = hullFilter != null ? hullFilter.sharedMesh : null; + if (hullMesh == null) + throw new InvalidOperationException($"{ship.Id}: hull-collider anchor {plan.HullCollider} needs a mesh in its GLB node."); + if (!hullMesh.isReadable) + throw new InvalidOperationException($"{ship.Id}: the hull-collider mesh imported unreadable, so it cannot back a MeshCollider."); + hullNode.gameObject.layer = combat; + var hullRenderer = hullNode.GetComponent(); + if (hullRenderer != null) hullRenderer.forceRenderingOff = true; + var collider = AddOrGet(hullNode.gameObject); + collider.sharedMesh = hullMesh; + collider.convex = true; + var surface = AddOrGet(hullNode.gameObject); + + var shieldMarker = Node(plan.Shield); + var scale = shieldMarker.localScale; + if (!(scale.x > 0 && scale.y > 0 && scale.z > 0)) + throw new InvalidOperationException($"{ship.Id}: the shield anchor scale must have three positive radii."); + var shield = Object.Instantiate(template.Shield.GetComponent(), shieldMarker, false); + Reset(shield.transform); + AddOrGet(shield.gameObject); + var tractor = Object.Instantiate(template.TractorBeam.GetComponent(), Node(plan.Tractor), false); + Reset(tractor.transform); + + var thrusters = plan.Thrusters.Select(id => + { + var hardpoint = AddOrGet(Node(id).gameObject); + hardpoint.Emitter = Renderer(id); + return hardpoint; + }).ToArray(); + var radiators = plan.Radiators.Select(id => + { + var hardpoint = AddOrGet(Node(id).gameObject); + hardpoint.Mesh = Renderer(id); + return hardpoint; + }).ToArray(); + var weapons = plan.Weapons.Select(weapon => + { + var hardpoint = AddOrGet(Node(weapon.Mount).gameObject); + hardpoint.FiringPoint = weapon.Muzzles.Select(Node).ToArray(); + return hardpoint; + }).ToArray(); + + var lines = visual.Root.transform.Find("Schematic Lines"); + if (lines != null) lines.gameObject.SetActive(false); + + var instance = AddOrGet(visual.Root); + instance.MapIcon = mapIcon; + instance.InfluencePrefab = null; + instance.PingPrefab = template.Ping.transform; + instance.InvisibleMaterial = template.Invisible; + instance.Shield = shield; + instance.HullColliders = new[] { surface }; + instance.EquipmentHardpoints = plan.Equipment.Select(Node).ToArray(); + instance.ThrusterHardpoints = thrusters; + instance.WeaponHardpoints = weapons; + instance.RadiatorHardpoints = radiators; + instance.ArticulationPoints = Array.Empty(); + instance.DestroyEffect = template.DestroyEffect; + instance.TractorBeam = tractor; + return instance; + } + + private static void Reset(Transform transform) + { + transform.localPosition = Vector3.zero; + transform.localRotation = Quaternion.identity; + } + + private static T AddOrGet(GameObject gameObject) where T : Component => + gameObject.TryGetComponent(out var found) ? found : gameObject.AddComponent(); +} diff --git a/Assets/Scripts/Gameplay/ShipModShips.cs.meta b/Assets/Scripts/Gameplay/ShipModShips.cs.meta new file mode 100644 index 000000000..b58e73ac4 --- /dev/null +++ b/Assets/Scripts/Gameplay/ShipModShips.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 3b2c0124382433447b5a5679e8b91b57 \ No newline at end of file diff --git a/Assets/Scripts/Gameplay/ShipModTemplate.cs b/Assets/Scripts/Gameplay/ShipModTemplate.cs new file mode 100644 index 000000000..a142aab98 --- /dev/null +++ b/Assets/Scripts/Gameplay/ShipModTemplate.cs @@ -0,0 +1,17 @@ +using UnityEngine; + +// The shared effect prototypes every mod ship is assembled with: the same assets ShipPrefabAuthoring wires into a +// prefab ship. It lives on one Addressable prefab, so a built player finds it by key without the Editor. +public class ShipModTemplate : MonoBehaviour +{ + // The template prefab's .meta GUID, its Addressables key (Assets/Content is an addressable folder). + public const string Key = "5d1f3a8c7e2b4f60a9c4b7e1d3f2a860"; + + // Prefab roots; the assembler takes the component it needs from each. + public GameObject Shield; + public GameObject TractorBeam; + public GameObject Ping; + public GameObject DestroyEffect; + public Material Invisible; + public Material MapIcon; +} diff --git a/Assets/Scripts/Gameplay/ShipModTemplate.cs.meta b/Assets/Scripts/Gameplay/ShipModTemplate.cs.meta new file mode 100644 index 000000000..8effd0b5a --- /dev/null +++ b/Assets/Scripts/Gameplay/ShipModTemplate.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7c3e9a52d8b14f0e8a6d2b1f4c95e703 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Gameplay/ShipModVisual.cs b/Assets/Scripts/Gameplay/ShipModVisual.cs new file mode 100644 index 000000000..c75bc577d --- /dev/null +++ b/Assets/Scripts/Gameplay/ShipModVisual.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using GLTFast; +using UnityEngine; +using Object = UnityEngine.Object; + +// A mod package's visual assembly. It does not decide hull cells or hardpoint roles. +public static class ShipModVisual +{ + public sealed class Instance + { + public GameObject Root; + public IReadOnlyDictionary Anchors; + public Mesh LineMesh; + public Material LineMaterial; + + public void Destroy() + { + DestroyObject(Root); + DestroyObject(LineMesh); + DestroyObject(LineMaterial); + } + } + + private sealed class Nodes : GameObjectInstantiator + { + public Nodes(IGltfReadable gltf, Transform parent) : base(gltf, parent) { } + public Transform Get(uint index) => m_Nodes.TryGetValue(index, out var node) ? node.transform : null; + } + + public static async Task LoadAsync(ShipModCatalog.Package package, Transform parent) + { + var ship = package.Visual; + + var root = new GameObject("mod-ship:" + ship.Id); + root.SetActive(false); + root.transform.SetParent(parent, false); + var result = new Instance { Root = root }; + try + { + // glTFast's default defer agent creates a DontDestroyOnLoad object, which is + // unavailable in edit-mode previews. Play mode keeps its frame-budgeted agent. + var gltf = new GltfImport(deferAgent: Application.isPlaying ? null : new UninterruptedDeferAgent()); + if (!await gltf.LoadFile(package.ModelPath)) + throw new InvalidOperationException($"{ship.Id}: GLB import failed."); + var nodes = new Nodes(gltf, root.transform); + if (!await gltf.InstantiateMainSceneAsync(nodes)) + throw new InvalidOperationException($"{ship.Id}: GLB scene instantiation failed."); + result.Anchors = ship.Anchors.ToDictionary(anchor => anchor.Id, anchor => + nodes.Get(package.NodeIndices[anchor.ModelNodeId]) ?? + throw new InvalidOperationException($"{ship.Id}: GLB scene omitted node {anchor.ModelNodeId}."), + StringComparer.Ordinal); + result.LineMesh = BuildLineMesh(ship.SchematicLines); + if (result.LineMesh != null) + { + var lines = new GameObject("Schematic Lines"); + lines.transform.SetParent(root.transform, false); + lines.AddComponent().sharedMesh = result.LineMesh; + var shader = Shader.Find("Sprites/Default") ?? + throw new InvalidOperationException("Sprites/Default shader is unavailable for ship lines."); + result.LineMaterial = new Material(shader) { name = "Ship Lines" }; + lines.AddComponent().sharedMaterial = result.LineMaterial; + } + root.SetActive(true); + return result; + } + catch + { + result.Destroy(); + throw; + } + } + + private static void DestroyObject(Object target) + { + if (target == null) return; + if (Application.isPlaying) Object.Destroy(target); + else Object.DestroyImmediate(target); + } + + // Blender Z-up to Unity Y-up through Blender's glTF export and glTFast's handedness conversion. + // Segment topology preserves every authored point; display width is currently one screen pixel. + public static Mesh BuildLineMesh(IReadOnlyList lines) + { + if (lines == null || lines.Count == 0) return null; + var vertices = new List(); + var colors = new List(); + var segments = new List(); + foreach (var line in lines) + { + var count = line.Points.Length / 3; + var start = vertices.Count; + for (var i = 0; i < count; i++) + { + var offset = i * 3; + vertices.Add(new Vector3(-line.Points[offset], line.Points[offset + 2], -line.Points[offset + 1])); + var rgba = line.Color; + colors.Add(new Color(rgba?[0] ?? 1, rgba?[1] ?? 1, rgba?[2] ?? 1, + (rgba?[3] ?? 1) * (line.Opacities?[i] ?? 1))); + if (i > 0) { segments.Add(start + i - 1); segments.Add(start + i); } + } + if (line.Cyclic && count > 2) { segments.Add(start + count - 1); segments.Add(start); } + } + var mesh = new Mesh { name = "Captured Ship Lines", indexFormat = UnityEngine.Rendering.IndexFormat.UInt32 }; + mesh.SetVertices(vertices); + mesh.SetColors(colors); + mesh.SetIndices(segments, MeshTopology.Lines, 0); + mesh.RecalculateBounds(); + return mesh; + } +} diff --git a/Assets/Scripts/Gameplay/ShipModVisual.cs.meta b/Assets/Scripts/Gameplay/ShipModVisual.cs.meta new file mode 100644 index 000000000..d64c22b9b --- /dev/null +++ b/Assets/Scripts/Gameplay/ShipModVisual.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a8a4f72a22b44819a71e43e21c7db894 diff --git a/Assets/Scripts/ServerShared/AetheriaStores.cs b/Assets/Scripts/ServerShared/AetheriaStores.cs index 8d9c2dfb2..55d8c2f92 100644 --- a/Assets/Scripts/ServerShared/AetheriaStores.cs +++ b/Assets/Scripts/ServerShared/AetheriaStores.cs @@ -6,7 +6,7 @@ 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(Faction), typeof(FactionProductData), typeof(PersonalityAttribute), typeof(NameFile), typeof(InputLayout), typeof(Loadout), typeof(Scenario) }; + public static readonly Type[] CatalogTypes = { typeof(ItemData), typeof(ShipAuthoring), typeof(Faction), typeof(FactionProductData), typeof(PersonalityAttribute), typeof(NameFile), typeof(InputLayout), typeof(Loadout), typeof(Scenario) }; public static readonly Type[] RunTypes = { typeof(OrbitData), typeof(BodyData), typeof(SavedZone), typeof(SavedGame), typeof(ProvenanceLedger) }; public static readonly Type[] PlayerTypes = { typeof(PlayerSettings) }; diff --git a/Assets/Scripts/ServerShared/EntitySerializer.cs b/Assets/Scripts/ServerShared/EntitySerializer.cs index 4b727eee4..6fb749b29 100644 --- a/Assets/Scripts/ServerShared/EntitySerializer.cs +++ b/Assets/Scripts/ServerShared/EntitySerializer.cs @@ -128,6 +128,7 @@ public static class EntitySerializer // docking bay units, and their stored contents. The provenance ledger's GC root walk. public static IEnumerable Items(EntityPack pack) { + if (pack == null) throw new InvalidOperationException("This run's save is malformed: an entity is null. Start a new game."); yield return pack.Hull; foreach (var (_, item) in pack.Equipment) yield return item; foreach (var (_, item) in pack.CargoBays) yield return item; diff --git a/Assets/Scripts/ServerShared/ItemData.cs b/Assets/Scripts/ServerShared/ItemData.cs index 896756612..40ec27532 100644 --- a/Assets/Scripts/ServerShared/ItemData.cs +++ b/Assets/Scripts/ServerShared/ItemData.cs @@ -531,6 +531,11 @@ public class HullData : EquippableItemData [Inspectable, JsonProperty("canTow"), Key(29)] public bool CanTow; + // The hull's visual: a ShipAuthoring record holding its model package, or unset for a Unity-prefab hull. A hull + // names exactly one of Prefab and Visual. Keys 30 and 31 are EquippableItemData's, so 32 is the next free key. + [Inspectable, JsonProperty("visual"), Key(32)] + public CultRecordRef Visual; + [IgnoreMember] public Shape InteriorCells { diff --git a/Assets/Scripts/ServerShared/Loadout.cs b/Assets/Scripts/ServerShared/Loadout.cs index d4a7262b1..0c445a100 100644 --- a/Assets/Scripts/ServerShared/Loadout.cs +++ b/Assets/Scripts/ServerShared/Loadout.cs @@ -64,11 +64,14 @@ public static class Loadouts // The only writer of presets. It opens its own short-lived cache over the catalog file, writable, and disposes it // after the one commit. No other cache is touched, so no catalog instance play holds (or has mutated) can reach the // file; a cache that already has the catalog open sees the preset only once it reloads. - // Throws and writes nothing when the file is missing (capture never creates a catalog), when a preset of this name + // Throws and writes nothing when the loadout names a mod design (hull or slot), when the file is missing (capture never creates a catalog), when a preset of this name // exists under another key, or when one exists under KeyOf(Name) and replace is not set. The commit is conditional // on the record at KeyOf(Name), so a preset changed on disk since this open is not clobbered: returns false then. public static bool Commit(string catalogPath, Loadout loadout, bool replace) { + var modDesigns = new[] { loadout.Hull.Key }.Concat(loadout.Slots.Select(slot => slot.Design.Key)).Where(ShipModCatalog.IsModKey).Select(key => key.Value).Distinct().ToArray(); + if (modDesigns.Length > 0) + throw new InvalidOperationException($"Preset '{loadout.Name}' names mod designs ({string.Join(", ", modDesigns)}); the shipped catalog never references a mod, so a mod ship cannot be captured as a preset."); if (!File.Exists(catalogPath)) throw new InvalidOperationException($"Catalog {catalogPath} does not exist; a preset capture never creates one."); using var cache = AetheriaStores.Open(catalogPath, catalogWritable: true); diff --git a/Assets/Scripts/ServerShared/SavedGame.cs b/Assets/Scripts/ServerShared/SavedGame.cs index 41cd613ac..71bd625af 100644 --- a/Assets/Scripts/ServerShared/SavedGame.cs +++ b/Assets/Scripts/ServerShared/SavedGame.cs @@ -91,6 +91,39 @@ public static class RunSave return (game, zones); } + // Continue's gate: every design a saved run names (each zone's items and each minted lot) must be one this catalog + // holds. A run made with a mod that is no longer installed is refused, naming the mod ships, before any scene is + // built; the save is never edited to fit. + public static void RequireDesigns(CultCache cache, SavedGame game) + { + var designs = new List(); + foreach (var zoneRef in game.Zones ?? Array.Empty>()) + { + var where = zoneRef.Key.Value; + var zone = cache.Get(zoneRef) ?? throw MalformedSave($"zone {where} has no record"); + // A zone never visited has no contents: legitimately null. + foreach (var pack in zone.Contents?.Entities ?? new List()) + foreach (var item in EntitySerializer.Items(pack)) + designs.Add((item ?? throw MalformedSave($"an item in {where} is null")).Data.Key); + } + foreach (var (number, lot) in Lots(cache).Lots ?? throw MalformedSave("the lot ledger has no lots")) + designs.Add((lot ?? throw MalformedSave($"lot {number} is null")).Design.Key); + var named = designs.Where(key => key.IsSet()).Distinct() + .Where(key => cache.Get(key) == null) + .Select(key => key.Value).OrderBy(key => key, StringComparer.Ordinal).ToArray(); + if (named.Length == 0) return; + const string modHull = "mod-hull:"; + var mods = named.Where(key => key.StartsWith(modHull, StringComparison.Ordinal)).Select(key => key.Substring(modHull.Length)).ToArray(); + var others = named.Where(key => !key.StartsWith(modHull, StringComparison.Ordinal)).ToArray(); + throw new InvalidOperationException("This run names designs the catalog no longer holds" + + (mods.Length > 0 ? $"; missing mod ships: {string.Join(", ", mods)}" : "") + + (others.Length > 0 ? $"; missing other designs: {string.Join(", ", others)}" : "") + + ". Reinstall them, or start a new game."); + } + + private static InvalidOperationException MalformedSave(string where) => + new InvalidOperationException($"This run's save is malformed: {where}. Start a new game."); + // The stored ledger, or a fresh empty one when the run has minted nothing yet. public static ProvenanceLedger Lots(CultCache cache) => cache.GetGlobal() ?? new ProvenanceLedger(); diff --git a/Assets/Scripts/ServerShared/ShipAuthoring.cs b/Assets/Scripts/ServerShared/ShipAuthoring.cs new file mode 100644 index 000000000..d7263fd42 --- /dev/null +++ b/Assets/Scripts/ServerShared/ShipAuthoring.cs @@ -0,0 +1,254 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; + +// 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. +[CultDocument("aetheria.ship_authoring", "1"), MessagePackObject] +public sealed class ShipAuthoring +{ + [CultName, Key(0)] public string Id; + // Key 1 held the embedded HullData until S1; it is retired and never reused. + [Key(2)] public string ModelAsset; + [Key(3)] public List Anchors = new List(); + [Key(4)] public List SchematicLines = new List(); +} + +[MessagePackObject] +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-muzzle, radiator-mesh, or articulation. + [Key(1)] public string Role; + // Stable node ID in the compiled model, never a Blender display name. + [Key(2)] public string ModelNodeId; + // Only child roles use ParentId; e.g. a muzzle names its weapon hardpoint. + [Key(3)] public string ParentId; + [Key(4)] public int Order; +} + +// Evaluated or baked Grease Pencil stroke coordinates in Blender's right-handed Z-up +// space. The runtime renderer owns its coordinate conversion and camera projection. +[MessagePackObject] +public sealed class ShipPolyline +{ + [Key(0)] public string Layer; + [Key(1)] public string Material; + [Key(2)] public float[] Points; + [Key(3)] public float[] Radii; + [Key(4)] public float[] Opacities; + [Key(5)] public bool Cyclic; + [Key(6)] public float[] Color; +} + +public static class ShipAuthoringStore +{ + // ShipAnchor.Role's vocabulary. + private static readonly HashSet Roles = new HashSet(StringComparer.Ordinal) + { + "map-icon", "hull-collider", "shield", "tractor", "thruster-emitter", "weapon-muzzle", "radiator-mesh", "articulation" + }; + + public static CultCache Open(string path, bool writable = false) + { + var cache = new CultCache(); + try + { + cache.AddBackingStore(new SingleFileMessagePackBackingStore(path, !writable), new[] { typeof(HullData), typeof(ShipAuthoring) }); + return cache; + } + catch + { + cache.Dispose(); + throw; + } + } + + // Writes one ship's two records under their deterministic keys, the shape Load expects. + public static void Write(CultCache cache, HullData hull, ShipAuthoring visual) + { + cache.UpsertAsync(typeof(HullData), hull, ShipModCatalog.HullKey(visual.Id)).GetAwaiter().GetResult(); + cache.UpsertAsync(typeof(ShipAuthoring), visual, ShipModCatalog.AuthoringKey(visual.Id)).GetAwaiter().GetResult(); + } + + // The structure of a ship file, without judging its content (drafts load): exactly one hull and one visual, each at + // its deterministic key, the hull naming that visual by its typed ref. + public static (HullData Hull, ShipAuthoring Visual) Load(string path) + { + RefuseLegacyEmbeddedHull(path); + try { return LoadRecords(path); } + catch (MessagePackSerializationException error) + { + throw new InvalidOperationException($"{path}: a record does not decode as its schema: {error.Message}", error); + } + } + + // Key 1 of ShipAuthoring held the whole hull before S1. The type no longer has that member, so a deserialized record + // shows nothing of it, and a file that still carries one would load as a ship silently ignoring its old hull. The + // raw payload is the only place the old shape is visible. + private static void RefuseLegacyEmbeddedHull(string path) + { + if (!File.Exists(path)) return; + var bytes = File.ReadAllBytes(path); + if (bytes.Length == 0) return; + CultPersistedStoreSnapshot snapshot; + try { snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(bytes); } + catch (MessagePackSerializationException error) + { + throw new InvalidOperationException($"{path}: not a readable ship file: {error.Message}", error); + } + var schema = typeof(ShipAuthoring).GetCustomAttribute().SchemaName; + foreach (var record in snapshot.Records) + { + if (snapshot.SchemaCatalog.FirstOrDefault(entry => entry.SchemaId == record.SchemaId)?.SchemaName != schema) continue; + var reader = new MessagePackReader(record.Payload); + if (reader.NextMessagePackType != MessagePackType.Array) continue; + var slots = reader.ReadArrayHeader(); + for (var slot = 0; slot < slots; slot++) + { + if (slot == RetiredHullKey && !reader.TryReadNil()) + throw new InvalidOperationException($"{path}: {record.Key}: legacy embedded hull at retired key {RetiredHullKey} of the ship authoring record. " + + $"Migrate it: write the hull as its own hull record at mod-hull: naming the visual, and rewrite the ship authoring record without key {RetiredHullKey}."); + if (slot != RetiredHullKey) reader.Skip(); + } + } + } + + private const int RetiredHullKey = 1; + + private static (HullData Hull, ShipAuthoring Visual) LoadRecords(string path) + { + using var cache = Open(path); + var hulls = cache.GetAll().ToArray(); + var visuals = cache.GetAll().ToArray(); + if (visuals.Length != 1) + throw new InvalidOperationException($"{path} must hold exactly one ship authoring record, found {visuals.Length}."); + if (hulls.Length != 1) + throw new InvalidOperationException($"{path} must hold exactly one hull record, found {hulls.Length}."); + var (hull, visual) = (hulls[0], visuals[0]); + if (!cache.TryGetHandle(hull).Value.Key.Equals(ShipModCatalog.HullKey(visual.Id)) || + !cache.TryGetHandle(visual).Value.Key.Equals(ShipModCatalog.AuthoringKey(visual.Id))) + throw new InvalidOperationException($"{path}: {visual.Id}: records must be stored under {ShipModCatalog.HullKey(visual.Id).Value} and {ShipModCatalog.AuthoringKey(visual.Id).Value}."); + return (hull, visual); + } + + public static (HullData Hull, ShipAuthoring Visual) Read(string path) + { + var (hull, visual) = Load(path); + Validate(hull, visual); + return (hull, visual); + } + + // A hull names one body: a Unity prefab (shipped hulls) or a ShipAuthoring record (mod ships), never both, so no + // consumer needs a precedence rule. A whitespace-only Prefab is unset. Every path that validates or composes hulls + // calls this. + public static void RequireOneBody(HullData hull, string label) + { + if (!string.IsNullOrWhiteSpace(hull.Prefab) && hull.Visual.IsSet()) + throw new InvalidOperationException($"{label}: a hull names one body, but this one names both a Unity prefab and a visual record."); + } + + // The one semantic check every path shares: the hull and its visual, judged together. + public static void Validate(HullData hull, ShipAuthoring ship) + { + if (ship == null) throw new InvalidOperationException("Ship authoring record is null."); + if (string.IsNullOrWhiteSpace(ship.Id)) throw new InvalidOperationException("Ship ID is required."); + if (!(ship.Id[0] >= 'a' && ship.Id[0] <= 'z' || ship.Id[0] >= '0' && ship.Id[0] <= '9') || ship.Id.Any(c => + !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == '-'))) + throw new InvalidOperationException($"{ship.Id}: ship ID must use lower-case ASCII letters, digits, dots, underscores, or hyphens."); + if (hull == null) throw new InvalidOperationException($"{ship.Id}: hull data is required."); + if (string.IsNullOrWhiteSpace(hull.Name)) throw new InvalidOperationException($"{ship.Id}: hull name is required."); + if (hull.Shape?.Cells == null || !hull.Shape.Cells.Cast().Any(occupied => occupied)) + throw new InvalidOperationException($"{ship.Id}: schematic must contain at least one cell."); + RequireOneBody(hull, ship.Id); + if (!hull.Visual.Key.Equals(ShipModCatalog.AuthoringKey(ship.Id))) + throw new InvalidOperationException($"{ship.Id}: the hull must name its visual record {ShipModCatalog.AuthoringKey(ship.Id).Value}."); + if (string.IsNullOrWhiteSpace(ship.ModelAsset) || Path.IsPathRooted(ship.ModelAsset) || + ship.ModelAsset.Replace('\\', '/').Split('/').Any(part => part == "..")) + throw new InvalidOperationException($"{ship.Id}: model asset must be a relative package path."); + + var anchors = ship.Anchors ?? throw new InvalidOperationException($"{ship.Id}: anchors are required."); + var ids = new HashSet(StringComparer.Ordinal); + var nodeIds = new HashSet(StringComparer.Ordinal); + foreach (var anchor in anchors) + { + if (anchor == null || string.IsNullOrWhiteSpace(anchor.Id) || !ids.Add(anchor.Id)) + throw new InvalidOperationException($"{ship.Id}: anchor IDs must be present and unique."); + if (string.IsNullOrWhiteSpace(anchor.ModelNodeId)) + throw new InvalidOperationException($"{ship.Id}: anchor {anchor.Id} needs a model node ID."); + if (!nodeIds.Add(anchor.ModelNodeId)) + throw new InvalidOperationException($"{ship.Id}: model node {anchor.ModelNodeId} is claimed by more than one anchor."); + } + foreach (var anchor in anchors) + if (!Roles.Contains(anchor.Role)) + throw new InvalidOperationException($"{ship.Id}: anchor {anchor.Id} has unknown role '{anchor.Role}'."); + foreach (var role in new[] { "map-icon", "hull-collider", "shield", "tractor" }) + if (anchors.Count(anchor => anchor.Role == role) != 1) + throw new InvalidOperationException($"{ship.Id}: exactly one {role} anchor is required."); + + var mounts = new HashSet(StringComparer.Ordinal); + var occupiedHardpointCells = new HashSet<(int x, int y)>(); + foreach (var hardpoint in hull.Hardpoints ?? new List()) + { + if (hardpoint == null || string.IsNullOrWhiteSpace(hardpoint.Transform) || + !mounts.Add(hardpoint.Transform)) + throw new InvalidOperationException($"{ship.Id}: hardpoint IDs must be present and unique."); + if (!Enum.IsDefined(typeof(HardpointType), hardpoint.Type)) + throw new InvalidOperationException($"{ship.Id}: hardpoint {hardpoint.Transform} has an unknown type {(int)hardpoint.Type}."); + if (!Enum.IsDefined(typeof(ItemRotation), hardpoint.Rotation)) + throw new InvalidOperationException($"{ship.Id}: hardpoint {hardpoint.Transform} has an unknown rotation {(int)hardpoint.Rotation}."); + if (!float.IsFinite(hardpoint.Armor) || hardpoint.Armor < 0 || !float.IsFinite(hardpoint.FiringArc) || hardpoint.FiringArc < 0) + throw new InvalidOperationException($"{ship.Id}: hardpoint {hardpoint.Transform} armor and firing arc must be finite and not negative."); + if (hardpoint.Shape?.Cells == null || !hardpoint.Shape.Cells.Cast().Any(occupied => occupied)) + throw new InvalidOperationException($"{ship.Id}: hardpoint {hardpoint.Transform} has no cells."); + for (var cellX = 0; cellX < hardpoint.Shape.Width; cellX++) + for (var cellY = 0; cellY < hardpoint.Shape.Height; cellY++) + { + if (!hardpoint.Shape.Cells[cellX, cellY]) continue; + var x = hardpoint.Position.x + cellX; + var y = hardpoint.Position.y + cellY; + if (x < 0 || y < 0 || x >= hull.Shape.Width || y >= hull.Shape.Height || !hull.Shape.Cells[x, y]) + throw new InvalidOperationException($"{ship.Id}: hardpoint {hardpoint.Transform} lies outside the hull schematic."); + if (!occupiedHardpointCells.Add((x, y))) + throw new InvalidOperationException($"{ship.Id}: hardpoint {hardpoint.Transform} overlaps another hardpoint."); + } + var mountAnchor = anchors.FirstOrDefault(anchor => anchor.Id == hardpoint.Transform); + if (mountAnchor == null) + throw new InvalidOperationException($"{ship.Id}: hardpoint {hardpoint.Transform} has no model anchor."); + // A mount's anchor plays the mount, so its role is fixed by the hardpoint type; the structural roles (map-icon, + // hull-collider, shield, tractor, weapon-muzzle) name other nodes and never double as a mount. + var mountRole = hardpoint.Type == HardpointType.Thruster ? "thruster-emitter" : + hardpoint.Type == HardpointType.Radiator ? "radiator-mesh" : "articulation"; + if (mountAnchor.Role != mountRole) + throw new InvalidOperationException($"{ship.Id}: {hardpoint.Type} hardpoint {hardpoint.Transform} needs a {mountRole} anchor of that id."); + } + foreach (var anchor in anchors.Where(anchor => !string.IsNullOrEmpty(anchor.ParentId))) + if (!mounts.Contains(anchor.ParentId)) + throw new InvalidOperationException($"{ship.Id}: anchor {anchor.Id} has unknown hardpoint parent {anchor.ParentId}."); + + foreach (var line in ship.SchematicLines ?? new List()) + { + var points = line?.Points; + if (points == null || points.Length < 6 || points.Length % 3 != 0 || + points.Any(value => float.IsNaN(value) || float.IsInfinity(value))) + throw new InvalidOperationException($"{ship.Id}: schematic line needs finite XYZ points."); + var count = points.Length / 3; + if (line.Radii != null && line.Radii.Length != count || + line.Opacities != null && line.Opacities.Length != count) + throw new InvalidOperationException($"{ship.Id}: schematic line point attributes have the wrong length."); + if (line.Radii != null && line.Radii.Any(value => float.IsNaN(value) || float.IsInfinity(value) || value < 0) || + line.Opacities != null && line.Opacities.Any(value => float.IsNaN(value) || value < 0 || value > 1)) + throw new InvalidOperationException($"{ship.Id}: schematic line radius and opacity must be finite and in range."); + if (line.Color != null && (line.Color.Length != 4 || + line.Color.Any(value => float.IsNaN(value) || float.IsInfinity(value)))) + throw new InvalidOperationException($"{ship.Id}: schematic line color must be finite RGBA."); + } + } +} diff --git a/Assets/Scripts/ServerShared/ShipAuthoring.cs.meta b/Assets/Scripts/ServerShared/ShipAuthoring.cs.meta new file mode 100644 index 000000000..b9d7af3b4 --- /dev/null +++ b/Assets/Scripts/ServerShared/ShipAuthoring.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0da6676b1995425fa66187e8e58956e7 diff --git a/Assets/Scripts/ServerShared/ShipModCatalog.cs b/Assets/Scripts/ServerShared/ShipModCatalog.cs new file mode 100644 index 000000000..ee80add89 --- /dev/null +++ b/Assets/Scripts/ServerShared/ShipModCatalog.cs @@ -0,0 +1,209 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using GameCult.Caching; +using Newtonsoft.Json.Linq; +using System.Text; + +// Builds the one catalog snapshot CultCache needs. Sources remain the shipped catalog and each +// mod-owned ship.cc; this output is disposable and never becomes an authoring surface. +public static class ShipModCatalog +{ + public sealed class Package + { + public HullData Hull; + public ShipAuthoring Visual; + public string ModelPath; + public Dictionary NodeIndices; + } + + public static CultRecordKey HullKey(string id) => new CultRecordKey("mod-hull:" + id); + public static CultRecordKey AuthoringKey(string id) => new CultRecordKey("mod-ship:" + id); + + // A key the mods own. The shipped catalog and its authored records never reference one: a mod may be uninstalled. + public static bool IsModKey(CultRecordKey key) => + key.IsSet() && (key.Value.StartsWith("mod-hull:", StringComparison.Ordinal) || key.Value.StartsWith("mod-ship:", StringComparison.Ordinal)); + + // A package left out of the composition, named by its directory, with every reason it was left out. + public sealed class Exclusion + { + public string Package; + public string Reason; + public override string ToString() => $"{Package}: {Reason}"; + } + + public sealed class Composition + { + // Ship IDs of the packages composed into the derived catalog, in directory order. + public string[] Included; + // Packages that failed on their own or collided with the catalog or with each other, in directory order. + public Exclusion[] Excluded; + } + + // One bad package never stops the rest. Each package is read and validated on its own; one that fails is excluded and + // named. A collision (with the shipped catalog, or with another package's hull name) excludes every package involved, + // since neither has a claim to the name. The derived catalog holds the shipped catalog plus the included packages. + // Unsafe inputs and outputs (a missing catalog, a derived file that would replace a source) still throw: nothing is composed. + public static Composition Compose(string shippedCatalog, string outputCatalog, string modsRoot) + { + var source = Path.GetFullPath(shippedCatalog); + var output = Path.GetFullPath(outputCatalog); + var root = Path.GetFullPath(modsRoot); + if (!File.Exists(source)) throw new FileNotFoundException("Shipped catalog is missing", source); + if (!Directory.Exists(root)) throw new DirectoryNotFoundException($"Mod root is missing: {root}"); + if (string.Equals(source, output, StringComparison.OrdinalIgnoreCase)) + throw new InvalidOperationException("The derived catalog cannot replace the shipped catalog."); + if (output.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + throw new InvalidOperationException("The derived catalog cannot replace a mod source or asset."); + + var reasons = new SortedDictionary>(StringComparer.Ordinal); + void Exclude(string package, string reason) + { + if (!reasons.TryGetValue(package, out var list)) reasons[package] = list = new List(); + list.Add(reason); + } + var packages = new List<(string Directory, Package Package)>(); + foreach (var directory in Directory.GetDirectories(root).OrderBy(path => path, StringComparer.Ordinal)) + { + var path = Path.Combine(directory, "ship.cc"); + if (!File.Exists(path)) continue; + var name = Path.GetFileName(directory); + // A package can fail in any way a hostile or broken file can, so its failure is quarantined whatever it is. + try { packages.Add((name, ReadPackage(path))); } + catch (Exception error) { Exclude(name, error.Message); } + } + + Directory.CreateDirectory(Path.GetDirectoryName(output)); + // The store keeps a lock file beside every file it opens, so the working copy gets its own directory and the + // whole directory goes away, whatever the store left in it. + var workspace = output + "." + Guid.NewGuid().ToString("N") + ".tmp"; + var temporary = Path.Combine(workspace, "catalog.cc"); + try + { + Directory.CreateDirectory(workspace); + File.Copy(source, temporary); + Composition composition; + using (var cache = AetheriaStores.Open(temporary, catalogWritable: true)) + { + // Collisions are judged against the shipped records alone, before any package is written, so the + // verdict does not depend on directory order. CultCache indexes names per concrete type and lets the + // last writer win, and GetByName over a base type throws on a match across subtypes: a mod hull named + // like any shipped item, or like another mod's hull, would make name lookups wrong or throw. + var keys = new HashSet(cache.AllStoredDocuments.Select(record => record.Key)); + var itemNames = new HashSet(cache.GetAll().Select(item => item.Name), StringComparer.Ordinal); + var shipIds = new HashSet(cache.GetAll().Select(existing => existing.Id), StringComparer.Ordinal); + foreach (var (directory, package) in packages) + { + var (hull, ship) = (package.Hull, package.Visual); + if (keys.Contains(HullKey(ship.Id)) || keys.Contains(AuthoringKey(ship.Id))) + Exclude(directory, $"a mod key collides with an existing catalog record."); + if (itemNames.Contains(hull.Name)) + Exclude(directory, $"hull name '{hull.Name}' collides with an existing catalog item."); + if (shipIds.Contains(ship.Id)) + Exclude(directory, $"ship ID collides with an existing catalog ship authoring record."); + } + foreach (var claim in packages.GroupBy(package => package.Package.Hull.Name, StringComparer.Ordinal).Where(group => group.Count() > 1)) + foreach (var (directory, package) in claim) + Exclude(directory, $"hull name '{claim.Key}' is also claimed by " + + string.Join(", ", claim.Where(other => other.Directory != directory).Select(other => other.Directory)) + "."); + + var included = packages.Where(package => !reasons.ContainsKey(package.Directory)).Select(package => package.Package).ToArray(); + foreach (var package in included) + // Verbatim: the mod store's own two records, under the keys it already holds them at. + ShipAuthoringStore.Write(cache, package.Hull, package.Visual); + // Shipped hulls too: the derived catalog must not hold a hull that names two bodies. + foreach (var hull in cache.GetAll()) + ShipAuthoringStore.RequireOneBody(hull, hull.Name); + cache.FlushAsync().GetAwaiter().GetResult(); + composition = new Composition + { + Included = included.Select(package => package.Visual.Id).ToArray(), + Excluded = reasons.Select(entry => new Exclusion { Package = entry.Key, Reason = string.Join("; ", entry.Value) }).ToArray() + }; + } + if (File.Exists(output)) File.Replace(temporary, output, null); + else File.Move(temporary, output); + return composition; + } + finally + { + if (Directory.Exists(workspace)) Directory.Delete(workspace, true); + } + } + + public static Package ReadPackage(string shipPath) + { + var path = Path.GetFullPath(shipPath); + var (hull, ship) = ShipAuthoringStore.Read(path); + return Bind(hull, ship, Path.GetDirectoryName(path), path); + } + + // The package a catalog hull names: its two records come from the catalog, and only the GLB comes from the mod + // directory (//). Gameplay reads a mod ship through this, never through its ship.cc. + public static Package PackageOf(CultCache catalog, HullData hull, string modsRoot) + { + var ship = catalog.Get(hull.Visual) ?? + throw new InvalidOperationException($"{hull.Name}: the catalog holds no visual record {hull.Visual.Key.Value}."); + ShipAuthoringStore.Validate(hull, ship); + var directory = Path.Combine(Path.GetFullPath(modsRoot), ship.Id); + return Bind(hull, ship, directory, Path.Combine(directory, "ship.cc")); + } + + // The one game-side choice of catalog: the shipped file when no package is installed or none survives composition, + // otherwise the derived file, composed afresh from the shipped one and the surviving packages. Recomposed every + // call, so the derived file is never stale and never an authority. Excluded packages come back named, for the menu. + public static (string Catalog, Exclusion[] Excluded) ResolveCatalog(string shippedCatalog, string derivedCatalog, string modsRoot) + { + if (!Directory.Exists(modsRoot) || + !Directory.GetDirectories(modsRoot).Any(directory => File.Exists(Path.Combine(directory, "ship.cc")))) + return (shippedCatalog, Array.Empty()); + Composition composition; + // A failure of the composition itself (an unwritable derived path, say) is still a mod problem, never a reason not to boot. + try { composition = Compose(shippedCatalog, derivedCatalog, modsRoot); } + catch (Exception error) { return (shippedCatalog, new[] { new Exclusion { Package = "(all mods)", Reason = error.Message } }); } + return (composition.Included.Length == 0 ? shippedCatalog : derivedCatalog, composition.Excluded); + } + + private static Package Bind(HullData hull, ShipAuthoring ship, string directory, string path) + { + if (!string.Equals(Path.GetFileName(directory), ship.Id, StringComparison.Ordinal)) + throw new InvalidOperationException($"{path}: ship ID must match its package directory name."); + var modelPath = Path.GetFullPath(Path.Combine(directory, ship.ModelAsset)); + // Containment is ShipAuthoringStore.Validate's job: it refuses rooted and `..` model paths before this line. + if (!File.Exists(modelPath) || !string.Equals(Path.GetExtension(modelPath), ".glb", StringComparison.OrdinalIgnoreCase)) + throw new InvalidOperationException($"{ship.Id}: model asset must name an existing GLB inside its package."); + var modelNodes = ReadNodeIds(modelPath); + foreach (var anchor in ship.Anchors) + if (!modelNodes.ContainsKey(anchor.ModelNodeId)) + throw new InvalidOperationException($"{ship.Id}: model has no node with aetheria.id={anchor.ModelNodeId} for anchor {anchor.Id}."); + CultRecordRefs.Validate(hull); + return new Package { Hull = hull, Visual = ship, ModelPath = modelPath, NodeIndices = modelNodes }; + } + + // GLB is the xenos asset boundary. Only its node extras are read here; geometry belongs to the runtime importer. + public static Dictionary ReadNodeIds(string path) + { + using var stream = File.OpenRead(path); + using var reader = new BinaryReader(stream); + if (stream.Length < 20 || reader.ReadUInt32() != 0x46546C67 || reader.ReadUInt32() != 2 || + reader.ReadUInt32() != stream.Length) + throw new InvalidOperationException($"{path}: invalid GLB 2 header."); + var chunkLength = reader.ReadUInt32(); + if (reader.ReadUInt32() != 0x4E4F534A || chunkLength > stream.Length - stream.Position) + throw new InvalidOperationException($"{path}: missing GLB JSON chunk."); + var json = JObject.Parse(Encoding.UTF8.GetString(reader.ReadBytes((int)chunkLength))); + var ids = new Dictionary(StringComparer.Ordinal); + var nodes = json["nodes"]?.OfType() ?? Enumerable.Empty(); + uint index = 0; + foreach (var node in nodes) + { + var id = (string)node["extras"]?["aetheria.id"]; + if (string.IsNullOrEmpty(id)) { index++; continue; } + if (!ids.TryAdd(id, index)) + throw new InvalidOperationException($"{path}: duplicate GLB node aetheria.id={id}."); + index++; + } + return ids; + } +} diff --git a/Assets/Scripts/ServerShared/ShipModCatalog.cs.meta b/Assets/Scripts/ServerShared/ShipModCatalog.cs.meta new file mode 100644 index 000000000..c81d1965d --- /dev/null +++ b/Assets/Scripts/ServerShared/ShipModCatalog.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 708d45e8a4144a6e89bcf40e96b0975a diff --git a/Assets/Scripts/ServerShared/ShipModPlan.cs b/Assets/Scripts/ServerShared/ShipModPlan.cs new file mode 100644 index 000000000..6b696bcaa --- /dev/null +++ b/Assets/Scripts/ServerShared/ShipModPlan.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +// Which anchor fills which slot of a ship's component arrays. Pure over (hull, visual) so the Unity assembler only +// follows it: the hull's hardpoint type decides what a mount is, the anchor's role decides which node plays the part. +public sealed class ShipModPlan +{ + public string MapIcon; + public string HullCollider; + public string Shield; + public string Tractor; + // Every hull hardpoint's mount id, in hardpoint order: the anchor node each one is matched to by name. + public string[] Equipment; + // Mount ids whose anchor (role thruster-emitter / radiator-mesh) is the emitter / mesh node itself. + public string[] Thrusters; + public string[] Radiators; + // A weapon mount's muzzle anchors, by Order then id. + public (string Mount, string[] Muzzles)[] Weapons; + + // Anchors with role "articulation" become ordinary mount nodes: ArticulationPoint's limits are not authorable until + // pivots move onto HullData, so no ArticulationPoint is planned. + public static ShipModPlan Build(HullData hull, ShipAuthoring visual) + { + ShipAuthoringStore.Validate(hull, visual); + var hardpoints = hull.Hardpoints ?? new List(); + var byMount = hardpoints.ToDictionary(hardpoint => hardpoint.Transform, StringComparer.Ordinal); + string Only(string wanted) => visual.Anchors.Single(anchor => anchor.Role == wanted).Id; + + foreach (var anchor in visual.Anchors.Where(anchor => anchor.Role == "thruster-emitter" || anchor.Role == "radiator-mesh")) + { + var wanted = anchor.Role == "thruster-emitter" ? HardpointType.Thruster : HardpointType.Radiator; + if (!byMount.ContainsKey(anchor.Id)) + throw new InvalidOperationException($"{visual.Id}: {anchor.Role} anchor {anchor.Id} must be a {wanted} hardpoint's mount."); + } + string[] Mounts(HardpointType type) => hardpoints.Where(hardpoint => hardpoint.Type == type).Select(hardpoint => hardpoint.Transform).ToArray(); + + var muzzles = visual.Anchors.Where(anchor => anchor.Role == "weapon-muzzle") + .OrderBy(anchor => anchor.Order).ThenBy(anchor => anchor.Id, StringComparer.Ordinal).ToArray(); + foreach (var muzzle in muzzles) + if (string.IsNullOrEmpty(muzzle.ParentId) || !IsWeapon(byMount[muzzle.ParentId].Type)) + throw new InvalidOperationException($"{visual.Id}: muzzle {muzzle.Id} must be parented to a weapon hardpoint's mount."); + var weapons = hardpoints.Where(hardpoint => IsWeapon(hardpoint.Type)).Select(hardpoint => ( + hardpoint.Transform, + muzzles.Where(muzzle => muzzle.ParentId == hardpoint.Transform).Select(muzzle => muzzle.Id).ToArray())).ToArray(); + foreach (var (mount, ids) in weapons) + if (ids.Length == 0) + throw new InvalidOperationException($"{visual.Id}: weapon hardpoint {mount} needs at least one muzzle anchor."); + + return new ShipModPlan + { + MapIcon = Only("map-icon"), + HullCollider = Only("hull-collider"), + Shield = Only("shield"), + Tractor = Only("tractor"), + Equipment = hardpoints.Select(hardpoint => hardpoint.Transform).ToArray(), + Thrusters = Mounts(HardpointType.Thruster), + Radiators = Mounts(HardpointType.Radiator), + Weapons = weapons + }; + } + + private static bool IsWeapon(HardpointType type) => + type == HardpointType.Energy || type == HardpointType.Ballistic || type == HardpointType.Launcher; +} diff --git a/Assets/Scripts/ServerShared/ShipModPlan.cs.meta b/Assets/Scripts/ServerShared/ShipModPlan.cs.meta new file mode 100644 index 000000000..6235b5279 --- /dev/null +++ b/Assets/Scripts/ServerShared/ShipModPlan.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b45caa5f5ad9c164b8a295528f1b4951 \ No newline at end of file diff --git a/Assets/Scripts/UI/MainMenu.cs b/Assets/Scripts/UI/MainMenu.cs index 8ace9b3c3..9d17af138 100644 --- a/Assets/Scripts/UI/MainMenu.cs +++ b/Assets/Scripts/UI/MainMenu.cs @@ -89,6 +89,8 @@ public class MainMenu : MonoBehaviour _fadeFromRight = fromRight; } + private static bool _exclusionsShown; + private void ShowMain() { _nextMenu.panel.Clear(); @@ -97,14 +99,21 @@ public class MainMenu : MonoBehaviour { // A run exists only as the run store's SavedGame global. var cache = ActionGameManager.CultCache; + if (ActionGameManager.ModExclusions.Length > 0 && !_exclusionsShown) + { + _exclusionsShown = true; + Refuse("Some mods were not loaded", string.Join("\n", ActionGameManager.ModExclusions.Select(exclusion => exclusion.ToString()))); + } var saved = cache.GetGlobal(); if (saved == null && cache.AllStoredDocuments.Any(stored => RunSave.IsRunRecord(stored.Descriptor.DocumentType))) Debug.Log("run store has no SavedGame; Continue disabled"); _nextMenu.panel.AddButton("Continue", saved == null ? (Action) null : () => { + try { RunSave.RequireDesigns(cache, saved); } + catch (InvalidOperationException error) { Refuse("Cannot continue this run", error.Message); return; } ActionGameManager.IsTutorial = saved.IsTutorial; ActionGameManager.CurrentGalaxy = new Galaxy(cache, saved, Debug.Log); - SceneManager.LoadScene("ARPG"); + EnterGame(); }); } _nextMenu.panel.AddButton("New Game", @@ -139,7 +148,7 @@ public class MainMenu : MonoBehaviour Observable.NextFrame().Subscribe(_ => { ActionGameManager.CurrentGalaxy = sector; - SceneManager.LoadScene("ARPG"); + EnterGame(); }); }).ContinueWith(t => Debug.LogException(t.Exception), TaskContinuationOptions.OnlyOnFaulted); } @@ -169,7 +178,7 @@ public class MainMenu : MonoBehaviour Observable.NextFrame().Subscribe(_ => { ActionGameManager.CurrentGalaxy = sector; - SceneManager.LoadScene("ARPG"); + EnterGame(); }); }).ContinueWith(t => Debug.LogException(t.Exception), TaskContinuationOptions.OnlyOnFaulted); } @@ -183,6 +192,31 @@ public class MainMenu : MonoBehaviour _nextMenu.panel.AddButton("Quit", Application.Quit); } + // The one way into the game scene. Mod ship prototypes import asynchronously at boot, so the scene waits for them, + // and a failed import stops here with its reason rather than in the first zone. + private void EnterGame() => StartCoroutine(EnterGameWhenModShipsAreReady()); + + private IEnumerator EnterGameWhenModShipsAreReady() + { + var loading = ShipModShips.Loading; + while (!loading.IsCompleted) yield return null; + if (loading.IsFaulted) + { + Refuse("Mod ships failed to load", loading.Exception.GetBaseException().Message); + yield break; + } + SceneManager.LoadScene("ARPG"); + } + + private void Refuse(string title, string reason) + { + Debug.LogError($"{title}: {reason}"); + Dialog.Clear(); + Dialog.Title.text = title; + Dialog.AddProperty(() => reason); + Dialog.Show(onCancel: () => { }, cancelText: "OK"); + } + private void ShowSettings() { _nextMenu.panel.Clear(); diff --git a/Assets/Scripts/UI/Menu/TradeMenu.cs b/Assets/Scripts/UI/Menu/TradeMenu.cs index 3b1643dab..c4fe6737a 100644 --- a/Assets/Scripts/UI/Menu/TradeMenu.cs +++ b/Assets/Scripts/UI/Menu/TradeMenu.cs @@ -3,7 +3,6 @@ using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; -using System.Runtime.Remoting.Contexts; using TMPro; using UnityEngine; using UnityEngine.UI; diff --git a/Assets/Scripts/Zone Display/ZoneRenderer.cs b/Assets/Scripts/Zone Display/ZoneRenderer.cs index 0b437dcfe..b3fec3ac8 100644 --- a/Assets/Scripts/Zone Display/ZoneRenderer.cs +++ b/Assets/Scripts/Zone Display/ZoneRenderer.cs @@ -289,10 +289,13 @@ public class ZoneRenderer : MonoBehaviour void LoadEntity(Entity entity) { var hullData = ItemManager.GetData(entity.Hull) as HullData; + GameObject Body() => hullData.Visual.IsSet() + ? ShipModShips.Instantiate(hullData, ZoneRoot) + : Instantiate(EngineAssets.Load(hullData.Prefab), ZoneRoot); EntityInstance instance; if (entity is Ship) { - instance = Instantiate(EngineAssets.Load(hullData.Prefab), ZoneRoot).GetComponent(); + instance = Body().GetComponent(); if (instance == null) { ItemManager.Log($"Failed to instantiate {hullData.Name} ship with invalid prefab: no ShipInstance component!"); @@ -301,7 +304,7 @@ public class ZoneRenderer : MonoBehaviour } else { - instance = Instantiate(EngineAssets.Load(hullData.Prefab), ZoneRoot).GetComponent(); + instance = Body().GetComponent(); if (instance == null) { ItemManager.Log($"Failed to instantiate {hullData.Name} entity with invalid prefab: no EntityInstance component!"); diff --git a/Packages/manifest.json b/Packages/manifest.json index 6e31d3b05..c166932fd 100644 --- a/Packages/manifest.json +++ b/Packages/manifest.json @@ -6,6 +6,7 @@ "com.unity.ai.navigation": "2.0.14", "com.unity.burst": "1.8.30", "com.unity.cinemachine": "2.10.7", + "com.unity.cloud.gltfast": "6.20.0", "com.unity.ide.rider": "3.0.40", "com.unity.ide.visualstudio": "2.0.26", "com.unity.inputsystem": "1.20.0", diff --git a/Packages/packages-lock.json b/Packages/packages-lock.json index d58d112e2..33cb60ccf 100644 --- a/Packages/packages-lock.json +++ b/Packages/packages-lock.json @@ -68,6 +68,19 @@ }, "url": "https://packages.unity.com" }, + "com.unity.cloud.gltfast": { + "version": "6.20.0", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.burst": "1.8.30", + "com.unity.collections": "2.6.8", + "com.unity.mathematics": "1.3.3", + "com.unity.modules.jsonserialize": "1.0.0", + "com.unity.modules.unitywebrequest": "1.0.0" + }, + "url": "https://packages.unity.com" + }, "com.unity.collections": { "version": "2.6.8", "depth": 1, diff --git a/docs/moddable-ship-authoring.md b/docs/moddable-ship-authoring.md new file mode 100644 index 000000000..5a69f06de --- /dev/null +++ b/docs/moddable-ship-authoring.md @@ -0,0 +1,230 @@ +# Moddable ship authoring: parallel proof + +Status: design and proof lane. The existing `HullData` catalog records, Longinus and +Djinni prefabs, and their spawn path remain live until a complete mod ship passes +authoring, validation, loading, and play checks. + +## LineArt proof from Quiet.blend + +The numbers in this section and in the compose example below come from an +unrecorded probe. `Build/quiet.cc` is git-ignored and no committed fixture or +test reproduces them. + +`C:\Users\Meta\Desktop\Quiet.blend` is a read-only source for this probe. At frame +1, `Quiet / Dexter Quiet Lineart` evaluates to 1,040 polylines with 3,125 +points. Blender 5.2.2 wrote those coordinates, point radii and opacities, +material/layer names, cyclic flags, and RGBA into `Build/quiet.cc` without +changing the `.blend`. C# reopened the same typed record and counted the same +lines and points. A second line replacement preserved its record key, schema +ID, hull, model asset, and anchors byte for byte. `Build/quiet.cc` is an +ignored draft probe, not an installed ship. + +The line positions remain 3D Blender world coordinates. The runtime can +lower them to a hologram or schematic view without regenerating LineArt. +LineArt evaluation depends on the source scene and camera, so a captured set +may be incomplete from another view. Gameplay cell occupancy remains the +authored `HullData.Shape` in the `.cc`; strokes do not decide armor or mount +footprints. + +`tools/blender/aetheria_ships` is a separate Blender add-on in Brokkr's +sidebar. It uses Brokkr's configured CultLib Python source and edits the +line slot of a ship file's `aetheria.ship_authoring` visual record and the +hull shape and hardpoint slots of the `aetheria.hulldata` record beside it. To try it, make +`F:\Projects\Brokkr\surfaces\blender` and this repo's `tools\blender` visible +to Blender's add-on search path, enable `brokkr_bridge` then +`aetheria_ships`, and install `msgpack` into Blender's Python environment. +Create a draft with `dotnet run --project tools/AetherDb -- ship-authoring +create `, choose that `.cc` in the **Aetheria +Ship** panel, select an object in its ship collection, and press **Bind Ship +Collection**. The collection stores `aetheria.asset_kind=ship`, the stable +`aetheria.id`, and a relative `.cc` path. Select a Grease Pencil object in +that bound collection and press **Capture Ship Lines**. Capture checks the +collection ID against the record before writing; object and collection +display names are not IDs. +**Load Ship Layout** opens the same `.cc` file's hull grid and hardpoints in +the panel. Toggle occupied grid cells, resize up to 32×32, and edit each +hardpoint's type, mount ID, position, footprint, rotation, armor, and firing +arc. A footprint uses top-to-bottom rows of `#` (occupied) and `.` (empty), +separated by `/`; `##/##` is a 2×2 mount. **Save Layout to .cc** replaces only +the hull shape and hardpoint slots. It preserves hull stats, anchors, visual +assets, lines, the record key, and schema. Save rejects a changed ship ID or +layout revision; reload first if another editor changed those fields. A line +capture leaves the loaded layout revision intact. The saved layout is a draft until +its mount IDs resolve to visual anchors and C# validation passes. +`ship-authoring inspect ` reads drafts; `validate` requires complete +hull, model, and anchor authoring. + +## Objective + +A mod author edits one ship `.cc` file, including the hull schematic and every +hardpoint. The file holds two typed records: the ship's `HullData` and the +`ShipAuthoring` visual package that hull names through `HullData.Visual`. Blender, through Aetheria tooling built on +Brokkr, edits that same record while displaying its visual source. The game +assembles an instance from the record and its referenced asset package at +runtime. A mod package can be installed without opening the Unity Editor. + +## Current mechanism + +`GameData/Aetheria.cc` holds `HullData`: the cell shape, hardpoint footprints, +stats, and a Unity Addressables prefab GUID. `ZoneRenderer.LoadEntity` loads +that prefab and expects `ShipInstance`; `EntityInstance` and `ShipInstance` +match catalog hardpoint transform strings against manually wired prefab +arrays. The new FBX naming builder automates prefab wiring but still emits a +Unity prefab and is part of this existing path. Brokkr can capture Blender +collections and custom properties; the AetheriaEve Blender authoring v1 +contract describes a future collection-to-CultMesh deploy lane, but that lane +is not yet an end-to-end ship loader in the current game. + +## Target authority map for the parallel lane + +- **Owner:** a mod-owned `.cc` file holds two records. Its `HullData` owns the + ship's authored hull semantics: schematic, hardpoints, and stats. Its + `ShipAuthoring` document owns the visual package: model path, anchor-to-node + associations, and schematic lines. `HullData.Visual` is the only binding + between them; a hull names exactly one of `Prefab` and `Visual`. A ship ID is stable across + display-name changes. +- **Inputs:** the authoring record; a Blender visual source identified by the + record; compiled mesh, texture, and material artifacts; references to gear + designs where the game requires them. +- **Outputs:** a validated runtime hull design and an assembled visual/physics + `ShipInstance`. The assembly and any catalog row are derived products. +- **Derived state:** Unity objects, component arrays, collision components, + particle emitters, and schematic UI. Installed equipment, damage, heat, + cargo, ownership, and position are live game state. +- **Forbidden writers:** Blender object names, Unity prefabs, generated catalog + rows, and runtime components may not independently decide the schematic, + hardpoint type or footprint, armor, drag, or mount identity. Geometry nodes + carry stable IDs; the `.cc` document gives them meaning. +- **Shared path:** Blender validation, command-line validation, editor preview, + and runtime loading read the same typed record and invoke the same semantic + validator. A bad mod is rejected before partial scene construction. +- **Cut line:** no existing ship path is removed during proof. Migration later + deletes or demotes the old ship-specific catalog/prefab authority for each + migrated hull; it does not keep two writable definitions of that hull. + +`ship-authoring validate`, the catalog composer, and the visual importer call +the same `ShipAuthoringStore.Validate(hull, visual)`; that shared path is true of the C# callers only. +The Blender side checks grid bounds and footprint shape (`ship_cc.py`) and +nothing semantic. Blender edits the hull grid, hardpoints, and +captured lines in the typed source records; `inspect` reads incomplete drafts. +Unity's **Aetheria / Preview Mod Ship +Package** imports a validated package from disk, resolves stable GLB node IDs, +and draws the captured polylines directly as 3D line segments. Point opacity +and color are retained; radius and material-specific stroke styling are not +rendered yet. The game reads mod records through the boot path described +under Runtime catalog seam. + +## Runtime catalog seam + +`AetheriaStores.CatalogTypes` routes `ShipAuthoring` to the shipped catalog, +but the shipped catalog contains no `ShipAuthoring` record. This stays correct +only while nothing writes a `ShipAuthoring` through a catalog-writable cache on +`Aetheria.cc`; a mod ship's authoring record lives in its own `ship.cc` and in +the derived catalog. + +`CultCache` routes `ItemData` to one home backing store, and +`ActionGameManager.CultCache` holds that store for the entire play session. +Attaching each mod's `.cc` as another item store would violate the cache's +one-home invariant. `ship-authoring compose` instead derives one runtime catalog from +the shipped catalog and validated mod packages, preserving all shipped record +keys. Each mod's stable `ShipAuthoring.Id` yields separate deterministic keys +for its copied `HullData` (`mod-hull:`) and its runtime authoring record +(`mod-ship:`). A mod's `ship.cc` stores its two records under those same +keys, and compose copies them verbatim, so the derived catalog holds one hull +per mod ship and `HullData.Visual` names the `mod-ship` record. The generated +catalog is disposable; the shipped catalog and each mod's source `.cc` remain +the owners. A player session opens one catalog snapshot and cannot hot-swap its +designs beneath existing entities. + +Each immediate child of the mods directory has an ID matching its directory +name and contains `ship.cc` plus the GLB at the record's relative `ModelAsset` +path. Every referenced anchor uses an `aetheria.id` custom property exported +into a GLB node's `extras`. Compose checks the asset, unique IDs, and every +reference before atomically replacing the derived catalog. For example: + +```text +dotnet run --project tools/AetherDb -- ship-authoring compose GameData/Aetheria.cc GameData/Aetheria.modded.cc GameData/Mods +``` + +The game does not need this command: at boot, when `GameData/Mods` holds a +package, it composes the derived catalog into `Application.persistentDataPath` +(`ShipModCatalog.ResolveCatalog`) and opens that file instead of +`Aetheria.cc`; with no package it opens the shipped catalog. The derived file is +recomposed on every launch. A playable ship is still outstanding. In the Quiet probe, +206 shipped records became 208 derived records: one `mod-hull:quiet` and one +`mod-ship:quiet`. A missing GLB node ID was rejected without changing the +previous derived file. The probe's four anchors and zero hardpoints are only +a data-path smoke, not a playable Quiet design. + +The visual importer uses [Unity glTFast's runtime +import](https://github.com/Unity-Technologies/com.unity.cloud.gltfast/blob/main/Packages/com.unity.cloud.gltfast/Documentation~/ImportRuntime.md) +to read the package GLB asynchronously and map its stable node IDs to Unity +transforms. It keeps a partially loaded object inactive and destroys it on +failure. `ShipModShips` preloads one assembled, inactive prototype per hull +that names a `Visual`, at boot and before the game scene loads. `ShipModPlan` +decides which anchor fills which `ShipInstance` slot: the hull's hardpoint type +says what a mount is, and its anchor (id equal to the mount id) supplies the +node; a thruster mount needs a `thruster-emitter` anchor, a radiator mount a +`radiator-mesh` anchor, a weapon mount muzzle anchors parented to it. An +`articulation` anchor is an ordinary mount node until pivots move onto +`HullData`. The shared effects (shield, tractor beam, ping, explosion, map +and invisible materials) come from the Addressable `ShipModTemplate` prefab. +`ZoneRenderer.LoadEntity` clones the prototype when the hull names a `Visual`. +Gameplay reads a mod ship's records from the derived catalog; the package +directory supplies only the GLB. `capturepreset` still writes the shipped +catalog. Continue refuses a run naming a design the catalog no longer holds +(`RunSave.RequireDesigns`), naming the missing mod ships. + +## Proof gates + +1. A typed `.cc` record round-trips between C# and Blender's Python runtime, + preserving unknown future fields and record identity. +2. Blender edits schematic cells and hardpoints in that record. Stable visual + node IDs still need a collection-to-package authoring action; the C# + validator checks their association with mount IDs and GLB nodes. The model + supplies geometry, not a second copy of hull semantics. +3. A command-line validator rejects malformed cells, overlapping or dangling + hardpoints, missing model nodes, and unresolved asset references with + precise errors. It changes no live catalog or scene on failure. The + composer now performs this check for a package before replacing its + derived catalog. +4. A packaged mod ship loads in a built Unity player without Unity Editor or + Blender installed. Runtime assembly creates the same components the + current `ShipInstance` expects and uses the existing simulation rules. +5. Spawn, equip, thrust, fire, shield, damage, save/reload, and schematic UI + work for the mod ship. Only then is a shipped hull eligible for migration. + +### Unity batch smokes + +Both run in batchmode against a package the tests generate: set `AETHERIA_SHIP_FIXTURE_DIR` while running +`ShipModCatalogTests.TheFixturePackageIsCompleteAndItsGlbCarriesAScene` and it leaves `mod.skiff/ship.cc` and +`skiff.glb` there (the GLB carries a tetrahedron mesh on the map, collider and thruster anchors, plus a weapon mount +and muzzle). Neither takes `-quit`: both are `async void` and end the Editor themselves. + +- `-executeMethod ShipModPreview.Smoke -shipModPath /mod.skiff/ship.cc [-assemble]` imports the GLB and checks + the anchors; `-assemble` also builds the `ShipInstance` from the template. +- `-executeMethod ShipModPlaySmoke.Run -shipModPath /mod.skiff/ship.cc [-shippedCatalog GameData/Aetheria.cc]` + composes a derived catalog with the package, runs `ShipModShips.Preload`, instantiates the ship through + `ShipModShips.Instantiate` (the call `ZoneRenderer.LoadEntity` makes) under a bare parent transform, and requires + thruster and weapon hardpoints (each weapon with a muzzle), one `MeshCollider` over a readable mesh, and a map icon. + It prints `SHIP_MOD_PLAY_SMOKE thrusters=N weapons=N collider=ok mapicon=ok` and exits 0, or logs the exception and + exits 1. It uses no scene and no zone. + +## Structural and build budget + +The proof reuses `HullData` simulation semantics, CultCache `.cc` persistence, +Brokkr's Blender host, and the current `ShipInstance` behavior. It adds one +authoring document type and validator, Blender-facing layout and line editing, +a disposable catalog composer, and one runtime GLB/line visual importer with +an Editor preview, `ShipInstance` assembly and boot-time preloading. No daemon, second gameplay simulation, or Unity +prefab generator is added. The existing FBX builder remains available to +existing content but is not an input to this lane. Its retirement follows +migration. + +Focused checks use `Aetheria.Shared` and `tests/Aetheria.Shared.Tests` under +`netstandard2.1` / `net10.0`, Python CultCache interoperability checks, and +the Unity 6000.3.24f1 Editor compile and play probe. No workspace-wide build +or new executable target is justified for schema work. The current catalog is +12.7 MB; it is not rewritten during the proof. The worktree starts clean from +`4b594e11`; unrelated Unity scene and material edits remain in the original +checkout. diff --git a/docs/moddable-ships-cut.md b/docs/moddable-ships-cut.md new file mode 100644 index 000000000..70b59e696 --- /dev/null +++ b/docs/moddable-ships-cut.md @@ -0,0 +1,516 @@ +# Aetheria Codex assimilation: refreshed cut maps (mining, moddable ships) + +Date 2026-09-29. Imagination output for Self. It re-anchors two Codex lanes to the Body as it will stand after +`codex/fire-control-12` merges to `master`. The Codex maps are raw material, not authority. Where this file and +a Codex map disagree, this file is the proposal and the Codex map is the input. + +## How this was established + +- **Branch tips read, 2026-09-29, after `git fetch`.** + - `origin/master` `9b85211f` + - `origin/codex/fire-control-12` `b66ba524` + - `origin/codex/mining` `283ce7dc` + - `origin/codex/moddable-ships` `375d6bd4` + - Nothing in `F:\Projects\Aetheria`'s working tree was read or switched. Every read is `git show` or `git grep` + against a SHA. +- **The post-fire-control Body is a synthetic merge.** `git merge-tree --write-tree origin/master + origin/codex/fire-control-12` is clean, tree `91576243`. I wrapped it in an unreferenced local commit, + `8a2db490` (no ref, no push to origin), so it can be built. The fire-control checklist (`docs/merge-to-master-checklist.md:7,107` + on `b66ba524`) predicts the same clean merge. +- **Anchors.** Each `file:line` names a real SHA, never the synthetic one: + - `b66ba524` for files only fire control touched; + - `283ce7dc` for files the mining branch touched; + - `375d6bd4` for files the ships branch touched. + + The three file sets are disjoint. I checked with `git diff --name-only` over each branch's own range, and none + of the three pairs shares a file. So each anchored line is byte-identical in the merged tree. +- **Tests ran on Yggdrasil, against synthetic merges** (section 0). CultLib `45c2f40` and CultMath `6d5e209` are + the pins in `Directory.Build.props`. The two LFS files the tests read (`GameData/Aetheria.cc`, + `Assets/Resources/Settings.asset`) were staged beside the job, because the verify mirror carries no LFS. +- **Catalog facts** come from a probe that opens the merged tree's `GameData/Aetheria.cc` through + `AetheriaStores.Open` (section 0). + +## 0. Probe results + +**Test suite on the synthetic merges**, Yggdrasil, `dotnet test tests/Aetheria.Shared.Tests`, CultLib `45c2f40`, +CultMath `6d5e209`, the `dotnet` image: + +| Tree | Commit (local, unreferenced) | Result | +|---|---|---| +| master + fire-control-12 + mining | `396d19e5` | **379 passed, 0 failed** | +| master + fire-control-12 + ships | `0036204f` | **364 passed, 0 failed** | +| master + fire-control-12 + mining + ships | `474c35c3` | **381 passed, 0 failed** | + +Fire control closed 12.4 at 362 tests. 379 = 362 + 17 mining tests, 364 = 362 + 2 ship tests, and 381 is both +together. Nothing on either branch breaks a fire-control test, and nothing in fire control breaks a branch test. +This proves the headless simulation only. No Unity compile ran. + +**Catalog probe** (`scratchpad/probe/Program.cs`: it opens `GameData/Aetheria.cc` through `AetheriaStores.Open` +in the merged tree; the catalog oid `2aa79c0a` is the same in all three merges and at `b66ba524`): + +- 124 items: 32 `GearData`, 18 `WeaponItemData`, 13 `SimpleCommodityData`, 5 `HullData`, 51 compound + commodities, 4 cargo bays, 1 docking bay. +- **Weapon damage types:** Kinetic 9, Electric 3, Optical 3, Thermal 3. There is none of Corrosive or Ionizing, + though the `DamageType` enum has all six. The mining map said Kinetic 10. +- **Penetration > 0:** only Autocannon, LRMM72 and SRMM72, each at 0.25. +- **DamageSpread > 0:** GT 3K 3.25, plight 3.3, pswarm 1.5, scorched void policy 1.5, and SRMM72 0.5. The map + listed four and missed SRMM72. +- **No weapon has `BlastRadius` or `Fuse`.** Blasts are dormant in shipped content until F12-2 authors them. +- **Simple commodities:** the 13 the map named. Every one is priced 0 **except Ammo, at 1000**. The map's + "every live simple commodity has Price 0" is off by one. +- **No live item carries a scanner or mining behaviour**, on fire control or on mining merged. +- **Pre-existing, on `b66ba524` as well as on the merges:** four `GearData` records (Refinery, Deep Ore + Extractor, Assembly Line, Shipyard) hold a **null element** in `Behaviors` (index 0 of 1). It does not come from + mining's union-26 retirement: the same four are null on fire control alone. This matters to variants C4 (A.6). +- **Shipped hull mount ids are not unique:** + + | Hull | Hardpoints | Distinct `Transform`s | Empty `Transform`s | + |---|---|---|---| + | Djinni | 22 | 20 | 3 | + | Longinus | 13 | 12 | 2 | + | LonginusX | 10 | 9 | 2 | + | Turret | 7 | 3 | 5 | + | Zenith | 5 | 1 | 5 | + + All five hulls use `Prefab`. This matters to ship migration (S5). + +## Shared precondition for both campaigns + +Both campaigns wait on one event: `codex/fire-control-12` merging into `master` with `--no-ff`, which Self does +after the operator signs off (`docs/merge-to-master-checklist.md:105-113` on `b66ba524`). Until then, neither +campaign has a base to merge onto except the fire-control branch itself. After it: + +``` +git switch codex/mining && git merge --no-ff master # in a worktree, never the operator's tree +git switch codex/moddable-ships && git merge --no-ff master +``` + +**Merge, do not rebase.** Both maps and their Soul receipts cite landed SHAs: mining cites 11 of its 13 commits, +and the ships doc cites its commits' results. A rebase rewrites every one of those SHAs, which strands the maps' +evidence. The merge has no conflicts (below), so it costs one merge commit per branch. + +--- + +## Rulings (operator, 2026-09-30) + +- **MQ1: a ship `.cc` is self-contained.** Operator: "The idea is for the new moddable ships to eventually + take over from the existing system. A ship .cc should contain everything needed to instantiate and render a + ship." The confirmed reading: the hull is its own `HullData` record and the visual is its own record, both in + the one ship `.cc`, side by side. The hull is not embedded in the visual. A hull family such as Longinus and + LonginusX lives together in one `.cc`, so variants resolve within one store. S1 follows option B, with both + records inside the ship's own store. +- **MQ2 A for now.** There are no cross-file variants of shipped hulls in this lane. **Operator note, to be + carried into CultLib's variants target:** "we'll want cross-store variant support eventually; modders should + be able to add variants of existing items without modifying the original". +- **MQ3 A.** The FBX prefab builder is scaffolding. The typed `.cc` lane replaces the existing system, and the + builder dies at S5. +- **MQ4 A.** Continue refuses loudly and names the missing mod ids. +- **MQ5 A.** The game composes the modded catalog at boot, from `GameData/Mods`, into a disposable file. +- **Soul (2026-09-30) on `375d6bd4`** found the Blender↔C# `.cc` round trip real, with no vendored codec. + Before any cut builds on it, the S-Soul fix slot must fix: + - F1: 8 of 9 validator mutations survive, including the `..` path guard and the prefab refusal. + - F2: `Compose`, `ReadPackage` and `ReadNodeIds` are untested. + - F3: there are no Python tests; slot numbers and enums are duplicated by position. + - F6: `CatalogTypes` includes `ShipAuthoring`. Check name collisions. + - F7: a drive-by `using` removal. + - F5 is settled by MQ1. + +- **Pivots own firing arcs (operator, 2026-09-30, from fire control).** A turret's arc belongs to its + pivot, not its hardpoints. When this campaign adds pivots to `HullData`, the arc moves from the hardpoint + to the pivot, and the interim "intersection of hardpoint arcs per pivot" rule in fire control is deleted. + Unity's `Pivot......` node-name parsing (`ShipPrefabAuthoring.cs:144`) must not + survive as a second arc authority. + +# Part B. Moddable ships + +## B.1 Status header (verified against git) + +Branch `codex/moddable-ships`, tip `375d6bd4`: 4 commits on `4b594e11`. `4b594e11` is an ancestor of fire +control, which has since moved 8 commits to `b66ba524`. Neither side touches the other's files. + +| SHA | What landed | +|---|---| +| `42eb5214` | `ShipAuthoring` record and validator; `AetherDb ship-authoring create/inspect/validate`; Blender LineArt capture; 2 xunit tests | +| `4ba4bbaf` | `ShipModCatalog.Compose` (derived catalog) and GLB node-id reader | +| `24c29640` | Unity `ShipModVisual` (glTFast runtime import, line mesh) and Editor preview; `com.unity.cloud.gltfast` 6.20.0 added to `Packages/manifest.json` | +| `375d6bd4` | Blender layout editing (hull grid, hardpoints) through `ship_cc.py` | + +The delta is +511 C# (including `tools/AetherDb`), +494 Python, +119 tests, and one new Unity package dependency. +It also carries a stray fix in `Assets/Scripts/UI/Menu/TradeMenu.cs` (an unused `using System.Runtime.Remoting.Contexts`). +Self's ruling: it stays on this branch as cleanup. Master compiled clean in Unity with the using present, so master does +not need it. + +**Test counts.** The two ship tests pass on the merged tree: 364/364 (section 0). + +**S-Soul status:** F1, F2, F3 and F6 fixed at `fe38f288` (479 tests). F4 has no spec entry. The Python tests +(`tools/blender/tests/test_ship_cc.py`, 32) have no runner yet; run them by hand. + +**S0 status (2026-09-30):** master `65c63495` (fire control 12, `dcd7bbc5`) merged into `codex/moddable-ships` with +`--no-ff` at `18e12d81`, no conflicts. Corrections 1-4 applied to `docs/moddable-ship-authoring.md`. Yggdrasil full +suite on the merge (`dotnet test tests/Aetheria.Shared.Tests`, CultLib `45c2f40`, CultMath `6d5e209`): **615 passed, 0 failed**. Self's steps, 2026-09-30 05:15 CEST: the Unity 6000.3.24f1 +batchmode compile of `01e9db1c` has 0 `error CS` and 0 `warning CS`, and `ShipModPreview.Smoke` passed +(`SHIP_MOD_VISUAL_SMOKE anchors=5 points=2 segments=1`, its first recorded run). **The branch has no committed +fixture package:** the smoke ran against one generated from `ShipAuthoringTests.Fixture()` with a hand-added glTF +`scene` (the test GLB has nodes but no scene; whether glTFast instantiates a scene-less GLB is unchecked). S1 should +commit a scene-bearing fixture package so the smoke is reproducible. + +**Anchors re-taken against the merged tree (`18e12d81`).** +- Unchanged: `ShipAuthoring.cs:15` (`Hull`, key 1), `:84`, `:111-136` (the hardpoint checks are `:112-131`), + `ShipModCatalog.cs:20-21` (keys), `ItemData.cs:512` (`Hardpoints` `Key(23)`), `:515` (`Prefab` `Key(24)`), + `Loadout.cs:74`, `EntityInstance.cs:15-27`, `ZoneRenderer.cs:289-310` (`LoadEntity`), `AetheriaStores.cs:9`. +- Moved: the second upsert in `ShipModCatalog.Compose` is `:68-69` (was `:60-61`; the F1-F3 fix added the + name-collision checks above it). `ship_cc.py`: slot constants are `:23-25`, `replace_layout` is `:96-124`, + the `body[HULL_SLOT]` reads are `:84,101`. `ActionGameManager.cs`: the catalog opens at `:55-59` + (`AetheriaStores.Open`, not `:45-60`); `capturepreset` is `:621-662`. +- S1's key 32 for `HullData.Visual` holds: `EquippableItemData` owns 30 and 31, `HullData` uses 23-29, and + `WeaponItemData.Fuse` at 32 (`ItemData.cs:505`) is a sibling class, not an ancestor. + +**Proof-gate status against the doc's own gates (`docs/moddable-ship-authoring.md:149-164` @`375d6bd4`):** + +| Gate | Doc implies | Verified in git | +|---|---|---| +| 1. C#/Python round trip preserving unknown fields | met | **C# only.** `StandaloneShipRoundTripsWithoutTouchingTheCatalog` pins C#. The Python half and "preserving unknown future fields" rest on the Quiet probe, whose output `Build/quiet.cc` is git-ignored. No repository test exercises `ship_cc.py`. | +| 2. Blender edits cells and hardpoints | met, except node-id authoring | **Code exists, unpinned.** `ship_cc.replace_layout` (`ship_cc.py:75-106`) has no test. | +| 3. Validator rejects malformed records, changes nothing on failure | met, and compose checks it | **Validator pinned.** `InvalidSchematicOrDanglingMountCannotBePublished` covers 5 cases. **Compose unpinned:** no test covers key collision, the atomic replace, a missing GLB node, or "the previous derived file is unchanged on failure" (`ShipModCatalog.cs:23-73`). | +| 4. Loads in a built player | outstanding | not started | +| 5. Play checks | outstanding | not started | + +**Corrections to `docs/moddable-ship-authoring.md` at `375d6bd4`:** + +1. **`:9-16` and `:132-136` report the Quiet probe's numbers as facts.** They include 1,040 polylines and + "206 shipped records became 208". Nothing in git reproduces them. Label them as an unrecorded probe, or + commit a fixture that pins them. +2. **The composed catalog holds two copies of every mod hull.** + - `:114-118` says compose preserves one owner per ship. + - `ShipModCatalog.cs:60-61` upserts `ship.Hull` as a `HullData` at `mod-hull:`, **and** the whole + `ShipAuthoring`, whose key 1 is the same `HullData`, at `mod-ship:`. + - Gameplay can read only the first. The second is a dead copy of the same truth inside a derived file. Q1 + decides the fix. +3. **`AetheriaStores.CatalogTypes` now routes `ShipAuthoring` to the shipped catalog** (`AetheriaStores.cs:9` + @`375d6bd4`), while the doc says the shipped catalog "contains no copy of that ship". Routing a type is not + holding a record, so this is harmless today. It stays correct only while nothing writes a `ShipAuthoring` + through a catalog-writable cache on `Aetheria.cc`. Name that invariant in the doc. +4. **`:98-106` "the same semantic validator" on every path.** The Blender side validates nothing semantic: it + checks grid bounds and footprint shape (`ship_cc.py:83-97`). "Shared path" is true for the C# callers only. + +## B.2 Merge path onto the fire-control-12 lineage + +| Probe | Result | +|---|---| +| `git merge-tree --write-tree origin/codex/fire-control-12 origin/codex/moddable-ships` | clean, tree `97711bcd` | +| `git merge-tree --write-tree 8a2db490 origin/codex/moddable-ships` (master+fc12) | clean, tree `88672977` | +| on top of mining merged into master+fc12 | clean, tree `a7410174` | +| files shared with fire control `4b594e11..b66ba524` (6 files: `Entity.cs`, `FireControl.cs`, two test files, two docs) | none | + +The merged tree passes the full headless suite: 364/364 alone, and 381/381 with mining (section 0). + +The only cross-lane seam is `Packages/manifest.json` (glTFast). It merges textually, but it needs Unity to +resolve the package on first open, like the CultMath tag already does (`docs/merge-to-master-checklist.md:14`). + +## B.3 Ordered cuts + +| Cut | Nature | Blocked by | +|---|---|---| +| S0 | Placement: merge master, correct the doc | fire-control-12 on master | +| S-Soul | Fix batch from the parallel Soul pass | Soul's report | +| S1 | One hull record, and a hull names its visual | MQ1 | +| S2 | The game composes and loads mod ships (`ShipInstance` wiring, boot preload) | S1; MQ4, MQ5 | +| S3 | Gate 4: a built player loads a mod ship | S2; a playable mod ship (content) | +| S4 | Gate 5: play checks | S3 | +| S5 | Migration of shipped hulls, onto variants; FBX builder retirement | S4; MQ2, MQ3; variants C4 | + +### S0. Placement and doc correction + +- **Repo/branch:** Aetheria, `codex/moddable-ships`, in a worktree. +- **Deletes first:** none. +- **Keeps/moves/adds:** `git merge --no-ff master`. Apply corrections 1-4 to the doc. +- **Verification:** + - Yggdrasil full suite on the merge (the M0 command). + - Unity batchmode compile of the merged tree with glTFast resolved. This is Self's step, and it needs network + for the package. + - The Editor smoke already in the branch: `-executeMethod ShipModPreview.Smoke -shipModPath ` + (`ShipModPreview.cs:8` @`375d6bd4`), run against a committed fixture package. It is the first recorded run + of that smoke. +- **Subtraction:** docs only. + +### S-Soul. Fix slot for the parallel Soul pass + +- **Repo/branch:** `codex/moddable-ships`, after S0. +- **Content:** Soul's findings. Two areas this map expects Soul to own, and does not duplicate: + - Compose's unpinned failure paths (B.1, gate 3). + - The hand-copied schema on the Python side: + - `ship_cc.py:17-21` slot constants (`HULL_SLOT 1`, `HULL_SHAPE_SLOT 5`, `HULL_HARDPOINTS_SLOT 23`); + - `ship_cc.py:88-98` hardpoint slots 0-6; + - `__init__.py:18-21`, a copy of the `HardpointType` and `ItemRotation` enums. + + All of these match C# today: `ItemData.cs:287` `Shape` is `Key(5)`, `HullData.Hardpoints` is `Key(23)` at + `:512`, and `HardpointData` is `:553-563`, all @`b66ba524`. `Enums.cs:38` matches too. The hazard is drift: + fire control added slot 6 (`FiringArc`) to `HardpointData` in this same lineage. The memory + `honor-invariants-over-workarounds` names hand-copied schemas as a known failure. The coherent fix reads + the published schema catalog. Soul decides whether it is in scope. + +### S1. One hull record, and a hull names its visual (written for MQ1 = B) + +- **Repo/branch:** `codex/moddable-ships`, after S-Soul. +- **Deletes first:** + - `ShipAuthoring.Hull` (`ShipAuthoring.cs:15`, key 1) becomes a retired-key comment. + - The embedded-hull branch of the validator (`ShipAuthoring.cs:84-133`) moves; it does not duplicate. + - The second upsert in `ShipModCatalog.Compose` (`ShipModCatalog.cs:60-61`) becomes a verbatim copy of the + mod store's records. + - `ship_cc.py`'s `body[HULL_SLOT]` indirection (`:63-66`, `:80-100`). + - The only existing `.cc` with the old shape is the git-ignored `Build/quiet.cc` probe. No committed content + migrates. +- **Adds:** + - A mod `.cc` holds two records: a `HullData` at the deterministic key `mod-hull:` (`ShipModCatalog.cs:20`) + and the `ShipAuthoring` visual package (`Id`, `ModelAsset`, `Anchors`, `SchematicLines`). + - `HullData` gains a nullable `CultRecordRef Visual` at the next free key on its ancestry. + `EquippableItemData` owns keys up to 31 (the comment at `ItemData.cs` `WeaponItemData.Fuse`), so it is 32, + unless C4 claims that slot first. + - The validator refuses a hull with both `Prefab` and `Visual` set, or neither, when it is a ship. + - The validator is one function over (hull, visual). It checks every `Hardpoints[].Transform` against the + visual's anchor ids, the checks that are at `ShipAuthoring.cs:111-136` today. +- **Authority map:** + - Owner: the `HullData` record owns hull semantics (cells, hardpoints, stats). The `ShipAuthoring` record owns + the visual package (model path, anchor-to-node map, lines). + - Inputs: the mod `.cc`, and the GLB node extras. + - Outputs: records copied verbatim into the derived catalog. + - Demotion: `ShipAuthoring` is no longer an owner of hull data. `mod-ship:` in the derived catalog is the + same record as in the mod store. + - Forbidden writers: compose transforming records; Blender writing hull slots inside `ShipAuthoring`; any + lookup from hull to visual by key-prefix convention. The typed `Visual` ref is the only binding. + - Shared paths: `ship-authoring validate`, compose, the Editor preview and the runtime loader all call the one + `(hull, visual)` validator. + - Deletion line: after S1, `grep -n "\.Hull\b" ShipAuthoring.cs ShipModCatalog.cs` finds no embedded hull. +- **Verification** (Yggdrasil, `--filter FullyQualifiedName~ShipAuthoring`, then the full suite): + - `ComposedCatalogHoldsOneHullPerModShip`: the negative for correction 2. It fails today. + - `HullNamesExactlyOneVisual`: Prefab xor Visual. + - `HardpointsMustResolveToTheVisualsAnchors`: moved from the old validator. + - `ComposeRefusesAKeyCollisionAndLeavesThePreviousFile` and `ComposeRefusesAMissingGlbNode`: the gate 3 + negatives, unless S-Soul already added them. + - `AHullVariantInheritsItsVisual`: runs only once Aetheria is on variants C4. It is the reason for B, and it + is recorded as pending until then. + - A Python check, in the Blender-free `python:3.12-slim` image with `pip install msgpack -e /packages/cultcache-py`: + `ship_cc.replace_layout` on a C#-written fixture preserves every untouched slot, then C# reopens it and it + validates. This pins gate 1's Python half for the first time. + - Operator: in Blender, load a layout, change a mount, save, then `ship-authoring validate`. +- **Subtraction estimate:** about 40 removed (the embedded-hull paths and the duplicate upsert), about 35 added + (`Visual`, the joint validator's plumbing), and about 25 in the Python path. + +### S2. The game composes and loads mod ships + +- **Repo/branch:** `codex/moddable-ships`, after S1. +- **Deletes first:** none. This cut is additive: it is the construction boundary the doc names at `:141-145`. +- **Adds, per MQ4 and MQ5:** + - **Compose at boot** (MQ5 = A): `ActionGameManager` opens its catalog at `ActionGameManager.cs:45-60` + (`b66ba524`). When `GameData/Mods` holds packages, it opens the derived file instead, composed at boot into + the persistent data path. `capturepreset` keeps writing the shipped catalog (`:605-620`, and the + `Loadout.cs:74` writable open). + - **Boot preload:** after the catalog opens and before the first zone loads, every hull with `Visual` set + imports its GLB through `ShipModVisual.LoadAsync` into an inactive prototype keyed by hull key. + `LoadEntity` then instantiates synchronously, as it does for prefabs. + - **Assembly:** a `ShipInstance` template prefab (Addressable) carries the shared effect prototypes: shield, + tractor, thruster particles, radiator material. The loader parents the GLB under it and fills + `EntityInstance`'s arrays (`EntityInstance.cs:15-27` @`b66ba524`: `MapIcon`, `Shield`, `HullColliders`, + `EquipmentHardpoints`, `RadiatorHardpoints`, `ThrusterHardpoints`, `WeaponHardpoints`, + `ArticulationPoints`, and `ShipInstance.TractorBeam`) from anchors by role. The name matches that + `EntityInstance.cs:245,260,271` and `ShipInstance.cs:69-70` do against `hp.Transform` keep working, because + anchor ids are the mount ids. + - **`ZoneRenderer.LoadEntity`** (`ZoneRenderer.cs:289-310` @`b66ba524`) branches on `hullData.Prefab` or + `hullData.Visual`. That is one branch point, owned by the hull record. +- **Authority map:** + - Owner: the hull's `Visual` ref decides the visual. The anchor role decides the component slot. + - Inputs: the derived catalog snapshot, the mod package directory, and the template prefab. + - Outputs: a `ShipInstance` indistinguishable to the simulation from a prefab one. + - Derived state: the prototypes (cache-only, rebuilt each boot) and the derived catalog (disposable). + - Forbidden writers: prefab arrays hand-wired for a mod ship; any async load during `LoadEntity`; any gameplay + read of a mod package outside the derived catalog. + - Shared paths: new game, Continue, zone entry, and wormhole transit all go through `LoadEntity`. +- **Verification:** + - Yggdrasil: `ComposeAtBootIsDeterministic`. The same packages give byte-identical derived records, which + pins run-store references across relaunches. + - `RunReferencingAMissingModRefusesContinue`, per MQ4. + - Unity batchmode (Self): an Editor play-mode smoke loads a fixture mod ship into a zone and asserts + `ThrusterHardpoints`, `WeaponHardpoints` and the collider are populated. + - Operator: none yet (S3 and S4). +- **Subtraction estimate:** 0 removed, about 150 added (loader, template, preload). This is the capability gate 4 + buys. + +**S2 status (2026-09-30, Self):** landed on `codex/moddable-ships` through `48cabc5f`. Soul passes on S2 and its +fixes (bad packages excluded and named, never fatal; mount anchors typed by hardpoint; `capturepreset` refuses mod +designs; explicit null checks at Continue; compose failure falls back to the shipped catalog). Headless 684/684. +Unity 6000.3.24f1: compile clean; `ShipModPlaySmoke.Run` (edit mode, real preload and `Instantiate`) prints +`SHIP_MOD_PLAY_SMOKE thrusters=1 weapons=1 collider=ok mapicon=ok`; `ShipModPreview.Smoke -assemble` passes against +the generated mesh fixture. Owed: the operator's play-mode checks (menu dialog for excluded mods, New Game/Continue +with a mod, zone entry, wormhole, Continue after removal). Recorded, not fixed: two processes sharing +`Aetheria.modded.cc`; preload running inside the `CultCache` getter; a mod updated in place that changes a hull +passes the gate. The interim ruling that a non-thruster/radiator/weapon mount must be an `articulation` anchor is +superseded by the ruling below. + +**Mount-point ruling (operator, 2026-09-30):** "Regarding mount points, they're only really needed for hardpoints +that are externally visible in some way. That's just weapons, radiators, thrusters right now." So a mount anchor +exists only for the `weapon`, `radiator` and `thruster` roles. There is no `equipment` role and no plain mount. +Other hardpoints are internal and carry no anchor. Articulation points (turret pivots, `ArticulationPoint.Group`) +are a separate concept and are not mounts. They stay. Follow-up for S3 prep: find out whether +`EquipmentHardpoints` (line 314) has a consumer outside anchor wiring. If it has none, delete it, and have the +validator refuse a mount with any other role. Also: the operator said "Missing design refusal on catalog entries +is good": keep it. + +### S3. Gate 4: a built player + +A player build loads a composed mod ship without the Editor or Blender. Only Self (the batchmode build) and the +operator (launch) can do this. It also requires a playable mod ship: a complete package with hardpoints, not the +Quiet probe, which has four anchors and zero hardpoints (`docs/moddable-ship-authoring.md:134-136`). That is +content, and it is the operator's to author or commission. + +### S4. Gate 5: play checks + +The operator only: spawn, equip, thrust, fire, shield, damage, save and reload, and the schematic UI for the mod +ship. It runs on master's post-fire-control rules, so the checklist's steps 11-15 (arcs, rolled impacts, blasts) +apply to the mod hull too. + +### S5. Migration onto variants + +After gate 5, and after MQ2 and MQ3. +- Shipped hulls move to `Visual` one at a time, and each migration deletes that hull's `Prefab`. +- Hull families collapse into variants in `Aetheria.cc`. The variants scan found Longinus/LonginusX, differing + in `Behaviors`, `Hardpoints` and two cosmetic members (`CultLib docs/document-variants-cut.md` §6). +- It waits on variants C4 (Aetheria adoption at `caching-unity-v1.5.0`). +- **Mount ids come first.** The typed lane requires unique, non-empty mount ids (`ShipAuthoring.cs:115-117` + @`375d6bd4`). No shipped hull has them: Djinni has 3 empty `Transform`s and one duplicate, and Zenith has 5 + hardpoints with one distinct `Transform` (section 0). Each migration first assigns unique mount ids and repoints + the prefab-era name matches. `Transform` is also not usable as a C2 element id, so C4's minted id and the mount + id stay two members: one is the identity for variants, and the other names the model node. +- **Deletion line:** when the last hull migrates, `HullData.Prefab` (key 24) retires, and `ShipPrefabAuthoring.cs` + goes (MQ3). + +## B.4 Subtraction ledger (estimate) + +| Cut | Removed | Added | Formats, targets, dependencies | +|---|---|---|---| +| landed | 1 | ~511 C#, ~494 Py, 119 test | `aetheria.ship_authoring` document type; glTFast package | +| S1 | ~40 | ~35 C#, ~25 Py | `ShipAuthoring` key 1 retired; `HullData` `Visual` slot added | +| S2 | 0 | ~150 | one template prefab; no new target | +| S5 | per hull: its prefab; finally `ShipPrefabAuthoring.cs` (252) plus its smoke (80) and `HullData.Prefab` | ~0 | FBX builder retired | + +The lane is net additive until S5, and S5 is where the old authority dies. Keeping two ship-authoring paths alive +indefinitely is the liability MQ3 exists to close. + +## B.5 Operator questions (moddable ships), one fork each + +**MQ1. Where does a mod ship's hull live, and how does a hull find its model?** (Blocks S1.) + +*Context.* +- Today a mod ship is one `ShipAuthoring` record with the `HullData` embedded inside it. +- Compose writes that hull twice into the derived catalog: once as a `HullData`, and once inside the + `ShipAuthoring` copy. +- The runtime has no binding yet from a hull to its model; the doc lists it as outstanding. +- You want variants to kill duplicate data entry for ships. A variant is a whole record whose base is another + record of the same type in the same store. +- "LonginusX is Longinus with another hardpoint layout" is therefore a `HullData` variant. An embedded hull inside + another document cannot be one. + +*Options.* +- **A:** keep the embedded hull. One record per mod, but a hull family must be full copies, and the derived + catalog keeps a dead second copy. +- **B:** split it. The hull is a plain `HullData` record, and it names its visual through a `Visual` ref, the way + it names a Unity prefab today. `ShipAuthoring` becomes the visual package only. A hull variant inherits its + base's visual through normal resolution. +- **C:** split it the other way. `ShipAuthoring` references its hull. Then a hull variant has no visual unless + something reads the variant's stored base key, and no consumer may read deltas (variants target, "Readers see + complete documents"). + +*Recommend B.* It is the only shape where variants reach ships without either copying or delta-reading. It costs +little now, because no committed content uses the old shape. + +**MQ2. Can a mod ship be a variant of a shipped hull?** (Blocks S5's plan for mods; does not block S1-S4.) + +*Context.* +- Your variants ruling 3 says a variant and its base live in the same store. A mod's `.cc` is its own store, so + "my Longinus with a turret" cannot name the shipped Longinus as its base. +- Separately, Blender reads mod stores through the Python runtime, and variants ruling 5 has Python refuse any + store holding a variant until Python resolution is built (it is parked). +- So even a family within one mod's store is blocked in Blender today. + +*Options.* +- **A:** no. A mod ships complete hulls, and families inside a mod wait for Python resolution. +- **B:** yes, through compose. Compose would resolve a mod-declared base against the shipped catalog, which is a + second resolver outside the cache. +- **C:** yes, by reopening ruling 3 for a mod layer. + +*Recommend A.* B is exactly the bespoke inheritance the variants campaign exists to prevent. C is a CultLib +decision bigger than this lane. + +**MQ3. What is the FBX prefab builder for, now that the typed `.cc` lane exists?** (Blocks S5.) + +*Context.* +- `ShipPrefabAuthoring.cs` (252 lines) and its smoke (80 lines) landed on fire-control-12 at `4b594e11`, so they + reach master in this merge. +- They build Unity prefabs from FBX collections by naming convention (`docs/ship-collection-authoring.md`). +- The typed lane builds the same `ShipInstance` from a `.cc` record and a GLB. +- The ships doc keeps the FBX builder "available to existing content", with retirement "following migration". +- As things stand, the game has two ship-authoring authorities, and no ruling says which one new ships use. + +*The question.* Is the FBX builder a permanent path, for example for artists who will never use Blender with +Brokkr? Or is it scaffolding until the typed lane passes gate 5? + +*Options.* +- **A:** scaffolding. New ships use the typed lane from gate 5 on, and the builder dies at S5. +- **B:** permanent. Both paths stay, and S2's loader keeps the `Prefab` branch forever. +- **C:** retire it now, and author no new ships until gate 5. + +*Recommend A.* Two permanent authoring authorities for one concept is the split this doctrine cuts. C stalls +content for no gain. + +**MQ4. What happens to a saved run when a mod it used is removed?** (Blocks S2's Continue path.) + +*Context.* +- The run store references designs by key, and a mod hull's key is `mod-hull:`. +- Remove the mod, and those references dangle. +- The fire-control checklist already records that an old run store throws on its first lot lookup + (`docs/merge-to-master-checklist.md:15`). + +*Options.* +- **A:** Continue refuses loudly and names the missing mod ids. +- **B:** the missing ships are stripped from the run on load. +- **C:** the run loads with placeholder hulls. + +*Recommend A.* A bad mod is rejected before any scene is built (the doc's own shared-path rule). B silently edits +the player's save. + +**MQ5. Who composes the derived catalog?** (Blocks S2.) + +*Context.* The doc's own objective is "a mod package can be installed without opening the Unity Editor". Gate 4 +says "in a built Unity player without Unity Editor or Blender". A built player ships no `AetherDb`, and today +only `AetherDb ship-authoring compose` composes. + +*Options.* +- **A:** the game composes at boot, from `GameData/Mods`, into a disposable file in the persistent data path. +- **B:** an installer or `AetherDb` step composes, and the game opens `Aetheria.modded.cc` when it exists. + +*Recommend A.* Compose already lives in `ServerShared` (`ShipModCatalog.cs`), so the game can call it. B makes +"is the derived file stale?" a new failure the player owns. + +## B.6 Dependencies (moddable ships) + +- **Fire-control-12 on master:** S0. +- **Unity package resolution:** glTFast 6.20.0 needs network on first open (S0 compile). +- **Document variants:** + - **C2 (element ids):** "ids everywhere" puts an element-id member on `ShipAnchor`, `ShipPolyline`, + `HardpointData`, `ItemRole` and `BehaviorData` (every object-list element these records reach). + Consequences I read from the code, not ran: + - **Hardpoint ids survive a Blender layout save** while the mount id is unchanged. `ship_cc.py:88-98` keeps + each hardpoint's slots from 7 on, keyed by `Transform`, so an id slot at 7 or later rides along. Renaming a + mount makes a new element, which is the ruling's own rule ("a moved element is a new element"). A + hardpoint created in Blender has no id until the next C# write mints one. + - **Line ids churn on every capture.** `replace_lines` replaces `SchematicLines` whole (`ship_cc.py:51`). + This is harmless: a variant would override lines whole anyway (variants Q7). + - **The Python side writes stores C2's registry will then require ids for.** C2 mints them on the first C# + write, and Python carries the id as an ordinary member (variants Q3 rollout). So mod stores need no + migration step. + - **Python refusal:** mod stores stay v1 (no variants) while Blender reads them through `cultcache-py` + (MQ2 = A). + - **C3 (Studio):** it edits hull variants in `Aetheria.cc`. It is a prerequisite for S5, not for S1-S4. + - **C4 (Aetheria adoption, `caching-unity-v1.5.0`):** S5, and the pending test `AHullVariantInheritsItsVisual`. + Slot coordination: S1 claims `HullData` key 32 for `Visual`, and C4's id slots must not collide with it. +- **Brokkr:** the Blender add-on depends on Brokkr's `brokkr_bridge` preferences for the CultLib Python path + (`__init__.py:182-186`). It is an operator-machine dependency with no pin in this repo. diff --git a/docs/scenarios-cut.md b/docs/scenarios-cut.md index 388745737..25102e378 100644 --- a/docs/scenarios-cut.md +++ b/docs/scenarios-cut.md @@ -26,6 +26,134 @@ claim measured against a real file. "No I won't, but you may." When Cut 4 lands, Self runs `git checkout -- GameData/Aetheria.cc` in `F:\Projects\Aetheria`. That one file is the only exception to the rule that agents do not touch the operator's tree. +- **The ten real designs with no product (operator, 2026-09-30).** Soul's census of Cut 1 found that "no product" + was not a clean marker for Q3 test designs, because ten shipped designs have none. The operator ruled: + - **Industrial gear:** Assembly Line, Deep Ore Extractor, Surface Ore Extractor, Industrial Thermostatic Heater, + Refinery, Shipyard. "An old carryover from this Aetheria repo's early history as an RTS game. We'll want those + when we eventually bring production back, but it's also fine to just delete them since the new economy won't + look anything like the old one." **Self: delete them.** Git history keeps them. + **Correction, same day:** the **Industrial Thermostatic Heater stays**. Operator: "that industrial heater is sort + of needed, though, because currently stations are mostly idle so there's nothing to keep them above freezing + and they often cool to near invisibility." Only the other five are deleted. The census test allows product-less + gear that stations actually equip, and that set is derived from station generation, not from a hand list. + **Superseded, same day.** Stations have never equipped the heater. Operator: "Stations freezing is an existing + defect, I don't think I ever made those heaters spawn." Station-heater ruling A: "Yep, A. The thermostatic + behavior is the same one used in ship cockpits to keep the player from freezing, and the industrial version + should fit anywhere as a generic equippable tool." + - Every generated station spawns with one heater, through station generation. + - The heater shares the cockpit thermostat's owner. + - It is equippable on any hull. + - Self default: as generic gear it gets a product, so the census test needs no station exception. + **Station power and the Tractor Beam (operator, 2026-09-30):** + - "Yep, we need a station reactor." Author a reactor that fits Zenith's 16-cell reactor slot, with a product, + so the station heater has power. + - "Nope, ships don't need these, 'fits anywhere' was a description of tool-type gear, which doesn't require a + specific hardpoint." The heater keeps its 12-cell shape. The ship-heater test is dropped. + - "Screw old saves." No retrofit of heaters onto stations loaded from existing saves. + - "Tractor Beam is supposed to be for item pickup. A ship without a pickup behavior shouldn't be able to pick + things up, but there is currently no such limitation AFAIK." Picking up items requires a pickup Behavior, + which the Tractor Beam carries. + - Starting loadouts (operator): "Yep, everyone gets tractor beams. Pickup behavior was previously discussed as + part of the field shield map, as one of the behaviors which we'll have various visual effects for. The tractor + beam item would use the existing pickup VFX but with the standardized pickup animation." Every generated ship + and the player's starting ship carry a Tractor Beam. The pickup Behavior and its presentation follow + `docs/shield-presentation-contract.md` ("Shield and Pickup Presentation Contract"). + - Autocannon (operator): "Leave the autocannon unsold, we'll need to author a bunch more hulls before all the + gear variety in the game has a home." Self's implementation: generation and stock never offer gear that no + hull's hardpoint can fit. The rule is derived from hardpoint fit, not a hand list. The Autocannon keeps its + product and becomes sold automatically once a hull fits it. The census test is unaffected. + - Station reactors by manufacturer (operator, 2026-09-30): "On station reactors: A is a compensator that breaks + the setting; a station with no access to Zhestokost gear should not have Zhestokost gear, so B." + - Batch 2 (`b3e7995c`) authored a Zhestokost Station Reactor scaled from Manhattan. A faction without + Zhestokost allegiance got no reactor, so its station heater had no power. + - The fix is content, not a generation exception: station reactors are authored for other manufacturers, so + that every faction's stations can power their heater from gear the faction can actually get. + - The heater must be reachable the same way. + - **Soul on batch 2 (`89ef80d2..adad301b`, 2026-09-30): do not merge.** + - F1 (high): the station reactor burns out after about 20 idle minutes. By minute 40 all 128 cells are + below freezing, and at 120 minutes the hull reads 155 K. Minutes 0-20 overshoot to 447 K, which makes the + station a sensor beacon. + - F2 (high): the idle test samples minutes 5-10 and does not pay for the heater. The inert-thermostat mutant + S17 survives. + - F3 (medium, operator question): `Entity.ItemFits` (the item fits inside the hardpoint; used for equip, save + load and presets) and `HardpointData.Takes` (the item fills the hardpoint; used by generation and + `HasHome`) are two fit rules. Under `Takes`, about 15 designs players can mount are kept out of station + stock. + - F4 (high): LRMM72 and SRMM72 have no `DamageCurve` but now have products, and 22 of 300 NPCs carry them. + `SampleDps` throws an NRE at `InstantWeapon.cs:64`. Autocannon, pswarm and plight are also missing curves. + - **F3 RULED (operator, 2026-09-30): "Hardpoint fit is loose: nobody's gonna stop you from putting a small + reactor in a large reactor's hardpoint."** One fit rule: an item fits if its shape fits within the + hardpoint. Generation, `HasHome`, stock, equip, save load, presets and `AetherDb hardpoint-fit` all use + it. So the Autocannon now has a home (the Turret) and is sold. The Autocannon ruling's own rule, "never + stock gear no hull can fit", is unchanged. + - **Batch 3 rulings (operator, 2026-09-30):** + - **Soul on batch 4 (`2125f2b1..aa3baf12`, 2026-10-01): do not merge yet.** + - **Blocker: origin outside the hardpoint.** The item origin can land outside its hardpoint (`Entity.cs:825`, + `:879-885`). Every other hardpoint lookup reads the cell under the origin, `Hardpoints[item.Position]`: + ArcFor, barrels, thrusters, `ActionGameManager`. For an L-shaped hardpoint that lookup returns nothing, so + Unity throws on the first shot. It is latent: every catalog hardpoint is rectangular today. + Two ways to fix it: + - keep the origin inside the hardpoint; + - look the hardpoint up by the item's cells. + + Probe: `scratchpad/soul5/SoulScen5Probes.cs` P30. + - **Minor:** + - `IsFilledBy` is its own oracle in the test. + - Last-row search and thermostat-order are unpinned. + - A gun can't be dragged within its own hardpoint (`InventoryPanel.cs:389`). + - The new station-reactor products drop their source products' quality spread. + - **Thermal:** the Vulcan Station Reactor burns out within 10 idle minutes. That goes to the thermal + campaign. Core Power ship reactors also shut down from heat in fights. + - **Queued, not dispatched:** the operator ordered a drain on 2026-10-01. + - **F1 re-ruled after batch 4 (operator, 2026-09-30): "A, separate thermal balance cut".** Radiators did not fix + it. Heat cannot cross the hull to Zenith's edge radiators: the reactor runs at 360-436 K while the radiator + cells sit at their 278 K floor. Every station reactor wears out between minute 20 and minute 100. Ships + show the same imbalance under load: MoveOnPro runs at about 480 K and is thermally shut down for most of a + fight (S8). Thermal balance becomes its own campaign, measured by a steady-state harness across all hulls + at idle and under load. Its levers are reactor idle heat, hull conductivity, reactor tolerance and radiator + placement. Scenarios Cut 1 merges with the station freeze recorded as a known defect, which predates this + work. The 120-minute idle test is held for that campaign. + - Idle station reactor overheating and burnout (F1): **"Stations should have radiators"** (option C). The + station has a heat source and no sink. + - Per-manufacturer station reactors: **"Keep the variety, not every galaxy will have Zhestokost in it"**. + The census showed every main-sector galaxy holds all 12 factions today. The reactors are authored anyway. + - Rossum & Douglas missing from its own allegiance: the operator asked "Does allegiance to oneself even make + sense?". Self's proposal: a faction always reaches its own manufacturer's gear, and allegiance lists only + other factions. **Ruled: "removing the 11 self-entries was my intention".** Own-faction reach is implicit + in the one reach function. + - **Soul on batch 3 (`adad301b..2125f2b1`, 2026-09-30): do not merge yet.** + - S1: the new belt-failure test is flaky and failed 5 of 8 runs. + - S2: a second occupancy rule. Entity.cs:820-823 requires every hardpoint cell to be free, while tool gear may + fill a hardpoint's spare cells. So a generated Turret refuses its own gun back (40 of 955). Operator question. + - **S2 RULED B (operator, 2026-09-30): "B is the design intent, saving slots in a hardpoint can be a valid + tradeoff for crowded ships if you really need to fit an extra tool".** A hardpoint item needs only its own + cells free. A hardpoint's leftover cells may hold general (tool) gear. A hardpoint still holds at most one + hardpoint item; option C, two hardpoint items sharing one hardpoint, was not chosen. + - S3: placement searches fewer offsets than `Takes`, so an L-shaped hardpoint crashes generation. Latent. + - S4: asteroid respawn timers never count down, so mined asteroids never return. **Already fixed by mining:** + `codex/mining` deleted the belt task threading (Cut 1, `22a54ccb`), `MineAsteroid` and `RespawnTimers` (Cut 2). + Respawn is `Zone.ChunkWear.BrokenUntil`. **Merge rule:** when scenarios and mining meet, mining's side wins + for belt and chunk code. **Corrected 2026-10-01 by mining Cut 3 Soul (rehearsal `62b7cefb`/`393334c4`, 557/557):** + scenarios' `CreateOrbit`/`AddOrbit` changes are only `SettleBelts()` calls, so drop `SettleBelts` and all + three calls (lines 169/190/324 on scenarios); they merge cleanly but reference the deleted `BeltUpdates`. Delete + scenarios tests `RunStartTests.cs:639` and `:669` (deleted belt API). Conflicts: `CatalogTypes` take both; + `Zone.cs` delete `MineAsteroid`; `FireControlCut124Tests.cs:2609` take scenarios' strict Exact; + `GameData/Aetheria.cc` take scenarios' `70a7b0a9` then rerun `AetherDb field-kinds apply`. + - S5: a shield charges while unbilled. This is documented design. + - S6: pins are missing for the filling preference, product reuse and the thermostat band. + - Held: F2 (no unbilled running in the catalog, players only warmer), F4 (no nulls; no exceptions in 24k-tick + ambient runs or crowded fights), the census, rotation, and no other fit checker. + - F5: `_time` is advanced before the belt wait. F6: mining races the belt tasks. F7: reuse by cell count is + unpinned. + - Soul did **not** reproduce the Zhestokost gap: every station in 5 seeds and 12 factions got a reactor. The + premise behind the per-manufacturer reactor ruling is being checked (census) before any authoring. + - Tractor/pickup (`adad301b`, Hands stopped at the fork): the ruled design is `headless-playground-cut.md` fork + L, which needs loot as simulation bodies. That substrate does not exist, so it becomes its own campaign, typed + in the new session (`F:\Projects\HANDOFF-eureka-typed-2026-09-30.md`). The census rule "price 0 is unsold" + waits for it. + - **Weapons:** Autocannon, LRMM72, SRMM72, Tractor Beam. "yep that's a content gap". They get products. + - After both, "no product" means exactly "Q3 test design". A census test pins that: every product-less design in + the shipped catalog is a scenario test design. --- @@ -698,3 +826,51 @@ Defaults Self took, which you may overrule: others; `Program.cs` is 1,477 lines). This is a subtraction pass of its own. - `ItemManager`'s clock seed (`ItemManager.cs:20`) makes lot quality vary per scenario launch. It is recorded, not fixed here. + +## Mining Cut 3: Soul (`codex/mining` `39cec96a..55ca6d3d`, 2026-10-01) + +**Verdict: hold for one fix batch.** It is queued, not dispatched, because the operator ordered a drain. + +No correctness bug was found. The suite passes 516/516 with the catalog `b698e224` and the settings `b2e346f5` that the commit pins. The shared `pins/data/Settings.asset` (`347752dd`) is scenarios' file, so any runner that mounts that path by default has been testing mining with the wrong settings. + +Findings: +- **F1 (medium, operator):** picking a rock in a big belt costs one scan of every rock the search circle reaches. `Zone.ChunksNear` (`Zone.cs:333`) and `VisibleChunksInReach` (`Entity.cs:378-385`) run on every reticle, next or previous key press. Measured cost: 63 ms at 30k rocks, 449 ms at 300k and 4.3 s at 3M. The per-tick cost is fine. +- **F2 (medium):** nothing tests that the shipped catalog has a rock kind. Taking either side of the catalog conflict unchanged ships dark belts silently. Add a test for "at least one rock kind with weight above 0". +- **F3:** the merge rule is corrected above. +- **F4 (medium):** nothing tests the ping half of `Sensor.Gain`, because the golden fixture saturates at the cap. Two mutants survive (`Sensor.cs:168`, `:189`). Soul's sweep fixture kills both and gives the same hash (`35DE0E26…`) before extraction, at extraction and at the tip. +- **F5:** `FieldKinds.Ensure`'s explicit save (`ZoneData.cs:162`) is needed on a clean store. Keep it and commit the probe. +- **F6/F7/F8 (low):** the `SetTarget` refusal is tested only on dark rocks (`Entity.cs:345`). The outer skip edge of `ChunksNear` is untested. Rock reach reads `Enabled`, and nothing tests it. +- **Deviation (operator):** launchers count toward rock reach (Q13), but under Q12 they can't mine. So after Cut 4 a player can pick a rock that no weapon can act on. +- **Plausible (operator visual check):** the target indicator uses `AsteroidVerticalOffset`, but the shader also subtracts the nebula surface height. + +Promises that held: +- The `Gain` extraction is bit-identical. +- `SetTarget` is the only writer. +- A dark target is dropped on the tick and on `Activate`. +- Docking, broken rocks and wormholes are handled. +- The catalog has 206 identical records, plus one kind and 18 weapons now Exact. +- Old saves get a kind on first load. + +The fix batch commits Soul's four probes (in the session scratchpad, `soul-mc3-run/probes/`) and the catalog-kind test. + +**Rulings (operator, 2026-10-01): "Fix the belt freeze; launchers shouldn't count toward reach".** +- F1: fix it before the merge. The cost of a key press must not grow with belt size. +- Rock reach counts only weapons that can mine; under Q12 launchers can't. This supersedes Hands' Q13 reading. +- The fix batch was dispatched with both rulings. + +**Mining fix batch, Hands (2026-10-01): `f88d1fc1`, `83d8371e` on `codex/mining`. 523/523; 9 mutants each killed by their own test.** +- Launchers: `Weapon.CanMine` (virtual, true by default; `LockWeapon` sets false) is the one predicate. Reach reads `CanMine && Active`. Cut 4's firing gate (`FireControl.cs:175`) must read the same predicate. +- Soul F2/F4/F5/F6/F7/F8 tests are committed. +- Belt freeze **not built; stopped at a fork.** + - Each rock has its own angular speed (`Distance` is a continuous float), so no band shares a phase. + - At 3M rocks, 633k are in reach and 2,240 are visible. + - Proposed: a derived per-belt index (bands of 256 by distance, sorted by turn, with the query arc widened by rate spread and at most 8 band re-sorts per query); a visibility upper bound that skips dark bands; best-first next/previous and reticle; the rules move from `ActionGameManager` to `Entity`. + - Work in progress (unbuilt) is in the session scratchpad: `hands-mc3fix-index-wip.patch`. +- Question: today's Previous with no target picks the second-farthest rock (off by one). Hands recommends fixing it. + +**Belt-freeze rulings (operator, 2026-10-01):** +- **Structure:** "Let's go for it. There's a voice in my head screaming that this is too much code and we should just reduce the whole belt to a single entity, but this stuff will be extra important for when we have EW and much more crowded levels. Just don't specialize the indexing too much towards asteroid belts, because we'll want a bunch of subsystems feeding targeting data. Think the spacebound microfauna from the slime mold experiment, pretty sure there's a campaign for that." + - The index is a general targeting index that many sources feed: belts, entities, later EW and microfauna. Belts are one provider, not the shape of the index. + - The slime-mold experiment is `Assets/Shaders/Compute/Slime/Slime.cs`. No campaign doc was found by grep on master docs or by voidbot; ask the operator before assuming one. +- **Previous off-by-one:** "Fix the off-by-one". With no current target, Previous picks the farthest rock. +- **Next step:** an Imagination pass (Opus) maps the general index. Inputs: the provider seam, motion models (orbiting rocks with per-rock rates, and moving entities), the brightness/visibility bound as a per-provider bound, and best-first queries. Hands' work in progress (`hands-mc3fix-index-wip.patch`) is input, not spec. Then Hands on Sonnet, then Soul. diff --git a/docs/ship-collection-authoring.md b/docs/ship-collection-authoring.md index b4e85f7a1..a92551ccd 100644 --- a/docs/ship-collection-authoring.md +++ b/docs/ship-collection-authoring.md @@ -1,6 +1,6 @@ # Ship collection authoring -Status: authoring contract for new ships. Longinus and Djinni predate this contract and keep their current prefabs. +Status: FBX-to-Unity-prefab contract for ships using the current catalog path. Longinus and Djinni predate this contract and keep their current prefabs. The parallel mod-owned `.cc` path is specified in [moddable-ship-authoring.md](moddable-ship-authoring.md). ## Objective and ownership diff --git a/tests/Aetheria.Shared.Tests/LoadoutTests.cs b/tests/Aetheria.Shared.Tests/LoadoutTests.cs index 03ea71364..0807dd234 100644 --- a/tests/Aetheria.Shared.Tests/LoadoutTests.cs +++ b/tests/Aetheria.Shared.Tests/LoadoutTests.cs @@ -122,6 +122,29 @@ public sealed class LoadoutTests : IDisposable Assert.True(!File.Exists(Player) || !SchemaNames(Player).Contains("aetheria.loadout")); } + // The shipped catalog never references a mod: a mod may be uninstalled, and a preset naming one would dangle. The + // refusal is at the only writer, so no caller (the editor command included) can get one into the file. + [Theory] + [InlineData("hull", "mod-hull:mod.skiff")] + [InlineData("slot", "mod-hull:mod.skiff")] + [InlineData("slot", "mod-ship:mod.skiff")] + public void APresetNamingAModDesignIsRefusedAndNothingIsWritten(string where, string key) + { + var mod = new CultRecordRef(new CultRecordKey(key)); + using var cache = Open(); + var loadout = HandBuilt(cache); + if (where == "hull") loadout.Hull = new CultRecordRef(new CultRecordKey(key)); + else loadout.Slots[1].Design = mod; + var before = Hash(Catalog); + + var error = Assert.Throws(() => Loadouts.Commit(Catalog, loadout, replace: false)); + + Assert.Contains("names mod designs", error.Message); + Assert.Contains(key, error.Message); + Assert.Equal(before, Hash(Catalog)); + Assert.True(Loadouts.Commit(Catalog, HandBuilt(cache), replace: false)); + } + // Recapturing a name refuses without replace and leaves the file untouched; with replace it replaces, never duplicates. [Fact] public void SameNameCaptureReplacesOnlyWhenAsked() diff --git a/tests/Aetheria.Shared.Tests/RunSaveTests.cs b/tests/Aetheria.Shared.Tests/RunSaveTests.cs index 86ca9a77e..9384b93ed 100644 --- a/tests/Aetheria.Shared.Tests/RunSaveTests.cs +++ b/tests/Aetheria.Shared.Tests/RunSaveTests.cs @@ -284,6 +284,220 @@ public sealed class RunSaveTests : IDisposable } } + // MQ4: Continue refuses a run that names a design the catalog no longer holds, naming the missing mod ships, and + // never edits the save. A design can be named by an item in a zone or only by a minted lot, so each is covered. + [Theory] + [InlineData(true, false)] + [InlineData(false, true)] + public void RunReferencingAMissingModRefusesContinue(bool itemNamesIt, bool lotNamesIt) + { + var modHull = new CultRecordKey("mod-hull:mod.skiff"); + var missing = new CultRecordRef(modHull); + CultRecordRef present; + using (var cache = AetheriaStores.Open(Catalog, catalogWritable: true)) + { + cache.UpsertAsync(typeof(HullData), new HullData { Name = "Skiff" }, modHull).GetAwaiter().GetResult(); + present = new CultRecordRef(cache.Upsert(new HullData { Name = "Wasp" }).Key); + cache.FlushAsync().Wait(); + } + var itemDesign = itemNamesIt ? missing : present; + var lotDesign = lotNamesIt ? missing : present; + + void CommitRun() + { + using var cache = Open(); + var lots = new ProvenanceLedger { NextLot = 3 }; + lots.Lots[1] = new Lot { Design = lotDesign, Origin = new Attributed() }; + // A lot minted before designs were recorded has none; an unset design is not a missing one. + lots.Lots[2] = new Lot { Origin = new Attributed() }; + var zone = new SavedZone + { + Name = "Zone 0", AdjacentZones = Array.Empty(), Factions = Array.Empty(), Owner = -1, + Contents = new ZonePack + { + Entities = new List + { + BarePack(hull: new EquippableItem { Data = itemDesign, Lot = 1 }), + BarePack(hull: new EquippableItem { Lot = 2 }) + } + } + }; + RunSave.Commit(cache, Game(cache), new[] { zone }, lots); + } + CommitRun(); + + // Installed: nothing is missing. + using (var cache = Open()) RunSave.RequireDesigns(cache, cache.GetGlobal()); + var before = File.ReadAllBytes(Run); + + using (var cache = AetheriaStores.Open(Catalog, catalogWritable: true)) + cache.Commit(batch => batch.Remove(modHull)); + using (var cache = Open()) + { + var refusal = Assert.Throws(() => RunSave.RequireDesigns(cache, cache.GetGlobal())); + Assert.Contains("missing mod ships: mod.skiff", refusal.Message); + Assert.DoesNotContain("other designs", refusal.Message); + } + Assert.Equal(before, File.ReadAllBytes(Run)); + } + + // --- RequireDesigns: what it walks, what it lists --------------------------------------------------------------- + + // Commits a run whose zones the caller builds, then returns RequireDesigns' refusal message, or null when it passes. + // `present` is a gear item ("Lamp", not a hull) the catalog holds; unit(design, lot) mints an item naming `design` + // whose lot names `lot`. + private string DesignsRefused(Func, Func, CultRecordRef, EquippableItem>, SavedZone[]> build) + { + CultRecordRef present; + using (var setup = AetheriaStores.Open(Catalog, catalogWritable: true)) + { + var existing = setup.GetAll().SingleOrDefault(gear => gear.Name == "Lamp"); + var lamp = existing != null ? setup.RefOf(existing) : + setup.Upsert(new GearData { Name = "Lamp", Hardpoint = HardpointType.Sensors, Shape = new Shape() }); + present = new CultRecordRef(lamp.Key); + setup.FlushAsync().Wait(); + } + using var cache = Open(); + var ledger = new ProvenanceLedger(); + EquippableItem Unit(CultRecordRef design, CultRecordRef lot) + { + var number = ledger.NextLot++; + ledger.Lots[number] = new Lot { Design = lot, Origin = new Attributed() }; + return new EquippableItem { Data = design, Lot = number }; + } + ledger.NextLot = 1; + RunSave.Commit(cache, Game(cache), build(present, Unit), ledger); + try { RunSave.RequireDesigns(cache, cache.GetGlobal()); return null; } + catch (InvalidOperationException refusal) { return refusal.Message; } + } + + private static CultRecordRef Key(string key) => new CultRecordRef(new CultRecordKey(key)); + + private static SavedZone ZoneOf(params EntityPack[] packs) => new SavedZone + { + Name = "Zone", AdjacentZones = Array.Empty(), Factions = Array.Empty(), Owner = -1, + Contents = new ZonePack { Entities = packs.ToList() } + }; + + // Whatever the slot, a design missing from the catalog is found, and a design the catalog holds (a gear item, not + // only a hull) is not: the gate walks every unit an entity carries, recursively, and resolves any item design. + [Theory] + [InlineData("hull")] + [InlineData("equipment")] + [InlineData("cargo bay")] + [InlineData("docking bay")] + [InlineData("cargo contents")] + [InlineData("docking contents")] + [InlineData("child hull")] + [InlineData("child equipment")] + public void RequireDesignsFindsAMissingDesignInEverySlotOfAnEntity(string slot) + { + string Refusal(bool missing) => DesignsRefused((present, unit) => + { + EquippableItem Slot(string where) => unit(missing && where == slot ? Key("hull:gone") : present, present); + var child = BarePack(Slot("child hull")); + child.Equipment = new[] { (new int2(0, 0), Slot("child equipment")) }; + var pack = BarePack(Slot("hull"), new EntityPack[] { child }); + pack.Equipment = new[] { (new int2(0, 0), Slot("equipment")) }; + pack.CargoBays = new[] { (new int2(0, 0), Slot("cargo bay")) }; + pack.DockingBays = new[] { (new int2(0, 0), Slot("docking bay")) }; + pack.CargoContents = new[] { new (int2, ItemInstance)[] { (new int2(0, 0), Slot("cargo contents")) } }; + pack.DockingBayContents = new[] { new (int2, ItemInstance)[] { (new int2(0, 0), Slot("docking contents")) } }; + return new[] { ZoneOf(pack) }; + }); + + Assert.Null(Refusal(missing: false)); + Assert.Contains("missing other designs: hull:gone. Reinstall", Refusal(missing: true)); + } + + // Every zone and every lot is read, not the first: each names its own missing design. + [Fact] + public void RequireDesignsReadsEveryZoneAndEveryLot() + { + var refusal = DesignsRefused((present, unit) => new[] + { + ZoneOf(BarePack(unit(Key("hull:zone-a"), present))), + ZoneOf(BarePack(unit(present, present))), + ZoneOf(BarePack(unit(Key("hull:zone-b"), present)), BarePack(unit(present, Key("hull:lot-a")))), + ZoneOf(BarePack(unit(present, present)), BarePack(unit(present, Key("hull:lot-b")))) + }); + + Assert.Contains("missing other designs: hull:lot-a, hull:lot-b, hull:zone-a, hull:zone-b. Reinstall", refusal); + } + + // Each missing design is listed once however many units name it, ordinally, mod ships apart from the rest. + [Fact] + public void RequireDesignsListsEachMissingDesignOnceInStableOrder() + { + var refusal = DesignsRefused((present, unit) => new[] + { + ZoneOf(BarePack(unit(Key("hull:b"), Key("mod-hull:z"))), BarePack(unit(Key("mod-hull:z"), Key("hull:b")))), + ZoneOf(BarePack(unit(Key("hull:B"), Key("mod-hull:m"))), BarePack(unit(Key("hull:a"), Key("hull:b")))) + }); + + Assert.Equal("This run names designs the catalog no longer holds; missing mod ships: m, z; " + + "missing other designs: hull:B, hull:a, hull:b. Reinstall them, or start a new game.", refusal); + } + + // A save can hold a null where the gate needs a value: refused with a message that says where, never a + // NullReferenceException. The records are written straight to the run store, since a save never writes them itself. + [Theory] + [InlineData("item", "an item in savedzone-0 is null")] + [InlineData("entity", "an entity is null")] + [InlineData("zone", "zone savedzone-1 has no record")] + [InlineData("lot", "lot 2 is null")] + [InlineData("lots", "the lot ledger has no lots")] + public void RequireDesignsRefusesANullWhereTheWalkNeedsAValue(string kind, string where) + { + using var cache = Open(); + var pack = BarePack(new EquippableItem { Data = Key("hull:none"), Lot = 1 }); + if (kind == "item") pack.Equipment = new[] { (new int2(0, 0), (EquippableItem) null) }; + if (kind == "entity") pack.Children = new EntityPack[] { null }; + var ledger = new ProvenanceLedger { NextLot = 3, Lots = { [1] = new Lot { Origin = new Attributed() } } }; + if (kind == "lot") ledger.Lots[2] = null; + if (kind == "lots") ledger.Lots = null; + var game = Game(cache); + game.Zones = new[] { new CultRecordRef(new CultRecordKey("savedzone-0")), new CultRecordRef(new CultRecordKey("savedzone-1")) }; + cache.Commit(batch => + { + batch.Upsert(typeof(SavedZone), ZoneOf(pack), new CultRecordKey("savedzone-0")); + if (kind != "zone") batch.Upsert(typeof(SavedZone), ZoneOf(), new CultRecordKey("savedzone-1")); + batch.Upsert(game); + batch.Upsert(ledger); + }); + + var refusal = Assert.Throws(() => RunSave.RequireDesigns(cache, cache.GetGlobal())); + Assert.Contains("save is malformed: " + where, refusal.Message); + } + + // The same run with nothing null is not malformed: null contents (a zone never visited) and unset designs are legitimate. + [Fact] + public void RequireDesignsAcceptsAZoneNeverVisitedAndAnUnsetDesign() + { + Assert.Null(DesignsRefused((present, unit) => new[] + { + new SavedZone { Name = "Never", AdjacentZones = Array.Empty(), Factions = Array.Empty(), Owner = -1 }, + ZoneOf(BarePack(unit(default, default))) + })); + } + + [Fact] + public void ARunNamingAMissingShippedDesignIsRefusedToo() + { + var gone = new CultRecordRef(new CultRecordKey("hull:gone")); + using var cache = Open(); + var zone = new SavedZone + { + Name = "Zone 0", AdjacentZones = Array.Empty(), Factions = Array.Empty(), Owner = -1, + Contents = new ZonePack { Entities = new List { BarePack(hull: new EquippableItem { Data = gone, Lot = 1 }) } } + }; + RunSave.Commit(cache, Game(cache), new[] { zone }, new ProvenanceLedger { NextLot = 2, Lots = { [1] = new Lot { Origin = new Attributed() } } }); + + var refusal = Assert.Throws(() => RunSave.RequireDesigns(cache, cache.GetGlobal())); + Assert.Contains("missing other designs: hull:gone", refusal.Message); + Assert.DoesNotContain("mod ships", refusal.Message); + } + // A minimal, valid EntityPack with every collection field non-null, for tests that build packs directly rather // than through EntitySerializer.Pack. private static ShipPack BarePack(EquippableItem hull, EntityPack[] children = null, diff --git a/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs b/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs new file mode 100644 index 000000000..2d6680933 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs @@ -0,0 +1,346 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using GameCult.Caching.MessagePack; +using MessagePack; +using CultMath; +using GameCult.Caching; +using Xunit; + +public sealed class ShipAuthoringTests +{ + [Fact] + public async Task StandaloneShipRoundTripsWithoutTouchingTheCatalog() + { + var root = Path.Combine(Path.GetTempPath(), "aetheria-ship-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + var path = Path.Combine(root, "skiff.cc"); + try + { + var ship = Fixture(); + ship.Validate(); + using (var cache = ShipAuthoringStore.Open(path, writable: true)) + { + ShipAuthoringStore.Write(cache, ship.Hull, ship.Visual); + await cache.FlushAsync(); + } + var (hull, visual) = ShipAuthoringStore.Read(path); + Assert.Equal("mod.skiff", visual.Id); + Assert.Equal("Skiff", hull.Name); + Assert.True(hull.Shape.Cells[1, 0]); + Assert.Equal("thruster.port", hull.Hardpoints[0].Transform); + Assert.Equal(ShipModCatalog.AuthoringKey("mod.skiff"), hull.Visual.Key); + Assert.Equal("skiff.glb", visual.ModelAsset); + Assert.Equal(2, visual.SchematicLines[0].Points.Length / 3); + } + finally { Directory.Delete(root, true); } + } + + [Fact] + public void InvalidSchematicOrDanglingMountCannotBePublished() + { + var ship = Fixture(); + ship.Hull.Shape.Cells[1, 0] = false; + Assert.Contains("outside the hull schematic", Assert.Throws(ship.Validate).Message); + + ship = Fixture(); + ship.Visual.Anchors.RemoveAt(ship.Visual.Anchors.Count - 1); + Assert.Contains("has no model anchor", Assert.Throws(ship.Validate).Message); + + ship = Fixture(); + ship.Visual.SchematicLines[0].Points[0] = float.NaN; + Assert.Contains("finite XYZ", Assert.Throws(ship.Validate).Message); + + ship = Fixture(); + ship.Hull.Hardpoints.Add(new HardpointData + { + Type = HardpointType.Thruster, + Position = new int2(1, 0), + Shape = new Shape(), + Transform = "thruster.starboard" + }); + ship.Visual.Anchors.Add(new ShipAnchor { Id = "thruster.starboard", Role = "thruster-emitter", ModelNodeId = "thruster-starboard" }); + Assert.Contains("overlaps another hardpoint", Assert.Throws(ship.Validate).Message); + } + + // The hull owns hull semantics and the visual owns the model package, so the one joint check refuses a hull mount the + // visual has no anchor for, and a visual anchor parented to a mount the hull does not have. + [Fact] + public void HardpointsMustResolveToTheVisualsAnchors() + { + var ship = Fixture(); + ship.Hull.Hardpoints[0].Transform = "thruster.renamed"; + Assert.Contains("thruster.renamed has no model anchor", Assert.Throws(ship.Validate).Message); + + ship = Fixture(); + ship.Visual.Anchors.Add(new ShipAnchor { Id = "muzzle", Role = "weapon-muzzle", ModelNodeId = "muzzle", ParentId = "thruster.gone" }); + Assert.Contains("unknown hardpoint parent thruster.gone", Assert.Throws(ship.Validate).Message); + + Fixture().Validate(); + } + + [Fact] + public void HullNamesExactlyOneVisual() + { + var ship = Fixture(); + ship.Hull.Prefab = "Djinni"; + Assert.Contains("names both a Unity prefab and a visual record", Assert.Throws(ship.Validate).Message); + + // A whitespace-only prefab is unset. + ship = Fixture(); + ship.Hull.Prefab = " \t"; + ship.Validate(); + + ship = Fixture(); + ship.Hull.Visual = default; + Assert.Contains("the hull must name its visual record mod-ship:mod.skiff", Assert.Throws(ship.Validate).Message); + + ship = Fixture(); + ship.Hull.Visual = new CultRecordRef(ShipModCatalog.AuthoringKey("mod.other")); + Assert.Contains("the hull must name its visual record mod-ship:mod.skiff", Assert.Throws(ship.Validate).Message); + + // The key is compared exactly: a differently-cased key is another record. + ship = Fixture(); + ship.Hull.Visual = new CultRecordRef(new CultRecordKey("MOD-SHIP:mod.skiff")); + Assert.Contains("the hull must name its visual record mod-ship:mod.skiff", Assert.Throws(ship.Validate).Message); + + Fixture().Validate(); + } + + // A hull with both a prefab and a visual is refused wherever hulls are validated or composed. + // ShipModCatalogTests.ComposeRefusesAShippedHullThatNamesTwoBodies covers Compose. + [Fact] + public void RequireOneBodyRefusesBothAndAcceptsEitherAlone() + { + var hull = Fixture().Hull; + ShipAuthoringStore.RequireOneBody(hull, "skiff"); + hull.Prefab = "Djinni"; + Assert.Contains("skiff: a hull names one body", Assert.Throws(() => ShipAuthoringStore.RequireOneBody(hull, "skiff")).Message); + hull.Visual = default; + ShipAuthoringStore.RequireOneBody(hull, "skiff"); + } + + // The ship authoring record held the whole hull at key 1 before S1. + [Fact] + public async Task LoadRefusesAShipAuthoringRecordThatStillCarriesTheRetiredEmbeddedHull() + { + using var directory = new TempDirectory(); + var path = Path.Combine(directory.Path, "legacy.cc"); + using (var cache = ShipAuthoringStore.Open(path, writable: true)) + { + ShipAuthoringStore.Write(cache, Fixture().Hull, Fixture().Visual); + await cache.FlushAsync(); + } + RewritePayload(path, "aetheria.ship_authoring", slots => { slots[1] = new object[] { "Skiff" }; }); + foreach (var load in new Action[] { () => ShipAuthoringStore.Load(path), () => ShipAuthoringStore.Read(path) }) + { + var message = Assert.Throws(load).Message; + Assert.Contains("legacy embedded hull at retired key 1", message); + Assert.Contains(path, message); + } + + // An old file has no separate hull record at all; it is named for what it is, not for a missing hull. + var oldShape = Path.Combine(directory.Path, "old.cc"); + using (var cache = ShipAuthoringStore.Open(oldShape, writable: true)) + { + cache.UpsertAsync(typeof(ShipAuthoring), Fixture().Visual, ShipModCatalog.AuthoringKey("mod.skiff")).GetAwaiter().GetResult(); + await cache.FlushAsync(); + } + RewritePayload(oldShape, "aetheria.ship_authoring", slots => { slots[1] = new object[] { "Skiff" }; }); + var oldMessage = Assert.Throws(() => ShipAuthoringStore.Load(oldShape)).Message; + Assert.Contains("legacy embedded hull", oldMessage); + Assert.DoesNotContain("exactly one hull record", oldMessage); + + // A nil in the retired slot is the shape every current file has. + RewritePayload(path, "aetheria.ship_authoring", slots => { slots[1] = null; }); + ShipAuthoringStore.Load(path); + } + + // The layout editor's Python once accepted any msgpack value in a cell; C# then failed with a bare serializer exception. + [Fact] + public async Task LoadNamesTheFileWhoseRecordDoesNotDecode() + { + using var directory = new TempDirectory(); + var path = Path.Combine(directory.Path, "cells.cc"); + using (var cache = ShipAuthoringStore.Open(path, writable: true)) + { + ShipAuthoringStore.Write(cache, Fixture().Hull, Fixture().Visual); + await cache.FlushAsync(); + } + // ItemData.Shape is key 5: [[width, height, cells]]. + RewritePayload(path, "aetheria.hulldata", slots => ((object[])((object[])slots[5])[0])[2] = new object[] { 5, false, true, false }); + var error = Assert.Throws(() => ShipAuthoringStore.Load(path)); + Assert.Contains(path, error.Message); + Assert.IsAssignableFrom(error.InnerException); + } + + // Decodes one record's payload of the named schema to its slot array, lets the edit change it, and stores it again. + private static void RewritePayload(string path, string schemaName, Action edit) + { + var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(path)); + var schemaId = snapshot.SchemaCatalog.Single(entry => entry.SchemaName == schemaName).SchemaId; + var record = snapshot.Records.Single(candidate => candidate.SchemaId == schemaId); + var slots = MessagePackSerializer.Deserialize(record.Payload); + edit(slots); + record.Payload = MessagePackSerializer.Serialize(slots); + File.WriteAllBytes(path, CultDocumentMessagePackSerialization.SerializeSnapshot(snapshot)); + } + + [Fact] + public async Task LoadRefusesAFileWhoseRecordsAreNotOneHullAndOneVisualAtTheirKeys() + { + using var directory = new TempDirectory(); + async Task Write(string name, Action fill) + { + var path = Path.Combine(directory.Path, name); + using var cache = ShipAuthoringStore.Open(path, writable: true); + fill(cache); + await cache.FlushAsync(); + return path; + } + void Hull(CultCache cache, string key) => + cache.UpsertAsync(typeof(HullData), Fixture().Hull, new CultRecordKey(key)).GetAwaiter().GetResult(); + void Visual(CultCache cache, string key, string id = "mod.skiff") => + cache.UpsertAsync(typeof(ShipAuthoring), Fixture().WithId(id).Visual, new CultRecordKey(key)).GetAwaiter().GetResult(); + + var twoShips = await Write("two.cc", cache => + { + ShipAuthoringStore.Write(cache, Fixture().Hull, Fixture().Visual); + Visual(cache, "mod-ship:mod.other", "mod.other"); + }); + Assert.Contains("found 2", Assert.Throws(() => ShipAuthoringStore.Load(twoShips)).Message); + + var noHull = await Write("nohull.cc", cache => Visual(cache, "mod-ship:mod.skiff")); + Assert.Contains("exactly one hull record, found 0", Assert.Throws(() => ShipAuthoringStore.Load(noHull)).Message); + + var twoHulls = await Write("twohulls.cc", cache => + { + ShipAuthoringStore.Write(cache, Fixture().Hull, Fixture().Visual); + Hull(cache, "mod-hull:mod.other"); + }); + Assert.Contains("exactly one hull record, found 2", Assert.Throws(() => ShipAuthoringStore.Load(twoHulls)).Message); + + var wrongHullKey = await Write("hullkey.cc", cache => { Hull(cache, "hull:skiff"); Visual(cache, "mod-ship:mod.skiff"); }); + Assert.Contains("records must be stored under mod-hull:mod.skiff and mod-ship:mod.skiff", + Assert.Throws(() => ShipAuthoringStore.Load(wrongHullKey)).Message); + + var wrongVisualKey = await Write("visualkey.cc", cache => { Hull(cache, "mod-hull:mod.skiff"); Visual(cache, "ship:skiff"); }); + Assert.Contains("records must be stored under", Assert.Throws(() => ShipAuthoringStore.Load(wrongVisualKey)).Message); + } + + // A mount's anchor plays the mount, so a structural anchor (the hull collider, the shield, a muzzle...) is never one. + // Interim ruling until an `equipment` role exists: a mount that is not a thruster or radiator is an articulation anchor. + [Theory] + [InlineData("map-icon", "map")] + [InlineData("hull-collider", "collider")] + [InlineData("shield", "shield")] + [InlineData("tractor", "tractor")] + [InlineData("weapon-muzzle", "muzzle")] + [InlineData("thruster-emitter", "emitter")] + [InlineData("radiator-mesh", "mesh")] + public void AStructuralAnchorCannotBeAnEquipmentMount(string role, string anchorId) + { + var ship = Fixture(); + // The extra anchors exist so the role-count and parent checks pass; the Tool hardpoint then claims the anchor. + ship.Visual.Anchors.Add(new ShipAnchor { Id = "muzzle", Role = "weapon-muzzle", ModelNodeId = "muzzle", ParentId = "thruster.port" }); + ship.Visual.Anchors.Add(new ShipAnchor { Id = "emitter", Role = "thruster-emitter", ModelNodeId = "emitter" }); + ship.Visual.Anchors.Add(new ShipAnchor { Id = "mesh", Role = "radiator-mesh", ModelNodeId = "mesh" }); + ship.Hull.Hardpoints.Add(new HardpointData { Type = HardpointType.Tool, Position = new int2(0, 0), Shape = new Shape(), Transform = anchorId }); + + Assert.Contains($"Tool hardpoint {anchorId} needs a articulation anchor of that id", Assert.Throws(ship.Validate).Message); + ship = Fixture(); + ship.Visual.Anchors.Add(new ShipAnchor { Id = "tool", Role = "articulation", ModelNodeId = "tool" }); + ship.Hull.Hardpoints.Add(new HardpointData { Type = HardpointType.Tool, Position = new int2(0, 0), Shape = new Shape(), Transform = "tool" }); + ship.Validate(); + } + + [Fact] + public void EveryHardpointTypeHasOneAnchorRoleForItsMount() + { + foreach (HardpointType type in Enum.GetValues(typeof(HardpointType))) + { + var wanted = type == HardpointType.Thruster ? "thruster-emitter" : type == HardpointType.Radiator ? "radiator-mesh" : "articulation"; + foreach (var role in new[] { "articulation", "thruster-emitter", "radiator-mesh" }) + { + var ship = Fixture(); + ship.Hull.Hardpoints.Clear(); + ship.Visual.Anchors.RemoveAll(anchor => anchor.Id == "thruster.port"); + ship.Hull.Hardpoints.Add(new HardpointData { Type = type, Position = new int2(0, 0), Shape = new Shape(), Transform = "mount" }); + ship.Visual.Anchors.Add(new ShipAnchor { Id = "mount", Role = role, ModelNodeId = "mount" }); + if (role == wanted) ship.Validate(); + else Assert.Contains($"{type} hardpoint mount needs a {wanted} anchor of that id", Assert.Throws(ship.Validate).Message); + } + } + } + + internal static ShipParts Fixture() + { + var shape = new Shape(2, 2); + shape.Cells[0, 0] = true; + shape.Cells[1, 0] = true; + return new ShipParts + { + Hull = new HullData + { + Name = "Skiff", + Shape = shape, + Visual = new CultRecordRef(ShipModCatalog.AuthoringKey("mod.skiff")), + Hardpoints = new List + { + new HardpointData + { + Type = HardpointType.Thruster, + Position = new int2(1, 0), + Shape = new Shape(), + Transform = "thruster.port" + } + } + }, + Visual = new ShipAuthoring + { + Id = "mod.skiff", + ModelAsset = "skiff.glb", + Anchors = new List + { + new ShipAnchor { Id = "map", Role = "map-icon", ModelNodeId = "map" }, + new ShipAnchor { Id = "collider", Role = "hull-collider", ModelNodeId = "collider" }, + new ShipAnchor { Id = "shield", Role = "shield", ModelNodeId = "shield" }, + new ShipAnchor { Id = "tractor", Role = "tractor", ModelNodeId = "tractor" }, + new ShipAnchor { Id = "thruster.port", Role = "thruster-emitter", ModelNodeId = "thruster-port" } + }, + SchematicLines = new List + { + new ShipPolyline + { + Layer = "Hull", + Material = "White", + Points = new[] { 0f, 0f, 0f, 1f, 0f, 0f }, + Radii = new[] { .01f, .01f }, + Opacities = new[] { 1f, 1f }, + Color = new[] { 1f, 1f, 1f, 1f } + } + } + } + }; + } +} + +// One ship's two records: the hull and the visual it names. +internal sealed class ShipParts +{ + public HullData Hull; + public ShipAuthoring Visual; + + public void Deconstruct(out HullData hull, out ShipAuthoring visual) => (hull, visual) = (Hull, Visual); + + public ShipParts WithId(string id) + { + Visual.Id = id; + Hull.Visual = new CultRecordRef(ShipModCatalog.AuthoringKey(id)); + return this; + } + + public void Validate() => ShipAuthoringStore.Validate(Hull, Visual); +} diff --git a/tests/Aetheria.Shared.Tests/ShipFixture.cs b/tests/Aetheria.Shared.Tests/ShipFixture.cs new file mode 100644 index 000000000..eb4f5c01e --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ShipFixture.cs @@ -0,0 +1,87 @@ +using System; +using System.IO; +using System.Linq; +using System.Text; +using CultMath; + +// Writes the mod package the tests, the Python round-trip check and the Unity smokes (ShipModPreview.Smoke and +// ShipModPlaySmoke) share. It is generated from ShipAuthoringTests.Fixture() so no opaque bytes are committed. +internal static class ShipFixture +{ + public static readonly string[] Nodes = { "map", "collider", "shield", "tractor", "thruster-port", "gun", "gun-muzzle" }; + + // The nodes that carry the fixture mesh: the anchors the assembler reads a renderer or a collider mesh from. + public static readonly string[] MeshNodes = { "map", "collider", "thruster-port" }; + + // One tetrahedron, non-indexed (12 vertices), so a convex MeshCollider can cook it. Written by the generator. + private static readonly float[] Tetrahedron = + { + 0, 0, 0, 0, 1, 0, 1, 0, 0, + 0, 0, 0, 1, 0, 0, 0, 0, 1, + 0, 0, 0, 0, 0, 1, 0, 1, 0, + 1, 0, 0, 0, 1, 0, 0, 0, 1 + }; + + public static byte[] MeshBytes() => Tetrahedron.SelectMany(BitConverter.GetBytes).ToArray(); + + // The GLB carries a glTF scene naming every node: glTFast instantiates a scene, and a scene-less file has none. + // Nodes in MeshNodes get the shared tetrahedron mesh, whose vertices live in the BIN chunk (MeshBytes). + public static string GlbJson(string[] nodes) + { + var length = MeshBytes().Length; + var mesh = nodes.Any(MeshNodes.Contains) + ? @",""meshes"":[{""primitives"":[{""attributes"":{""POSITION"":0}}]}]," + + @"""accessors"":[{""bufferView"":0,""componentType"":5126,""count"":12,""type"":""VEC3"",""min"":[0,0,0],""max"":[1,1,1]}]," + + $@"""bufferViews"":[{{""buffer"":0,""byteLength"":{length}}}],""buffers"":[{{""byteLength"":{length}}}]" + : ""; + return @"{""asset"":{""version"":""2.0""},""scene"":0,""scenes"":[{""nodes"":[" + string.Join(",", nodes.Select((_, index) => index)) + @"]}]" + mesh + @",""nodes"":[" + + string.Join(",", nodes.Select(node => + $@"{{""name"":""{node}""{(MeshNodes.Contains(node) ? @",""mesh"":0" : "")},""extras"":{{""aetheria.id"":""{node}""}}}}")) + "]}"; + } + + public static byte[] Glb(string json, byte[] bin = null) + { + var body = Encoding.UTF8.GetBytes(json); + var padded = new byte[(body.Length + 3) / 4 * 4]; + Array.Fill(padded, (byte)' '); + body.CopyTo(padded, 0); + bin ??= Array.Empty(); + var binPadded = new byte[(bin.Length + 3) / 4 * 4]; + bin.CopyTo(binPadded, 0); + var bytes = new byte[28 + padded.Length + binPadded.Length]; + BitConverter.GetBytes(0x46546C67u).CopyTo(bytes, 0); + BitConverter.GetBytes(2u).CopyTo(bytes, 4); + BitConverter.GetBytes((uint)bytes.Length).CopyTo(bytes, 8); + BitConverter.GetBytes((uint)padded.Length).CopyTo(bytes, 12); + BitConverter.GetBytes(0x4E4F534Au).CopyTo(bytes, 16); + padded.CopyTo(bytes, 20); + BitConverter.GetBytes((uint)binPadded.Length).CopyTo(bytes, 20 + padded.Length); + BitConverter.GetBytes(0x004E4942u).CopyTo(bytes, 24 + padded.Length); + binPadded.CopyTo(bytes, 28 + padded.Length); + return bytes; + } + + // //ship.cc plus the GLB at the record's ModelAsset path. + public static string WritePackage(string modsRoot, string id, string hullName = "Skiff", string[] nodes = null, + string modelAsset = "skiff.glb", Action tweak = null) + { + var ship = ShipAuthoringTests.Fixture(); + // A playable rig: the fixture thruster plus one energy weapon mount on the hull's other cell, with its muzzle. + ship.Hull.Hardpoints.Add(new HardpointData { Type = HardpointType.Energy, Position = new int2(0, 0), Shape = new Shape(), Transform = "gun" }); + ship.Visual.Anchors.Add(new ShipAnchor { Id = "gun", Role = "articulation", ModelNodeId = "gun" }); + ship.Visual.Anchors.Add(new ShipAnchor { Id = "gun.muzzle", Role = "weapon-muzzle", ModelNodeId = "gun-muzzle", ParentId = "gun" }); + tweak?.Invoke(ship); + ship.WithId(id); + ship.Hull.Name = hullName; + ship.Visual.ModelAsset = modelAsset; + var directory = Path.Combine(modsRoot, id); + Directory.CreateDirectory(directory); + using (var cache = ShipAuthoringStore.Open(Path.Combine(directory, "ship.cc"), writable: true)) + { + ShipAuthoringStore.Write(cache, ship.Hull, ship.Visual); + cache.FlushAsync().Wait(); + } + File.WriteAllBytes(Path.Combine(directory, modelAsset), Glb(GlbJson(nodes ?? Nodes), MeshBytes())); + return directory; + } +} diff --git a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs new file mode 100644 index 000000000..82cca60f5 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs @@ -0,0 +1,551 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using GameCult.Caching; +using Newtonsoft.Json.Linq; +using Xunit; + +// Compose, ReadPackage and ReadNodeIds: the derived catalog a game would open, and the GLB node ids its anchors bind to. +public sealed class ShipModCatalogTests : IDisposable +{ + private readonly TempDirectory _directory = new TempDirectory(); + private string Shipped => Path.Combine(_directory.Path, "Aetheria.cc"); + private string Derived => Path.Combine(_directory.Path, "Derived", "Aetheria.modded.cc"); + private string Mods => Path.Combine(_directory.Path, "Mods"); + private static readonly string[] FixtureNodes = ShipFixture.Nodes; + + public ShipModCatalogTests() + { + Directory.CreateDirectory(Mods); + using var cache = AetheriaStores.Open(Shipped, catalogWritable: true); + // The test assembly registers TestCatalogGlobal (AetheriaStoresTests), so any populated catalog must hold one. + cache.Upsert(new TestCatalogGlobal { Name = "Temperament" }); + cache.Upsert(new HullData { Name = "Wasp", Shape = ShipAuthoringTests.Fixture().Hull.Shape }); + cache.Upsert(new GearData { Name = "Widget" }); + cache.FlushAsync().Wait(); + } + + public void Dispose() => _directory.Dispose(); + + [Fact] + public void ComposeDerivesACatalogAndLeavesTheShippedOneUntouched() + { + WritePackage("mod.skiff"); + Directory.CreateDirectory(Path.Combine(Mods, "notes")); + var shippedBefore = Hash(Shipped); + + Assert.Equal(1, ShipModCatalog.Compose(Shipped, Derived, Mods).Included.Length); + + Assert.Equal(shippedBefore, Hash(Shipped)); + using var cache = AetheriaStores.Open(Derived); + Assert.Contains("Wasp", cache.GetAll().Select(hull => hull.Name)); + Assert.Contains("Widget", cache.GetAll().Select(gear => gear.Name)); + var records = cache.AllStoredDocuments.ToDictionary(record => record.Key.Value, record => record.Document); + Assert.Equal("Skiff", Assert.IsType(records[ShipModCatalog.HullKey("mod.skiff").Value]).Name); + Assert.Equal("mod.skiff", Assert.IsType(records[ShipModCatalog.AuthoringKey("mod.skiff").Value]).Id); + AssertOnlyTheDerivedFile(); + } + + // Correction 2 of the S0 map: the derived catalog held each mod hull twice, once as a HullData and once inside the + // ship's authoring record. The hull is now one record, and the visual holds no hull. + [Fact] + public void ComposedCatalogHoldsOneHullPerModShip() + { + WritePackage("mod.skiff", hullName: "Skiffhull"); + ShipModCatalog.Compose(Shipped, Derived, Mods); + + using var cache = AetheriaStores.Open(Derived); + Assert.Equal(1, cache.GetAll().Count(hull => hull.Name == "Skiffhull")); + // The hull's name is stored exactly once in the derived file, so no second copy of the hull hides in another record. + Assert.Equal(1, Occurrences(File.ReadAllBytes(Derived), Encoding.UTF8.GetBytes("Skiffhull"))); + var visual = cache.GetAll().Single(); + Assert.Equal("mod.skiff", visual.Id); + } + + [Fact] + public void ComposeRefusesAShippedHullThatNamesTwoBodies() + { + WritePackage("mod.skiff"); + using (var cache = AetheriaStores.Open(Shipped, catalogWritable: true)) + { + cache.Upsert(new HullData + { + Name = "Chimera", + Shape = ShipAuthoringTests.Fixture().Hull.Shape, + Prefab = "Djinni", + Visual = new CultRecordRef(ShipModCatalog.AuthoringKey("mod.skiff")) + }); + cache.FlushAsync().Wait(); + } + Assert.Contains("Chimera: a hull names one body", + Assert.Throws(() => ShipModCatalog.Compose(Shipped, Derived, Mods)).Message); + Assert.False(File.Exists(Derived)); + } + + [Fact] + public void ComposeCopiesTheModStoresRecordsUnchangedAndTheHullNamesItsVisualByRef() + { + WritePackage("mod.skiff"); + var (modHull, modVisual) = ShipAuthoringStore.Read(Path.Combine(Mods, "mod.skiff", "ship.cc")); + ShipModCatalog.Compose(Shipped, Derived, Mods); + + using var cache = AetheriaStores.Open(Derived); + var hull = cache.Get(ShipModCatalog.HullKey("mod.skiff")); + var visual = cache.Get(ShipModCatalog.AuthoringKey("mod.skiff")); + Assert.Same(visual, cache.Get(hull.Visual)); + var options = GameCult.Caching.MessagePack.CultDocumentMessagePackSerialization.OptionsFor(typeof(ShipAuthoring).Assembly); + Assert.Equal(MessagePack.MessagePackSerializer.Serialize(modHull, options), MessagePack.MessagePackSerializer.Serialize(hull, options)); + Assert.Equal(MessagePack.MessagePackSerializer.Serialize(modVisual, options), MessagePack.MessagePackSerializer.Serialize(visual, options)); + } + + // The package the Unity smoke (ShipModPreview.Smoke) loads. Set AETHERIA_SHIP_FIXTURE_DIR to have this run leave it + // there: `-shipModPath $AETHERIA_SHIP_FIXTURE_DIR/mod.skiff/ship.cc`. + [Fact] + public void TheFixturePackageIsCompleteAndItsGlbCarriesAScene() + { + var directory = ShipFixture.WritePackage(Mods, "mod.skiff"); + + var package = ShipModCatalog.ReadPackage(Path.Combine(directory, "ship.cc")); + Assert.Equal(ShipFixture.Nodes.Length, package.NodeIndices.Count); + var glb = File.ReadAllBytes(package.ModelPath); + var json = JObject.Parse(Encoding.UTF8.GetString(glb, 20, (int)BitConverter.ToUInt32(glb, 12))); + Assert.Equal(0, (int)json["scene"]); + Assert.Equal(Enumerable.Range(0, ShipFixture.Nodes.Length), json["scenes"][0]["nodes"].Select(node => (int)node)); + Assert.Equal(1, ShipModCatalog.Compose(Shipped, Derived, Mods).Included.Length); + + var export = Environment.GetEnvironmentVariable("AETHERIA_SHIP_FIXTURE_DIR"); + if (string.IsNullOrEmpty(export)) return; + var target = Path.Combine(export, "mod.skiff"); + Directory.CreateDirectory(target); + foreach (var name in new[] { "ship.cc", "skiff.glb" }) File.Copy(Path.Combine(directory, name), Path.Combine(target, name), true); + } + + [Fact] + public void TheFixtureGlbCarriesARealMeshOnEveryAnchorTheAssemblerReadsOneFrom() + { + var package = ShipModCatalog.ReadPackage(Path.Combine(ShipFixture.WritePackage(Mods, "mod.skiff"), "ship.cc")); + var glb = File.ReadAllBytes(package.ModelPath); + var jsonLength = (int)BitConverter.ToUInt32(glb, 12); + var json = JObject.Parse(Encoding.UTF8.GetString(glb, 20, jsonLength)); + var binLength = (int)BitConverter.ToUInt32(glb, 20 + jsonLength); + Assert.Equal(0x004E4942u, BitConverter.ToUInt32(glb, 24 + jsonLength)); + Assert.Equal(glb.Length, 28 + jsonLength + binLength); + Assert.Equal((int)json["buffers"][0]["byteLength"], ShipFixture.MeshBytes().Length); + Assert.True(binLength >= ShipFixture.MeshBytes().Length); + + var roles = new[] { "map-icon", "hull-collider", "thruster-emitter", "radiator-mesh" }; + var needed = package.Visual.Anchors.Where(anchor => roles.Contains(anchor.Role)).ToArray(); + Assert.Contains(needed, anchor => anchor.Role == "thruster-emitter"); + foreach (var anchor in needed) + { + var node = json["nodes"][(int)package.NodeIndices[anchor.ModelNodeId]]; + var mesh = json["meshes"][(int)node["mesh"]]; + var accessor = json["accessors"][(int)mesh["primitives"][0]["attributes"]["POSITION"]]; + Assert.True((int)accessor["count"] >= 4, anchor.Id); + } + Assert.Contains(package.Visual.Anchors, anchor => anchor.Role == "weapon-muzzle" && anchor.ParentId == "gun"); + Assert.Contains(package.Hull.Hardpoints, hardpoint => hardpoint.Type == HardpointType.Energy && hardpoint.Transform == "gun"); + } + + [Fact] + public void ComposeCountsEveryPackageAndReplacesAnExistingDerivedCatalog() + { + WritePackage("mod.skiff"); + Assert.Equal(1, ShipModCatalog.Compose(Shipped, Derived, Mods).Included.Length); + WritePackage("mod.barge", hullName: "Barge"); + + Assert.Equal(2, ShipModCatalog.Compose(Shipped, Derived, Mods).Included.Length); + + using var cache = AetheriaStores.Open(Derived); + Assert.Equal(new[] { "Barge", "Skiff", "Wasp" }, cache.GetAll().Select(hull => hull.Name).OrderBy(name => name)); + AssertOnlyTheDerivedFile(); + } + + // One bad package never stops the game: it is left out and named, and the rest are composed. + [Fact] + public void ABadPackageIsExcludedAndNamedWhileTheGoodOnesCompose() + { + WritePackage("mod.good", hullName: "Good"); + WritePackage("mod.nomodel", hullName: "Nomodel", nodes: FixtureNodes.Where(node => node != "shield").ToArray()); + WritePackage("mod.nofile", hullName: "Nofile"); + File.Delete(Path.Combine(Mods, "mod.nofile", "skiff.glb")); + Directory.CreateDirectory(Path.Combine(Mods, "mod.garbage")); + File.WriteAllText(Path.Combine(Mods, "mod.garbage", "ship.cc"), "not a ship file"); + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Equal(new[] { "mod.good" }, composition.Included); + Assert.Equal(new[] { "mod.garbage", "mod.nofile", "mod.nomodel" }, composition.Excluded.Select(exclusion => exclusion.Package)); + Assert.Contains("model has no node with aetheria.id=shield", composition.Excluded.Single(e => e.Package == "mod.nomodel").Reason); + Assert.Contains("must name an existing GLB", composition.Excluded.Single(e => e.Package == "mod.nofile").Reason); + Assert.Contains("mod.nofile: ", composition.Excluded.Single(e => e.Package == "mod.nofile").ToString()); + using (var cache = AetheriaStores.Open(Derived)) + Assert.Equal(new[] { "Good", "Wasp" }, cache.GetAll().Select(hull => hull.Name).OrderBy(name => name)); + AssertOnlyTheDerivedFile(); + } + + // A name collision leaves out every package that claims the name; the verdict does not depend on directory order. + [Fact] + public void ACollisionExcludesEveryPackageInvolvedAndNoneOfTheRest() + { + WritePackage("mod.a", hullName: "Skiff"); + WritePackage("mod.b", hullName: "Skiff"); + WritePackage("mod.c", hullName: "Skiff"); + WritePackage("mod.d", hullName: "Wasp"); + WritePackage("mod.e", hullName: "Fine"); + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Equal(new[] { "mod.e" }, composition.Included); + Assert.Equal(new[] { "mod.a", "mod.b", "mod.c", "mod.d" }, composition.Excluded.Select(exclusion => exclusion.Package)); + Assert.Equal("hull name 'Skiff' is also claimed by mod.b, mod.c.", composition.Excluded[0].Reason); + Assert.Equal("hull name 'Skiff' is also claimed by mod.a, mod.c.", composition.Excluded[1].Reason); + Assert.Equal("hull name 'Wasp' collides with an existing catalog item.", composition.Excluded[3].Reason); + using var cache = AetheriaStores.Open(Derived); + Assert.Equal(new[] { "Fine", "Wasp" }, cache.GetAll().Select(hull => hull.Name).OrderBy(name => name)); + } + + // A package that fails for two reasons names both. + [Fact] + public void APackageThatCollidesTwiceNamesBothReasons() + { + WritePackage("mod.a", hullName: "Wasp"); + WritePackage("mod.b", hullName: "Wasp"); + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Empty(composition.Included); + Assert.Equal("hull name 'Wasp' collides with an existing catalog item.; hull name 'Wasp' is also claimed by mod.b.", + composition.Excluded[0].Reason); + } + + [Theory] + [InlineData("mod-hull:mod.skiff", false)] + [InlineData("mod-ship:mod.skiff", true)] + public void APackageWhoseKeyAlreadyExistsInTheCatalogIsExcluded(string key, bool authoring) + { + WritePackage("mod.skiff"); + WritePackage("mod.other", hullName: "Other"); + using (var cache = AetheriaStores.Open(Shipped, catalogWritable: true)) + { + if (authoring) + { + var stranger = ShipAuthoringTests.Fixture().WithId("stranger").Visual; + cache.UpsertAsync(typeof(ShipAuthoring), stranger, new CultRecordKey(key)).GetAwaiter().GetResult(); + } + else + cache.UpsertAsync(typeof(HullData), new HullData { Name = "Stranger", Shape = ShipAuthoringTests.Fixture().Hull.Shape }, + new CultRecordKey(key)).GetAwaiter().GetResult(); + cache.FlushAsync().Wait(); + } + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Equal(new[] { "mod.other" }, composition.Included); + Assert.Contains("a mod key collides", Assert.Single(composition.Excluded).Reason); + Assert.Equal("mod.skiff", composition.Excluded[0].Package); + } + + [Theory] + [InlineData(typeof(HullData))] + [InlineData(typeof(GearData))] + public void APackageWithAHullNamedLikeAShippedItemIsExcluded(Type shippedType) + { + using (var cache = AetheriaStores.Open(Shipped, catalogWritable: true)) + { + if (shippedType == typeof(HullData)) + cache.Upsert(new HullData { Name = "Skiff", Shape = ShipAuthoringTests.Fixture().Hull.Shape }); + else + cache.Upsert(new GearData { Name = "Skiff" }); + cache.FlushAsync().Wait(); + } + WritePackage("mod.skiff"); + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Empty(composition.Included); + Assert.Equal("hull name 'Skiff' collides with an existing catalog item.", Assert.Single(composition.Excluded).Reason); + } + + [Fact] + public void APackageWhoseShipIdAShippedAuthoringRecordAlreadyUsesIsExcluded() + { + using (var cache = AetheriaStores.Open(Shipped, catalogWritable: true)) + { + cache.UpsertAsync(typeof(ShipAuthoring), ShipAuthoringTests.Fixture().Visual, new CultRecordKey("shipped:skiff")).GetAwaiter().GetResult(); + cache.FlushAsync().Wait(); + } + WritePackage("mod.skiff", hullName: "Different"); + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Empty(composition.Included); + Assert.Equal("ship ID collides with an existing catalog ship authoring record.", Assert.Single(composition.Excluded).Reason); + } + + // The game's boot: a bad package is named and the rest boot; with none left, the shipped catalog boots. + [Fact] + public void TheBootCatalogSurvivesBadPackages() + { + WritePackage("mod.good", hullName: "Good"); + WritePackage("mod.bad", hullName: "Bad", nodes: FixtureNodes.Where(node => node != "shield").ToArray()); + + var (catalog, excluded) = ShipModCatalog.ResolveCatalog(Shipped, Derived, Mods); + Assert.Equal(Derived, catalog); + Assert.Equal("mod.bad", Assert.Single(excluded).Package); + + Directory.Delete(Path.Combine(Mods, "mod.good"), true); + (catalog, excluded) = ShipModCatalog.ResolveCatalog(Shipped, Derived, Mods); + Assert.Equal(Shipped, catalog); + Assert.Equal("mod.bad", Assert.Single(excluded).Package); + } + + public void ComposeRefusesUnsafeInputsAndOutputs() + { + WritePackage("mod.skiff"); + Assert.Contains("Shipped catalog is missing", Assert.Throws(() => + ShipModCatalog.Compose(Path.Combine(_directory.Path, "absent.cc"), Derived, Mods)).Message); + Assert.Contains("Mod root is missing", Assert.Throws(() => + ShipModCatalog.Compose(Shipped, Derived, Path.Combine(_directory.Path, "NoMods"))).Message); + var before = Hash(Shipped); + Assert.Contains("cannot replace the shipped catalog", Assert.Throws(() => + ShipModCatalog.Compose(Shipped, Shipped, Mods)).Message); + Assert.Contains("cannot replace the shipped catalog", Assert.Throws(() => + ShipModCatalog.Compose(Shipped, Shipped.ToUpperInvariant().Replace(_directory.Path.ToUpperInvariant(), _directory.Path), Mods)).Message); + Assert.Contains("cannot replace a mod source or asset", Assert.Throws(() => + ShipModCatalog.Compose(Shipped, Path.Combine(Mods, "mod.skiff", "out.cc"), Mods)).Message); + Assert.Equal(before, Hash(Shipped)); + Assert.False(File.Exists(Path.Combine(Mods, "mod.skiff", "out.cc"))); + } + + [Fact] + public void ReadPackageBindsTheShipToItsDirectoryAndGlb() + { + WritePackage("mod.skiff"); + var package = ShipModCatalog.ReadPackage(Path.Combine(Mods, "mod.skiff", "ship.cc")); + Assert.Equal("mod.skiff", package.Visual.Id); + Assert.Equal(Path.GetFullPath(Path.Combine(Mods, "mod.skiff", "skiff.glb")), package.ModelPath); + Assert.Equal(new Dictionary { ["map"] = 0, ["collider"] = 1, ["shield"] = 2, ["tractor"] = 3, ["thruster-port"] = 4, ["gun"] = 5, ["gun-muzzle"] = 6 }, package.NodeIndices); + } + + [Fact] + public void ReadPackageRefusesADirectoryNameThatIsNotTheShipId() + { + WritePackage("mod.skiff"); + Directory.Move(Path.Combine(Mods, "mod.skiff"), Path.Combine(Mods, "renamed")); + Assert.Contains("ship ID must match its package directory name", Assert.Throws(() => + ShipModCatalog.ReadPackage(Path.Combine(Mods, "renamed", "ship.cc"))).Message); + } + + [Fact] + public void ReadPackageRefusesAMissingOrWronglyNamedModel() + { + WritePackage("mod.skiff"); + File.Delete(Path.Combine(Mods, "mod.skiff", "skiff.glb")); + Assert.Contains("must name an existing GLB inside its package", Assert.Throws(() => + ShipModCatalog.ReadPackage(Path.Combine(Mods, "mod.skiff", "ship.cc"))).Message); + + Directory.Delete(Path.Combine(Mods, "mod.skiff"), true); + WritePackage("mod.skiff", modelAsset: "skiff.bin"); + Assert.Contains("must name an existing GLB inside its package", Assert.Throws(() => + ShipModCatalog.ReadPackage(Path.Combine(Mods, "mod.skiff", "ship.cc"))).Message); + } + + [Fact] + public void ReadPackageAppliesTheCatalogsItemValidationToTheHull() + { + WritePackage("mod.skiff", tweak: ship => ship.Hull.MinimumTemperature = ship.Hull.MaximumTemperature); + Assert.Contains("zero-span range", Assert.Throws(() => + ShipModCatalog.ReadPackage(Path.Combine(Mods, "mod.skiff", "ship.cc"))).Message); + } + + [Fact] + public void ReadPackageRefusesAnAnchorWhoseNodeIsNotInTheModel() + { + WritePackage("mod.skiff", nodes: FixtureNodes.Where(node => node != "thruster-port").ToArray()); + Assert.Contains("model has no node with aetheria.id=thruster-port for anchor thruster.port", Assert.Throws(() => + ShipModCatalog.ReadPackage(Path.Combine(Mods, "mod.skiff", "ship.cc"))).Message); + } + + [Fact] + public void NodeIdsMapToTheirGlbNodeIndexSkippingNodesWithoutOne() + { + var path = Write("nodes.glb", ShipFixture.Glb(@"{""asset"":{""version"":""2.0""},""nodes"":[ + {""name"":""plain""},{""extras"":{""aetheria.id"":""a""}},{""extras"":{}},{""extras"":{""aetheria.id"":""""}},{""extras"":{""aetheria.id"":""b""}}]}")); + Assert.Equal(new Dictionary { ["a"] = 1, ["b"] = 4 }, ShipModCatalog.ReadNodeIds(path)); + } + + [Fact] + public void AGlbWithoutNodesHasNoIds() => + Assert.Empty(ShipModCatalog.ReadNodeIds(Write("empty.glb", ShipFixture.Glb(@"{""asset"":{""version"":""2.0""}}")))); + + [Fact] + public void ADuplicateNodeIdIsRefused() => + Assert.Contains("duplicate GLB node aetheria.id=a", Assert.Throws(() => + ShipModCatalog.ReadNodeIds(Write("dup.glb", ShipFixture.Glb(@"{""nodes"":[{""extras"":{""aetheria.id"":""a""}},{""extras"":{""aetheria.id"":""a""}}]}")))).Message); + + [Fact] + public void AMalformedGlbHeaderIsRefused() + { + var good = ShipFixture.Glb(@"{""nodes"":[]}"); + void Refuse(string name, byte[] bytes, string message) => + Assert.Contains(message, Assert.Throws(() => ShipModCatalog.ReadNodeIds(Write(name, bytes))).Message); + + Refuse("short.glb", With(good.Take(19).ToArray(), 8, 19), "invalid GLB 2 header"); + Refuse("magic.glb", With(good, 0, 0x46546C68), "invalid GLB 2 header"); + Refuse("version.glb", With(good, 4, 1), "invalid GLB 2 header"); + Refuse("longer.glb", With(good, 8, (uint)good.Length + 1), "invalid GLB 2 header"); + Refuse("shorter.glb", With(good, 8, (uint)good.Length - 4), "invalid GLB 2 header"); + Refuse("chunktype.glb", With(good, 16, 0x004E4942), "missing GLB JSON chunk"); + Refuse("chunklength.glb", With(good, 12, (uint)good.Length), "missing GLB JSON chunk"); + } + + [Fact] + public void AGlbWhoseJsonChunkFillsTheFileIsAccepted() + { + var json = Encoding.UTF8.GetBytes(@"{""nodes"":[{""extras"":{""aetheria.id"":""a""}}]} "); + var bytes = new byte[20 + json.Length]; + BitConverter.GetBytes(0x46546C67u).CopyTo(bytes, 0); + BitConverter.GetBytes(2u).CopyTo(bytes, 4); + BitConverter.GetBytes((uint)bytes.Length).CopyTo(bytes, 8); + BitConverter.GetBytes((uint)json.Length).CopyTo(bytes, 12); + BitConverter.GetBytes(0x4E4F534Au).CopyTo(bytes, 16); + json.CopyTo(bytes, 20); + Assert.Equal(new Dictionary { ["a"] = 0 }, ShipModCatalog.ReadNodeIds(Write("full.glb", bytes))); + } + + // A run store references a mod hull by its key, so the same packages must derive the same records on every launch, + // whatever order the directories were created in. + [Fact] + public void ComposeAtBootIsDeterministic() + { + var ids = new[] { "mod.a", "mod.b", "mod.c", "mod.d", "mod.e", "mod.f" }; + foreach (var id in ids.Reverse()) WritePackage(id, hullName: "Hull " + id); + var firstMods = Mods; + var secondMods = Path.Combine(_directory.Path, "Mods2"); + foreach (var id in ids) ShipFixture.WritePackage(secondMods, id, "Hull " + id); + var second = Path.Combine(_directory.Path, "Derived2", "Aetheria.modded.cc"); + + ShipModCatalog.Compose(Shipped, Derived, firstMods); + ShipModCatalog.Compose(Shipped, second, secondMods); + ShipModCatalog.Compose(Shipped, Path.Combine(_directory.Path, "Derived3", "Aetheria.modded.cc"), firstMods); + + Assert.Equal(Records(Derived), Records(second)); + Assert.Equal(Records(Derived), Records(Path.Combine(_directory.Path, "Derived3", "Aetheria.modded.cc"))); + Assert.Contains(ShipModCatalog.HullKey("mod.c").Value, Records(Derived).Keys); + } + + [Fact] + public void TheBootCatalogIsTheShippedOneUntilAModIsInstalled() + { + Assert.Equal(Shipped, ShipModCatalog.ResolveCatalog(Shipped, Derived, Path.Combine(_directory.Path, "absent")).Catalog); + Directory.CreateDirectory(Path.Combine(Mods, "notes")); + Assert.Equal(Shipped, ShipModCatalog.ResolveCatalog(Shipped, Derived, Mods).Catalog); + Assert.False(File.Exists(Derived)); + + WritePackage("mod.skiff"); + Assert.Equal(Derived, ShipModCatalog.ResolveCatalog(Shipped, Derived, Mods).Catalog); + using (var cache = AetheriaStores.Open(Derived)) + Assert.Contains("Skiff", cache.GetAll().Select(hull => hull.Name)); + + // Recomposed on every call: a mod removed since the last boot is gone from the file the game opens next. + Directory.Delete(Path.Combine(Mods, "mod.skiff"), true); + Assert.Equal(Shipped, ShipModCatalog.ResolveCatalog(Shipped, Derived, Mods).Catalog); + WritePackage("mod.barge", hullName: "Barge"); + Assert.Equal(Derived, ShipModCatalog.ResolveCatalog(Shipped, Derived, Mods).Catalog); + using (var cache = AetheriaStores.Open(Derived)) + Assert.Equal(new[] { "Barge", "Wasp" }, cache.GetAll().Select(hull => hull.Name).OrderBy(name => name)); + } + + // A failure of the composition itself is a mod problem too: the game boots on the shipped catalog and names it. + [Fact] + public void TheBootCatalogSurvivesAComposeThatFails() + { + WritePackage("mod.skiff"); + var blocker = Path.Combine(_directory.Path, "blocker"); + File.WriteAllText(blocker, "a file where the derived catalog's directory should be"); + + var (catalog, excluded) = ShipModCatalog.ResolveCatalog(Shipped, Path.Combine(blocker, "Aetheria.modded.cc"), Mods); + + Assert.Equal(Shipped, catalog); + var exclusion = Assert.Single(excluded); + Assert.Equal("(all mods)", exclusion.Package); + Assert.False(string.IsNullOrWhiteSpace(exclusion.Reason)); + // An invalid output (the shipped catalog itself) is refused the same way, with its reason. + (catalog, excluded) = ShipModCatalog.ResolveCatalog(Shipped, Shipped, Mods); + Assert.Equal(Shipped, catalog); + Assert.Contains("cannot replace the shipped catalog", Assert.Single(excluded).Reason); + } + + // Gameplay reads a mod ship's records from the derived catalog; the package directory supplies only the GLB. + [Fact] + public void PackageOfTakesItsRecordsFromTheCatalogAndOnlyTheGlbFromTheMod() + { + WritePackage("mod.skiff"); + ShipModCatalog.Compose(Shipped, Derived, Mods); + File.Delete(Path.Combine(Mods, "mod.skiff", "ship.cc")); + + using var cache = AetheriaStores.Open(Derived); + var hull = cache.GetAll().Single(candidate => candidate.Name == "Skiff"); + var package = ShipModCatalog.PackageOf(cache, hull, Mods); + + Assert.Same(hull, package.Hull); + Assert.Same(cache.Get(hull.Visual), package.Visual); + Assert.Equal(Path.Combine(Mods, "mod.skiff", "skiff.glb"), package.ModelPath); + Assert.Equal(ShipFixture.Nodes.Length, package.NodeIndices.Count); + + // The shared validator judges the catalog's records too, not only a ship.cc. + hull.Prefab = "Djinni"; + Assert.Contains("names both a Unity prefab and a visual record", Assert.Throws(() => + ShipModCatalog.PackageOf(cache, hull, Mods)).Message); + hull.Prefab = null; + + // A hull whose visual the catalog does not hold, and a mod whose GLB is gone, are refused. + Assert.Contains("holds no visual record", Assert.Throws(() => + ShipModCatalog.PackageOf(cache, new HullData { Name = "Ghost" }, Mods)).Message); + File.Delete(package.ModelPath); + Assert.Contains("model asset must name an existing GLB", Assert.Throws(() => + ShipModCatalog.PackageOf(cache, hull, Mods)).Message); + } + + // Every stored record's key, schema and payload bytes. StoredAt is a write timestamp, not record content. + private static Dictionary Records(string path) => + GameCult.Caching.MessagePack.CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(path)).Records + .ToDictionary(record => record.Key, record => record.SchemaId + ":" + Convert.ToHexString(record.Payload)); + + private void AssertOnlyTheDerivedFile() + { + var names = Directory.GetFileSystemEntries(Path.GetDirectoryName(Derived)).Select(entry => Path.GetFileName(entry)).ToArray(); + Assert.True(names.Length == 1 && names[0] == "Aetheria.modded.cc", string.Join(" | ", names)); + } + + private static byte[] With(byte[] bytes, int offset, uint value) + { + var copy = (byte[])bytes.Clone(); + BitConverter.GetBytes(value).CopyTo(copy, offset); + return copy; + } + + private string Write(string name, byte[] bytes) + { + var path = Path.Combine(_directory.Path, name); + File.WriteAllBytes(path, bytes); + return path; + } + + private void WritePackage(string id, string hullName = "Skiff", string[] nodes = null, string modelAsset = "skiff.glb", + Action tweak = null) => ShipFixture.WritePackage(Mods, id, hullName, nodes, modelAsset, tweak); + + private static int Occurrences(byte[] haystack, byte[] needle) + { + var count = 0; + for (var start = 0; start <= haystack.Length - needle.Length; start++) + if (haystack.AsSpan(start, needle.Length).SequenceEqual(needle)) count++; + return count; + } + + private static string Hash(string path) => Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path))); +} diff --git a/tests/Aetheria.Shared.Tests/ShipModPlanTests.cs b/tests/Aetheria.Shared.Tests/ShipModPlanTests.cs new file mode 100644 index 000000000..c98ff3a10 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ShipModPlanTests.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using CultMath; +using Xunit; + +// ShipModPlan: which anchor fills which component slot. The Unity assembler only follows this. +public sealed class ShipModPlanTests +{ + // Thruster, turret and radiator mounts on a 3x1 hull. The muzzles' Order runs against their ids on purpose. + private static ShipParts Rig() + { + var ship = ShipAuthoringTests.Fixture(); + var shape = new Shape(3, 1); + for (var x = 0; x < 3; x++) shape.Cells[x, 0] = true; + ship.Hull.Shape = shape; + ship.Hull.Hardpoints[0].Position = new int2(2, 0); + ship.Hull.Hardpoints.Add(new HardpointData { Type = HardpointType.Energy, Position = new int2(0, 0), Shape = new Shape(), Transform = "gun" }); + ship.Hull.Hardpoints.Add(new HardpointData { Type = HardpointType.Radiator, Position = new int2(1, 0), Shape = new Shape(), Transform = "fin" }); + ship.Visual.Anchors.Add(new ShipAnchor { Id = "gun", Role = "articulation", ModelNodeId = "gun" }); + ship.Visual.Anchors.Add(new ShipAnchor { Id = "gun.a", Role = "weapon-muzzle", ModelNodeId = "gun-a", ParentId = "gun", Order = 1 }); + ship.Visual.Anchors.Add(new ShipAnchor { Id = "gun.z", Role = "weapon-muzzle", ModelNodeId = "gun-z", ParentId = "gun", Order = 0 }); + ship.Visual.Anchors.Add(new ShipAnchor { Id = "fin", Role = "radiator-mesh", ModelNodeId = "fin" }); + return ship; + } + + private static ShipModPlan Plan(ShipParts ship) => ShipModPlan.Build(ship.Hull, ship.Visual); + private static string Refusal(ShipParts ship) => Assert.Throws(() => Plan(ship)).Message; + + [Fact] + public void EachSlotIsFilledFromItsAnchor() + { + var plan = Plan(Rig()); + + Assert.Equal(("map", "collider", "shield", "tractor"), (plan.MapIcon, plan.HullCollider, plan.Shield, plan.Tractor)); + Assert.Equal(new[] { "thruster.port", "gun", "fin" }, plan.Equipment); + Assert.Equal(new[] { "thruster.port" }, plan.Thrusters); + Assert.Equal(new[] { "fin" }, plan.Radiators); + var (mount, muzzles) = Assert.Single(plan.Weapons); + Assert.Equal("gun", mount); + Assert.Equal(new[] { "gun.z", "gun.a" }, muzzles); + } + + [Fact] + public void AThrusterOrRadiatorMountMustCarryItsRole() + { + var ship = Rig(); + ship.Visual.Anchors.Single(anchor => anchor.Id == "thruster.port").Role = "articulation"; + Assert.Contains("Thruster hardpoint thruster.port needs a thruster-emitter anchor", Refusal(ship)); + + ship = Rig(); + ship.Visual.Anchors.Single(anchor => anchor.Id == "fin").Role = "articulation"; + Assert.Contains("Radiator hardpoint fin needs a radiator-mesh anchor", Refusal(ship)); + } + + [Fact] + public void AnEmitterOrMeshAnchorMustBeItsHardpointsMount() + { + // A thruster-emitter anchor on a weapon mount, and a radiator-mesh anchor that is no mount at all. + var ship = Rig(); + ship.Visual.Anchors.Single(anchor => anchor.Id == "gun").Role = "thruster-emitter"; + Assert.Contains("Energy hardpoint gun needs a articulation anchor of that id", Refusal(ship)); + + ship = Rig(); + ship.Visual.Anchors.Add(new ShipAnchor { Id = "loose", Role = "radiator-mesh", ModelNodeId = "loose" }); + Assert.Contains("radiator-mesh anchor loose must be a Radiator hardpoint's mount", Refusal(ship)); + } + + // Equal Order falls back to the id, compared ordinally, whatever order the anchors were authored in. + [Fact] + public void MuzzlesOfEqualOrderAreTiedByIdOrdinally() + { + var ship = Rig(); + ship.Visual.Anchors.RemoveAll(anchor => anchor.Role == "weapon-muzzle"); + foreach (var id in new[] { "gun.c", "gun.a", "gun.B", "gun.b" }) + ship.Visual.Anchors.Add(new ShipAnchor { Id = id, Role = "weapon-muzzle", ModelNodeId = id, ParentId = "gun", Order = 2 }); + ship.Visual.Anchors.Add(new ShipAnchor { Id = "gun.z", Role = "weapon-muzzle", ModelNodeId = "gun.z", ParentId = "gun", Order = 1 }); + + Assert.Equal(new[] { "gun.z", "gun.B", "gun.a", "gun.b", "gun.c" }, Assert.Single(Plan(ship).Weapons).Muzzles); + } + + [Fact] + public void MuzzlesBelongToWeaponMountsAndEveryWeaponHasOne() + { + var ship = Rig(); + ship.Visual.Anchors.Single(anchor => anchor.Id == "gun.z").ParentId = null; + Assert.Contains("muzzle gun.z must be parented to a weapon hardpoint's mount", Refusal(ship)); + + ship = Rig(); + ship.Visual.Anchors.Single(anchor => anchor.Id == "gun.z").ParentId = "thruster.port"; + Assert.Contains("muzzle gun.z must be parented to a weapon hardpoint's mount", Refusal(ship)); + + ship = Rig(); + ship.Visual.Anchors.RemoveAll(anchor => anchor.Role == "weapon-muzzle"); + Assert.Contains("weapon hardpoint gun needs at least one muzzle anchor", Refusal(ship)); + } + + [Theory] + [InlineData(HardpointType.Energy)] + [InlineData(HardpointType.Ballistic)] + [InlineData(HardpointType.Launcher)] + public void EveryWeaponHardpointTypeTakesMuzzles(HardpointType type) + { + var ship = Rig(); + ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "gun").Type = type; + Assert.Equal("gun", Assert.Single(Plan(ship).Weapons).Mount); + + // Any other type refuses the same muzzles. + ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "gun").Type = HardpointType.Tool; + Assert.Contains("must be parented to a weapon hardpoint's mount", Refusal(ship)); + } + + [Fact] + public void ABodyThatFailsTheSharedValidatorIsNeverPlanned() + { + var ship = Rig(); + ship.Hull.Prefab = "Djinni"; + Assert.Contains("names both a Unity prefab and a visual record", Refusal(ship)); + } +} diff --git a/tests/Aetheria.Shared.Tests/ShipSchemaPinTests.cs b/tests/Aetheria.Shared.Tests/ShipSchemaPinTests.cs new file mode 100644 index 000000000..418c8f31a --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ShipSchemaPinTests.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; +using Xunit; + +// tools/blender/aetheria_ships/ship_cc.py edits a ship file's HullData and ShipAuthoring records by MessagePack slot +// number and by hardpoint member position. These tests bind that file to the C# types that own the numbers: any renumbered, renamed or +// reordered member, enum value, or nested array shape fails here instead of corrupting a ship the next time Blender saves. +public sealed class ShipSchemaPinTests +{ + private static readonly string Source = File.ReadAllText(Locate("tools", "blender", "aetheria_ships", "ship_cc.py")); + + [Theory] + [InlineData("SCHEMATIC_LINES_SLOT", typeof(ShipAuthoring), nameof(ShipAuthoring.SchematicLines))] + [InlineData("HULL_SHAPE_SLOT", typeof(HullData), nameof(HullData.Shape))] + [InlineData("HULL_HARDPOINTS_SLOT", typeof(HullData), nameof(HullData.Hardpoints))] + public void PythonSlotConstantsAreTheKeysOfTheMembersTheyNameInTheirComments(string constant, Type owner, string member) + { + Assert.Equal(KeyOf(owner, member), Integer(constant)); + Assert.Matches(new Regex($@"^{constant} = \d+ # \w+\.{member}\r?$", RegexOptions.Multiline), Source); + } + + [Fact] + public void PythonSchemaNamesAreTheDocumentsTheyNameAndTheRetiredSlotIsNotReused() + { + Assert.Equal(typeof(ShipAuthoring).GetCustomAttribute().SchemaName, Text("SCHEMA")); + Assert.Equal(typeof(HullData).GetCustomAttribute().SchemaName, Text("HULL_SCHEMA")); + Assert.Equal(1, Integer("RETIRED_HULL_SLOT")); + // Key 1 held the embedded hull until S1. A later member must not take it, or an old file would decode as it. + Assert.DoesNotContain(typeof(ShipAuthoring).GetMembers(BindingFlags.Public | BindingFlags.Instance), + member => member.GetCustomAttribute()?.IntKey == 1); + } + + // HullData.Visual is the one binding between a hull and its visual; its slot is the wire contract. + [Fact] + public void HullVisualIsKey32() + { + Assert.Equal(32, KeyOf(typeof(HullData), nameof(HullData.Visual))); + var taken = typeof(HullData).GetMembers(BindingFlags.Public | BindingFlags.Instance) + .Select(member => member.GetCustomAttribute()?.IntKey).Where(key => key != null).ToArray(); + Assert.Equal(taken.Length, taken.Distinct().Count()); + } + + [Fact] + public void PythonHardpointMembersAreHardpointDataMembersAtTheirOwnPositions() + { + var members = Strings("HARDPOINT_MEMBERS"); + Assert.Equal(7, members.Length); + for (var slot = 0; slot < members.Length; slot++) + Assert.Equal(slot, KeyOf(typeof(HardpointData), members[slot])); + } + + [Fact] + public void PythonEnumNamesAreTheEnumsInValueOrder() + { + Assert.Equal(EnumNames(), Strings("HARDPOINT_TYPE_NAMES")); + Assert.Equal(EnumNames(), Strings("ROTATION_NAMES")); + } + + [Fact] + public void SerializedShipHasTheNestedArrayShapesPythonIndexes() + { + var (hull, visual) = ShipAuthoringTests.Fixture(); + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(ShipAuthoring).Assembly); + object[] Body(object document) => Assert.IsType(MessagePackSerializer.Deserialize( + MessagePackSerializer.Serialize(document.GetType(), document, options), MessagePackSerializerOptions.Standard)); + + var body = Body(visual); + Assert.Equal("mod.skiff", body[0]); + var lines = Assert.IsType(body[Integer("SCHEMATIC_LINES_SLOT")]); + Assert.Equal("Hull", Assert.IsType(Assert.Single(lines))[0]); + + var hullBody = Body(hull); + // A schematic is [[width, height, cells]] with cells flattened x-major (index x * height + y). + var hullShape = Assert.IsType(Assert.IsType(hullBody[Integer("HULL_SHAPE_SLOT")])[0]); + Assert.Equal(new object[] { 2, 2 }, hullShape.Take(2).Select(value => (object)Convert.ToInt32(value))); + Assert.Equal(new[] { true, false, true, false }, Assert.IsType(hullShape[2]).Cast()); + + var hardpoints = Assert.IsType(hullBody[Integer("HULL_HARDPOINTS_SLOT")]); + var row = Assert.IsType(Assert.Single(hardpoints)); + var members = Strings("HARDPOINT_MEMBERS"); + Assert.True(row.Length >= members.Length); + Assert.Equal("thruster.port", row[Array.IndexOf(members, "Transform")]); + var footprint = Assert.IsType(Assert.IsType(row[Array.IndexOf(members, "Shape")])[0]); + Assert.Equal(3, footprint.Length); + Assert.Equal(new[] { true }, Assert.IsType(footprint[2]).Cast()); + Assert.Equal(new[] { 1, 0 }, Assert.IsType(row[Array.IndexOf(members, "Position")]).Select(value => Convert.ToInt32(value))); + } + + private static int KeyOf(Type owner, string member) + { + var found = owner.GetMember(member, BindingFlags.Public | BindingFlags.Instance).Single(); + return Assert.IsType(found.GetCustomAttribute().IntKey); + } + + private static int Integer(string constant) => + int.Parse(Regex.Match(Source, $@"^{constant} = (\d+)", RegexOptions.Multiline).Groups[1].Value); + + private static string Text(string constant) + { + var match = Regex.Match(Source, $@"^{constant} = ""([^""]*)""", RegexOptions.Multiline); + Assert.True(match.Success, $"{constant} is not a string in ship_cc.py"); + return match.Groups[1].Value; + } + + private static string[] Strings(string constant) + { + var block = Regex.Match(Source, $@"^{constant} = \((.*?)\)\r?$", RegexOptions.Multiline | RegexOptions.Singleline); + Assert.True(block.Success, $"{constant} is not a tuple in ship_cc.py"); + return Regex.Matches(block.Groups[1].Value, "\"([^\"]*)\"").Select(match => match.Groups[1].Value).ToArray(); + } + + private static string[] EnumNames() where T : struct, Enum + { + var values = Enum.GetValues().OrderBy(value => Convert.ToInt32(value)).ToArray(); + Assert.Equal(Enumerable.Range(0, values.Length), values.Select(value => Convert.ToInt32(value))); + return values.Select(value => value.ToString()).ToArray(); + } + + private static string Locate(params string[] relative) + { + for (var directory = new DirectoryInfo(AppContext.BaseDirectory); directory != null; directory = directory.Parent) + { + var candidate = Path.Combine(new[] { directory.FullName }.Concat(relative).ToArray()); + if (File.Exists(candidate)) return candidate; + } + throw new FileNotFoundException("Repository file not found above the test binary: " + Path.Combine(relative)); + } +} diff --git a/tests/Aetheria.Shared.Tests/ShipValidationTests.cs b/tests/Aetheria.Shared.Tests/ShipValidationTests.cs new file mode 100644 index 000000000..eb150939a --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ShipValidationTests.cs @@ -0,0 +1,253 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using CultMath; +using Xunit; + +// One case per refusal in ShipAuthoringStore.Validate and Read. Each case starts from the valid fixture, breaks exactly +// one thing, and names the message that guard alone produces, so a guard that stops firing (or fires for the wrong +// reason) fails its own case and no other. +public sealed class ShipValidationTests +{ + private static readonly Dictionary Break, string Message)> Cases = Build(); + + public static IEnumerable CaseNames => Cases.Keys.Select(name => new object[] { name }); + + [Fact] + public void TheFixtureIsValid() => ShipAuthoringTests.Fixture().Validate(); + + [Theory, MemberData(nameof(CaseNames))] + public void ValidatorRefusesEachBreakageByItsOwnGuard(string name) + { + var ship = ShipAuthoringTests.Fixture(); + Cases[name].Break(ship); + var error = Assert.Throws(ship.Validate); + Assert.Contains(Cases[name].Message, error.Message); + } + + [Fact] + public void HardpointsAtTheEdgesOfTheirRangesAreValid() + { + var ship = ShipAuthoringTests.Fixture(); + ship.Hull.Hardpoints[0].Armor = 5; + ship.Hull.Hardpoints[0].FiringArc = 360; + ship.Hull.Hardpoints[0].Type = HardpointType.AetherDrive; + ship.Visual.Anchors.Single(anchor => anchor.Id == "thruster.port").Role = "articulation"; + ship.Hull.Hardpoints[0].Rotation = ItemRotation.Clockwise; + ship.Validate(); + } + + [Fact] + public void ValidatorRefusesANullRecord() => + Assert.Contains("is null", Assert.Throws(() => ShipAuthoringStore.Validate(ShipAuthoringTests.Fixture().Hull, null)).Message); + + [Theory] + [InlineData("a"), InlineData("z"), InlineData("0"), InlineData("9"), InlineData("a0z9"), InlineData("0a"), InlineData("9z"), + InlineData("a.b_c-d"), InlineData("a-"), InlineData("z_")] + public void IdsMayUseLowerCaseAsciiDigitsDotsUnderscoresAndHyphens(string id) + { + var ship = ShipAuthoringTests.Fixture(); + ship.WithId(id).Validate(); + } + + [Theory] + [InlineData("`a"), InlineData("{a"), InlineData("/a"), InlineData(":a"), InlineData("@a"), InlineData("-a"), InlineData(".a"), InlineData("_a"), + InlineData("a`"), InlineData("a{"), InlineData("a/"), InlineData("a:"), InlineData("a@"), InlineData("aA"), InlineData("a b")] + public void IdsOutsideThatAlphabetAreRefused(string id) + { + var ship = ShipAuthoringTests.Fixture(); + ship.WithId(id); + Assert.Contains("ship ID must use", Assert.Throws(ship.Validate).Message); + } + + [Theory] + [InlineData("skiff.glb"), InlineData("models/skiff.glb"), InlineData("models\\skiff.glb"), InlineData("..skiff.glb"), InlineData("a..b/skiff.glb")] + public void ModelAssetsMayLiveInsideTheirPackage(string asset) + { + var ship = ShipAuthoringTests.Fixture(); + ship.Visual.ModelAsset = asset; + ship.Validate(); + } + + [Theory] + [InlineData("../skiff.glb"), InlineData("..\\skiff.glb"), InlineData("a/../skiff.glb"), InlineData("a\\..\\skiff.glb"), InlineData("a/..")] + public void ModelAssetsCannotEscapeTheirPackage(string asset) + { + var ship = ShipAuthoringTests.Fixture(); + ship.Visual.ModelAsset = asset; + Assert.Contains("relative package path", Assert.Throws(ship.Validate).Message); + } + + [Fact] + public void RootedModelAssetsAreRefused() + { + var ship = ShipAuthoringTests.Fixture(); + ship.Visual.ModelAsset = Path.GetFullPath("skiff.glb"); + Assert.Contains("relative package path", Assert.Throws(ship.Validate).Message); + } + + [Fact] + public void OptionalPartsAndRangeEdgesAreAccepted() + { + var ship = ShipAuthoringTests.Fixture(); + var line = ship.Visual.SchematicLines[0]; + line.Points = new[] { 0f, 0f, 0f, 1f, 0f, 0f, 2f, 0f, 0f }; + line.Radii = new[] { 0f, 5f, 0f }; + line.Opacities = new[] { 0f, 1f, .5f }; + ship.Validate(); + line.Radii = null; + line.Opacities = null; + line.Color = null; + ship.Validate(); + ship.Visual.SchematicLines = null; + ship.Hull.Hardpoints = null; + ship.Visual.Anchors.RemoveAt(ship.Visual.Anchors.Count - 1); + ship.Validate(); + } + + [Fact] + public void EmptyCellsInAHardpointFootprintNeedNotLieOnTheHull() + { + var ship = ShipAuthoringTests.Fixture(); + ship.Hull.Hardpoints[0].Shape = new Shape(2, 1); + ship.Hull.Hardpoints[0].Shape.Cells[0, 0] = true; + ship.Validate(); + } + + [Fact] + public void AnEmptyParentIdMeansNoParent() + { + var ship = ShipAuthoringTests.Fixture(); + ship.Visual.Anchors[0].ParentId = ""; + ship.Validate(); + } + + [Fact] + public void AnAnchorMayNameItsHardpointAsParent() + { + var ship = ShipAuthoringTests.Fixture(); + ship.Visual.Anchors.Add(new ShipAnchor { Id = "muzzle", Role = "weapon-muzzle", ModelNodeId = "muzzle", ParentId = "thruster.port" }); + ship.Validate(); + } + + [Fact] + public async Task ReadValidatesWhatItLoads() + { + using var directory = new TempDirectory(); + var path = Path.Combine(directory.Path, "bad.cc"); + var ship = ShipAuthoringTests.Fixture(); + ship.Hull.Name = ""; + using (var cache = ShipAuthoringStore.Open(path, writable: true)) + { + ShipAuthoringStore.Write(cache, ship.Hull, ship.Visual); + await cache.FlushAsync(); + } + Assert.Contains("hull name is required", Assert.Throws(() => ShipAuthoringStore.Read(path)).Message); + } + + private static Dictionary, string)> Build() + { + var cases = new Dictionary, string)>(); + void Add(string name, Action breakIt, string message) => cases.Add(name, (breakIt, message)); + HardpointData Mount(ShipParts ship) => ship.Hull.Hardpoints[0]; + + Add("id-null", s => s.Visual.Id = null, "Ship ID is required"); + Add("id-blank", s => s.Visual.Id = " ", "Ship ID is required"); + Add("hull-null", s => s.Hull = null, "hull data is required"); + Add("hull-name-null", s => s.Hull.Name = null, "hull name is required"); + Add("hull-name-blank", s => s.Hull.Name = " ", "hull name is required"); + Add("hull-shape-null", s => s.Hull.Shape = null, "at least one cell"); + Add("hull-cells-null", s => s.Hull.Shape.Cells = null, "at least one cell"); + Add("hull-width-zero", s => s.Hull.Shape.Cells = new bool[0, 2], "at least one cell"); + Add("hull-height-zero", s => s.Hull.Shape.Cells = new bool[2, 0], "at least one cell"); + Add("hull-no-occupied-cell", s => s.Hull.Shape.Cells = new bool[2, 2], "at least one cell"); + Add("hull-names-a-prefab-and-a-visual", s => s.Hull.Prefab = "Djinni", "names both a Unity prefab and a visual record"); + Add("model-null", s => s.Visual.ModelAsset = null, "relative package path"); + Add("model-blank", s => s.Visual.ModelAsset = " ", "relative package path"); + + Add("anchors-null", s => s.Visual.Anchors = null, "anchors are required"); + Add("anchor-null", s => s.Visual.Anchors.Add(null), "anchor IDs must be present and unique"); + Add("anchor-id-null", s => s.Visual.Anchors[4].Id = null, "anchor IDs must be present and unique"); + Add("anchor-id-blank", s => s.Visual.Anchors.Add(new ShipAnchor { Id = " ", Role = "articulation", ModelNodeId = "x" }), "anchor IDs must be present and unique"); + Add("anchor-id-duplicate", s => s.Visual.Anchors.Add(new ShipAnchor { Id = "map", Role = "articulation", ModelNodeId = "x" }), "anchor IDs must be present and unique"); + Add("anchor-node-null", s => s.Visual.Anchors[4].ModelNodeId = null, "needs a model node ID"); + Add("anchor-node-blank", s => s.Visual.Anchors[4].ModelNodeId = " ", "needs a model node ID"); + Add("anchor-node-shared", s => s.Visual.Anchors.Add(new ShipAnchor { Id = "other", Role = "articulation", ModelNodeId = "map" }), "claimed by more than one anchor"); + foreach (var role in new[] { "map-icon", "hull-collider", "shield", "tractor" }) + { + Add("role-missing-" + role, s => s.Visual.Anchors.RemoveAll(a => a.Role == role), $"exactly one {role} anchor is required"); + Add("role-doubled-" + role, s => s.Visual.Anchors.Add(new ShipAnchor { Id = "extra", Role = role, ModelNodeId = "extra" }), $"exactly one {role} anchor is required"); + } + + Add("anchor-role-unknown", s => s.Visual.Anchors.Add(new ShipAnchor { Id = "x", Role = "engine", ModelNodeId = "x" }), "has unknown role 'engine'"); + Add("anchor-role-null", s => s.Visual.Anchors.Add(new ShipAnchor { Id = "x", Role = null, ModelNodeId = "x" }), "has unknown role ''"); + Add("anchor-role-cased", s => s.Visual.Anchors[0].Role = "Map-Icon", "has unknown role 'Map-Icon'"); + + Add("hardpoint-null", s => s.Hull.Hardpoints.Add(null), "hardpoint IDs must be present and unique"); + Add("hardpoint-transform-null", s => Mount(s).Transform = null, "hardpoint IDs must be present and unique"); + Add("hardpoint-transform-blank", s => Mount(s).Transform = " ", "hardpoint IDs must be present and unique"); + Add("hardpoint-transform-duplicate", s => s.Hull.Hardpoints.Add(new HardpointData { Position = new int2(0, 0), Transform = "thruster.port" }), "hardpoint IDs must be present and unique"); + Add("hardpoint-shape-null", s => Mount(s).Shape = null, "has no cells"); + Add("hardpoint-cells-null", s => Mount(s).Shape.Cells = null, "has no cells"); + Add("hardpoint-cells-all-empty", s => Mount(s).Shape.Cells = new bool[1, 1], "has no cells"); + Add("hardpoint-type-undefined", s => Mount(s).Type = (HardpointType)99, "unknown type 99"); + Add("hardpoint-type-negative", s => Mount(s).Type = (HardpointType)(-1), "unknown type -1"); + Add("hardpoint-rotation-undefined", s => Mount(s).Rotation = (ItemRotation)4, "unknown rotation 4"); + Add("hardpoint-rotation-negative", s => Mount(s).Rotation = (ItemRotation)(-1), "unknown rotation -1"); + Add("hardpoint-armor-nan", s => Mount(s).Armor = float.NaN, "armor and firing arc must be finite and not negative"); + Add("hardpoint-armor-infinite", s => Mount(s).Armor = float.PositiveInfinity, "armor and firing arc must be finite and not negative"); + Add("hardpoint-armor-negative", s => Mount(s).Armor = -1, "armor and firing arc must be finite and not negative"); + Add("hardpoint-arc-nan", s => Mount(s).FiringArc = float.NaN, "armor and firing arc must be finite and not negative"); + Add("hardpoint-arc-infinite", s => Mount(s).FiringArc = float.NegativeInfinity, "armor and firing arc must be finite and not negative"); + Add("hardpoint-arc-negative", s => Mount(s).FiringArc = -1, "armor and firing arc must be finite and not negative"); + Add("hardpoint-left-of-hull", s => Mount(s).Position = new int2(-1, 0), "outside the hull schematic"); + Add("hardpoint-below-hull", s => Mount(s).Position = new int2(1, -1), "outside the hull schematic"); + Add("hardpoint-right-of-hull", s => Mount(s).Position = new int2(2, 0), "outside the hull schematic"); + Add("hardpoint-above-hull", s => Mount(s).Position = new int2(1, 2), "outside the hull schematic"); + Add("hardpoint-on-an-empty-hull-cell", s => Mount(s).Position = new int2(0, 1), "outside the hull schematic"); + Add("hardpoint-footprint-overhangs", s => + { + Mount(s).Shape = new Shape(2, 1); + Mount(s).Shape.Cells[0, 0] = Mount(s).Shape.Cells[1, 0] = true; + }, "outside the hull schematic"); + Add("hardpoints-overlap", s => + { + s.Hull.Hardpoints.Add(new HardpointData { Position = new int2(1, 0), Transform = "thruster.starboard" }); + s.Visual.Anchors.Add(new ShipAnchor { Id = "thruster.starboard", Role = "thruster-emitter", ModelNodeId = "thruster-starboard" }); + }, "overlaps another hardpoint"); + Add("hardpoint-without-anchor", s => s.Visual.Anchors.RemoveAll(a => a.Id == "thruster.port"), "has no model anchor"); + Add("anchor-parent-unknown", s => s.Visual.Anchors.Add(new ShipAnchor { Id = "muzzle", Role = "weapon-muzzle", ModelNodeId = "muzzle", ParentId = "nowhere" }), "unknown hardpoint parent"); + + Add("line-null", s => s.Visual.SchematicLines.Add(null), "finite XYZ points"); + Add("line-points-null", s => s.Visual.SchematicLines[0].Points = null, "finite XYZ points"); + Add("line-one-point", s => s.Visual.SchematicLines[0].Points = new[] { 0f, 0f, 0f }, "finite XYZ points"); + Add("line-points-not-triples", s => s.Visual.SchematicLines[0].Points = new float[7], "finite XYZ points"); + Add("line-point-nan", s => s.Visual.SchematicLines[0].Points[3] = float.NaN, "finite XYZ points"); + Add("line-point-infinite", s => s.Visual.SchematicLines[0].Points[5] = float.PositiveInfinity, "finite XYZ points"); + Add("line-radii-too-short", s => s.Visual.SchematicLines[0].Radii = new[] { .1f }, "attributes have the wrong length"); + Add("line-radii-too-long", s => s.Visual.SchematicLines[0].Radii = new[] { .1f, .1f, .1f }, "attributes have the wrong length"); + Add("line-opacities-too-short", s => s.Visual.SchematicLines[0].Opacities = new[] { 1f }, "attributes have the wrong length"); + Add("line-opacities-too-long", s => s.Visual.SchematicLines[0].Opacities = new[] { 1f, 1f, 1f }, "attributes have the wrong length"); + Add("line-radius-nan", s => s.Visual.SchematicLines[0].Radii[1] = float.NaN, "radius and opacity must be finite"); + Add("line-radius-infinite", s => s.Visual.SchematicLines[0].Radii[1] = float.PositiveInfinity, "radius and opacity must be finite"); + Add("line-radius-negative", s => s.Visual.SchematicLines[0].Radii[0] = -.01f, "radius and opacity must be finite"); + Add("line-opacity-nan", s => s.Visual.SchematicLines[0].Opacities[1] = float.NaN, "radius and opacity must be finite"); + Add("line-opacity-infinite", s => s.Visual.SchematicLines[0].Opacities[1] = float.PositiveInfinity, "radius and opacity must be finite"); + Add("line-opacity-negative", s => s.Visual.SchematicLines[0].Opacities[0] = -.01f, "radius and opacity must be finite"); + Add("line-opacity-above-one", s => s.Visual.SchematicLines[0].Opacities[0] = 1.01f, "radius and opacity must be finite"); + Add("line-color-short", s => s.Visual.SchematicLines[0].Color = new[] { 1f, 1f, 1f }, "must be finite RGBA"); + Add("line-color-long", s => s.Visual.SchematicLines[0].Color = new[] { 1f, 1f, 1f, 1f, 1f }, "must be finite RGBA"); + Add("line-color-nan", s => s.Visual.SchematicLines[0].Color[2] = float.NaN, "must be finite RGBA"); + Add("line-color-infinite", s => s.Visual.SchematicLines[0].Color[3] = float.NegativeInfinity, "must be finite RGBA"); + return cases; + } +} + +internal sealed class TempDirectory : IDisposable +{ + public string Path { get; } = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "aetheria-ship-" + Guid.NewGuid().ToString("N")); + public TempDirectory() => Directory.CreateDirectory(Path); + public void Dispose() => Directory.Delete(Path, true); +} diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index 034bbfd6f..251494d7d 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -36,8 +36,9 @@ public static class Program case "targeting-catalog": return TargetingCatalog(args.Contains("apply")); case "targeting-catalog-6c": return TargetingCatalog6c(args.Contains("apply")); case "targeting-catalog-6d": return TargetingCatalog6d(args.Contains("apply")); + case "ship-authoring": return ShipAuthoringCommands.Run(args.Skip(1).ToArray()); default: - Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear ]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply], firing-arc-migrate [apply], targeting-catalog [apply], targeting-catalog-6c [apply], targeting-catalog-6d [apply]"); + Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear ]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply], firing-arc-migrate [apply], targeting-catalog [apply], targeting-catalog-6c [apply], targeting-catalog-6d [apply], ship-authoring create|inspect|validate|compose"); return 1; } } diff --git a/tools/AetherDb/ShipAuthoringCommands.cs b/tools/AetherDb/ShipAuthoringCommands.cs new file mode 100644 index 000000000..52a8f75fd --- /dev/null +++ b/tools/AetherDb/ShipAuthoringCommands.cs @@ -0,0 +1,67 @@ +using GameCult.Caching; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +// Uses the existing database executable; mod authoring does not earn another binary target. +public static class ShipAuthoringCommands +{ + public static int Run(string[] args) + { + if (args.Length == 0) + { + Console.Error.WriteLine("ship-authoring create | inspect | validate | compose "); + return 1; + } + try + { + if (args[0] == "compose" && args.Length == 4) + { + var composition = ShipModCatalog.Compose(args[1], args[2], args[3]); + Console.WriteLine($"Composed {composition.Included.Length} mod ships into {Path.GetFullPath(args[2])}"); + foreach (var exclusion in composition.Excluded) Console.Error.WriteLine($"Excluded {exclusion}"); + return composition.Excluded.Length == 0 ? 0 : 1; + } + if (args[0] == "inspect" && args.Length == 2) + { + var (hull, ship) = ShipAuthoringStore.Load(args[1]); + Console.WriteLine($"{ship.Id}: {hull.Name}, {hull.Hardpoints?.Count ?? 0} hardpoints, {ship.SchematicLines?.Count ?? 0} lines, {ship.SchematicLines?.Sum(line => line.Points?.Length / 3 ?? 0) ?? 0} points"); + return 0; + } + if (args[0] == "validate" && args.Length == 2) + { + var (hull, ship) = ShipAuthoringStore.Read(args[1]); + Console.WriteLine($"{ship.Id}: {hull.Name}, {hull.Hardpoints.Count} hardpoints, {ship.SchematicLines.Count} lines"); + return 0; + } + if (args[0] == "create" && args.Length == 4) + { + var path = Path.GetFullPath(args[1]); + if (File.Exists(path)) throw new InvalidOperationException($"Refusing to replace {path}"); + Directory.CreateDirectory(Path.GetDirectoryName(path)); + var ship = new ShipAuthoring { Id = args[2], ModelAsset = "ship.glb", Anchors = new List() }; + var hull = new HullData + { + Name = args[3], + Shape = new Shape(), + Visual = new CultRecordRef(ShipModCatalog.AuthoringKey(ship.Id)) + }; + using (var cache = ShipAuthoringStore.Open(path, writable: true)) + { + ShipAuthoringStore.Write(cache, hull, ship); + cache.FlushAsync().Wait(); + } + Console.WriteLine($"Created draft {path}; fill its model bindings and schematic in Blender."); + return 0; + } + Console.Error.WriteLine("ship-authoring create | inspect | validate | compose "); + return 1; + } + catch (Exception ex) + { + Console.Error.WriteLine(ex.Message); + return 1; + } + } +} diff --git a/tools/blender/.gitignore b/tools/blender/.gitignore new file mode 100644 index 000000000..7a60b85e1 --- /dev/null +++ b/tools/blender/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.pyc diff --git a/tools/blender/aetheria_ships/__init__.py b/tools/blender/aetheria_ships/__init__.py new file mode 100644 index 000000000..1c21ded35 --- /dev/null +++ b/tools/blender/aetheria_ships/__init__.py @@ -0,0 +1,347 @@ +"""Aetheria ship authoring controls in Brokkr's Blender sidebar.""" + +bl_info = { + "name": "Aetheria Ships for Brokkr", + "author": "GameCult", + "version": (0, 1, 0), + "blender": (4, 3, 0), + "location": "View3D > Sidebar > Brokkr > Aetheria Ship", + "description": "Write Grease Pencil ship lines into a typed Aetheria .cc ship record", + "category": "Object", +} + +import bpy + +from .ship_cc import (HARDPOINT_TYPE_NAMES, ROTATION_NAMES, capture_grease_pencil, decode_hardpoint, + encode_hardpoint, read, read_layout, replace_layout, replace_lines) + + +HARDPOINT_TYPES = tuple((str(i), name, name) for i, name in enumerate(HARDPOINT_TYPE_NAMES)) +ROTATIONS = tuple((str(i), name, name) for i, name in enumerate(ROTATION_NAMES)) + + +class AETHERIA_PG_cell(bpy.types.PropertyGroup): + occupied: bpy.props.BoolProperty(name="Occupied") + + +class AETHERIA_PG_hardpoint(bpy.types.PropertyGroup): + mount_id: bpy.props.StringProperty(name="Mount ID") + kind: bpy.props.EnumProperty(name="Type", items=HARDPOINT_TYPES) + x: bpy.props.IntProperty(name="X", min=0, max=31) + y: bpy.props.IntProperty(name="Y", min=0, max=31) + footprint: bpy.props.StringProperty( + name="Footprint", default="#", description="Top-to-bottom rows of # and ., separated by /" + ) + rotation: bpy.props.EnumProperty(name="Rotation", items=ROTATIONS) + armor: bpy.props.FloatProperty(name="Armor", min=0) + firing_arc: bpy.props.FloatProperty(name="Firing Arc", min=0, max=360) + + +class AETHERIA_PG_layout(bpy.types.PropertyGroup): + ship_id: bpy.props.StringProperty() + ship_cc: bpy.props.StringProperty() + revision: bpy.props.StringProperty() + width: bpy.props.IntProperty(default=1) + height: bpy.props.IntProperty(default=1) + new_width: bpy.props.IntProperty(name="Width", default=1, min=1, max=32) + new_height: bpy.props.IntProperty(name="Height", default=1, min=1, max=32) + cells: bpy.props.CollectionProperty(type=AETHERIA_PG_cell) + hardpoints: bpy.props.CollectionProperty(type=AETHERIA_PG_hardpoint) + + +def _footprint(raw): + width, height, cells = raw[0] + return "/".join("".join("#" if cells[x * height + y] else "." for x in range(width)) + for y in range(height - 1, -1, -1)) + + +def _parse_footprint(text): + rows = text.split("/") + width = len(rows[0]) + height = len(rows) + if not (1 <= width <= 32 and 1 <= height <= 32 and + all(len(row) == width and set(row) <= {"#", "."} for row in rows)): + raise ValueError("Footprint must use equal-width #/. rows separated by /") + return [[width, height, [rows[height - 1 - y][x] == "#" + for x in range(width) for y in range(height)]]] + + +def _layout_path(context): + collection = _ship_collection(context) + if not collection.get("aetheria.ship_cc"): + raise ValueError("Ship collection has no bound .cc path") + return collection, bpy.path.abspath(collection["aetheria.ship_cc"]) + + +class AETHERIA_OT_load_layout(bpy.types.Operator): + bl_idname = "aetheria.load_ship_layout" + bl_label = "Load Ship Layout" + bl_options = {"REGISTER"} + + def execute(self, context): + try: + collection, path = _layout_path(context) + shape, hardpoints, revision = read_layout(path, _brokkr_cultlib(context)) + width, height, cells = shape + state = context.scene.aetheria_layout + state.ship_id = collection["aetheria.id"] + state.ship_cc = path + state.revision = revision + state.width = state.new_width = width + state.height = state.new_height = height + state.cells.clear() + for cell in cells: + state.cells.add().occupied = bool(cell) + state.hardpoints.clear() + for raw in hardpoints: + fields = decode_hardpoint(raw) + hp = state.hardpoints.add() + hp.kind = str(fields["Type"]) + hp.x, hp.y = fields["Position"] + hp.footprint = _footprint(fields["Shape"]) + hp.mount_id = fields["Transform"] or "" + hp.rotation = str(fields["Rotation"]) + hp.armor = fields["Armor"] + hp.firing_arc = fields["FiringArc"] + self.report({"INFO"}, f"Loaded {width}x{height} layout and {len(hardpoints)} hardpoints") + return {"FINISHED"} + except (OSError, ValueError, RuntimeError, ImportError, KeyError) as exc: + self.report({"ERROR"}, str(exc)) + return {"CANCELLED"} + + +class AETHERIA_OT_resize_layout(bpy.types.Operator): + bl_idname = "aetheria.resize_ship_layout" + bl_label = "Resize Grid" + bl_options = {"REGISTER", "UNDO"} + + def execute(self, context): + state = context.scene.aetheria_layout + old = [cell.occupied for cell in state.cells] + width, height = state.width, state.height + expanded = [old[x * height + y] if x < width and y < height else False + for x in range(state.new_width) for y in range(state.new_height)] + state.cells.clear() + for cell in expanded: + state.cells.add().occupied = cell + state.width, state.height = state.new_width, state.new_height + return {"FINISHED"} + + +class AETHERIA_OT_add_hardpoint(bpy.types.Operator): + bl_idname = "aetheria.add_ship_hardpoint" + bl_label = "Add Hardpoint" + bl_options = {"REGISTER", "UNDO"} + + def execute(self, context): + context.scene.aetheria_layout.hardpoints.add() + return {"FINISHED"} + + +class AETHERIA_OT_remove_hardpoint(bpy.types.Operator): + bl_idname = "aetheria.remove_ship_hardpoint" + bl_label = "Remove Hardpoint" + bl_options = {"REGISTER", "UNDO"} + index: bpy.props.IntProperty() + + def execute(self, context): + state = context.scene.aetheria_layout + if 0 <= self.index < len(state.hardpoints): + state.hardpoints.remove(self.index) + return {"FINISHED"} + + +class AETHERIA_OT_save_layout(bpy.types.Operator): + bl_idname = "aetheria.save_ship_layout" + bl_label = "Save Layout to .cc" + bl_options = {"REGISTER"} + + def execute(self, context): + try: + collection, path = _layout_path(context) + state = context.scene.aetheria_layout + if state.ship_id != collection["aetheria.id"] or state.ship_cc != path: + raise ValueError("Load this collection's layout before saving") + cells = [cell.occupied for cell in state.cells] + hardpoints = [encode_hardpoint( + Type=int(hp.kind), Position=[hp.x, hp.y], Shape=_parse_footprint(hp.footprint), + Transform=hp.mount_id, Rotation=int(hp.rotation), Armor=hp.armor, FiringArc=hp.firing_arc) + for hp in state.hardpoints] + state.revision = replace_layout( + path, _brokkr_cultlib(context), state.ship_id, state.revision, + [state.width, state.height, cells], hardpoints + ) + self.report({"INFO"}, f"Saved {len(hardpoints)} hardpoints to {path}") + return {"FINISHED"} + except (OSError, ValueError, RuntimeError, ImportError, KeyError) as exc: + self.report({"ERROR"}, str(exc)) + return {"CANCELLED"} + + +def _brokkr_cultlib(context): + brokkr = context.preferences.addons.get("brokkr_bridge") + if brokkr is None: + raise RuntimeError("Enable Brokkr before using Aetheria Ships") + return brokkr.preferences.cultlib_py_src + + +def _ship_collection(context): + obj = context.active_object + if obj is None: + raise ValueError("Select an object in the ship collection") + matches = [collection for collection in bpy.data.collections + if collection.get("aetheria.asset_kind") == "ship" and obj.name in collection.all_objects] + if len(matches) != 1: + raise ValueError("Selected object must belong to exactly one bound ship collection") + return matches[0] + + +class AETHERIA_OT_bind_ship_collection(bpy.types.Operator): + bl_idname = "aetheria.bind_ship_collection" + bl_label = "Bind Ship Collection" + bl_description = "Bind the active collection to one typed ship .cc record" + bl_options = {"REGISTER", "UNDO"} + + def execute(self, context): + try: + if not context.scene.aetheria_ship_cc_path: + raise ValueError("Choose an existing ship authoring .cc file") + obj = context.active_object + if obj is None: + raise ValueError("Select an object in the ship collection") + direct = list(obj.users_collection) + marked = [collection for collection in bpy.data.collections + if collection.get("aetheria.asset_kind") == "ship" and obj.name in collection.all_objects] + if len(marked) == 1: + collection = marked[0] + elif len(marked) == 0 and len(direct) == 1: + collection = direct[0] + else: + raise ValueError("Select an object in exactly one ship collection") + path = bpy.path.abspath(context.scene.aetheria_ship_cc_path) + ship_id = read(path, _brokkr_cultlib(context)).ship.body[0] + if collection.get("aetheria.asset_kind") not in (None, "ship"): + raise ValueError(f"{collection.name} has another aetheria.asset_kind") + if collection.get("aetheria.id") not in (None, ship_id): + raise ValueError(f"{collection.name} is bound to another ship ID") + collection["aetheria.asset_kind"] = "ship" + collection["aetheria.id"] = ship_id + collection["aetheria.ship_cc"] = bpy.path.relpath(path) + self.report({"INFO"}, f"Bound {collection.name} to {ship_id}") + return {"FINISHED"} + except (OSError, ValueError, RuntimeError, ImportError) as exc: + self.report({"ERROR"}, str(exc)) + return {"CANCELLED"} + + +class AETHERIA_OT_capture_ship_lines(bpy.types.Operator): + bl_idname = "aetheria.capture_ship_lines" + bl_label = "Capture Ship Lines" + bl_description = "Replace only the line slot in the selected typed ship .cc record" + bl_options = {"REGISTER"} + + def execute(self, context): + try: + obj = context.active_object + collection = _ship_collection(context) + if not collection.get("aetheria.ship_cc"): + raise ValueError(f"{collection.name} has no bound ship .cc path") + path = bpy.path.abspath(collection["aetheria.ship_cc"]) + cultlib = _brokkr_cultlib(context) + if read(path, cultlib).ship.body[0] != collection["aetheria.id"]: + raise ValueError("The bound collection ID does not match its .cc ship ID") + lines = capture_grease_pencil( + obj, context.evaluated_depsgraph_get(), context.scene.frame_current, + evaluated=context.scene.aetheria_capture_evaluated_lines, + ) + count = replace_lines(path, cultlib, lines) + self.report({"INFO"}, f"Captured {count} lines into {path}") + return {"FINISHED"} + except (OSError, ValueError, RuntimeError, ImportError) as exc: + self.report({"ERROR"}, str(exc)) + return {"CANCELLED"} + + +class AETHERIA_PT_ship(bpy.types.Panel): + bl_label = "Aetheria Ship" + bl_idname = "AETHERIA_PT_ship" + bl_space_type = "VIEW_3D" + bl_region_type = "UI" + bl_category = "Brokkr" + + def draw(self, context): + layout = self.layout + layout.prop(context.scene, "aetheria_ship_cc_path") + layout.operator("aetheria.bind_ship_collection", icon="LINKED") + layout.prop(context.scene, "aetheria_capture_evaluated_lines") + obj = context.active_object + layout.label(text=f"Source: {obj.name if obj else '(none)'}") + try: + collection = _ship_collection(context) + layout.label(text=f"Ship: {collection['aetheria.id']}") + except (ValueError, KeyError): + layout.label(text="No bound ship collection", icon="ERROR") + layout.operator("aetheria.capture_ship_lines", icon="GREASEPENCIL") + + layout.separator() + layout.operator("aetheria.load_ship_layout", icon="IMPORT") + state = context.scene.aetheria_layout + if not state.ship_id: + return + layout.label(text=f"Layout: {state.ship_id}") + dims = layout.row(align=True) + dims.prop(state, "new_width") + dims.prop(state, "new_height") + dims.operator("aetheria.resize_ship_layout", text="Resize") + grid = layout.box() + grid.label(text="Hull cells (top row first)") + if len(state.cells) == state.width * state.height: + for y in range(state.height - 1, -1, -1): + row = grid.row(align=True) + row.label(text=str(y)) + for x in range(state.width): + row.prop(state.cells[x * state.height + y], "occupied", text="") + layout.label(text="Hardpoints") + for index, hp in enumerate(state.hardpoints): + box = layout.box() + header = box.row(align=True) + header.prop(hp, "mount_id") + header.operator("aetheria.remove_ship_hardpoint", text="", icon="X").index = index + box.prop(hp, "kind") + position = box.row(align=True) + position.prop(hp, "x") + position.prop(hp, "y") + box.prop(hp, "footprint") + box.prop(hp, "rotation") + box.prop(hp, "armor") + box.prop(hp, "firing_arc") + layout.operator("aetheria.add_ship_hardpoint", icon="ADD") + layout.operator("aetheria.save_ship_layout", icon="FILE_TICK") + + +classes = (AETHERIA_PG_cell, AETHERIA_PG_hardpoint, AETHERIA_PG_layout, + AETHERIA_OT_load_layout, AETHERIA_OT_resize_layout, + AETHERIA_OT_add_hardpoint, AETHERIA_OT_remove_hardpoint, + AETHERIA_OT_save_layout, AETHERIA_OT_bind_ship_collection, + AETHERIA_OT_capture_ship_lines, AETHERIA_PT_ship) + + +def register(): + for cls in classes: + bpy.utils.register_class(cls) + bpy.types.Scene.aetheria_layout = bpy.props.PointerProperty(type=AETHERIA_PG_layout) + bpy.types.Scene.aetheria_ship_cc_path = bpy.props.StringProperty( + name="Ship .cc", subtype="FILE_PATH", description="Existing typed ship authoring record" + ) + bpy.types.Scene.aetheria_capture_evaluated_lines = bpy.props.BoolProperty( + name="Evaluated LineArt", default=True, + description="Capture the visible modifier result at the current frame", + ) + + +def unregister(): + del bpy.types.Scene.aetheria_layout + for cls in reversed(classes): + bpy.utils.unregister_class(cls) + del bpy.types.Scene.aetheria_capture_evaluated_lines + del bpy.types.Scene.aetheria_ship_cc_path diff --git a/tools/blender/aetheria_ships/ship_cc.py b/tools/blender/aetheria_ships/ship_cc.py new file mode 100644 index 000000000..16f48dbbc --- /dev/null +++ b/tools/blender/aetheria_ships/ship_cc.py @@ -0,0 +1,203 @@ +"""Aetheria's Blender-side view of one ship file: a typed HullData record and the ShipAuthoring visual it names. + +The schemas and authority live in Aetheria's C# HullData and ShipAuthoring types. This module edits the hull's grid +and hardpoints and the visual's lines, and preserves the C# schema catalog and every slot it does not edit. Brokkr +supplies the Blender host and CultLib Python dependency path. +""" + +from __future__ import annotations + +import sys +import hashlib +from dataclasses import replace +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, NamedTuple + +SCHEMA = "aetheria.ship_authoring" +HULL_SCHEMA = "aetheria.hulldata" + +# MessagePack slots of the C# types, which own them (ShipAuthoring, ItemData.Shape, HullData.Hardpoints, +# HardpointData). RETIRED_HULL_SLOT is the ShipAuthoring key that held the embedded hull before S1; no member owns it now. ShipSchemaPinTests in tests/Aetheria.Shared.Tests fails when any number or name below +# disagrees with those types' [Key] attributes, so a renumbered or added member cannot drift silently. +RETIRED_HULL_SLOT = 1 +SCHEMATIC_LINES_SLOT = 4 # ShipAuthoring.SchematicLines +HULL_SHAPE_SLOT = 5 # ItemData.Shape +HULL_HARDPOINTS_SLOT = 23 # HullData.Hardpoints +# HardpointData member names in slot order; a hardpoint row is one value per name, and any slot past the last +# name belongs to a later schema and is carried through untouched. +HARDPOINT_MEMBERS = ("Type", "Position", "Shape", "Transform", "Rotation", "Armor", "FiringArc") +# Enum member names in value order (HardpointType, ItemRotation). +HARDPOINT_TYPE_NAMES = ("Hull", "Tool", "Thermal", "Thruster", "WarpDrive", "Reactor", "Radiator", + "Shield", "Sensors", "Energy", "Ballistic", "Launcher", "ControlModule", "AetherDrive") +ROTATION_NAMES = ("None", "CounterClockwise", "Reversed", "Clockwise") + + +def decode_hardpoint(row: list[Any]) -> dict[str, Any]: + return dict(zip(HARDPOINT_MEMBERS, row)) + + +def encode_hardpoint(**fields: Any) -> list[Any]: + if set(fields) != set(HARDPOINT_MEMBERS): + raise ValueError(f"A hardpoint row needs exactly {', '.join(HARDPOINT_MEMBERS)}") + return [fields[name] for name in HARDPOINT_MEMBERS] + + +def _libraries(cultlib_packages: str): + source = Path(cultlib_packages) / "cultcache-py" / "src" + if source.exists() and str(source) not in sys.path: + sys.path.insert(0, str(source)) + import cultcache_py # type: ignore + import msgpack # type: ignore + return cultcache_py, msgpack + + +class Record(NamedTuple): + envelope: Any + body: list + + +class ShipFile(NamedTuple): + store: Any + ship: Record # the ShipAuthoring visual + hull: Record # the HullData it belongs to + msgpack: Any + + +def read(path: str, cultlib_packages: str) -> ShipFile: + cultcache, msgpack = _libraries(cultlib_packages) + store = cultcache.SingleFileMessagePackBackingStore(path) + envelopes = store.pull_all() + ships = [envelope for envelope in envelopes if envelope.type == SCHEMA] + hulls = [envelope for envelope in envelopes if envelope.type == HULL_SCHEMA] + # Before S1 the hull lived inside the ship record. Saving such a file would preserve the stale hull under a ship that + # no longer reads it, so it is refused before anything else is said about its shape. + for envelope in ships: + body = msgpack.unpackb(envelope.payload, raw=False) + if isinstance(body, list) and len(body) > RETIRED_HULL_SLOT and body[RETIRED_HULL_SLOT] is not None: + raise ValueError( + f"{path}: {envelope.key}: legacy embedded hull at retired key {RETIRED_HULL_SLOT} of the {SCHEMA} record; " + f"migrate it into its own {HULL_SCHEMA} record that names the visual, and drop key {RETIRED_HULL_SLOT}") + if len(envelopes) != 2 or len(ships) != 1 or len(hulls) != 1: + raise ValueError(f"{path} must hold exactly one {SCHEMA} record and one {HULL_SCHEMA} record") + bodies = [] + for envelope in (ships[0], hulls[0]): + body = msgpack.unpackb(envelope.payload, raw=False) + if not isinstance(body, list): + raise ValueError(f"{path} has an incompatible {envelope.type} payload") + bodies.append(Record(envelope, body)) + ship, hull = bodies + if len(ship.body) < SCHEMATIC_LINES_SLOT + 1: + raise ValueError(f"{path} has an incompatible {SCHEMA} payload") + return ShipFile(store, ship, hull, msgpack) + + +def _stamped(record: Record, msgpack: Any): + return replace( + record.envelope, + payload=msgpack.packb(record.body, use_bin_type=True), + stored_at=datetime.now(timezone.utc).isoformat(), + ) + + +def replace_lines(path: str, cultlib_packages: str, lines: list[list[Any]]) -> int: + file = read(path, cultlib_packages) + if not lines: + raise ValueError("No Grease Pencil strokes were captured; the ship record was not changed") + file.ship.body[SCHEMATIC_LINES_SLOT] = lines + file.store.push(_stamped(file.ship, file.msgpack)) + return len(lines) + + +def _hull_body(file: ShipFile) -> list: + if len(file.hull.body) <= HULL_HARDPOINTS_SLOT: + raise ValueError("Ship hull has an incompatible typed payload") + return file.hull.body + + +def read_layout(path: str, cultlib_packages: str): + file = read(path, cultlib_packages) + hull = _hull_body(file) + return hull[HULL_SHAPE_SLOT][0], hull[HULL_HARDPOINTS_SLOT], _layout_revision(hull, file.msgpack) + + +def _layout_revision(hull, msgpack): + return hashlib.sha256(msgpack.packb( + [hull[HULL_SHAPE_SLOT], hull[HULL_HARDPOINTS_SLOT]], use_bin_type=True + )).hexdigest() + + +def replace_layout(path: str, cultlib_packages: str, expected_id: str, expected_revision: str, + shape: list[Any], hardpoints: list[list[Any]]) -> str: + file = read(path, cultlib_packages) + if file.ship.body[0] != expected_id: + raise ValueError("The bound ship ID changed; reload its layout") + hull = _hull_body(file) + if _layout_revision(hull, file.msgpack) != expected_revision: + raise ValueError("The .cc layout changed since Load; reload before saving") + width, height, cells = shape + if not (1 <= width <= 32 and 1 <= height <= 32 and len(cells) == width * height): + raise ValueError("Hull grid must be 1..32 cells wide and high with one value per cell") + if not all(type(cell) is bool for cell in cells): + raise ValueError("Hull grid cells must be booleans") + if not any(cells): + raise ValueError("Hull grid needs an occupied cell") + known = len(HARDPOINT_MEMBERS) + previous = {decode_hardpoint(hp)["Transform"]: hp[known:] for hp in hull[HULL_HARDPOINTS_SLOT] + if isinstance(hp, list) and len(hp) > known and isinstance(decode_hardpoint(hp)["Transform"], str)} + updated_hardpoints = [] + for hardpoint in hardpoints: + fields = decode_hardpoint(hardpoint) + mount = fields.get("Transform") + if len(hardpoint) != known or not isinstance(mount, str) or not mount: + raise ValueError(f"Each hardpoint needs {known} typed fields and a stable mount ID") + hp_width, hp_height, hp_cells = fields["Shape"][0] + if not all(type(cell) is bool for cell in hp_cells): + raise ValueError(f"Hardpoint {mount} footprint cells must be booleans") + if not (1 <= hp_width <= 32 and 1 <= hp_height <= 32 and + len(hp_cells) == hp_width * hp_height and any(hp_cells)): + raise ValueError(f"Hardpoint {mount} has an invalid footprint") + updated_hardpoints.append(hardpoint + previous.get(mount, [])) + hull[HULL_SHAPE_SLOT] = [shape] + hull[HULL_HARDPOINTS_SLOT] = updated_hardpoints + file.store.push(_stamped(file.hull, file.msgpack)) + return _layout_revision(hull, file.msgpack) + + +def capture_grease_pencil(obj: Any, depsgraph: Any, frame_number: int, *, evaluated: bool = True) -> list[list[Any]]: + if obj.type != "GREASEPENCIL": + raise ValueError(f"{obj.name} is not a Grease Pencil object") + source = obj.evaluated_get(depsgraph) if evaluated else obj + lines: list[list[Any]] = [] + for layer in source.data.layers: + frames = [frame for frame in layer.frames if frame.frame_number <= frame_number] + if not frames: + continue + frame = max(frames, key=lambda candidate: candidate.frame_number) + for stroke in frame.drawing.strokes: + if len(stroke.points) < 2: + continue + material = source.data.materials[stroke.material_index] + rgba = ( + tuple(material.grease_pencil.color) + if material and material.grease_pencil + else tuple(material.diffuse_color) if material else (1.0, 1.0, 1.0, 1.0) + ) + points: list[float] = [] + radii: list[float] = [] + opacities: list[float] = [] + for point in stroke.points: + position = obj.matrix_world @ point.position + points.extend(float(value) for value in position) + radii.append(float(point.radius)) + opacities.append(float(point.opacity)) + lines.append([ + layer.name, + material.name if material else "", + points, + radii, + opacities, + bool(stroke.cyclic), + [float(value) for value in rgba], + ]) + return lines diff --git a/tools/blender/tests/test_ship_cc.py b/tools/blender/tests/test_ship_cc.py new file mode 100644 index 000000000..0ab0c9877 --- /dev/null +++ b/tools/blender/tests/test_ship_cc.py @@ -0,0 +1,542 @@ +"""Blender-free tests for aetheria_ships/ship_cc.py, the Python view of a ship file's HullData and ShipAuthoring records. + +Run with CultLib's cultcache-py and msgpack importable: + + CULTLIB_PACKAGES=/packages python -m unittest discover -s tools/blender/tests + +ship_cc is loaded by path because the package __init__ imports bpy. The record layout the tests build comes from +ship_cc's own slot constants; ShipSchemaPinTests (C#) pins those constants to the C# [Key] attributes. +""" + +import dataclasses +import importlib.util +import os +import shutil +import sys +import tempfile +import unittest +from datetime import datetime +from pathlib import Path +from types import SimpleNamespace + +PACKAGES = os.environ.get("CULTLIB_PACKAGES") +if not PACKAGES: + raise RuntimeError("Set CULTLIB_PACKAGES to CultLib's packages directory") + +_spec = importlib.util.spec_from_file_location( + "ship_cc", Path(__file__).resolve().parents[1] / "aetheria_ships" / "ship_cc.py") +ship_cc = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(ship_cc) + +sys.path.insert(0, str(Path(PACKAGES) / "cultcache-py" / "src")) +import cultcache_py # noqa: E402 +import msgpack # noqa: E402 + + +def shape(width, height, cells): + return [width, height, cells] + + +def hardpoint_row(mount="thruster.port", tail=("future-hardpoint-slot",)): + row = ship_cc.encode_hardpoint( + Type=3, Position=[1, 0], Shape=[shape(1, 1, [True])], Transform=mount, Rotation=0, Armor=0.0, FiringArc=0.0) + return row + list(tail) + + +def hull_body(): + hull = [None] * (ship_cc.HULL_HARDPOINTS_SLOT + 1) + hull[1] = "Skiff" + hull[ship_cc.HULL_SHAPE_SLOT] = [shape(2, 2, [True, False, True, False])] + hull[ship_cc.HULL_HARDPOINTS_SLOT] = [hardpoint_row()] + hull.append("future-hull-slot") + return hull + + +LINES = [["Hull", "White", [0.0, 0.0, 0.0, 1.0, 0.0, 0.0], [0.01, 0.01], [1.0, 1.0], False, [1.0, 1.0, 1.0, 1.0]]] + + +def ship_body(): + body = [None] * (ship_cc.SCHEMATIC_LINES_SLOT + 1) + body[0] = "mod.skiff" + body[2] = "skiff.glb" + body[3] = [["map", "map-icon", "map", None, 0]] + body[ship_cc.SCHEMATIC_LINES_SLOT] = LINES + return body + + +def catalog(schema_id, schema_name): + return cultcache_py.CultCacheSchemaCatalogEntry( + schema_id=schema_id, schema_name=schema_name, schema_version="1", + content_hash="hash", canonical_schema_json='{"members":[{"slot":9,"name":"FutureMember"}]}', + compatible_schema_ids=(schema_id,), + members=(cultcache_py.CultCacheSchemaCatalogMember(slot=9, member_name="FutureMember", type_name="string"),)) + + +CATALOG = catalog("ship-authoring-schema-1", ship_cc.SCHEMA) +HULL_CATALOG = catalog("hull-schema-1", ship_cc.HULL_SCHEMA) + + +def envelope(key, schema, entry, body): + return cultcache_py.CultCacheEnvelope.create( + key=key, type=schema, payload=msgpack.packb(body, use_bin_type=True), + schema_id=entry.schema_id, catalog_entry=entry) + + +class ShipFileCase(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.path = str(Path(directory.name) / "ship.cc") + self.write(ship_body(), hull_body()) + + def write(self, ship, hull, path=None): + cultcache_py.SingleFileMessagePackBackingStore(path or self.path).push_all([ + envelope("mod-ship:mod.skiff", ship_cc.SCHEMA, CATALOG, ship), + envelope("mod-hull:mod.skiff", ship_cc.HULL_SCHEMA, HULL_CATALOG, hull)]) + + def ship(self): + return ship_cc.read(self.path, PACKAGES).ship.body + + def hull(self): + return ship_cc.read(self.path, PACKAGES).hull.body + + def envelopes(self): + return {(e.type, e.key): e for e in cultcache_py.SingleFileMessagePackBackingStore(self.path).pull_all()} + + def bytes(self): + return Path(self.path).read_bytes() + + +class ReadTests(ShipFileCase): + def test_reads_the_ship_and_its_hull(self): + file = ship_cc.read(self.path, PACKAGES) + self.assertEqual("mod.skiff", file.ship.body[0]) + self.assertEqual(ship_cc.SCHEMA, file.ship.envelope.type) + self.assertEqual("Skiff", file.hull.body[1]) + self.assertEqual(ship_cc.HULL_SCHEMA, file.hull.envelope.type) + + def test_refuses_a_file_with_another_record_beside_the_pair(self): + cultcache_py.SingleFileMessagePackBackingStore(self.path).push(cultcache_py.CultCacheEnvelope.create( + key="other", type="aetheria.something", payload=msgpack.packb([1], use_bin_type=True))) + with self.assertRaisesRegex(ValueError, "must hold exactly one"): + ship_cc.read(self.path, PACKAGES) + + def test_refuses_a_file_missing_either_half_of_the_pair(self): + for name, schema, entry, body in (("hull only", ship_cc.HULL_SCHEMA, HULL_CATALOG, hull_body()), + ("ship only", ship_cc.SCHEMA, CATALOG, ship_body())): + other = str(Path(self.path).with_name(name.replace(" ", "-") + ".cc")) + cultcache_py.SingleFileMessagePackBackingStore(other).push(envelope("key", schema, entry, body)) + with self.subTest(name): + with self.assertRaisesRegex(ValueError, "must hold exactly one"): + ship_cc.read(other, PACKAGES) + + def test_refuses_a_file_with_two_hulls(self): + cultcache_py.SingleFileMessagePackBackingStore(self.path).push( + envelope("mod-hull:mod.other", ship_cc.HULL_SCHEMA, HULL_CATALOG, hull_body())) + with self.assertRaisesRegex(ValueError, "must hold exactly one"): + ship_cc.read(self.path, PACKAGES) + + def test_refuses_a_file_with_no_record(self): + empty = str(Path(self.path).with_name("empty.cc")) + Path(empty).write_bytes(b"") + with self.assertRaisesRegex(ValueError, "must hold exactly one"): + ship_cc.read(empty, PACKAGES) + + def test_refuses_a_ship_record_that_still_carries_the_retired_embedded_hull(self): + for name, ship in (("nested hull", ["mod.skiff", hull_body()]), + ("any value", ["mod.skiff", 0])): + body = ship_body() + body[ship_cc.RETIRED_HULL_SLOT] = ship[1] + with self.subTest(name): + self.write(body, hull_body()) + with self.assertRaisesRegex(ValueError, "legacy embedded hull at retired key 1"): + ship_cc.read(self.path, PACKAGES) + # Nothing else is said about its shape: an old file has no hull record beside the ship. + cultcache_py.SingleFileMessagePackBackingStore(self.path).push_all( + [envelope("mod-ship:mod.skiff", ship_cc.SCHEMA, CATALOG, body)]) + with self.assertRaisesRegex(ValueError, "legacy embedded hull"): + ship_cc.read(self.path, PACKAGES) + + def test_refuses_a_save_over_a_file_with_the_retired_embedded_hull_and_writes_nothing(self): + body = ship_body() + body[ship_cc.RETIRED_HULL_SLOT] = hull_body() + self.write(body, hull_body()) + before = self.bytes() + with self.assertRaisesRegex(ValueError, "legacy embedded hull"): + ship_cc.replace_lines(self.path, PACKAGES, LINES) + with self.assertRaisesRegex(ValueError, "legacy embedded hull"): + ship_cc.replace_layout(self.path, PACKAGES, "mod.skiff", "any", [2, 2, [True] * 4], []) + self.assertEqual(before, self.bytes()) + + def test_a_nil_in_the_retired_slot_is_the_current_shape(self): + self.assertIsNone(self.ship()[ship_cc.RETIRED_HULL_SLOT]) + + def test_refuses_a_ship_payload_too_short_for_the_line_slot(self): + for body in (["mod.skiff"], ["mod.skiff", None]): + with self.subTest(slots=len(body)): + self.write(body, hull_body()) + with self.assertRaisesRegex(ValueError, "incompatible"): + ship_cc.read(self.path, PACKAGES) + + def test_refuses_a_payload_that_is_not_an_array(self): + for payload in ({"Id": "mod.skiff"}, {str(index): index for index in range(9)}, "a string long enough to fill every slot"): + with self.subTest(ship=payload): + self.write(payload, hull_body()) + with self.assertRaisesRegex(ValueError, "incompatible"): + ship_cc.read(self.path, PACKAGES) + with self.subTest(hull=payload): + self.write(ship_body(), payload) + with self.assertRaisesRegex(ValueError, "incompatible"): + ship_cc.read(self.path, PACKAGES) + + +class ReplaceLinesTests(ShipFileCase): + def test_replaces_only_the_line_slot(self): + new_lines = [["Detail", "Red", [0.0] * 6, [0.1, 0.1], [1.0, 1.0], True, [1.0, 0.0, 0.0, 1.0]]] + before = self.ship() + self.assertEqual(1, ship_cc.replace_lines(self.path, PACKAGES, new_lines)) + after = self.ship() + self.assertEqual(new_lines, after[ship_cc.SCHEMATIC_LINES_SLOT]) + for slot in range(len(before)): + if slot != ship_cc.SCHEMATIC_LINES_SLOT: + self.assertEqual(before[slot], after[slot], f"slot {slot} changed") + + def test_a_save_refreshes_the_stored_at_of_the_record_it_writes_and_only_that_one(self): + stale = "2000-01-01T00:00:00+00:00" + envelopes = self.envelopes() + cultcache_py.SingleFileMessagePackBackingStore(self.path).push_all( + [dataclasses.replace(envelopes[key], stored_at=stale) for key in envelopes]) + ship_cc.replace_lines(self.path, PACKAGES, LINES) + after = self.envelopes() + self.assertGreater(datetime.fromisoformat(after[(ship_cc.SCHEMA, "mod-ship:mod.skiff")].stored_at), + datetime.fromisoformat(stale)) + self.assertEqual(stale, after[(ship_cc.HULL_SCHEMA, "mod-hull:mod.skiff")].stored_at) + + def test_leaves_the_hull_record_byte_identical(self): + before = self.envelopes()[(ship_cc.HULL_SCHEMA, "mod-hull:mod.skiff")] + ship_cc.replace_lines(self.path, PACKAGES, LINES) + self.assertEqual(before, self.envelopes()[(ship_cc.HULL_SCHEMA, "mod-hull:mod.skiff")]) + + def test_keeps_the_schema_catalog(self): + ship_cc.replace_lines(self.path, PACKAGES, LINES) + envelope = self.envelopes()[(ship_cc.SCHEMA, "mod-ship:mod.skiff")] + self.assertEqual(CATALOG.members, envelope.catalog_entry.members) + self.assertEqual(CATALOG.canonical_schema_json, envelope.catalog_entry.canonical_schema_json) + + def test_refuses_an_empty_capture_and_changes_nothing(self): + before = self.bytes() + with self.assertRaisesRegex(ValueError, "No Grease Pencil strokes"): + ship_cc.replace_lines(self.path, PACKAGES, []) + self.assertEqual(before, self.bytes()) + + +class LayoutTests(ShipFileCase): + def layout(self): + return ship_cc.read_layout(self.path, PACKAGES) + + def edit(self, revision, width=2, height=2, cells=None, hardpoints=None, ship_id="mod.skiff"): + return ship_cc.replace_layout( + self.path, PACKAGES, ship_id, revision, + [width, height, cells if cells is not None else [True, True, True, False]], + hardpoints if hardpoints is not None else [hardpoint_row(tail=())]) + + def test_reads_the_shape_hardpoints_and_a_revision(self): + shape_triple, hardpoints, revision = self.layout() + self.assertEqual([2, 2, [True, False, True, False]], shape_triple) + self.assertEqual("thruster.port", ship_cc.decode_hardpoint(hardpoints[0])["Transform"]) + self.assertEqual(64, len(revision)) + + def test_the_revision_follows_the_layout_and_only_the_layout(self): + _, _, revision = self.layout() + ship = self.ship() + ship[ship_cc.SCHEMATIC_LINES_SLOT] = [] + hull = self.hull() + hull[1] = "Renamed" + self.write(ship, hull) + self.assertEqual(revision, self.layout()[2]) + hull[ship_cc.HULL_SHAPE_SLOT] = [shape(2, 2, [True, True, True, True])] + self.write(ship, hull) + self.assertNotEqual(revision, self.layout()[2]) + + def test_the_revision_follows_the_hardpoints_too(self): + _, _, revision = self.layout() + moved = hardpoint_row(tail=()) + moved[1] = [0, 0] + same_cells = [True, False, True, False] + self.assertEqual(revision, self.edit(revision, cells=same_cells, hardpoints=[hardpoint_row(tail=())])) + self.assertNotEqual(revision, self.edit(revision, cells=same_cells, hardpoints=[moved])) + + def test_saves_the_layout_and_returns_the_new_revision(self): + _, _, revision = self.layout() + moved = hardpoint_row(tail=()) + moved[1] = [0, 0] + returned = self.edit(revision, cells=[True, True, True, False], hardpoints=[moved]) + shape_triple, hardpoints, saved = self.layout() + self.assertEqual([2, 2, [True, True, True, False]], shape_triple) + self.assertEqual([0, 0], ship_cc.decode_hardpoint(hardpoints[0])["Position"]) + self.assertEqual(saved, returned) + self.assertNotEqual(revision, returned) + + def test_preserves_every_slot_it_does_not_edit(self): + _, _, revision = self.layout() + ship_before, hull_before = self.ship(), self.hull() + ship_envelope = self.envelopes()[(ship_cc.SCHEMA, "mod-ship:mod.skiff")] + self.edit(revision) + self.assertEqual(ship_before, self.ship()) + self.assertEqual(ship_envelope, self.envelopes()[(ship_cc.SCHEMA, "mod-ship:mod.skiff")]) + hull_after = self.hull() + self.assertEqual(len(hull_before), len(hull_after)) + for slot in range(len(hull_before)): + if slot not in (ship_cc.HULL_SHAPE_SLOT, ship_cc.HULL_HARDPOINTS_SLOT): + self.assertEqual(hull_before[slot], hull_after[slot], f"hull slot {slot} changed") + + def test_carries_a_later_schemas_hardpoint_slots_by_mount_id(self): + _, _, revision = self.layout() + starboard = hardpoint_row("thruster.starboard", tail=()) + self.edit(revision, hardpoints=[starboard, hardpoint_row(tail=())]) + rows = self.layout()[1] + self.assertEqual(["thruster.starboard", "thruster.port"], [ship_cc.decode_hardpoint(row)["Transform"] for row in rows]) + self.assertEqual(len(ship_cc.HARDPOINT_MEMBERS), len(rows[0])) + self.assertEqual(["future-hardpoint-slot"], rows[1][len(ship_cc.HARDPOINT_MEMBERS):]) + + def test_drops_the_row_of_a_removed_mount(self): + _, _, revision = self.layout() + self.edit(revision, hardpoints=[]) + self.assertEqual([], self.layout()[1]) + + def test_keeps_the_schema_catalog(self): + _, _, revision = self.layout() + self.edit(revision) + envelope = self.envelopes()[(ship_cc.HULL_SCHEMA, "mod-hull:mod.skiff")] + self.assertEqual(HULL_CATALOG.members, envelope.catalog_entry.members) + + def test_refuses_a_ship_id_that_changed_and_writes_nothing(self): + _, _, revision = self.layout() + before = self.bytes() + with self.assertRaisesRegex(ValueError, "bound ship ID changed"): + self.edit(revision, ship_id="mod.other") + self.assertEqual(before, self.bytes()) + + def test_refuses_a_stale_revision_and_writes_nothing(self): + _, _, revision = self.layout() + self.edit(revision) + before = self.bytes() + with self.assertRaisesRegex(ValueError, "layout changed since Load"): + self.edit(revision) + self.assertEqual(before, self.bytes()) + + def test_refuses_grid_sizes_outside_one_to_thirty_two_and_writes_nothing(self): + _, _, revision = self.layout() + before = self.bytes() + for width, height in ((0, 2), (2, 0), (33, 1), (1, 33)): + with self.subTest(width=width, height=height): + with self.assertRaisesRegex(ValueError, "1..32 cells"): + self.edit(revision, width=width, height=height, cells=[True] * (width * height)) + for width, height in ((1, 1), (32, 32)): + with self.subTest(width=width, height=height): + self.edit(revision, width=width, height=height, cells=[True] * (width * height), hardpoints=[]) + revision = self.layout()[2] + self.assertNotEqual(before, self.bytes()) + + def test_a_layout_save_refreshes_the_stored_at_of_the_hull_and_leaves_the_ships(self): + stale = "2000-01-01T00:00:00+00:00" + envelopes = self.envelopes() + cultcache_py.SingleFileMessagePackBackingStore(self.path).push_all( + [dataclasses.replace(envelopes[key], stored_at=stale) for key in envelopes]) + self.edit(self.layout()[2]) + after = self.envelopes() + self.assertGreater(datetime.fromisoformat(after[(ship_cc.HULL_SCHEMA, "mod-hull:mod.skiff")].stored_at), + datetime.fromisoformat(stale)) + self.assertEqual(stale, after[(ship_cc.SCHEMA, "mod-ship:mod.skiff")].stored_at) + + def test_refuses_cells_that_are_not_booleans_and_writes_nothing(self): + _, _, revision = self.layout() + before = self.bytes() + for name, cells in (("integer", [True, 1, True, False]), ("zero", [True, True, True, 0]), + ("string", [True, "x", True, False]), ("none", [True, None, True, False])): + with self.subTest(name): + with self.assertRaisesRegex(ValueError, "Hull grid cells must be booleans"): + self.edit(revision, cells=cells) + self.assertEqual(before, self.bytes()) + + def test_refuses_hardpoint_footprint_cells_that_are_not_booleans_and_writes_nothing(self): + _, _, revision = self.layout() + before = self.bytes() + for name, cells in (("integer", [1, True]), ("none", [True, None])): + row = ship_cc.encode_hardpoint(**{**ship_cc.decode_hardpoint(hardpoint_row(tail=())), + "Shape": [shape(2, 1, cells)]}) + with self.subTest(name): + with self.assertRaisesRegex(ValueError, "thruster.port footprint cells must be booleans"): + self.edit(revision, hardpoints=[row]) + self.assertEqual(before, self.bytes()) + + def test_refuses_a_cell_count_that_does_not_fill_the_grid(self): + _, _, revision = self.layout() + before = self.bytes() + with self.assertRaisesRegex(ValueError, "1..32 cells"): + self.edit(revision, cells=[True, True, True]) + self.assertEqual(before, self.bytes()) + + def test_refuses_a_grid_with_no_occupied_cell(self): + _, _, revision = self.layout() + with self.assertRaisesRegex(ValueError, "needs an occupied cell"): + self.edit(revision, cells=[False] * 4) + + def test_refuses_a_hardpoint_row_of_the_wrong_arity_or_without_a_mount_id(self): + _, _, revision = self.layout() + before = self.bytes() + row = hardpoint_row(tail=()) + for name, bad in (("short", row[:-1]), ("long", row + [0]), + ("blank", ship_cc.encode_hardpoint(**{**ship_cc.decode_hardpoint(row), "Transform": ""})), + ("none", ship_cc.encode_hardpoint(**{**ship_cc.decode_hardpoint(row), "Transform": None})), + ("number", ship_cc.encode_hardpoint(**{**ship_cc.decode_hardpoint(row), "Transform": 4}))): + with self.subTest(name): + with self.assertRaisesRegex(ValueError, "stable mount ID"): + self.edit(revision, hardpoints=[bad]) + self.assertEqual(before, self.bytes()) + + def test_refuses_a_hardpoint_footprint_that_is_not_a_filled_grid_of_one_to_thirty_two(self): + _, _, revision = self.layout() + before = self.bytes() + for name, footprint in (("no width", shape(0, 1, [])), ("no height", shape(1, 0, [])), + ("too wide", shape(33, 1, [True] * 33)), ("too tall", shape(1, 33, [True] * 33)), + ("short", shape(2, 1, [True])), ("empty", shape(1, 1, [False]))): + row = ship_cc.encode_hardpoint(**{**ship_cc.decode_hardpoint(hardpoint_row(tail=())), "Shape": [footprint]}) + with self.subTest(name): + with self.assertRaisesRegex(ValueError, "thruster.port has an invalid footprint"): + self.edit(revision, hardpoints=[row]) + self.assertEqual(before, self.bytes()) + + def test_refuses_a_hull_payload_without_the_hardpoint_slot(self): + hull = self.hull()[:ship_cc.HULL_HARDPOINTS_SLOT] + self.write(self.ship(), hull) + with self.assertRaisesRegex(ValueError, "incompatible typed payload"): + self.layout() + + +@unittest.skipUnless(os.environ.get("SHIP_FIXTURE_DIR"), "SHIP_FIXTURE_DIR names the C#-written fixture (see below)") +class CSharpWrittenFixtureTests(unittest.TestCase): + """Gate 1's Python half: a package C# wrote survives a Python edit with every untouched slot intact. + + The fixture comes from the C# suite (`AETHERIA_SHIP_FIXTURE_DIR= dotnet test ... --filter + TheFixturePackageIsCompleteAndItsGlbCarriesAScene`). Point SHIP_FIXTURE_DIR at that and, optionally, + SHIP_EDITED_DIR at an empty directory to keep the edited package; C# then reopens and validates it with + `dotnet run --project tools/AetherDb -- ship-authoring validate /mod.skiff/ship.cc`. + """ + + def test_a_layout_and_line_edit_preserves_every_slot_it_does_not_own(self): + with tempfile.TemporaryDirectory() as scratch: + path = str(Path(scratch) / "ship.cc") + shutil.copy(Path(os.environ["SHIP_FIXTURE_DIR"]) / "mod.skiff" / "ship.cc", path) + before = ship_cc.read(path, PACKAGES) + shape_triple, hardpoints, revision = ship_cc.read_layout(path, PACKAGES) + width, height, cells = shape_triple + self.assertEqual(64, len(revision)) + cells = list(cells) + cells[-1] = True + ship_cc.replace_layout(path, PACKAGES, before.ship.body[0], revision, [width, height, cells], hardpoints) + ship_cc.replace_lines(path, PACKAGES, before.ship.body[ship_cc.SCHEMATIC_LINES_SLOT]) + after = ship_cc.read(path, PACKAGES) + + self.assertEqual(before.ship.body, after.ship.body) + self.assertEqual(before.ship.envelope.key, after.ship.envelope.key) + self.assertEqual(before.ship.envelope.catalog_entry, after.ship.envelope.catalog_entry) + self.assertEqual(before.hull.envelope.key, after.hull.envelope.key) + self.assertEqual(before.hull.envelope.catalog_entry, after.hull.envelope.catalog_entry) + for slot in range(len(before.hull.body)): + if slot != ship_cc.HULL_SHAPE_SLOT: + self.assertEqual(before.hull.body[slot], after.hull.body[slot], f"hull slot {slot} changed") + self.assertTrue(after.hull.body[ship_cc.HULL_SHAPE_SLOT][0][2][-1]) + + kept = os.environ.get("SHIP_EDITED_DIR") + if kept: + target = Path(kept) / "mod.skiff" + target.mkdir(parents=True, exist_ok=True) + shutil.copy(path, target / "ship.cc") + shutil.copy(Path(os.environ["SHIP_FIXTURE_DIR"]) / "mod.skiff" / "skiff.glb", target / "skiff.glb") + + +class HardpointRowTests(unittest.TestCase): + def test_a_row_is_one_value_per_member_in_slot_order(self): + fields = dict(Type=1, Position=[2, 3], Shape="shape", Transform="mount", Rotation=2, Armor=4.0, FiringArc=90.0) + row = ship_cc.encode_hardpoint(**fields) + self.assertEqual([fields[name] for name in ship_cc.HARDPOINT_MEMBERS], row) + self.assertEqual(fields, ship_cc.decode_hardpoint(row)) + + def test_encoding_needs_every_member_and_no_other(self): + good = dict.fromkeys(ship_cc.HARDPOINT_MEMBERS, 0) + with self.assertRaises(ValueError): + ship_cc.encode_hardpoint(**{name: 0 for name in ship_cc.HARDPOINT_MEMBERS[1:]}) + with self.assertRaises(ValueError): + ship_cc.encode_hardpoint(**good, Extra=1) + + +class Matrix: + """Stands in for mathutils.Matrix: a translation by (10, 20, 30).""" + + def __matmul__(self, position): + return tuple(value + offset for value, offset in zip(position, (10.0, 20.0, 30.0))) + + +def point(x, radius=0.5, opacity=1.0): + return SimpleNamespace(position=(x, 0.0, 0.0), radius=radius, opacity=opacity) + + +def stroke(points, material_index=0, cyclic=False): + return SimpleNamespace(points=points, material_index=material_index, cyclic=cyclic) + + +def frame(number, strokes): + return SimpleNamespace(frame_number=number, drawing=SimpleNamespace(strokes=strokes)) + + +def layer(name, frames): + return SimpleNamespace(name=name, frames=frames) + + +def grease_pencil(layers, materials): + return SimpleNamespace(type="GREASEPENCIL", matrix_world=Matrix(), data=SimpleNamespace(layers=layers, materials=materials)) + + +class CaptureTests(unittest.TestCase): + def test_refuses_an_object_that_is_not_grease_pencil(self): + with self.assertRaisesRegex(ValueError, "is not a Grease Pencil object"): + ship_cc.capture_grease_pencil(SimpleNamespace(type="MESH", name="Cube"), None, 1) + + def test_captures_the_latest_frame_at_or_before_the_current_one(self): + materials = [SimpleNamespace(name="Ink", grease_pencil=SimpleNamespace(color=(0.1, 0.2, 0.3, 1.0)))] + obj = grease_pencil([layer("Hull", [frame(1, [stroke([point(1.0), point(2.0)])]), + frame(5, [stroke([point(3.0), point(4.0)])]), + frame(9, [stroke([point(5.0), point(6.0)])])])], materials) + lines = ship_cc.capture_grease_pencil(obj, None, 5, evaluated=False) + self.assertEqual([["Hull", "Ink", [13.0, 20.0, 30.0, 14.0, 20.0, 30.0], [0.5, 0.5], [1.0, 1.0], False, + [0.1, 0.2, 0.3, 1.0]]], lines) + self.assertEqual(13.0, ship_cc.capture_grease_pencil(obj, None, 6, evaluated=False)[0][2][0]) + self.assertEqual(11.0, ship_cc.capture_grease_pencil(obj, None, 1, evaluated=False)[0][2][0]) + + def test_skips_layers_without_a_frame_yet_and_strokes_of_one_point(self): + obj = grease_pencil([layer("Later", [frame(7, [stroke([point(1.0), point(2.0)])])]), + layer("Now", [frame(1, [stroke([point(1.0)]), stroke([point(1.0), point(2.0)], cyclic=True)])])], + [SimpleNamespace(name="Plain", grease_pencil=None, diffuse_color=(0.4, 0.5, 0.6, 1.0))]) + lines = ship_cc.capture_grease_pencil(obj, None, 3, evaluated=False) + self.assertEqual(1, len(lines)) + self.assertEqual(["Now", "Plain"], lines[0][:2]) + self.assertTrue(lines[0][5]) + self.assertEqual([0.4, 0.5, 0.6, 1.0], lines[0][6]) + + def test_a_stroke_without_a_material_is_white_and_unnamed(self): + obj = grease_pencil([layer("Hull", [frame(1, [stroke([point(1.0), point(2.0)])])])], [None]) + line = ship_cc.capture_grease_pencil(obj, None, 1, evaluated=False)[0] + self.assertEqual(["Hull", ""], line[:2]) + self.assertEqual([1.0, 1.0, 1.0, 1.0], line[6]) + + def test_reads_strokes_from_the_evaluated_copy_but_transforms_by_the_source_object(self): + evaluated = grease_pencil([layer("Baked", [frame(1, [stroke([point(1.0), point(2.0)])])])], [None]) + source = grease_pencil([layer("Raw", [frame(1, [stroke([point(1.0), point(2.0)])])])], [None]) + source.evaluated_get = lambda depsgraph: evaluated + self.assertEqual("Baked", ship_cc.capture_grease_pencil(source, "graph", 1)[0][0]) + self.assertEqual("Raw", ship_cc.capture_grease_pencil(source, "graph", 1, evaluated=False)[0][0]) + + +if __name__ == "__main__": + unittest.main()