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
TilesheetDefinitionSerializer.cs
4using Newtonsoft.Json;
5
7
11public static partial class TilesheetDefinitionSerializer
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 TilesheetDefinition Load(string filePath)
27 {
28 return DefinitionDocumentJson.Select(LoadAll(filePath), definition => definition.Name);
29 }
30
36 public static TilesheetDefinition Load(Stream stream)
37 {
38 return DefinitionDocumentJson.Select(LoadAll(stream), definition => definition.Name);
39 }
40
46 public static void Save(string filePath, TilesheetDefinition definition)
47 {
48 ArgumentNullException.ThrowIfNull(definition);
49 SaveAll(filePath, [definition]);
50 }
51
57 public static TilesheetDefinition FromJson(string json) =>
58 DefinitionDocumentJson.Select(FromDocumentJson(json).Definitions, definition => definition.Name);
59
65 public static string ToJson(TilesheetDefinition definition)
66 {
67 ArgumentNullException.ThrowIfNull(definition);
68 return JsonConvert.SerializeObject(definition, Settings);
69 }
70
78 public static TilesheetDefinition FromTilesheet(
79 Tilesheet tilesheet,
80 string? baseDirectory = null,
81 bool makePathsRelative = false)
82 {
83 ArgumentNullException.ThrowIfNull(tilesheet);
84
85 return new TilesheetDefinition
86 {
87 Name = tilesheet.Name,
88 Image = CreateImageDefinition(
89 tilesheet,
90 baseDirectory,
91 makePathsRelative),
92 Regions = tilesheet.Regions
93 .Select(CreateRegionDefinition)
94 .ToList(),
95 Mask = CreateMaskDefinition(tilesheet),
96 PremultiplyAlpha = tilesheet.Premultiplied && tilesheet.MaskColor is null,
97 Source = TilesheetDefinitionSource.Generated()
98 };
99 }
100
114 public static void Save(
115 string filePath,
116 Tilesheet tilesheet,
117 bool makePathsRelative = true)
118 {
119 if (string.IsNullOrWhiteSpace(filePath))
120 throw new ArgumentException("GTS file path must be a non-empty string.", nameof(filePath));
121
122 ArgumentNullException.ThrowIfNull(tilesheet);
123
124 var fullPath = Path.GetFullPath(filePath);
125
126 if (string.IsNullOrWhiteSpace(tilesheet.ImageFilePath) &&
127 string.IsNullOrWhiteSpace(tilesheet.AssetIdentifier?.AssetsFile.SourcePath))
128 {
129 tilesheet.PersistImageToFile(
130 Path.ChangeExtension(fullPath, ".png"));
131 }
132
133 var definition = FromTilesheet(
134 tilesheet,
135 Path.GetDirectoryName(fullPath),
136 makePathsRelative);
137
138 Save(fullPath, definition);
139 }
140
148 public static string ToJson(
149 Tilesheet tilesheet,
150 string? baseDirectory = null,
151 bool makePathsRelative = false)
152 {
153 return ToJson(
154 FromTilesheet(
155 tilesheet,
156 baseDirectory,
157 makePathsRelative));
158 }
159
160 private static TilesheetDefinition ParseDefinition(
161 string json,
162 string? sourceDescription)
163 {
164 if (string.IsNullOrWhiteSpace(json))
165 throw new ArgumentException("GTS JSON content must be a non-empty string.", nameof(json));
166
167 try
168 {
169 var definition = JsonConvert.DeserializeObject<TilesheetDefinition>(json, Settings);
170
171 if (definition is null)
172 {
173 var source = string.IsNullOrWhiteSpace(sourceDescription)
174 ? "GTS JSON content"
175 : sourceDescription;
176
177 throw new InvalidDataException(
178 $"Failed to deserialize {source}. Result was null.");
179 }
180
181 // Maintain compatibility with files written before frame-level metadata existed,
182 // and tolerate explicit null collection values from hand-authored JSON.
183 definition.Regions ??= [];
184
185 foreach (var region in definition.Regions)
186 {
187 if (region is null)
188 throw new InvalidDataException("GTS Regions cannot contain null entries.");
189
190 region.Frames ??= [];
191 }
192
193 return definition;
194 }
195 catch (JsonException ex)
196 {
197 var source = string.IsNullOrWhiteSpace(sourceDescription)
198 ? "GTS JSON content"
199 : sourceDescription;
200
201 throw new InvalidDataException($"Failed to deserialize {source}.", ex);
202 }
203 }
204
205 private static TilesheetImageDefinition CreateImageDefinition(
206 Tilesheet tilesheet,
207 string? baseDirectory,
208 bool makePathsRelative)
209 {
210 if (!string.IsNullOrWhiteSpace(tilesheet.ImageFilePath))
211 {
212 return new TilesheetImageDefinition
213 {
214 FilePath = NormalizePath(
215 tilesheet.ImageFilePath,
216 baseDirectory,
217 makePathsRelative)
218 };
219 }
220
221 if (tilesheet.AssetIdentifier is not null)
222 {
223 var assetIdentifier = tilesheet.AssetIdentifier;
224
225 if (assetIdentifier.AssetType != AssetTypes.Image)
226 {
227 throw new InvalidOperationException(
228 $"Tilesheet '{tilesheet.Name}' references an asset of type '{assetIdentifier.AssetType}', but expected '{AssetTypes.Image}'.");
229 }
230
231 if (assetIdentifier.AssetsFile is null ||
232 string.IsNullOrWhiteSpace(assetIdentifier.AssetsFile.SourcePath))
233 {
234 throw new InvalidOperationException(
235 $"Tilesheet '{tilesheet.Name}' has an asset identifier, but the assets file path is missing.");
236 }
237
238 return new TilesheetImageDefinition
239 {
240 AssetsFilePath = NormalizePath(
241 assetIdentifier.AssetsFile.SourcePath,
242 baseDirectory,
243 makePathsRelative),
244 AssetEntryName = assetIdentifier.AssetName
245 };
246 }
247
248 throw new InvalidOperationException(
249 $"Tilesheet '{tilesheet.Name}' cannot be converted to a TilesheetDefinition because it has no ImageFilePath or AssetIdentifier.");
250 }
251
252 private static TilesheetRegionDefinition CreateRegionDefinition(
253 TilesheetRegion region)
254 {
255 var definition = new TilesheetRegionDefinition
256 {
257 Name = region.Name,
258 Area = region.Area,
259 TileSize = region.TileSize,
260 TilePadding = region.TilePadding,
261 RegionMargin = region.RegionMargin,
262 Overhang = region.Overhang,
263 CollisionAdjust = region.CollisionAdjust,
264 CollisionType = region.CollisionType
265 };
266
267 // Persist every frame coordinate while retaining the distinction between an
268 // inherited region default (null) and an explicit frame-level override.
269 for (int y = 0; y < region.Rows; y++)
270 {
271 for (int x = 0; x < region.Columns; x++)
272 {
273 CollisionAdjust? collisionAdjust =
274 region.TryGetFrameCollisionAdjustOverride(
275 x,
276 y,
277 out var frameCollisionAdjust)
278 ? frameCollisionAdjust
279 : null;
280
281 TileCollisionType? collisionType =
282 region.TryGetFrameCollisionTypeOverride(
283 x,
284 y,
285 out var frameCollisionType)
286 ? frameCollisionType
287 : null;
288
289 definition.Frames.Add(
290 new TilesheetFrameDefinition
291 {
292 XTile = x,
293 YTile = y,
294 CollisionAdjust = collisionAdjust,
295 CollisionType = collisionType
296 });
297 }
298 }
299
300 return definition;
301 }
302
303 private static TilesheetMaskDefinition? CreateMaskDefinition(Tilesheet tilesheet)
304 {
305 if (tilesheet.MaskColor is null)
306 return null;
307
308 var color = tilesheet.MaskColor.Value;
309
310 return new TilesheetMaskDefinition
311 {
312 Red = color.Red,
313 Green = color.Green,
314 Blue = color.Blue,
315 Alpha = color.Alpha,
316 Tolerance = tilesheet.MaskTolerance
317 };
318 }
319
320 private static void ApplyDefaultSource(
321 TilesheetDefinition definition,
322 TilesheetDefinitionSource source)
323 {
324 if (definition.Source.Kind == TilesheetDefinitionSourceKind.None)
325 definition.Source = source;
326 }
327
328 private static string NormalizePath(
329 string path,
330 string? baseDirectory,
331 bool makeRelative)
332 {
333 if (string.IsNullOrWhiteSpace(path))
334 return path;
335
336 if (!makeRelative || string.IsNullOrWhiteSpace(baseDirectory))
337 return path.Replace('\\', '/');
338
339 if (!Path.IsPathRooted(path))
340 return path.Replace('\\', '/');
341
342 var fullPath = Path.GetFullPath(path);
343 var fullBaseDirectory = Path.GetFullPath(baseDirectory);
344
345 return Path.GetRelativePath(fullBaseDirectory, fullPath).Replace('\\', '/');
346 }
347}
AssetTypes
Defines the types of assets that can be stored and managed by the engine.
Definition AssetTypes.cs:8
@ TilesheetDefinition
Represents a tilesheet definition file (.gts) for Gondwana.Drawing.Tilesheets.GTS....
Definition AssetTypes.cs:47
@ Image
Represents an image file type.
Definition AssetTypes.cs:12
TilesheetDefinitionSourceKind
Indicates where a tilesheet definition came from.
TileCollisionType
Defines the default collision behavior associated with a tilesheet region, frame, or runtime tile.