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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
use std::collections::HashSet;
use std::ops::{Deref, DerefMut};
use std::any::TypeId;
use std::cell::UnsafeCell;
use std::mem;
use std::marker::PhantomData;

use rayon::prelude::*;
use fnv::FnvHashMap;
use arrayvec::ArrayVec;

use entities::*;
use resource::*;
use bitset::*;
use join::*;

bitflags! {
    flags ResourceDescription: u32 {
        const ENTITY_DATA = 0b00000001
    }
}

struct ResourceCell {
    cell: UnsafeCell<Box<Resource>>,
    type_id: TypeId,
    desc: ResourceDescription,
}

impl ResourceCell {
    // pub unsafe fn get(&self) -> &Resource {
    //     (&*self.cell.get()).deref()
    // }

    pub unsafe fn get_mut(&self) -> &mut Resource {
        (&mut *self.cell.get()).deref_mut()
    }

    pub unsafe fn get_as<T: Resource>(&self) -> &T {
        assert!(self.type_id == TypeId::of::<T>());
        let borrow = &*self.cell.get();
        borrow.downcast_ref_unsafe::<T>()
    }

    pub unsafe fn get_as_mut<T: Resource>(&self) -> &mut T {
        assert!(self.type_id == TypeId::of::<T>());
        let borrow = &mut *self.cell.get();
        borrow.downcast_mut_unsafe::<T>()
    }
}

/// Constructs and configures a world resource.
pub struct ResourceBuilder<T: Resource> {
    resource: T,
    desc: ResourceDescription,
}

impl<T: Resource> ResourceBuilder<T> {
    /// Constructs a new `ResourceBuilder`.
    pub fn new(resource: T) -> ResourceBuilder<T> {
        ResourceBuilder {
            resource: resource,
            desc: ResourceDescription::empty(),
        }
    }

    fn to_resource_cell(self) -> ResourceCell {
        ResourceCell {
            cell: UnsafeCell::new(Box::new(self.resource)),
            type_id: TypeId::of::<T>(),
            desc: self.desc,
        }
    }
}

impl<T: Resource + EntityResource> ResourceBuilder<T> {
    /// Marks this resource as containing entity data which should be cleared when entities
    /// are destroyed.
    pub fn activate_entity_disposal(mut self) -> ResourceBuilder<T> {
        self.desc.insert(ENTITY_DATA);
        self
    }
}

/// Stores entities are resources, and provides mechanisms to update the world state via systems.
pub struct World {
    entities: Entities,
    resources: FnvHashMap<TypeId, (u8, ResourceCell)>,
    entity_resources: Vec<TypeId>,
    changes_buffer: Option<Vec<EntityChangeSet>>,
}

// resource access is ensured safe by the system scheduler
unsafe impl Sync for World {}

impl World {
    /// Constructs a new `World`.
    pub fn new() -> World {
        World {
            entities: Entities::new(),
            resources: FnvHashMap::default(),
            entity_resources: Vec::new(),
            changes_buffer: Some(Vec::new()),
        }
    }

    /// Registers a new resource with the `World`, allowing systems to access the resource.
    pub fn register<T: Resource>(&mut self, builder: ResourceBuilder<T>) -> u8 {
        let cell = builder.to_resource_cell();
        let type_id = cell.type_id;

        if cell.desc.contains(ENTITY_DATA) {
            self.entity_resources.push(type_id);
        }

        let id = self.resources.len() as u8;
        let value = (id, cell);
        self.resources.insert(type_id, value);

        id
    }

    /// Registers a new resource with the `World`, allowing systems to access the resource.
    pub fn register_resource<T: Resource>(&mut self, resource: T) -> u8 {
        self.register(resource.to_builder())
    }

    // Can only be safely called from within a system, and only for the resources the system declares
    unsafe fn get_resource<T: Resource>(&self) -> Option<(u8, &T)> {
        let type_id = TypeId::of::<T>();
        if let Some(&(id, ref resource)) = self.resources.get(&type_id) {
            let resource = resource.get_as();
            return Some((id, resource));
        }
        return None;
    }

    // Can only be safely called from within a system, and only for the resources the system declares
    unsafe fn get_resource_mut<T: Resource>(&self) -> Option<(u8, &mut T)> {
        let type_id = TypeId::of::<T>();
        if let Some(&(id, ref resource)) = self.resources.get(&type_id) {
            let resource = resource.get_as_mut();
            return Some((id, resource));
        }
        return None;
    }

    // Can only be safely called in between systems, on the main thread
    unsafe fn clean_deleted_entities(&mut self, changes: &[EntityChangeSet]) {
        for id in self.entity_resources.iter() {
            let &mut (_, ref mut resource) = self.resources.get_mut(&id).unwrap();
            let resource = resource.get_mut();
            for cs in changes.iter() {
                resource.clear_entity_data(&cs.deleted);
            }
        }
    }
}

trait System<S: Send + Sync + 'static>: Send {
    fn id(&self) -> u32;
    fn resource_access(&self) -> (&HashSet<TypeId>, &HashSet<TypeId>);
    fn execute(&mut self, &World, &S) -> EntityChangeSet;
}

struct FnSystem<S, F>
    where F: FnMut(&World, &S) -> EntityChangeSet + Send,
          S: Send + Sync + 'static
{
    id: u32,
    read: HashSet<TypeId>,
    write: HashSet<TypeId>,
    f: F,
    phantom: PhantomData<&'static S>,
}

impl<S: Send + Sync + 'static, T: FnMut(&World, &S) -> EntityChangeSet + Send> System<S> for FnSystem<S, T> {
    #[inline]
    fn id(&self) -> u32 {
        self.id
    }

    #[inline]
    fn resource_access(&self) -> (&HashSet<TypeId>, &HashSet<TypeId>) {
        (&self.read, &self.write)
    }

    #[inline]
    fn execute(&mut self, world: &World, state: &S) -> EntityChangeSet {
        (self.f)(world, state)
    }
}

/// Contains system execution state information.
pub struct SystemContext<'a, S: Send + Sync + 'static> {
    entities: &'a Entities,
    transaction: EntitiesTransaction<'a>,
    state: &'a S,
}

impl<'a, S: Send + Sync + 'static> Deref for SystemContext<'a, S> {
    type Target = EntitiesTransaction<'a>;

    fn deref(&self) -> &EntitiesTransaction<'a> {
        &self.transaction
    }
}

impl<'a, S: Send + Sync + 'static> DerefMut for SystemContext<'a, S> {
    fn deref_mut(&mut self) -> &mut EntitiesTransaction<'a> {
        &mut self.transaction
    }
}

impl<'a, S: Send + Sync + 'static> SystemContext<'a, S> {
    /// Gets the current system execution state.
    pub fn state(&self) -> &S {
        self.state
    }

    fn to_change_set(self) -> EntityChangeSet {
        self.transaction.to_change_set()
    }
}

/// Systems queued within a `SystemScope` may be scheduled to run in parallel.
pub struct SystemScope<S: Send + Sync + 'static> {
    systems: Vec<Box<System<S>>>,
}

impl<S: Send + Sync + 'static> SystemScope<S> {
    fn new() -> SystemScope<S> {
        SystemScope { systems: Vec::new() }
    }
}

/// Records system executions, to be run later within a `World`.
pub struct SystemCommandBuffer<S: Send + Sync + 'static = ()> {
    batches: Vec<Vec<Box<System<S>>>>,
}

impl SystemCommandBuffer<()> {
    /// Constructs a new 'SystemCommandBuffer' with an empty state.
    pub fn default() -> SystemCommandBuffer<()> {
        SystemCommandBuffer::new()
    }
}

impl<S: Send + Sync + 'static> SystemCommandBuffer<S> {
    /// Constructs a new `SystemCommandBuffer`.
    pub fn new() -> SystemCommandBuffer<S> {
        SystemCommandBuffer { batches: Vec::new() }
    }

    /// Queues a sequence of systems into the command buffer.
    /// Each system may potentially be run concurrently.
    pub fn queue_systems<'a, F, R>(&mut self, f: F) -> R
        where F: FnOnce(&mut SystemScope<S>) -> R + 'a
    {
        let mut scope = SystemScope::new();
        let result = f(&mut scope);

        let mut reading = HashSet::<TypeId>::new();
        let mut writing = HashSet::<TypeId>::new();
        let mut batch = Vec::<Box<System<S>>>::new();
        for system in scope.systems.into_iter() {
            {
                let (system_reading, system_writing) = system.resource_access();
                if !can_batch_system(&reading, &writing, (system_reading, system_writing)) {
                    self.batches.push(batch);
                    batch = Vec::<Box<System<S>>>::new();
                    reading.clear();
                    writing.clear();
                }

                reading = &reading | system_reading;
                writing = &writing | system_writing;
            }
            batch.push(system);
        }

        if batch.len() > 0 {
            self.batches.push(batch);
        }

        result
    }
}

fn can_batch_system(reading: &HashSet<TypeId>, writing: &HashSet<TypeId>, (system_reads, system_writes): (&HashSet<TypeId>, &HashSet<TypeId>)) -> bool {
    // the system does not write to any resources being read (which includes writers)
    // the system does not read any resources that are being written
    reading.is_disjoint(system_writes) && writing.is_disjoint(system_reads)
}

macro_rules! impl_run_system {
    ($name:ident [$($read:ident),*] [$($write:ident),*]) => (
        impl<S: Send + Sync + 'static> SystemScope<S> {
            /// Queues a new system into the command buffer.
            ///
            /// Each system queued within a single `SystemScope` may be executed
            /// in parallel with each other. See crate documentation for more
            /// information.
            #[allow(non_snake_case, unused_variables, unused_mut)]
            pub fn $name<$($read,)* $($write,)* F>(&mut self, mut f: F) -> u32
                where $($read:Resource,)*
                      $($write:Resource,)*
                      F: for<'a, 'b> FnMut(&'a mut SystemContext<'b, S>, $(&'b $read,)* $(&'b mut $write,)*) + Send + 'static
            {
                let system = move |world: &World, state: &S| {
                    // safety of these gets is ensured by the system scheduler
                    $(let (_, $read) = unsafe {
                        world.get_resource::<$read>().expect("World does not contain required resource")
                    };)*
                    $(let (_, mut $write) = unsafe {
                        world.get_resource_mut::<$write>().expect("World does not contain required resource")
                    };)*

                    let mut context = SystemContext {
                        entities: &world.entities,
                        transaction: world.entities.transaction(),
                        state: state
                    };

                    f(&mut context, $($read.deref(),)* $($write.deref_mut(),)*);
                    context.to_change_set()
                };

                let mut read = HashSet::<TypeId>::new();
                $(read.insert(TypeId::of::<$read>());)*
                $(read.insert(TypeId::of::<$write>());)*

                let mut write = HashSet::<TypeId>::new();
                $(write.insert(TypeId::of::<$write>());)*

                let id = self.systems.len() as u32;
                let boxed = Box::new(FnSystem {
                    id: id,
                    read: read,
                    write: write,
                    f: system,
                    phantom: PhantomData
                });

                self.systems.push(boxed);
                id
            }
        }
    )
}

impl_run_system!(run_r0w0 [] []);
impl_run_system!(run_r1w0 [R0] []);
impl_run_system!(run_r2w0 [R0, R1] []);
impl_run_system!(run_r3w0 [R0, R1, R2] []);
impl_run_system!(run_r4w0 [R0, R1, R2, R3] []);
impl_run_system!(run_r5w0 [R0, R1, R2, R3, R4] []);
impl_run_system!(run_r6w0 [R0, R1, R2, R3, R4, R5] []);
impl_run_system!(run_r0w1 [] [W0]);
impl_run_system!(run_r1w1 [R0] [W0]);
impl_run_system!(run_r2w1 [R0, R1] [W0]);
impl_run_system!(run_r3w1 [R0, R1, R2] [W0]);
impl_run_system!(run_r4w1 [R0, R1, R2, R3] [W0]);
impl_run_system!(run_r5w1 [R0, R1, R2, R3, R4] [W0]);
impl_run_system!(run_r6w1 [R0, R1, R2, R3, R4, R5] [W0]);
impl_run_system!(run_r0w2 [] [W0, W1]);
impl_run_system!(run_r1w2 [R0] [W0, W1]);
impl_run_system!(run_r2w2 [R0, R1] [W0, W1]);
impl_run_system!(run_r3w2 [R0, R1, R2] [W0, W1]);
impl_run_system!(run_r4w2 [R0, R1, R2, R3] [W0, W1]);
impl_run_system!(run_r5w2 [R0, R1, R2, R3, R4] [W0, W1]);
impl_run_system!(run_r6w2 [R0, R1, R2, R3, R4, R5] [W0, W1]);
impl_run_system!(run_r0w3 [] [W0, W1, W3]);
impl_run_system!(run_r1w3 [R0] [W0, W1, W2]);
impl_run_system!(run_r2w3 [R0, R1] [W0, W1, W2]);
impl_run_system!(run_r3w3 [R0, R1, R2] [W0, W1, W2]);
impl_run_system!(run_r4w3 [R0, R1, R2, R3] [W0, W1, W2]);
impl_run_system!(run_r5w3 [R0, R1, R2, R3, R4] [W0, W1, W2]);
impl_run_system!(run_r6w3 [R0, R1, R2, R3, R4, R5] [W0, W1, W2]);

/// Determines the behavior entity transaction commits when running a
/// system command buffer sequentially.
pub enum SequentialExecute {
    /// Entity creations and delections are always comitted after each system,
    /// guarenteeing that delections will always be observed by later queued
    /// systems.
    ///
    /// This does not always result in the same behavior as parallel command
    /// buffer execution.
    SequentialCommit,
    /// Entity creations and delections are always comitted in the same batches
    /// that would otherwise had been scheduled for parallel execution had the
    /// command buffer been executed in parallel.
    ///
    /// This emulates the same behavior as parallel command buffer execution.
    ParallelBatchedCommit,
}

impl World {
    /// Executes a `SystemCommandBuffer`, potentially scheduling systems for parallel execution, with the given state.
    pub fn run_with_state<S: Send + Sync + 'static>(&mut self, systems: &mut SystemCommandBuffer<S>, state: &S) {
        self.execute_batched(systems, |world, batch, changes| {
            batch.par_iter_mut()
                .weight_max()
                .map(|system| system.execute(world, state))
                .collect_into(changes);
        });
    }

    /// Executes a `SystemCommandBuffer`, potentially scheduling systems for parallel execution, with a default state value.
    pub fn run<S: Send + Sync + Default + 'static>(&mut self, systems: &mut SystemCommandBuffer<S>) {
        let state: S = Default::default();
        self.run_with_state(systems, &state);
    }

    /// Executes a `SystemCommandBuffer` sequentially, with the given state.
    pub fn run_with_state_sequential<S: Send + Sync + 'static>(&mut self, systems: &mut SystemCommandBuffer<S>, mode: SequentialExecute, state: &S) {
        match mode {
            SequentialExecute::SequentialCommit => self.run_sequential_sc(systems, state),
            SequentialExecute::ParallelBatchedCommit => self.run_sequential_pc(systems, state),
        };
    }

    /// Executes a `SystemCommandBuffer` sequentially, with a default state value.
    pub fn run_sequential<S: Send + Sync + Default + 'static>(&mut self, systems: &mut SystemCommandBuffer<S>, mode: SequentialExecute) {
        let state: S = Default::default();
        self.run_with_state_sequential(systems, mode, &state);
    }

    fn run_sequential_pc<S: Send + Sync + 'static>(&mut self, systems: &mut SystemCommandBuffer<S>, state: &S) {
        self.execute_batched(systems, |world, batch, changes| {
            for system in batch.iter_mut() {
                changes.push(system.execute(world, state));
            }
        });
    }

    fn run_sequential_sc<S: Send + Sync + 'static>(&mut self, systems: &mut SystemCommandBuffer<S>, state: &S) {
        for batch in systems.batches.iter_mut() {
            for system in batch.iter_mut() {
                let changes = [system.execute(self, state)];
                unsafe { self.clean_deleted_entities(&changes) };
                self.entities.merge(ArrayVec::from(changes).into_iter());
            }
        }
    }

    fn execute_batched<F, S: Send + Sync + 'static>(&mut self, systems: &mut SystemCommandBuffer<S>, mut f: F)
        where F: FnMut(&mut World,
                       &mut Vec<Box<System<S>>>,
                       &mut Vec<EntityChangeSet>)
    {
        let mut changes = mem::replace(&mut self.changes_buffer, None).unwrap();
        for batch in systems.batches.iter_mut() {
            let additional = batch.len() - changes.len();
            if additional > 0 {
                changes.reserve(additional);
            }

            f(self, batch, &mut changes);

            unsafe { self.clean_deleted_entities(&changes) };
            self.entities.merge(changes.drain(..));
        }

        self.changes_buffer = Some(changes);
    }
}

/// Provides methods for efficiently iterating through entity resources.
pub struct EntityIteratorBuilder<'a, R, W> {
    entities: &'a Entities,
    read_resources: R,
    write_resources: W,
}

impl<'a, R, W> EntityIteratorBuilder<'a, R, W> {
    /// Constructs a new `EntityIteratorBuilder`.
    fn new(entities: &'a Entities, read_resources: R, write_resources: W) -> EntityIteratorBuilder<'a, R, W> {
        EntityIteratorBuilder {
            entities: entities,
            read_resources: read_resources,
            write_resources: write_resources,
        }
    }
}

macro_rules! impl_entity_iterators {
    ($name:ident [$($read:ident : $read_api:ident),*] [$($write:ident : $write_api:ident),*] [$iter:ty]) => (
        impl<'a, S: Sync + Send> SystemContext<'a, S> {
            /// Constructs an entity iterator builder for performing iterations
            /// over the given resources.
            #[allow(non_snake_case)]
            pub fn $name<'b, $($read,)* $($write,)*>(&self, $($read: &'b $read,)* $($write: &'b mut $write,)*) -> EntityIteratorBuilder<'a, ($(&'b $read,)*), ($(&'b mut $write,)*)> 
                where $($read: EntityResource,)*
                      $($write: EntityResource,)*
            {
                EntityIteratorBuilder::new(self.entities, ($($read,)*), ($($write,)*))
            }
        }

        impl<'b, 'c, $($read,)* $($write,)*> EntityIteratorBuilder<'b, ($(&'c $read,)*), ($(&'c mut $write,)*)>
            where $($read: EntityResource,)*
                  $($write: EntityResource,)*
        {
            /// Constructs an iterator which yields each entity with
            /// data stored in all given entity resources.
            ///
            /// This function borrows each resource, preventing mutation of the
            /// resource for the duration of its' scope. However, the user is
            /// provided with restricted APIs for each resource which may allow
            /// mutable access to entity data stored within the resource, without
            /// allowing any operations which would invalidate the entity iterator.
            #[allow(non_snake_case)]
            pub fn entities<'a, F, R>(&mut self, f: F) -> R
                where F: FnOnce(EntityIter<'b, $iter>, $(&$read::Api,)* $(&mut $write::Api,)*) -> R + 'a
            {
                let ($(ref $read,)*) = self.read_resources;
                let ($(ref mut $write,)*) = self.write_resources;
                $(let $read = $read.deconstruct();)*
                $(let $write = $write.deconstruct_mut();)*
                let iter = ($($read.0,)* $($write.0,)*).and().iter();

                f(EntityIter::new(self.entities, iter), $($read.1,)* $($write.1,)*)
            }
        }

        impl<'b, 'c, $($read, $read_api,)* $($write, $write_api,)*> EntityIteratorBuilder<'b, ($(&'c $read,)*), ($(&'c mut $write,)*)>
            where $($read: EntityResource<Api=$read_api>,)*
                  $($write: EntityResource<Api=$write_api>,)*
                  $($read_api: ComponentResourceApi,)*
                  $($write_api: ComponentResourceApi,)*
        {
            /// Constructs an iterator which yields the components associated
            /// with all entities which have data stored in all of the given
            /// resources.
            #[allow(non_snake_case)]
            pub fn components<'a, F>(&mut self, mut f: F)
                where F: FnMut(Entity, 
                            $(&<<$read as EntityResource>::Api as ComponentResourceApi>::Component,)*
                            $(&mut <<$write as EntityResource>::Api as ComponentResourceApi>::Component,)*) + 'a
            {
                let ($(ref $read,)*) = self.read_resources;
                let ($(ref mut $write,)*) = self.write_resources;
                $(let $read = $read.deconstruct();)*
                $(let $write = $write.deconstruct_mut();)*
                let iter = ($($read.0,)* $($write.0,)*).and().iter();
                
                for e in EntityIter::new(self.entities, iter) {
                    f(e, 
                      $(unsafe{$read.1.get_unchecked(e)},)*
                      $(unsafe{$write.1.get_unchecked_mut(e)},)*)
                }
            }
        }
    )
}

// todo: Find out why the compiler gets confused when using associated types in
// the FnOnce with iterate entities for the iterator and BitSet.
// Solving this would eliminate the need to provide the iterator type in the
// macro invocations, and allow EntityResources to specify alternate BitSetLike
// filters via associated types.
//
// The following expression expands out to the iterator type provided in the
// below macro expansions:
// `BitIter<<($(&$read::Filter,)* $(&$write::Filter,)*) as BitAnd>::Value>`
//
// The compiler does not expand this expression correctly when it is a parameter
// in an FnOnce type. It does elsewhere.

impl_entity_iterators!(iter_r0w1 [] [W0:W0Api] [BitIter<&BitSet>]);
impl_entity_iterators!(iter_r0w2 [] [W0:W0Api, W1:W1Api] [BitIter<BitSetAnd<&BitSet, &BitSet>>]);
impl_entity_iterators!(iter_r0w3 [] [W0:W0Api, W1:W1Api, W2:W2Api] [BitIter<BitSetAnd<&BitSet, BitSetAnd<&BitSet, &BitSet>>>]);
impl_entity_iterators!(iter_r1w0 [R0:R0Api] [] [BitIter<&BitSet>]);
impl_entity_iterators!(iter_r1w1 [R0:R0Api] [W0:W0Api] [BitIter<BitSetAnd<&BitSet, &BitSet>>]);
impl_entity_iterators!(iter_r1w2 [R0:R0Api] [W0:W0Api, W1:W1Api] [BitIter<BitSetAnd<&BitSet, BitSetAnd<&BitSet, &BitSet>>>]);
impl_entity_iterators!(iter_r1w3 [R0:R0Api] [W0:W0Api, W1:W1Api, W2:W2Api] [BitIter<BitSetAnd<BitSetAnd<&BitSet, &BitSet>, BitSetAnd<&BitSet, &BitSet>>>]);
impl_entity_iterators!(iter_r2w0 [R0:R0Api, R1:R1Api] [] [BitIter<BitSetAnd<&BitSet, &BitSet>>]);
impl_entity_iterators!(iter_r2w1 [R0:R0Api, R1:R1Api] [W0:W0Api] [BitIter<BitSetAnd<&BitSet, BitSetAnd<&BitSet, &BitSet>>>]);
impl_entity_iterators!(iter_r2w2 [R0:R0Api, R1:R1Api] [W0:W0Api, W1:W1Api] [BitIter<BitSetAnd<BitSetAnd<&BitSet, &BitSet>, BitSetAnd<&BitSet, &BitSet>>>]);
impl_entity_iterators!(iter_r2w3 [R0:R0Api, R1:R1Api] [W0:W0Api, W1:W1Api, W3:W2Api] [BitIter<BitSetAnd<BitSetAnd<&BitSet, &BitSet>, BitSetAnd<&BitSet, BitSetAnd<&BitSet, &BitSet>>>>]);
impl_entity_iterators!(iter_r3w0 [R0:R0Api, R1:R1Api, R2:R2Api] [] [BitIter<BitSetAnd<&BitSet, BitSetAnd<&BitSet, &BitSet>>>]);
impl_entity_iterators!(iter_r3w1 [R0:R0Api, R1:R1Api, R2:R2Api] [W0:W0Api] [BitIter<BitSetAnd<BitSetAnd<&BitSet, &BitSet>, BitSetAnd<&BitSet, &BitSet>>>]);
impl_entity_iterators!(iter_r3w2 [R0:R0Api, R1:R1Api, R2:R2Api] [W0:W0Api, W1:W1Api] [BitIter<BitSetAnd<BitSetAnd<&BitSet, &BitSet>, BitSetAnd<&BitSet, BitSetAnd<&BitSet, &BitSet>>>>]);
impl_entity_iterators!(iter_r3w3 [R0:R0Api, R1:R1Api, R2:R2Api] [W0:W0Api, W1:W1Api, W3:W2Api][BitIter<BitSetAnd<BitSetAnd<&BitSet, BitSetAnd<&BitSet, &BitSet>>, BitSetAnd<&BitSet, BitSetAnd<&BitSet, &BitSet>>>>]);
impl_entity_iterators!(iter_r4w0 [R0:R0Api, R1:R1Api, R2:R2Api, R3:R3Api] [] [BitIter<BitSetAnd<BitSetAnd<&BitSet, &BitSet>, BitSetAnd<&BitSet, &BitSet>>>]);
impl_entity_iterators!(iter_r4w1 [R0:R0Api, R1:R1Api, R2:R2Api, R3:R3Api] [W0:W0Api] [BitIter<BitSetAnd<BitSetAnd<&BitSet, &BitSet>, BitSetAnd<&BitSet, BitSetAnd<&BitSet, &BitSet>>>>]);
impl_entity_iterators!(iter_r4w2 [R0:R0Api, R1:R1Api, R2:R2Api, R3:R3Api] [W0:W0Api, W1:W1Api] [BitIter<BitSetAnd<BitSetAnd<&BitSet, BitSetAnd<&BitSet, &BitSet>>, BitSetAnd<&BitSet, BitSetAnd<&BitSet, &BitSet>>>>]);
impl_entity_iterators!(iter_r4w3 [R0:R0Api, R1:R1Api, R2:R2Api, R3:R3Api] [W0:W0Api, W1:W1Api, W3:W2Api] [BitIter<BitSetAnd<BitSetAnd<&BitSet, BitSetAnd<&BitSet, &BitSet>>, BitSetAnd<BitSetAnd<&BitSet, &BitSet>, BitSetAnd<&BitSet, &BitSet>>>>]);

#[cfg(test)]
mod tests {
    use super::*;
    use entities::*;
    use resource::*;
    use std::collections::HashSet;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    struct TestResource {
        pub x: u8,
    }

    struct TestResource2 { }
    struct TestResource3 { }

    impl Resource for TestResource {}
    impl Resource for TestResource2 {}
    impl Resource for TestResource3 {}

    #[test]
    fn create_world() {
        World::new();
    }

    #[test]
    fn register_resource() {
        let mut world = World::new();
        world.register_resource(TestResource { x: 1 });
    }

    #[test]
    fn register_resources_unique_id() {
        let mut world = World::new();
        let mut ids: HashSet<u8> = HashSet::new();

        let id = world.register_resource(TestResource { x: 1 });
        assert!(!ids.contains(&id));
        ids.insert(id);

        let id = world.register_resource(TestResource2 {});
        assert!(!ids.contains(&id));
        ids.insert(id);

        let id = world.register_resource(TestResource3 {});
        assert!(!ids.contains(&id));
        ids.insert(id);
    }

    #[test]
    fn get_resource() {
        let mut world = World::new();
        world.register_resource(TestResource { x: 1 });

        let (_, test) = unsafe { world.get_resource::<TestResource>().unwrap() };
        assert_eq!(test.x, 1);
    }

    #[test]
    fn get_resource_mut() {
        let mut world = World::new();
        world.register_resource(TestResource { x: 1 });

        let (_, mut test) = unsafe { world.get_resource_mut::<TestResource>().unwrap() };
        assert_eq!(test.x, 1);
        test.x = 2;
    }

    #[test]
    fn run_system() {
        let mut world = World::new();

        let run_count = Arc::new(AtomicUsize::new(0));

        let run_count_clone = run_count.clone();

        let mut buffer = SystemCommandBuffer::default();
        buffer.queue_systems(|scope| {
            scope.run_r0w0(move |_| {
                run_count_clone.fetch_add(1, Ordering::Relaxed);
            });
        });

        world.run(&mut buffer);

        assert_eq!(run_count.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn run_multiple_system() {
        let mut world = World::new();

        let run_count = Arc::new(AtomicUsize::new(0));

        let run_count_clone1 = run_count.clone();
        let run_count_clone2 = run_count.clone();
        let run_count_clone3 = run_count.clone();

        let mut buffer = SystemCommandBuffer::default();
        buffer.queue_systems(|scope| {
            scope.run_r0w0(move |_| {
                run_count_clone1.fetch_add(1, Ordering::Relaxed);
            });
            scope.run_r0w0(move |_| {
                run_count_clone2.fetch_add(1, Ordering::Relaxed);
            });
            scope.run_r0w0(move |_| {
                run_count_clone3.fetch_add(1, Ordering::Relaxed);
            });
        });

        world.run(&mut buffer);

        assert_eq!(run_count.load(Ordering::Relaxed), 3);
    }

    #[test]
    fn run_system_exclusive_write_sequential() {
        let mut world = World::new();
        world.register_resource(TestResource { x: 1 });
        world.register_resource(TestResource2 {});

        let mut buffer = SystemCommandBuffer::default();
        buffer.queue_systems(|scope| {
            scope.run_r1w0(move |_, r: &TestResource| {
                assert_eq!(r.x, 1);
            });
            scope.run_r1w0(move |_, r: &TestResource| {
                assert_eq!(r.x, 1);
            });
            scope.run_r1w1(|_, _: &TestResource2, w: &mut TestResource| {
                assert_eq!(w.x, 1);
                w.x = 2;
            });
            scope.run_r1w0(move |_, r: &TestResource| {
                assert_eq!(r.x, 2);
            });
        });

        world.run_sequential(&mut buffer, SequentialExecute::SequentialCommit);
    }

    #[test]
    fn run_system_exclusive_write_parallel() {
        for _ in 0..1000 {
            let mut world = World::new();
            world.register_resource(TestResource { x: 1 });
            world.register_resource(TestResource2 {});

            let mut buffer = SystemCommandBuffer::default();
            let (a, b, c, d) = buffer.queue_systems(|scope| {
                let a = scope.run_r1w0(move |_, r: &TestResource| {
                    assert_eq!(r.x, 1);
                });
                let b = scope.run_r1w0(move |_, r: &TestResource| {
                    assert_eq!(r.x, 1);
                });
                let c = scope.run_r1w1(|_, _: &TestResource2, w: &mut TestResource| {
                    assert_eq!(w.x, 1);
                    w.x = 2;
                });
                let d = scope.run_r1w0(move |_, r: &TestResource| {
                    assert_eq!(r.x, 2);
                });

                (a, b, c, d)
            });

            assert_eq!(buffer.batches.len(), 3);
            assert_eq!(buffer.batches[0].len(), 2);
            assert_eq!(buffer.batches[0][0].id(), a);
            assert_eq!(buffer.batches[0][1].id(), b);
            assert_eq!(buffer.batches[1].len(), 1);
            assert_eq!(buffer.batches[1][0].id(), c);
            assert_eq!(buffer.batches[2].len(), 1);
            assert_eq!(buffer.batches[2][0].id(), d);

            world.run(&mut buffer);
        }
    }

    #[test]
    fn system_batch_all_read_distinct() {
        let mut buffer = SystemCommandBuffer::default();

        buffer.queue_systems(|scope| {
            scope.run_r1w0(|_, _: &TestResource| {});
            scope.run_r1w0(|_, _: &TestResource2| {});
            scope.run_r1w0(|_, _: &TestResource3| {});
        });

        assert_eq!(buffer.batches.len(), 1);
        assert_eq!(buffer.batches[0].len(), 3);
    }

    #[test]
    fn system_batch_all_read() {
        let mut buffer = SystemCommandBuffer::default();

        buffer.queue_systems(|scope| {
            scope.run_r1w0(|_, _: &TestResource| {});
            scope.run_r1w0(|_, _: &TestResource| {});
            scope.run_r1w0(|_, _: &TestResource2| {});
        });

        assert_eq!(buffer.batches.len(), 1);
        assert_eq!(buffer.batches[0].len(), 3);
    }

    #[test]
    fn system_batch_all_write_distinct() {
        let mut buffer = SystemCommandBuffer::default();

        buffer.queue_systems(|scope| {
            scope.run_r0w1(|_, _: &mut TestResource| {});
            scope.run_r0w1(|_, _: &mut TestResource2| {});
            scope.run_r0w1(|_, _: &mut TestResource3| {});
        });

        assert_eq!(buffer.batches.len(), 1);
        assert_eq!(buffer.batches[0].len(), 3);
        assert_eq!(buffer.batches[0][0].id(), 0);
        assert_eq!(buffer.batches[0][1].id(), 1);
        assert_eq!(buffer.batches[0][2].id(), 2);
    }

    #[test]
    fn system_batch_all_write() {
        let mut buffer = SystemCommandBuffer::default();

        buffer.queue_systems(|scope| {
            scope.run_r0w1(|_, _: &mut TestResource| {});
            scope.run_r0w1(|_, _: &mut TestResource2| {});
            scope.run_r0w2(|_, _: &mut TestResource, _: &mut TestResource2| {});
        });

        assert_eq!(buffer.batches.len(), 2);
        assert_eq!(buffer.batches[0].len(), 2);
        assert_eq!(buffer.batches[0][0].id(), 0);
        assert_eq!(buffer.batches[0][1].id(), 1);
        assert_eq!(buffer.batches[1].len(), 1);
        assert_eq!(buffer.batches[1][0].id(), 2);
    }

    #[test]
    fn system_batch_all_write_interleaved() {
        let mut buffer = SystemCommandBuffer::default();

        buffer.queue_systems(|scope| {
            scope.run_r0w1(|_, _: &mut TestResource| {});
            scope.run_r0w2(|_, _: &mut TestResource, _: &mut TestResource2| {});
            scope.run_r0w1(|_, _: &mut TestResource2| {});
        });

        assert_eq!(buffer.batches.len(), 3);
        assert_eq!(buffer.batches[0].len(), 1);
        assert_eq!(buffer.batches[0][0].id(), 0);
        assert_eq!(buffer.batches[1].len(), 1);
        assert_eq!(buffer.batches[1][0].id(), 1);
        assert_eq!(buffer.batches[2].len(), 1);
        assert_eq!(buffer.batches[2][0].id(), 2);
    }

    #[test]
    fn system_batch_mixed() {
        let mut buffer = SystemCommandBuffer::default();

        buffer.queue_systems(|scope| {
            scope.run_r1w0(|_, _: &TestResource| {});
            scope.run_r1w1(|_, _: &TestResource, _: &mut TestResource2| {});
            scope.run_r1w0(|_, _: &TestResource| {});
            scope.run_r2w0(|_, _: &TestResource, _: &TestResource2| {});
            scope.run_r1w0(|_, _: &TestResource| {});
            scope.run_r0w1(|_, _: &mut TestResource| {});
        });

        assert_eq!(buffer.batches.len(), 3);
        assert_eq!(buffer.batches[0].len(), 3);
        assert_eq!(buffer.batches[0][0].id(), 0);
        assert_eq!(buffer.batches[0][1].id(), 1);
        assert_eq!(buffer.batches[0][2].id(), 2);
        assert_eq!(buffer.batches[1].len(), 2);
        assert_eq!(buffer.batches[1][0].id(), 3);
        assert_eq!(buffer.batches[1][1].id(), 4);
        assert_eq!(buffer.batches[2].len(), 1);
        assert_eq!(buffer.batches[2][0].id(), 5);
    }

    #[test]
    fn system_command_buffer() {
        let mut systems = SystemCommandBuffer::default();
        systems.queue_systems(|scope| {
            scope.run_r1w1(|_, _: &TestResource, _: &mut TestResource2| {

            });

            scope.run_r1w1(|_, _: &TestResource, _: &mut TestResource2| {

            });
        });

        let mut world = World::new();
        world.register_resource(TestResource { x: 1 });
        world.register_resource(TestResource2 {});
        world.run(&mut systems);
    }

    #[test]
    fn pass_state() {
        let mut systems = SystemCommandBuffer::<u32>::new();
        systems.queue_systems(|scope| {
            scope.run_r0w0(|ctx| {
                assert_eq!(ctx.state(), &5u32);
            });
        });

        let mut world = World::new();
        world.run_with_state(&mut systems, &5u32);
    }

    #[test]
    fn clean_deleted_entities() {
        let mut world = World::new();
        world.register_resource(VecResource::<u32>::new());

        let mut buffer = SystemCommandBuffer::default();
        buffer.queue_systems(|scope| {
            scope.run_r0w1(|tx, resource: &mut VecResource<u32>| {
                println!("Creating entities");
                for i in 0..1000 {
                    let e = tx.create();
                    resource.add(e, i);
                }
                println!("Entities created");
            });

            scope.run_r1w0(|ctx, resource: &VecResource<u32>| {
                println!("Verifying entity creation");
                ctx.iter_r1w0(resource).entities(|iter, r| {
                    for e in iter {
                        assert_eq!(e.index(), *r.get(e).unwrap());
                    }
                });
                println!("Verified entity creation");
            });

            scope.run_r0w1(|ctx, resource: &mut VecResource<u32>| {
                println!("Deleting entities");
                let mut entities = Vec::<Entity>::new();
                ctx.iter_r1w0(resource).entities(|iter, _| {
                    for e in iter {
                        entities.push(e);
                    }
                });

                for e in entities {
                    ctx.destroy(e);
                }
                println!("Deleted entities");
            });

            scope.run_r1w0(|ctx, resource: &VecResource<u32>| {
                println!("Verifying entity deletion");
                let mut entities = Vec::<Entity>::new();
                ctx.iter_r1w0(resource).entities(|iter, _| {
                    for e in iter {
                        entities.push(e);
                    }
                });

                assert_eq!(entities.len(), 0);
                println!("Verified entity delection");
            });
        });

        world.run(&mut buffer);
    }
}