Add tutorial and QoL improvements

This commit is contained in:
2026-10-24 00:52:14 +02:00
parent ac48c24a03
commit ec3e784683
53 changed files with 3526 additions and 939 deletions
+258 -19
View File
@@ -1,7 +1,11 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using KernelPanic.Data;
using KernelPanic.Core;
using KernelPanic.Run;
using UnityEngine;
namespace KernelPanic.Meta
@@ -12,44 +16,251 @@ namespace KernelPanic.Meta
public sealed class SaveService
{
private const string SaveFileName = "kernel-panic-save.json";
public const int CurrentSchemaVersion = 5;
private static readonly object FileLock = new();
public string SavePath => Path.Combine(Application.persistentDataPath, SaveFileName);
public string SavePath { get; }
public string BackupPath => SavePath + ".bak";
public SaveService() : this(ResolveDefaultSavePath()) { }
/// <summary>Allows tools and tests to use isolated saves without touching player progression.</summary>
public SaveService(string savePath)
{
if (string.IsNullOrWhiteSpace(savePath) || !Path.IsPathFullyQualified(savePath))
{
throw new ArgumentException("Save path must be an absolute file path.", nameof(savePath));
}
SavePath = Path.GetFullPath(savePath);
}
public void Save(SaveData data)
{
data ??= new SaveData();
data.EnsureLists();
string directory = Path.GetDirectoryName(SavePath);
if (!string.IsNullOrEmpty(directory))
lock (FileLock)
{
Directory.CreateDirectory(directory);
}
// Check even when the caller did not Load first. An older build must never
// overwrite a newer save, nor replace unrecoverable data with fresh progression.
ReadResult primary = ReadFile(SavePath, out _, out string primaryProblem);
ReadResult backup = ReadFile(BackupPath, out _, out string backupProblem);
RejectFutureVersion(primary, primaryProblem);
RejectFutureVersion(backup, backupProblem);
if ((primary == ReadResult.Invalid || backup == ReadResult.Invalid)
&& primary != ReadResult.Valid && backup != ReadResult.Valid)
{
throw UnrecoverableSave(primaryProblem, backupProblem);
}
string json = JsonUtility.ToJson(data, true);
File.WriteAllText(SavePath, json);
data ??= SaveData.CreateDefault();
data.EnsureLists();
string payload = JsonUtility.ToJson(data, true);
string json = JsonUtility.ToJson(new SaveFile
{
schemaVersion = CurrentSchemaVersion,
payload = payload,
checksum = Checksum(payload)
}, true);
Directory.CreateDirectory(Path.GetDirectoryName(SavePath));
string temporaryPath = SavePath + ".tmp." + Guid.NewGuid().ToString("N");
try
{
// The temporary file lives beside the destination, so replacement stays
// on the same volume. Flush the complete snapshot before committing it.
byte[] bytes = new UTF8Encoding(false).GetBytes(json);
using (FileStream stream = new(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
stream.Write(bytes, 0, bytes.Length);
stream.Flush(true);
}
if (primary == ReadResult.Missing)
{
File.Move(temporaryPath, SavePath);
}
else
{
// A corrupt primary must not displace the known-good backup we just
// recovered. File.Replace atomically commits the completed snapshot.
File.Replace(temporaryPath, SavePath, primary == ReadResult.Valid ? BackupPath : null);
}
}
finally
{
try
{
if (File.Exists(temporaryPath))
{
File.Delete(temporaryPath);
}
}
catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)
{
// Preserve the original write/commit failure if cleanup also fails.
// Leftover temporary files are never considered committed saves.
Debug.LogWarning($"Temporary save file could not be removed: {ex.Message}");
}
}
}
}
public SaveData Load()
{
if (!File.Exists(SavePath))
lock (FileLock)
{
return SaveData.CreateDefault();
ReadResult primary = ReadFile(SavePath, out SaveData data, out string primaryProblem);
RejectFutureVersion(primary, primaryProblem);
if (primary == ReadResult.Valid)
{
data.EnsureLists();
return data;
}
ReadResult backup = ReadFile(BackupPath, out data, out string backupProblem);
RejectFutureVersion(backup, backupProblem);
if (backup == ReadResult.Valid)
{
data.EnsureLists();
Debug.LogWarning("Recovered progression from the backup save. The primary save will be repaired on the next successful save.");
return data;
}
if (primary == ReadResult.Missing && backup == ReadResult.Missing)
{
return SaveData.CreateDefault();
}
throw UnrecoverableSave(primaryProblem, backupProblem);
}
}
private static ReadResult ReadFile(string path, out SaveData data, out string problem)
{
data = null;
problem = null;
if (!File.Exists(path))
{
return ReadResult.Missing;
}
// Permission and device errors propagate; they are not evidence of corrupt data.
string json = File.ReadAllText(path);
try
{
SaveData data = JsonUtility.FromJson<SaveData>(File.ReadAllText(SavePath));
data ??= SaveData.CreateDefault();
data.EnsureLists();
return data;
if (string.IsNullOrWhiteSpace(json) || !json.TrimStart().StartsWith("{") || !json.TrimEnd().EndsWith("}"))
{
throw new InvalidDataException("The save is empty or incomplete.");
}
SaveFile file = JsonUtility.FromJson<SaveFile>(json);
if (file == null || file.schemaVersion < 0)
{
throw new InvalidDataException("The save header is invalid.");
}
if (file.schemaVersion > CurrentSchemaVersion)
{
problem = $"Save '{path}' uses schema {file.schemaVersion}; this build supports up to {CurrentSchemaVersion}. Open it with a newer game build. No files were changed.";
return ReadResult.FutureVersion;
}
if (file.schemaVersion == 0)
{
// Version 0 is the original unversioned SaveData JSON. Actual legacy
// saves always wrote ownership lists; reject arbitrary or empty objects.
LegacySaveMarker marker = JsonUtility.FromJson<LegacySaveMarker>(json);
if (marker == null || (marker.ownedUnits == null && marker.ownedUnitIds == null
&& marker.ownedPackages == null && marker.ownedPackageIds == null))
{
throw new InvalidDataException("The file is not a recognized legacy save.");
}
data = JsonUtility.FromJson<SaveData>(json);
}
else
{
if (string.IsNullOrWhiteSpace(file.payload) || string.IsNullOrEmpty(file.checksum)
|| !string.Equals(Checksum(file.payload), file.checksum, StringComparison.Ordinal))
{
throw new InvalidDataException("The save integrity check failed.");
}
data = JsonUtility.FromJson<SaveData>(file.payload);
}
if (data == null)
{
throw new InvalidDataException("The save contains no progression.");
}
// Existing EnsureLists migrations (ownership, currencies, merge balances)
// run only on the snapshot selected by Load, preserving duplicate refunds.
return ReadResult.Valid;
}
catch (Exception ex)
catch (Exception ex) when (ex is ArgumentException || ex is InvalidDataException)
{
Debug.LogWarning($"Save file could not be loaded; starting fresh. {ex.Message}");
return SaveData.CreateDefault();
problem = $"{path}: {ex.Message}";
return ReadResult.Invalid;
}
}
private static void RejectFutureVersion(ReadResult result, string problem)
{
if (result == ReadResult.FutureVersion)
{
throw new InvalidDataException(problem);
}
}
private static InvalidDataException UnrecoverableSave(string primaryProblem, string backupProblem)
{
return new InvalidDataException($"Progression could not be loaded from the save or its backup. Files were left unchanged; restore a known-good save and retry. {primaryProblem} {backupProblem}");
}
private static string Checksum(string payload)
{
using SHA256 sha = SHA256.Create();
return Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(payload)));
}
private static string ResolveDefaultSavePath()
{
#if UNITY_EDITOR || DEVELOPMENT_BUILD
string[] arguments = Environment.GetCommandLineArgs();
for (int i = 0; i < arguments.Length; i++)
{
if (arguments[i] == "--kernel-panic-save-path")
{
if (i + 1 >= arguments.Length || !Path.IsPathFullyQualified(arguments[i + 1]))
{
throw new ArgumentException("--kernel-panic-save-path requires an absolute file path.");
}
return arguments[i + 1];
}
}
#endif
return Path.Combine(Application.persistentDataPath, SaveFileName);
}
private enum ReadResult { Missing, Valid, Invalid, FutureVersion }
[Serializable]
private sealed class SaveFile
{
public int schemaVersion;
public string payload;
public string checksum;
}
[Serializable]
private sealed class LegacySaveMarker
{
public OwnedUnitSaveEntry[] ownedUnits;
public string[] ownedUnitIds;
public OwnedPackageSaveEntry[] ownedPackages;
public string[] ownedPackageIds;
}
}
/// <summary>
@@ -59,6 +270,12 @@ namespace KernelPanic.Meta
public sealed class SaveData
{
public bool starterChosen;
// Opt-in at the first starter transaction. Missing fields leave existing profiles alone.
public bool tutorialRequired;
public int tutorialLesson;
public string tutorialDistroId;
public bool tutorialRewardClaimed;
public RunCheckpoint tutorialCheckpoint;
public int entropyBalance;
public int rootCredits = GachaService.TestRootCreditsBalance;
public int commitsBalance;
@@ -83,6 +300,10 @@ namespace KernelPanic.Meta
public GachaBannerState beginnerBannerState = new(GachaService.BeginnerBannerId);
public GachaBannerState standardBannerState = new(GachaService.StandardBannerId);
public LastRunLoadoutSaveEntry lastRunLoadout = new();
public List<RunBuildDraftSaveEntry> runBuildDrafts = new();
public string lastSetupDistroId;
public RunCheckpoint activeRun;
public List<RunHistoryEntry> recentRuns = new();
public string lastRunDistroId;
public List<DistroBestWaveSaveEntry> distroBestWaves = new();
@@ -100,6 +321,13 @@ namespace KernelPanic.Meta
public void EnsureLists()
{
if (tutorialCheckpoint != null && string.IsNullOrEmpty(tutorialCheckpoint.runId)) tutorialCheckpoint = null;
// JsonUtility materializes null inline serializable objects as empty instances.
// Preserve malformed/nonempty checkpoints for an explicit recovery error, but
// recognize the empty representation emitted when a checkpoint is consumed.
if (activeRun != null && string.IsNullOrEmpty(activeRun.runId) && string.IsNullOrEmpty(activeRun.distroId)
&& string.IsNullOrEmpty(activeRun.savedUtc) && activeRun.wave == 0)
activeRun = null;
ownedUnits ??= new List<OwnedUnitSaveEntry>();
ownedPackages ??= new List<OwnedPackageSaveEntry>();
ownedPackageIds ??= new List<string>();
@@ -115,6 +343,10 @@ namespace KernelPanic.Meta
standardBannerState.EnsureLists();
lastRunLoadout ??= new LastRunLoadoutSaveEntry();
lastRunLoadout.EnsureLists();
runBuildDrafts ??= new List<RunBuildDraftSaveEntry>();
foreach (RunBuildDraftSaveEntry draft in runBuildDrafts) draft?.EnsureLists();
recentRuns ??= new List<RunHistoryEntry>();
RunHistory.Normalize(recentRuns);
if (string.IsNullOrWhiteSpace(lastRunDistroId) && !string.IsNullOrWhiteSpace(lastRunLoadout.distroId))
{
lastRunDistroId = lastRunLoadout.distroId;
@@ -455,10 +687,17 @@ namespace KernelPanic.Meta
{
public string distroId;
public List<string> cardIds = new();
public List<Language> languages = new();
public List<RunBuildPackageSaveEntry> packages = new();
public int distroVersion = 1;
public bool hasRunSeed;
public int runSeed;
public void EnsureLists()
{
cardIds ??= new List<string>();
languages ??= new List<Language>();
packages ??= new List<RunBuildPackageSaveEntry>();
}
}