using System.IO; using AibisDream.Utility; using Newtonsoft.Json; using UnityEngine; namespace AibisDream.SaveSystem { /// /// 快照与磁盘的边界:序列化和读写 JSON 文件。 /// /// P2 起,业务存档统一通过 写入槽位目录; /// 本类保留按路径读写的低级接口,供迁移和外部调试使用。 /// /// public static class SnapshotPersistence { private static readonly JsonSerializerSettings Settings = new() { TypeNameHandling = TypeNameHandling.None, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Ignore }; /// P1 自测落盘:SnapshotTestPath/latest_snapshot.json(P2 迁移源)。 public static string GetTestFilePath() { return Path.Combine(ConstRef.SnapshotTestPath, ConstRef.SnapshotTestFileName); } /// 将快照序列化并写入指定槽位。 public static void SaveToSlot(int slotIndex, SaveSnapshot snapshot) { SlotManager.SaveToSlot(slotIndex, snapshot, null); } /// 从指定槽位读取快照。 public static SaveSnapshot LoadFromSlot(int slotIndex) { return SlotManager.LoadSnapshot(slotIndex); } /// 将快照序列化为 JSON 字符串(紧凑格式)。 public static string Serialize(SaveSnapshot snapshot) { return JsonConvert.SerializeObject(snapshot, Formatting.None, Settings); } /// 从 JSON 字符串反序列化为快照。 public static SaveSnapshot Deserialize(string json) { var snapshot = JsonConvert.DeserializeObject(json, Settings); if (snapshot != null && snapshot.schemaVersion != SaveSnapshotSchema.CurrentVersion) { Debug.LogWarning( $"[SnapshotPersistence] schemaVersion {snapshot.schemaVersion} != {SaveSnapshotSchema.CurrentVersion},按当前结构读取。"); } return snapshot; } /// 将快照序列化并写入 path(自动补 .json 后缀)。 public static void Save(SaveSnapshot snapshot, string pathWithoutExtension) { var json = Serialize(snapshot); var path = JsonUtil.FormatAsJsonPath(pathWithoutExtension); var dir = Path.GetDirectoryName(path); if (!string.IsNullOrEmpty(dir)) { Directory.CreateDirectory(dir); } File.WriteAllText(path, json); } /// 从 path 读取并反序列化为 public static SaveSnapshot Load(string pathWithoutExtension) { var json = File.ReadAllText(JsonUtil.FormatAsJsonPath(pathWithoutExtension)); return Deserialize(json); } } }