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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921

use crate::spawnable::SpawnableSet;
use crate::tilemap::Tilemap;
use crate::visual::{Lerpable, Costume, Drawable};
use crate::SYSTEM_PRIORITY_POST_FRAME;

use keeshond::scene::{Component, SceneType, ThinkerSystem, ThinkerArgs, DynArgList, DynArg};
use keeshond::util::{BakedRect, NamedItemStore};

use keeshond_datapack::{DataObject, TrustPolicy, ReadSeek, DataError, DataHandle, LoadErrorMode};
use keeshond_datapack::source::Source;

use std::collections::{HashMap, HashSet};
use std::str::FromStr;

use serde::{Serialize, Deserialize, Deserializer};
use bincode::Options;

#[derive(Clone)]
pub struct Position
{
    pub x : Lerpable<f64>,
    pub y : Lerpable<f64>
}

impl Position
{
    pub fn new(x : f64, y : f64) -> Position
    {
        Position
        {
            x : Lerpable::new(x),
            y : Lerpable::new(y)
        }
    }
}

impl Component for Position {}


pub struct Camera
{
    pub x : f64,
    pub y : f64,
    pub(crate) old_x : f64,
    pub(crate) old_y : f64,
    pub(crate) older_x : f64,
    pub(crate) older_y : f64,
    pub scroll_stop : BakedRect<f64>
}

impl Camera
{
    pub fn bounds(&self, width : f64, height : f64, scroll_rate_x : f64, scroll_rate_y : f64) -> BakedRect<f64>
    {
        BakedRect
        {
            x1: self.x * scroll_rate_x,
            y1: self.y * scroll_rate_y,
            x2: self.x * scroll_rate_x + width,
            y2: self.y * scroll_rate_y + height
        }
    }

    pub fn bounds_lerped(&self, width : f64, height : f64, scroll_rate_x : f64, scroll_rate_y : f64) -> BakedRect<f64>
    {
        let mut current = BakedRect
        {
            x1: self.x * scroll_rate_x,
            y1: self.y * scroll_rate_y,
            x2: self.x * scroll_rate_x + width,
            y2: self.y * scroll_rate_y + height
        };

        let old = BakedRect
        {
            x1: self.older_x * scroll_rate_x,
            y1: self.older_y * scroll_rate_y,
            x2: self.older_x * scroll_rate_x + width,
            y2: self.older_y * scroll_rate_y + height
        };

        current.combine(old);

        current
    }
}

impl Default for Camera
{
    fn default() -> Self
    {
        Camera
        {
            x : 0.0,
            y : 0.0,
            old_x : 0.0,
            old_y : 0.0,
            older_x : 0.0,
            older_y : 0.0,
            scroll_stop : Default::default()
        }
    }
}

impl Component for Camera {}

pub struct CameraThinker<T : SceneType + 'static>
{
    first_frame : bool,
    phantom : std::marker::PhantomData::<T>
}

impl<T : SceneType + 'static> CameraThinker<T>
{
    pub fn new() -> CameraThinker::<T>
    {
        CameraThinker::<T>
        {
            first_frame : true,
            phantom : std::marker::PhantomData
        }
    }
}

impl<T : SceneType + 'static> ThinkerSystem<T> for CameraThinker<T>
{
    fn think(&mut self, args : ThinkerArgs<T>)
    {
        let mut camera_store = args.components.store_mut::<Camera>();
        let mut camera = camera_store.singleton_mut();
        let (screen_width, screen_height) = args.game.renderer().base_size();

        let x2 = (camera.scroll_stop.x2 - screen_width as f64).max(0.0);
        let y2 = (camera.scroll_stop.y2 - screen_height as f64).max(0.0);

        camera.x = camera.x.max(camera.scroll_stop.x1).min(x2);
        camera.y = camera.y.max(camera.scroll_stop.y1).min(y2);

        let max_lerp_distance = (screen_width + screen_height) as f64 / 2.0;
        let lerp_distance = ((camera.x - camera.old_x).powi(2) + (camera.y - camera.old_y).powi(2)).sqrt();

        if self.first_frame || lerp_distance > max_lerp_distance
        {
            camera.old_x = camera.x;
            camera.old_y = camera.y;
        }

        camera.older_x = camera.old_x;
        camera.older_y = camera.old_y;
        camera.old_x = camera.x;
        camera.old_y = camera.y;

        for (_, camera) in camera_store.iter_mut()
        {
            camera.x = camera.x.max(camera.scroll_stop.x1).min(camera.scroll_stop.x2);
            camera.y = camera.y.max(camera.scroll_stop.y1).min(camera.scroll_stop.y2);

            if self.first_frame
            {
                camera.old_x = camera.x;
                camera.old_y = camera.y;
            }

            camera.older_x = camera.old_x;
            camera.older_y = camera.old_y;
            camera.old_x = camera.x;
            camera.old_y = camera.y;
        }

        self.first_frame = false;
    }

    fn priority(&self) -> i32 { SYSTEM_PRIORITY_POST_FRAME }
}

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct LevelBackground
{
    pub r : f32,
    pub g : f32,
    pub b : f32
}

impl LevelBackground
{
    pub fn black() -> LevelBackground
    {
        LevelBackground
        {
            r : 0.0,
            g : 0.0,
            b : 0.0
        }
    }
}

pub struct LevelBackgroundTag {}

impl Component for LevelBackgroundTag {}

#[derive(Clone, Serialize, Deserialize, Debug, Display)]
pub enum LevelRepresentation
{
    None,
    Actor
    {
        custom_costume : Option<DataHandle<Costume>>
    },
    Tilemap
    {
        tiles : Tilemap
    }
}

impl LevelRepresentation
{
    pub fn is_none(&self) -> bool
    {
        match self
        {
            LevelRepresentation::None => { true }
            _ => { false }
        }
    }

    pub fn index(&self) -> usize
    {
        match self
        {
            LevelRepresentation::None => { 0 }
            LevelRepresentation::Actor { .. } => { 1 }
            LevelRepresentation::Tilemap { .. } => { 2 }
        }
    }
}

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct LevelSpawnable
{
    #[serde(rename = "ty")]
    #[serde(alias = "spawn_name_id")]
    pub spawn_name_id : u32,
    pub x : f64,
    pub y : f64,
    pub args : Option<DynArgList>,
    #[serde(rename = "re")]
    #[serde(alias = "representation")]
    pub representation : LevelRepresentation
}

impl LevelSpawnable
{
    pub fn modify_args<F : FnMut(&mut DynArgList)>(&mut self, mut func : F)
    {
        if self.args.is_none()
        {
            self.args = Some(DynArgList::new());
        }

        if let Some(args) = &mut self.args
        {
            func(args);
        }
    }

    pub fn args_empty(&self) -> bool
    {
        match &self.args
        {
            None => { true }
            Some(arg_list) =>
            {
                arg_list.is_empty()
            }
        }
    }
}

#[derive(Clone, Default, Serialize, Debug)]
struct SpawnableNameIdMap
{
    #[serde(skip_serializing)]
    names : HashMap<String, u32>,
    #[serde(serialize_with = "crate::util::sort_map")]
    #[serde(rename = "i")]
    #[serde(alias = "ids")]
    ids : HashMap<u32, String>
}

#[derive(Deserialize, Debug)]
struct NameIdMapRaw
{
    #[serde(rename = "i")]
    #[serde(alias = "ids")]
    ids : HashMap<u32, String>
}

impl<'de> Deserialize<'de> for SpawnableNameIdMap
{
    fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
        where D : Deserializer<'de>
    {
        let map_raw = NameIdMapRaw::deserialize(deserializer)?;

        let mut names = HashMap::new();

        for (id, name) in &map_raw.ids
        {
            names.insert(name.clone(), *id);
        }

        Ok(SpawnableNameIdMap
        {
            names,
            ids : map_raw.ids
        })
    }
}

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct LevelLayer
{
    #[serde(default)]
    spawnables : Vec<LevelSpawnable>,
    #[serde(default)]
    depth : Option<f32>,
    #[serde(default)]
    scroll_rate : Option<(f32, f32)>,
    #[serde(default)]
    visible : bool,
    #[serde(default)]
    locked : bool
}

impl Default for LevelLayer
{
    fn default() -> LevelLayer
    {
        LevelLayer
        {
            spawnables : Vec::new(),
            depth : None,
            scroll_rate : None,
            visible : true,
            locked : false
        }
    }
}

impl LevelLayer
{
    pub fn spawnable(&self, id : usize) -> Option<&LevelSpawnable>
    {
        self.spawnables.get(id)
    }

    pub fn spawnable_mut(&mut self, id : usize) -> Option<&mut LevelSpawnable>
    {
        self.spawnables.get_mut(id)
    }

    pub fn insert_spawnable(&mut self, pos : usize, spawnable : LevelSpawnable) -> bool
    {
        if pos <= self.spawnables.len()
        {
            self.spawnables.insert(pos, spawnable);

            return true;
        }

        false
    }

    pub fn remove_spawnable(&mut self, id : usize) -> Option<LevelSpawnable>
    {
        if id >= self.spawnables.len()
        {
            return None;
        }

        Some(self.spawnables.remove(id))
    }

    pub fn spawnable_count(&self) -> usize
    {
        self.spawnables.len()
    }

    pub fn depth(&self) -> Option<f32>
    {
        self.depth
    }

    pub fn set_depth(&mut self, depth : Option<f32>)
    {
        self.depth = depth;
    }

    pub fn scroll_rate(&self) -> Option<(f32, f32)>
    {
        self.scroll_rate
    }

    pub fn set_scroll_rate(&mut self, scroll_rate : Option<(f32, f32)>)
    {
        self.scroll_rate = scroll_rate;
    }

    pub fn visible(&self) -> bool
    {
        self.visible
    }

    pub fn set_visible(&mut self, visible : bool)
    {
        self.visible = visible;
    }

    pub fn locked(&self) -> bool
    {
        self.locked
    }

    pub fn set_locked(&mut self, locked : bool)
    {
        self.locked = locked;
    }
}

#[derive(Clone, Debug)]
pub struct LevelApplyOptions
{
    pub global_properties : bool
}

impl Default for LevelApplyOptions
{
    fn default() -> Self
    {
        LevelApplyOptions
        {
            global_properties : true
        }
    }
}

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Level
{
    header : String,
    #[serde(rename = "bb")]
    bounds : BakedRect<f64>,
    bg : Option<LevelBackground>,
    #[serde(default)]
    spawnable_set : DataHandle<SpawnableSet>,
    spawnable_names : SpawnableNameIdMap,
    #[serde(default)]
    layers : NamedItemStore<LevelLayer>,
    #[serde(skip)]
    generation : u64
}

impl Level
{
    pub fn new() -> Level
    {
        Level
        {
            header : String::from("Keeshond Level Format r1"),
            bounds : BakedRect::default(),
            bg : None,
            spawnable_set : DataHandle::new("", ""),
            spawnable_names : SpawnableNameIdMap::default(),
            layers : NamedItemStore::new(),
            generation : 0
        }
    }

    fn next_generation(&mut self)
    {
        self.generation += 1;

        if self.generation == 0
        {
            warn!("Generation overflow!");
            self.generation = 1;
        }
    }

    pub fn apply<T : SceneType + 'static>(args : &mut ThinkerArgs<T>, apply_options : LevelApplyOptions)
    {
        let mut level = Level::new();

        {
            let mut level_store = args.game.res().store_mut::<Level>();
            let level_handle = DataHandle::new("level_example", "level.keelvl");

            if let Some(store_level) = level_handle.get(&mut level_store, LoadErrorMode::Fatal).cloned()
            {
                level = store_level.clone();
            }
        }

        if apply_options.global_properties
        {
            let mut camera_store = args.components.store_mut::<Camera>();
            let mut camera = camera_store.singleton_mut();

            camera.scroll_stop = level.bounds;

            if let Some(level_bg) = level.bg
            {
                let bg_store = args.components.store_mut::<LevelBackgroundTag>();

                if bg_store.count() == 0
                {
                    let bg_entity = args.scene.add_entity_later();
                    args.scene.add_component_later(&bg_entity, LevelBackgroundTag {});
                    args.scene.add_component_later(&bg_entity, Drawable::with_background_color(level_bg.r, level_bg.g, level_bg.b));
                }
            }
        }

        let mut spawnable_map : HashMap<u32, T::SpawnableIdType> = HashMap::new();

        for (id, name) in &level.spawnable_names.ids
        {
            if let Ok(spawnable_type) = T::SpawnableIdType::from_str(name)
            {
                spawnable_map.insert(*id, spawnable_type);
            }
            else
            {
                warn!("Unknown Spawnable name \"{}\"", name);
            }
        }

        for layer in &level.layers
        {
            for spawnable in &layer.spawnables
            {
                if let Some(id) = spawnable_map.get(&spawnable.spawn_name_id)
                {
                    let mut new_args;

                    if let Some(spawnable_args) = &spawnable.args
                    {
                        new_args = spawnable_args.clone();
                    }
                    else
                    {
                        new_args = DynArgList::new();
                    }

                    if let Some(depth) = layer.depth
                    {
                        if new_args.get_named("draw_depth").is_none()
                        {
                            new_args.push_named(String::from("draw_depth"), DynArg::Float(depth as f64));
                        }
                    }
                    if let Some((scroll_rate_x, scroll_rate_y)) = layer.scroll_rate
                    {
                        if new_args.get_named("scroll_rate_x").is_none() && new_args.get_named("scroll_rate_y").is_none()
                        {
                            new_args.push_named(String::from("scroll_rate_x"), DynArg::Float(scroll_rate_x as f64));
                            new_args.push_named(String::from("scroll_rate_y"), DynArg::Float(scroll_rate_y as f64));
                        }
                    }

                    let entity = args.scene.spawn_later_with(*id, args.game, spawnable.x, spawnable.y, &new_args);

                    match &spawnable.representation
                    {
                        LevelRepresentation::None => {}
                        LevelRepresentation::Actor { .. } => {}
                        LevelRepresentation::Tilemap { tiles } =>
                        {
                            args.scene.add_component_later(&entity, tiles.clone());
                        }
                    }
                }
            }
        }
    }

    pub fn bounds(&self) -> &BakedRect<f64>
    {
        &self.bounds
    }

    pub fn set_bounds(&mut self, bounds : BakedRect<f64>)
    {
        self.bounds = bounds;

        self.next_generation();
    }

    pub fn background(&self) -> Option<&LevelBackground>
    {
        self.bg.as_ref()
    }

    pub fn set_background(&mut self, bg : Option<LevelBackground>)
    {
        self.bg = bg;

        self.next_generation();
    }

    pub fn spawnable_set(&self) -> &DataHandle<SpawnableSet>
    {
        &self.spawnable_set
    }

    pub fn set_spawnable_set(&mut self, spawnable_set : DataHandle<SpawnableSet>)
    {
        self.spawnable_set = spawnable_set;

        self.next_generation();
    }

    fn next_name_id(&mut self) -> u32
    {
        let mut next_id = 1;

        while self.spawnable_names.ids.contains_key(&next_id) // TODO optimize
        {
            next_id += 1;
        }

        next_id
    }

    pub fn spawnable_name_id(&self, name : &str) -> Option<u32>
    {
        self.spawnable_names.names.get(name).cloned()
    }

    pub fn spawnable_name_id_mut(&mut self, name : &str) -> u32
    {
        match self.spawnable_names.names.get(name).cloned()
        {
            None =>
            {
                let id = self.next_name_id();
                self.spawnable_names.names.insert(String::from(name), id);
                self.spawnable_names.ids.insert(id, String::from(name));

                self.next_generation();

                return id;
            }
            Some(id) => { return id; }
        }
    }

    pub fn spawnable_name_for_id(&self, id : u32) -> Option<&String>
    {
        self.spawnable_names.ids.get(&id)
    }

    pub fn clean_spawnable_names(&mut self)
    {
        let mut defined_set = HashSet::new();
        let mut used_set = HashSet::new();

        for id in self.spawnable_names.ids.keys()
        {
            defined_set.insert(*id);
        }

        for i in 0..self.layers.len()
        {
            if let Some(layer) = self.layers.get(i)
            {
                for spawnable in &layer.spawnables
                {
                    used_set.insert(spawnable.spawn_name_id);
                }
            }
        }

        for id in &defined_set
        {
            if !used_set.contains(id)
            {
                if let Some(name) = self.spawnable_names.ids.remove(id)
                {
                    self.spawnable_names.names.remove(&name);
                }
            }
        }
    }

    pub fn layer(&self, id : usize) -> Option<&LevelLayer>
    {
        self.layers.get(id)
    }

    pub fn set_layer(&mut self, id : usize, layer : LevelLayer) -> bool
    {
        let success = self.layers.set(id, layer);

        if success
        {
            self.next_generation();
        }

        success
    }

    pub fn modify_layer<F : FnMut(&mut LevelLayer)>(&mut self, id : usize, mut func : F) -> bool
    {
        if let Some(layer) = self.layers.get_mut(id)
        {
            func(layer);
            self.next_generation();

            return true;
        }

        false
    }

    pub fn insert_layer(&mut self, pos : usize, layer : LevelLayer) -> bool
    {
        let success = self.layers.insert_item(pos, layer);

        if success
        {
            self.next_generation();
        }

        success
    }

    pub fn remove_layer(&mut self, id : usize) -> Option<LevelLayer>
    {
        let item = self.layers.remove_item(id);

        if item.is_some()
        {
            self.next_generation();
        }

        item
    }

    pub fn rename_layer(&mut self, id : usize, new_name : &str) -> bool
    {
        let success = self.layers.rename_item(id, new_name);

        if success
        {
            self.next_generation();
        }

        success
    }

    pub fn layer_name(&self, id : usize) -> Option<String>
    {
        self.layers.get_name(id)
    }

    pub fn layer_id(&self, name : &str) -> Option<usize>
    {
        self.layers.get_id(name)
    }

    pub fn layer_count(&self) -> usize
    {
        self.layers.len()
    }

    pub fn layer_spawnable_count(&self, id : usize) -> usize
    {
        if let Some(layer) = self.layers.get(id)
        {
            return layer.spawnable_count();
        }

        0
    }

    pub fn spawnable(&self, layer_id : usize, spawnable_id : usize) -> Option<&LevelSpawnable>
    {
        if let Some(layer) = self.layers.get(layer_id)
        {
            return layer.spawnable(spawnable_id);
        }

        None
    }

    pub fn set_spawnable(&mut self, layer_id : usize, spawnable_id : usize, spawnable : LevelSpawnable) -> bool
    {
        if let Some(layer) = self.layers.get_mut(layer_id)
        {
            if let Some(old_spawnable) = layer.spawnable_mut(spawnable_id)
            {
                *old_spawnable = spawnable;
                self.next_generation();

                return true;
            }
        }

        false
    }

    pub fn modify_spawnable<F : FnMut(&mut LevelSpawnable)>(&mut self, layer_id : usize, spawnable_id : usize, mut func : F) -> bool
    {
        if let Some(layer) = self.layers.get_mut(layer_id)
        {
            if let Some(spawnable) = layer.spawnable_mut(spawnable_id)
            {
                func(spawnable);
                self.next_generation();

                return true;
            }
        }

        false
    }

    pub fn insert_spawnable(&mut self, layer_id : usize, spawnable_id : usize, spawnable : LevelSpawnable) -> bool
    {
        if let Some(layer) = self.layers.get_mut(layer_id)
        {
            let success = layer.insert_spawnable(spawnable_id, spawnable);

            if success
            {
                self.next_generation();
            }

            return success;
        }

        false
    }

    pub fn remove_spawnable(&mut self, layer_id : usize, spawnable_id : usize) -> Option<LevelSpawnable>
    {
        if let Some(layer) = self.layers.get_mut(layer_id)
        {
            let item = layer.remove_spawnable(spawnable_id);

            if item.is_some()
            {
                self.next_generation();
            }

            return item;
        }

        None
    }
}

impl DataObject for Level
{
    fn folder_name() -> &'static str where Self : Sized { "levels" }
    fn trust_policy() -> TrustPolicy { TrustPolicy::UntrustedOk }
    fn want_file(pathname : &str) -> bool where Self : Sized { pathname.ends_with(".keelvl") }

    fn from_io(reader : Box<dyn ReadSeek>, full_pathname : &str, _source : &mut Box<dyn Source>) -> Result<Self, DataError> where Self : Sized
    {
        let options = bincode::DefaultOptions::new().with_varint_encoding();

        match options.deserialize_from(reader)
        {
            Ok(loaded_data) =>
            {
                return Ok(loaded_data);
            },
            Err(error) =>
            {
                return Err(DataError::BadData(format!("{}: {}", full_pathname, error)));
            }
        }
    }

    fn write(&mut self, full_pathname : &str, source : &mut Box<dyn Source>) -> Result<(), DataError>
    {
        self.clean_spawnable_names();

        let writer = try_or_else!(source.write_file(full_pathname),
            |error| Err(DataError::PackageSourceError(error)));

        let options = bincode::DefaultOptions::new().with_varint_encoding();

        match options.serialize_into(writer, &self)
        {
            Err(error) =>
            {
                return Err(DataError::BadData(format!("{}: {}", full_pathname, error)));
            },
            Ok(_) =>
            {
                info!("Wrote level to {}", full_pathname);

                return Ok(());
            }
        }
    }

    fn generation(&self) -> u64
    {
        self.generation
    }

    fn set_generation(&mut self, generation : u64)
    {
        self.generation = generation;
    }
}