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
//! Edict is a fast, powerful and ergonomic ECS crate that expands traditional ECS feature set.
//! Written in Rust by your fellow 🦀
//!
//! # Basic usage 🌱
//!
//! ```
//! use edict::prelude::*;
//!
//! // Create world instance.
//! let mut world = World::new();
//!
//! // Declare some components.
//! #[derive(Component)]
//! struct Pos(f32, f32);
//!
//! // Declare some more.
//! #[derive(Component)]
//! struct Vel(f32, f32);
//!
//! // Spawn entity with components.
//! world.spawn((Pos(0.0, 0.0), Vel(1.0, 1.0)));
//!
//! // Query components and iterate over views.
//! for (pos, vel) in world.view::<(&mut Pos, &Vel)>() {
//! pos.0 += vel.0;
//! pos.1 += vel.1;
//! }
//!
//!
//! // Define functions that will be used as systems.
//! #[edict::system::system] // This attribute is optional, but it catches if function is not a system.
//! fn move_system(pos_vel: View<(&mut Pos, &Vel)>) {
//! for (pos, vel) in pos_vel {
//! pos.0 += vel.0;
//! pos.1 += vel.1;
//! }
//! }
//!
//! # #[cfg(feature = "scheduler")]
//! # {
//! // Create scheduler to run systems. Requires "scheduler" feature.
//! use edict::scheduler::Scheduler;
//!
//! let mut scheduler = Scheduler::new();
//! scheduler.add_system(move_system);
//!
//! // Run systems without parallelism.
//! scheduler.run_sequential(&mut world);
//!
//! # #[cfg(feature = "std")]
//! # {
//! // Run systems using threads. Requires "std" feature.
//! scheduler.run_threaded(&mut world);
//! # }
//!
//! // Or use custom thread pool.
//! # }
//! ```
//!
//! # Features
//!
//! ## Entities 🧩
//!
//! ### Simple IDs
//!
//! In *Entity* Component Systems we create entities and address them to fetch associated data.
//! Edict provides [`EntityId`] type to address entities.
//!
//! [`EntityId`] as a world-unique identifier of an entity.
//! Edict uses IDs without generation and recycling, for this purpose it employs `u64` underlying type with a niche.
//! It is enough to create IDs non-stop for hundreds of years before running out of them.
//!
//! [`EntityId`] can be converted into bits and from bits.
//!
//! This greatly simplifying serialization of the [`World`]'s state as it doesn't require any processing of entity IDs.
//!
//! By default entity IDs are unique only within one [`World`].
//! For multi-world scenarios Edict provides a way to make entity IDs unique between any required combination of worlds.
//!
//! IDs are allocated in sequence from [`IdRange`]s that are allocated by [`IdRangeAllocator`].
//! By default [`IdRange`] that spans from 1 to `u64::MAX - 1` is used. This makes default ID allocation extremely fast.
//! Custom [`IdRangeAllocator`] can be provided to [`WorldBuilder`] to use custom ID ranges.
//!
//! For example in client-server architecture, server and client may use non-overlapping ID ranges.
//! Thus allowing state serialized on server to be transferred to client without ID mapping,
//! which can be cumbersome when components reference entities.
//!
//! In multi-server or p2p architecture [`IdRangeAllocator`] would need to communicate to allocate disjoint ID ranges for each server.
//!
//! ### Ergonomic entity types
//!
//! Using ECS may lead to lots of `.unwrap()` calls or excessive error handling.
//! There a lot of situations when entity is guaranteed to exist (for example it just returned from a view).
//! To avoid handling [`NoSuchEntity`] error when it is unreachable, Edict provides [`AliveEntity`] trait that extends [`Entity`] trait.
//! Various methods require [`AliveEntity`] handle and skip existence check.
//!
//! [`Entity`] and [`AliveEntity`] traits implemented for number of entity types.
//!
//! [`EntityId`] implements only [`Entity`] as it doesn't provide any guaranties.
//!
//! [`EntityBound`] is guaranteed to be alive, allowing using it in methods that doesn't handle entity absence.
//! It keeps lifetime of [`World`] borrow, making it impossible to despawn any entity from the world.
//! Using it with wrong [`World`] may cause panic.
//! [`EntityBound`] can be acquire from relation queries.
//!
//! [`EntityLoc`] not only guarantees entity existence but also contains location of the entity in the archetypes,
//! allowing to skip lookup step when accessing its components.
//! Similarly to [`EntityBound`], it keeps lifetime of [`World`] borrow, making it impossible to despawn any entity from the world.
//! Using it with wrong [`World`] may cause panic.
//! [`EntityLoc`] can be acquire from [`Entities`] query.
//!
//! [`EntityRef`] is special.
//! It doesn't implement [`Entity`] or [`AliveEntity`] traits since it should not be used in world methods.
//! Instead it provides direct access to entity's data and allows mutations such as inserting/removing components.
//!
//! ## Components 🛠️
//!
//! ### Non-thread-safe types
//!
//! Support for [`!Send`] and [`!Sync`] components and resources with some limitations.
//!
//! [`World`] itself is not sendable but shareable between threads.
//! Thread owning [`World`] is referred as "main" thread in documentation.
//!
//! Components and resources that are [`!Send`] can be fetched mutably only from "main" thread.
//! Components and resources that are [`!Sync`] can be fetched immutably only from "main" thread.
//! Since reference to [`World`] may exist outside "main" thread, [`WorldLocal`] reference should be used,
//! it can be created using mutable reference to [`World`].
//!
//! ### Components with trait and without
//!
//! Optional [`Component`] trait that allows implicit component type registration when component is inserted first time.
//! Implicit registration uses behavior defined by [`Component`] implementation as-is.
//! When needed, explicit registration can be done using [`WorldBuilder`] to override component behavior.
//!
//! Non [`Component`] types require explicit registration and
//! few methods with `_external` suffix is used with them instead of normal ones.
//! Only default registration is possible when [`World`] is already built.
//! When needed, explicit registration can be done using [`WorldBuilder`] to override component behavior.
//!
//! ## Entity relations 🔗
//!
//! A relation can be added to pair of entities, binding them together.
//! Queries may fetch relations and filter entities by their relations to other entities.
//! When either of the two entities is despawned, relation is dropped.
//! [`Relation`] type may further configure behavior of the bounded entities.
//!
//! ## Queries 🔍
//!
//! Powerful [`Query`] mechanism that can filter entities by components, relations and other criteria and fetch entity data.
//! Queries can be mutable or immutable, sendable or non-sendable, stateful or stateless.
//!
//! Using query on [`World`] creates Views.
//! Views can be used to iterate over entities that match the query yielding query items.
//! Or fetch single entity data.
//!
//! [`ViewRef`] and [`ViewMut`] are convenient type aliases to view types returned from [`World`] methods.
//!
//! ## Runtime and compile time checks
//!
//! Runtime checks are available for query mutable aliasing avoidance.
//!
//! [`ViewRef`] and [`ViewCell`] do runtime checks allowing multiple views with aliased access coexist,
//! deferring checks to runtime that prevents invalid aliasing to occur.
//!
//! When this is not required, [`ViewMut`] and [`View`]s with compile time checks should be used instead.
//!
//! When [`View`] is expected [`ViewRef`] and [`ViewCell`] can be locked to make a [`View`].
//!
//! ### Borrows
//!
//! Component type may define borrowing operations to borrow another type from it.
//! Borrowed type may be not sized, allowing slices and dyn traits to be borrowed.
//! A macro to help define borrowing operations is provided.
//! Queries that tries to borrow type from suitable components are provided:
//! * [`BorrowAll`] borrows from all components that implement borrowing requested type.
//! Yields a `Vec` with borrowed values since multiple components of the entity may provide it.
//! Skips entities if none of the components provide the requested type.
//! * [`BorrowAny`] borrows from first suitable component that implements borrowing requested type.
//! Yields a single value.
//! Skips entities if none of the components provide the requested type.
//! * [`BorrowOne`] is configured with [`TypeId`] of component from which it should borrow requested type.
//! Panics if component doesn't provide the requested type.
//! Skips entities without the component.
//!
//! ## Resources 📦
//!
//! Built-in type-map for singleton values called "resources".
//! Resources can be inserted into/fetched from [`World`].
//! Resources live separately from entities and their components.
//!
//! ## Actions 🏃♂️
//!
//! Use [`ActionEncoder`] for recording actions and run them later with mutable access to [`World`].
//! Or [`LocalActionEncoder`] instead when action is not [`Send`].
//! Or convenient [`WorldLocal::defer*`] methods to defer actions to internal [`LocalActionEncoder`].
//!
//! ## Automatic change tracking 🤖
//!
//! Each component instance is equipped with epoch counter that tracks last potential mutation of the component.
//! Queries may read and update components epoch to track changes.
//! Queries to filter recently changed components are provided with [`Modified`] type.
//! Last epoch can be obtained with [`World::epoch`].
//!
//! ## Systems ⚙️
//!
//! Systems is convenient way to build logic that operates on [`World`].
//! Edict defines [`System`] trait to run logic on [`World`].
//! And [`IntoSystem`] trait for types convertible to [`System`].
//!
//! Functions may implement [`IntoSystem`] automatically -
//! it is required to return `()` and accept arguments that implement [`FnArg`] trait.
//! There are [`FnArg`] implementations:
//!
//! - [`View`] and [`ViewCell`] to iterate over entities and their components.
//! Use [`View`] unless [`ViewCell`] is required to handle intra-system views conflict.
//! - [`Res`] and [`ResMut`] to access resources.
//! - [`ResLocal`] and [`ResMutLocal`] to access no-thread-safe resources.
//! This will make system non-sendable and force it to run on main thread.
//! - [`ActionEncoder`] to record actions that mutate [`World`] state, such as entity spawning, inserting and removing components or resources.
//! - [`State`] to store system's local state between runs.
//!
//! ## Easy scheduler 📅
//!
//! [`Scheduler`] is provided to run [`System`]s.
//! Systems added to the [`Scheduler`] run in parallel where possible,
//! however they act **as if** executed sequentially in order they were added.
//!
//! If systems do not conflict they may be executed in parallel.
//!
//! If systems conflict, the one added first will be executed before the one added later can start.
//!
//! `std` threads or `rayon` can be used as an executor.
//! User may provide custom executor by implementing [`ScopedExecutor`] trait.
//!
//! Requires `"scheduler"` feature which is enabled by default.
//!
//! ## Hooks 🎣
//!
//! Component replace/drop hooks are called automatically when component is replaced or dropped.
//!
//! When component is registered it can be equipped with hooks to be called when component value is replaced or dropped.
//! Implicit registration of [`Component`] types will register hooks defined on the trait impl.
//!
//! Drop hook is called when component is dropped via [`World::drop`] or entity is despawned and is not
//! called when component is removed from entity.
//!
//! Replace hook is called when component is replaced e.g. component is inserted into entity
//! and entity already has component of the same type.
//! Replace hook returns boolean value that indicates if drop hook should be called for replaced component.
//!
//! Hooks can record actions into provided [`LocalActionEncoder`] that will be executed
//! before [`World`] method that caused the hook to be called returns.
//!
//! When component implements [`Component`] trait, hooks defined on the trait impl are registered automatically to call
//! [`Component::on_drop`] and [`Component::on_replace`] methods.
//! They may be overridden with custom hooks using [`WorldBuilder`].
//! For non [`Component`] types hooks can be registered only via [`WorldBuilder`].
//! Default registration with [`World`] will not register any hooks.
//!
//! ## Async-await ⏳
//!
//! Futures executor to run logic that requires waiting for certain conditions or events
//! or otherwise spans for multiple ticks.
//!
//! Logic that requires waiting can be complex to implement using systems.
//! Systems run in loop and usually work on every entity with certain components.
//! Implementing waiting logic would require adding waiting state to existing or new components and
//! logic would be spread across many system runs or even many systems.
//!
//! Futures may use `await` syntax to wait for certain conditions or events.
//! Futures that can access ECS data are referred in Edict as "flows".
//!
//! Flows can be spawned in the [`World`] using [`World::spawn_flow`] or [`FlowWorld::spawn_flow`] method.
//! [`Flows`] type is used as an executor to run spawned flows.
//!
//! Flows can be bound to an entity and spawned using [`World::spawn_flow_for`], [`FlowWorld::spawn_flow_for`], [`EntityRef::spawn_flow`] or [`FlowEntity::spawn_flow`] method.
//! Such flows will be cancelled if entity is despawned.
//!
//! Functions that return futures may serve as flows.
//! For [`World::spawn_flow`] use function or closure with signature `FnOnce(FlowWorld) -> Future`
//! For [`World::spawn_flow_for`] use function or closure with signature `FnOnce(FlowEntity) -> Future`
//!
//! User may implement low-level futures using `poll*` methods of [`FlowWorld`] and [`FlowEntity`] to access tasks [`Context`].
//! Edict provides only a couple of low-level futures that will do the waiting:
//! - [`yield_now!`] yields control to the executor once and resumes on next execution.
//! - [`FlowEntity::wait_despawned`] waits until entity is despawned.
//! - [`FlowEntity::wait_has_component`] waits until entity get a component.
//!
//! [`WakeOnDrop`] component can be used when despawning entity should wake a task.
//!
//! It is recommended to use flows for high-level logic that spans multiple ticks
//! and use systems to do low-level logic that runs every tick.
//! Flows may request systems to perform operations by adding special components to entities.
//! And systems may spawn flows to do long-running operations.
//!
//! Requires `"flow"` feature which is enabled by default.
//!
//! # no_std support
//!
//! Edict can be used in `no_std` environment but requires `alloc` crate.
//! `"std"` feature is enabled by default.
//!
//! If "std" feature is not enabled error types will not implement [`std::error::Error`].
//!
//! When "flow" feature is enabled and "std" is not, extern functions are used to implement TLS.
//! Application must provide implementation for these functions or linking will fail.
//!
//! "scheduler" feature enables [`Scheduler`] type.
//! "threaded-scheduler" feature enables multithreaded execution for [`Scheduler`], using [`Scheduler::run_with`] and [`Scheduler::run_threaded`].
//! "rayon-scheduler" feature enables rayon based execution for [`Scheduler`] using [`Scheduler::run_rayon`].
//!
//! [`!Send`]: core::marker::Send
//! [`!Sized`]: core::marker::Sized
//! [`!Sync`]: core::marker::Sync
//! [`ActionEncoder`]: crate::action::ActionEncoder
//! [`AliveEntity`]: crate::entity::AliveEntity
//! [`BorrowAll`]: crate::query::BorrowAll
//! [`BorrowAny`]: crate::query::BorrowAny
//! [`BorrowOne`]: crate::query::BorrowOne
//! [`Component`]: crate::component::Component
//! [`Component::on_drop`]: crate::component::Component::on_drop
//! [`Component::on_replace`]: crate::component::Component::on_replace
//! [`Context`]: std::task::Context
//! [`Entities`]: crate::query::Entities
//! [`Entity`]: crate::entity::Entity
//! [`EntityBound`]: crate::entity::EntityBound
//! [`EntityId`]: crate::entity::EntityId
//! [`EntityLoc`]: crate::entity::EntityLoc
//! [`EntityRef`]: crate::entity::EntityRef
//! [`EntityRef::spawn_flow`]: crate::entity::EntityRef::spawn_flow
//! [`flow`]: crate::flow
//! [`FlowEntity`]: crate::flow::FlowEntity
//! [`FlowEntity::spawn_flow`]: crate::flow::FlowEntity::spawn_flow
//! [`FlowEntity::wait_despawned`]: crate::flow::FlowEntity::wait_despawned
//! [`FlowEntity::wait_has_component`]: crate::flow::FlowEntity::wait_has_component
//! [`Flows`]: crate::flow::Flows
//! [`Flows::execute`]: crate::flow::Flows::execute
//! [`FlowWorld`]: crate::flow::FlowWorld
//! [`FlowWorld::spawn_flow`]: crate::flow::FlowWorld::spawn_flow
//! [`FlowWorld::spawn_flow_for`]: crate::flow::FlowWorld::spawn_flow_for
//! [`FnArg`]: crate::system::FnArg
//! [`IdRange`]: crate::entity::IdRange
//! [`IdRangeAllocator`]: crate::entity::IdRangeAllocator
//! [`IntoSystem`]: crate::system::IntoSystem
//! [`LocalActionEncoder`]: crate::action::LocalActionEncoder
//! [`Modified`]: crate::query::Modified
//! [`Query`]: crate::query::Query
//! [`Relation`]: crate::relation::Relation
//! [`Res`]: crate::resources::Res
//! [`ResMut`]: crate::resources::ResMut
//! [`ResLocal`]: crate::system::ResLocal
//! [`ResMutLocal`]: crate::system::ResMutLocal
//! [`Scheduler`]: crate::scheduler::Scheduler
//! [`Scheduler::run_rayon`]: crate::scheduler::Scheduler::run_rayon
//! [`Scheduler::run_threaded`]: crate::scheduler::Scheduler::run_threaded
//! [`Scheduler::run_with`]: crate::scheduler::Scheduler::run_with
//! [`ScopedExecutor`]: crate::scheduler::ScopedExecutor
//! [`State`]: crate::system::State
//! [`System`]: crate::system::System
//! [`TypeId`]: core::any::TypeId
//! [`View`]: crate::view::View
//! [`ViewCell`]: crate::view::ViewCell
//! [`ViewMut`]: crate::view::ViewMut
//! [`ViewRef`]: crate::view::ViewRef
//! [`WakeOnDrop`]: crate::flow::WakeOnDrop
//! [`World`]: crate::world::World
//! [`World::drop`]: crate::world::World::drop
//! [`World::epoch`]: crate::world::World::epoch
//! [`World::spawn_flow`]: crate::world::World::spawn_flow
//! [`World::spawn_flow_for`]: crate::world::World::spawn_flow_for
//! [`WorldBuilder`]: crate::world::WorldBuilder
//! [`WorldLocal`]: crate::world::WorldLocal
//! [`WorldLocal::defer*`]: crate::world::WorldLocal::defer
//!
//!
extern crate alloc;
extern crate self as edict;
use ;
};
}
$?) => ;
}
}
};
}
;
unsafe
unsafe