2020-10-18 20:48:15 +00:00
|
|
|
use anyhow::Result;
|
Bevy ECS V2 (#1525)
# Bevy ECS V2
This is a rewrite of Bevy ECS (basically everything but the new executor/schedule, which are already awesome). The overall goal was to improve the performance and versatility of Bevy ECS. Here is a quick bulleted list of changes before we dive into the details:
* Complete World rewrite
* Multiple component storage types:
* Tables: fast cache friendly iteration, slower add/removes (previously called Archetypes)
* Sparse Sets: fast add/remove, slower iteration
* Stateful Queries (caches query results for faster iteration. fragmented iteration is _fast_ now)
* Stateful System Params (caches expensive operations. inspired by @DJMcNab's work in #1364)
* Configurable System Params (users can set configuration when they construct their systems. once again inspired by @DJMcNab's work)
* Archetypes are now "just metadata", component storage is separate
* Archetype Graph (for faster archetype changes)
* Component Metadata
* Configure component storage type
* Retrieve information about component size/type/name/layout/send-ness/etc
* Components are uniquely identified by a densely packed ComponentId
* TypeIds are now totally optional (which should make implementing scripting easier)
* Super fast "for_each" query iterators
* Merged Resources into World. Resources are now just a special type of component
* EntityRef/EntityMut builder apis (more efficient and more ergonomic)
* Fast bitset-backed `Access<T>` replaces old hashmap-based approach everywhere
* Query conflicts are determined by component access instead of archetype component access (to avoid random failures at runtime)
* With/Without are still taken into account for conflicts, so this should still be comfy to use
* Much simpler `IntoSystem` impl
* Significantly reduced the amount of hashing throughout the ecs in favor of Sparse Sets (indexed by densely packed ArchetypeId, ComponentId, BundleId, and TableId)
* Safety Improvements
* Entity reservation uses a normal world reference instead of unsafe transmute
* QuerySets no longer transmute lifetimes
* Made traits "unsafe" where relevant
* More thorough safety docs
* WorldCell
* Exposes safe mutable access to multiple resources at a time in a World
* Replaced "catch all" `System::update_archetypes(world: &World)` with `System::new_archetype(archetype: &Archetype)`
* Simpler Bundle implementation
* Replaced slow "remove_bundle_one_by_one" used as fallback for Commands::remove_bundle with fast "remove_bundle_intersection"
* Removed `Mut<T>` query impl. it is better to only support one way: `&mut T`
* Removed with() from `Flags<T>` in favor of `Option<Flags<T>>`, which allows querying for flags to be "filtered" by default
* Components now have is_send property (currently only resources support non-send)
* More granular module organization
* New `RemovedComponents<T>` SystemParam that replaces `query.removed::<T>()`
* `world.resource_scope()` for mutable access to resources and world at the same time
* WorldQuery and QueryFilter traits unified. FilterFetch trait added to enable "short circuit" filtering. Auto impled for cases that don't need it
* Significantly slimmed down SystemState in favor of individual SystemParam state
* System Commands changed from `commands: &mut Commands` back to `mut commands: Commands` (to allow Commands to have a World reference)
Fixes #1320
## `World` Rewrite
This is a from-scratch rewrite of `World` that fills the niche that `hecs` used to. Yes, this means Bevy ECS is no longer a "fork" of hecs. We're going out our own!
(the only shared code between the projects is the entity id allocator, which is already basically ideal)
A huge shout out to @SanderMertens (author of [flecs](https://github.com/SanderMertens/flecs)) for sharing some great ideas with me (specifically hybrid ecs storage and archetype graphs). He also helped advise on a number of implementation details.
## Component Storage (The Problem)
Two ECS storage paradigms have gained a lot of traction over the years:
* **Archetypal ECS**:
* Stores components in "tables" with static schemas. Each "column" stores components of a given type. Each "row" is an entity.
* Each "archetype" has its own table. Adding/removing an entity's component changes the archetype.
* Enables super-fast Query iteration due to its cache-friendly data layout
* Comes at the cost of more expensive add/remove operations for an Entity's components, because all components need to be copied to the new archetype's "table"
* **Sparse Set ECS**:
* Stores components of the same type in densely packed arrays, which are sparsely indexed by densely packed unsigned integers (Entity ids)
* Query iteration is slower than Archetypal ECS because each entity's component could be at any position in the sparse set. This "random access" pattern isn't cache friendly. Additionally, there is an extra layer of indirection because you must first map the entity id to an index in the component array.
* Adding/removing components is a cheap, constant time operation
Bevy ECS V1, hecs, legion, flec, and Unity DOTS are all "archetypal ecs-es". I personally think "archetypal" storage is a good default for game engines. An entity's archetype doesn't need to change frequently in general, and it creates "fast by default" query iteration (which is a much more common operation). It is also "self optimizing". Users don't need to think about optimizing component layouts for iteration performance. It "just works" without any extra boilerplate.
Shipyard and EnTT are "sparse set ecs-es". They employ "packing" as a way to work around the "suboptimal by default" iteration performance for specific sets of components. This helps, but I didn't think this was a good choice for a general purpose engine like Bevy because:
1. "packs" conflict with each other. If bevy decides to internally pack the Transform and GlobalTransform components, users are then blocked if they want to pack some custom component with Transform.
2. users need to take manual action to optimize
Developers selecting an ECS framework are stuck with a hard choice. Select an "archetypal" framework with "fast iteration everywhere" but without the ability to cheaply add/remove components, or select a "sparse set" framework to cheaply add/remove components but with slower iteration performance.
## Hybrid Component Storage (The Solution)
In Bevy ECS V2, we get to have our cake and eat it too. It now has _both_ of the component storage types above (and more can be added later if needed):
* **Tables** (aka "archetypal" storage)
* The default storage. If you don't configure anything, this is what you get
* Fast iteration by default
* Slower add/remove operations
* **Sparse Sets**
* Opt-in
* Slower iteration
* Faster add/remove operations
These storage types complement each other perfectly. By default Query iteration is fast. If developers know that they want to add/remove a component at high frequencies, they can set the storage to "sparse set":
```rust
world.register_component(
ComponentDescriptor::new::<MyComponent>(StorageType::SparseSet)
).unwrap();
```
## Archetypes
Archetypes are now "just metadata" ... they no longer store components directly. They do store:
* The `ComponentId`s of each of the Archetype's components (and that component's storage type)
* Archetypes are uniquely defined by their component layouts
* For example: entities with "table" components `[A, B, C]` _and_ "sparse set" components `[D, E]` will always be in the same archetype.
* The `TableId` associated with the archetype
* For now each archetype has exactly one table (which can have no components),
* There is a 1->Many relationship from Tables->Archetypes. A given table could have any number of archetype components stored in it:
* Ex: an entity with "table storage" components `[A, B, C]` and "sparse set" components `[D, E]` will share the same `[A, B, C]` table as an entity with `[A, B, C]` table component and `[F]` sparse set components.
* This 1->Many relationship is how we preserve fast "cache friendly" iteration performance when possible (more on this later)
* A list of entities that are in the archetype and the row id of the table they are in
* ArchetypeComponentIds
* unique densely packed identifiers for (ArchetypeId, ComponentId) pairs
* used by the schedule executor for cheap system access control
* "Archetype Graph Edges" (see the next section)
## The "Archetype Graph"
Archetype changes in Bevy (and a number of other archetypal ecs-es) have historically been expensive to compute. First, you need to allocate a new vector of the entity's current component ids, add or remove components based on the operation performed, sort it (to ensure it is order-independent), then hash it to find the archetype (if it exists). And thats all before we get to the _already_ expensive full copy of all components to the new table storage.
The solution is to build a "graph" of archetypes to cache these results. @SanderMertens first exposed me to the idea (and he got it from @gjroelofs, who came up with it). They propose adding directed edges between archetypes for add/remove component operations. If `ComponentId`s are densely packed, you can use sparse sets to cheaply jump between archetypes.
Bevy takes this one step further by using add/remove `Bundle` edges instead of `Component` edges. Bevy encourages the use of `Bundles` to group add/remove operations. This is largely for "clearer game logic" reasons, but it also helps cut down on the number of archetype changes required. `Bundles` now also have densely-packed `BundleId`s. This allows us to use a _single_ edge for each bundle operation (rather than needing to traverse N edges ... one for each component). Single component operations are also bundles, so this is strictly an improvement over a "component only" graph.
As a result, an operation that used to be _heavy_ (both for allocations and compute) is now two dirt-cheap array lookups and zero allocations.
## Stateful Queries
World queries are now stateful. This allows us to:
1. Cache archetype (and table) matches
* This resolves another issue with (naive) archetypal ECS: query performance getting worse as the number of archetypes goes up (and fragmentation occurs).
2. Cache Fetch and Filter state
* The expensive parts of fetch/filter operations (such as hashing the TypeId to find the ComponentId) now only happen once when the Query is first constructed
3. Incrementally build up state
* When new archetypes are added, we only process the new archetypes (no need to rebuild state for old archetypes)
As a result, the direct `World` query api now looks like this:
```rust
let mut query = world.query::<(&A, &mut B)>();
for (a, mut b) in query.iter_mut(&mut world) {
}
```
Requiring `World` to generate stateful queries (rather than letting the `QueryState` type be constructed separately) allows us to ensure that _all_ queries are properly initialized (and the relevant world state, such as ComponentIds). This enables QueryState to remove branches from its operations that check for initialization status (and also enables query.iter() to take an immutable world reference because it doesn't need to initialize anything in world).
However in systems, this is a non-breaking change. State management is done internally by the relevant SystemParam.
## Stateful SystemParams
Like Queries, `SystemParams` now also cache state. For example, `Query` system params store the "stateful query" state mentioned above. Commands store their internal `CommandQueue`. This means you can now safely use as many separate `Commands` parameters in your system as you want. `Local<T>` system params store their `T` value in their state (instead of in Resources).
SystemParam state also enabled a significant slim-down of SystemState. It is much nicer to look at now.
Per-SystemParam state naturally insulates us from an "aliased mut" class of errors we have hit in the past (ex: using multiple `Commands` system params).
(credit goes to @DJMcNab for the initial idea and draft pr here #1364)
## Configurable SystemParams
@DJMcNab also had the great idea to make SystemParams configurable. This allows users to provide some initial configuration / values for system parameters (when possible). Most SystemParams have no config (the config type is `()`), but the `Local<T>` param now supports user-provided parameters:
```rust
fn foo(value: Local<usize>) {
}
app.add_system(foo.system().config(|c| c.0 = Some(10)));
```
## Uber Fast "for_each" Query Iterators
Developers now have the choice to use a fast "for_each" iterator, which yields ~1.5-3x iteration speed improvements for "fragmented iteration", and minor ~1.2x iteration speed improvements for unfragmented iteration.
```rust
fn system(query: Query<(&A, &mut B)>) {
// you now have the option to do this for a speed boost
query.for_each_mut(|(a, mut b)| {
});
// however normal iterators are still available
for (a, mut b) in query.iter_mut() {
}
}
```
I think in most cases we should continue to encourage "normal" iterators as they are more flexible and more "rust idiomatic". But when that extra "oomf" is needed, it makes sense to use `for_each`.
We should also consider using `for_each` for internal bevy systems to give our users a nice speed boost (but that should be a separate pr).
## Component Metadata
`World` now has a `Components` collection, which is accessible via `world.components()`. This stores mappings from `ComponentId` to `ComponentInfo`, as well as `TypeId` to `ComponentId` mappings (where relevant). `ComponentInfo` stores information about the component, such as ComponentId, TypeId, memory layout, send-ness (currently limited to resources), and storage type.
## Significantly Cheaper `Access<T>`
We used to use `TypeAccess<TypeId>` to manage read/write component/archetype-component access. This was expensive because TypeIds must be hashed and compared individually. The parallel executor got around this by "condensing" type ids into bitset-backed access types. This worked, but it had to be re-generated from the `TypeAccess<TypeId>`sources every time archetypes changed.
This pr removes TypeAccess in favor of faster bitset access everywhere. We can do this thanks to the move to densely packed `ComponentId`s and `ArchetypeComponentId`s.
## Merged Resources into World
Resources had a lot of redundant functionality with Components. They stored typed data, they had access control, they had unique ids, they were queryable via SystemParams, etc. In fact the _only_ major difference between them was that they were unique (and didn't correlate to an entity).
Separate resources also had the downside of requiring a separate set of access controls, which meant the parallel executor needed to compare more bitsets per system and manage more state.
I initially got the "separate resources" idea from `legion`. I think that design was motivated by the fact that it made the direct world query/resource lifetime interactions more manageable. It certainly made our lives easier when using Resources alongside hecs/bevy_ecs. However we already have a construct for safely and ergonomically managing in-world lifetimes: systems (which use `Access<T>` internally).
This pr merges Resources into World:
```rust
world.insert_resource(1);
world.insert_resource(2.0);
let a = world.get_resource::<i32>().unwrap();
let mut b = world.get_resource_mut::<f64>().unwrap();
*b = 3.0;
```
Resources are now just a special kind of component. They have their own ComponentIds (and their own resource TypeId->ComponentId scope, so they don't conflict wit components of the same type). They are stored in a special "resource archetype", which stores components inside the archetype using a new `unique_components` sparse set (note that this sparse set could later be used to implement Tags). This allows us to keep the code size small by reusing existing datastructures (namely Column, Archetype, ComponentFlags, and ComponentInfo). This allows us the executor to use a single `Access<ArchetypeComponentId>` per system. It should also make scripting language integration easier.
_But_ this merge did create problems for people directly interacting with `World`. What if you need mutable access to multiple resources at the same time? `world.get_resource_mut()` borrows World mutably!
## WorldCell
WorldCell applies the `Access<ArchetypeComponentId>` concept to direct world access:
```rust
let world_cell = world.cell();
let a = world_cell.get_resource_mut::<i32>().unwrap();
let b = world_cell.get_resource_mut::<f64>().unwrap();
```
This adds cheap runtime checks (a sparse set lookup of `ArchetypeComponentId` and a counter) to ensure that world accesses do not conflict with each other. Each operation returns a `WorldBorrow<'w, T>` or `WorldBorrowMut<'w, T>` wrapper type, which will release the relevant ArchetypeComponentId resources when dropped.
World caches the access sparse set (and only one cell can exist at a time), so `world.cell()` is a cheap operation.
WorldCell does _not_ use atomic operations. It is non-send, does a mutable borrow of world to prevent other accesses, and uses a simple `Rc<RefCell<ArchetypeComponentAccess>>` wrapper in each WorldBorrow pointer.
The api is currently limited to resource access, but it can and should be extended to queries / entity component access.
## Resource Scopes
WorldCell does not yet support component queries, and even when it does there are sometimes legitimate reasons to want a mutable world ref _and_ a mutable resource ref (ex: bevy_render and bevy_scene both need this). In these cases we could always drop down to the unsafe `world.get_resource_unchecked_mut()`, but that is not ideal!
Instead developers can use a "resource scope"
```rust
world.resource_scope(|world: &mut World, a: &mut A| {
})
```
This temporarily removes the `A` resource from `World`, provides mutable pointers to both, and re-adds A to World when finished. Thanks to the move to ComponentIds/sparse sets, this is a cheap operation.
If multiple resources are required, scopes can be nested. We could also consider adding a "resource tuple" to the api if this pattern becomes common and the boilerplate gets nasty.
## Query Conflicts Use ComponentId Instead of ArchetypeComponentId
For safety reasons, systems cannot contain queries that conflict with each other without wrapping them in a QuerySet. On bevy `main`, we use ArchetypeComponentIds to determine conflicts. This is nice because it can take into account filters:
```rust
// these queries will never conflict due to their filters
fn filter_system(a: Query<&mut A, With<B>>, b: Query<&mut B, Without<B>>) {
}
```
But it also has a significant downside:
```rust
// these queries will not conflict _until_ an entity with A, B, and C is spawned
fn maybe_conflicts_system(a: Query<(&mut A, &C)>, b: Query<(&mut A, &B)>) {
}
```
The system above will panic at runtime if an entity with A, B, and C is spawned. This makes it hard to trust that your game logic will run without crashing.
In this pr, I switched to using `ComponentId` instead. This _is_ more constraining. `maybe_conflicts_system` will now always fail, but it will do it consistently at startup. Naively, it would also _disallow_ `filter_system`, which would be a significant downgrade in usability. Bevy has a number of internal systems that rely on disjoint queries and I expect it to be a common pattern in userspace.
To resolve this, I added a new `FilteredAccess<T>` type, which wraps `Access<T>` and adds with/without filters. If two `FilteredAccess` have with/without values that prove they are disjoint, they will no longer conflict.
## EntityRef / EntityMut
World entity operations on `main` require that the user passes in an `entity` id to each operation:
```rust
let entity = world.spawn((A, )); // create a new entity with A
world.get::<A>(entity);
world.insert(entity, (B, C));
world.insert_one(entity, D);
```
This means that each operation needs to look up the entity location / verify its validity. The initial spawn operation also requires a Bundle as input. This can be awkward when no components are required (or one component is required).
These operations have been replaced by `EntityRef` and `EntityMut`, which are "builder-style" wrappers around world that provide read and read/write operations on a single, pre-validated entity:
```rust
// spawn now takes no inputs and returns an EntityMut
let entity = world.spawn()
.insert(A) // insert a single component into the entity
.insert_bundle((B, C)) // insert a bundle of components into the entity
.id() // id returns the Entity id
// Returns EntityMut (or panics if the entity does not exist)
world.entity_mut(entity)
.insert(D)
.insert_bundle(SomeBundle::default());
{
// returns EntityRef (or panics if the entity does not exist)
let d = world.entity(entity)
.get::<D>() // gets the D component
.unwrap();
// world.get still exists for ergonomics
let d = world.get::<D>(entity).unwrap();
}
// These variants return Options if you want to check existence instead of panicing
world.get_entity_mut(entity)
.unwrap()
.insert(E);
if let Some(entity_ref) = world.get_entity(entity) {
let d = entity_ref.get::<D>().unwrap();
}
```
This _does not_ affect the current Commands api or terminology. I think that should be a separate conversation as that is a much larger breaking change.
## Safety Improvements
* Entity reservation in Commands uses a normal world borrow instead of an unsafe transmute
* QuerySets no longer transmutes lifetimes
* Made traits "unsafe" when implementing a trait incorrectly could cause unsafety
* More thorough safety docs
## RemovedComponents SystemParam
The old approach to querying removed components: `query.removed:<T>()` was confusing because it had no connection to the query itself. I replaced it with the following, which is both clearer and allows us to cache the ComponentId mapping in the SystemParamState:
```rust
fn system(removed: RemovedComponents<T>) {
for entity in removed.iter() {
}
}
```
## Simpler Bundle implementation
Bundles are no longer responsible for sorting (or deduping) TypeInfo. They are just a simple ordered list of component types / data. This makes the implementation smaller and opens the door to an easy "nested bundle" implementation in the future (which i might even add in this pr). Duplicate detection is now done once per bundle type by World the first time a bundle is used.
## Unified WorldQuery and QueryFilter types
(don't worry they are still separate type _parameters_ in Queries .. this is a non-breaking change)
WorldQuery and QueryFilter were already basically identical apis. With the addition of `FetchState` and more storage-specific fetch methods, the overlap was even clearer (and the redundancy more painful).
QueryFilters are now just `F: WorldQuery where F::Fetch: FilterFetch`. FilterFetch requires `Fetch<Item = bool>` and adds new "short circuit" variants of fetch methods. This enables a filter tuple like `(With<A>, Without<B>, Changed<C>)` to stop evaluating the filter after the first mismatch is encountered. FilterFetch is automatically implemented for `Fetch` implementations that return bool.
This forces fetch implementations that return things like `(bool, bool, bool)` (such as the filter above) to manually implement FilterFetch and decide whether or not to short-circuit.
## More Granular Modules
World no longer globs all of the internal modules together. It now exports `core`, `system`, and `schedule` separately. I'm also considering exporting `core` submodules directly as that is still pretty "glob-ey" and unorganized (feedback welcome here).
## Remaining Draft Work (to be done in this pr)
* ~~panic on conflicting WorldQuery fetches (&A, &mut A)~~
* ~~bevy `main` and hecs both currently allow this, but we should protect against it if possible~~
* ~~batch_iter / par_iter (currently stubbed out)~~
* ~~ChangedRes~~
* ~~I skipped this while we sort out #1313. This pr should be adapted to account for whatever we land on there~~.
* ~~The `Archetypes` and `Tables` collections use hashes of sorted lists of component ids to uniquely identify each archetype/table. This hash is then used as the key in a HashMap to look up the relevant ArchetypeId or TableId. (which doesn't handle hash collisions properly)~~
* ~~It is currently unsafe to generate a Query from "World A", then use it on "World B" (despite the api claiming it is safe). We should probably close this gap. This could be done by adding a randomly generated WorldId to each world, then storing that id in each Query. They could then be compared to each other on each `query.do_thing(&world)` operation. This _does_ add an extra branch to each query operation, so I'm open to other suggestions if people have them.~~
* ~~Nested Bundles (if i find time)~~
## Potential Future Work
* Expand WorldCell to support queries.
* Consider not allocating in the empty archetype on `world.spawn()`
* ex: return something like EntityMutUninit, which turns into EntityMut after an `insert` or `insert_bundle` op
* this actually regressed performance last time i tried it, but in theory it should be faster
* Optimize SparseSet::insert (see `PERF` comment on insert)
* Replace SparseArray `Option<T>` with T::MAX to cut down on branching
* would enable cheaper get_unchecked() operations
* upstream fixedbitset optimizations
* fixedbitset could be allocation free for small block counts (store blocks in a SmallVec)
* fixedbitset could have a const constructor
* Consider implementing Tags (archetype-specific by-value data that affects archetype identity)
* ex: ArchetypeA could have `[A, B, C]` table components and `[D(1)]` "tag" component. ArchetypeB could have `[A, B, C]` table components and a `[D(2)]` tag component. The archetypes are different, despite both having D tags because the value inside D is different.
* this could potentially build on top of the `archetype.unique_components` added in this pr for resource storage.
* Consider reverting `all_tuples` proc macro in favor of the old `macro_rules` implementation
* all_tuples is more flexible and produces cleaner documentation (the macro_rules version produces weird type parameter orders due to parser constraints)
* but unfortunately all_tuples also appears to make Rust Analyzer sad/slow when working inside of `bevy_ecs` (does not affect user code)
* Consider "resource queries" and/or "mixed resource and entity component queries" as an alternative to WorldCell
* this is basically just "systems" so maybe it's not worth it
* Add more world ops
* `world.clear()`
* `world.reserve<T: Bundle>(count: usize)`
* Try using the old archetype allocation strategy (allocate new memory on resize and copy everything over). I expect this to improve batch insertion performance at the cost of unbatched performance. But thats just a guess. I'm not an allocation perf pro :)
* Adapt Commands apis for consistency with new World apis
## Benchmarks
key:
* `bevy_old`: bevy `main` branch
* `bevy`: this branch
* `_foreach`: uses an optimized for_each iterator
* ` _sparse`: uses sparse set storage (if unspecified assume table storage)
* `_system`: runs inside a system (if unspecified assume test happens via direct world ops)
### Simple Insert (from ecs_bench_suite)
![image](https://user-images.githubusercontent.com/2694663/109245573-9c3ce100-7795-11eb-9003-bfd41cd5c51f.png)
### Simpler Iter (from ecs_bench_suite)
![image](https://user-images.githubusercontent.com/2694663/109245795-ffc70e80-7795-11eb-92fb-3ffad09aabf7.png)
### Fragment Iter (from ecs_bench_suite)
![image](https://user-images.githubusercontent.com/2694663/109245849-0fdeee00-7796-11eb-8d25-eb6b7a682c48.png)
### Sparse Fragmented Iter
Iterate a query that matches 5 entities from a single matching archetype, but there are 100 unmatching archetypes
![image](https://user-images.githubusercontent.com/2694663/109245916-2b49f900-7796-11eb-9a8f-ed89c203f940.png)
### Schedule (from ecs_bench_suite)
![image](https://user-images.githubusercontent.com/2694663/109246428-1fab0200-7797-11eb-8841-1b2161e90fa4.png)
### Add Remove Component (from ecs_bench_suite)
![image](https://user-images.githubusercontent.com/2694663/109246492-39e4e000-7797-11eb-8985-2706bd0495ab.png)
### Add Remove Component Big
Same as the test above, but each entity has 5 "large" matrix components and 1 "large" matrix component is added and removed
![image](https://user-images.githubusercontent.com/2694663/109246517-449f7500-7797-11eb-835e-28b6790daeaa.png)
### Get Component
Looks up a single component value a large number of times
![image](https://user-images.githubusercontent.com/2694663/109246129-87ad1880-7796-11eb-9fcb-c38012aa7c70.png)
2021-03-05 07:54:35 +00:00
|
|
|
use bevy_asset::{
|
|
|
|
AssetIoError, AssetLoader, AssetPath, BoxedFuture, Handle, LoadContext, LoadedAsset,
|
|
|
|
};
|
2021-01-01 21:30:18 +00:00
|
|
|
use bevy_core::Name;
|
Bevy ECS V2 (#1525)
# Bevy ECS V2
This is a rewrite of Bevy ECS (basically everything but the new executor/schedule, which are already awesome). The overall goal was to improve the performance and versatility of Bevy ECS. Here is a quick bulleted list of changes before we dive into the details:
* Complete World rewrite
* Multiple component storage types:
* Tables: fast cache friendly iteration, slower add/removes (previously called Archetypes)
* Sparse Sets: fast add/remove, slower iteration
* Stateful Queries (caches query results for faster iteration. fragmented iteration is _fast_ now)
* Stateful System Params (caches expensive operations. inspired by @DJMcNab's work in #1364)
* Configurable System Params (users can set configuration when they construct their systems. once again inspired by @DJMcNab's work)
* Archetypes are now "just metadata", component storage is separate
* Archetype Graph (for faster archetype changes)
* Component Metadata
* Configure component storage type
* Retrieve information about component size/type/name/layout/send-ness/etc
* Components are uniquely identified by a densely packed ComponentId
* TypeIds are now totally optional (which should make implementing scripting easier)
* Super fast "for_each" query iterators
* Merged Resources into World. Resources are now just a special type of component
* EntityRef/EntityMut builder apis (more efficient and more ergonomic)
* Fast bitset-backed `Access<T>` replaces old hashmap-based approach everywhere
* Query conflicts are determined by component access instead of archetype component access (to avoid random failures at runtime)
* With/Without are still taken into account for conflicts, so this should still be comfy to use
* Much simpler `IntoSystem` impl
* Significantly reduced the amount of hashing throughout the ecs in favor of Sparse Sets (indexed by densely packed ArchetypeId, ComponentId, BundleId, and TableId)
* Safety Improvements
* Entity reservation uses a normal world reference instead of unsafe transmute
* QuerySets no longer transmute lifetimes
* Made traits "unsafe" where relevant
* More thorough safety docs
* WorldCell
* Exposes safe mutable access to multiple resources at a time in a World
* Replaced "catch all" `System::update_archetypes(world: &World)` with `System::new_archetype(archetype: &Archetype)`
* Simpler Bundle implementation
* Replaced slow "remove_bundle_one_by_one" used as fallback for Commands::remove_bundle with fast "remove_bundle_intersection"
* Removed `Mut<T>` query impl. it is better to only support one way: `&mut T`
* Removed with() from `Flags<T>` in favor of `Option<Flags<T>>`, which allows querying for flags to be "filtered" by default
* Components now have is_send property (currently only resources support non-send)
* More granular module organization
* New `RemovedComponents<T>` SystemParam that replaces `query.removed::<T>()`
* `world.resource_scope()` for mutable access to resources and world at the same time
* WorldQuery and QueryFilter traits unified. FilterFetch trait added to enable "short circuit" filtering. Auto impled for cases that don't need it
* Significantly slimmed down SystemState in favor of individual SystemParam state
* System Commands changed from `commands: &mut Commands` back to `mut commands: Commands` (to allow Commands to have a World reference)
Fixes #1320
## `World` Rewrite
This is a from-scratch rewrite of `World` that fills the niche that `hecs` used to. Yes, this means Bevy ECS is no longer a "fork" of hecs. We're going out our own!
(the only shared code between the projects is the entity id allocator, which is already basically ideal)
A huge shout out to @SanderMertens (author of [flecs](https://github.com/SanderMertens/flecs)) for sharing some great ideas with me (specifically hybrid ecs storage and archetype graphs). He also helped advise on a number of implementation details.
## Component Storage (The Problem)
Two ECS storage paradigms have gained a lot of traction over the years:
* **Archetypal ECS**:
* Stores components in "tables" with static schemas. Each "column" stores components of a given type. Each "row" is an entity.
* Each "archetype" has its own table. Adding/removing an entity's component changes the archetype.
* Enables super-fast Query iteration due to its cache-friendly data layout
* Comes at the cost of more expensive add/remove operations for an Entity's components, because all components need to be copied to the new archetype's "table"
* **Sparse Set ECS**:
* Stores components of the same type in densely packed arrays, which are sparsely indexed by densely packed unsigned integers (Entity ids)
* Query iteration is slower than Archetypal ECS because each entity's component could be at any position in the sparse set. This "random access" pattern isn't cache friendly. Additionally, there is an extra layer of indirection because you must first map the entity id to an index in the component array.
* Adding/removing components is a cheap, constant time operation
Bevy ECS V1, hecs, legion, flec, and Unity DOTS are all "archetypal ecs-es". I personally think "archetypal" storage is a good default for game engines. An entity's archetype doesn't need to change frequently in general, and it creates "fast by default" query iteration (which is a much more common operation). It is also "self optimizing". Users don't need to think about optimizing component layouts for iteration performance. It "just works" without any extra boilerplate.
Shipyard and EnTT are "sparse set ecs-es". They employ "packing" as a way to work around the "suboptimal by default" iteration performance for specific sets of components. This helps, but I didn't think this was a good choice for a general purpose engine like Bevy because:
1. "packs" conflict with each other. If bevy decides to internally pack the Transform and GlobalTransform components, users are then blocked if they want to pack some custom component with Transform.
2. users need to take manual action to optimize
Developers selecting an ECS framework are stuck with a hard choice. Select an "archetypal" framework with "fast iteration everywhere" but without the ability to cheaply add/remove components, or select a "sparse set" framework to cheaply add/remove components but with slower iteration performance.
## Hybrid Component Storage (The Solution)
In Bevy ECS V2, we get to have our cake and eat it too. It now has _both_ of the component storage types above (and more can be added later if needed):
* **Tables** (aka "archetypal" storage)
* The default storage. If you don't configure anything, this is what you get
* Fast iteration by default
* Slower add/remove operations
* **Sparse Sets**
* Opt-in
* Slower iteration
* Faster add/remove operations
These storage types complement each other perfectly. By default Query iteration is fast. If developers know that they want to add/remove a component at high frequencies, they can set the storage to "sparse set":
```rust
world.register_component(
ComponentDescriptor::new::<MyComponent>(StorageType::SparseSet)
).unwrap();
```
## Archetypes
Archetypes are now "just metadata" ... they no longer store components directly. They do store:
* The `ComponentId`s of each of the Archetype's components (and that component's storage type)
* Archetypes are uniquely defined by their component layouts
* For example: entities with "table" components `[A, B, C]` _and_ "sparse set" components `[D, E]` will always be in the same archetype.
* The `TableId` associated with the archetype
* For now each archetype has exactly one table (which can have no components),
* There is a 1->Many relationship from Tables->Archetypes. A given table could have any number of archetype components stored in it:
* Ex: an entity with "table storage" components `[A, B, C]` and "sparse set" components `[D, E]` will share the same `[A, B, C]` table as an entity with `[A, B, C]` table component and `[F]` sparse set components.
* This 1->Many relationship is how we preserve fast "cache friendly" iteration performance when possible (more on this later)
* A list of entities that are in the archetype and the row id of the table they are in
* ArchetypeComponentIds
* unique densely packed identifiers for (ArchetypeId, ComponentId) pairs
* used by the schedule executor for cheap system access control
* "Archetype Graph Edges" (see the next section)
## The "Archetype Graph"
Archetype changes in Bevy (and a number of other archetypal ecs-es) have historically been expensive to compute. First, you need to allocate a new vector of the entity's current component ids, add or remove components based on the operation performed, sort it (to ensure it is order-independent), then hash it to find the archetype (if it exists). And thats all before we get to the _already_ expensive full copy of all components to the new table storage.
The solution is to build a "graph" of archetypes to cache these results. @SanderMertens first exposed me to the idea (and he got it from @gjroelofs, who came up with it). They propose adding directed edges between archetypes for add/remove component operations. If `ComponentId`s are densely packed, you can use sparse sets to cheaply jump between archetypes.
Bevy takes this one step further by using add/remove `Bundle` edges instead of `Component` edges. Bevy encourages the use of `Bundles` to group add/remove operations. This is largely for "clearer game logic" reasons, but it also helps cut down on the number of archetype changes required. `Bundles` now also have densely-packed `BundleId`s. This allows us to use a _single_ edge for each bundle operation (rather than needing to traverse N edges ... one for each component). Single component operations are also bundles, so this is strictly an improvement over a "component only" graph.
As a result, an operation that used to be _heavy_ (both for allocations and compute) is now two dirt-cheap array lookups and zero allocations.
## Stateful Queries
World queries are now stateful. This allows us to:
1. Cache archetype (and table) matches
* This resolves another issue with (naive) archetypal ECS: query performance getting worse as the number of archetypes goes up (and fragmentation occurs).
2. Cache Fetch and Filter state
* The expensive parts of fetch/filter operations (such as hashing the TypeId to find the ComponentId) now only happen once when the Query is first constructed
3. Incrementally build up state
* When new archetypes are added, we only process the new archetypes (no need to rebuild state for old archetypes)
As a result, the direct `World` query api now looks like this:
```rust
let mut query = world.query::<(&A, &mut B)>();
for (a, mut b) in query.iter_mut(&mut world) {
}
```
Requiring `World` to generate stateful queries (rather than letting the `QueryState` type be constructed separately) allows us to ensure that _all_ queries are properly initialized (and the relevant world state, such as ComponentIds). This enables QueryState to remove branches from its operations that check for initialization status (and also enables query.iter() to take an immutable world reference because it doesn't need to initialize anything in world).
However in systems, this is a non-breaking change. State management is done internally by the relevant SystemParam.
## Stateful SystemParams
Like Queries, `SystemParams` now also cache state. For example, `Query` system params store the "stateful query" state mentioned above. Commands store their internal `CommandQueue`. This means you can now safely use as many separate `Commands` parameters in your system as you want. `Local<T>` system params store their `T` value in their state (instead of in Resources).
SystemParam state also enabled a significant slim-down of SystemState. It is much nicer to look at now.
Per-SystemParam state naturally insulates us from an "aliased mut" class of errors we have hit in the past (ex: using multiple `Commands` system params).
(credit goes to @DJMcNab for the initial idea and draft pr here #1364)
## Configurable SystemParams
@DJMcNab also had the great idea to make SystemParams configurable. This allows users to provide some initial configuration / values for system parameters (when possible). Most SystemParams have no config (the config type is `()`), but the `Local<T>` param now supports user-provided parameters:
```rust
fn foo(value: Local<usize>) {
}
app.add_system(foo.system().config(|c| c.0 = Some(10)));
```
## Uber Fast "for_each" Query Iterators
Developers now have the choice to use a fast "for_each" iterator, which yields ~1.5-3x iteration speed improvements for "fragmented iteration", and minor ~1.2x iteration speed improvements for unfragmented iteration.
```rust
fn system(query: Query<(&A, &mut B)>) {
// you now have the option to do this for a speed boost
query.for_each_mut(|(a, mut b)| {
});
// however normal iterators are still available
for (a, mut b) in query.iter_mut() {
}
}
```
I think in most cases we should continue to encourage "normal" iterators as they are more flexible and more "rust idiomatic". But when that extra "oomf" is needed, it makes sense to use `for_each`.
We should also consider using `for_each` for internal bevy systems to give our users a nice speed boost (but that should be a separate pr).
## Component Metadata
`World` now has a `Components` collection, which is accessible via `world.components()`. This stores mappings from `ComponentId` to `ComponentInfo`, as well as `TypeId` to `ComponentId` mappings (where relevant). `ComponentInfo` stores information about the component, such as ComponentId, TypeId, memory layout, send-ness (currently limited to resources), and storage type.
## Significantly Cheaper `Access<T>`
We used to use `TypeAccess<TypeId>` to manage read/write component/archetype-component access. This was expensive because TypeIds must be hashed and compared individually. The parallel executor got around this by "condensing" type ids into bitset-backed access types. This worked, but it had to be re-generated from the `TypeAccess<TypeId>`sources every time archetypes changed.
This pr removes TypeAccess in favor of faster bitset access everywhere. We can do this thanks to the move to densely packed `ComponentId`s and `ArchetypeComponentId`s.
## Merged Resources into World
Resources had a lot of redundant functionality with Components. They stored typed data, they had access control, they had unique ids, they were queryable via SystemParams, etc. In fact the _only_ major difference between them was that they were unique (and didn't correlate to an entity).
Separate resources also had the downside of requiring a separate set of access controls, which meant the parallel executor needed to compare more bitsets per system and manage more state.
I initially got the "separate resources" idea from `legion`. I think that design was motivated by the fact that it made the direct world query/resource lifetime interactions more manageable. It certainly made our lives easier when using Resources alongside hecs/bevy_ecs. However we already have a construct for safely and ergonomically managing in-world lifetimes: systems (which use `Access<T>` internally).
This pr merges Resources into World:
```rust
world.insert_resource(1);
world.insert_resource(2.0);
let a = world.get_resource::<i32>().unwrap();
let mut b = world.get_resource_mut::<f64>().unwrap();
*b = 3.0;
```
Resources are now just a special kind of component. They have their own ComponentIds (and their own resource TypeId->ComponentId scope, so they don't conflict wit components of the same type). They are stored in a special "resource archetype", which stores components inside the archetype using a new `unique_components` sparse set (note that this sparse set could later be used to implement Tags). This allows us to keep the code size small by reusing existing datastructures (namely Column, Archetype, ComponentFlags, and ComponentInfo). This allows us the executor to use a single `Access<ArchetypeComponentId>` per system. It should also make scripting language integration easier.
_But_ this merge did create problems for people directly interacting with `World`. What if you need mutable access to multiple resources at the same time? `world.get_resource_mut()` borrows World mutably!
## WorldCell
WorldCell applies the `Access<ArchetypeComponentId>` concept to direct world access:
```rust
let world_cell = world.cell();
let a = world_cell.get_resource_mut::<i32>().unwrap();
let b = world_cell.get_resource_mut::<f64>().unwrap();
```
This adds cheap runtime checks (a sparse set lookup of `ArchetypeComponentId` and a counter) to ensure that world accesses do not conflict with each other. Each operation returns a `WorldBorrow<'w, T>` or `WorldBorrowMut<'w, T>` wrapper type, which will release the relevant ArchetypeComponentId resources when dropped.
World caches the access sparse set (and only one cell can exist at a time), so `world.cell()` is a cheap operation.
WorldCell does _not_ use atomic operations. It is non-send, does a mutable borrow of world to prevent other accesses, and uses a simple `Rc<RefCell<ArchetypeComponentAccess>>` wrapper in each WorldBorrow pointer.
The api is currently limited to resource access, but it can and should be extended to queries / entity component access.
## Resource Scopes
WorldCell does not yet support component queries, and even when it does there are sometimes legitimate reasons to want a mutable world ref _and_ a mutable resource ref (ex: bevy_render and bevy_scene both need this). In these cases we could always drop down to the unsafe `world.get_resource_unchecked_mut()`, but that is not ideal!
Instead developers can use a "resource scope"
```rust
world.resource_scope(|world: &mut World, a: &mut A| {
})
```
This temporarily removes the `A` resource from `World`, provides mutable pointers to both, and re-adds A to World when finished. Thanks to the move to ComponentIds/sparse sets, this is a cheap operation.
If multiple resources are required, scopes can be nested. We could also consider adding a "resource tuple" to the api if this pattern becomes common and the boilerplate gets nasty.
## Query Conflicts Use ComponentId Instead of ArchetypeComponentId
For safety reasons, systems cannot contain queries that conflict with each other without wrapping them in a QuerySet. On bevy `main`, we use ArchetypeComponentIds to determine conflicts. This is nice because it can take into account filters:
```rust
// these queries will never conflict due to their filters
fn filter_system(a: Query<&mut A, With<B>>, b: Query<&mut B, Without<B>>) {
}
```
But it also has a significant downside:
```rust
// these queries will not conflict _until_ an entity with A, B, and C is spawned
fn maybe_conflicts_system(a: Query<(&mut A, &C)>, b: Query<(&mut A, &B)>) {
}
```
The system above will panic at runtime if an entity with A, B, and C is spawned. This makes it hard to trust that your game logic will run without crashing.
In this pr, I switched to using `ComponentId` instead. This _is_ more constraining. `maybe_conflicts_system` will now always fail, but it will do it consistently at startup. Naively, it would also _disallow_ `filter_system`, which would be a significant downgrade in usability. Bevy has a number of internal systems that rely on disjoint queries and I expect it to be a common pattern in userspace.
To resolve this, I added a new `FilteredAccess<T>` type, which wraps `Access<T>` and adds with/without filters. If two `FilteredAccess` have with/without values that prove they are disjoint, they will no longer conflict.
## EntityRef / EntityMut
World entity operations on `main` require that the user passes in an `entity` id to each operation:
```rust
let entity = world.spawn((A, )); // create a new entity with A
world.get::<A>(entity);
world.insert(entity, (B, C));
world.insert_one(entity, D);
```
This means that each operation needs to look up the entity location / verify its validity. The initial spawn operation also requires a Bundle as input. This can be awkward when no components are required (or one component is required).
These operations have been replaced by `EntityRef` and `EntityMut`, which are "builder-style" wrappers around world that provide read and read/write operations on a single, pre-validated entity:
```rust
// spawn now takes no inputs and returns an EntityMut
let entity = world.spawn()
.insert(A) // insert a single component into the entity
.insert_bundle((B, C)) // insert a bundle of components into the entity
.id() // id returns the Entity id
// Returns EntityMut (or panics if the entity does not exist)
world.entity_mut(entity)
.insert(D)
.insert_bundle(SomeBundle::default());
{
// returns EntityRef (or panics if the entity does not exist)
let d = world.entity(entity)
.get::<D>() // gets the D component
.unwrap();
// world.get still exists for ergonomics
let d = world.get::<D>(entity).unwrap();
}
// These variants return Options if you want to check existence instead of panicing
world.get_entity_mut(entity)
.unwrap()
.insert(E);
if let Some(entity_ref) = world.get_entity(entity) {
let d = entity_ref.get::<D>().unwrap();
}
```
This _does not_ affect the current Commands api or terminology. I think that should be a separate conversation as that is a much larger breaking change.
## Safety Improvements
* Entity reservation in Commands uses a normal world borrow instead of an unsafe transmute
* QuerySets no longer transmutes lifetimes
* Made traits "unsafe" when implementing a trait incorrectly could cause unsafety
* More thorough safety docs
## RemovedComponents SystemParam
The old approach to querying removed components: `query.removed:<T>()` was confusing because it had no connection to the query itself. I replaced it with the following, which is both clearer and allows us to cache the ComponentId mapping in the SystemParamState:
```rust
fn system(removed: RemovedComponents<T>) {
for entity in removed.iter() {
}
}
```
## Simpler Bundle implementation
Bundles are no longer responsible for sorting (or deduping) TypeInfo. They are just a simple ordered list of component types / data. This makes the implementation smaller and opens the door to an easy "nested bundle" implementation in the future (which i might even add in this pr). Duplicate detection is now done once per bundle type by World the first time a bundle is used.
## Unified WorldQuery and QueryFilter types
(don't worry they are still separate type _parameters_ in Queries .. this is a non-breaking change)
WorldQuery and QueryFilter were already basically identical apis. With the addition of `FetchState` and more storage-specific fetch methods, the overlap was even clearer (and the redundancy more painful).
QueryFilters are now just `F: WorldQuery where F::Fetch: FilterFetch`. FilterFetch requires `Fetch<Item = bool>` and adds new "short circuit" variants of fetch methods. This enables a filter tuple like `(With<A>, Without<B>, Changed<C>)` to stop evaluating the filter after the first mismatch is encountered. FilterFetch is automatically implemented for `Fetch` implementations that return bool.
This forces fetch implementations that return things like `(bool, bool, bool)` (such as the filter above) to manually implement FilterFetch and decide whether or not to short-circuit.
## More Granular Modules
World no longer globs all of the internal modules together. It now exports `core`, `system`, and `schedule` separately. I'm also considering exporting `core` submodules directly as that is still pretty "glob-ey" and unorganized (feedback welcome here).
## Remaining Draft Work (to be done in this pr)
* ~~panic on conflicting WorldQuery fetches (&A, &mut A)~~
* ~~bevy `main` and hecs both currently allow this, but we should protect against it if possible~~
* ~~batch_iter / par_iter (currently stubbed out)~~
* ~~ChangedRes~~
* ~~I skipped this while we sort out #1313. This pr should be adapted to account for whatever we land on there~~.
* ~~The `Archetypes` and `Tables` collections use hashes of sorted lists of component ids to uniquely identify each archetype/table. This hash is then used as the key in a HashMap to look up the relevant ArchetypeId or TableId. (which doesn't handle hash collisions properly)~~
* ~~It is currently unsafe to generate a Query from "World A", then use it on "World B" (despite the api claiming it is safe). We should probably close this gap. This could be done by adding a randomly generated WorldId to each world, then storing that id in each Query. They could then be compared to each other on each `query.do_thing(&world)` operation. This _does_ add an extra branch to each query operation, so I'm open to other suggestions if people have them.~~
* ~~Nested Bundles (if i find time)~~
## Potential Future Work
* Expand WorldCell to support queries.
* Consider not allocating in the empty archetype on `world.spawn()`
* ex: return something like EntityMutUninit, which turns into EntityMut after an `insert` or `insert_bundle` op
* this actually regressed performance last time i tried it, but in theory it should be faster
* Optimize SparseSet::insert (see `PERF` comment on insert)
* Replace SparseArray `Option<T>` with T::MAX to cut down on branching
* would enable cheaper get_unchecked() operations
* upstream fixedbitset optimizations
* fixedbitset could be allocation free for small block counts (store blocks in a SmallVec)
* fixedbitset could have a const constructor
* Consider implementing Tags (archetype-specific by-value data that affects archetype identity)
* ex: ArchetypeA could have `[A, B, C]` table components and `[D(1)]` "tag" component. ArchetypeB could have `[A, B, C]` table components and a `[D(2)]` tag component. The archetypes are different, despite both having D tags because the value inside D is different.
* this could potentially build on top of the `archetype.unique_components` added in this pr for resource storage.
* Consider reverting `all_tuples` proc macro in favor of the old `macro_rules` implementation
* all_tuples is more flexible and produces cleaner documentation (the macro_rules version produces weird type parameter orders due to parser constraints)
* but unfortunately all_tuples also appears to make Rust Analyzer sad/slow when working inside of `bevy_ecs` (does not affect user code)
* Consider "resource queries" and/or "mixed resource and entity component queries" as an alternative to WorldCell
* this is basically just "systems" so maybe it's not worth it
* Add more world ops
* `world.clear()`
* `world.reserve<T: Bundle>(count: usize)`
* Try using the old archetype allocation strategy (allocate new memory on resize and copy everything over). I expect this to improve batch insertion performance at the cost of unbatched performance. But thats just a guess. I'm not an allocation perf pro :)
* Adapt Commands apis for consistency with new World apis
## Benchmarks
key:
* `bevy_old`: bevy `main` branch
* `bevy`: this branch
* `_foreach`: uses an optimized for_each iterator
* ` _sparse`: uses sparse set storage (if unspecified assume table storage)
* `_system`: runs inside a system (if unspecified assume test happens via direct world ops)
### Simple Insert (from ecs_bench_suite)
![image](https://user-images.githubusercontent.com/2694663/109245573-9c3ce100-7795-11eb-9003-bfd41cd5c51f.png)
### Simpler Iter (from ecs_bench_suite)
![image](https://user-images.githubusercontent.com/2694663/109245795-ffc70e80-7795-11eb-92fb-3ffad09aabf7.png)
### Fragment Iter (from ecs_bench_suite)
![image](https://user-images.githubusercontent.com/2694663/109245849-0fdeee00-7796-11eb-8d25-eb6b7a682c48.png)
### Sparse Fragmented Iter
Iterate a query that matches 5 entities from a single matching archetype, but there are 100 unmatching archetypes
![image](https://user-images.githubusercontent.com/2694663/109245916-2b49f900-7796-11eb-9a8f-ed89c203f940.png)
### Schedule (from ecs_bench_suite)
![image](https://user-images.githubusercontent.com/2694663/109246428-1fab0200-7797-11eb-8841-1b2161e90fa4.png)
### Add Remove Component (from ecs_bench_suite)
![image](https://user-images.githubusercontent.com/2694663/109246492-39e4e000-7797-11eb-8985-2706bd0495ab.png)
### Add Remove Component Big
Same as the test above, but each entity has 5 "large" matrix components and 1 "large" matrix component is added and removed
![image](https://user-images.githubusercontent.com/2694663/109246517-449f7500-7797-11eb-835e-28b6790daeaa.png)
### Get Component
Looks up a single component value a large number of times
![image](https://user-images.githubusercontent.com/2694663/109246129-87ad1880-7796-11eb-9fcb-c38012aa7c70.png)
2021-03-05 07:54:35 +00:00
|
|
|
use bevy_ecs::world::World;
|
2020-10-18 20:48:15 +00:00
|
|
|
use bevy_math::Mat4;
|
2020-11-16 04:32:23 +00:00
|
|
|
use bevy_pbr::prelude::{PbrBundle, StandardMaterial};
|
2020-05-15 23:55:44 +00:00
|
|
|
use bevy_render::{
|
2020-11-07 01:08:15 +00:00
|
|
|
camera::{
|
|
|
|
Camera, CameraProjection, OrthographicProjection, PerspectiveProjection, VisibleEntities,
|
|
|
|
},
|
2020-10-31 02:21:53 +00:00
|
|
|
mesh::{Indices, Mesh, VertexAttributeValues},
|
2020-07-17 01:26:21 +00:00
|
|
|
pipeline::PrimitiveTopology,
|
2020-10-18 20:48:15 +00:00
|
|
|
prelude::{Color, Texture},
|
2020-11-07 01:08:15 +00:00
|
|
|
render_graph::base,
|
2021-03-26 18:47:47 +00:00
|
|
|
texture::{AddressMode, FilterMode, ImageType, SamplerDescriptor, TextureError, TextureFormat},
|
2020-05-15 23:55:44 +00:00
|
|
|
};
|
2020-10-18 20:48:15 +00:00
|
|
|
use bevy_scene::Scene;
|
|
|
|
use bevy_transform::{
|
|
|
|
hierarchy::{BuildWorldChildren, WorldChildBuilder},
|
|
|
|
prelude::{GlobalTransform, Transform},
|
|
|
|
};
|
2020-10-29 21:22:45 +00:00
|
|
|
use gltf::{
|
|
|
|
mesh::Mode,
|
|
|
|
texture::{MagFilter, MinFilter, WrappingMode},
|
2020-12-09 03:36:41 +00:00
|
|
|
Material, Primitive,
|
2020-10-29 21:22:45 +00:00
|
|
|
};
|
2021-03-26 18:47:47 +00:00
|
|
|
use std::{
|
|
|
|
collections::{HashMap, HashSet},
|
|
|
|
path::Path,
|
|
|
|
};
|
2020-05-15 23:55:44 +00:00
|
|
|
use thiserror::Error;
|
|
|
|
|
2020-12-31 20:57:15 +00:00
|
|
|
use crate::{Gltf, GltfNode};
|
|
|
|
|
2020-08-09 23:13:04 +00:00
|
|
|
/// An error that occurs when loading a GLTF file
|
2020-05-15 23:55:44 +00:00
|
|
|
#[derive(Error, Debug)]
|
|
|
|
pub enum GltfError {
|
2020-12-02 19:31:16 +00:00
|
|
|
#[error("unsupported primitive mode")]
|
2020-05-15 23:55:44 +00:00
|
|
|
UnsupportedPrimitive { mode: Mode },
|
2020-12-02 19:31:16 +00:00
|
|
|
#[error("invalid GLTF file")]
|
2020-05-15 23:55:44 +00:00
|
|
|
Gltf(#[from] gltf::Error),
|
2020-12-02 19:31:16 +00:00
|
|
|
#[error("binary blob is missing")]
|
2020-08-25 23:55:08 +00:00
|
|
|
MissingBlob,
|
2020-12-02 19:31:16 +00:00
|
|
|
#[error("failed to decode base64 mesh data")]
|
2020-08-12 17:23:54 +00:00
|
|
|
Base64Decode(#[from] base64::DecodeError),
|
2020-12-02 19:31:16 +00:00
|
|
|
#[error("unsupported buffer format")]
|
2020-08-12 17:23:54 +00:00
|
|
|
BufferFormatUnsupported,
|
2020-12-02 19:31:16 +00:00
|
|
|
#[error("invalid image mime type")]
|
2020-10-18 20:48:15 +00:00
|
|
|
InvalidImageMimeType(String),
|
2020-12-02 19:31:16 +00:00
|
|
|
#[error("failed to load an image")]
|
2021-03-03 21:36:16 +00:00
|
|
|
ImageError(#[from] TextureError),
|
2020-12-02 19:31:16 +00:00
|
|
|
#[error("failed to load an asset path")]
|
2020-10-18 20:48:15 +00:00
|
|
|
AssetIoError(#[from] AssetIoError),
|
2020-05-15 23:55:44 +00:00
|
|
|
}
|
|
|
|
|
2020-10-18 20:48:15 +00:00
|
|
|
/// Loads meshes from GLTF files into Mesh assets
|
|
|
|
#[derive(Default)]
|
|
|
|
pub struct GltfLoader;
|
|
|
|
|
|
|
|
impl AssetLoader for GltfLoader {
|
2020-10-20 00:29:31 +00:00
|
|
|
fn load<'a>(
|
|
|
|
&'a self,
|
|
|
|
bytes: &'a [u8],
|
|
|
|
load_context: &'a mut LoadContext,
|
|
|
|
) -> BoxedFuture<'a, Result<()>> {
|
|
|
|
Box::pin(async move { Ok(load_gltf(bytes, load_context).await?) })
|
2020-10-18 20:48:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn extensions(&self) -> &[&str] {
|
2020-11-17 21:40:18 +00:00
|
|
|
&["gltf", "glb"]
|
2020-05-15 23:55:44 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-20 00:29:31 +00:00
|
|
|
async fn load_gltf<'a, 'b>(
|
|
|
|
bytes: &'a [u8],
|
|
|
|
load_context: &'a mut LoadContext<'b>,
|
|
|
|
) -> Result<(), GltfError> {
|
2020-10-18 20:48:15 +00:00
|
|
|
let gltf = gltf::Gltf::from_slice(bytes)?;
|
2020-10-20 00:29:31 +00:00
|
|
|
let buffer_data = load_buffers(&gltf, load_context, load_context.path()).await?;
|
2020-10-18 20:48:15 +00:00
|
|
|
|
2020-12-31 20:57:15 +00:00
|
|
|
let mut materials = vec![];
|
|
|
|
let mut named_materials = HashMap::new();
|
2021-03-26 18:47:47 +00:00
|
|
|
let mut linear_textures = HashSet::new();
|
2020-12-31 20:57:15 +00:00
|
|
|
for material in gltf.materials() {
|
|
|
|
let handle = load_material(&material, load_context);
|
|
|
|
if let Some(name) = material.name() {
|
|
|
|
named_materials.insert(name.to_string(), handle.clone());
|
|
|
|
}
|
|
|
|
materials.push(handle);
|
2021-03-26 18:47:47 +00:00
|
|
|
if let Some(texture) = material.normal_texture() {
|
|
|
|
linear_textures.insert(texture.texture().index());
|
|
|
|
}
|
|
|
|
if let Some(texture) = material.occlusion_texture() {
|
|
|
|
linear_textures.insert(texture.texture().index());
|
|
|
|
}
|
2021-03-26 21:00:34 +00:00
|
|
|
if let Some(texture) = material
|
|
|
|
.pbr_metallic_roughness()
|
|
|
|
.metallic_roughness_texture()
|
|
|
|
{
|
|
|
|
linear_textures.insert(texture.texture().index());
|
|
|
|
}
|
2020-12-31 20:57:15 +00:00
|
|
|
}
|
2020-10-18 20:48:15 +00:00
|
|
|
|
2020-12-31 20:57:15 +00:00
|
|
|
let mut meshes = vec![];
|
|
|
|
let mut named_meshes = HashMap::new();
|
2020-10-18 20:48:15 +00:00
|
|
|
for mesh in gltf.meshes() {
|
2020-12-31 20:57:15 +00:00
|
|
|
let mut primitives = vec![];
|
2020-10-18 20:48:15 +00:00
|
|
|
for primitive in mesh.primitives() {
|
|
|
|
let primitive_label = primitive_label(&mesh, &primitive);
|
2020-12-31 20:57:15 +00:00
|
|
|
let reader = primitive.reader(|buffer| Some(&buffer_data[buffer.index()]));
|
|
|
|
let primitive_topology = get_primitive_topology(primitive.mode())?;
|
2020-10-18 20:48:15 +00:00
|
|
|
|
2020-12-31 20:57:15 +00:00
|
|
|
let mut mesh = Mesh::new(primitive_topology);
|
2020-10-18 20:48:15 +00:00
|
|
|
|
2020-12-31 20:57:15 +00:00
|
|
|
if let Some(vertex_attribute) = reader
|
|
|
|
.read_positions()
|
|
|
|
.map(|v| VertexAttributeValues::Float3(v.collect()))
|
|
|
|
{
|
|
|
|
mesh.set_attribute(Mesh::ATTRIBUTE_POSITION, vertex_attribute);
|
|
|
|
}
|
2020-10-18 20:48:15 +00:00
|
|
|
|
2020-12-31 20:57:15 +00:00
|
|
|
if let Some(vertex_attribute) = reader
|
|
|
|
.read_normals()
|
|
|
|
.map(|v| VertexAttributeValues::Float3(v.collect()))
|
|
|
|
{
|
|
|
|
mesh.set_attribute(Mesh::ATTRIBUTE_NORMAL, vertex_attribute);
|
|
|
|
}
|
2020-10-18 20:48:15 +00:00
|
|
|
|
2021-03-26 21:00:34 +00:00
|
|
|
if let Some(vertex_attribute) = reader
|
|
|
|
.read_tangents()
|
|
|
|
.map(|v| VertexAttributeValues::Float4(v.collect()))
|
|
|
|
{
|
|
|
|
mesh.set_attribute(Mesh::ATTRIBUTE_TANGENT, vertex_attribute);
|
|
|
|
}
|
|
|
|
|
2020-12-31 20:57:15 +00:00
|
|
|
if let Some(vertex_attribute) = reader
|
|
|
|
.read_tex_coords(0)
|
|
|
|
.map(|v| VertexAttributeValues::Float2(v.into_f32().collect()))
|
|
|
|
{
|
|
|
|
mesh.set_attribute(Mesh::ATTRIBUTE_UV_0, vertex_attribute);
|
|
|
|
}
|
2020-10-18 20:48:15 +00:00
|
|
|
|
2020-12-31 20:57:15 +00:00
|
|
|
if let Some(indices) = reader.read_indices() {
|
|
|
|
mesh.set_indices(Some(Indices::U32(indices.into_u32().collect())));
|
2020-10-18 20:48:15 +00:00
|
|
|
};
|
2020-12-31 20:57:15 +00:00
|
|
|
|
|
|
|
let mesh = load_context.set_labeled_asset(&primitive_label, LoadedAsset::new(mesh));
|
|
|
|
primitives.push(super::GltfPrimitive {
|
|
|
|
mesh,
|
|
|
|
material: primitive
|
|
|
|
.material()
|
|
|
|
.index()
|
|
|
|
.and_then(|i| materials.get(i).cloned()),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
let handle = load_context.set_labeled_asset(
|
|
|
|
&mesh_label(&mesh),
|
|
|
|
LoadedAsset::new(super::GltfMesh { primitives }),
|
|
|
|
);
|
|
|
|
if let Some(name) = mesh.name() {
|
|
|
|
named_meshes.insert(name.to_string(), handle.clone());
|
|
|
|
}
|
|
|
|
meshes.push(handle);
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut nodes_intermediate = vec![];
|
|
|
|
let mut named_nodes_intermediate = HashMap::new();
|
|
|
|
for node in gltf.nodes() {
|
|
|
|
let node_label = node_label(&node);
|
|
|
|
nodes_intermediate.push((
|
|
|
|
node_label,
|
|
|
|
GltfNode {
|
|
|
|
children: vec![],
|
|
|
|
mesh: node
|
|
|
|
.mesh()
|
|
|
|
.map(|mesh| mesh.index())
|
|
|
|
.and_then(|i| meshes.get(i).cloned()),
|
|
|
|
transform: match node.transform() {
|
|
|
|
gltf::scene::Transform::Matrix { matrix } => {
|
|
|
|
Transform::from_matrix(bevy_math::Mat4::from_cols_array_2d(&matrix))
|
|
|
|
}
|
|
|
|
gltf::scene::Transform::Decomposed {
|
|
|
|
translation,
|
|
|
|
rotation,
|
|
|
|
scale,
|
|
|
|
} => Transform {
|
|
|
|
translation: bevy_math::Vec3::from(translation),
|
|
|
|
rotation: bevy_math::Quat::from(rotation),
|
|
|
|
scale: bevy_math::Vec3::from(scale),
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
node.children()
|
|
|
|
.map(|child| child.index())
|
|
|
|
.collect::<Vec<_>>(),
|
|
|
|
));
|
|
|
|
if let Some(name) = node.name() {
|
|
|
|
named_nodes_intermediate.insert(name, node.index());
|
2020-05-15 23:55:44 +00:00
|
|
|
}
|
|
|
|
}
|
2020-12-31 20:57:15 +00:00
|
|
|
let nodes = resolve_node_hierarchy(nodes_intermediate)
|
|
|
|
.into_iter()
|
|
|
|
.map(|(label, node)| load_context.set_labeled_asset(&label, LoadedAsset::new(node)))
|
|
|
|
.collect::<Vec<bevy_asset::Handle<GltfNode>>>();
|
|
|
|
let named_nodes = named_nodes_intermediate
|
|
|
|
.into_iter()
|
|
|
|
.filter_map(|(name, index)| {
|
|
|
|
nodes
|
|
|
|
.get(index)
|
|
|
|
.map(|handle| (name.to_string(), handle.clone()))
|
|
|
|
})
|
|
|
|
.collect();
|
2020-05-15 23:55:44 +00:00
|
|
|
|
2021-03-03 21:36:16 +00:00
|
|
|
for gltf_texture in gltf.textures() {
|
2021-03-26 18:47:47 +00:00
|
|
|
let mut texture = match gltf_texture.source().source() {
|
|
|
|
gltf::image::Source::View { view, mime_type } => {
|
|
|
|
let start = view.offset() as usize;
|
|
|
|
let end = (view.offset() + view.length()) as usize;
|
|
|
|
let buffer = &buffer_data[view.buffer().index()][start..end];
|
|
|
|
Texture::from_buffer(buffer, ImageType::MimeType(mime_type))?
|
|
|
|
}
|
|
|
|
gltf::image::Source::Uri { uri, mime_type } => {
|
|
|
|
let parent = load_context.path().parent().unwrap();
|
|
|
|
let image_path = parent.join(uri);
|
|
|
|
let bytes = load_context.read_asset_bytes(image_path.clone()).await?;
|
|
|
|
Texture::from_buffer(
|
|
|
|
&bytes,
|
|
|
|
mime_type
|
|
|
|
.map(|mt| ImageType::MimeType(mt))
|
|
|
|
.unwrap_or_else(|| {
|
|
|
|
ImageType::Extension(image_path.extension().unwrap().to_str().unwrap())
|
|
|
|
}),
|
|
|
|
)?
|
|
|
|
}
|
|
|
|
};
|
|
|
|
let texture_label = texture_label(&gltf_texture);
|
|
|
|
texture.sampler = texture_sampler(&gltf_texture);
|
|
|
|
if linear_textures.contains(&gltf_texture.index()) {
|
|
|
|
texture.format = TextureFormat::Rgba8Unorm;
|
2020-10-18 20:48:15 +00:00
|
|
|
}
|
2021-03-26 18:47:47 +00:00
|
|
|
load_context.set_labeled_asset::<Texture>(&texture_label, LoadedAsset::new(texture));
|
2020-10-18 20:48:15 +00:00
|
|
|
}
|
2020-08-16 07:30:04 +00:00
|
|
|
|
2020-12-31 20:57:15 +00:00
|
|
|
let mut scenes = vec![];
|
|
|
|
let mut named_scenes = HashMap::new();
|
2020-10-18 20:48:15 +00:00
|
|
|
for scene in gltf.scenes() {
|
|
|
|
let mut err = None;
|
2020-12-31 20:57:15 +00:00
|
|
|
let mut world = World::default();
|
Bevy ECS V2 (#1525)
# Bevy ECS V2
This is a rewrite of Bevy ECS (basically everything but the new executor/schedule, which are already awesome). The overall goal was to improve the performance and versatility of Bevy ECS. Here is a quick bulleted list of changes before we dive into the details:
* Complete World rewrite
* Multiple component storage types:
* Tables: fast cache friendly iteration, slower add/removes (previously called Archetypes)
* Sparse Sets: fast add/remove, slower iteration
* Stateful Queries (caches query results for faster iteration. fragmented iteration is _fast_ now)
* Stateful System Params (caches expensive operations. inspired by @DJMcNab's work in #1364)
* Configurable System Params (users can set configuration when they construct their systems. once again inspired by @DJMcNab's work)
* Archetypes are now "just metadata", component storage is separate
* Archetype Graph (for faster archetype changes)
* Component Metadata
* Configure component storage type
* Retrieve information about component size/type/name/layout/send-ness/etc
* Components are uniquely identified by a densely packed ComponentId
* TypeIds are now totally optional (which should make implementing scripting easier)
* Super fast "for_each" query iterators
* Merged Resources into World. Resources are now just a special type of component
* EntityRef/EntityMut builder apis (more efficient and more ergonomic)
* Fast bitset-backed `Access<T>` replaces old hashmap-based approach everywhere
* Query conflicts are determined by component access instead of archetype component access (to avoid random failures at runtime)
* With/Without are still taken into account for conflicts, so this should still be comfy to use
* Much simpler `IntoSystem` impl
* Significantly reduced the amount of hashing throughout the ecs in favor of Sparse Sets (indexed by densely packed ArchetypeId, ComponentId, BundleId, and TableId)
* Safety Improvements
* Entity reservation uses a normal world reference instead of unsafe transmute
* QuerySets no longer transmute lifetimes
* Made traits "unsafe" where relevant
* More thorough safety docs
* WorldCell
* Exposes safe mutable access to multiple resources at a time in a World
* Replaced "catch all" `System::update_archetypes(world: &World)` with `System::new_archetype(archetype: &Archetype)`
* Simpler Bundle implementation
* Replaced slow "remove_bundle_one_by_one" used as fallback for Commands::remove_bundle with fast "remove_bundle_intersection"
* Removed `Mut<T>` query impl. it is better to only support one way: `&mut T`
* Removed with() from `Flags<T>` in favor of `Option<Flags<T>>`, which allows querying for flags to be "filtered" by default
* Components now have is_send property (currently only resources support non-send)
* More granular module organization
* New `RemovedComponents<T>` SystemParam that replaces `query.removed::<T>()`
* `world.resource_scope()` for mutable access to resources and world at the same time
* WorldQuery and QueryFilter traits unified. FilterFetch trait added to enable "short circuit" filtering. Auto impled for cases that don't need it
* Significantly slimmed down SystemState in favor of individual SystemParam state
* System Commands changed from `commands: &mut Commands` back to `mut commands: Commands` (to allow Commands to have a World reference)
Fixes #1320
## `World` Rewrite
This is a from-scratch rewrite of `World` that fills the niche that `hecs` used to. Yes, this means Bevy ECS is no longer a "fork" of hecs. We're going out our own!
(the only shared code between the projects is the entity id allocator, which is already basically ideal)
A huge shout out to @SanderMertens (author of [flecs](https://github.com/SanderMertens/flecs)) for sharing some great ideas with me (specifically hybrid ecs storage and archetype graphs). He also helped advise on a number of implementation details.
## Component Storage (The Problem)
Two ECS storage paradigms have gained a lot of traction over the years:
* **Archetypal ECS**:
* Stores components in "tables" with static schemas. Each "column" stores components of a given type. Each "row" is an entity.
* Each "archetype" has its own table. Adding/removing an entity's component changes the archetype.
* Enables super-fast Query iteration due to its cache-friendly data layout
* Comes at the cost of more expensive add/remove operations for an Entity's components, because all components need to be copied to the new archetype's "table"
* **Sparse Set ECS**:
* Stores components of the same type in densely packed arrays, which are sparsely indexed by densely packed unsigned integers (Entity ids)
* Query iteration is slower than Archetypal ECS because each entity's component could be at any position in the sparse set. This "random access" pattern isn't cache friendly. Additionally, there is an extra layer of indirection because you must first map the entity id to an index in the component array.
* Adding/removing components is a cheap, constant time operation
Bevy ECS V1, hecs, legion, flec, and Unity DOTS are all "archetypal ecs-es". I personally think "archetypal" storage is a good default for game engines. An entity's archetype doesn't need to change frequently in general, and it creates "fast by default" query iteration (which is a much more common operation). It is also "self optimizing". Users don't need to think about optimizing component layouts for iteration performance. It "just works" without any extra boilerplate.
Shipyard and EnTT are "sparse set ecs-es". They employ "packing" as a way to work around the "suboptimal by default" iteration performance for specific sets of components. This helps, but I didn't think this was a good choice for a general purpose engine like Bevy because:
1. "packs" conflict with each other. If bevy decides to internally pack the Transform and GlobalTransform components, users are then blocked if they want to pack some custom component with Transform.
2. users need to take manual action to optimize
Developers selecting an ECS framework are stuck with a hard choice. Select an "archetypal" framework with "fast iteration everywhere" but without the ability to cheaply add/remove components, or select a "sparse set" framework to cheaply add/remove components but with slower iteration performance.
## Hybrid Component Storage (The Solution)
In Bevy ECS V2, we get to have our cake and eat it too. It now has _both_ of the component storage types above (and more can be added later if needed):
* **Tables** (aka "archetypal" storage)
* The default storage. If you don't configure anything, this is what you get
* Fast iteration by default
* Slower add/remove operations
* **Sparse Sets**
* Opt-in
* Slower iteration
* Faster add/remove operations
These storage types complement each other perfectly. By default Query iteration is fast. If developers know that they want to add/remove a component at high frequencies, they can set the storage to "sparse set":
```rust
world.register_component(
ComponentDescriptor::new::<MyComponent>(StorageType::SparseSet)
).unwrap();
```
## Archetypes
Archetypes are now "just metadata" ... they no longer store components directly. They do store:
* The `ComponentId`s of each of the Archetype's components (and that component's storage type)
* Archetypes are uniquely defined by their component layouts
* For example: entities with "table" components `[A, B, C]` _and_ "sparse set" components `[D, E]` will always be in the same archetype.
* The `TableId` associated with the archetype
* For now each archetype has exactly one table (which can have no components),
* There is a 1->Many relationship from Tables->Archetypes. A given table could have any number of archetype components stored in it:
* Ex: an entity with "table storage" components `[A, B, C]` and "sparse set" components `[D, E]` will share the same `[A, B, C]` table as an entity with `[A, B, C]` table component and `[F]` sparse set components.
* This 1->Many relationship is how we preserve fast "cache friendly" iteration performance when possible (more on this later)
* A list of entities that are in the archetype and the row id of the table they are in
* ArchetypeComponentIds
* unique densely packed identifiers for (ArchetypeId, ComponentId) pairs
* used by the schedule executor for cheap system access control
* "Archetype Graph Edges" (see the next section)
## The "Archetype Graph"
Archetype changes in Bevy (and a number of other archetypal ecs-es) have historically been expensive to compute. First, you need to allocate a new vector of the entity's current component ids, add or remove components based on the operation performed, sort it (to ensure it is order-independent), then hash it to find the archetype (if it exists). And thats all before we get to the _already_ expensive full copy of all components to the new table storage.
The solution is to build a "graph" of archetypes to cache these results. @SanderMertens first exposed me to the idea (and he got it from @gjroelofs, who came up with it). They propose adding directed edges between archetypes for add/remove component operations. If `ComponentId`s are densely packed, you can use sparse sets to cheaply jump between archetypes.
Bevy takes this one step further by using add/remove `Bundle` edges instead of `Component` edges. Bevy encourages the use of `Bundles` to group add/remove operations. This is largely for "clearer game logic" reasons, but it also helps cut down on the number of archetype changes required. `Bundles` now also have densely-packed `BundleId`s. This allows us to use a _single_ edge for each bundle operation (rather than needing to traverse N edges ... one for each component). Single component operations are also bundles, so this is strictly an improvement over a "component only" graph.
As a result, an operation that used to be _heavy_ (both for allocations and compute) is now two dirt-cheap array lookups and zero allocations.
## Stateful Queries
World queries are now stateful. This allows us to:
1. Cache archetype (and table) matches
* This resolves another issue with (naive) archetypal ECS: query performance getting worse as the number of archetypes goes up (and fragmentation occurs).
2. Cache Fetch and Filter state
* The expensive parts of fetch/filter operations (such as hashing the TypeId to find the ComponentId) now only happen once when the Query is first constructed
3. Incrementally build up state
* When new archetypes are added, we only process the new archetypes (no need to rebuild state for old archetypes)
As a result, the direct `World` query api now looks like this:
```rust
let mut query = world.query::<(&A, &mut B)>();
for (a, mut b) in query.iter_mut(&mut world) {
}
```
Requiring `World` to generate stateful queries (rather than letting the `QueryState` type be constructed separately) allows us to ensure that _all_ queries are properly initialized (and the relevant world state, such as ComponentIds). This enables QueryState to remove branches from its operations that check for initialization status (and also enables query.iter() to take an immutable world reference because it doesn't need to initialize anything in world).
However in systems, this is a non-breaking change. State management is done internally by the relevant SystemParam.
## Stateful SystemParams
Like Queries, `SystemParams` now also cache state. For example, `Query` system params store the "stateful query" state mentioned above. Commands store their internal `CommandQueue`. This means you can now safely use as many separate `Commands` parameters in your system as you want. `Local<T>` system params store their `T` value in their state (instead of in Resources).
SystemParam state also enabled a significant slim-down of SystemState. It is much nicer to look at now.
Per-SystemParam state naturally insulates us from an "aliased mut" class of errors we have hit in the past (ex: using multiple `Commands` system params).
(credit goes to @DJMcNab for the initial idea and draft pr here #1364)
## Configurable SystemParams
@DJMcNab also had the great idea to make SystemParams configurable. This allows users to provide some initial configuration / values for system parameters (when possible). Most SystemParams have no config (the config type is `()`), but the `Local<T>` param now supports user-provided parameters:
```rust
fn foo(value: Local<usize>) {
}
app.add_system(foo.system().config(|c| c.0 = Some(10)));
```
## Uber Fast "for_each" Query Iterators
Developers now have the choice to use a fast "for_each" iterator, which yields ~1.5-3x iteration speed improvements for "fragmented iteration", and minor ~1.2x iteration speed improvements for unfragmented iteration.
```rust
fn system(query: Query<(&A, &mut B)>) {
// you now have the option to do this for a speed boost
query.for_each_mut(|(a, mut b)| {
});
// however normal iterators are still available
for (a, mut b) in query.iter_mut() {
}
}
```
I think in most cases we should continue to encourage "normal" iterators as they are more flexible and more "rust idiomatic". But when that extra "oomf" is needed, it makes sense to use `for_each`.
We should also consider using `for_each` for internal bevy systems to give our users a nice speed boost (but that should be a separate pr).
## Component Metadata
`World` now has a `Components` collection, which is accessible via `world.components()`. This stores mappings from `ComponentId` to `ComponentInfo`, as well as `TypeId` to `ComponentId` mappings (where relevant). `ComponentInfo` stores information about the component, such as ComponentId, TypeId, memory layout, send-ness (currently limited to resources), and storage type.
## Significantly Cheaper `Access<T>`
We used to use `TypeAccess<TypeId>` to manage read/write component/archetype-component access. This was expensive because TypeIds must be hashed and compared individually. The parallel executor got around this by "condensing" type ids into bitset-backed access types. This worked, but it had to be re-generated from the `TypeAccess<TypeId>`sources every time archetypes changed.
This pr removes TypeAccess in favor of faster bitset access everywhere. We can do this thanks to the move to densely packed `ComponentId`s and `ArchetypeComponentId`s.
## Merged Resources into World
Resources had a lot of redundant functionality with Components. They stored typed data, they had access control, they had unique ids, they were queryable via SystemParams, etc. In fact the _only_ major difference between them was that they were unique (and didn't correlate to an entity).
Separate resources also had the downside of requiring a separate set of access controls, which meant the parallel executor needed to compare more bitsets per system and manage more state.
I initially got the "separate resources" idea from `legion`. I think that design was motivated by the fact that it made the direct world query/resource lifetime interactions more manageable. It certainly made our lives easier when using Resources alongside hecs/bevy_ecs. However we already have a construct for safely and ergonomically managing in-world lifetimes: systems (which use `Access<T>` internally).
This pr merges Resources into World:
```rust
world.insert_resource(1);
world.insert_resource(2.0);
let a = world.get_resource::<i32>().unwrap();
let mut b = world.get_resource_mut::<f64>().unwrap();
*b = 3.0;
```
Resources are now just a special kind of component. They have their own ComponentIds (and their own resource TypeId->ComponentId scope, so they don't conflict wit components of the same type). They are stored in a special "resource archetype", which stores components inside the archetype using a new `unique_components` sparse set (note that this sparse set could later be used to implement Tags). This allows us to keep the code size small by reusing existing datastructures (namely Column, Archetype, ComponentFlags, and ComponentInfo). This allows us the executor to use a single `Access<ArchetypeComponentId>` per system. It should also make scripting language integration easier.
_But_ this merge did create problems for people directly interacting with `World`. What if you need mutable access to multiple resources at the same time? `world.get_resource_mut()` borrows World mutably!
## WorldCell
WorldCell applies the `Access<ArchetypeComponentId>` concept to direct world access:
```rust
let world_cell = world.cell();
let a = world_cell.get_resource_mut::<i32>().unwrap();
let b = world_cell.get_resource_mut::<f64>().unwrap();
```
This adds cheap runtime checks (a sparse set lookup of `ArchetypeComponentId` and a counter) to ensure that world accesses do not conflict with each other. Each operation returns a `WorldBorrow<'w, T>` or `WorldBorrowMut<'w, T>` wrapper type, which will release the relevant ArchetypeComponentId resources when dropped.
World caches the access sparse set (and only one cell can exist at a time), so `world.cell()` is a cheap operation.
WorldCell does _not_ use atomic operations. It is non-send, does a mutable borrow of world to prevent other accesses, and uses a simple `Rc<RefCell<ArchetypeComponentAccess>>` wrapper in each WorldBorrow pointer.
The api is currently limited to resource access, but it can and should be extended to queries / entity component access.
## Resource Scopes
WorldCell does not yet support component queries, and even when it does there are sometimes legitimate reasons to want a mutable world ref _and_ a mutable resource ref (ex: bevy_render and bevy_scene both need this). In these cases we could always drop down to the unsafe `world.get_resource_unchecked_mut()`, but that is not ideal!
Instead developers can use a "resource scope"
```rust
world.resource_scope(|world: &mut World, a: &mut A| {
})
```
This temporarily removes the `A` resource from `World`, provides mutable pointers to both, and re-adds A to World when finished. Thanks to the move to ComponentIds/sparse sets, this is a cheap operation.
If multiple resources are required, scopes can be nested. We could also consider adding a "resource tuple" to the api if this pattern becomes common and the boilerplate gets nasty.
## Query Conflicts Use ComponentId Instead of ArchetypeComponentId
For safety reasons, systems cannot contain queries that conflict with each other without wrapping them in a QuerySet. On bevy `main`, we use ArchetypeComponentIds to determine conflicts. This is nice because it can take into account filters:
```rust
// these queries will never conflict due to their filters
fn filter_system(a: Query<&mut A, With<B>>, b: Query<&mut B, Without<B>>) {
}
```
But it also has a significant downside:
```rust
// these queries will not conflict _until_ an entity with A, B, and C is spawned
fn maybe_conflicts_system(a: Query<(&mut A, &C)>, b: Query<(&mut A, &B)>) {
}
```
The system above will panic at runtime if an entity with A, B, and C is spawned. This makes it hard to trust that your game logic will run without crashing.
In this pr, I switched to using `ComponentId` instead. This _is_ more constraining. `maybe_conflicts_system` will now always fail, but it will do it consistently at startup. Naively, it would also _disallow_ `filter_system`, which would be a significant downgrade in usability. Bevy has a number of internal systems that rely on disjoint queries and I expect it to be a common pattern in userspace.
To resolve this, I added a new `FilteredAccess<T>` type, which wraps `Access<T>` and adds with/without filters. If two `FilteredAccess` have with/without values that prove they are disjoint, they will no longer conflict.
## EntityRef / EntityMut
World entity operations on `main` require that the user passes in an `entity` id to each operation:
```rust
let entity = world.spawn((A, )); // create a new entity with A
world.get::<A>(entity);
world.insert(entity, (B, C));
world.insert_one(entity, D);
```
This means that each operation needs to look up the entity location / verify its validity. The initial spawn operation also requires a Bundle as input. This can be awkward when no components are required (or one component is required).
These operations have been replaced by `EntityRef` and `EntityMut`, which are "builder-style" wrappers around world that provide read and read/write operations on a single, pre-validated entity:
```rust
// spawn now takes no inputs and returns an EntityMut
let entity = world.spawn()
.insert(A) // insert a single component into the entity
.insert_bundle((B, C)) // insert a bundle of components into the entity
.id() // id returns the Entity id
// Returns EntityMut (or panics if the entity does not exist)
world.entity_mut(entity)
.insert(D)
.insert_bundle(SomeBundle::default());
{
// returns EntityRef (or panics if the entity does not exist)
let d = world.entity(entity)
.get::<D>() // gets the D component
.unwrap();
// world.get still exists for ergonomics
let d = world.get::<D>(entity).unwrap();
}
// These variants return Options if you want to check existence instead of panicing
world.get_entity_mut(entity)
.unwrap()
.insert(E);
if let Some(entity_ref) = world.get_entity(entity) {
let d = entity_ref.get::<D>().unwrap();
}
```
This _does not_ affect the current Commands api or terminology. I think that should be a separate conversation as that is a much larger breaking change.
## Safety Improvements
* Entity reservation in Commands uses a normal world borrow instead of an unsafe transmute
* QuerySets no longer transmutes lifetimes
* Made traits "unsafe" when implementing a trait incorrectly could cause unsafety
* More thorough safety docs
## RemovedComponents SystemParam
The old approach to querying removed components: `query.removed:<T>()` was confusing because it had no connection to the query itself. I replaced it with the following, which is both clearer and allows us to cache the ComponentId mapping in the SystemParamState:
```rust
fn system(removed: RemovedComponents<T>) {
for entity in removed.iter() {
}
}
```
## Simpler Bundle implementation
Bundles are no longer responsible for sorting (or deduping) TypeInfo. They are just a simple ordered list of component types / data. This makes the implementation smaller and opens the door to an easy "nested bundle" implementation in the future (which i might even add in this pr). Duplicate detection is now done once per bundle type by World the first time a bundle is used.
## Unified WorldQuery and QueryFilter types
(don't worry they are still separate type _parameters_ in Queries .. this is a non-breaking change)
WorldQuery and QueryFilter were already basically identical apis. With the addition of `FetchState` and more storage-specific fetch methods, the overlap was even clearer (and the redundancy more painful).
QueryFilters are now just `F: WorldQuery where F::Fetch: FilterFetch`. FilterFetch requires `Fetch<Item = bool>` and adds new "short circuit" variants of fetch methods. This enables a filter tuple like `(With<A>, Without<B>, Changed<C>)` to stop evaluating the filter after the first mismatch is encountered. FilterFetch is automatically implemented for `Fetch` implementations that return bool.
This forces fetch implementations that return things like `(bool, bool, bool)` (such as the filter above) to manually implement FilterFetch and decide whether or not to short-circuit.
## More Granular Modules
World no longer globs all of the internal modules together. It now exports `core`, `system`, and `schedule` separately. I'm also considering exporting `core` submodules directly as that is still pretty "glob-ey" and unorganized (feedback welcome here).
## Remaining Draft Work (to be done in this pr)
* ~~panic on conflicting WorldQuery fetches (&A, &mut A)~~
* ~~bevy `main` and hecs both currently allow this, but we should protect against it if possible~~
* ~~batch_iter / par_iter (currently stubbed out)~~
* ~~ChangedRes~~
* ~~I skipped this while we sort out #1313. This pr should be adapted to account for whatever we land on there~~.
* ~~The `Archetypes` and `Tables` collections use hashes of sorted lists of component ids to uniquely identify each archetype/table. This hash is then used as the key in a HashMap to look up the relevant ArchetypeId or TableId. (which doesn't handle hash collisions properly)~~
* ~~It is currently unsafe to generate a Query from "World A", then use it on "World B" (despite the api claiming it is safe). We should probably close this gap. This could be done by adding a randomly generated WorldId to each world, then storing that id in each Query. They could then be compared to each other on each `query.do_thing(&world)` operation. This _does_ add an extra branch to each query operation, so I'm open to other suggestions if people have them.~~
* ~~Nested Bundles (if i find time)~~
## Potential Future Work
* Expand WorldCell to support queries.
* Consider not allocating in the empty archetype on `world.spawn()`
* ex: return something like EntityMutUninit, which turns into EntityMut after an `insert` or `insert_bundle` op
* this actually regressed performance last time i tried it, but in theory it should be faster
* Optimize SparseSet::insert (see `PERF` comment on insert)
* Replace SparseArray `Option<T>` with T::MAX to cut down on branching
* would enable cheaper get_unchecked() operations
* upstream fixedbitset optimizations
* fixedbitset could be allocation free for small block counts (store blocks in a SmallVec)
* fixedbitset could have a const constructor
* Consider implementing Tags (archetype-specific by-value data that affects archetype identity)
* ex: ArchetypeA could have `[A, B, C]` table components and `[D(1)]` "tag" component. ArchetypeB could have `[A, B, C]` table components and a `[D(2)]` tag component. The archetypes are different, despite both having D tags because the value inside D is different.
* this could potentially build on top of the `archetype.unique_components` added in this pr for resource storage.
* Consider reverting `all_tuples` proc macro in favor of the old `macro_rules` implementation
* all_tuples is more flexible and produces cleaner documentation (the macro_rules version produces weird type parameter orders due to parser constraints)
* but unfortunately all_tuples also appears to make Rust Analyzer sad/slow when working inside of `bevy_ecs` (does not affect user code)
* Consider "resource queries" and/or "mixed resource and entity component queries" as an alternative to WorldCell
* this is basically just "systems" so maybe it's not worth it
* Add more world ops
* `world.clear()`
* `world.reserve<T: Bundle>(count: usize)`
* Try using the old archetype allocation strategy (allocate new memory on resize and copy everything over). I expect this to improve batch insertion performance at the cost of unbatched performance. But thats just a guess. I'm not an allocation perf pro :)
* Adapt Commands apis for consistency with new World apis
## Benchmarks
key:
* `bevy_old`: bevy `main` branch
* `bevy`: this branch
* `_foreach`: uses an optimized for_each iterator
* ` _sparse`: uses sparse set storage (if unspecified assume table storage)
* `_system`: runs inside a system (if unspecified assume test happens via direct world ops)
### Simple Insert (from ecs_bench_suite)
![image](https://user-images.githubusercontent.com/2694663/109245573-9c3ce100-7795-11eb-9003-bfd41cd5c51f.png)
### Simpler Iter (from ecs_bench_suite)
![image](https://user-images.githubusercontent.com/2694663/109245795-ffc70e80-7795-11eb-92fb-3ffad09aabf7.png)
### Fragment Iter (from ecs_bench_suite)
![image](https://user-images.githubusercontent.com/2694663/109245849-0fdeee00-7796-11eb-8d25-eb6b7a682c48.png)
### Sparse Fragmented Iter
Iterate a query that matches 5 entities from a single matching archetype, but there are 100 unmatching archetypes
![image](https://user-images.githubusercontent.com/2694663/109245916-2b49f900-7796-11eb-9a8f-ed89c203f940.png)
### Schedule (from ecs_bench_suite)
![image](https://user-images.githubusercontent.com/2694663/109246428-1fab0200-7797-11eb-8841-1b2161e90fa4.png)
### Add Remove Component (from ecs_bench_suite)
![image](https://user-images.githubusercontent.com/2694663/109246492-39e4e000-7797-11eb-8985-2706bd0495ab.png)
### Add Remove Component Big
Same as the test above, but each entity has 5 "large" matrix components and 1 "large" matrix component is added and removed
![image](https://user-images.githubusercontent.com/2694663/109246517-449f7500-7797-11eb-835e-28b6790daeaa.png)
### Get Component
Looks up a single component value a large number of times
![image](https://user-images.githubusercontent.com/2694663/109246129-87ad1880-7796-11eb-9fcb-c38012aa7c70.png)
2021-03-05 07:54:35 +00:00
|
|
|
world
|
|
|
|
.spawn()
|
2021-03-13 18:23:39 +00:00
|
|
|
.insert_bundle((Transform::identity(), GlobalTransform::identity()))
|
2020-10-18 20:48:15 +00:00
|
|
|
.with_children(|parent| {
|
|
|
|
for node in scene.nodes() {
|
|
|
|
let result = load_node(&node, parent, load_context, &buffer_data);
|
|
|
|
if result.is_err() {
|
|
|
|
err = Some(result);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
if let Some(Err(err)) = err {
|
|
|
|
return Err(err);
|
|
|
|
}
|
2020-12-31 20:57:15 +00:00
|
|
|
let scene_handle = load_context
|
|
|
|
.set_labeled_asset(&scene_label(&scene), LoadedAsset::new(Scene::new(world)));
|
|
|
|
|
|
|
|
if let Some(name) = scene.name() {
|
|
|
|
named_scenes.insert(name.to_string(), scene_handle.clone());
|
|
|
|
}
|
|
|
|
scenes.push(scene_handle);
|
2020-10-18 20:48:15 +00:00
|
|
|
}
|
|
|
|
|
2020-12-31 20:57:15 +00:00
|
|
|
load_context.set_default_asset(LoadedAsset::new(Gltf {
|
|
|
|
default_scene: gltf
|
|
|
|
.default_scene()
|
|
|
|
.and_then(|scene| scenes.get(scene.index()))
|
|
|
|
.cloned(),
|
|
|
|
scenes,
|
|
|
|
named_scenes,
|
|
|
|
meshes,
|
|
|
|
named_meshes,
|
|
|
|
materials,
|
|
|
|
named_materials,
|
|
|
|
nodes,
|
|
|
|
named_nodes,
|
|
|
|
}));
|
2020-10-18 20:48:15 +00:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
2020-08-16 07:30:04 +00:00
|
|
|
|
2020-12-31 20:57:15 +00:00
|
|
|
fn load_material(material: &Material, load_context: &mut LoadContext) -> Handle<StandardMaterial> {
|
2020-12-09 03:36:41 +00:00
|
|
|
let material_label = material_label(&material);
|
2021-03-26 21:00:34 +00:00
|
|
|
|
2020-12-09 03:36:41 +00:00
|
|
|
let pbr = material.pbr_metallic_roughness();
|
2021-03-26 21:00:34 +00:00
|
|
|
|
|
|
|
let color = pbr.base_color_factor();
|
|
|
|
let base_color_texture = if let Some(info) = pbr.base_color_texture() {
|
|
|
|
// TODO: handle info.tex_coord() (the *set* index for the right texcoords)
|
|
|
|
let label = texture_label(&info.texture());
|
|
|
|
let path = AssetPath::new_ref(load_context.path(), Some(&label));
|
|
|
|
Some(load_context.get_handle(path))
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
|
|
|
|
let normal_map = if let Some(normal_texture) = material.normal_texture() {
|
|
|
|
// TODO: handle normal_texture.scale
|
|
|
|
// TODO: handle normal_texture.tex_coord() (the *set* index for the right texcoords)
|
|
|
|
let label = texture_label(&normal_texture.texture());
|
|
|
|
let path = AssetPath::new_ref(load_context.path(), Some(&label));
|
|
|
|
Some(load_context.get_handle(path))
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
|
|
|
|
let metallic_roughness_texture = if let Some(info) = pbr.metallic_roughness_texture() {
|
|
|
|
// TODO: handle info.tex_coord() (the *set* index for the right texcoords)
|
|
|
|
let label = texture_label(&info.texture());
|
|
|
|
let path = AssetPath::new_ref(load_context.path(), Some(&label));
|
|
|
|
Some(load_context.get_handle(path))
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
|
|
|
|
let occlusion_texture = if let Some(occlusion_texture) = material.occlusion_texture() {
|
|
|
|
// TODO: handle occlusion_texture.tex_coord() (the *set* index for the right texcoords)
|
|
|
|
// TODO: handle occlusion_texture.strength() (a scalar multiplier for occlusion strength)
|
|
|
|
let label = texture_label(&occlusion_texture.texture());
|
|
|
|
let path = AssetPath::new_ref(load_context.path(), Some(&label));
|
|
|
|
Some(load_context.get_handle(path))
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
|
|
|
|
let emissive = material.emissive_factor();
|
|
|
|
let emissive_texture = if let Some(info) = material.emissive_texture() {
|
|
|
|
// TODO: handle occlusion_texture.tex_coord() (the *set* index for the right texcoords)
|
|
|
|
// TODO: handle occlusion_texture.strength() (a scalar multiplier for occlusion strength)
|
2021-03-26 18:47:47 +00:00
|
|
|
let label = texture_label(&info.texture());
|
|
|
|
let path = AssetPath::new_ref(load_context.path(), Some(&label));
|
|
|
|
Some(load_context.get_handle(path))
|
2020-12-09 03:36:41 +00:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
|
|
|
|
load_context.set_labeled_asset(
|
|
|
|
&material_label,
|
|
|
|
LoadedAsset::new(StandardMaterial {
|
2021-03-20 03:22:33 +00:00
|
|
|
base_color: Color::rgba(color[0], color[1], color[2], color[3]),
|
2021-03-26 21:00:34 +00:00
|
|
|
base_color_texture,
|
2021-03-20 03:22:33 +00:00
|
|
|
roughness: pbr.roughness_factor(),
|
|
|
|
metallic: pbr.metallic_factor(),
|
2021-03-26 21:00:34 +00:00
|
|
|
metallic_roughness_texture,
|
|
|
|
normal_map,
|
|
|
|
double_sided: material.double_sided(),
|
|
|
|
occlusion_texture,
|
|
|
|
emissive: Color::rgba(emissive[0], emissive[1], emissive[2], 1.0),
|
|
|
|
emissive_texture,
|
2021-02-01 01:13:16 +00:00
|
|
|
unlit: material.unlit(),
|
2021-03-20 03:22:33 +00:00
|
|
|
..Default::default()
|
2021-03-26 18:47:47 +00:00
|
|
|
}),
|
2020-12-09 03:36:41 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2020-10-18 20:48:15 +00:00
|
|
|
fn load_node(
|
2020-11-07 01:08:15 +00:00
|
|
|
gltf_node: &gltf::Node,
|
2020-10-18 20:48:15 +00:00
|
|
|
world_builder: &mut WorldChildBuilder,
|
|
|
|
load_context: &mut LoadContext,
|
|
|
|
buffer_data: &[Vec<u8>],
|
|
|
|
) -> Result<(), GltfError> {
|
2020-11-07 01:08:15 +00:00
|
|
|
let transform = gltf_node.transform();
|
2020-10-18 20:48:15 +00:00
|
|
|
let mut gltf_error = None;
|
2021-03-23 00:23:40 +00:00
|
|
|
let mut node = world_builder.spawn_bundle((
|
2020-11-07 01:08:15 +00:00
|
|
|
Transform::from_matrix(Mat4::from_cols_array_2d(&transform.matrix())),
|
2021-03-13 18:23:39 +00:00
|
|
|
GlobalTransform::identity(),
|
2020-11-07 01:08:15 +00:00
|
|
|
));
|
|
|
|
|
2020-12-31 20:57:15 +00:00
|
|
|
if let Some(name) = gltf_node.name() {
|
2021-03-23 00:23:40 +00:00
|
|
|
node.insert(Name::new(name.to_string()));
|
2020-12-31 20:57:15 +00:00
|
|
|
}
|
|
|
|
|
2020-11-07 01:08:15 +00:00
|
|
|
// create camera node
|
|
|
|
if let Some(camera) = gltf_node.camera() {
|
2021-03-23 00:23:40 +00:00
|
|
|
node.insert(VisibleEntities {
|
2020-11-07 01:08:15 +00:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
match camera.projection() {
|
|
|
|
gltf::camera::Projection::Orthographic(orthographic) => {
|
|
|
|
let xmag = orthographic.xmag();
|
|
|
|
let ymag = orthographic.ymag();
|
2020-11-09 22:12:42 +00:00
|
|
|
let orthographic_projection: OrthographicProjection = OrthographicProjection {
|
|
|
|
left: -xmag,
|
|
|
|
right: xmag,
|
|
|
|
top: ymag,
|
|
|
|
bottom: -ymag,
|
|
|
|
far: orthographic.zfar(),
|
|
|
|
near: orthographic.znear(),
|
|
|
|
..Default::default()
|
|
|
|
};
|
|
|
|
|
2021-03-23 00:23:40 +00:00
|
|
|
node.insert(Camera {
|
2020-12-03 21:46:15 +00:00
|
|
|
name: Some(base::camera::CAMERA_2D.to_owned()),
|
2020-11-07 01:08:15 +00:00
|
|
|
projection_matrix: orthographic_projection.get_projection_matrix(),
|
|
|
|
..Default::default()
|
|
|
|
});
|
2021-03-23 00:23:40 +00:00
|
|
|
node.insert(orthographic_projection);
|
2020-11-07 01:08:15 +00:00
|
|
|
}
|
|
|
|
gltf::camera::Projection::Perspective(perspective) => {
|
2020-11-09 22:12:42 +00:00
|
|
|
let mut perspective_projection: PerspectiveProjection = PerspectiveProjection {
|
|
|
|
fov: perspective.yfov(),
|
|
|
|
near: perspective.znear(),
|
|
|
|
..Default::default()
|
|
|
|
};
|
2020-11-07 01:08:15 +00:00
|
|
|
if let Some(zfar) = perspective.zfar() {
|
|
|
|
perspective_projection.far = zfar;
|
|
|
|
}
|
|
|
|
if let Some(aspect_ratio) = perspective.aspect_ratio() {
|
|
|
|
perspective_projection.aspect_ratio = aspect_ratio;
|
2020-10-18 20:48:15 +00:00
|
|
|
}
|
2021-03-23 00:23:40 +00:00
|
|
|
node.insert(Camera {
|
2020-12-03 21:46:15 +00:00
|
|
|
name: Some(base::camera::CAMERA_3D.to_owned()),
|
2020-11-07 01:08:15 +00:00
|
|
|
projection_matrix: perspective_projection.get_projection_matrix(),
|
|
|
|
..Default::default()
|
|
|
|
});
|
2021-03-23 00:23:40 +00:00
|
|
|
node.insert(perspective_projection);
|
2020-08-16 07:30:04 +00:00
|
|
|
}
|
2020-11-07 01:08:15 +00:00
|
|
|
}
|
|
|
|
}
|
2020-08-16 07:30:04 +00:00
|
|
|
|
2020-11-07 01:08:15 +00:00
|
|
|
node.with_children(|parent| {
|
|
|
|
if let Some(mesh) = gltf_node.mesh() {
|
|
|
|
// append primitives
|
|
|
|
for primitive in mesh.primitives() {
|
2020-12-09 03:36:41 +00:00
|
|
|
let material = primitive.material();
|
|
|
|
let material_label = material_label(&material);
|
|
|
|
|
|
|
|
// This will make sure we load the default material now since it would not have been
|
|
|
|
// added when iterating over all the gltf materials (since the default material is
|
|
|
|
// not explicitly listed in the gltf).
|
|
|
|
if !load_context.has_labeled_asset(&material_label) {
|
|
|
|
load_material(&material, load_context);
|
|
|
|
}
|
|
|
|
|
2020-11-07 01:08:15 +00:00
|
|
|
let primitive_label = primitive_label(&mesh, &primitive);
|
|
|
|
let mesh_asset_path =
|
|
|
|
AssetPath::new_ref(load_context.path(), Some(&primitive_label));
|
|
|
|
let material_asset_path =
|
|
|
|
AssetPath::new_ref(load_context.path(), Some(&material_label));
|
2020-12-09 03:36:41 +00:00
|
|
|
|
2021-03-23 00:23:40 +00:00
|
|
|
parent.spawn_bundle(PbrBundle {
|
2020-11-07 01:08:15 +00:00
|
|
|
mesh: load_context.get_handle(mesh_asset_path),
|
|
|
|
material: load_context.get_handle(material_asset_path),
|
|
|
|
..Default::default()
|
|
|
|
});
|
2020-09-25 21:29:30 +00:00
|
|
|
}
|
2020-11-07 01:08:15 +00:00
|
|
|
}
|
2020-05-15 23:55:44 +00:00
|
|
|
|
2020-11-07 01:08:15 +00:00
|
|
|
// append other nodes
|
|
|
|
for child in gltf_node.children() {
|
|
|
|
if let Err(err) = load_node(&child, parent, load_context, buffer_data) {
|
|
|
|
gltf_error = Some(err);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
2020-10-18 20:48:15 +00:00
|
|
|
if let Some(err) = gltf_error {
|
|
|
|
Err(err)
|
|
|
|
} else {
|
|
|
|
Ok(())
|
2020-05-15 23:55:44 +00:00
|
|
|
}
|
2020-10-18 20:48:15 +00:00
|
|
|
}
|
2020-05-15 23:55:44 +00:00
|
|
|
|
2020-12-31 20:57:15 +00:00
|
|
|
fn mesh_label(mesh: &gltf::Mesh) -> String {
|
|
|
|
format!("Mesh{}", mesh.index())
|
|
|
|
}
|
|
|
|
|
2020-10-18 20:48:15 +00:00
|
|
|
fn primitive_label(mesh: &gltf::Mesh, primitive: &Primitive) -> String {
|
|
|
|
format!("Mesh{}/Primitive{}", mesh.index(), primitive.index())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn material_label(material: &gltf::Material) -> String {
|
|
|
|
if let Some(index) = material.index() {
|
|
|
|
format!("Material{}", index)
|
|
|
|
} else {
|
|
|
|
"MaterialDefault".to_string()
|
2020-05-15 23:55:44 +00:00
|
|
|
}
|
2020-10-18 20:48:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn texture_label(texture: &gltf::Texture) -> String {
|
|
|
|
format!("Texture{}", texture.index())
|
|
|
|
}
|
2020-05-15 23:55:44 +00:00
|
|
|
|
2020-12-31 20:57:15 +00:00
|
|
|
fn node_label(node: &gltf::Node) -> String {
|
|
|
|
format!("Node{}", node.index())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn scene_label(scene: &gltf::Scene) -> String {
|
|
|
|
format!("Scene{}", scene.index())
|
|
|
|
}
|
|
|
|
|
2021-03-13 18:44:26 +00:00
|
|
|
fn texture_sampler(texture: &gltf::Texture) -> SamplerDescriptor {
|
2020-10-29 21:22:45 +00:00
|
|
|
let gltf_sampler = texture.sampler();
|
|
|
|
|
2021-03-13 18:44:26 +00:00
|
|
|
SamplerDescriptor {
|
2020-10-29 21:22:45 +00:00
|
|
|
address_mode_u: texture_address_mode(&gltf_sampler.wrap_s()),
|
|
|
|
address_mode_v: texture_address_mode(&gltf_sampler.wrap_t()),
|
|
|
|
|
|
|
|
mag_filter: gltf_sampler
|
|
|
|
.mag_filter()
|
|
|
|
.map(|mf| match mf {
|
|
|
|
MagFilter::Nearest => FilterMode::Nearest,
|
|
|
|
MagFilter::Linear => FilterMode::Linear,
|
|
|
|
})
|
|
|
|
.unwrap_or(SamplerDescriptor::default().mag_filter),
|
|
|
|
|
|
|
|
min_filter: gltf_sampler
|
|
|
|
.min_filter()
|
|
|
|
.map(|mf| match mf {
|
2021-03-13 18:44:26 +00:00
|
|
|
MinFilter::Nearest
|
|
|
|
| MinFilter::NearestMipmapNearest
|
|
|
|
| MinFilter::NearestMipmapLinear => FilterMode::Nearest,
|
|
|
|
MinFilter::Linear
|
|
|
|
| MinFilter::LinearMipmapNearest
|
|
|
|
| MinFilter::LinearMipmapLinear => FilterMode::Linear,
|
2020-10-29 21:22:45 +00:00
|
|
|
})
|
|
|
|
.unwrap_or(SamplerDescriptor::default().min_filter),
|
|
|
|
|
2021-03-13 18:44:26 +00:00
|
|
|
mipmap_filter: gltf_sampler
|
|
|
|
.min_filter()
|
|
|
|
.map(|mf| match mf {
|
|
|
|
MinFilter::Nearest
|
|
|
|
| MinFilter::Linear
|
|
|
|
| MinFilter::NearestMipmapNearest
|
|
|
|
| MinFilter::LinearMipmapNearest => FilterMode::Nearest,
|
|
|
|
MinFilter::NearestMipmapLinear | MinFilter::LinearMipmapLinear => {
|
|
|
|
FilterMode::Linear
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.unwrap_or(SamplerDescriptor::default().mipmap_filter),
|
|
|
|
|
2020-10-29 21:22:45 +00:00
|
|
|
..Default::default()
|
2021-03-13 18:44:26 +00:00
|
|
|
}
|
2020-10-29 21:22:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn texture_address_mode(gltf_address_mode: &gltf::texture::WrappingMode) -> AddressMode {
|
|
|
|
match gltf_address_mode {
|
|
|
|
WrappingMode::ClampToEdge => AddressMode::ClampToEdge,
|
|
|
|
WrappingMode::Repeat => AddressMode::Repeat,
|
|
|
|
WrappingMode::MirroredRepeat => AddressMode::MirrorRepeat,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-18 20:48:15 +00:00
|
|
|
fn get_primitive_topology(mode: Mode) -> Result<PrimitiveTopology, GltfError> {
|
|
|
|
match mode {
|
|
|
|
Mode::Points => Ok(PrimitiveTopology::PointList),
|
|
|
|
Mode::Lines => Ok(PrimitiveTopology::LineList),
|
|
|
|
Mode::LineStrip => Ok(PrimitiveTopology::LineStrip),
|
|
|
|
Mode::Triangles => Ok(PrimitiveTopology::TriangleList),
|
|
|
|
Mode::TriangleStrip => Ok(PrimitiveTopology::TriangleStrip),
|
|
|
|
mode => Err(GltfError::UnsupportedPrimitive { mode }),
|
|
|
|
}
|
2020-05-15 23:55:44 +00:00
|
|
|
}
|
|
|
|
|
2020-10-20 00:29:31 +00:00
|
|
|
async fn load_buffers(
|
2020-10-18 20:48:15 +00:00
|
|
|
gltf: &gltf::Gltf,
|
2020-10-20 00:29:31 +00:00
|
|
|
load_context: &LoadContext<'_>,
|
2020-10-18 20:48:15 +00:00
|
|
|
asset_path: &Path,
|
|
|
|
) -> Result<Vec<Vec<u8>>, GltfError> {
|
2020-08-12 17:23:54 +00:00
|
|
|
const OCTET_STREAM_URI: &str = "data:application/octet-stream;base64,";
|
|
|
|
|
2020-05-15 23:55:44 +00:00
|
|
|
let mut buffer_data = Vec::new();
|
2020-08-25 23:55:08 +00:00
|
|
|
for buffer in gltf.buffers() {
|
2020-05-15 23:55:44 +00:00
|
|
|
match buffer.source() {
|
2020-10-18 20:48:15 +00:00
|
|
|
gltf::buffer::Source::Uri(uri) => {
|
2020-05-15 23:55:44 +00:00
|
|
|
if uri.starts_with("data:") {
|
2021-03-12 03:05:14 +00:00
|
|
|
buffer_data.push(base64::decode(
|
|
|
|
uri.strip_prefix(OCTET_STREAM_URI)
|
|
|
|
.ok_or(GltfError::BufferFormatUnsupported)?,
|
|
|
|
)?);
|
2020-05-15 23:55:44 +00:00
|
|
|
} else {
|
2020-10-18 20:48:15 +00:00
|
|
|
// TODO: Remove this and add dep
|
2020-05-17 03:18:30 +00:00
|
|
|
let buffer_path = asset_path.parent().unwrap().join(uri);
|
2020-10-20 00:29:31 +00:00
|
|
|
let buffer_bytes = load_context.read_asset_bytes(buffer_path).await?;
|
2020-05-15 23:55:44 +00:00
|
|
|
buffer_data.push(buffer_bytes);
|
|
|
|
}
|
|
|
|
}
|
2020-10-18 20:48:15 +00:00
|
|
|
gltf::buffer::Source::Bin => {
|
2020-08-25 23:55:08 +00:00
|
|
|
if let Some(blob) = gltf.blob.as_deref() {
|
|
|
|
buffer_data.push(blob.into());
|
|
|
|
} else {
|
|
|
|
return Err(GltfError::MissingBlob);
|
|
|
|
}
|
|
|
|
}
|
2020-05-15 23:55:44 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(buffer_data)
|
|
|
|
}
|
2020-12-31 20:57:15 +00:00
|
|
|
|
|
|
|
fn resolve_node_hierarchy(
|
|
|
|
nodes_intermediate: Vec<(String, GltfNode, Vec<usize>)>,
|
|
|
|
) -> Vec<(String, GltfNode)> {
|
|
|
|
let mut max_steps = nodes_intermediate.len();
|
|
|
|
let mut nodes_step = nodes_intermediate
|
|
|
|
.into_iter()
|
|
|
|
.enumerate()
|
|
|
|
.map(|(i, (label, node, children))| (i, label, node, children))
|
|
|
|
.collect::<Vec<_>>();
|
|
|
|
let mut nodes = std::collections::HashMap::<usize, (String, GltfNode)>::new();
|
|
|
|
while max_steps > 0 && !nodes_step.is_empty() {
|
|
|
|
if let Some((index, label, node, _)) = nodes_step
|
|
|
|
.iter()
|
|
|
|
.find(|(_, _, _, children)| children.is_empty())
|
|
|
|
.cloned()
|
|
|
|
{
|
|
|
|
nodes.insert(index, (label, node));
|
|
|
|
for (_, _, node, children) in nodes_step.iter_mut() {
|
|
|
|
if let Some((i, _)) = children
|
|
|
|
.iter()
|
|
|
|
.enumerate()
|
|
|
|
.find(|(_, child_index)| **child_index == index)
|
|
|
|
{
|
|
|
|
children.remove(i);
|
|
|
|
|
|
|
|
if let Some((_, child_node)) = nodes.get(&index) {
|
|
|
|
node.children.push(child_node.clone())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
nodes_step = nodes_step
|
|
|
|
.into_iter()
|
|
|
|
.filter(|(i, _, _, _)| *i != index)
|
|
|
|
.collect()
|
|
|
|
}
|
|
|
|
max_steps -= 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut nodes_to_sort = nodes.into_iter().collect::<Vec<_>>();
|
|
|
|
nodes_to_sort.sort_by_key(|(i, _)| *i);
|
|
|
|
nodes_to_sort
|
|
|
|
.into_iter()
|
|
|
|
.map(|(_, resolved)| resolved)
|
|
|
|
.collect()
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
|
|
|
use super::resolve_node_hierarchy;
|
|
|
|
use crate::GltfNode;
|
|
|
|
|
|
|
|
impl GltfNode {
|
|
|
|
fn empty() -> Self {
|
|
|
|
GltfNode {
|
|
|
|
children: vec![],
|
|
|
|
mesh: None,
|
2021-03-13 18:23:39 +00:00
|
|
|
transform: bevy_transform::prelude::Transform::identity(),
|
2020-12-31 20:57:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn node_hierarchy_single_node() {
|
|
|
|
let result = resolve_node_hierarchy(vec![("l1".to_string(), GltfNode::empty(), vec![])]);
|
|
|
|
|
|
|
|
assert_eq!(result.len(), 1);
|
|
|
|
assert_eq!(result[0].0, "l1");
|
|
|
|
assert_eq!(result[0].1.children.len(), 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn node_hierarchy_no_hierarchy() {
|
|
|
|
let result = resolve_node_hierarchy(vec![
|
|
|
|
("l1".to_string(), GltfNode::empty(), vec![]),
|
|
|
|
("l2".to_string(), GltfNode::empty(), vec![]),
|
|
|
|
]);
|
|
|
|
|
|
|
|
assert_eq!(result.len(), 2);
|
|
|
|
assert_eq!(result[0].0, "l1");
|
|
|
|
assert_eq!(result[0].1.children.len(), 0);
|
|
|
|
assert_eq!(result[1].0, "l2");
|
|
|
|
assert_eq!(result[1].1.children.len(), 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn node_hierarchy_simple_hierarchy() {
|
|
|
|
let result = resolve_node_hierarchy(vec![
|
|
|
|
("l1".to_string(), GltfNode::empty(), vec![1]),
|
|
|
|
("l2".to_string(), GltfNode::empty(), vec![]),
|
|
|
|
]);
|
|
|
|
|
|
|
|
assert_eq!(result.len(), 2);
|
|
|
|
assert_eq!(result[0].0, "l1");
|
|
|
|
assert_eq!(result[0].1.children.len(), 1);
|
|
|
|
assert_eq!(result[1].0, "l2");
|
|
|
|
assert_eq!(result[1].1.children.len(), 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn node_hierarchy_hierarchy() {
|
|
|
|
let result = resolve_node_hierarchy(vec![
|
|
|
|
("l1".to_string(), GltfNode::empty(), vec![1]),
|
|
|
|
("l2".to_string(), GltfNode::empty(), vec![2]),
|
|
|
|
("l3".to_string(), GltfNode::empty(), vec![3, 4, 5]),
|
|
|
|
("l4".to_string(), GltfNode::empty(), vec![6]),
|
|
|
|
("l5".to_string(), GltfNode::empty(), vec![]),
|
|
|
|
("l6".to_string(), GltfNode::empty(), vec![]),
|
|
|
|
("l7".to_string(), GltfNode::empty(), vec![]),
|
|
|
|
]);
|
|
|
|
|
|
|
|
assert_eq!(result.len(), 7);
|
|
|
|
assert_eq!(result[0].0, "l1");
|
|
|
|
assert_eq!(result[0].1.children.len(), 1);
|
|
|
|
assert_eq!(result[1].0, "l2");
|
|
|
|
assert_eq!(result[1].1.children.len(), 1);
|
|
|
|
assert_eq!(result[2].0, "l3");
|
|
|
|
assert_eq!(result[2].1.children.len(), 3);
|
|
|
|
assert_eq!(result[3].0, "l4");
|
|
|
|
assert_eq!(result[3].1.children.len(), 1);
|
|
|
|
assert_eq!(result[4].0, "l5");
|
|
|
|
assert_eq!(result[4].1.children.len(), 0);
|
|
|
|
assert_eq!(result[5].0, "l6");
|
|
|
|
assert_eq!(result[5].1.children.len(), 0);
|
|
|
|
assert_eq!(result[6].0, "l7");
|
|
|
|
assert_eq!(result[6].1.children.len(), 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn node_hierarchy_cyclic() {
|
|
|
|
let result = resolve_node_hierarchy(vec![
|
|
|
|
("l1".to_string(), GltfNode::empty(), vec![1]),
|
|
|
|
("l2".to_string(), GltfNode::empty(), vec![0]),
|
|
|
|
]);
|
|
|
|
|
|
|
|
assert_eq!(result.len(), 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn node_hierarchy_missing_node() {
|
|
|
|
let result = resolve_node_hierarchy(vec![
|
|
|
|
("l1".to_string(), GltfNode::empty(), vec![2]),
|
|
|
|
("l2".to_string(), GltfNode::empty(), vec![]),
|
|
|
|
]);
|
|
|
|
|
|
|
|
assert_eq!(result.len(), 1);
|
|
|
|
assert_eq!(result[0].0, "l2");
|
|
|
|
assert_eq!(result[0].1.children.len(), 0);
|
|
|
|
}
|
|
|
|
}
|