Merge master into eureka/aetheria-release-scenarios: adopt the scenarios lane onto master's base

The one conflict is AetheriaStores.CatalogTypes: keep ShipAuthoring from the
ships lane and Scenario from the scenarios lane.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-03 14:53:29 +02:00
commit 2d39c83504
47 changed files with 5005 additions and 12 deletions

View file

@ -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 <project> -executeMethod ShipModPlaySmoke.Run
// -shipModPath <mods>/<id>/ship.cc [-shippedCatalog GameData/Aetheria.cc] -logFile <log>
//
// 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 <package/ship.cc> 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<HullData>().Single(candidate => candidate.Visual.IsSet() && candidate.Name == package.Hull.Name);
zone = new GameObject("Play Smoke Zone");
var ship = ShipModShips.Instantiate(hull, zone.transform).GetComponent<ShipInstance>();
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<MeshCollider>();
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);
}
}
}

View file

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

View file

@ -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 <package/ship.cc> [-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 <package/ship.cc> 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<ShipModTemplate>(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<ShipInstance>();
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<MeshCollider>() != 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); }
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4d32248a66f6454a9be20458fa43f3ef

View file

@ -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<ShipModCatalog.Exclusion>();
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;
}
}

View file

@ -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<CultRecordKey, GameObject> Prototypes = new Dictionary<CultRecordKey, GameObject>();
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<HullData>().Where(hull => hull.Visual.IsSet()).ToArray();
if (hulls.Length == 0) return;
var template = EngineAssets.Load<ShipModTemplate>(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<MeshRenderer>(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<MeshFilter>();
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<MeshRenderer>();
if (hullRenderer != null) hullRenderer.forceRenderingOff = true;
var collider = AddOrGet<MeshCollider>(hullNode.gameObject);
collider.sharedMesh = hullMesh;
collider.convex = true;
var surface = AddOrGet<HullCollider>(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<ShieldManager>(), shieldMarker, false);
Reset(shield.transform);
AddOrGet<ShieldEnvelope>(shield.gameObject);
var tractor = Object.Instantiate(template.TractorBeam.GetComponent<TractorBeam>(), Node(plan.Tractor), false);
Reset(tractor.transform);
var thrusters = plan.Thrusters.Select(id =>
{
var hardpoint = AddOrGet<ThrusterHardpoint>(Node(id).gameObject);
hardpoint.Emitter = Renderer(id);
return hardpoint;
}).ToArray();
var radiators = plan.Radiators.Select(id =>
{
var hardpoint = AddOrGet<RadiatorHardpoint>(Node(id).gameObject);
hardpoint.Mesh = Renderer(id);
return hardpoint;
}).ToArray();
var weapons = plan.Weapons.Select(weapon =>
{
var hardpoint = AddOrGet<WeaponHardpoint>(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<ShipInstance>(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<ArticulationPoint>();
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<T>(GameObject gameObject) where T : Component =>
gameObject.TryGetComponent<T>(out var found) ? found : gameObject.AddComponent<T>();
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3b2c0124382433447b5a5679e8b91b57

View file

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

View file

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

View file

@ -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<string, Transform> 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<Instance> 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<MeshFilter>().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<MeshRenderer>().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<ShipPolyline> lines)
{
if (lines == null || lines.Count == 0) return null;
var vertices = new List<Vector3>();
var colors = new List<Color>();
var segments = new List<int>();
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;
}
}

View file

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

View file

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

View file

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

View file

@ -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<ShipAuthoring> Visual;
[IgnoreMember]
public Shape InteriorCells
{

View file

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

View file

@ -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<CultRecordKey>();
foreach (var zoneRef in game.Zones ?? Array.Empty<CultRecordRef<SavedZone>>())
{
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<EntityPack>())
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<ItemData>(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<ProvenanceLedger>() ?? new ProvenanceLedger();

View file

@ -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<ShipAnchor> Anchors = new List<ShipAnchor>();
[Key(4)] public List<ShipPolyline> SchematicLines = new List<ShipPolyline>();
}
[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<string> Roles = new HashSet<string>(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<CultDocumentAttribute>().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:<id> 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<HullData>().ToArray();
var visuals = cache.GetAll<ShipAuthoring>().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<bool>().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<string>(StringComparer.Ordinal);
var nodeIds = new HashSet<string>(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<string>(StringComparer.Ordinal);
var occupiedHardpointCells = new HashSet<(int x, int y)>();
foreach (var hardpoint in hull.Hardpoints ?? new List<HardpointData>())
{
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<bool>().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<ShipPolyline>())
{
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.");
}
}
}

View file

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

View file

@ -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<string, uint> 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<string, List<string>>(StringComparer.Ordinal);
void Exclude(string package, string reason)
{
if (!reasons.TryGetValue(package, out var list)) reasons[package] = list = new List<string>();
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<CultRecordKey>(cache.AllStoredDocuments.Select(record => record.Key));
var itemNames = new HashSet<string>(cache.GetAll<ItemData>().Select(item => item.Name), StringComparer.Ordinal);
var shipIds = new HashSet<string>(cache.GetAll<ShipAuthoring>().Select(existing => existing.Id), StringComparer.Ordinal);
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<HullData>())
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 (<modsRoot>/<id>/<ModelAsset>). 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<Exclusion>());
Composition composition;
// A failure of the composition itself (an unwritable derived path, say) is still a mod problem, never a reason not to boot.
try { composition = Compose(shippedCatalog, derivedCatalog, modsRoot); }
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<string, uint> 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<string, uint>(StringComparer.Ordinal);
var nodes = json["nodes"]?.OfType<JObject>() ?? Enumerable.Empty<JObject>();
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;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 708d45e8a4144a6e89bcf40e96b0975a

View file

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

View file

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

View file

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

View file

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

View file

@ -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<GameObject>(hullData.Prefab), ZoneRoot);
EntityInstance instance;
if (entity is Ship)
{
instance = Instantiate(EngineAssets.Load<GameObject>(hullData.Prefab), ZoneRoot).GetComponent<ShipInstance>();
instance = Body().GetComponent<ShipInstance>();
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<GameObject>(hullData.Prefab), ZoneRoot).GetComponent<EntityInstance>();
instance = Body().GetComponent<EntityInstance>();
if (instance == null)
{
ItemManager.Log($"Failed to instantiate {hullData.Name} entity with invalid prefab: no EntityInstance component!");