using System; using System.Collections.Generic; using System.IO; using System.Text; using UnityEngine; namespace GrassCutter { public struct SlotInfo { public bool used; public double money, shipped, mown; public DateTime when; public Difficulty level; } /// /// Five saves on disk, each in a folder of its own: the game, the mow map and up to five backups, the first a minute in and /// then one every half hour. A save that can't be read is put right from its newest good backup. /// Each Steam account has its own folder, saves/<SteamID64>, which Steam Auto-Cloud syncs as /// WinAppDataLocalLow / GreenHaul/Grass Cutters Together/saves/{64BitSteamID}: two people on one PC never share saves. /// public static class SaveSlots { public const int Count = 5, Backups = 5; const string GameFile = "game.json", MapFile = "mow.bin", OldKey = "grasscutter_save_v2"; [Serializable] class Head { public double money, shipped, mown; public int level; public int[] tiles; } public static int Current { get; set; } /// The game used to be called Grass Cutter and so did its folder. The saves come over once, and the old ones stay where they were. static void TakeOldFolder() { var old = Path.Combine(Path.GetDirectoryName(Application.persistentDataPath), "Grass Cutter", "saves"); if (Dev || Directory.Exists(Shared) || !Directory.Exists(old)) return; foreach (var file in Directory.GetFiles(old, "*", SearchOption.AllDirectories)) { var to = Shared + file.Substring(old.Length); Directory.CreateDirectory(Path.GetDirectoryName(to)); File.Copy(file, to); } } /// /// Slots from before saves were kept per Steam account sit straight in saves. The first account to start the game /// takes them into its own folder; anyone after starts with empty slots. Checked slot by slot, not by the folder: Steam /// makes the account folder itself (for steam_autocloud.vdf) before the game ever runs. A slot already played in /// the account folder stays, and the old one waits under the next free number, or where it is if none is free. /// static void TakeSharedSlots(string mine) { if (!Directory.Exists(Shared)) return; for (int i = 0; i < Count; i++) { var from = Path.Combine(Shared, "slot" + (i + 1)); if (!Directory.Exists(from)) continue; int to = Directory.Exists(Path.Combine(mine, "slot" + (i + 1))) ? FreeSlot(mine) : i; if (to < 0) { Debug.LogWarning("[Save] no free slot for old slot " + (i + 1) + ", left in " + Shared); continue; } Directory.CreateDirectory(mine); Directory.Move(from, Path.Combine(mine, "slot" + (to + 1))); Debug.Log("[Save] old slot " + (i + 1) + " moved into " + mine + " as slot " + (to + 1)); } } static int FreeSlot(string root) { for (int i = 0; i < Count; i++) if (!Directory.Exists(Path.Combine(root, "slot" + (i + 1)))) return i; return -1; } static bool Dev => CommandLine.Has("-autodemo") || CommandLine.Has("-mpdemo") || EndingCinematic.Preview; /// Without Steam (and in test runs) the slots sit straight in here. static string Shared => Path.Combine(Application.persistentDataPath, Dev ? "saves_dev" : "saves"); static string _ready; static string Root { get { var root = !Dev && SteamManager.Initialized ? Path.Combine(Shared, SteamManager.MySteamId.m_SteamID.ToString()) : Shared; if (_ready != root) { _ready = root; try { TakeOldFolder(); if (root != Shared) TakeSharedSlots(root); } catch (IOException e) { Debug.LogWarning("[Save] couldn't bring old saves over: " + e.Message); } } return root; } } static string Folder(int slot) => Path.Combine(Root, "slot" + (slot + 1)); static string Copy(int slot, int n) => Path.Combine(Folder(slot), "backup" + (n + 1)); public static string MapPath => Path.Combine(Folder(Current), MapFile); public static string GamePath => Path.Combine(Folder(Current), GameFile); // ───────────────────────── writing ───────────────────────── // the disk work of a save runs off the main thread, one write after another: a big farm's mow map is over ten // megabytes, and writing it in the frame froze the game every half minute static System.Threading.Tasks.Task s_io = System.Threading.Tasks.Task.CompletedTask; static readonly object s_ioGate = new object(); public static void Write(string json, byte[] map) => Write(() => json, () => map); /// The save, its text and its map put together off the main thread (JsonUtility works on any thread). public static void Write(Func json, Func map) { var dir = Folder(Current); lock (s_ioGate) s_io = s_io.ContinueWith(_ => { try { Directory.CreateDirectory(dir); Put(Path.Combine(dir, GameFile), Encoding.UTF8.GetBytes(json())); Put(Path.Combine(dir, MapFile), map()); } catch (Exception e) { Debug.LogWarning("[Save] couldn't write " + dir + ": " + e.Message); } }); } /// Waits for a save still being written: before anything reads, copies or deletes the files, and on quitting. public static void Flush() { System.Threading.Tasks.Task t; lock (s_ioGate) t = s_io; try { t.Wait(); } catch (AggregateException e) { Debug.LogWarning("[Save] " + e.InnerException?.Message); } } [RuntimeInitializeOnLoadMethod] static void FlushOnQuit() => Application.quitting += Flush; /// Written whole or not at all: a crash halfway leaves the last save as it was. static void Put(string path, byte[] data) { string tmp = path + ".tmp"; File.WriteAllBytes(tmp, data); if (File.Exists(path)) File.Delete(path); File.Move(tmp, path); } /// The current save goes over the oldest of its backups. public static void Backup() { // in the same queue as the writes, after the save just asked for: the copy is of that save, and nothing waits var dir = Folder(Current); var copies = new string[Backups]; for (int n = 0; n < Backups; n++) copies[n] = Copy(Current, n); lock (s_ioGate) s_io = s_io.ContinueWith(_ => { try { CopyToBackup(dir, copies); } catch (Exception e) { Debug.LogWarning("[Save] couldn't back up " + dir + ": " + e.Message); } }); } static void CopyToBackup(string dir, string[] copies) { var game = Path.Combine(dir, GameFile); if (!File.Exists(game)) return; int pick = 0; var oldest = DateTime.MaxValue; for (int n = 0; n < copies.Length; n++) { var path = Path.Combine(copies[n], GameFile); var when = File.Exists(path) ? File.GetLastWriteTimeUtc(path) : DateTime.MinValue; if (when < oldest) { oldest = when; pick = n; } } var to = copies[pick]; Directory.CreateDirectory(to); File.Copy(game, Path.Combine(to, GameFile), true); File.SetLastWriteTimeUtc(Path.Combine(to, GameFile), DateTime.UtcNow); var map = Path.Combine(dir, MapFile); if (File.Exists(map)) File.Copy(map, Path.Combine(to, MapFile), true); } // ───────────────────────── reading ───────────────────────── static string Text(string path) { try { return File.Exists(path) ? File.ReadAllText(path) : null; } catch (IOException e) { Debug.LogWarning("[Save] can't read " + path + ": " + e.Message); return null; } } static Head Parse(string json) { if (string.IsNullOrEmpty(json)) return null; try { var h = JsonUtility.FromJson(json); return h != null && h.tiles != null && h.tiles.Length > 0 ? h : null; } catch (ArgumentException) { return null; } } /// Backups of a slot, the newest first. static List Newest(int slot) { var list = new List(); for (int n = 0; n < Backups; n++) if (File.Exists(Path.Combine(Copy(slot, n), GameFile))) list.Add(Copy(slot, n)); list.Sort((a, b) => File.GetLastWriteTimeUtc(Path.Combine(b, GameFile)).CompareTo(File.GetLastWriteTimeUtc(Path.Combine(a, GameFile)))); return list; } /// The save to load, or null for a new game. A bad one is replaced from its backups first. public static string Read() { Flush(); Migrate(); var dir = Folder(Current); var json = Text(Path.Combine(dir, GameFile)); if (Parse(json) != null) return json; foreach (var copy in Newest(Current)) { var old = Text(Path.Combine(copy, GameFile)); if (Parse(old) == null) continue; Debug.LogWarning("[Save] the save was damaged, restored from " + copy); File.Copy(Path.Combine(copy, GameFile), Path.Combine(dir, GameFile), true); if (File.Exists(Path.Combine(copy, MapFile))) File.Copy(Path.Combine(copy, MapFile), Path.Combine(dir, MapFile), true); return old; } return null; } /// Mow maps to fall back on when the slot's own won't load, the newest first. public static IEnumerable OlderMaps() { foreach (var copy in Newest(Current)) yield return Path.Combine(copy, MapFile); } public static SlotInfo Info(int slot) { Flush(); var path = Path.Combine(Folder(slot), GameFile); var h = Parse(Text(path)); if (h == null) return new SlotInfo { used = File.Exists(path) }; return new SlotInfo { used = true, money = h.money, shipped = h.shipped, mown = h.mown, level = (Difficulty)h.level, when = File.GetLastWriteTime(path) }; } public static void Delete(int slot) { Flush(); if (Directory.Exists(Folder(slot))) Directory.Delete(Folder(slot), true); } /// Saves from before the slots lived in the registry: they become the first slot. static void Migrate() { if (Dev || !PlayerPrefs.HasKey(OldKey)) return; var dir = Folder(0); if (!File.Exists(Path.Combine(dir, GameFile))) { Directory.CreateDirectory(dir); File.WriteAllText(Path.Combine(dir, GameFile), PlayerPrefs.GetString(OldKey)); var map = Path.Combine(Application.persistentDataPath, MapFile); if (File.Exists(map)) File.Move(map, Path.Combine(dir, MapFile)); } PlayerPrefs.DeleteKey(OldKey); PlayerPrefs.Save(); } } }