using Godot; using System; using System.Linq; using System.Text.Json; public static class Serializer { public static string CreateGameJson(game g, ExportSettings es) => JsonSerializer.Serialize(CreateGameObject(g, es)); private static SerialGame CreateGameObject(game g, ExportSettings es) => new() { Rows = g.GetNode("%RowContainer").GetChildren().OfType() .Select(r => RowToSerial(r, es)).ToArray(), UnassignedCards = g.GetNode("%UnassignedCardContainer").GetChildren() .OfType().Select(c => CardToSerial(c, es)).ToArray(), }; private static SerialRow RowToSerial(row r, ExportSettings es) => new() { Color = new(r.RowColor), Cards = r.Cards.Select(c => CardToSerial(c, es)).ToArray(), Text = r.RowText }; private static SerialCard CardToSerial(card c, ExportSettings es) { byte[] imData; var i = c.GetTexture()?.GetImage(); if (i is Image img) { if (es.ScaleImages) { Image copy = new(); copy.CopyFrom(img); copy.Resize(500, 500); imData = copy.SaveWebpToBuffer(true); } else imData = img.SaveWebpToBuffer(false); } else imData = Array.Empty(); return new() { Text = c.CardName, Image = new() { DataWebp = imData, StretchMode = c.GetStretchMode(), }, }; } public static void LoadFromSerial(game g, string jsonString) { var sg = JsonSerializer.Deserialize(jsonString) ?? throw new Exception("Failed to deserialize game"); g.Clear(); using var context = card.MakeContext(g.GetTree()); foreach (var r in sg.Rows) g.AddRow(r.ToRow(g.GetTree())); foreach (var c in sg.UnassignedCards) g.AddUnassignedCard(c.ToCard(g.GetTree())); g.PropogateCardSize(); } }