1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! A crate for reading reading the [LDtk] 2D tile map format.
//!
//! The LDtk map format is simply a JSON format, which allows us to read the map file using
//! [`serde`]. This crate contains the serializable Rust structures corresponding to the map file
//! JSON structure.
//!
//! ## Example
//!
//! ```rust
//! use ldtk::Project;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // Load the map
//!     let map: Project = serde_json::from_slice(include_bytes!("../examples/full-features.ldtk"))?;
//!
//!     // Debug print the map
//!     dbg!(map);
//!
//!     Ok(())
//! }
//! ```
//!
//! [LDtk]: https://github.com/deepnight/ldtk

//
// Types below were modified from the types generated by
// [Quicktype](https://github.com/quicktype/quicktype) from the JSON schema file here:
// https://github.com/deepnight/ldtk/blob/6540f9f9efd0c4f51aa6704f7bd43b3671c9cfe9/schema.json
//

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// An LDtk project, representing the whole `.ldtk` file
#[derive(Debug, Serialize, Deserialize)]
pub struct Project {
    /// Project background color
    #[serde(rename = "bgColor")]
    pub bg_color: String,

    /// Default grid size for new layers
    #[serde(rename = "defaultGridSize")]
    pub default_grid_size: i64,

    /// Default background color of levels
    #[serde(rename = "defaultLevelBgColor")]
    pub default_level_bg_color: String,

    /// Default X pivot (0 to 1) for new entities
    #[serde(rename = "defaultPivotX")]
    pub default_pivot_x: f64,

    /// Default Y pivot (0 to 1) for new entities
    #[serde(rename = "defaultPivotY")]
    pub default_pivot_y: f64,

    /// A structure containing all the definitions of this project
    #[serde(rename = "defs")]
    pub defs: Option<Definitions>,

    /// If TRUE, a Tiled compatible file will also be generated along with the LDtk JSON file
    /// (default is FALSE)
    #[serde(rename = "exportTiled")]
    pub export_tiled: bool,

    /// File format version
    #[serde(rename = "jsonVersion")]
    pub json_version: String,

    /// All levels. The order of this array is only relevant in `LinearHorizontal` and
    /// `linearVertical` world layouts (see `worldLayout` value). Otherwise, you should refer to
    /// the `worldX`,`worldY` coordinates of each Level.
    #[serde(rename = "levels")]
    pub levels: Vec<Option<Level>>,

    /// If TRUE, the Json is partially minified (no indentation, nor line breaks, default is
    /// FALSE)
    #[serde(rename = "minifyJson")]
    pub minify_json: bool,

    #[serde(rename = "nextUid")]
    pub next_uid: i64,

    /// Height of the world grid in pixels.
    #[serde(rename = "worldGridHeight")]
    pub world_grid_height: i64,

    /// Width of the world grid in pixels.
    #[serde(rename = "worldGridWidth")]
    pub world_grid_width: i64,

    /// An enum that describes how levels are organized in this project (ie. linearly or in a 2D
    /// space). Possible values are: Free, GridVania, LinearHorizontal and LinearVertical;
    #[serde(rename = "worldLayout")]
    pub world_layout: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Definitions {
    #[serde(rename = "entities")]
    pub entities: Vec<Option<EntityDef>>,

    #[serde(rename = "enums")]
    pub enums: Vec<Option<EnumDef>>,

    /// Note: external enums are exactly the same as `enums`, except they have a `relPath` to
    /// point to an external source file.
    #[serde(rename = "externalEnums")]
    pub external_enums: Vec<Option<EnumDef>>,

    #[serde(rename = "layers")]
    pub layers: Vec<Option<LayerDef>>,

    #[serde(rename = "tilesets")]
    pub tilesets: Vec<Option<TilesetDef>>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct EntityDef {
    /// Base entity color
    #[serde(rename = "color")]
    pub color: String,

    /// Array of field definitions
    #[serde(rename = "fieldDefs")]
    pub field_defs: Vec<Option<FieldDef>>,

    /// Pixel height
    #[serde(rename = "height")]
    pub height: i64,

    /// Unique String identifier
    #[serde(rename = "identifier")]
    pub identifier: String,

    #[serde(rename = "limitBehavior")]
    pub limit_behavior: String,

    /// Max instances per level
    #[serde(rename = "maxPerLevel")]
    pub max_per_level: i64,

    /// Pivot X coordinate (from 0 to 1.0)
    #[serde(rename = "pivotX")]
    pub pivot_x: f64,

    /// Pivot Y coordinate (from 0 to 1.0)
    #[serde(rename = "pivotY")]
    pub pivot_y: f64,

    #[serde(rename = "renderMode")]
    pub render_mode: String,

    /// Display entity name in editor
    #[serde(rename = "showName")]
    pub show_name: bool,

    /// Tile ID used for optional tile display
    #[serde(rename = "tileId")]
    pub tile_id: Option<i64>,

    #[serde(rename = "tileRenderMode")]
    pub tile_render_mode: String,

    /// Tileset ID used for optional tile display
    #[serde(rename = "tilesetId")]
    pub tileset_id: Option<i64>,

    /// Unique Int identifier
    #[serde(rename = "uid")]
    pub uid: i64,

    /// Pixel width
    #[serde(rename = "width")]
    pub width: i64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FieldDef {
    /// Human readable value type (eg. `Int`, `Float`, `Point`, etc.). If the field is an array,
    /// this field will look like `Array<...>` (eg. `Array<Int>`, `Array<Point>` etc.)
    #[serde(rename = "__type")]
    pub field_def_type: String,

    /// Optional list of accepted file extensions for FilePath value type. Includes the dot:
    /// `.ext`
    #[serde(rename = "acceptFileTypes")]
    pub accept_file_types: Option<Vec<String>>,

    /// Array max length
    #[serde(rename = "arrayMaxLength")]
    pub array_max_length: Option<i64>,

    /// Array min length
    #[serde(rename = "arrayMinLength")]
    pub array_min_length: Option<i64>,

    /// TRUE if the value can be null. For arrays, TRUE means it can contain null values
    /// (exception: array of Points can't have null values).
    #[serde(rename = "canBeNull")]
    pub can_be_null: bool,

    /// Default value if selected value is null or invalid.
    #[serde(rename = "defaultOverride")]
    pub default_override: serde_json::Value,

    #[serde(rename = "editorAlwaysShow")]
    pub editor_always_show: bool,

    #[serde(rename = "editorDisplayMode")]
    pub editor_display_mode: String,

    #[serde(rename = "editorDisplayPos")]
    pub editor_display_pos: String,

    /// Unique String identifier
    #[serde(rename = "identifier")]
    pub identifier: String,

    /// TRUE if the value is an array of multiple values
    #[serde(rename = "isArray")]
    pub is_array: bool,

    /// Max limit for value, if applicable
    #[serde(rename = "max")]
    pub max: Option<f64>,

    /// Min limit for value, if applicable
    #[serde(rename = "min")]
    pub min: Option<f64>,

    /// Optional regular expression that needs to be matched to accept values. Expected format:
    /// `/some_reg_ex/g`, with optional "i" flag.
    #[serde(rename = "regex")]
    pub regex: Option<String>,

    /// Internal type enum
    #[serde(rename = "type")]
    pub field_type: serde_json::Value,

    /// Unique Intidentifier
    #[serde(rename = "uid")]
    pub uid: i64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct EnumDef {
    #[serde(rename = "externalFileChecksum")]
    pub external_file_checksum: Option<String>,

    /// Relative path to the external file providing this Enum
    #[serde(rename = "externalRelPath")]
    pub external_rel_path: Option<String>,

    /// Tileset UID if provided
    #[serde(rename = "iconTilesetUid")]
    pub icon_tileset_uid: Option<i64>,

    /// Unique String identifier
    #[serde(rename = "identifier")]
    pub identifier: String,

    /// Unique Int identifier
    #[serde(rename = "uid")]
    pub uid: i64,

    /// All possible enum values, with their optional Tile infos.
    #[serde(rename = "values")]
    pub values: Vec<HashMap<String, Option<serde_json::Value>>>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LayerDef {
    /// Type of the layer (*IntGrid, Entities, Tiles or AutoLayer*)
    #[serde(rename = "__type")]
    pub layer_def_type: String,

    /// Contains all the auto-layer rule definitions.
    #[serde(rename = "autoRuleGroups")]
    pub auto_rule_groups: Vec<HashMap<String, Option<serde_json::Value>>>,

    #[serde(rename = "autoSourceLayerDefUid")]
    pub auto_source_layer_def_uid: Option<i64>,

    /// Reference to the Tileset UID being used by this auto-layer rules
    #[serde(rename = "autoTilesetDefUid")]
    pub auto_tileset_def_uid: Option<i64>,

    /// Opacity of the layer (0 to 1.0)
    #[serde(rename = "displayOpacity")]
    pub display_opacity: f64,

    /// Width and height of the grid in pixels
    #[serde(rename = "gridSize")]
    pub grid_size: i64,

    /// Unique String identifier
    #[serde(rename = "identifier")]
    pub identifier: String,

    #[serde(rename = "intGridValues")]
    pub int_grid_values: Vec<HashMap<String, Option<serde_json::Value>>>,

    /// X offset of the layer, in pixels (IMPORTANT: this should be added to the `LayerInstance`
    /// optional offset)
    #[serde(rename = "pxOffsetX")]
    pub px_offset_x: i64,

    /// Y offset of the layer, in pixels (IMPORTANT: this should be added to the `LayerInstance`
    /// optional offset)
    #[serde(rename = "pxOffsetY")]
    pub px_offset_y: i64,

    /// If the tiles are smaller or larger than the layer grid, the pivot value will be used to
    /// position the tile relatively its grid cell.
    #[serde(rename = "tilePivotX")]
    pub tile_pivot_x: f64,

    /// If the tiles are smaller or larger than the layer grid, the pivot value will be used to
    /// position the tile relatively its grid cell.
    #[serde(rename = "tilePivotY")]
    pub tile_pivot_y: f64,

    /// Reference to the Tileset UID being used by this tile layer
    #[serde(rename = "tilesetDefUid")]
    pub tileset_def_uid: Option<i64>,

    /// Type of the layer as Haxe Enum
    #[serde(rename = "type")]
    pub purple_type: String,

    /// Unique Int identifier
    #[serde(rename = "uid")]
    pub uid: i64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TilesetDef {
    /// The following data is used internally for various optimizations. It's always synced with
    /// source image changes.
    #[serde(rename = "cachedPixelData")]
    pub cached_pixel_data: Option<HashMap<String, Option<serde_json::Value>>>,

    /// Unique String identifier
    #[serde(rename = "identifier")]
    pub identifier: String,

    /// Distance in pixels from image borders
    #[serde(rename = "padding")]
    pub padding: i64,

    /// Image height in pixels
    #[serde(rename = "pxHei")]
    pub px_hei: i64,

    /// Image width in pixels
    #[serde(rename = "pxWid")]
    pub px_wid: i64,

    /// Path to the source file, relative to the current project JSON file
    #[serde(rename = "relPath")]
    pub rel_path: String,

    /// Array of group of tiles selections, only meant to be used in the editor
    #[serde(rename = "savedSelections")]
    pub saved_selections: Vec<HashMap<String, Option<serde_json::Value>>>,

    /// Space in pixels between all tiles
    #[serde(rename = "spacing")]
    pub spacing: i64,

    #[serde(rename = "tileGridSize")]
    pub tile_grid_size: i64,

    /// Unique Intidentifier
    #[serde(rename = "uid")]
    pub uid: i64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Level {
    /// Background color of the level (same as `bgColor`, except the default value is
    /// automatically used here if its value is `null`)
    #[serde(rename = "__bgColor")]
    pub bg_color: String,

    /// An array listing all other levels touching this one on the world map. The `dir` is a
    /// single lowercase character tipping on the level location (`n`orth, `s`outh, `w`est,
    /// `e`ast). In "linear" world layouts, this array is populated with previous/next levels in
    /// array, and `dir` depends on the linear horizontal/vertical layout.
    #[serde(rename = "__neighbours")]
    pub neighbours: Vec<HashMap<String, Option<serde_json::Value>>>,

    /// Background color of the level. If `null`, the project `defaultLevelBgColor` should be
    /// used.
    #[serde(rename = "bgColor")]
    pub level_bg_color: Option<String>,

    /// Unique String identifier
    #[serde(rename = "identifier")]
    pub identifier: String,

    #[serde(rename = "layerInstances")]
    pub layer_instances: Vec<Option<LayerInstance>>,

    /// Height of the level in pixels
    #[serde(rename = "pxHei")]
    pub px_hei: i64,

    /// Width of the level in pixels
    #[serde(rename = "pxWid")]
    pub px_wid: i64,

    /// Unique Int identifier
    #[serde(rename = "uid")]
    pub uid: i64,

    /// World X coordinate in pixels
    #[serde(rename = "worldX")]
    pub world_x: i64,

    /// World Y coordinate in pixels
    #[serde(rename = "worldY")]
    pub world_y: i64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LayerInstance {
    /// Grid-based height
    #[serde(rename = "__cHei")]
    pub c_hei: i64,

    /// Grid-based width
    #[serde(rename = "__cWid")]
    pub c_wid: i64,

    /// Grid size
    #[serde(rename = "__gridSize")]
    pub grid_size: i64,

    /// Unique String identifier
    #[serde(rename = "__identifier")]
    pub identifier: String,

    /// Layer opacity as Float [0-1]
    #[serde(rename = "__opacity")]
    pub opacity: f64,

    /// Total layer X pixel offset, including both instance and definition offsets.
    #[serde(rename = "__pxTotalOffsetX")]
    pub px_total_offset_x: i64,

    /// Total layer Y pixel offset, including both instance and definition offsets.
    #[serde(rename = "__pxTotalOffsetY")]
    pub px_total_offset_y: i64,

    /// The definition UID of corresponding Tileset, if any.
    #[serde(rename = "__tilesetDefUid")]
    pub tileset_def_uid: Option<i64>,

    /// The relative path to corresponding Tileset, if any.
    #[serde(rename = "__tilesetRelPath")]
    pub tileset_rel_path: Option<String>,

    /// Layer type (possible values: IntGrid, Entities, Tiles or AutoLayer)
    #[serde(rename = "__type")]
    pub layer_instance_type: String,

    /// An array containing all tiles generated by Auto-layer rules. The array is already sorted
    /// in display order (ie. 1st tile is beneath 2nd, which is beneath 3rd
    /// etc.).<br/><br/>        Note: if multiple tiles are stacked in the same cell as the
    /// result of different rules, all tiles behind opaque ones will be discarded.
    #[serde(rename = "autoLayerTiles")]
    pub auto_layer_tiles: Vec<Option<Tile>>,

    #[serde(rename = "entityInstances")]
    pub entity_instances: Vec<Option<EntityInstance>>,

    #[serde(rename = "gridTiles")]
    pub grid_tiles: Vec<Option<Tile>>,

    #[serde(rename = "intGrid")]
    pub int_grid: Vec<HashMap<String, Option<serde_json::Value>>>,

    /// Reference the Layer definition UID
    #[serde(rename = "layerDefUid")]
    pub layer_def_uid: i64,

    /// Reference to the UID of the level containing this layer instance
    #[serde(rename = "levelId")]
    pub level_id: i64,

    /// X offset in pixels to render this layer, usually 0 (IMPORTANT: this should be added to
    /// the `LayerDef` optional offset, see `__pxTotalOffsetX`)
    #[serde(rename = "pxOffsetX")]
    pub px_offset_x: i64,

    /// Y offset in pixels to render this layer, usually 0 (IMPORTANT: this should be added to
    /// the `LayerDef` optional offset, see `__pxTotalOffsetY`)
    #[serde(rename = "pxOffsetY")]
    pub px_offset_y: i64,

    /// Random seed used for Auto-Layers rendering
    #[serde(rename = "seed")]
    pub seed: i64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Tile {
    /// Internal data used by the editor.<br/>        For auto-layer tiles: `[ruleId,
    /// coordId]`.<br/>        For tile-layer tiles: `[coordId]`.
    #[serde(rename = "d")]
    pub d: Vec<i64>,

    /// "Flip bits", a 2-bits integer to represent the mirror transformations of the
    /// tile.<br/>         - Bit 0 = X flip<br/>         - Bit 1 = Y flip<br/>         Examples:
    /// f=0 (no flip), f=1 (X flip only), f=2 (Y flip only), f=3 (both flips)
    #[serde(rename = "f")]
    pub f: i64,

    /// Pixel coordinates of the tile in the **layer** (`[x,y]` format). Don't forget optional
    /// layer offsets, if they exist!
    #[serde(rename = "px")]
    pub px: Vec<i64>,

    /// Pixel coordinates of the tile in the **tileset** (`[x,y]` format)
    #[serde(rename = "src")]
    pub src: Vec<i64>,

    /// The *Tile ID* in the corresponding tileset.
    #[serde(rename = "t")]
    pub t: i64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct EntityInstance {
    /// Grid-based coordinates (`[x,y]` format)
    #[serde(rename = "__grid")]
    pub grid: Vec<i64>,

    /// Unique String identifier
    #[serde(rename = "__identifier")]
    pub identifier: String,

    /// Optional Tile used to display this entity (it could either be the default Entity tile, or
    /// some tile provided by a field value, like an Enum).
    #[serde(rename = "__tile")]
    pub tile: Option<HashMap<String, Option<serde_json::Value>>>,

    /// Reference of the **Entity definition** UID
    #[serde(rename = "defUid")]
    pub def_uid: i64,

    #[serde(rename = "fieldInstances")]
    pub field_instances: Vec<Option<FieldInstance>>,

    /// Pixel coordinates (`[x,y]` format). Don't forget optional layer offsets, if they exist!
    #[serde(rename = "px")]
    pub px: Vec<i64>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FieldInstance {
    /// Unique String identifier
    #[serde(rename = "__identifier")]
    pub identifier: String,

    /// Type of the field, such as Int, Float, Enum(enum_name), Bool, etc.
    #[serde(rename = "__type")]
    pub field_instance_type: String,

    /// Actual value of the field instance. The value type may vary, depending on `__type`
    /// (Integer, Boolean, String etc.)<br/>        It can also be an `Array` of various types.
    #[serde(rename = "__value")]
    pub value: Option<serde_json::Value>,

    /// Reference of the **Field definition** UID
    #[serde(rename = "defUid")]
    pub def_uid: i64,

    #[serde(rename = "realEditorValues")]
    pub real_editor_values: Vec<Option<serde_json::Value>>,
}