Ship S2: the game composes and loads mod ships

Boot opens the derived catalog when GameData/Mods holds packages
(ShipModCatalog.ResolveCatalog), preloads each hull's GLB into an assembled
inactive prototype (ShipModShips), and LoadEntity clones it when the hull names
a Visual. ShipModPlan decides which anchor fills which ShipInstance slot; a
ShipModTemplate prefab carries the shared effects. Continue refuses a run that
names a design the catalog no longer holds (RunSave.RequireDesigns).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-30 06:43:52 +02:00
commit 460bb85ed0
16 changed files with 702 additions and 13 deletions

View file

@ -1,10 +1,16 @@
using System;
using System.Linq;
using UnityEditor;
using UnityEngine;
public static class ShipModPreview
{
// Batch proof: -executeMethod ShipModPreview.Smoke -shipModPath <package/ship.cc>
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();
@ -18,10 +24,12 @@ public static class ShipModPreview
ShipModVisual.Instance visual = null;
try
{
visual = await ShipModVisual.LoadAsync(args[option + 1], null);
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);
}
@ -33,6 +41,41 @@ public static class ShipModPreview
}
}
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()
{
@ -40,7 +83,7 @@ public static class ShipModPreview
if (string.IsNullOrEmpty(path)) return;
try
{
var visual = await ShipModVisual.LoadAsync(path, null);
var visual = await ShipModVisual.LoadAsync(ShipModCatalog.ReadPackage(path), null);
Undo.RegisterCreatedObjectUndo(visual.Root, "Preview mod ship");
Selection.activeGameObject = visual.Root;
SceneView.FrameLastActiveSceneView();

View file

@ -43,6 +43,9 @@ public class ActionGameManager : MonoBehaviour
private static CultCache _cultCache;
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 +55,16 @@ 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.
_cultCache = AetheriaStores.Open(
CatalogPath,
ShipModCatalog.ResolveCatalog(CatalogPath, DerivedCatalogPath, ModsPath),
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,168 @@
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);
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,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

@ -30,9 +30,8 @@ public static class ShipModVisual
public Transform Get(uint index) => m_Nodes.TryGetValue(index, out var node) ? node.transform : null;
}
public static async Task<Instance> LoadAsync(string shipPath, Transform parent)
public static async Task<Instance> LoadAsync(ShipModCatalog.Package package, Transform parent)
{
var package = ShipModCatalog.ReadPackage(shipPath);
var ship = package.Visual;
var root = new GameObject("mod-ship:" + ship.Id);

View file

@ -91,6 +91,28 @@ 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 named = (game.Zones ?? Array.Empty<CultRecordRef<SavedZone>>())
.SelectMany(zone => cache.Get(zone)?.Contents?.Entities ?? new List<EntityPack>())
.SelectMany(EntitySerializer.Items).Select(item => item.Data.Key)
.Concat(Lots(cache).Lots.Values.Select(lot => lot.Design.Key))
.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.");
}
// 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

@ -88,8 +88,35 @@ public static class ShipModCatalog
public static Package ReadPackage(string shipPath)
{
var path = Path.GetFullPath(shipPath);
var directory = Path.GetDirectoryName(path);
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 the mods root holds no package, otherwise the derived
// file, composed afresh from the shipped one and the packages. Recomposed every call, so the derived file is never
// stale and never an authority.
public static string 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;
Compose(shippedCatalog, derivedCatalog, modsRoot);
return derivedCatalog;
}
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));

View file

@ -0,0 +1,68 @@
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);
var role = visual.Anchors.ToDictionary(anchor => anchor.Id, anchor => anchor.Role, 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.TryGetValue(anchor.Id, out var mount) || mount.Type != wanted)
throw new InvalidOperationException($"{visual.Id}: {anchor.Role} anchor {anchor.Id} must be a {wanted} hardpoint's mount.");
}
string[] Mounts(HardpointType type, string wantedRole) => hardpoints.Where(hardpoint => hardpoint.Type == type).Select(hardpoint =>
role[hardpoint.Transform] == wantedRole ? hardpoint.Transform :
throw new InvalidOperationException($"{visual.Id}: {type} hardpoint {hardpoint.Transform} needs a {wantedRole} anchor of that id.")).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, "thruster-emitter"),
Radiators = Mounts(HardpointType.Radiator, "radiator-mesh"),
Weapons = weapons
};
}
private static bool IsWeapon(HardpointType type) =>
type == HardpointType.Energy || type == HardpointType.Ballistic || type == HardpointType.Launcher;
}

View file

@ -102,9 +102,11 @@ public class MainMenu : MonoBehaviour
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 +141,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 +171,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 +185,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

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