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:
commit
2d39c83504
47 changed files with 5005 additions and 12 deletions
|
|
@ -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) };
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
||||
|
|
|
|||
254
Assets/Scripts/ServerShared/ShipAuthoring.cs
Normal file
254
Assets/Scripts/ServerShared/ShipAuthoring.cs
Normal 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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/ServerShared/ShipAuthoring.cs.meta
Normal file
2
Assets/Scripts/ServerShared/ShipAuthoring.cs.meta
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 0da6676b1995425fa66187e8e58956e7
|
||||
209
Assets/Scripts/ServerShared/ShipModCatalog.cs
Normal file
209
Assets/Scripts/ServerShared/ShipModCatalog.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/ServerShared/ShipModCatalog.cs.meta
Normal file
2
Assets/Scripts/ServerShared/ShipModCatalog.cs.meta
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 708d45e8a4144a6e89bcf40e96b0975a
|
||||
65
Assets/Scripts/ServerShared/ShipModPlan.cs
Normal file
65
Assets/Scripts/ServerShared/ShipModPlan.cs
Normal 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;
|
||||
}
|
||||
2
Assets/Scripts/ServerShared/ShipModPlan.cs.meta
Normal file
2
Assets/Scripts/ServerShared/ShipModPlan.cs.meta
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
fileFormatVersion: 2
|
||||
guid: b45caa5f5ad9c164b8a295528f1b4951
|
||||
Loading…
Reference in a new issue