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
mod container;
mod builders;
mod any_system;

pub use self::container::{
    Systems, Priority, StatsType, SystemId,
    PredecessorsCache, SystemHandle
};
#[cfg(feature="parallel_systems")]
pub use self::container::{SendSystems, SendSystemsStats};
pub use self::builders::*;
pub use self::any_system::AnySystem;

use std::cell::UnsafeCell;
use std::any::{Any, TypeId};
use crate::resource::ResourcesCreation;
use crate::storage::{SubStorages, StorageRegistry};
use crate::component::{self, Component};
use crate::bitmask::Bitmask;
use crate::{Entities, Resources, EntitiesThreadLocal, ResourcesThreadLocal, EntitiesCreation};
#[cfg(feature="debug_parameters")]
use crate::debug::SystemDebug;
#[cfg(feature="async")]
use futures::Future;
#[cfg(feature="async")]
use futures::task::{ArcWake, waker_ref, Context, Poll};
#[cfg(feature="async")]
use std::pin::Pin;
#[cfg(feature="async")]
use std::cell::Cell;
#[cfg(feature="async")]
use std::sync::Arc;

/// Trait for systems that can run from any thread in parallel with other systems.
///
/// Types implementing this trait must be `Send` and are usually called `Send` `System`
/// in the documentation.
///
/// Any function that receives an `Entities` and a `Resources` parameter in that order
/// can be added as a `System` to the world.
pub trait System: Send{
    fn run(&mut self, entities: Entities, resources: Resources);
    fn checks(_: &mut StorageRegistry) -> Option<SystemConditionSend> where Self: Sized { None }
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
    fn updates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn needs() -> Vec<TypeId> where Self: Sized { vec![] }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}

/// Trait for systems that can only run from the main thread but in parallel with
/// `Send` systems.
///
/// Any function that receives an `EntitiesThreadLocal` and a `ResourcesThreadLocal`
/// parameter in that order can be added as a `SystemThreadLocal` to the world.
pub trait SystemThreadLocal{
    fn run(&mut self, entities: EntitiesThreadLocal, resources: ResourcesThreadLocal);
    fn checks(_: &mut StorageRegistry) -> Option<SystemConditionThreadLocal> where Self: Sized { None }
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn runs_on_gpu() -> bool  where Self: Sized { false }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
    fn updates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn needs() -> Vec<TypeId> where Self: Sized { vec![] }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}

impl<F: FnMut(Entities, Resources) + Send> System for F{
    fn run(&mut self, e: Entities, r: Resources){
        (*self)(e,r)
    }
}

impl<F: FnMut(EntitiesThreadLocal, ResourcesThreadLocal)> SystemThreadLocal for F{
    fn run(&mut self, e: EntitiesThreadLocal, r: ResourcesThreadLocal){
        (*self)(e,r)
    }
}

/// Trait for systems that receive a data parameter and can run from any
/// thread in parallel with other systems.
///
/// This trait is mostly useful from dynamic systems that are funcitons with their corresponding
/// objects created outside the dynamic library since dynamic systems can't allocate memory
pub trait SystemWithData<D: Send + 'static>: Send{
    fn run(&mut self, data: &mut D, entities: Entities, resources: Resources);
    fn checks(_: &mut StorageRegistry) -> Option<SystemConditionSend> where Self: Sized { None }
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
    fn updates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn needs() -> Vec<TypeId> where Self: Sized { vec![] }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}

impl<D: Send + 'static, F: FnMut(&mut D, Entities, Resources) + Send> SystemWithData<D> for F {
    fn run(&mut self, data: &mut D, entities: Entities, resources: Resources){
        self(data, entities, resources)
    }
}

impl<D: Send + 'static, S: SystemWithData<D> + Send> System for (S, D){
    fn run(&mut self, entities: Entities, resources: Resources){
        self.0.run(&mut self.1, entities, resources)
    }
    fn checks(entities: &mut StorageRegistry) -> Option<SystemConditionSend> where Self: Sized {
        S::checks(entities)
    }
    fn name() -> Option<&'static str> where Self: Sized { S::name() }
    fn before() -> Vec<SystemId> where Self: Sized { S::before() }
    fn after() -> Vec<SystemId> where Self: Sized { S::after() }
    fn updates() -> Vec<TypeId> where Self: Sized { S::updates() }
    fn needs() -> Vec<TypeId> where Self: Sized { S::needs() }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}


/// Trait for systems that receive a data parameter and can only run from
/// the main thread but in parallel with `Send` systems.
///
/// This trait is mostly useful from dynamic systems that are funcitons with their corresponding
/// objects created outside the dynamic library since dynamic systems can't allocate memory
pub trait SystemWithDataThreadLocal<D: 'static>{
    fn run(&mut self, data: &mut D, entities: EntitiesThreadLocal, resources: ResourcesThreadLocal);
    fn checks(_: &mut StorageRegistry) -> Option<SystemConditionThreadLocal> where Self: Sized { None }
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn runs_on_gpu() -> bool  where Self: Sized { false }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
    fn updates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn needs() -> Vec<TypeId> where Self: Sized { vec![] }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}

impl<D: 'static, F: FnMut(&mut D, EntitiesThreadLocal, ResourcesThreadLocal)> SystemWithDataThreadLocal<D> for F {
    fn run(&mut self, data: &mut D, entities: EntitiesThreadLocal, resources: ResourcesThreadLocal){
        self(data, entities, resources)
    }
}

impl<D: 'static, S: SystemWithDataThreadLocal<D>> SystemThreadLocal for (S, D){
    fn run(&mut self, entities: EntitiesThreadLocal, resources: ResourcesThreadLocal){
        self.0.run(&mut self.1, entities, resources)
    }
    fn checks(e: &mut StorageRegistry) -> Option<SystemConditionThreadLocal>
        where Self: Sized
    {
        S::checks(e)
    }
    fn name() -> Option<&'static str> where Self: Sized { S::name() }
    fn runs_on_gpu() -> bool  where Self: Sized { S::runs_on_gpu() }
    fn before() -> Vec<SystemId> where Self: Sized { S::before() }
    fn after() -> Vec<SystemId> where Self: Sized { S::after() }
    fn updates() -> Vec<TypeId> where Self: Sized { S::updates() }
    fn needs() -> Vec<TypeId> where Self: Sized { S::needs() }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}

/// Trait for systems that can create entities and resources.
///
/// These systems will run in the main thread and always alone with nothing
/// else running in parallel
pub trait CreationSystem{
    fn run(&mut self, entities: EntitiesCreation, resources: ResourcesCreation);
    fn checks(_: &mut StorageRegistry) -> Option<SystemConditionCreation> where Self: Sized {
        None
    }
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn runs_on_gpu() -> bool  where Self: Sized { false }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
    fn updates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn needs() -> Vec<TypeId> where Self: Sized { vec![] }
    fn creates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}

/// Trait for systems that receive a data parameter and can create entities and resources.
///
/// These systems will run in the main thread and always alone with nothing
/// else running in parallel
///
/// This trait is mostly useful from dynamic systems that are funcitons with their corresponding
/// objects created outside the dynamic library since dynamic systems can't allocate memory
pub trait CreationSystemWithData<D: 'static>{
    fn run(&mut self, data: &mut D, entities: EntitiesCreation, resources: ResourcesCreation);
    fn checks(_: &mut StorageRegistry) -> Option<SystemConditionCreation> where Self: Sized { None }
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn runs_on_gpu() -> bool  where Self: Sized { false }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
    fn updates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn needs() -> Vec<TypeId> where Self: Sized { vec![] }
    fn creates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}

/// Trait for systems that will run only once from any thread in parallel with other systems.
///
/// Types implementing this trait must be `Send` and are usually called `Send` `System`
/// in the documentation.
///
/// Any FnOnce that receives an `Entities` and a `Resources` parameter in that order
/// can be added as a `System` to the world.
pub trait SystemOnce: Send{
    fn run(self, entities: Entities, resources: Resources);
    fn checks(_: &mut StorageRegistry) -> Option<SystemConditionSendOnce> where Self: Sized { None }
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
    fn updates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn needs() -> Vec<TypeId> where Self: Sized { vec![] }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}

impl<F: FnOnce(Entities, Resources) + Send> SystemOnce for F{
    fn run(self, e: Entities, r: Resources){
        (self)(e,r)
    }
}

pub struct SystemOnceRunner{
    runner: UnsafeCell<Box<dyn FnMut(Entities, Resources) + Send>>
}

unsafe impl Sync for SystemOnceRunner{}

impl SystemOnceRunner{
    pub fn new<S: SystemOnce + 'static>(system: S) -> SystemOnceRunner{
        let mut system = Some(system);
        SystemOnceRunner{
            runner: UnsafeCell::new(Box::new(move |entities, resources|
                if let Some(system) = system.take(){
                    system.run(entities, resources)
                }
            ))
        }
    }

    pub fn run(&self, entities: Entities, resources: Resources){
        unsafe{ (*self.runner.get())(entities, resources) }
    }
}

/// Trait for systems that will run only once from the main thread but parallel with `Send` systems.
///
/// Types implementing this trait must be `Send` and are usually called `Send` `System`
/// in the documentation.
///
/// Any FnOnce that receives an `Entities` and a `Resources` parameter in that order
/// can be added as a `System` to the world.
pub trait SystemOnceThreadLocal {
    fn run(self, entities: EntitiesThreadLocal, resources: ResourcesThreadLocal);
    fn checks(_: &mut StorageRegistry) -> Option<SystemConditionThreadLocalOnce> where Self: Sized { None }
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn runs_on_gpu() -> bool  where Self: Sized { false }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
    fn updates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn needs() -> Vec<TypeId> where Self: Sized { vec![] }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}

impl<F: FnOnce(EntitiesThreadLocal, ResourcesThreadLocal) + Send> SystemOnceThreadLocal for F{
    fn run(self, e: EntitiesThreadLocal, r: ResourcesThreadLocal){
        (self)(e,r)
    }
}

pub struct SystemOnceThreadLocalRunner{
    runner: Box<dyn FnMut(EntitiesThreadLocal, ResourcesThreadLocal)>
}

impl SystemOnceThreadLocalRunner{
    pub fn new<S: SystemOnceThreadLocal + 'static>(system: S) -> SystemOnceThreadLocalRunner{
        let mut system = Some(system);
        SystemOnceThreadLocalRunner{
            runner: Box::new(move |entities, resources|
                if let Some(system) = system.take(){
                    system.run(entities, resources)
                }
            )
        }
    }

    pub fn run(&mut self, entities: EntitiesThreadLocal, resources: ResourcesThreadLocal){
        (*self.runner)(entities, resources)
    }
}

/// Trait for creation systems that will run only once.
///
/// Types implementing this trait must be `Send` and are usually called `Send` `System`
/// in the documentation.
///
/// Any FnOnce that receives an `Entities` and a `Resources` parameter in that order
/// can be added as a `System` to the world.
pub trait CreationSystemOnce {
    fn run(self, entities: EntitiesCreation, resources: ResourcesCreation);
    fn checks(_: &mut StorageRegistry) -> Option<SystemConditionCreationOnce> where Self: Sized { None }
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn runs_on_gpu() -> bool  where Self: Sized { false }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
    fn updates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn needs() -> Vec<TypeId> where Self: Sized { vec![] }
    fn creates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}

impl<F: FnOnce(EntitiesCreation, ResourcesCreation) + Send> CreationSystemOnce for F{
    fn run(self, e: EntitiesCreation, r: ResourcesCreation){
        (self)(e,r)
    }
}

pub struct CreationSystemOnceRunner{
    runner: Box<dyn FnMut(EntitiesCreation, ResourcesCreation)>
}

impl CreationSystemOnceRunner{
    pub fn new<S: CreationSystemOnce + 'static>(system: S) -> CreationSystemOnceRunner{
        let mut system = Some(system);
        CreationSystemOnceRunner{
            runner: Box::new(move |entities, resources|
                if let Some(system) = system.take(){
                    system.run(entities, resources)
                }
            )
        }
    }

    pub fn run(&mut self, entities: EntitiesCreation, resources: ResourcesCreation){
        (*self.runner)(entities, resources)
    }
}

/// Trait for systems that can create entities and resources.
///
/// These systems will run in the main thread and always alone with nothing
/// else running in parallel
#[cfg(feature = "async")]
pub trait CreationSystemAsync{
    fn run(self, entities: EntitiesCreation) -> Pin<Box<dyn Future<Output = ()>>>;
    fn checks(_: &mut StorageRegistry) -> Option<SystemConditionCreationAsync> where Self: Sized {
        None
    }
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn runs_on_gpu() -> bool  where Self: Sized { false }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
    fn updates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn needs() -> Vec<TypeId> where Self: Sized { vec![] }
    fn creates() -> Vec<TypeId> where Self: Sized { vec![] }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}

#[cfg(feature = "async")]
pub struct Task{
    future: UnsafeCell<Option<Pin<Box<dyn Future<Output = ()>>>>>,
    ready: Cell<bool>,
}

#[cfg(feature = "async")]
impl Task{
    pub fn new(future: Pin<Box<dyn Future<Output = ()>>>) -> Task{
        Task{
            future: UnsafeCell::new(Some(future)),
            ready: Cell::new(true)
        }
    }

    pub fn is_ready(&self) -> bool{
        self.ready.get()
    }

    pub fn future(&self) -> Option<Pin<Box<dyn Future<Output = ()>>>>{
        unsafe{ (*self.future.get()).take() }
    }

    pub fn reset_future(&self, future: Pin<Box<dyn Future<Output = ()>>>){
        unsafe{ *self.future.get() = Some(future) }
    }

    pub fn run(arc_self: &Arc<Self>) -> Poll<()> {
        if arc_self.is_ready(){
            let waker = waker_ref(arc_self);
            let context = &mut Context::from_waker(&*waker);
            arc_self.ready.set(false);
            if let Some(mut future) = arc_self.future(){
                let poll_res = future.as_mut().poll(context);
                if Poll::Pending == poll_res{
                    arc_self.reset_future(future)
                }
                poll_res
            }else{
                Poll::Pending
            }
        }else{
            Poll::Pending
        }
    }
}

#[cfg(feature = "async")]
unsafe impl Send for Task{}
#[cfg(feature = "async")]
unsafe impl Sync for Task{}

#[cfg(feature = "async")]
impl ArcWake for Task {
    fn wake_by_ref(arc_self: &Arc<Self>) {
        arc_self.ready.set(true)
    }
}

impl<F: FnMut(EntitiesCreation, ResourcesCreation)> CreationSystem for F{
    fn run(&mut self, entities: EntitiesCreation, resources: ResourcesCreation){
        self(entities, resources)
    }
}


impl<D: 'static, F: FnMut(&mut D, EntitiesCreation, ResourcesCreation)> CreationSystemWithData<D> for F{
    fn run(&mut self, data: &mut D, entities: EntitiesCreation, resources: ResourcesCreation){
        self(data, entities, resources)
    }
}

#[cfg(feature = "async")]
impl<F: FnOnce(CreationProxy) -> Pin<Box<dyn Future<Output = ()>>>> CreationSystemAsync for F{
    fn run(self, entities: CreationProxy) -> Pin<Box<dyn Future<Output = ()>>>{
        self(entities)
    }
}

impl<D: 'static, S: CreationSystemWithData<D>> CreationSystem for (S, D) {
    fn run(&mut self, entities: EntitiesCreation, resources: ResourcesCreation){
        self.0.run(&mut self.1, entities, resources)
    }
    fn checks(entities: &mut StorageRegistry) -> Option<SystemConditionCreation> where Self: Sized {
        S::checks(entities)
    }
    fn name() -> Option<&'static str> where Self: Sized { S::name() }
    fn runs_on_gpu() -> bool  where Self: Sized { S::runs_on_gpu() }
    fn before() -> Vec<SystemId> where Self: Sized { S::before() }
    fn after() -> Vec<SystemId> where Self: Sized { S::after() }
    fn updates() -> Vec<TypeId> where Self: Sized { S::updates() }
    fn needs() -> Vec<TypeId> where Self: Sized { S::needs() }
    fn creates() -> Vec<TypeId> where Self: Sized { S::creates() }
    fn reads() -> Vec<TypeId> where Self: Sized { vec![] }
    fn writes() -> Vec<TypeId> where Self: Sized { vec![] }
    fn file_line_info(&self) -> &'static str { "" }
}

#[derive(Debug)]
pub enum SystemCondition{
    StorageChanged(component::Id),
    HasComponents(Bitmask),
    ResourcesChanged(TypeId, Box<dyn Any>),
    HasResource(TypeId),
    All(Vec<SystemCondition>),
    Any(Vec<SystemCondition>),
    Not(Box<SystemCondition>),
}

unsafe impl Send for SystemCondition{}
unsafe impl Sync for SystemCondition{}

impl SystemCondition{
    pub fn all(all: Vec<SystemCondition>) -> SystemCondition{
        SystemCondition::All(all)
    }

    pub fn any(any: Vec<SystemCondition>) -> SystemCondition{
        SystemCondition::Any(any)
    }

    pub fn storage_changed<C: Component>() -> SystemCondition{
        SystemCondition::StorageChanged(TypeId::of::<C>())
    }

    pub fn has_resource<R: 'static>() -> SystemCondition{
        SystemCondition::HasResource(TypeId::of::<R>())
    }

    pub fn has_any(mask: Bitmask) -> SystemCondition{
        SystemCondition::HasComponents(mask)
    }

    pub fn not(condition: SystemCondition) -> SystemCondition{
        SystemCondition::Not(Box::new(condition))
    }

    pub fn resource_changed<R: 'static, F: 'static + Send + Fn(&R) -> bool>(f: F) -> SystemCondition{
        let boxed: Box<dyn Fn(&R) -> bool> = Box::new(f);
        SystemCondition::ResourcesChanged(TypeId::of::<R>(), Box::new(boxed))
    }

    pub fn else_run<Else>(self, cond_else: Else) -> SystemConditionElse<Else>{
        SystemConditionElse{
            condition: self,
            cond_else: Some(cond_else),
        }
    }

    pub fn build<Else>(self) -> SystemConditionElse<Else>{
        SystemConditionElse{
            condition: self,
            cond_else: None,
        }
    }

    fn check_should_run(&self, storages: &SubStorages, resources: &Resources) -> bool{
        match self{
            SystemCondition::StorageChanged(id) => storages.check_storage_changed(*id),

            SystemCondition::HasComponents(mask) => {
                storages.any_has_mask(mask.clone())
            }

            SystemCondition::Not(condition) => !condition.check_should_run(storages, resources),

            SystemCondition::Any(checks) => checks.iter()
                .any(|check| check.check_should_run(storages, resources)),

            SystemCondition::All(checks) => checks.iter()
                .all(|check| check.check_should_run(storages, resources)),

            SystemCondition::ResourcesChanged(id, func) => {
                resources.check_resource(id, func)
            }

            SystemCondition::HasResource(id) => resources.has_resource(id)
        }
    }

    fn check_should_run_thread_local(&self, storages: &SubStorages, resources: &ResourcesThreadLocal) -> bool{
        match self{
            SystemCondition::StorageChanged(id) => storages.check_storage_changed(*id),

            SystemCondition::HasComponents(mask) => {
                storages.any_has_mask(mask.clone())
            }

            SystemCondition::Not(condition) =>
                !condition.check_should_run_thread_local(storages, resources),

            SystemCondition::Any(checks) => checks.iter()
                .any(|check| check.check_should_run_thread_local(storages, resources)),

            SystemCondition::All(checks) => checks.iter()
                .all(|check| check.check_should_run_thread_local(storages, resources)),

            SystemCondition::ResourcesChanged(id, func) => {
                resources.check_resource(id, func)
            }

            SystemCondition::HasResource(id) => resources.has_resource(id)
        }
    }

    fn check_should_run_creation(&self, storages: &SubStorages, resources: &ResourcesCreation) -> bool{
        match self{
            SystemCondition::StorageChanged(id) => storages.check_storage_changed(*id),

            SystemCondition::HasComponents(mask) => {
                storages.any_has_mask(mask.clone())
            }

            SystemCondition::Not(condition) =>
                !condition.check_should_run_creation(storages, resources),

            SystemCondition::Any(checks) => checks.iter()
                .any(|check| check.check_should_run_creation(storages, resources)),

            SystemCondition::All(checks) => checks.iter()
                .all(|check| check.check_should_run_creation(storages, resources)),

            SystemCondition::ResourcesChanged(id, func) => {
                resources.check_resource(id, func)
            }

            SystemCondition::HasResource(id) => resources.has_resource(id)
        }
    }
}

pub struct SystemConditionElse<Else>{
    condition: SystemCondition,
    cond_else: Option<Else>,
}

impl<Else> SystemConditionElse<Else>{
    pub fn build<TraitObject>(self) -> SystemConditionElse<TraitObject>
    where Else: AnySystem<TraitObject>
    {
        let els = self.cond_else.map(|els| els.into_trait_object());

        SystemConditionElse {
            condition: self.condition,
            cond_else: els
        }
    }

    pub fn condition_else(self) -> (Option<SystemCondition>, Option<Else>){
        (Some(self.condition), self.cond_else)
    }
}

pub type SystemConditionSend = SystemConditionElse<SyncSystem>;
pub type SystemConditionSendOnce = SystemConditionElse<SystemOnceRunner>;
pub type SystemConditionThreadLocal = SystemConditionElse<Box<dyn SystemThreadLocal>>;
pub type SystemConditionThreadLocalOnce = SystemConditionElse<SystemOnceThreadLocalRunner>;
pub type SystemConditionCreation = SystemConditionElse<Box<dyn CreationSystem>>;
pub type SystemConditionCreationOnce = SystemConditionElse<CreationSystemOnceRunner>;
#[cfg(feature = "async")]
pub type SystemConditionCreationAsync = SystemConditionElse<Box<dyn CreationSystemAsync>>;


pub struct SyncSystem(UnsafeCell<Box<dyn System>>);

impl SyncSystem{
    fn new<S: System + 'static>(s: S) -> SyncSystem{
        SyncSystem(UnsafeCell::new(Box::new(s)))
    }

    unsafe fn borrow_mut(&self) -> &mut dyn System{
        &mut **self.0.get()
    }

    fn _borrow(&self) -> &dyn System{
        unsafe{ &**self.0.get() }
    }

    #[allow(dead_code)]
    fn file_line_info(&self) -> &'static str {
        self._borrow().file_line_info()
    }
}

unsafe impl Send for SyncSystem{}
unsafe impl Sync for SyncSystem{}

/// A Barrier is one more way to synchronize systems.
///
/// Any system can specify that it has to run before or after a Barrier
/// and a Barrier itself can also specify that it has to run after or before certain systems or
/// other Barriers
pub trait Barrier{
    fn name() -> Option<&'static str> where Self: Sized { None }
    fn before() -> Vec<SystemId> where Self: Sized { vec![] }
    fn after() -> Vec<SystemId> where Self: Sized { vec![] }
}