edict 1.0.0-rc9

Powerful entity-component-system library
Documentation
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
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
use core::{
    any::TypeId,
    future::Future,
    marker::PhantomData,
    pin::Pin,
    task::{Context, Poll},
};

use crate::{
    bundle::{Bundle, DynamicBundle, DynamicComponentBundle},
    component::Component,
    entity::{Entity, EntityBound, EntityId, EntityLoc, EntityRef, EntitySet, Location},
    query::{AsDefaultQuery, IntoQuery, Query, QueryItem},
    world::{World, WorldLocal},
    EntityError, NoSuchEntity,
};

use super::{get_flow_world, Flow, FlowWorld, WakeOnDrop};

/// Entity reference usable in flows.
///
/// It can be used to access entity's components,
/// insert and remove components.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct FlowEntity {
    id: EntityId,
    marker: PhantomData<fn() -> &'static mut WorldLocal>,
}

impl Entity for FlowEntity {
    #[inline]
    fn id(&self) -> EntityId {
        self.id
    }

    #[inline]
    fn lookup(&self, entities: &EntitySet) -> Option<Location> {
        self.id.lookup(entities)
    }

    #[inline]
    fn is_alive(&self, entities: &EntitySet) -> bool {
        self.id.is_alive(entities)
    }

    #[inline]
    fn entity_loc<'a>(&self, entities: &'a EntitySet) -> Option<EntityLoc<'a>> {
        self.id.entity_loc(entities)
    }

    #[inline]
    fn entity_ref<'a>(&self, world: &'a mut World) -> Option<EntityRef<'a>> {
        self.id.entity_ref(world)
    }
}

impl PartialEq<EntityId> for FlowEntity {
    #[inline]
    fn eq(&self, other: &EntityId) -> bool {
        self.id == *other
    }
}

impl PartialEq<FlowEntity> for EntityId {
    #[inline]
    fn eq(&self, other: &FlowEntity) -> bool {
        *self == other.id
    }
}

impl PartialEq<EntityBound<'_>> for FlowEntity {
    #[inline]
    fn eq(&self, other: &EntityBound<'_>) -> bool {
        self.id == other.id()
    }
}

impl PartialEq<FlowEntity> for EntityBound<'_> {
    #[inline]
    fn eq(&self, other: &FlowEntity) -> bool {
        self.id() == other.id
    }
}

impl PartialEq<EntityLoc<'_>> for FlowEntity {
    #[inline]
    fn eq(&self, other: &EntityLoc<'_>) -> bool {
        self.id == other.id()
    }
}

impl PartialEq<FlowEntity> for EntityLoc<'_> {
    #[inline]
    fn eq(&self, other: &FlowEntity) -> bool {
        self.id() == other.id
    }
}

impl PartialEq<EntityRef<'_>> for FlowEntity {
    #[inline]
    fn eq(&self, other: &EntityRef<'_>) -> bool {
        self.id == other.id()
    }
}

impl PartialEq<FlowEntity> for EntityRef<'_> {
    #[inline]
    fn eq(&self, other: &FlowEntity) -> bool {
        self.id() == other.id
    }
}

/// Future wrapped to be used as a flow.
#[doc(hidden)]
pub struct FutureEntityFlow<F> {
    id: EntityId,
    fut: F,
}

impl<F> FutureEntityFlow<F> {
    fn pin_project(self: Pin<&mut Self>) -> (Pin<&mut F>, EntityId) {
        let me = unsafe { self.get_unchecked_mut() };
        let id = me.id;
        let fut = unsafe { Pin::new_unchecked(&mut me.fut) };
        (fut, id)
    }
}

impl<F> Flow for FutureEntityFlow<F>
where
    F: Future<Output = ()> + Send,
{
    unsafe fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        // Safety: `me` never moves.
        let (fut, id) = self.pin_project();

        {
            // Safety: world reference does not escape this scope.
            let world = unsafe { get_flow_world() };

            if !world.is_alive(id) {
                // Terminate flow if entity is removed.
                return Poll::Ready(());
            };
        }

        let poll = fut.poll(cx);

        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        let mut e = match world.entity(id) {
            Err(NoSuchEntity) => {
                // Terminate flow if entity is removed.
                return Poll::Ready(());
            }
            Ok(e) => e,
        };

        match poll {
            Poll::Pending => {
                // When entity is despawned, this task needs to be woken up
                // to cancel the flow.

                let auto_wake = e.with(WakeOnDrop::new);
                auto_wake.add_waker(cx.waker());
            }
            Poll::Ready(()) => {
                // If waker is registered, remove it for clean up.
                if let Some(auto_wake) = e.get_mut::<&mut WakeOnDrop>() {
                    auto_wake.remove_waker(cx.waker());
                }
            }
        }
        poll
    }
}

/// Type that can be spawned as a flow for an entity.
/// It can be an async function or a closure
/// that accepts [`FlowEntity`] as the only argument.
///
/// # Example
///
/// ```
/// # use edict::{world::World, flow::FlowEntity};
///
/// let mut world = edict::world::World::new();
///
/// let e = world.spawn(()).id();
///
/// world.spawn_flow_for(e, |e: FlowEntity| async move {
///   e.despawn();
/// });
/// ```
#[diagnostic::on_unimplemented(
    note = "Try `async fn(e: FlowEntity)` or `flow_fn!(|e: FlowEntity| {{ ... }})`"
)]
pub trait IntoEntityFlow: 'static {
    /// Flow type that will be polled.
    type Flow: Flow;

    /// Converts self into a flow.
    fn into_entity_flow(self, e: FlowEntity) -> Option<Self::Flow>;
}

impl<F, Fut> IntoEntityFlow for F
where
    F: FnOnce(FlowEntity) -> Fut + 'static,
    Fut: Future<Output = ()> + Send + 'static,
{
    type Flow = FutureEntityFlow<Fut>;

    fn into_entity_flow(self, e: FlowEntity) -> Option<Self::Flow> {
        Some(FutureEntityFlow {
            id: e.id(),
            fut: self(e),
        })
    }
}

impl FlowEntity {
    #[doc(hidden)]
    #[inline]
    pub fn new(id: EntityId) -> Self {
        FlowEntity {
            id,
            marker: PhantomData,
        }
    }

    /// Returns the entity id.
    #[inline]
    pub fn id(self) -> EntityId {
        self.id
    }

    /// Returns the world reference.
    pub fn world(self) -> FlowWorld {
        FlowWorld::new()
    }

    /// Access entity reference in the world with closure.
    /// Returns closure result.
    ///
    /// # Panics
    ///
    /// If entity is not alive the closure will not be called and the method will panic.
    /// Use [`FlowEntity::try_map`] to handle entity not alive case.
    #[inline]
    pub fn map<F, R>(self, f: F) -> R
    where
        F: FnOnce(EntityRef) -> R,
    {
        match self.try_map(f) {
            Ok(r) => r,
            Err(NoSuchEntity) => entity_not_alive(),
        }
    }

    /// Returns a future that will poll the closure with entity reference.
    /// The future will resolve to closure result in [`Poll::Ready`].
    /// The closure may use task context to register wakers.
    ///
    /// If entity is not alive the future will not poll closure and never resolve.
    #[inline]
    pub fn try_map<F, R>(self, f: F) -> Result<R, NoSuchEntity>
    where
        F: FnOnce(EntityRef) -> R,
    {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        let e = world.entity(self.id)?;
        Ok(f(e))
    }

    /// Returns a future that will poll the closure with entity reference.
    /// The future will resolve to closure result in [`Poll::Ready`].
    /// The closure may use task context to register wakers.
    ///
    /// If entity is not alive the future will not poll closure and never resolve.
    /// Use [`FlowEntity::try_poll`] to handle entity not alive case.
    #[inline]
    pub fn poll<F, R>(self, f: F) -> PollEntityRef<F>
    where
        F: FnMut(EntityRef, &mut Context) -> Poll<R>,
    {
        PollEntityRef {
            entity: self.id,
            f,
            world: self.world(),
        }
    }

    /// Returns a future that will poll the closure with entity reference.
    /// The future will resolve to closure result in [`Poll::Ready`].
    /// The future will resolve to `Err` if entity is despawned.
    ///
    /// The closure may use task context to register wakers.
    #[inline]
    pub fn try_poll<F, R>(self, f: F) -> TryPollEntityRef<F>
    where
        F: FnMut(EntityRef, &mut Context) -> Poll<R>,
    {
        TryPollEntityRef {
            entity: self.id,
            f,
            world: self.world(),
        }
    }

    /// Returns a future that will poll the closure with entity view
    /// constructed with specified query type.
    /// The future will resolve to closure result in [`Poll::Ready`].
    /// The closure may use task context to register wakers.
    ///
    /// If entity is not alive the future will not poll closure and never resolve.
    /// Use [`FlowEntity::try_poll_view`] to handle entity not alive case.
    ///
    /// Future will not poll closure and resolve until query is satisfied.
    pub fn poll_view<Q, F, R>(self, f: F) -> PollEntityView<Q::Query, F>
    where
        Q: AsDefaultQuery,
        F: FnMut(QueryItem<Q>, &mut Context) -> Poll<R>,
    {
        PollEntityView {
            entity: self.id,
            f,
            query: Q::default_query(),
            world: self.world(),
        }
    }

    /// Returns a future that will poll the closure with entity view
    /// constructed with specified query type.
    /// The future will resolve to closure result in [`Poll::Ready`].
    /// The future will resolve to `Err` if entity is not alive or query is not satisfied.
    /// The closure may use task context to register wakers.
    pub fn try_poll_view<Q, F, R>(self, f: F) -> TryPollEntityView<Q::Query, F>
    where
        Q: AsDefaultQuery,
        F: FnMut(QueryItem<Q>, &mut Context) -> Poll<R>,
    {
        TryPollEntityView {
            entity: self.id,
            f,
            query: Q::default_query(),
            world: self.world(),
        }
    }

    /// Returns a future that will poll the closure with entity view
    /// constructed with specified query.
    /// The future will resolve to closure result in [`Poll::Ready`].
    /// The closure may use task context to register wakers.
    ///
    /// If entity is not alive the future will not poll closure and never resolve.
    /// Use [`FlowEntity::try_poll_view_with`] to handle entity not alive case.
    ///
    /// Future will not poll closure and resolve until query is satisfied.
    pub fn poll_view_with<Q, F, R>(self, query: Q, f: F) -> PollEntityView<Q::Query, F>
    where
        Q: IntoQuery,
        F: FnMut(QueryItem<Q>, &mut Context) -> Poll<R>,
    {
        PollEntityView {
            entity: self.id,
            f,
            query: query.into_query(),
            world: self.world(),
        }
    }

    /// Returns a future that will poll the closure with entity view
    /// constructed with specified query.
    /// The future will resolve to closure result in [`Poll::Ready`].
    /// The future will resolve to `Err` if entity is not alive or query is not satisfied.
    /// The closure may use task context to register wakers.
    pub fn try_poll_view_with<Q, F, R>(self, query: Q, f: F) -> TryPollEntityView<Q::Query, F>
    where
        Q: IntoQuery,
        F: FnMut(QueryItem<Q>, &mut Context) -> Poll<R>,
    {
        TryPollEntityView {
            entity: self.id,
            f,
            query: query.into_query(),
            world: self.world(),
        }
    }

    /// Checks if entity is alive.
    pub fn is_alive(self) -> bool {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        world.is_alive(self.id)
    }

    /// Returns clone of the entity's component if it exists.
    /// Otherwise returns `None`.
    ///
    /// # Panics
    ///
    /// Panics if entity is not alive.
    #[inline]
    pub fn get_cloned<T>(self) -> Option<T>
    where
        T: Clone + 'static,
    {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        match world.try_get_cloned(self.id) {
            Ok(c) => Some(c),
            Err(EntityError::Mismatch) => None,
            Err(EntityError::NoSuchEntity) => entity_not_alive(),
        }
    }

    /// Returns clone of the entity's component if it exists.
    /// Otherwise returns error.
    /// If entity is not alive, returns `Err(NoSuchEntity)`.
    /// If entity does not have component of specified type, returns `Err(Mismatch)`.
    #[inline]
    pub fn try_get_cloned<T>(self) -> Result<T, EntityError>
    where
        T: Clone + 'static,
    {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        world.try_get_cloned(self.id)
    }

    /// Sets new value for the entity component.
    ///
    /// Returns error if entity does not have component of specified type.
    #[inline]
    pub fn set<T>(self, value: T) -> Result<(), T>
    where
        T: 'static,
    {
        match self.try_set(value) {
            Ok(_) => Ok(()),
            Err((EntityError::Mismatch, value)) => Err(value),
            Err((EntityError::NoSuchEntity, _)) => entity_not_alive(),
        }
    }

    /// Sets new value for the entity component.
    ///
    /// Returns error if entity does not have component of specified type.
    #[inline]
    pub fn try_set<T>(self, value: T) -> Result<(), (EntityError, T)>
    where
        T: 'static,
    {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        match world.get::<&mut T>(self.id) {
            Ok(c) => {
                let c: &mut T = c;
                *c = value;
                Ok(())
            }
            Err(e) => Err((e, value)),
        }
    }

    /// Insert a component to the entity.
    #[inline]
    pub fn insert<T>(self, component: T)
    where
        T: Component,
    {
        match self.try_insert(component) {
            Ok(_) => (),
            Err(NoSuchEntity) => entity_not_alive(),
        }
    }

    /// Insert a component to the entity.
    #[inline]
    pub fn try_insert<T>(self, component: T) -> Result<(), NoSuchEntity>
    where
        T: Component,
    {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        world.insert(self.id, component)
    }

    /// Attempts to inserts component to the entity.
    ///
    /// If entity already had component of that type,
    /// old component value is replaced with new one.
    /// Otherwise new component is added to the entity.
    #[inline]
    pub fn insert_external<T>(self, component: T)
    where
        T: 'static,
    {
        match self.try_insert_external(component) {
            Ok(_) => (),
            Err(NoSuchEntity) => entity_not_alive(),
        }
    }

    /// Attempts to inserts component to the entity.
    ///
    /// If entity already had component of that type,
    /// old component value is replaced with new one.
    /// Otherwise new component is added to the entity.
    #[inline]
    pub fn try_insert_external<T>(self, component: T) -> Result<(), NoSuchEntity>
    where
        T: 'static,
    {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        world.insert_external(self.id, component)
    }

    /// Inserts a component to the entity if it does not have one.
    #[inline]
    pub fn with<T>(self, component: impl FnOnce() -> T)
    where
        T: Component,
    {
        match self.try_with(component) {
            Ok(_) => (),
            Err(NoSuchEntity) => entity_not_alive(),
        }
    }

    /// Inserts a component to the entity if it does not have one.
    #[inline]
    pub fn try_with<T>(self, component: impl FnOnce() -> T) -> Result<(), NoSuchEntity>
    where
        T: Component,
    {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        world.with(self.id, component)?;
        Ok(())
    }

    /// Attempts to insert a component to the entity if it does not have one.
    #[inline]
    pub fn with_external<T>(self, component: impl FnOnce() -> T)
    where
        T: 'static,
    {
        match self.try_with_external(component) {
            Ok(_) => (),
            Err(NoSuchEntity) => entity_not_alive(),
        }
    }

    /// Attempts to insert a component to the entity if it does not have one.
    #[inline]
    pub fn try_with_external<T>(self, component: impl FnOnce() -> T) -> Result<(), NoSuchEntity>
    where
        T: 'static,
    {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        world.with_external(self.id, component)?;
        Ok(())
    }

    /// Inserts bundle of components to the entity.
    /// This is moral equivalent to calling `WorldLocal::insert` with each component separately,
    /// but more efficient.
    ///
    /// For each component type in bundle:
    /// If entity already had component of that type,
    /// old component value is replaced with new one.
    /// Otherwise new component is added to the entity.
    ///
    /// If entity is not alive, fails with `Err(NoSuchEntity)`.
    #[inline]
    pub fn insert_bundle<B>(self, bundle: B)
    where
        B: DynamicComponentBundle,
    {
        match self.try_insert_bundle(bundle) {
            Ok(_) => (),
            Err(NoSuchEntity) => entity_not_alive(),
        }
    }

    /// Inserts bundle of components to the entity.
    /// This is moral equivalent to calling `WorldLocal::insert` with each component separately,
    /// but more efficient.
    ///
    /// For each component type in bundle:
    /// If entity already had component of that type,
    /// old component value is replaced with new one.
    /// Otherwise new component is added to the entity.
    ///
    /// If entity is not alive, fails with `Err(NoSuchEntity)`.
    #[inline]
    pub fn try_insert_bundle<B>(self, bundle: B) -> Result<(), NoSuchEntity>
    where
        B: DynamicComponentBundle,
    {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        world.insert_bundle(self.id, bundle)
    }

    /// Inserts bundle of components to the entity.
    /// This is moral equivalent to calling `WorldLocal::insert` with each component separately,
    /// but more efficient.
    ///
    /// For each component type in bundle:
    /// If entity already had component of that type,
    /// old component value is replaced with new one.
    /// Otherwise new component is added to the entity.
    ///
    /// If entity is not alive, fails with `Err(NoSuchEntity)`.
    #[inline]
    pub fn insert_external_bundle<B>(self, bundle: B)
    where
        B: DynamicBundle,
    {
        match self.try_insert_external_bundle(bundle) {
            Ok(_) => (),
            Err(NoSuchEntity) => entity_not_alive(),
        }
    }

    /// Inserts bundle of components to the entity.
    /// This is moral equivalent to calling `WorldLocal::insert` with each component separately,
    /// but more efficient.
    ///
    /// For each component type in bundle:
    /// If entity already had component of that type,
    /// old component value is replaced with new one.
    /// Otherwise new component is added to the entity.
    ///
    /// If entity is not alive, fails with `Err(NoSuchEntity)`.
    #[inline]
    pub fn try_insert_external_bundle<B>(self, bundle: B) -> Result<(), NoSuchEntity>
    where
        B: DynamicBundle,
    {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        world.insert_external_bundle(self.id, bundle)
    }

    /// Removes a component from the entity.
    /// Returns the component if it was present.
    #[inline]
    pub fn remove<T>(self) -> Option<T>
    where
        T: 'static,
    {
        match self.try_remove::<T>() {
            Ok(c) => Some(c),
            Err(EntityError::Mismatch) => None,
            Err(EntityError::NoSuchEntity) => entity_not_alive(),
        }
    }

    /// Removes a component from the entity.
    /// Returns the component if it was present.
    #[inline]
    pub fn try_remove<T>(self) -> Result<T, EntityError>
    where
        T: 'static,
    {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        let (c, _) = world.remove::<T>(self.id)?;
        match c {
            None => Err(EntityError::Mismatch),
            Some(c) => Ok(c),
        }
    }

    /// Drops a component from the entity.
    #[inline]
    pub fn drop<T>(self)
    where
        T: 'static,
    {
        match self.try_drop::<T>() {
            Ok(_) => (),
            Err(NoSuchEntity) => entity_not_alive(),
        }
    }

    /// Drops a component from the entity.
    #[inline]
    pub fn try_drop<T>(self) -> Result<(), NoSuchEntity>
    where
        T: 'static,
    {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        world.drop::<T>(self.id)
    }

    /// Drops a component from the entity.
    #[inline]
    pub fn drop_erased(self, ty: TypeId) {
        match self.try_drop_erased(ty) {
            Ok(_) => (),
            Err(NoSuchEntity) => entity_not_alive(),
        }
    }

    /// Drops a component from the entity.
    #[inline]
    pub fn try_drop_erased(self, ty: TypeId) -> Result<(), NoSuchEntity> {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        world.drop_erased(self.id, ty)
    }

    /// Drops entity's components that are found in the specified bundle.
    ///
    /// If entity is not alive, fails with `Err(NoSuchEntity)`.
    ///
    /// Unlike other methods that use `Bundle` trait, this method does not require
    /// all components from bundle to be registered in the world.
    /// Entity can't have components that are not registered in the world,
    /// so no need to drop them.
    ///
    /// For this reason there's no separate method that uses `ComponentBundle` trait.
    #[inline]
    pub fn drop_bundle<B>(self)
    where
        B: Bundle,
    {
        match self.try_drop_bundle::<B>() {
            Ok(_) => (),
            Err(NoSuchEntity) => entity_not_alive(),
        }
    }

    /// Drops entity's components that are found in the specified bundle.
    ///
    /// If entity is not alive, fails with `Err(NoSuchEntity)`.
    ///
    /// Unlike other methods that use `Bundle` trait, this method does not require
    /// all components from bundle to be registered in the world.
    /// Entity can't have components that are not registered in the world,
    /// so no need to drop them.
    ///
    /// For this reason there's no separate method that uses `ComponentBundle` trait.
    #[inline]
    pub fn try_drop_bundle<B>(self) -> Result<(), NoSuchEntity>
    where
        B: Bundle,
    {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        world.drop_bundle::<B>(self.id)
    }

    /// Despawns the referenced entity.
    #[inline]
    pub fn despawn(self) {
        match self.try_despawn() {
            Ok(_) => (),
            Err(NoSuchEntity) => entity_not_alive(),
        }
    }

    /// Despawns the referenced entity.
    #[inline]
    pub fn try_despawn(self) -> Result<(), NoSuchEntity> {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        world.despawn(self.id)
    }

    /// Checks if entity has component of specified type.
    ///
    /// If entity is not alive, fails with `Err(NoSuchEntity)`.
    #[inline]
    pub fn has_component<T: 'static>(self) -> bool {
        match self.try_has_component::<T>() {
            Ok(b) => b,
            Err(NoSuchEntity) => entity_not_alive(),
        }
    }

    /// Checks if entity has component of specified type.
    ///
    /// If entity is not alive, fails with `Err(NoSuchEntity)`.
    #[inline]
    pub fn try_has_component<T: 'static>(self) -> Result<bool, NoSuchEntity> {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        world.try_has_component::<T>(self.id)
    }

    /// Spawns a new flow for the entity.
    pub fn spawn_flow<F>(self, f: F)
    where
        F: IntoEntityFlow,
    {
        // Safety: world reference does not escape this scope.
        let world = unsafe { get_flow_world() };

        world.spawn_flow_for(self.id, f);
    }
}

/// Future that polls the closure with entity reference.
/// Resolves to closure result in [`Poll::Ready`].
/// The closure may use task context to register wakers.
///
/// If entity is not alive the future will not poll closure and never resolve.
#[must_use = "Future does nothing unless polled"]
pub struct PollEntityRef<F> {
    entity: EntityId,
    f: F,
    world: FlowWorld,
}

impl<F, R> Future for PollEntityRef<F>
where
    F: FnMut(EntityRef, &mut Context) -> Poll<R>,
{
    type Output = R;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<R> {
        // Safety: `me` never moves.
        let me = unsafe { self.get_unchecked_mut() };

        // Safety: world reference does not escape this scope.
        let world = unsafe { me.world.get() };

        let Ok(e) = world.entity(me.entity) else {
            return Poll::Pending;
        };
        (me.f)(e, cx)
    }
}

/// Future that will poll the closure with entity reference.
/// Resolves to closure result in [`Poll::Ready`].
/// Resolves to `Err` if entity is despawned.
///
/// The closure may use task context to register wakers.
#[must_use = "Future does nothing unless polled"]
pub struct TryPollEntityRef<F> {
    entity: EntityId,
    f: F,
    world: FlowWorld,
}

impl<F, R> Future for TryPollEntityRef<F>
where
    F: FnMut(EntityRef, &mut Context) -> Poll<R>,
{
    type Output = Result<R, NoSuchEntity>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<R, NoSuchEntity>> {
        // Safety: `me` never moves.
        let me = unsafe { self.get_unchecked_mut() };

        // Safety: world reference does not escape this scope.
        let world = unsafe { me.world.get() };

        let e = world.entity(me.entity)?;
        let poll = (me.f)(e, cx);
        try_poll(poll, me.entity, world, cx)
    }
}

/// Future that will poll the closure with entity view
/// constructed with specified query.
/// Resolves to closure result in [`Poll::Ready`].
/// The closure may use task context to register wakers.
///
/// If entity is not alive the future will not poll closure and never resolve.
/// Future will not poll closure and resolve until query is satisfied.
#[must_use = "Future does nothing unless polled"]
pub struct PollEntityView<Q, F> {
    entity: EntityId,
    query: Q,
    f: F,
    world: FlowWorld,
}

impl<Q, F, R> Future for PollEntityView<Q, F>
where
    Q: Query,
    for<'a> F: FnMut(QueryItem<'a, Q>, &mut Context) -> Poll<R>,
{
    type Output = R;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<R> {
        // Safety: `me` never moves.
        let me = unsafe { self.get_unchecked_mut() };

        // Safety: world reference does not escape this scope.
        let world = unsafe { me.world.get() };

        match world.get_with(me.entity, me.query) {
            Err(EntityError::NoSuchEntity) => Poll::Pending,
            Err(EntityError::Mismatch) => {
                // TODO: Should archetype change be detected to wake up the task?
                cx.waker().wake_by_ref();
                Poll::Pending
            }
            Ok(item) => (me.f)(item, cx),
        }
    }
}

/// Future that will poll the closure with entity view
/// constructed with specified query.
/// Resolves to closure result in [`Poll::Ready`].
/// Resolves to `Err` if entity is not alive or query is not satisfied.
/// The closure may use task context to register wakers.
#[must_use = "Future does nothing unless polled"]
pub struct TryPollEntityView<Q, F> {
    entity: EntityId,
    query: Q,
    f: F,
    world: FlowWorld,
}

impl<Q, F, R> Future for TryPollEntityView<Q, F>
where
    Q: Query,
    for<'a> F: FnMut(QueryItem<'a, Q>, &mut Context) -> Poll<R>,
{
    type Output = Result<R, EntityError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<R, EntityError>> {
        // Safety: `me` never moves.
        let me = unsafe { self.get_unchecked_mut() };

        // Safety: world reference does not escape this scope.
        let world = unsafe { me.world.get() };

        let item = world.get_with(me.entity, me.query)?;
        let poll = (me.f)(item, cx);
        let poll = try_poll(poll, me.entity, world, cx)?;
        poll.map(Ok)
    }
}

fn try_poll<R>(
    poll: Poll<R>,
    entity: EntityId,
    world: &mut WorldLocal,
    cx: &mut Context<'_>,
) -> Poll<Result<R, NoSuchEntity>> {
    let mut e = world.entity(entity)?;

    match poll {
        Poll::Pending => {
            // When entity is despawned, this task needs to be woken up
            // to resolve the future.

            let auto_wake = e.with(WakeOnDrop::new);
            auto_wake.add_waker(cx.waker());

            Poll::Pending
        }
        Poll::Ready(result) => {
            // If waker is registered, remove it for clean up.
            if let Some(auto_wake) = e.get_mut::<&mut WakeOnDrop>() {
                auto_wake.remove_waker(cx.waker());
            }

            Poll::Ready(Ok(result))
        }
    }
}

/// Handles despawned entity in methods that assume entity is alive.
#[cold]
#[inline(never)]
fn entity_not_alive() -> ! {
    panic!("Entity is not alive");
}