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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
use crate::map::*;
use crate::convert::TryTo;

use image::RgbaImage;
use ndarray::Array2;

use std::fmt;

impl Info {
    pub const MAX_AUTHOR_LENGTH: usize = 31;
    pub const MAX_VERSION_LENGTH: usize = 15;
    pub const MAX_CREDITS_LENGTH: usize = 127;
    pub const MAX_LICENSE_LENGTH: usize = 31;
    pub const MAX_SETTING_LENGTH: usize = 255;
}

impl Image {
    pub const MAX_NAME_LENGTH: usize = 127;
}

impl Envelope {
    pub const MAX_NAME_LENGTH: usize = 31;
}

impl Group {
    pub const MAX_NAME_LENGTH: usize = 11;
}

impl Layer {
    pub const MAX_NAME_LENGTH: usize = 11;
}

impl Sound {
    pub const MAX_NAME_LENGTH: usize = 127;
}

impl TwMap {
    /// Returns a empty map struct with only the version set.
    pub fn empty(version: Version) -> TwMap {
        TwMap {
            version,
            info: Info::default(),
            images: vec![],
            envelopes: vec![],
            groups: vec![],
            sounds: vec![],
        }
    }

    /// Returns a reference to the physics group.
    pub fn physics_group(&self) -> &Group {
        self.groups.iter()
            .find(|group| group.is_physics_group())
            .unwrap()
    }

    /// Returns a mutable reference to the physics group.
    pub fn physics_group_mut(&mut self) -> &mut Group {
        self.groups.iter_mut()
            .find(|group| group.is_physics_group())
            .unwrap()
    }
}

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{{x: {}, y: {}}}", self.x, self.y)
    }
}

impl Group {
    /// Checks if the group contains any physics layers.
    pub fn is_physics_group(&self) -> bool {
        self.layers.iter()
            .any(|layer| layer.kind().is_physics_layer())
    }
}


impl From<ExternalImage> for Image {
    fn from(image: ExternalImage) -> Self {
        Image::External(image)
    }
}

impl From<EmbeddedImage> for Image {
    fn from(image: EmbeddedImage) -> Self {
        Image::Embedded(image)
    }
}

impl Image {
    pub fn name(&self) -> &String {
        match self {
            Image::External(img) => &img.name,
            Image::Embedded(img) => &img.name,
        }
    }

    pub fn name_mut(&mut self) -> &mut String {
        match self {
            Image::External(img) => &mut img.name,
            Image::Embedded(img) => &mut img.name,
        }
    }

    pub fn width(&self) -> i32 {
        match self {
            Image::External(image) => image.width.try_to(),
            Image::Embedded(image) => match &image.image {
                CompressedData::Compressed(_, _, info) => info.width,
                CompressedData::Loaded(image) => image.width().try_to(),
            },
        }
    }

    pub fn height(&self) -> i32 {
        match self {
            Image::External(image) => image.height,
            Image::Embedded(image) => match &image.image {
                CompressedData::Compressed(_, _, info) => info.height,
                CompressedData::Loaded(image) => image.height().try_to(),
            },
        }
    }

    pub fn image(&self) -> Option<&CompressedData<RgbaImage, ImageLoadInfo>> {
        match self {
            Image::External(_) => None,
            Image::Embedded(image) => Some(&image.image)
        }
    }

    pub fn image_mut(&mut self) -> Option<&mut CompressedData<RgbaImage, ImageLoadInfo>> {
        match self {
            Image::External(_) => None,
            Image::Embedded(image) => Some(&mut image.image)
        }
    }
}

impl LayerKind {
    pub fn is_physics_layer(&self) -> bool {
        use LayerKind::*;
        match self {
            Game | Front | Tele | Speedup | Switch | Tune => true,
            Tiles | Quads | Sounds | Invalid(_) => false,
        }
    }

    pub fn is_tile_map_layer(&self) -> bool {
        use LayerKind::*;
        match self {
            Game | Tiles | Front | Tele | Speedup | Switch | Tune => true,
            Quads | Sounds | Invalid(_) => false,
        }
    }
}

impl<T> CompressedData<Array2<T>, TilesLoadInfo> {
    /// Returns the (height, width) 2-dimensional array of tiles.
    pub fn shape(&self) -> (usize, usize) {
        match self {
            CompressedData::Compressed(_, _, info) => (info.height.try_to(), info.width.try_to::<usize>()),
            CompressedData::Loaded(array) => (array.nrows(), array.ncols()),
        }
    }
}

impl Layer {
    /// Returns an identifier for the type of the layer.
    pub fn kind(&self) -> LayerKind {
        use Layer::*;
        match self {
            Game(_) => LayerKind::Game,
            Tiles(_) => LayerKind::Tiles,
            Quads(_) => LayerKind::Quads,
            Front(_) => LayerKind::Front,
            Tele(_) => LayerKind::Tele,
            Speedup(_) => LayerKind::Speedup,
            Switch(_) => LayerKind::Switch,
            Tune(_) => LayerKind::Tune,
            Sounds(_) => LayerKind::Sounds,
            Invalid(kind) => LayerKind::Invalid(*kind),
        }
    }

    /// Returns the (height, width) of the 2-dimensional array of tiles, if the contained layer is a tile map layer.
    pub fn shape(&self) -> Option<(usize, usize)> {
        use Layer::*;
        match self {
            Game(l) => Some(l.tiles().shape()),
            Tiles(l) => Some(l.tiles().shape()),
            Quads(_) => None,
            Front(l) => Some(l.tiles().shape()),
            Tele(l) => Some(l.tiles().shape()),
            Speedup(l) => Some(l.tiles().shape()),
            Switch(l) => Some(l.tiles().shape()),
            Tune(l) => Some(l.tiles().shape()),
            Sounds(_) => None,
            Invalid(_) => None,
        }
    }
}

impl<T, U> From<T> for CompressedData<T, U> {
    fn from(data: T) -> Self {
        CompressedData::Loaded(data)
    }
}

impl<T, U> CompressedData<T, U> {
    /// Returns a reference to the inner loaded value. Panics if isn't loaded.
    pub fn unwrap_ref(&self) -> &T {
        match self {
            CompressedData::Compressed(_, _, _) => panic!(),
            CompressedData::Loaded(data) => data,
        }
    }

    /// Returns a mutable reference to the inner loaded value. Panics if isn't loaded.
    pub fn unwrap_mut(&mut self) -> &mut T {
        match self {
            CompressedData::Compressed(_, _, _) => panic!(),
            CompressedData::Loaded(data) => data,
        }
    }

    /// Returns the inner loaded value. Panics if isn't loaded.
    pub fn unwrap(self) -> T {
        match self {
            CompressedData::Compressed(_, _, _) => panic!(),
            CompressedData::Loaded(data) => data,
        }
    }
}

impl Envelope {
    /// Returns a reference to the name of the envelope.
    pub fn name(&self) -> &String {
        use Envelope::*;
        match self {
            Position(env) => &env.name,
            Color(env) => &env.name,
            Sound(env) => &env.name,
        }
    }

    /// Returns a mutable reference to the name of the envelope.
    pub fn name_mut (&mut self) -> &mut String {
        use Envelope::*;
        match self {
            Position(env) => &mut env.name,
            Color(env) => &mut env.name,
            Sound(env) => &mut env.name,
        }
    }
}

impl Default for Group {
    fn default() -> Self {
        Group {
            offset_x: 0,
            offset_y: 0,
            parallax_x: 100,
            parallax_y: 100,
            layers: vec![],
            clipping: false,
            clip_x: 0,
            clip_y: 0,
            clip_width: 0,
            clip_height: 0,
            name: String::new(),
        }
    }
}

impl Group {
    /// Constructor for the game group, make sure not to change any values apart from the layers
    pub fn game() -> Self {
        let mut group = Group::default();
        group.name = String::from("Game");
        group
    }
}

impl TilesLayer {
    /// Creates a tiles layer with the default values and the specified dimensions.
    pub fn new(shape: (usize, usize)) -> Self {
        TilesLayer {
            detail: false,
            color: Color::default(),
            color_env: None,
            color_env_offset: 0,
            image: None,
            tiles: Array2::default(shape).into(),
            name: "".to_string(),
            auto_mapper: AutoMapper::default()
        }
    }
}

impl Layer {
    /// Returns a reference to the name of the layer.
    pub fn name(&self) -> &str {
        use Layer::*;
        match self {
            Game(_) => LayerKind::Game.static_name(),
            Tiles(l) => &l.name,
            Quads(l) => &l.name,
            Front(_) => LayerKind::Front.static_name(),
            Tele(_) => LayerKind::Tele.static_name(),
            Speedup(_) => LayerKind::Speedup.static_name(),
            Switch(_) => LayerKind::Switch.static_name(),
            Tune(_) => LayerKind::Tune.static_name(),
            Sounds(l) => &l.name,
            Invalid(_) => panic!(),
        }
    }

    /// Returns a mutable reference to the name of the layer, if the layer type supports an editable name.
    pub fn name_mut(&mut self) -> Option<&mut String> {
        use Layer::*;
        match self {
            Game(_) => None,
            Tiles(l) => Some(&mut l.name),
            Quads(l) => Some(&mut l.name),
            Front(_) => None,
            Tele(_) => None,
            Speedup(_) => None,
            Switch(_) => None,
            Tune(_) => None,
            Sounds(l) => Some(&mut l.name),
            Invalid(_) => panic!(),
        }
    }
}

impl Tile {
    /// Constructor, required due to unused bytes which will be set to 0.
    pub fn new(id: u8, flags: TileFlags) -> Self {
        Tile {
            id,
            flags,
            skip: 0,
            unused: 0,
        }
    }
}

impl GameTile {
    /// Constructor, required due to unused bytes which will be set to 0.
    pub fn new(id: u8, flags: TileFlags) -> Self {
        GameTile {
            id,
            flags,
            skip: 0,
            unused: 0,
        }
    }
}

impl Speedup {
    /// Constructor, required due to unused bytes which will be set to 0.
    pub fn new(id: u8, force: u8, max_speed: u8, angle: i16) -> Self {
        Speedup {
            force,
            max_speed,
            id,
            unused_padding: 0,
            angle: angle.into(),
        }
    }
}

impl From<i16> for I16 {
    fn from(x: i16) -> Self {
        I16 {
            bytes: x.to_le_bytes(),
        }
    }
}

impl From<I16> for i16 {
    fn from(x: I16) -> Self {
        i16::from_le_bytes(x.bytes)
    }
}

impl Default for Color {
    fn default() -> Self {
        Color {
            r: 255,
            g: 255,
            b: 255,
            a: 255,
        }
    }
}

impl Default for I32Color {
    fn default() -> Self {
        I32Color {
            r: 1024,
            g: 1024,
            b: 1024,
            a: 1024,
        }
    }
}

impl TileMapLayer for TilesLayer {
    type TileType = Tile;

    fn tiles(&self) -> &CompressedData<Array2<Self::TileType>, TilesLoadInfo> {
        &self.tiles
    }

    fn tiles_mut(&mut self) -> &mut CompressedData<Array2<Self::TileType>, TilesLoadInfo> {
        &mut self.tiles
    }
}

impl TileMapLayer for GameLayer {
    type TileType = GameTile;

    fn tiles(&self) -> &CompressedData<Array2<Self::TileType>, TilesLoadInfo> {
        &self.tiles
    }

    fn tiles_mut(&mut self) -> &mut CompressedData<Array2<Self::TileType>, TilesLoadInfo> {
        &mut self.tiles
    }
}

impl TileMapLayer for FrontLayer {
    type TileType = GameTile;

    fn tiles(&self) -> &CompressedData<Array2<Self::TileType>, TilesLoadInfo> {
        &self.tiles
    }

    fn tiles_mut(&mut self) -> &mut CompressedData<Array2<Self::TileType>, TilesLoadInfo> {
        &mut self.tiles
    }
}

impl TileMapLayer for TeleLayer {
    type TileType = Tele;

    fn tiles(&self) -> &CompressedData<Array2<Self::TileType>, TilesLoadInfo> {
        &self.tiles
    }

    fn tiles_mut(&mut self) -> &mut CompressedData<Array2<Self::TileType>, TilesLoadInfo> {
        &mut self.tiles
    }
}

impl TileMapLayer for SpeedupLayer {
    type TileType = Speedup;

    fn tiles(&self) -> &CompressedData<Array2<Self::TileType>, TilesLoadInfo> {
        &self.tiles
    }

    fn tiles_mut(&mut self) -> &mut CompressedData<Array2<Self::TileType>, TilesLoadInfo> {
        &mut self.tiles
    }
}

impl TileMapLayer for SwitchLayer {
    type TileType = Switch;

    fn tiles(&self) -> &CompressedData<Array2<Self::TileType>, TilesLoadInfo> {
        &self.tiles
    }

    fn tiles_mut(&mut self) -> &mut CompressedData<Array2<Self::TileType>, TilesLoadInfo> {
        &mut self.tiles
    }
}

impl TileMapLayer for TuneLayer {
    type TileType = Tune;

    fn tiles(&self) -> &CompressedData<Array2<Self::TileType>, TilesLoadInfo> {
        &self.tiles
    }

    fn tiles_mut(&mut self) -> &mut CompressedData<Array2<Self::TileType>, TilesLoadInfo> {
        &mut self.tiles
    }
}

impl AnyTile for Tile {
    fn id(&self) -> u8 { self.id }

    fn flags(&self) -> Option<TileFlags> { Some(self.flags) }
}

impl AnyTile for GameTile {
    fn id(&self) -> u8 { self.id }

    fn flags(&self) -> Option<TileFlags> { Some(self.flags) }
}

impl AnyTile for Switch {
    fn id(&self) -> u8 { self.id }

    fn flags(&self) -> Option<TileFlags> { Some(self.flags) }
}

impl AnyTile for Tele {
    fn id(&self) -> u8 { self.id }

    fn flags(&self) -> Option<TileFlags> { None }
}

impl AnyTile for Speedup {
    fn id(&self) -> u8 { self.id }

    fn flags(&self) -> Option<TileFlags> { None }
}

impl AnyTile for Tune {
    fn id(&self) -> u8 { self.id }

    fn flags(&self) -> Option<TileFlags> { None }
}

impl AnyLayer for GameLayer {
    fn kind() -> LayerKind {
        LayerKind::Game
    }

    fn get(layer: &Layer) -> Option<&Self> {
        if let Layer::Game(l) = layer {
            Some(l)
        }
        else {
            None
        }
    }
}

impl AnyLayer for TilesLayer {
    fn kind() -> LayerKind {
        LayerKind::Tiles
    }

    fn get(layer: &Layer) -> Option<&Self> {
        if let Layer::Tiles(l) = layer {
            Some(l)
        }
        else {
            None
        }
    }
}

impl AnyLayer for QuadsLayer {
    fn kind() -> LayerKind {
        LayerKind::Quads
    }

    fn get(layer: &Layer) -> Option<&Self> {
        if let Layer::Quads(l) = layer {
            Some(l)
        }
        else {
            None
        }
    }
}

impl AnyLayer for FrontLayer {
    fn kind() -> LayerKind {
        LayerKind::Front
    }

    fn get(layer: &Layer) -> Option<&Self> {
        if let Layer::Front(l) = layer {
            Some(l)
        }
        else {
            None
        }
    }
}

impl AnyLayer for TeleLayer {
    fn kind() -> LayerKind {
        LayerKind::Tele
    }

    fn get(layer: &Layer) -> Option<&Self> {
        if let Layer::Tele(l) = layer {
            Some(l)
        }
        else {
            None
        }
    }
}

impl AnyLayer for SpeedupLayer {
    fn kind() -> LayerKind {
        LayerKind::Speedup
    }

    fn get(layer: &Layer) -> Option<&Self> {
        if let Layer::Speedup(l) = layer {
            Some(l)
        }
        else {
            None
        }
    }
}

impl AnyLayer for SwitchLayer {
    fn kind() -> LayerKind {
        LayerKind::Switch
    }

    fn get(layer: &Layer) -> Option<&Self> {
        if let Layer::Switch(l) = layer {
            Some(l)
        }
        else {
            None
        }
    }
}

impl AnyLayer for TuneLayer {
    fn kind() -> LayerKind {
        LayerKind::Tune
    }

    fn get(layer: &Layer) -> Option<&Self> {
        if let Layer::Tune(l) = layer {
            Some(l)
        }
        else {
            None
        }
    }
}

impl AnyLayer for SoundsLayer {
    fn kind() -> LayerKind {
        LayerKind::Sounds
    }

    fn get(layer: &Layer) -> Option<&Self> {
        if let Layer::Sounds(l) = layer {
            Some(l)
        }
        else {
            None
        }
    }
}