Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
AnimationDefinitionSerializer.cs
4using Newtonsoft.Json;
5
7
11public static partial class AnimationDefinitionSerializer
12{
13 private static readonly JsonSerializerSettings Settings = new()
14 {
15 Formatting = Formatting.Indented,
16 NullValueHandling = NullValueHandling.Ignore,
17 DefaultValueHandling = DefaultValueHandling.Include,
18 MissingMemberHandling = MissingMemberHandling.Ignore
19 };
20
26 public static AnimationDefinition Load(string filePath)
27 {
28 return DefinitionDocumentJson.Select(
29 LoadAll(filePath),
30 definition => definition.Key,
31 identityComparer: StringComparer.OrdinalIgnoreCase);
32 }
33
39 public static AnimationDefinition Load(Stream stream)
40 {
41 return DefinitionDocumentJson.Select(
42 LoadAll(stream),
43 definition => definition.Key,
44 identityComparer: StringComparer.OrdinalIgnoreCase);
45 }
46
53 public static AnimationDefinition Load(AssetsFile assetsFile, string entryName)
54 {
55 return DefinitionDocumentJson.Select(
56 LoadAll(assetsFile, entryName),
57 definition => definition.Key,
58 identityComparer: StringComparer.OrdinalIgnoreCase);
59 }
60
66 public static void Save(string filePath, AnimationDefinition definition)
67 {
68 ArgumentNullException.ThrowIfNull(definition);
69 SaveAll(filePath, [definition]);
70 }
71
77 public static void Save(string filePath, Cycle cycle)
78 {
79 ArgumentNullException.ThrowIfNull(cycle);
80 Save(filePath, FromCycle(cycle));
81 }
82
88 public static AnimationDefinition FromJson(string json) =>
89 DefinitionDocumentJson.Select(
90 FromDocumentJson(json).Definitions,
91 definition => definition.Key,
92 identityComparer: StringComparer.OrdinalIgnoreCase);
93
99 public static string ToJson(AnimationDefinition definition)
100 {
101 ArgumentNullException.ThrowIfNull(definition);
102 return JsonConvert.SerializeObject(definition, Settings);
103 }
104
110 public static AnimationDefinition FromCycle(Cycle cycle)
111 {
112 ArgumentNullException.ThrowIfNull(cycle);
113
114 var definition = new AnimationDefinition
115 {
116 Key = cycle.CycleKey,
117 ThrottleTime = cycle.ThrottleTime,
118 CycleType = cycle.Sequence.SequenceCycleType,
119 HideTileOnCycleEnd = cycle.HideTileOnCycleEnd,
120 NextCycleKey = cycle.NextCycle?.CycleKey,
121 Frames = cycle.Sequence.FrameList
122 .Select((frame, index) =>
123 {
124 var definition = CreateFrameDefinition(frame);
125 definition.DurationSeconds = cycle.Sequence.GetDurationSeconds(index);
126 return definition;
127 })
128 .ToList(),
129 Source = AnimationDefinitionSource.Generated()
130 };
131
132 foreach (var name in definition.Frames.Select(frame => frame.Tilesheet)
133 .Where(name => !string.IsNullOrWhiteSpace(name))
134 .Distinct(StringComparer.Ordinal))
135 {
136 var source = DefinitionDependencyProvenance.ForTilesheet(
137 TilesheetRegistry.Instance.GetOrNull(name));
138
139 if (source?.FilePath is { } loose)
140 definition.TilesheetSources.Add(AnimationTilesheetSourceDefinition.Loose(name, loose));
141 else if (source?.AssetsFilePath is { } archive && source.AssetEntryName is { } entry)
142 definition.TilesheetSources.Add(AnimationTilesheetSourceDefinition.Packed(name, archive, entry));
143 }
144
145 return definition;
146 }
147
153 public static string ToJson(Cycle cycle) => ToJson(FromCycle(cycle));
154
163 public static Cycle ToCycle(AnimationDefinition definition)
164 {
165 var previous = Cycle._cycles.TryGetValue(definition.Key, out var existing)
166 ? existing
167 : null;
168
169 var cycle = MaterializeCycle(definition);
170
171 try
172 {
173 ApplyNextCycle(cycle, definition);
174 return cycle;
175 }
176 catch
177 {
178 if (Cycle._cycles.TryGetValue(cycle.CycleKey, out var registered) &&
179 ReferenceEquals(registered, cycle))
180 {
181 cycle.Dispose();
182
183 if (previous is not null)
184 Cycle._cycles[definition.Key] = previous;
185 }
186
187 throw;
188 }
189 }
190
196 public static Cycle LoadCycle(string filePath) => ToCycle(Load(filePath));
197
204 public static Cycle LoadCycle(AssetsFile assetsFile, string entryName) =>
205 ToCycle(Load(assetsFile, entryName));
206
207 internal static Cycle MaterializeCycle(AnimationDefinition definition)
208 {
209 ArgumentNullException.ThrowIfNull(definition);
210
211 var errors = AnimationDefinitionValidator.Validate(definition);
212
213 if (errors.Count != 0)
214 {
215 throw new InvalidDataException(
216 "GANI definition is invalid:" + Environment.NewLine +
217 string.Join(Environment.NewLine, errors.Select(error => "- " + error)));
218 }
219
220 var frames = definition.Frames
221 .Select(ResolveFrame)
222 .ToList();
223
224 var sequence = new FrameSequence(frames)
225 {
226 SequenceCycleType = definition.CycleType
227 };
228
229 sequence.SetDurations(definition.Frames.Select(frame => frame.DurationSeconds));
230
231 return new Cycle(
232 sequence,
233 definition.ThrottleTime,
234 definition.Key,
235 definition.HideTileOnCycleEnd);
236 }
237
238 internal static void ApplyNextCycle(
239 Cycle cycle,
240 AnimationDefinition definition)
241 {
242 ArgumentNullException.ThrowIfNull(cycle);
243 ArgumentNullException.ThrowIfNull(definition);
244
245 if (string.IsNullOrWhiteSpace(definition.NextCycleKey) ||
246 string.Equals(
247 definition.NextCycleKey,
248 cycle.CycleKey,
249 StringComparison.OrdinalIgnoreCase))
250 {
251 cycle.NextCycle = cycle;
252 CaptureProvenance(cycle, definition);
253 return;
254 }
255
256 if (!Cycle._cycles.TryGetValue(definition.NextCycleKey, out var nextCycle))
257 {
258 throw new InvalidDataException(
259 $"GANI animation '{definition.Key}' references next cycle '{definition.NextCycleKey}', but it is not registered.");
260 }
261
262 cycle.NextCycle = nextCycle;
263 CaptureProvenance(cycle, definition);
264 }
265
266 private static void CaptureProvenance(Cycle cycle, AnimationDefinition definition) =>
267 cycle.DefinitionProvenance = definition.LoadStamp?.Materialized(
268 definition,
269 () => FromCycle(cycle));
270
271 private static AnimationDefinition ParseDefinition(
272 string json,
273 string? sourceDescription)
274 {
275 if (string.IsNullOrWhiteSpace(json))
276 throw new ArgumentException("GANI JSON content must be a non-empty string.", nameof(json));
277
278 try
279 {
280 var definition = JsonConvert.DeserializeObject<AnimationDefinition>(json, Settings);
281
282 if (definition is null)
283 {
284 var source = string.IsNullOrWhiteSpace(sourceDescription)
285 ? "GANI JSON content"
286 : sourceDescription;
287
288 throw new InvalidDataException($"Failed to deserialize {source}. Result was null.");
289 }
290
291 definition.TilesheetSources ??= [];
292
293 for (int i = 0; i < definition.TilesheetSources.Count; i++)
294 {
295 if (definition.TilesheetSources[i] is null)
296 {
297 throw new InvalidDataException(
298 $"GANI TilesheetSources cannot contain a null entry at index {i}.");
299 }
300 }
301
302 definition.Frames ??= [];
303
304 for (int i = 0; i < definition.Frames.Count; i++)
305 {
306 if (definition.Frames[i] is null)
307 throw new InvalidDataException($"GANI Frames cannot contain a null entry at index {i}.");
308 }
309
310 return definition;
311 }
312 catch (JsonException ex)
313 {
314 var source = string.IsNullOrWhiteSpace(sourceDescription)
315 ? "GANI JSON content"
316 : sourceDescription;
317
318 throw new InvalidDataException($"Failed to deserialize {source}.", ex);
319 }
320 }
321
322 private static AnimationFrameDefinition CreateFrameDefinition(Frame frame)
323 {
324 if (frame.Tilesheet is null)
325 {
326 throw new InvalidOperationException(
327 "A GANI animation frame cannot be created from an unassigned runtime Frame.");
328 }
329
330 return new AnimationFrameDefinition
331 {
332 Tilesheet = frame.Tilesheet.Name,
333 RegionName = frame.RegionName,
334 XTile = frame.XTile,
335 YTile = frame.YTile
336 };
337 }
338
339 private static Frame ResolveFrame(AnimationFrameDefinition definition)
340 {
341 var tilesheet = TilesheetRegistry.Instance.GetOrNull(definition.Tilesheet)
342 ?? throw new InvalidDataException(
343 $"GANI references tilesheet '{definition.Tilesheet}', but it is not registered.");
344
345 var region = tilesheet.GetRegion(definition.RegionName)
346 ?? throw new InvalidDataException(
347 $"GANI references region '{definition.RegionName}' on tilesheet '{definition.Tilesheet}', but it does not exist.");
348
349 if (definition.XTile < 0 ||
350 definition.YTile < 0 ||
351 definition.XTile >= region.Columns ||
352 definition.YTile >= region.Rows)
353 {
354 throw new InvalidDataException(
355 $"GANI frame ({definition.XTile}, {definition.YTile}) is outside region '{definition.RegionName}' on tilesheet '{definition.Tilesheet}'.");
356 }
357
358 return tilesheet.GetFrame(
359 definition.RegionName,
360 definition.XTile,
361 definition.YTile);
362 }
363}
@ AnimationDefinition
Represents an animation definition file (.gani) for Gondwana.Drawing.Animation.GANI....
Definition AssetTypes.cs:57
CycleType
Simple is self-terminating; the other two are repeating.
Definition CycleType.cs:11
readonly Tilesheet Tilesheet
The tilesheet that contains the source bitmap for this frame.
Definition Frame.cs:16
readonly string RegionName
The tilesheet region that contains the source bitmap for this frame.
Definition Frame.cs:21
readonly int XTile
The horizontal tile coordinate (column index) within the tilesheet.
Definition Frame.cs:26