Delete the old run, settings, layout and loadout authorities (Cut 10)
The deletion line lands before RunSave, as the spec orders. Deleted, not demoted: - PlayerSettings.SavedRun (Key 1 stays unclaimed) and the SavedGame constructor that upserted a fresh SavedZone per zone on every save. - ActionGameManager: the PlayerSettings.msgpack getter, file path and writer; the .loadout format (_loadoutPath, Loadouts, SaveLoadout and its default-options serializer, the commented loader); OnApplicationQuit and SaveState; SaveZone, which had no caller. - MainMenu's SavedRun Continue branch and both `SavedRun = null` writes. - InventoryPanel's Save Loadout and Restore Loadout bodies. - InputDisplayLayout's KeyboardLayouts file reader, ParseJson, AssociateInputKeys, SaveLayout and the usings they alone needed. - AetherDb's Cut 9 importer (Import.cs, legacy-census, import). - The three-gates note on loading writes; Cut 3 made loading non-writing. - .gitignore ignores GameData/run.cc and GameData/player.cc instead of PlayerSettings.msgpack. DOES NOT BUILD in Unity: ActionGameManager, MainMenu and InputDisplayLayout still reference the deleted members until the next commit wires RunSave, the settings getter and the catalog layout read. Headless builds. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
parent
aa05a99617
commit
5c5c3d5e19
11 changed files with 6 additions and 508 deletions
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -91,7 +91,8 @@ crashlytics-build.properties
|
|||
*.blend1
|
||||
|
||||
Packages/packages-lock.json
|
||||
GameData/PlayerSettings.msgpack
|
||||
GameData/run.cc
|
||||
GameData/player.cc
|
||||
Vault/Aetheria/.obsidian/plugins/copilot/data.json
|
||||
|
||||
# Agent scratch, sandboxed toolchain caches, and throwaway checkouts. These had
|
||||
|
|
|
|||
|
|
@ -55,23 +55,6 @@ public class ActionGameManager : MonoBehaviour
|
|||
}
|
||||
}
|
||||
|
||||
private static PlayerSettings _playerSettings;
|
||||
public static PlayerSettings PlayerSettings
|
||||
{
|
||||
get
|
||||
{
|
||||
return _playerSettings ??= File.Exists(_playerSettingsFilePath)
|
||||
? MessagePackSerializer.Deserialize<PlayerSettings>(File.ReadAllBytes(_playerSettingsFilePath), CultDocumentMessagePackSerialization.OptionsFor(typeof(PlayerSettings).Assembly))
|
||||
: GetDefaultPlayerSettings();
|
||||
}
|
||||
}
|
||||
|
||||
private static string _playerSettingsFilePath => Path.Combine(GameDataDirectory.FullName, "PlayerSettings.msgpack");
|
||||
public static void SavePlayerSettings()
|
||||
{
|
||||
File.WriteAllBytes(_playerSettingsFilePath, MessagePackSerializer.Serialize(_playerSettings, CultDocumentMessagePackSerialization.OptionsFor(typeof(PlayerSettings).Assembly)));
|
||||
}
|
||||
|
||||
private static PlayerSettings GetDefaultPlayerSettings()
|
||||
{
|
||||
var settings = new PlayerSettings();
|
||||
|
|
@ -161,7 +144,6 @@ public class ActionGameManager : MonoBehaviour
|
|||
// private CinemachineFramingTransposer _transposer;
|
||||
// private CinemachineComposer _composer;
|
||||
|
||||
private DirectoryInfo _loadoutPath;
|
||||
private bool _paused;
|
||||
private float _time;
|
||||
private int _zoomLevelIndex;
|
||||
|
|
@ -205,7 +187,6 @@ public class ActionGameManager : MonoBehaviour
|
|||
|
||||
public ItemManager ItemManager { get; private set; }
|
||||
public Zone Zone { get; private set; }
|
||||
public List<EntityPack> Loadouts { get; } = new List<EntityPack>();
|
||||
|
||||
private readonly (float2 direction, string name)[] _directions = {
|
||||
(float2(0, 1), "Front"),
|
||||
|
|
@ -224,24 +205,6 @@ public class ActionGameManager : MonoBehaviour
|
|||
get => MessagePackSerializer.Deserialize<EntitySettings>(MessagePackSerializer.Serialize(Settings.GameplaySettings.DefaultEntitySettings));
|
||||
}
|
||||
|
||||
public void SaveLoadout(EntityPack pack)
|
||||
{
|
||||
File.WriteAllBytes(Path.Combine(_loadoutPath.FullName, $"{pack.Name}.loadout"), MessagePackSerializer.Serialize(pack));
|
||||
}
|
||||
|
||||
private void OnApplicationQuit() => SaveState();
|
||||
|
||||
public void SaveState()
|
||||
{
|
||||
PlayerSettings.SavedRun = CurrentGalaxy == null ? null : new SavedGame(CultCache, CurrentGalaxy, Zone, DockedEntity ?? CurrentEntity);
|
||||
if(PlayerSettings.SavedRun != null)
|
||||
{
|
||||
PlayerSettings.SavedRun.IsTutorial = IsTutorial;
|
||||
PlayerSettings.SavedRun.ActionBarBindings = _actionBarSlots.Select(slot => slot.Save()).ToArray();
|
||||
}
|
||||
SavePlayerSettings();
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
Input.Dispose();
|
||||
|
|
@ -264,10 +227,6 @@ public class ActionGameManager : MonoBehaviour
|
|||
|
||||
// TODO: Process Stories
|
||||
|
||||
// _loadoutPath = GameDataDirectory.CreateSubdirectory("Loadouts");
|
||||
// Loadouts.AddRange(_loadoutPath.EnumerateFiles("*.loadout")
|
||||
// .Select(fi => MessagePackSerializer.Deserialize<EntityPack>(File.ReadAllBytes(fi.FullName))));
|
||||
|
||||
#region Input Handling
|
||||
|
||||
Input = new AetheriaInput();
|
||||
|
|
@ -1084,9 +1043,6 @@ public class ActionGameManager : MonoBehaviour
|
|||
});
|
||||
}
|
||||
|
||||
public void SaveZone(string name) => File.WriteAllBytes(
|
||||
Path.Combine(_gameDataDirectory.FullName, $"{name}.zone"), MessagePackSerializer.Serialize(Zone.PackZone()));
|
||||
|
||||
// public void ToggleEditMode()
|
||||
// {
|
||||
// _editMode = !_editMode;
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ using MessagePack;
|
|||
public class PlayerSettings
|
||||
{
|
||||
[Key(0)] public string Name = "Anonymous";
|
||||
[Key(1)] public SavedGame SavedRun;
|
||||
[Key(2)] public bool TutorialPassed;
|
||||
[Key(3)] public Dictionary<string, string> HashedStoryFiles = new Dictionary<string, string>();
|
||||
[Key(4)] public PlayerGameplaySettings GameplaySettings = new PlayerGameplaySettings();
|
||||
|
|
|
|||
|
|
@ -48,40 +48,6 @@ public class SavedGame
|
|||
[Key(12)]
|
||||
public FactionRelationship[] Relationships;
|
||||
|
||||
public SavedGame() { }
|
||||
|
||||
// Writes a SavedZone record for every galaxy zone through the cache.
|
||||
public SavedGame(CultCache cache, Galaxy galaxy, Zone currentZone, Entity currentEntity)
|
||||
{
|
||||
DiscoveredZones = galaxy.DiscoveredZones.Select(dz => Array.IndexOf(galaxy.Zones, dz)).ToArray();
|
||||
Background = galaxy.Background;
|
||||
var factions = galaxy.HomeZones.Keys.ToArray();
|
||||
Factions = factions.Select(f => cache.RefOf(f)).ToArray();
|
||||
Relationships = galaxy.Factions.Select(f => galaxy.FactionRelationships[f]).ToArray();
|
||||
|
||||
HomeZones = galaxy.HomeZones.ToDictionary(
|
||||
x => Array.IndexOf(factions, x.Key),
|
||||
x => Array.IndexOf(galaxy.Zones, x.Value));
|
||||
BossZones = galaxy.BossZones.ToDictionary(
|
||||
x => Array.IndexOf(factions, x.Key),
|
||||
x => Array.IndexOf(galaxy.Zones, x.Value));
|
||||
|
||||
Zones = galaxy.Zones.Select(zone => cache.Upsert(new SavedZone
|
||||
{
|
||||
Name = zone.Name,
|
||||
Position = zone.Position,
|
||||
AdjacentZones = zone.AdjacentZones.Select(az=> Array.IndexOf(galaxy.Zones, az)).ToArray(),
|
||||
Factions = zone.Factions.Select(f=> Array.IndexOf(factions, f)).ToArray(),
|
||||
Contents = zone.Contents?.PackZone(),
|
||||
Owner = zone.Owner == null ? -1 : Array.IndexOf(factions, zone.Owner)
|
||||
})).ToArray();
|
||||
|
||||
CurrentZone = Array.FindIndex(galaxy.Zones, zone => zone.Contents == currentZone);
|
||||
CurrentZoneEntity = currentZone.Entities.IndexOf(currentEntity);
|
||||
|
||||
Entrance = Array.IndexOf(galaxy.Zones, galaxy.Entrance);
|
||||
Exit = Array.IndexOf(galaxy.Zones, galaxy.Exit);
|
||||
}
|
||||
}
|
||||
|
||||
[CultDocument("aetheria.savedzone", "1"), MessagePackObject]
|
||||
|
|
|
|||
|
|
@ -1,11 +1,7 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using TMPro;
|
||||
using UniRx;
|
||||
using UnityEngine;
|
||||
|
|
@ -85,11 +81,6 @@ public class InputDisplayLayout : MonoBehaviour
|
|||
void Start()
|
||||
{
|
||||
_canvas = transform.root.GetComponent<Canvas>();
|
||||
var path = Path.Combine(ActionGameManager.GameDataDirectory.CreateSubdirectory("KeyboardLayouts").FullName, $"{LayoutFile.name}.msgpack");
|
||||
// _inputLayout = ParseJson(LayoutFile.text);
|
||||
_inputLayout = MessagePackSerializer.Deserialize<InputLayout>(File.ReadAllBytes(path));
|
||||
// _inputLayout = JsonConvert.DeserializeObject<InputLayout>(File.ReadAllText(path));
|
||||
// SaveLayout();
|
||||
DisplayLayout(_inputLayout);
|
||||
|
||||
_buttonMappings.Add(MapMouseButton(MouseLeft, "<Mouse>/leftButton"));
|
||||
|
|
@ -147,8 +138,6 @@ public class InputDisplayLayout : MonoBehaviour
|
|||
|
||||
RegisterMouseCallbacks();
|
||||
});
|
||||
|
||||
//StartCoroutine(AssociateInputKeys(_inputLayout));
|
||||
}
|
||||
|
||||
private ButtonMapping MapMouseButton(InputDisplayButton button, string path)
|
||||
|
|
@ -383,121 +372,6 @@ public class InputDisplayLayout : MonoBehaviour
|
|||
}
|
||||
}
|
||||
|
||||
public InputLayout ParseJson(string layout)
|
||||
{
|
||||
var rows = new List<InputLayoutRow>();
|
||||
var nextWidth = 1f;
|
||||
var nextHeight = 1;
|
||||
var reader = new JsonTextReader(new StringReader(layout));
|
||||
|
||||
reader.Read();
|
||||
if (reader.TokenType != JsonToken.StartArray)
|
||||
throw new JsonReaderException($"Unexpected JSON format in line {reader.LineNumber}:{reader.LinePosition}, expected: StartArray, received: {Enum.GetName(typeof(JsonToken), reader.TokenType)}");
|
||||
|
||||
while(reader.Read() && reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
if (reader.TokenType != JsonToken.StartArray)
|
||||
throw new JsonReaderException($"Unexpected JSON format in line {reader.LineNumber}:{reader.LinePosition}, expected: StartArray, received: {Enum.GetName(typeof(JsonToken), reader.TokenType)}");
|
||||
|
||||
var row = new InputLayoutKeyRow();
|
||||
var columns = new List<InputLayoutColumn>();
|
||||
|
||||
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
switch (reader.TokenType)
|
||||
{
|
||||
case JsonToken.StartObject:
|
||||
while(reader.Read() && reader.TokenType != JsonToken.EndObject)
|
||||
{
|
||||
switch (reader.Value.ToString())
|
||||
{
|
||||
case "a": break;
|
||||
case "w":
|
||||
nextWidth = (float) (reader.ReadAsDouble() ?? 1.0);
|
||||
break;
|
||||
case "h":
|
||||
nextHeight = reader.ReadAsInt32() ?? 1;
|
||||
break;
|
||||
case "y":
|
||||
rows.Add(new InputLayoutRowSpacer{Height = (float) (reader.ReadAsDouble() ?? 0.0)});
|
||||
break;
|
||||
case "x":
|
||||
columns.Add(new InputLayoutColumnSpacer{Width = (float) (reader.ReadAsDouble() ?? 0.0)});
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case JsonToken.String:
|
||||
InputLayoutKey key;
|
||||
var v = reader.Value.ToString().Trim();
|
||||
if (!string.IsNullOrEmpty(v))
|
||||
{
|
||||
var labels = v.Split('\n');
|
||||
key = nextHeight != 1 ? new InputLayoutMultiRowKey {Height = nextHeight} : new InputLayoutBindableKey();
|
||||
nextHeight = 1;
|
||||
((InputLayoutBindableKey) key).MainLabel = labels.Length == 2 ? labels[1] : v;
|
||||
((InputLayoutBindableKey) key).AltLabel = labels.Length == 2 ? labels[0] : "";
|
||||
}
|
||||
else
|
||||
key = new InputLayoutKey();
|
||||
|
||||
key.Width = nextWidth;
|
||||
columns.Add(key);
|
||||
nextWidth = 1f;
|
||||
break;
|
||||
default:
|
||||
throw new JsonReaderException($"Unexpected JSON format in line {reader.LineNumber}:{reader.LinePosition}");
|
||||
}
|
||||
}
|
||||
|
||||
row.Columns = columns.ToArray();
|
||||
rows.Add(row);
|
||||
}
|
||||
|
||||
return new InputLayout {Rows = rows.ToArray()};
|
||||
}
|
||||
|
||||
private IEnumerator AssociateInputKeys()
|
||||
{
|
||||
var path = "";
|
||||
var keyPress = new InputAction(binding: "/<Keyboard>/<button>");
|
||||
keyPress.performed += context =>
|
||||
{
|
||||
if (context.control.path.EndsWith("anyKey")) return;
|
||||
path = context.control.path;
|
||||
};
|
||||
keyPress.Enable();
|
||||
foreach (var button in _buttonMappings)
|
||||
{
|
||||
button.DisplayButton.Outline.color = HighlightColor;
|
||||
var fillColor = HighlightColor;
|
||||
fillColor *= FillMultiplier;
|
||||
fillColor.a = FillAlpha;
|
||||
button.DisplayButton.Fill.color = fillColor;
|
||||
|
||||
path = "";
|
||||
while (string.IsNullOrEmpty(path)) yield return null;
|
||||
button.Button.InputSystemPath = path;
|
||||
//Debug.Log($"Bound \"{path}\" to \"{bindableKey.MainLabel}\"");
|
||||
|
||||
button.DisplayButton.Outline.color = DefaultColor;
|
||||
fillColor = DefaultColor;
|
||||
fillColor *= FillMultiplier;
|
||||
fillColor.a = FillAlpha;
|
||||
button.DisplayButton.Fill.color = fillColor;
|
||||
}
|
||||
keyPress.Disable();
|
||||
|
||||
SaveLayout();
|
||||
}
|
||||
|
||||
private void SaveLayout()
|
||||
{
|
||||
File.WriteAllBytes(
|
||||
Path.Combine(ActionGameManager.GameDataDirectory.CreateSubdirectory("KeyboardLayouts").FullName, $"{LayoutFile.name}.msgpack"),
|
||||
MessagePackSerializer.Serialize(_inputLayout));
|
||||
}
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
foreach(var buttonMapping in _buttonMappings)
|
||||
|
|
|
|||
|
|
@ -91,22 +91,6 @@ public class MainMenu : MonoBehaviour
|
|||
{
|
||||
_nextMenu.panel.Clear();
|
||||
_nextMenu.panel.Title.text = TitleSubtitle("aetheria", "terminus");
|
||||
if (!InGame)
|
||||
{
|
||||
if(ActionGameManager.PlayerSettings.SavedRun != null)
|
||||
_nextMenu.panel.AddButton("Continue",
|
||||
() =>
|
||||
{
|
||||
ActionGameManager.IsTutorial = ActionGameManager.PlayerSettings.SavedRun.IsTutorial;
|
||||
ActionGameManager.CurrentGalaxy = new Galaxy(
|
||||
ActionGameManager.CultCache,
|
||||
ActionGameManager.PlayerSettings.SavedRun,
|
||||
Debug.Log);
|
||||
SceneManager.LoadScene("ARPG");
|
||||
});
|
||||
else
|
||||
_nextMenu.panel.AddButton("Continue", null);
|
||||
}
|
||||
_nextMenu.panel.AddButton("New Game",
|
||||
() =>
|
||||
{
|
||||
|
|
@ -135,7 +119,6 @@ public class MainMenu : MonoBehaviour
|
|||
setState);
|
||||
Observable.NextFrame().Subscribe(_ =>
|
||||
{
|
||||
ActionGameManager.PlayerSettings.SavedRun = null;
|
||||
ActionGameManager.CurrentGalaxy = sector;
|
||||
SceneManager.LoadScene("ARPG");
|
||||
});
|
||||
|
|
@ -164,7 +147,6 @@ public class MainMenu : MonoBehaviour
|
|||
setState);
|
||||
Observable.NextFrame().Subscribe(_ =>
|
||||
{
|
||||
ActionGameManager.PlayerSettings.SavedRun = null;
|
||||
ActionGameManager.CurrentGalaxy = sector;
|
||||
SceneManager.LoadScene("ARPG");
|
||||
});
|
||||
|
|
|
|||
|
|
@ -166,33 +166,6 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler
|
|||
|
||||
if(GameManager.DockingBay!=null && _displayedCargo!=GameManager.DockingBay)
|
||||
ContextMenu.AddOption(GameManager.DockingBay.Name, () => Display(GameManager.DockingBay));
|
||||
|
||||
ContextMenu.AddOption("Save Loadout",
|
||||
() =>
|
||||
{
|
||||
GameManager.SaveLoadout(EntitySerializer.Pack(_displayedEntity));
|
||||
});
|
||||
|
||||
if (GameManager.Loadouts.Any())
|
||||
{
|
||||
ContextMenu.AddDropdown("Restore Loadout",
|
||||
GameManager.Loadouts.Select<EntityPack, (string text, Action action, bool enabled)>(pack =>
|
||||
(
|
||||
$"{pack.Name} - {pack.Price(GameManager.ItemManager):n0}", () =>
|
||||
{
|
||||
var entity = EntitySerializer.Unpack(GameManager.ItemManager, GameManager.Zone, pack, true);
|
||||
entity.SetParent(GameManager.DockedEntity);
|
||||
GameManager.Credits -= pack.Price(GameManager.ItemManager);
|
||||
GameManager.CurrentEntity = entity;
|
||||
if(entity is Ship ship)
|
||||
{
|
||||
ship.IsPlayerShip = true;
|
||||
GameManager.DockingBay.DockedShip = ship;
|
||||
}
|
||||
Display(entity);
|
||||
}, pack.Price(GameManager.ItemManager) < GameManager.Credits
|
||||
)));
|
||||
}
|
||||
|
||||
ContextMenu.Show();
|
||||
});
|
||||
|
|
|
|||
BIN
GameData/PlayerSettings.msgpack
(Stored with Git LFS)
Normal file
BIN
GameData/PlayerSettings.msgpack
(Stored with Git LFS)
Normal file
Binary file not shown.
|
|
@ -58,15 +58,6 @@ AI share it, so AI accuracy is no longer superhuman by construction.
|
|||
- **Deferred Unity-physics surfaces:** ship collision (`HullCollider`), loot
|
||||
pickup (`ShieldManager`), `TractorBeam`, `Mine`. Not blockers.
|
||||
|
||||
**Known ownership smell in CultCache: loading writes.** `AddBackingStore`
|
||||
subscribes `Add` to a store's `EntryAdded`; `MultiFileBackingStore.PullAll`
|
||||
re-emits every entry it loads; `Add` pushes to the store registered for that
|
||||
type, and that `Push` writes a file. So a cache with a second store rewrites
|
||||
that store's files on open, and the game does this to `GameData/NameFile` at
|
||||
every startup. Nothing distinguishes "loaded this" from "changed this".
|
||||
Whoever next owns persistence should separate the two; until then, readers
|
||||
must not register a writable store they only mean to read.
|
||||
|
||||
**Invariant: game simulation runs independently of Unity.** `ServerShared`
|
||||
cannot reference UnityEngine (`Aetheria.Shared.Unity.asmdef` sets
|
||||
`noEngineReferences`), and `Aetheria.Shared/Aetheria.Shared.csproj` builds it
|
||||
|
|
|
|||
|
|
@ -1,245 +0,0 @@
|
|||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using MessagePack;
|
||||
|
||||
// One-shot import of the legacy GameData msgpack files into GameData/Aetheria.cc. Cut 10 deletes it.
|
||||
public static class Import
|
||||
{
|
||||
// The legacy DatabaseEntry union's catalog tags. Any other tag is not catalog state and throws.
|
||||
private static readonly (int Tag, Type Type)[] Tags =
|
||||
{
|
||||
(0, typeof(SimpleCommodityData)), (1, typeof(CompoundCommodityData)), (2, typeof(GearData)), (3, typeof(HullData)),
|
||||
(9, typeof(NameFile)), (13, typeof(Faction)), (17, typeof(PersonalityAttribute)), (29, typeof(CargoBayData)),
|
||||
(30, typeof(DockingBayData)), (31, typeof(WeaponItemData)), (32, typeof(FactionProductData))
|
||||
};
|
||||
|
||||
private static string GameData => Path.Combine(AetherDb.FindRoot(), "GameData");
|
||||
private static string[] NameFiles => Directory.GetFiles(Path.Combine(GameData, "NameFile"), "*.msgpack");
|
||||
private static string[] Layouts => Directory.GetFiles(Path.Combine(GameData, "KeyboardLayouts"), "*.msgpack");
|
||||
|
||||
public static int LegacyCensus()
|
||||
{
|
||||
var records = Read(Path.Combine(GameData, "AetherDB.msgpack"), true);
|
||||
Console.WriteLine("tags " + string.Join(", ", records.GroupBy(r => r.Tag).OrderBy(g => g.Key).Select(g => $"{g.Key}:{g.Count()}")));
|
||||
Console.WriteLine($"{NameFiles.Length} name files, {Layouts.Length} layouts");
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int Run()
|
||||
{
|
||||
var path = Path.Combine(GameData, "Aetheria.cc");
|
||||
if (File.Exists(path))
|
||||
{
|
||||
Console.WriteLine($"{path} exists. The import is one-shot and never merges.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Every Guid-slotted type, which is every tagged one; InputLayout is imported bare and keeps its Key(0).
|
||||
var keyed = Tags.Select(t => t.Type).FirstOrDefault(type => Members(type).ContainsKey(0));
|
||||
if (keyed != null) throw new InvalidOperationException($"{keyed.Name} declares [Key(0)], the slot the legacy Guid occupies.");
|
||||
|
||||
var records = Read(Path.Combine(GameData, "AetherDB.msgpack"), true).Concat(NameFiles.SelectMany(file => Read(file, false))).ToArray();
|
||||
var context = new Context();
|
||||
using (var cache = AetheriaStores.Open(path, catalogWritable: true))
|
||||
{
|
||||
var documents = new List<(Type Type, object Document, CultRecordKey Key)>();
|
||||
for (var index = 0; index < records.Length; index++)
|
||||
{
|
||||
var record = records[index];
|
||||
context.Key = null;
|
||||
try
|
||||
{
|
||||
var type = Tags.FirstOrDefault(t => t.Tag == record.Tag).Type ?? throw new InvalidOperationException("not a catalog tag");
|
||||
var buffer = new ArrayBufferWriter<byte>();
|
||||
var writer = new MessagePackWriter(buffer);
|
||||
var reader = new MessagePackReader(record.Payload);
|
||||
Rewrite(ref reader, ref writer, type, context, document: true);
|
||||
writer.Flush();
|
||||
documents.Add((type, CultDocumentMessagePackSerialization.DeserializeUntyped(type, buffer.WrittenSpan.ToArray(), cache.Registry), new CultRecordKey(context.Key)));
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new InvalidOperationException($"tag {record.Tag}, record {index} ({record.Source}), legacy key {context.Key ?? "unread"}: {e.Message}", e);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var layout in Layouts)
|
||||
documents.Add((typeof(InputLayout), CultDocumentMessagePackSerialization.DeserializeUntyped(typeof(InputLayout), File.ReadAllBytes(layout), cache.Registry),
|
||||
new CultRecordKey(Path.GetFileNameWithoutExtension(layout))));
|
||||
|
||||
if (!cache.Commit(batch =>
|
||||
{
|
||||
foreach (var (type, document, key) in documents) batch.Upsert(type, document, key);
|
||||
}))
|
||||
throw new InvalidOperationException("The catalog commit was refused.");
|
||||
}
|
||||
|
||||
// Reopened read-only, so the catalog-global check runs against what landed.
|
||||
using (var cache = AetheriaStores.Open(path))
|
||||
{
|
||||
var order = Tags.Select(t => t.Type).Append(typeof(InputLayout)).ToList();
|
||||
var stored = cache.AllStoredDocuments.ToArray();
|
||||
Console.WriteLine(string.Join(", ", stored.GroupBy(s => s.Document.GetType()).OrderBy(g => order.IndexOf(g.Key))
|
||||
.Select(g => $"{g.Key.Name} {g.Count()}")) + $", {stored.Length} records in all");
|
||||
|
||||
var dangling = context.Refs.Where(r => !r.Target.IsInstanceOfType(cache.Get(new CultRecordKey(r.Key)))).ToArray();
|
||||
Console.WriteLine($"{dangling.Length} refs resolve to nothing:");
|
||||
foreach (var r in dangling)
|
||||
{
|
||||
var owner = cache.Get(new CultRecordKey(r.Record));
|
||||
Console.WriteLine($" {owner?.GetType().GetField("Name")?.GetValue(owner)} {r.Member} -> {r.Key}");
|
||||
}
|
||||
}
|
||||
|
||||
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(path));
|
||||
Console.WriteLine("schemas " + string.Join(", ", snapshot.Records
|
||||
.Select(record => snapshot.SchemaCatalog.Single(entry => entry.SchemaId == record.SchemaId).SchemaName).Distinct().OrderBy(name => name)));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private sealed class Context
|
||||
{
|
||||
public string Key;
|
||||
public string Member;
|
||||
public readonly List<(string Record, string Member, Type Target, string Key)> Refs = new List<(string, string, Type, string)>();
|
||||
}
|
||||
|
||||
// Legacy records are [tag, payload] pairs: many in AetherDB.msgpack, one per name file.
|
||||
private static List<(int Tag, byte[] Payload, string Source)> Read(string path, bool many)
|
||||
{
|
||||
var records = new List<(int, byte[], string)>();
|
||||
var reader = new MessagePackReader(File.ReadAllBytes(path));
|
||||
var count = many ? reader.ReadArrayHeader() : 1;
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
if (reader.ReadArrayHeader() != 2) throw new InvalidOperationException($"{path} record {i} is not [tag, payload].");
|
||||
var tag = reader.ReadInt32();
|
||||
records.Add((tag, reader.ReadRaw().ToArray(), $"{Path.GetFileName(path)}[{i}]"));
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
// Copies one legacy value, rewriting Guids into record keys by the target type's shape.
|
||||
private static void Rewrite(ref MessagePackReader reader, ref MessagePackWriter writer, Type type, Context context, bool document = false)
|
||||
{
|
||||
if (reader.TryReadNil())
|
||||
{
|
||||
writer.WriteNil();
|
||||
return;
|
||||
}
|
||||
|
||||
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(CultRecordRef<>))
|
||||
{
|
||||
var key = ReadGuid(ref reader);
|
||||
if (key == null) writer.WriteNil();
|
||||
else
|
||||
{
|
||||
writer.Write(key);
|
||||
context.Refs.Add((context.Key, context.Member, type.GetGenericArguments()[0], key));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var unions = type.GetCustomAttributes<UnionAttribute>(false).ToArray();
|
||||
if (unions.Length > 0)
|
||||
{
|
||||
if (reader.ReadArrayHeader() != 2) throw new InvalidOperationException($"{type.Name} is not [tag, payload].");
|
||||
var tag = reader.ReadInt32();
|
||||
var subtype = unions.FirstOrDefault(u => u.Key == tag)?.SubType ?? throw new InvalidOperationException($"{type.Name} has no union tag {tag}.");
|
||||
writer.WriteArrayHeader(2);
|
||||
writer.Write(tag);
|
||||
Rewrite(ref reader, ref writer, subtype, context);
|
||||
return;
|
||||
}
|
||||
|
||||
if (document && (type.GetCustomAttribute<MessagePackObjectAttribute>(false) == null || reader.NextMessagePackType != MessagePackType.Array))
|
||||
throw new InvalidOperationException($"{type.Name} is not an integer-keyed MessagePack object.");
|
||||
|
||||
if (type.GetCustomAttribute<MessagePackObjectAttribute>(false) != null && reader.NextMessagePackType == MessagePackType.Array)
|
||||
{
|
||||
var members = Members(type);
|
||||
var count = reader.ReadArrayHeader();
|
||||
writer.WriteArrayHeader(count);
|
||||
for (var slot = 0; slot < count; slot++)
|
||||
{
|
||||
if (document && slot == 0)
|
||||
{
|
||||
context.Key = ReadGuid(ref reader) ?? throw new InvalidOperationException("slot 0 holds no Guid");
|
||||
writer.WriteNil();
|
||||
}
|
||||
else if (!members.TryGetValue(slot, out var member)) writer.WriteRaw(reader.ReadRaw());
|
||||
else if (member.DeclaringType == typeof(StatModifierData) && member.Name == nameof(StatModifierData.RequireBehavior))
|
||||
{
|
||||
// A legacy assembly-qualified type name; the game compares simple names.
|
||||
var name = reader.ReadString();
|
||||
var head = name?.Split(',')[0];
|
||||
writer.Write(head?.Substring(head.LastIndexOf('.') + 1));
|
||||
}
|
||||
else
|
||||
{
|
||||
var outer = context.Member;
|
||||
if (document) context.Member = $"{type.Name}.{member.Name}";
|
||||
Rewrite(ref reader, ref writer, member is FieldInfo field ? field.FieldType : ((PropertyInfo)member).PropertyType, context);
|
||||
context.Member = outer;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var list = type.IsArray && type.GetArrayRank() == 1 && type != typeof(byte[]) ? type.GetElementType()
|
||||
: type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>) ? type.GetGenericArguments()[0] : null;
|
||||
if (list != null && reader.NextMessagePackType == MessagePackType.Array)
|
||||
{
|
||||
var count = reader.ReadArrayHeader();
|
||||
writer.WriteArrayHeader(count);
|
||||
for (var i = 0; i < count; i++) Rewrite(ref reader, ref writer, list, context);
|
||||
return;
|
||||
}
|
||||
|
||||
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>) && reader.NextMessagePackType == MessagePackType.Map)
|
||||
{
|
||||
var arguments = type.GetGenericArguments();
|
||||
var count = reader.ReadMapHeader();
|
||||
writer.WriteMapHeader(count);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
Rewrite(ref reader, ref writer, arguments[0], context);
|
||||
Rewrite(ref reader, ref writer, arguments[1], context);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
writer.WriteRaw(reader.ReadRaw());
|
||||
}
|
||||
|
||||
// A legacy Guid: a 16-byte bin, a DatabaseLink [bin16], or nil. The all-zero Guid is unset, so it becomes nil.
|
||||
private static string ReadGuid(ref MessagePackReader reader)
|
||||
{
|
||||
if (reader.TryReadNil()) return null;
|
||||
if (reader.NextMessagePackType == MessagePackType.Array)
|
||||
{
|
||||
if (reader.ReadArrayHeader() != 1) throw new InvalidOperationException("a legacy DatabaseLink is not [guid]");
|
||||
return ReadGuid(ref reader);
|
||||
}
|
||||
var bytes = reader.ReadBytes()?.ToArray();
|
||||
if (bytes == null || bytes.Length != 16) throw new InvalidOperationException("a legacy Guid is not a 16-byte bin");
|
||||
var guid = new Guid(bytes);
|
||||
return guid == Guid.Empty ? null : guid.ToString("D");
|
||||
}
|
||||
|
||||
private static Dictionary<int, MemberInfo> Members(Type type)
|
||||
{
|
||||
var members = new Dictionary<int, MemberInfo>();
|
||||
for (var t = type; t != null; t = t.BaseType)
|
||||
foreach (var member in t.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly))
|
||||
if ((member is FieldInfo || member is PropertyInfo) && member.GetCustomAttribute<KeyAttribute>()?.IntKey is int slot && !members.ContainsKey(slot))
|
||||
members[slot] = member;
|
||||
return members;
|
||||
}
|
||||
}
|
||||
|
|
@ -29,10 +29,8 @@ public static class Program
|
|||
case "dangling": return Dangling(args.Skip(1).ToArray());
|
||||
case "settings": return Settings();
|
||||
case "settings-dump": return SettingsDump();
|
||||
case "legacy-census": return Import.LegacyCensus();
|
||||
case "import": return Import.Run();
|
||||
default:
|
||||
Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear <Type.Member>]... [apply], legacy-census, import");
|
||||
Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear <Type.Member>]... [apply]");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue