# Objective
- Make it so that `Time` can be cloned
- Makes it so I can clone the entire current `Time` and easily pass it to the user in [Rusty Engine](https://github.com/CleanCut/rusty_engine) instead of [doing this](8302dc3914/src/game.rs (L147-L150))
## Solution
- Derive the `Clone` trait on `Time`
# Objective
- CI jobs are starting to fail due to `clippy::bool-assert-comparison` and `clippy::single_component_path_imports` being triggered.
## Solution
- Fix all uses where `asset_eq!(<condition>, <bool>)` could be replace by `assert!`
- Move the `#[allow()]` for `single_component_path_imports` to `#![allow()]` at the start of the files.
# Objective
- Currently `AssetServer::get_handle_path` always returns `None` since the inner hash map is never written to.
## Solution
- Inside the `load_untracked` function, insert the asset path into the map.
This is similar to #1290 (thanks @TheRawMeatball)
# Objective
- The `DetectChanges` trait is used for types that detect change on mutable access (such as `ResMut`, `Mut`, etc...)
- `DetectChanges` was not implemented for `NonSendMut`
## Solution
- implement `NonSendMut` in terms of `DetectChanges`
# Objective
Currently, you can't call `is_added` or `is_changed` on a `NonSend` SystemParam, unless the Resource is a Component (implements `Send` and `Sync`).
This defeats the purpose of providing change detection for NonSend Resources.
While fixing this, I also noticed that `NonSend` does not have a bound at all on its struct.
## Solution
Change the bounds of `T` to always be `'static`.
# Objective
Prevent future unnecessary mental effort spent figuring out why this trait exists and how to resolve the `TODO`.
## Solution
I happened to notice this trait being used when expanding the `#[derive(Reflect)]` macro in my own crate to figure out how it worked, and noticed that there was a `TODO` comment on it because it is only used in the derive macro and thus appeared to be unused.
I figured I should document my findings to prevent someone else from finding them out the hard way in the future 😆
Co-authored-by: Waridley <Waridley64@gmail.com>
# Objective
- Currently, when calling any of the `AssetServer`'s `load` functions, if the extension does not exist for the given path, the returned handle's load state is always `LoadState::NotLoaded`.
- This is due to the `load_async` function early returning without properly creating a `SourceInfo` for the requested asset.
- Fixes#2261
## Solution
- Add the `SourceInfo` prior to checking for valid extension loaders. And set the `LoadState` to `Failed` if the according loader does not exist.
When loading a gltf, if there is an error loading textures, it is completely ignored.
This can happen for example when loading a file with `jpg` textures without the `jpeg` Bevy feature enabled.
This PR adds `warn` logs for the few cases that can happen when loading a texture.
Other possible fix would be to break on first error and returning, making the asset loading failed
1) Sets `LoadState` properly on all failing cases in `AssetServer::load_async`
2) Adds more tests for sad and happy paths of asset loading
_Note_: this brings in the `tempfile` crate.
fixes#2169
Instead of having custom methods with reduced visibility, implement `From<image::DynamicImage> for Texture` and `TryFrom<Texture> for image::DynamicImage`
[RENDERED](https://github.com/NiklasEi/bevy/blob/ecs_readme/crates/bevy_ecs/README.md)
Since I am trying to learn more about Bevy ECS at the moment, I thought this issue is a perfect fit.
This PR adds a readme to the `bevy_ecs` crate containing a minimal running example of stand alone `bevy_ecs`. Unique features like customizable component storage, Resources or change detection are introduced. For each of these features the readme links to an example in a newly created examples directory inside the `bevy_esc` crate.
Resolves#2008
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
Since `visible_entities_system` already checks `Visiblie::is_visible` for each entity and requires it to be `true`, there's no reason to verify visibility in `PassNode::prepare` which consumes entities produced by the system.
# Objective
- When creating an asset, the `update_asset_storage` function was unnecessarily creating an extraneous `Handle` to the created asset via calling `set`. This has some overhead as the `RefChange::Increment/Decrement` event was being sent.
- A similar exteraneous handle is also created in `load_async` when loading dependencies.
## Solution
- Have the implementation use `Assets::set_untracked` and `AssetServer::load_untracked` so no intermediate handle is created.
When implementing `AssetLoader ` you need to specify which File extensions are supported by that loader.
Currently, Bevy always says it supports extensions that actually require activating a Feature beforehand.
This PR adds cf attributes, so Bevy only tries to load those Extensions whose Features were activated.
This prevents Bevy from Panicking and reports such a warning:
```
Jun 02 23:05:57.139 WARN bevy_asset::asset_server: no `AssetLoader` found for the following extension: ogg
```
This also fixes the Bug, that the `png Feature had to be activated even if you wanted to load a different image format.
Fixes#640
## Problem
- The `Query` struct does not provide an easy way to check if it is empty.
- Specifically, users have to use `.iter().peekable()` or `.iter().next().is_none()` which is not very ergonomic.
- Fixes: #2270
## Solution
- Implement an `is_empty` function for queries to more easily check if the query is empty.
This enables `SystemParams` to be used outside of function systems. Anything can create and store `SystemState`, which enables efficient "param state cached" access to `SystemParams`.
It adds a `ReadOnlySystemParamFetch` trait, which enables safe `SystemState::get` calls without unique world access.
I renamed the old `SystemState` to `SystemMeta` to enable us to mirror the `QueryState` naming convention (but I'm happy to discuss alternative names if people have other ideas). I initially pitched this as `ParamState`, but given that it needs to include full system metadata, that doesn't feel like a particularly accurate name.
```rust
#[derive(Eq, PartialEq, Debug)]
struct A(usize);
#[derive(Eq, PartialEq, Debug)]
struct B(usize);
let mut world = World::default();
world.insert_resource(A(42));
world.spawn().insert(B(7));
// we get nice lifetime elision when declaring the type on the left hand side
let mut system_state: SystemState<(Res<A>, Query<&B>)> = SystemState::new(&mut world);
let (a, query) = system_state.get(&world);
assert_eq!(*a, A(42), "returned resource matches initial value");
assert_eq!(
*query.single().unwrap(),
B(7),
"returned component matches initial value"
);
// mutable system params require unique world access
let mut system_state: SystemState<(ResMut<A>, Query<&mut B>)> = SystemState::new(&mut world);
let (a, query) = system_state.get_mut(&mut world);
// static lifetimes are required when declaring inside of structs
struct SomeContainer {
state: SystemState<(Res<'static, A>, Res<'static, B>)>
}
// this can be shortened using type aliases, which will be useful for complex param tuples
type MyParams<'a> = (Res<'a, A>, Res<'a, B>);
struct SomeContainer {
state: SystemState<MyParams<'static>>
}
// It is the user's responsibility to call SystemState::apply(world) for parameters that queue up work
let mut system_state: SystemState<(Commands, Query<&B>)> = SystemState::new(&mut world);
{
let (mut commands, query) = system_state.get(&world);
commands.insert_resource(3.14);
}
system_state.apply(&mut world);
```
## Future Work
* Actually use SystemState inside FunctionSystem. This would be trivial, but it requires FunctionSystem to wrap SystemState in Option in its current form (which complicates system metadata lookup). I'd prefer to hold off until we adopt something like the later designs linked in #1364, which enable us to contruct Systems using a World reference (and also remove the need for `.system`).
* Consider a "scoped" approach to automatically call SystemState::apply when systems params are no longer being used (either a container type with a Drop impl, or a function that takes a closure for user logic operating on params).
When dropping the data, we originally only checked the size of an individual item instead of the size of the allocation. However with a capacity of 0, we attempt to deallocate a pointer which was not the result of allocation. That is, an item of `Layout { size_: 8, align_: 8 }` produces an array of `Layout { size_: 0, align_: 8 }` when `capacity = 0`.
Fixes#2294
## Objective
- Fixes: #2275
- `Assets` were being flagged as 'changed' each frame regardless of if the assets were actually being updated.
## Solution
- Only have `Assets` change detection be triggered when the collection is actually modified.
- This includes utilizing `ResMut` further down the stack instead of a `&mut Assets` directly.
Continuing the work on reducing the safety footguns in the code, I've removed one extra `UnsafeCell` in favour of safe `Cell` usage inisde `ComponentTicks`. That change led to discovery of misbehaving component insert logic, where data wasn't properly dropped when overwritten. Apart from that being fixed, some method names were changed to better convey the "initialize new allocation" and "replace existing allocation" semantic.
Depends on #2221, I will rebase this PR after the dependency is merged. For now, review just the last commit.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
`ResMut`, `Mut` and `ReflectMut` all share very similar code for change detection.
This PR is a first pass at refactoring these implementation and removing a lot of the duplicated code.
Note, this introduces a new trait `ChangeDetectable`.
Please feel free to comment away and let me know what you think!
Fixes#2274
When calling `despawn_recursive`, the recursive loop doesn't need to remove the entity from the children list of its parent when the parent will also be deleted
Upside:
* Removes two entity lookup per entity being recursively despawned
Downside:
* The change detection on the `Children` component of a deleted entity in the despawned hierarchy will not be triggered
Updates the requirements on [rodio](https://github.com/RustAudio/rodio) to permit the latest version.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a href="https://github.com/RustAudio/rodio/blob/master/CHANGELOG.md">rodio's changelog</a>.</em></p>
<blockquote>
<h1>Version 0.14.0 (2021-05-21)</h1>
<ul>
<li>Re-export <code>cpal</code> in full.</li>
<li>Replace panics when calling <code>OutputStream::try_default</code>, <code>OutputStream::try_from_device</code> with new
<code>StreamError</code> variants.</li>
<li><code>OutputStream::try_default</code> will now fallback to non-default output devices if an <code>OutputStream</code>
cannot be created from the default device.</li>
</ul>
<h1>Version 0.13.1 (2021-03-28)</h1>
<ul>
<li>Fix panic when no <code>pulseaudio-alsa</code> was installed.</li>
</ul>
<h1>Version 0.13.0 (2020-11-03)</h1>
<ul>
<li>Update <code>cpal</code> to <a href="https://github.com/RustAudio/cpal/blob/master/CHANGELOG.md#version-0130-2020-10-28">0.13</a>.</li>
<li>Add Android support.</li>
</ul>
<h1>Version 0.12.0 (2020-10-05)</h1>
<ul>
<li>Breaking: Update <code>cpal</code> to <a href="https://github.com/RustAudio/cpal/blob/master/CHANGELOG.md#version-0120-2020-07-09">0.12</a>.</li>
<li>Breaking: Rework API removing global "rodio audio processing" thread & adapting to the upstream cpal API changes.</li>
<li>Add new_X format specific methods to Decoder.</li>
<li>Fix resampler dependency on internal <code>Vec::capacity</code> behaviour.</li>
</ul>
<h1>Version 0.11.0 (2020-03-16)</h1>
<ul>
<li>Update <code>lewton</code> to <a href="https://github.com/RustAudio/lewton/blob/master/CHANGELOG.md#release-0100---january-30-2020">0.10</a>.</li>
<li>Breaking: Update <code>cpal</code> to <a href="https://github.com/RustAudio/cpal/blob/master/CHANGELOG.md#version-0110-2019-12-11">0.11</a></li>
</ul>
<h1>Version 0.10.0 (2019-11-16)</h1>
<ul>
<li>Removal of nalgebra in favour of own code.</li>
<li>Fix a bug that switched channels when resuming after having paused.</li>
<li>Attempt all supported output formats if the default format fails in <code>Sink::new</code>.</li>
<li>Breaking: Update <code>cpal</code> to <a href="https://github.com/RustAudio/cpal/blob/master/CHANGELOG.md#version-0100-2019-07-05">0.10</a>.</li>
</ul>
<h1>Version 0.9.0 (2019-06-08)</h1>
<ul>
<li>Remove exclusive <code>&mut</code> borrow requirements in <code>Sink</code> & <code>SpatialSink</code> setters.</li>
<li>Use <code>nalgebra</code> instead of <code>cgmath</code> for <code>Spatial</code> source.</li>
</ul>
<h1>Version 0.8.1 (2018-09-18)</h1>
<ul>
<li>Update <code>lewton</code> dependency to <a href="https://github.com/RustAudio/lewton/blob/master/CHANGELOG.md#release-090---august-16-2018">0.9</a></li>
<li>Change license from <code>Apache-2.0</code> only to <code>Apache-2.0 OR MIT</code></li>
</ul>
<h1>Version 0.8.0 (2018-06-22)</h1>
<ul>
<li>Add mp3 decoding capabilities via <code>minimp3</code></li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a href="https://github.com/RustAudio/rodio/commits">compare view</a></li>
</ul>
</details>
<br />
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
</details>
I've noticed that we are overusing interior mutability of the Table data, where in many cases we already own a unique reference to it. That prompted a slight refactor aiming to reduce number of safety constraints that must be manually upheld. Now the majority of those are just about avoiding bound checking, which is relatively easy to prove right.
Another aspect is reducing the complexity of Table struct. Notably, we don't ever use archetypes stored there, so this whole thing goes away. Capacity and grow amount were mostly superficial, as we are already using Vecs inside anyway, so I've got rid of those too. Now the overall table capacity is being driven by the internal entity Vec capacity. This has a side effect of automatically implementing exponential growth pattern for BitVecs reallocations inside Table, which to my measurements slightly improves performance in tests that are heavy on inserts. YMMV, but I hope that those tests were at least remotely correct.
The previous implementation of `Events::extend` iterated through each event and manually `sent` it via `Events:;send`.
However, this could be a minor performance hit since calling `Vec::push` in a loop is not optimal.
This refactors the code to use `Vec::extend`.
This new api stems from this [discord conversation](https://discord.com/channels/691052431525675048/742569353878437978/844057268172357663).
This exposes a public facing `set_changed` method on `ResMut` and `Mut`.
As a side note: `ResMut` and `Mut` have a lot of duplicated code, I have a PR I may put up later that refactors these commonalities into a trait.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
- simplified code around archetype generations a little bit, as the special case value is not actually needed
- removed unnecessary UnsafeCell around pointer value that is never updated through shared references
- fixed and added a test for correct drop behaviour when removing sparse components through remove_bundle command
While trying to figure out how to implement a `SystemParam`, I spent a
long time looking for a feature that would do exactly what `Config`
does. I ignored it at first because all the examples I could find used
`()` and I couldn't see a way to modify it.
This is documented in other places, but `Config` is a logical place to
include some breadcrumbs. I've added some text that gives a brief
overview of what `Config` is for, and links to the existing docs on
`FunctionSystem::config` for more details.
This would have saved me from embarrassing myself by filing https://github.com/bevyengine/bevy/issues/2178.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
During PR #2046 @cart suggested that the `(): ()` notation is less legible than `_input: ()`. The first notation still managed to slip in though. This PR applies the second writing.
Related to [discussion on discord](https://discord.com/channels/691052431525675048/742569353878437978/824731187724681289)
With const generics, it is now possible to write generic iterator over multiple entities at once.
This enables patterns of query iterations like
```rust
for [e1, e2, e3] in query.iter_combinations() {
// do something with relation of all three entities
}
```
The compiler is able to infer the correct iterator for given size of array, so either of those work
```rust
for [e1, e2] in query.iter_combinations() { ... }
for [e1, e2, e3] in query.iter_combinations() { ... }
```
This feature can be very useful for systems like collision detection.
When you ask for permutations of size K of N entities:
- if K == N, you get one result of all entities
- if K < N, you get all possible subsets of N with size K, without repetition
- if K > N, the result set is empty (no permutation of size K exist)
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
This can save users from having to type `&*X` all the time at the cost of some complexity in the type signature. For instance, this allows me to accommodate @jakobhellermann's suggestion in #1799 without requiring users to type `&*windows` 99% of the time.
Fixes the frag shader for unlit materials by correcting the scope of the `#ifndef` to include the light functions. Closes#2190, introduced in #2112.
Tested by changing materials in the the `3d_scene` example to be unlit. Unsure how to prevent future regressions without creating a test case scene that will catch these runtime panics.
This gets rid of multiple unsafe blocks that we had to maintain ourselves, and instead depends on library that's commonly used and supported by the ecosystem. We also get support for glam types for free.
There is still some things to clear up with the `Bytes` trait, but that is a bit more substantial change and can be done separately. Also there are already separate efforts to use `crevice` crate, so I've just added that as a TODO.
`ParallelSystemContainer`'s `system` pointer was extracted from box, but it was never deallocated. This change adds missing drop implementation that cleans up that memory.
The first commit monomorphizes `add_system_inner` which I think was intended to be monomorphized anyway. The second commit moves the type argument of `GraphNode` to an associated type.
Updates the requirements on [gltf](https://github.com/gltf-rs/gltf) to permit the latest version.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a href="https://github.com/gltf-rs/gltf/blob/master/CHANGELOG.md">gltf's changelog</a>.</em></p>
<blockquote>
<h2>[0.16.0] - 2021-05-13</h2>
<h3>Added</h3>
<ul>
<li>Support for the <code>KHR_texture_transform</code> extension.</li>
<li>Support for the <code>KHR_materials_transmission_ior extension</code>.</li>
</ul>
<h3>Changed</h3>
<ul>
<li><code>Material::alpha_cutoff</code> is now optional.</li>
</ul>
<h3>Fixed</h3>
<ul>
<li>URIs with embedded data failing to import when using <code>import_slice</code>.</li>
<li>Serialization of empty primitives object being skipped.</li>
</ul>
<h2>[0.15.2] - 2020-03-29</h2>
<h3>Changed</h3>
<ul>
<li>All features are now exposed in the <a href="http://docs.rs/gltf">online documentation</a>.</li>
<li>Primary iterators now implement <code>Iterator::nth</code> explicitly for improved performance.</li>
</ul>
<h3>Fixed</h3>
<ul>
<li>Compiler warnings regarding deprecation of <code>std::error::Error::description</code>.</li>
</ul>
<h2>[0.15.1] - 2020-03-15</h2>
<h3>Added</h3>
<ul>
<li>New feature <code>guess_mime_type</code> which, as the name suggests, attempts to guess
the MIME type of an image if it doesn't exactly match the standard.</li>
</ul>
<h3>Changed</h3>
<ul>
<li><code>base64</code> updated to <code>0.11</code>.</li>
<li><code>byteorder</code> updated to <code>1.3</code>.</li>
<li><code>image</code> updated to <code>0.23.0</code>.</li>
<li><code>Format</code> has additional variants for 16-bit pixel formats.</li>
</ul>
<h3>Fixed</h3>
<ul>
<li>Off-by-one error when reading whole files incurring a gratuitous reallocation.</li>
</ul>
<h2>[0.15.0] - 2020-01-18</h2>
<h3>Added</h3>
<ul>
<li>Support for the <code>KHR_materials_unlit</code> extension, which adds an <code>unlit</code> field</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a href="https://github.com/gltf-rs/gltf/commits">compare view</a></li>
</ul>
</details>
<br />
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
</details>
There's what might be considered a proper bug in `PipelineCompiler::compile_pipeline()`, where it overwrites the `step_mode` for the passed in `VertexBufferLayout` with `InputStepMode::Vertex`. Due to this some ugly workarounds are needed to do any kind of instancing.
In the somewhat longer term, `PipelineCompiler::compile_pipeline()` should probably also handle a `Vec<VertexBufferLayout>`, but that would be a (slightly) larger PR, rather than a bugfix. And I'd love to have this fix in sooner than we can deal with a bigger PR.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
Problem:
- When using the 'as_crate' attribute, if 'as_crate' was empty, the only
error you would get is 'integer underflow'.
Solution:
- Provide an explicit check for the 'as_crate' attribute's token stream
to ensure the formatting is correct.
Note:
- Also reworked 'get_meta' by not making it call 'Manifest::find' twice.
Required by #1429,
- Adds the `Ushort4` vertex attribute for joint indices
- `Mesh::ATTRIBUTE_JOINT_WEIGHT` and `Mesh::ATTRIBUTE_JOINT_INDEX` to import vertex attributes related to skinning from GLTF
- impl `Default` for `Mesh` a empty triangle mesh is created (needed by reflect)
- impl `Reflect` for `Mesh` all attributes are ignored (needed by the animation system)
For review, first iteration of bevy code documentation.
I can continue submitting docs every now and then for relevant parts.
Some challenges I found:
* plugins example had to be commented out, as adding bevy_internal (where plugins reside) would pull in too many dependencies
Co-authored-by: Mika <1299457+blaind@users.noreply.github.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
fixes#824fixes#1956
* marked asset loading methods as `must_use`
* fixed asset re-loading while asset is still loading to work as comment is describing code
* introduced a 1 frame delay between unused asset marking and actual asset removal
Updates the requirements on [rectangle-pack](https://github.com/chinedufn/rectangle-pack) to permit the latest version.
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a href="https://github.com/chinedufn/rectangle-pack/commits">compare view</a></li>
</ul>
</details>
<br />
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
</details>
Changes to get Bevy to compile with wgpu master.
With this, on a Mac:
* 2d examples look fine
* ~~3d examples crash with an error specific to metal about a compilation error~~
* 3d examples work fine after enabling feature `wgpu/cross`
Feature `wgpu/cross` seems to be needed only on some platforms, not sure how to know which. It was introduced in https://github.com/gfx-rs/wgpu-rs/pull/826
Hi, ran into this problem with the derive macro.
It fails trying to derive the Default trait when the asset does not implements it also. This is unnecessary because this plugin does not need that from the asset type, just needs to create the phantom data.
Fixes#2037 (and then some)
Problem:
- `TypeUuid`, `RenderResource`, and `Bytes` derive macros did not properly handle generic structs.
Solution:
- Rework the derive macro implementations to handle the generics.
While trying to reduce load time of gltf files, I noticed most of the loading time is spent transforming bytes into an actual texture.
This PR add asynchronously loading for them using io task pool in gltf loader. It reduces loading of a large glb file from 15 seconds to 6~8 on my laptop
To allow asynchronous tasks in an asset loader, I added a reference to the task pool from the asset server in the load context, which I can use later in the loader.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
This alias is to aid people finding the cursor_position function, as the mouse
pressed / moved functionality and naming likely primes people for thinking
of "mouse" before "cursor" when searching the api documentation.
In response to #2023, here is a draft for a PR.
Fixes#2023
I've added an example to show how to use `WithBundle`, and also to test it out.
Right now there is a bug: If a bundle and a query are "the same", then it doesn't filter out
what it needs to filter out.
Example:
```
Print component initated from bundle.
[examples/ecs/query_bundle.rs:57] x = Dummy( <========= This should not get printed
111,
)
[examples/ecs/query_bundle.rs:57] x = Dummy(
222,
)
Show all components
[examples/ecs/query_bundle.rs:50] x = Dummy(
111,
)
[examples/ecs/query_bundle.rs:50] x = Dummy(
222,
)
```
However, it behaves the right way, if I add one more component to the bundle,
so the query and the bundle doesn't look the same:
```
Print component initated from bundle.
[examples/ecs/query_bundle.rs:57] x = Dummy(
222,
)
Show all components
[examples/ecs/query_bundle.rs:50] x = Dummy(
111,
)
[examples/ecs/query_bundle.rs:50] x = Dummy(
222,
)
```
I hope this helps. I'm definitely up for tinkering with this, and adding anything that I'm asked to add
or change.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
I'm using Bevy ECS in a project of mine and I'd like to do world changes asynchronously.
The current public API for creating entities, `Commands` , has a lifetime that restricts it from being sent across threads. `CommandQueue` on the other hand is a Vec of commands that can be later ran on a World.
So far this is all public, but the commands themselves are private API. I know the intented use is with `Commands`, but that's not possible for my use case as I mentioned, and so I simply copied over the code for the commands I need and it works. Obviously, this isn't a nice solution, so I'd like to ask if it's not out of scope to make the commands public?
If a mesh without any vertex attributes is rendered (for example, one that only has indices), bevy will crash since the mesh still creates a vertex buffer even though it's empty. Later code assumes that there is vertex data, causing an index-out-of-bounds panic. This PR fixes the issue by adding a check that there is any vertex data before creating a vertex buffer.
I ran into this issue while rendering a tilemap without any vertex attributes (only indices).
Stack trace:
```
thread 'main' panicked at 'index out of bounds: the len is 0 but the index is 0', C:\Dev\Games\bevy\crates\bevy_render\src\render_graph\nodes\pass_node.rs:346:9
stack backtrace:
0: std::panicking::begin_panic_handler
at /rustc/bb491ed23937aef876622e4beb68ae95938b3bf9\/library\std\src\panicking.rs:493
1: core::panicking::panic_fmt
at /rustc/bb491ed23937aef876622e4beb68ae95938b3bf9\/library\core\src\panicking.rs:92
2: core::panicking::panic_bounds_check
at /rustc/bb491ed23937aef876622e4beb68ae95938b3bf9\/library\core\src\panicking.rs:69
3: core::slice::index::{{impl}}::index<core::option::Option<tuple<bevy_render::renderer::render_resource::buffer::BufferId, u64>>>
at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\core\src\slice\index.rs:184
4: core::slice::index::{{impl}}::index<core::option::Option<tuple<bevy_render::renderer::render_resource::buffer::BufferId, u64>>,usize>
at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\core\src\slice\index.rs:15
5: alloc::vec::{{impl}}::index<core::option::Option<tuple<bevy_render::renderer::render_resource::buffer::BufferId, u64>>,usize,alloc::alloc::Global>
at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\alloc\src\vec\mod.rs:2386
6: bevy_render::render_graph::nodes::pass_node::DrawState::is_vertex_buffer_set
at C:\Dev\Games\bevy\crates\bevy_render\src\render_graph\nodes\pass_node.rs:346
7: bevy_render::render_graph::nodes::pass_node::{{impl}}::update::{{closure}}<bevy_render::render_graph::base::MainPass*>
at C:\Dev\Games\bevy\crates\bevy_render\src\render_graph\nodes\pass_node.rs:285
8: bevy_wgpu::renderer::wgpu_render_context::{{impl}}::begin_pass
at C:\Dev\Games\bevy\crates\bevy_wgpu\src\renderer\wgpu_render_context.rs:196
9: bevy_render::render_graph::nodes::pass_node::{{impl}}::update<bevy_render::render_graph::base::MainPass*>
at C:\Dev\Games\bevy\crates\bevy_render\src\render_graph\nodes\pass_node.rs:244
10: bevy_wgpu::renderer::wgpu_render_graph_executor::WgpuRenderGraphExecutor::execute
at C:\Dev\Games\bevy\crates\bevy_wgpu\src\renderer\wgpu_render_graph_executor.rs:75
11: bevy_wgpu::wgpu_renderer::{{impl}}::run_graph::{{closure}}
at C:\Dev\Games\bevy\crates\bevy_wgpu\src\wgpu_renderer.rs:115
12: bevy_ecs::world::World::resource_scope<bevy_render::render_graph::graph::RenderGraph,tuple<>,closure-0>
at C:\Dev\Games\bevy\crates\bevy_ecs\src\world\mod.rs:715
13: bevy_wgpu::wgpu_renderer::WgpuRenderer::run_graph
at C:\Dev\Games\bevy\crates\bevy_wgpu\src\wgpu_renderer.rs:104
14: bevy_wgpu::wgpu_renderer::WgpuRenderer::update
at C:\Dev\Games\bevy\crates\bevy_wgpu\src\wgpu_renderer.rs:121
15: bevy_wgpu::get_wgpu_render_system::{{closure}}
at C:\Dev\Games\bevy\crates\bevy_wgpu\src\lib.rs:112
16: alloc::boxed::{{impl}}::call_mut<tuple<mut bevy_ecs::world::World*>,FnMut<tuple<mut bevy_ecs::world::World*>>,alloc::alloc::Global>
at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\alloc\src\boxed.rs:1553
17: bevy_ecs::system::exclusive_system::{{impl}}::run
at C:\Dev\Games\bevy\crates\bevy_ecs\src\system\exclusive_system.rs:41
18: bevy_ecs::schedule::stage::{{impl}}::run
at C:\Dev\Games\bevy\crates\bevy_ecs\src\schedule\stage.rs:812
19: bevy_ecs::schedule::Schedule::run_once
at C:\Dev\Games\bevy\crates\bevy_ecs\src\schedule\mod.rs:201
20: bevy_ecs::schedule::{{impl}}::run
at C:\Dev\Games\bevy\crates\bevy_ecs\src\schedule\mod.rs:219
21: bevy_app::app::App::update
at C:\Dev\Games\bevy\crates\bevy_app\src\app.rs:58
22: bevy_winit::winit_runner_with::{{closure}}
at C:\Dev\Games\bevy\crates\bevy_winit\src\lib.rs:485
23: winit::platform_impl::platform::event_loop::{{impl}}::run_return::{{closure}}<tuple<>,closure-1>
at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop.rs:203
24: alloc::boxed::{{impl}}::call_mut<tuple<winit::event::Event<tuple<>>, mut winit::event_loop::ControlFlow*>,FnMut<tuple<winit::event::Event<tuple<>>, mut winit::event_loop::ControlFlow*>>,alloc::alloc::Global>
at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\alloc\src\boxed.rs:1553
25: winit::platform_impl::platform::event_loop:🏃:{{impl}}::call_event_handler::{{closure}}<tuple<>>
at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop\runner.rs:245
26: std::panic::{{impl}}::call_once<tuple<>,closure-0>
at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panic.rs:344
27: std::panicking::try::do_call<std::panic::AssertUnwindSafe<closure-0>,tuple<>>
at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panicking.rs:379
28: hashbrown::set::HashSet<mut winapi::shared::windef::HWND__*, std::collections:#️⃣:map::RandomState, alloc::alloc::Global>::iter<mut winapi::shared::windef::HWND__*,std::collections:#️⃣:map::RandomState,alloc::alloc::Global>
29: std::panicking::try<tuple<>,std::panic::AssertUnwindSafe<closure-0>>
at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panicking.rs:343
30: std::panic::catch_unwind<std::panic::AssertUnwindSafe<closure-0>,tuple<>>
at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panic.rs:431
31: winit::platform_impl::platform::event_loop:🏃:EventLoopRunner<tuple<>>::catch_unwind<tuple<>,tuple<>,closure-0>
at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop\runner.rs:152
32: winit::platform_impl::platform::event_loop:🏃:EventLoopRunner<tuple<>>::call_event_handler<tuple<>>
at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop\runner.rs:239
33: winit::platform_impl::platform::event_loop:🏃:EventLoopRunner<tuple<>>::move_state_to<tuple<>>
at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop\runner.rs:341
34: winit::platform_impl::platform::event_loop:🏃:EventLoopRunner<tuple<>>::main_events_cleared<tuple<>>
at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop\runner.rs:227
35: winit::platform_impl::platform::event_loop::flush_paint_messages<tuple<>>
at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop.rs:676
36: winit::platform_impl::platform::event_loop::thread_event_target_callback::{{closure}}<tuple<>>
at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop.rs:1967
37: std::panic::{{impl}}::call_once<isize,closure-0>
at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panic.rs:344
38: std::panicking::try::do_call<std::panic::AssertUnwindSafe<closure-0>,isize>
at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panicking.rs:379
39: hashbrown::set::HashSet<mut winapi::shared::windef::HWND__*, std::collections:#️⃣:map::RandomState, alloc::alloc::Global>::iter<mut winapi::shared::windef::HWND__*,std::collections:#️⃣:map::RandomState,alloc::alloc::Global>
40: std::panicking::try<isize,std::panic::AssertUnwindSafe<closure-0>>
at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panicking.rs:343
41: std::panic::catch_unwind<std::panic::AssertUnwindSafe<closure-0>,isize>
at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panic.rs:431
42: winit::platform_impl::platform::event_loop:🏃:EventLoopRunner<tuple<>>::catch_unwind<tuple<>,isize,closure-0>
at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop\runner.rs:152
43: winit::platform_impl::platform::event_loop::thread_event_target_callback<tuple<>>
at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop.rs:2151
44: DefSubclassProc
45: DefSubclassProc
46: CallWindowProcW
47: DispatchMessageW
48: SendMessageTimeoutW
49: KiUserCallbackDispatcher
50: NtUserDispatchMessage
51: DispatchMessageW
52: winit::platform_impl::platform::event_loop::EventLoop<tuple<>>::run_return<tuple<>,closure-1>
at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop.rs:218
53: winit::platform_impl::platform::event_loop::EventLoop<tuple<>>::run<tuple<>,closure-1>
at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\platform_impl\windows\event_loop.rs:188
54: winit::event_loop::EventLoop<tuple<>>::run<tuple<>,closure-1>
at C:\Users\tehpe\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.24.0\src\event_loop.rs:154
55: bevy_winit::run<closure-1>
at C:\Dev\Games\bevy\crates\bevy_winit\src\lib.rs:171
56: bevy_winit::winit_runner_with
at C:\Dev\Games\bevy\crates\bevy_winit\src\lib.rs:493
57: bevy_winit::winit_runner
at C:\Dev\Games\bevy\crates\bevy_winit\src\lib.rs:211
58: core::ops::function::Fn::call<fn(bevy_app::app::App),tuple<bevy_app::app::App>>
at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\core\src\ops\function.rs:70
59: alloc::boxed::{{impl}}::call<tuple<bevy_app::app::App>,Fn<tuple<bevy_app::app::App>>,alloc::alloc::Global>
at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\alloc\src\boxed.rs:1560
60: bevy_app::app::App::run
at C:\Dev\Games\bevy\crates\bevy_app\src\app.rs:68
61: bevy_app::app_builder::AppBuilder::run
at C:\Dev\Games\bevy\crates\bevy_app\src\app_builder.rs:54
62: game_main::main
at .\crates\game_main\src\main.rs:23
63: core::ops::function::FnOnce::call_once<fn(),tuple<>>
at C:\Users\tehpe\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\core\src\ops\function.rs:227
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
Apr 27 21:51:01.026 ERROR gpu_descriptor::allocator: `DescriptorAllocator` is dropped while some descriptor sets were not deallocated
error: process didn't exit successfully: `target/cargo\debug\game_main.exe` (exit code: 0xc000041d)
```
fix a few dead links
* Links in `Input` missed a refactor
* `Reflect::downcast` can't use the intra doc link format, as it's not a link to a trait function, but to a function implemented on `dyn Reflect`
noticed in https://github.com/bevyengine/bevy/pull/1781#discussion_r619777879
Fixes#1892
The following code is a cut down version of the issue, and crashes the same way:
```rust
enum AssetLifecycleEvent <T> {
Create(T),
Free
}
fn main() {
let (sender, _receiver) = crossbeam_channel::unbounded();
sender.send(AssetLifecycleEvent::<[u32; 32000]>::Free).unwrap();
}
```
- We're creating a channel that need to be able to hold `AssetLifecycleEvent::Create(T)` which has the size of our type `T`
- The two variants of the enums have a very different size
By keeping `T` boxed while sending through the channel, it doesn't crash
The documentation for `ShouldRun` doesn't completely explain what each of the variants you can return does. For instance, it isn't very clear that looping systems aren't executed again until after all the systems in a stage have had a chance to run.
This PR adds to the documentation for `ShouldRun`, and hopefully clarifies what is happening during a stage's execution when run criteria are checked and systems are being executed.
Some panic messages for systems include the system name, but there's a few panic messages which do not. This PR adds the system name for the remaining panic messages.
This is a continuation of the work done in #1864.
Related: #1846
Fixes#1895
Changed most `println` to `info` in examples, some to `warn` when it was useful to differentiate from other more noisy logs.
Added doc on `LogPlugin`, how to configure it, and why (and how) you may need to disable it
This shrinks breakout from 316k to 310k when using `--feature dynamic`.
I haven't run the ecs benchmark to test performance as my laptop is too noisy for reliable benchmarking.
There are cases where we want an enum variant name. Right now the only way to do that with rust's std is to derive Debug, but this will also print out the variant's fields. This creates the unfortunate situation where we need to manually write out each variant's string name (ex: in #1963), which is both boilerplate-ey and error-prone. Crates such as `strum` exist for this reason, but it includes a lot of code and complexity that we don't need.
This adds a dead-simple `EnumVariantMeta` derive that exposes `enum_variant_index` and `enum_variant_name` functions. This allows us to make cases like #1963 much cleaner (see the second commit). We might also be able to reuse this logic for `bevy_reflect` enum derives.
In bevy_webgl2, the `RenderResourceContext` is created after startup as it needs to first wait for an event from js side:
f31e5d49de/src/lib.rs (L117)
remove `panic` introduced in #1965 and log as a `warn` instead
After running `bevy_core` through `miri`, errors were reported surrounding incorrect memory accesses within the `bytes` test suit.
Specifically:
```
test bytes::tests::test_array_round_trip ... error: Undefined Behavior: accessing memory with alignment 1, but alignment 4 is required
--> crates/bevy_core/src/bytes.rs:55:13
|
55 | (*ptr).clone()
| ^^^^^^ accessing memory with alignment 1, but alignment 4 is required
|
```
and
```
test bytes::tests::test_vec_bytes_round_trip ... error: Undefined Behavior: accessing memory with alignment 2, but alignment 4 is required
--> /home/nward/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/slice/raw.rs:95:14
|
95 | unsafe { &*ptr::slice_from_raw_parts(data, len) }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ accessing memory with alignment 2, but alignment 4 is required
|
```
Solution:
The solution is to use `slice::align_to` method to ensure correct alignment.
This implementations allows you
convert std::vec::Vec<T> to VertexAttributeValues::T and back.
# Examples
```rust
use std::convert::TryInto;
use bevy_render::mesh::VertexAttributeValues;
// creating vector of values
let before = vec![[0_u32; 4]; 10];
let values = VertexAttributeValues::from(before.clone());
let after: Vec<[u32; 4]> = values.try_into().unwrap();
assert_eq!(before, after);
```
Co-authored-by: aloucks <aloucks@cofront.net>
Co-authored-by: simens_green <34134129+simensgreen@users.noreply.github.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
This was nowhere documented inside Bevy.
Should I also mention the use case of debugging a project?
Closes#810
Co-authored-by: MinerSebas <66798382+MinerSebas@users.noreply.github.com>
We discussed with @alice-i-cecile privately on iterators and agreed that making a custom ordered iterator over query makes no sense since materialization is required anyway and it's better to reuse existing components or code. Therefore, just adding an example to the documentation as requested.
Fixes#1470.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
Introduced in #1778, not fixed by #1931
The size of `Lights` buffer currently is :
```rust
16 // (color, `[f32; 4]`)
+ 16 // (number of lights, `f32` encoded as a `[f32; 4]`)
+ 10 // (maximum number of lights)
* ( 16 // (light position, `[f32; 4]`
+ 16 // (color, `[16; 4]`)
+ 4 // (inverse_range_squared, `f32`)
)
-> 392
```
This makes the pbr shader crash when running with Xcode debugger or with the WebGL2 backend. They both expect a buffer sized 512. This can also be seen on desktop by adding a second light to a scene with a color, it's position and color will be wrong.
adding a second light to example `load_gltf`:
```rust
commands
.spawn_bundle(PointLightBundle {
transform: Transform::from_xyz(-3.0, 5.0, -3.0),
point_light: PointLight {
color: Color::BLUE,
..Default::default()
},
..Default::default()
})
.insert(Rotates);
```
before fix:
<img width="1392" alt="Screenshot 2021-04-16 at 19 14 59" src="https://user-images.githubusercontent.com/8672791/115060744-866fb080-9ee8-11eb-8915-f87cc872ad48.png">
after fix:
<img width="1392" alt="Screenshot 2021-04-16 at 19 16 44" src="https://user-images.githubusercontent.com/8672791/115060759-8cfe2800-9ee8-11eb-92c2-d79f39c7b36b.png">
This PR changes `inverse_range_squared` to be a `[f32; 4]` instead of a `f32` to have the expected alignement
Fixes#1921
Buffer was growing with the actual number of lights instead of being limited to the max number of lights.
As it's a query that can be exactly sized, I also switched `count()` to `len()`
This includes a lot of single line comments where either saying more wasn't helpful or due to me not knowing enough about things yet to be able to go more indepth. Proofreading is very much welcome.
Allows render resources to move data to the heap by boxing them. I did this as a workaround to #1892, but it seems like it'd be useful regardless. If not, feel free to close this PR.
I've had problems with compiling and running the pbr example:
```
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Compilation("glslang_shader_preprocess:\nInfo log:\nERROR: 0:40: \'#version\' : must occur first in shader \nERROR: 0:40: \'#version\' : bad profile name; use es, core, or compatibility \nERROR: 0:40: \'#version\' : bad tokens following profile -- expected newline \nERROR: 3 compilation errors. No code generated.\n\n\nDebug log:\n\n")', crates/bevy_render/src/pipeline/pipeline_compiler.rs:161:22
```
I've checked each shader, and only one shader hasn't had `#version` in the first line.
This change fixed my issue.
Fixes#1846
Got scared of the other "Requested resource does not exist" error at line 395 in `system_param.rs`, under `impl<'a, T: Component> SystemParamFetch<'a> for ResMutState<T> {`. Someone with better knowledge of the code might be able to go in and improve that one.
Implements `Byteable` and `RenderResource` for any array containing `Byteable` elements. This allows `RenderResources` to be implemented on structs with arbitrarily-sized arrays, among other things:
```rust
#[derive(RenderResources, TypeUuid)]
#[uuid = "2733ff34-8f95-459f-bf04-3274e686ac5f"]
struct Foo {
buffer: [i32; 256],
}
```
From suggestion from Godot workflows: https://github.com/bevyengine/bevy/issues/1730#issuecomment-810321110
* Add a feature `bevy_debug` that will make Bevy read a debug config file to setup some debug systems
* Currently, only one that will exit after x frames
* Could add option to dump screen to image file once that's possible
* Add a job in CI workflow that will run a few examples using [`swiftshader`](https://github.com/google/swiftshader)
* This job takes around 13 minutes, so doesn't add to global CI duration
|example|number of frames|duration|
|-|-|-|
|`alien_cake_addict`|300|1:50|
|`breakout`|1800|0:44|
|`contributors`|1800|0:43|
|`load_gltf`|300|2:37|
|`scene`|1800|0:44|
Fixes#1809. It makes it also possible to use `derive` for `SystemParam` inside ECS and avoid manual implementation. An alternative solution to macro changes is to use `use crate as bevy_ecs;` in `event.rs`.
The `VertexBufferLayout` returned by `crates\bevy_render\src\mesh\mesh.rs:308` was unstable, because `HashMap.iter()` has a random order. This caused the pipeline_compiler to wrongly consider a specialization to be different (`crates\bevy_render\src\pipeline\pipeline_compiler.rs:123`), causing each mesh changed event to potentially result in a different `PipelineSpecialization`. This in turn caused `Draw` to emit a `set_pipeline` much more often than needed.
This fix shaves off a `BindPipeline` and two `BindDescriptorSets` (for the Camera and for global renderresources) for every mesh after the first that can now use the same specialization, where it didn't before (which was random).
`StableHashMap` was not a good replacement, because it isn't `Clone`, so instead I replaced it with a `BTreeMap` which is OK in this instance, because there shouldn't be many insertions on `Mesh.attributes` after the mesh is created.
related to #1700
This PR:
* documents all methods on `Input<T>`
* adds documentation on the struct about how to use it, and how to implement it for a new input type
* renames method `update` to a easier to understand `clear`
* adds two methods to check for state and clear it after, allowing easier use in the case of #1700
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
- prints glsl compile error message in multiple lines instead of `thread 'main' panicked at 'called Result::unwrap() on an Err value: Compilation("glslang_shader_parse:\nInfo log:\nERROR: 0:335: \'assign\' : l-value required \"anon@7\" (can\'t modify a uniform)\nERROR: 0:335: \'\' : compilation terminated \nERROR: 2 compilation errors. No code generated.\n\n\nDebug log:\n\n")', crates/bevy_render/src/pipeline/pipeline_compiler.rs:161:22`
- makes gltf error messages have more context
New error:
```rust
thread 'Compute Task Pool (5)' panicked at 'Shader compilation error:
glslang_shader_parse:
Info log:
ERROR: 0:12: 'assign' : l-value required "anon@1" (can't modify a uniform)
ERROR: 0:12: '' : compilation terminated
ERROR: 2 compilation errors. No code generated.
', crates/bevy_render/src/pipeline/pipeline_compiler.rs:364:5
```
These changes are a bit unrelated. I can open separate PRs if someone wants that.
After an inquiry on Reddit about support for Directional Lights and the unused properties on Light, I wanted to clean it up, to hopefully make it ever so slightly more clear for anyone wanting to add additional light types.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
After #1697 I looked at all other Iterators from Bevy and added overrides for `size_hint` where it wasn't done.
Also implemented `ExactSizeIterator` where applicable.
This reduces the size of executables when using bevy as dylib by
ensuring that they get codegened in bevy_assets instead of the game
itself. This by extension avoids pulling in parts of bevy_tasks and
async_task.
Before this change the breakout example was 923k big after this change
it is only 775k big for cg_clif. For cg_llvm in release mode breakout
shrinks from 356k to 316k. For cg_llvm in debug mode breakout shrinks
from 3814k to 3057k.
In shaders, `vec3` should be avoided for `std140` layout, as they take the size of a `vec4` and won't support manual padding by adding an additional `float`.
This change is needed for 3D to work in WebGL2. With it, I get PBR to render
<img width="1407" alt="Screenshot 2021-04-02 at 02 57 14" src="https://user-images.githubusercontent.com/8672791/113368551-5a3c2780-935f-11eb-8c8d-e9ba65b5ee98.png">
Without it, nothing renders... @cart Could this be considered for 0.5 release?
Also, I learned shaders 2 days ago, so don't hesitate to correct any issue or misunderstanding I may have
bevy_webgl2 PR in progress for Bevy 0.5 is here if you want to test: https://github.com/rparrett/bevy_webgl2/pull/1
fixes#1772
1st commit: the limit was at 11 as the macro was not using a range including the upper end. I changed that as it feels the purpose of the macro is clearer that way.
2nd commit: as suggested in the `// TODO`, I added a `Config` trait to go to 16 elements tuples. This means that if someone has a custom system parameter with a config that is not a tuple or an `Option`, they will have to implement `Config` for it instead of the standard `Default`.
I think [collection, thing_removed_from_collection] is a more natural order than [thing_removed_from_collection, collection]. Just a small tweak that I think we should include in 0.5.
This PR adds normal maps on top of PBR #1554. Once that PR lands, the changes should look simpler.
Edit: Turned out to be so little extra work, I added metallic/roughness texture too. And occlusion and emissive.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
The only API to add a parent/child relationship between existing entities is through commands, there is no easy way to do it from `World`. Manually inserting the components is not completely possible since `PreviousParent` has no public constructor.
This PR adds two methods to set entities as children of an `EntityMut`: `insert_children` and `push_children`. ~~The API is similar to the one on `Commands`, except that the parent is the `EntityMut`.~~ The API is the same as in #1703.
However, the `Parent` and `Children` components are defined in `bevy_transform` which depends on `bevy_ecs`, while `EntityMut` is defined in `bevy_ecs`, so the methods are added to the `BuildWorldChildren` trait instead.
If #1545 is merged this should be fixed too.
I'm aware cart was experimenting with entity hierarchies, but unless it's a coming soon this PR would be useful to have meanwhile.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
Load textures from gltf as linear when needed.
This is for #1632, but can be done independently and won't have any visible impact before.
* during iteration over materials, register textures that need to be loaded as linear
* during iteration over textures
* directly load bytes from external files instead of adding them as dependencies in the load context
* configure the texture the same way for buffered and external textures
* if the texture is linear rgb, set as linear rgb
Fixes#1753.
The problem was introduced while reworking the logic around stages' own criteria. Before #1675 they used to be stored and processed inline with the systems' criteria, and systems without criteria used that of their stage. After, criteria-less systems think they should run, always. This PR more or less restores previous behavior; a less cludge solution can wait until after 0.5 - ideally, until stageless.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
Frustum culling has some pretty major gaps right now (such as not supporting sprite transform scaling and not taking into account projections). It should be disabled by default until it provides a solid experience across all bevy use cases.
This is intended to help protect users against #1671. It doesn't resolve the issue, but I think its a good stop-gap solution for 0.5. A "full" fix would be very involved (and maybe not worth the added complexity).
Removing the checks on this line https://github.com/bevyengine/bevy/blob/main/crates/bevy_sprite/src/frustum_culling.rs#L64 and running the "many_sprites" example revealed two corner case bugs in bevy_ecs. The first, a simple and honest missed line introduced in #1471. The other, an insidious monster that has been there since the ECS v2 rewrite, just waiting for the time to strike:
1. #1471 accidentally removed the "insert" line for sparse set components with the "mutated" bundle state. Re-adding it fixes the problem. I did a slight refactor here to make the implementation simpler and remove a branch.
2. The other issue is nastier. ECS v2 added an "archetype graph". When determining what components were added/mutated during an archetype change, we read the FromBundle edge (which encodes this state) on the "new" archetype. The problem is that unlike "add edges" which are guaranteed to be unique for a given ("graph node", "bundle id") pair, FromBundle edges are not necessarily unique:
```rust
// OLD_ARCHETYPE -> NEW_ARCHETYPE
// [] -> [usize]
e.insert(2usize);
// [usize] -> [usize, i32]
e.insert(1i32);
// [usize, i32] -> [usize, i32]
e.insert(1i32);
// [usize, i32] -> [usize]
e.remove::<i32>();
// [usize] -> [usize, i32]
e.insert(1i32);
```
Note that the second `e.insert(1i32)` command has a different "archetype graph edge" than the first, but they both lead to the same "new archetype".
The fix here is simple: just remove FromBundle edges because they are broken and store the information in the "add edges", which are guaranteed to be unique.
FromBundle edges were added to cut down on the number of archetype accesses / make the archetype access patterns nicer. But benching this change resulted in no significant perf changes and the addition of get_2_mut() for archetypes resolves the access pattern issue.
In the current impl, next clears out the entire stack and replaces it with a new state. This PR moves this functionality into a replace method, and changes the behavior of next to only change the top state.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
This PR adds two systems to the sprite module that culls Sprites and AtlasSprites that are not within the camera's view.
This is achieved by removing / adding a new `Viewable` Component dynamically.
Some of the render queries now use a `With<Viewable>` filter to only process the sprites that are actually on screen, which improves performance drastically for scene swith a large amount of sprites off-screen.
https://streamable.com/vvzh2u
This scene shows a map with a 320x320 tiles, with a grid size of 64p.
This is exactly 102400 Sprites in the entire scene.
Without this PR, this scene runs with 1 to 4 FPS.
With this PR..
.. at 720p, there are around 600 visible sprites and runs at ~215 FPS
.. at 1440p there are around 2000 visible sprites and runs at ~135 FPS
The Systems this PR adds take around 1.2ms (with 100K+ sprites in the scene)
Note:
This is only implemented for Sprites and AtlasTextureSprites.
There is no culling for 3D in this PR.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
I'm opening this prematurely; consider this an RFC that predates RFCs and therefore not super-RFC-like.
This PR does two "big" things: decouple run criteria from system sets, reimagine system sets as weapons of mass system description.
### What it lets us do:
* Reuse run criteria within a stage.
* Pipe output of one run criteria as input to another.
* Assign labels, dependencies, run criteria, and ambiguity sets to many systems at the same time.
### Things already done:
* Decoupled run criteria from system sets.
* Mass system description superpowers to `SystemSet`.
* Implemented `RunCriteriaDescriptor`.
* Removed `VirtualSystemSet`.
* Centralized all run criteria of `SystemStage`.
* Extended system descriptors with per-system run criteria.
* `.before()` and `.after()` for run criteria.
* Explicit order between state driver and related run criteria. Fixes#1672.
* Opt-in run criteria deduplication; default behavior is to panic.
* Labels (not exposed) for state run criteria; state run criteria are deduplicated.
### API issues that need discussion:
* [`FixedTimestep::step(1.0).label("my label")`](eaccf857cd/crates/bevy_ecs/src/schedule/run_criteria.rs (L120-L122)) and [`FixedTimestep::step(1.0).with_label("my label")`](eaccf857cd/crates/bevy_core/src/time/fixed_timestep.rs (L86-L89)) are both valid but do very different things.
---
I will try to maintain this post up-to-date as things change. Do check the diffs in "edited" thingy from time to time.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
Resolves#1253#1562
This makes the Commands apis consistent with World apis. This moves to a "type state" pattern (like World) where the "current entity" is stored in an `EntityCommands` builder.
In general this tends to cuts down on indentation and line count. It comes at the cost of needing to type `commands` more and adding more semicolons to terminate expressions.
I also added `spawn_bundle` to Commands because this is a common enough operation that I think its worth providing a shorthand.
Updates the requirements on [fixedbitset](https://github.com/bluss/fixedbitset) to permit the latest version.
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a href="https://github.com/bluss/fixedbitset/commits">compare view</a></li>
</ul>
</details>
<br />
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
</details>
This is a rebase of StarArawns PBR work from #261 with IngmarBitters work from #1160 cherry-picked on top.
I had to make a few minor changes to make some intermediate commits compile and the end result is not yet 100% what I expected, so there's a bit more work to do.
Co-authored-by: John Mitchell <toasterthegamer@gmail.com>
Co-authored-by: Ingmar Bitter <ingmar.bitter@gmail.com>
Fixes#1692
Alternative to #1696
This ensures that the capacity actually grows in increments of grow_amount, and also ensures that Table capacity is always <= column and entity vec capacity.
Debug logs that describe the new logic (running the example in #1692)
[out.txt](https://github.com/bevyengine/bevy/files/6173808/out.txt)
Alternative to #1203 and #1611
Camera bindings have historically been "hacked in". They were _required_ in all shaders and only supported a single Mat4. PBR (#1554) requires the CameraView matrix, but adding this using the "hacked" method forced users to either include all possible camera data in a single binding (#1203) or include all possible bindings (#1611).
This approach instead assigns each "active camera" its own RenderResourceBindings, which are populated by CameraNode. The PassNode then retrieves (and initializes) the relevant bind groups for all render pipelines used by visible entities.
* Enables any number of camera bindings , including zero (with any set or binding number ... set 0 should still be used to avoid rebinds).
* Renames Camera binding to CameraViewProj
* Adds CameraView binding
# Problem Definition
The current change tracking (via flags for both components and resources) fails to detect changes made by systems that are scheduled to run earlier in the frame than they are.
This issue is discussed at length in [#68](https://github.com/bevyengine/bevy/issues/68) and [#54](https://github.com/bevyengine/bevy/issues/54).
This is very much a draft PR, and contributions are welcome and needed.
# Criteria
1. Each change is detected at least once, no matter the ordering.
2. Each change is detected at most once, no matter the ordering.
3. Changes should be detected the same frame that they are made.
4. Competitive ergonomics. Ideally does not require opting-in.
5. Low CPU overhead of computation.
6. Memory efficient. This must not increase over time, except where the number of entities / resources does.
7. Changes should not be lost for systems that don't run.
8. A frame needs to act as a pure function. Given the same set of entities / components it needs to produce the same end state without side-effects.
**Exact** change-tracking proposals satisfy criteria 1 and 2.
**Conservative** change-tracking proposals satisfy criteria 1 but not 2.
**Flaky** change tracking proposals satisfy criteria 2 but not 1.
# Code Base Navigation
There are three types of flags:
- `Added`: A piece of data was added to an entity / `Resources`.
- `Mutated`: A piece of data was able to be modified, because its `DerefMut` was accessed
- `Changed`: The bitwise OR of `Added` and `Changed`
The special behavior of `ChangedRes`, with respect to the scheduler is being removed in [#1313](https://github.com/bevyengine/bevy/pull/1313) and does not need to be reproduced.
`ChangedRes` and friends can be found in "bevy_ecs/core/resources/resource_query.rs".
The `Flags` trait for Components can be found in "bevy_ecs/core/query.rs".
`ComponentFlags` are stored in "bevy_ecs/core/archetypes.rs", defined on line 446.
# Proposals
**Proposal 5 was selected for implementation.**
## Proposal 0: No Change Detection
The baseline, where computations are performed on everything regardless of whether it changed.
**Type:** Conservative
**Pros:**
- already implemented
- will never miss events
- no overhead
**Cons:**
- tons of repeated work
- doesn't allow users to avoid repeating work (or monitoring for other changes)
## Proposal 1: Earlier-This-Tick Change Detection
The current approach as of Bevy 0.4. Flags are set, and then flushed at the end of each frame.
**Type:** Flaky
**Pros:**
- already implemented
- simple to understand
- low memory overhead (2 bits per component)
- low time overhead (clear every flag once per frame)
**Cons:**
- misses systems based on ordering
- systems that don't run every frame miss changes
- duplicates detection when looping
- can lead to unresolvable circular dependencies
## Proposal 2: Two-Tick Change Detection
Flags persist for two frames, using a double-buffer system identical to that used in events.
A change is observed if it is found in either the current frame's list of changes or the previous frame's.
**Type:** Conservative
**Pros:**
- easy to understand
- easy to implement
- low memory overhead (4 bits per component)
- low time overhead (bit mask and shift every flag once per frame)
**Cons:**
- can result in a great deal of duplicated work
- systems that don't run every frame miss changes
- duplicates detection when looping
## Proposal 3: Last-Tick Change Detection
Flags persist for two frames, using a double-buffer system identical to that used in events.
A change is observed if it is found in the previous frame's list of changes.
**Type:** Exact
**Pros:**
- exact
- easy to understand
- easy to implement
- low memory overhead (4 bits per component)
- low time overhead (bit mask and shift every flag once per frame)
**Cons:**
- change detection is always delayed, possibly causing painful chained delays
- systems that don't run every frame miss changes
- duplicates detection when looping
## Proposal 4: Flag-Doubling Change Detection
Combine Proposal 2 and Proposal 3. Differentiate between `JustChanged` (current behavior) and `Changed` (Proposal 3).
Pack this data into the flags according to [this implementation proposal](https://github.com/bevyengine/bevy/issues/68#issuecomment-769174804).
**Type:** Flaky + Exact
**Pros:**
- allows users to acc
- easy to implement
- low memory overhead (4 bits per component)
- low time overhead (bit mask and shift every flag once per frame)
**Cons:**
- users must specify the type of change detection required
- still quite fragile to system ordering effects when using the flaky `JustChanged` form
- cannot get immediate + exact results
- systems that don't run every frame miss changes
- duplicates detection when looping
## [SELECTED] Proposal 5: Generation-Counter Change Detection
A global counter is increased after each system is run. Each component saves the time of last mutation, and each system saves the time of last execution. Mutation is detected when the component's counter is greater than the system's counter. Discussed [here](https://github.com/bevyengine/bevy/issues/68#issuecomment-769174804). How to handle addition detection is unsolved; the current proposal is to use the highest bit of the counter as in proposal 1.
**Type:** Exact (for mutations), flaky (for additions)
**Pros:**
- low time overhead (set component counter on access, set system counter after execution)
- robust to systems that don't run every frame
- robust to systems that loop
**Cons:**
- moderately complex implementation
- must be modified as systems are inserted dynamically
- medium memory overhead (4 bytes per component + system)
- unsolved addition detection
## Proposal 6: System-Data Change Detection
For each system, track which system's changes it has seen. This approach is only worth fully designing and implementing if Proposal 5 fails in some way.
**Type:** Exact
**Pros:**
- exact
- conceptually simple
**Cons:**
- requires storing data on each system
- implementation is complex
- must be modified as systems are inserted dynamically
## Proposal 7: Total-Order Change Detection
Discussed [here](https://github.com/bevyengine/bevy/issues/68#issuecomment-754326523). This proposal is somewhat complicated by the new scheduler, but I believe it should still be conceptually feasible. This approach is only worth fully designing and implementing if Proposal 5 fails in some way.
**Type:** Exact
**Pros:**
- exact
- efficient data storage relative to other exact proposals
**Cons:**
- requires access to the scheduler
- complex implementation and difficulty grokking
- must be modified as systems are inserted dynamically
# Tests
- We will need to verify properties 1, 2, 3, 7 and 8. Priority: 1 > 2 = 3 > 8 > 7
- Ideally we can use identical user-facing syntax for all proposals, allowing us to re-use the same syntax for each.
- When writing tests, we need to carefully specify order using explicit dependencies.
- These tests will need to be duplicated for both components and resources.
- We need to be sure to handle cases where ambiguous system orders exist.
`changing_system` is always the system that makes the changes, and `detecting_system` always detects the changes.
The component / resource changed will be simple boolean wrapper structs.
## Basic Added / Mutated / Changed
2 x 3 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs before `detecting_system`
- verify at the end of tick 2
## At Least Once
2 x 3 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs after `detecting_system`
- verify at the end of tick 2
## At Most Once
2 x 3 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs once before `detecting_system`
- increment a counter based on the number of changes detected
- verify at the end of tick 2
## Fast Detection
2 x 3 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs before `detecting_system`
- verify at the end of tick 1
## Ambiguous System Ordering Robustness
2 x 3 x 2 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs [before/after] `detecting_system` in tick 1
- `changing_system` runs [after/before] `detecting_system` in tick 2
## System Pausing
2 x 3 design:
- Resources vs. Components
- Added vs. Changed vs. Mutated
- `changing_system` runs in tick 1, then is disabled by run criteria
- `detecting_system` is disabled by run criteria until it is run once during tick 3
- verify at the end of tick 3
## Addition Causes Mutation
2 design:
- Resources vs. Components
- `adding_system_1` adds a component / resource
- `adding system_2` adds the same component / resource
- verify the `Mutated` flag at the end of the tick
- verify the `Added` flag at the end of the tick
First check tests for: https://github.com/bevyengine/bevy/issues/333
Second check tests for: https://github.com/bevyengine/bevy/issues/1443
## Changes Made By Commands
- `adding_system` runs in Update in tick 1, and sends a command to add a component
- `detecting_system` runs in Update in tick 1 and 2, after `adding_system`
- We can't detect the changes in tick 1, since they haven't been processed yet
- If we were to track these changes as being emitted by `adding_system`, we can't detect the changes in tick 2 either, since `detecting_system` has already run once after `adding_system` :(
# Benchmarks
See: [general advice](https://github.com/bevyengine/bevy/blob/master/docs/profiling.md), [Criterion crate](https://github.com/bheisler/criterion.rs)
There are several critical parameters to vary:
1. entity count (1 to 10^9)
2. fraction of entities that are changed (0% to 100%)
3. cost to perform work on changed entities, i.e. workload (1 ns to 1s)
1 and 2 should be varied between benchmark runs. 3 can be added on computationally.
We want to measure:
- memory cost
- run time
We should collect these measurements across several frames (100?) to reduce bootup effects and accurately measure the mean, variance and drift.
Entity-component change detection is much more important to benchmark than resource change detection, due to the orders of magnitude higher number of pieces of data.
No change detection at all should be included in benchmarks as a second control for cases where missing changes is unacceptable.
## Graphs
1. y: performance, x: log_10(entity count), color: proposal, facet: performance metric. Set cost to perform work to 0.
2. y: run time, x: cost to perform work, color: proposal, facet: fraction changed. Set number of entities to 10^6
3. y: memory, x: frames, color: proposal
# Conclusions
1. Is the theoretical categorization of the proposals correct according to our tests?
2. How does the performance of the proposals compare without any load?
3. How does the performance of the proposals compare with realistic loads?
4. At what workload does more exact change tracking become worth the (presumably) higher overhead?
5. When does adding change-detection to save on work become worthwhile?
6. Is there enough divergence in performance between the best solutions in each class to ship more than one change-tracking solution?
# Implementation Plan
1. Write a test suite.
2. Verify that tests fail for existing approach.
3. Write a benchmark suite.
4. Get performance numbers for existing approach.
5. Implement, test and benchmark various solutions using a Git branch per proposal.
6. Create a draft PR with all solutions and present results to team.
7. Select a solution and replace existing change detection.
Co-authored-by: Brice DAVIER <bricedavier@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
fixes#1599
* Added doc on `Transform` and `GlobalTransform` to describe usage and how `GlobalTransform` is updated
* Documented all methods on `Transform`
* `#[doc(hidden)]` most constructors and methods mutating `GlobalTransform`, documented the other
* Mentioned z-ordering for `Transform` in 2d
Many a game will provide some sort of video settings where a window mode option is a common inclusion. I ran into problems, however, with [egui's](https://github.com/emilk/egui) `combo_box` that imposes a `PartialEq` necessity. Deriving the trait would fix this problem, and as this does not break any existing API it should be a non-controversial change.
`Color` can now be from different color spaces or representation:
- sRGB
- linear RGB
- HSL
This fixes#1193 by allowing the creation of const colors of all types, and writing it to the linear RGB color space for rendering.
I went with an enum after trying with two different types (`Color` and `LinearColor`) to be able to use the different variants in all place where a `Color` is expected.
I also added the HLS representation because:
- I like it
- it's useful for some case, see example `contributors`: I can just change the saturation and lightness while keeping the hue of the color
- I think adding another variant not using `red`, `green`, `blue` makes it clearer there are differences
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
Fixes#1100
Implementors must make sure that `Reflect::any` and `Reflect::any_mut` both return the `self` reference passed in (both for logical correctness and downcast safety).
fixes#1161, fixes#1243
this adds two systems:
- first is keeping an hashmap of textures and their containing color materials, then listening to events on textures to select color materials that should be updated
- second is chained to send a modified event for all color materials that need updating
An alternative to StateStages that uses SystemSets. Also includes pop and push operations since this was originally developed for my personal project which needed them.
Error message noticed in #1475
When an asset type hasn't been added to the app but a load was attempted, the error message wasn't helpful:
```
thread 'IO Task Pool (0)' panicked at 'Failed to find AssetLifecycle for label Some("Mesh0/Primitive0"), which has an asset type 8ecbac0f-f545-4473-ad43-e1f4243af51e. Are you sure that is a registered asset type?', /.cargo/git/checkouts/bevy-f7ffde730c324c74/89a41bc/crates/bevy_asset/src/asset_server.rs:435:17
```
means that
```rust
.add_asset::<bevy::render::prelude::Mesh>()
```
needs to be added.
* type name was not given, only UUID, which may make it hard to identify type across bevy/plugins
* instruction were not helpful as the `register_asset_type` method is not public
new error message:
```
thread 'IO Task Pool (1)' panicked at 'Failed to find AssetLifecycle for label 'Some("Mesh0/Primitive0")', which has an asset type "bevy_render::mesh::mesh::Mesh" (UUID 8ecbac0f-f545-4473-ad43-e1f4243af51e). Are you sure this asset type has been added to your app builder?', /bevy/crates/bevy_asset/src/asset_server.rs:435:17
```
As mentioned in #1609.
I'm not sure if this is desirable, but on top of factoring the `set` and `set_untracked` methods I added a warning when the return value of `set` isn't used to mitigate similar issues.
I silenced it for the only occurence where it's currently done 68606934e3/crates/bevy_asset/src/asset_server.rs (L468)
This removes the `GltfError::UnsupportedMinFilter` error.
I don't think this error should have existed in the first place, because it prevents users from using assets that bevy could totally render (without mipmap support as of yet).
It's much better to load the asset properly and then render it (even if it looks a little ugly), than to refuse to load the asset at all, giving users a confusing error.
it's a followup of #1550
I think calling explicit methods/values instead of default makes the code easier to read: "what is `Quat::default()`" vs "Oh, it's `Quat::IDENTITY`"
`Transform::identity()` and `GlobalTransform::identity()` can also be consts and I replaced the calls to their `default()` impl with `identity()`
Fixes all warnings from `cargo doc --all`.
Those related to code blocks were introduced in #1612, but re-formatting using the experimental features in `rustfmt.toml` doesn't seem to reintroduce them.
These are largely targeted at beginners, as `Entity`, `Component` and `System` are the most obvious terms to search when first getting introduced to Bevy.
Idea being this would be easier to grasp for end-users. Problem with the logical defaults is this breaks current setups, because light will become 20 times less bright. But most folks won't have customized this resource or will not have used `..Default::default()` due to lack of other fields.
That override was added to support pre 1.45 Versions of Rust, but Bevy requires currently the latest stable rust release.
This means that the reason for the override doesn't apply anymore.
Removes `get_unchecked` and `get_unchecked_mut` from `Tables` and `Archetypes` collections in favor of safe Index implementations. This fixes a safety error in `Archetypes::get_id_or_insert()` (which previously relied on TableId being valid to be safe ... the alternative was to make that method unsafe too). It also cuts down on a lot of unsafe and makes the code easier to look at. I'm not sure what changed since the last benchmark, but these numbers are more favorable than my last tests of similar changes. I didn't include the Components collection as those severely killed perf last time I tried. But this does inspire me to try again (just in a separate pr)!
Note that the `simple_insert/bevy_unbatched` benchmark fluctuates a lot on both branches (this was also true for prior versions of bevy). It seems like the allocator has more variance for many small allocations. And `sparse_frag_iter/bevy` operates on such a small scale that 10% fluctuations are common.
Some benches do take a small hit here, but I personally think its worth it.
This also fixes a safety error in Query::for_each_mut, which needed to mutably borrow Query (aaahh!).
![image](https://user-images.githubusercontent.com/2694663/110726926-2b52eb80-81cf-11eb-9ea3-bff951060c7c.png)
![image](https://user-images.githubusercontent.com/2694663/110726991-4c1b4100-81cf-11eb-9199-ca79bef0b9bd.png)
* Adds labels and orderings to systems that need them (uses the new many-to-many labels for InputSystem)
* Removes the Event, PreEvent, Scene, and Ui stages in favor of First, PreUpdate, and PostUpdate (there is more collapsing potential, such as the Asset stages and _maybe_ removing First, but those have more nuance so they should be handled separately)
* Ambiguity detection now prints component conflicts
* Removed broken change filters from flex calculation (which implicitly relied on the z-update system always modifying translation.z). This will require more work to make it behave as expected so i just removed it (and it was already doing this work every frame).
Should fix https://github.com/bevyengine/bevy/issues/1516.
I don't have any devices available to test this tbh but I feel like this was the only spot that could be causing a panic.
@ptircylinder since you posted this issue, could you please try to run the example on this branch and check if you get the same behavior while using your device? Thank you!
This is an effort to provide the correct `#[reflect_value(...)]` attributes where they are needed.
Supersedes #1533 and resolves#1528.
---
I am working under the following assumptions (thanks to @bjorn3 and @Davier for advice here):
- Any `enum` that derives `Reflect` and one or more of { `Serialize`, `Deserialize`, `PartialEq`, `Hash` } needs a `#[reflect_value(...)]` attribute containing the same subset of { `Serialize`, `Deserialize`, `PartialEq`, `Hash` } that is present on the derive.
- Same as above for `struct` and `#[reflect(...)]`, respectively.
- If a `struct` is used as a component, it should also have `#[reflect(Component)]`
- All reflected types should be registered in their plugins
I treated the following as components (added `#[reflect(Component)]` if necessary):
- `bevy_render`
- `struct RenderLayers`
- `bevy_transform`
- `struct GlobalTransform`
- `struct Parent`
- `struct Transform`
- `bevy_ui`
- `struct Style`
Not treated as components:
- `bevy_math`
- `struct Size<T>`
- `struct Rect<T>`
- Note: The updates for `Size<T>` and `Rect<T>` in `bevy::math::geometry` required using @Davier's suggestion to add `+ PartialEq` to the trait bound. I then registered the specific types used over in `bevy_ui` such as `Size<Val>`, etc. in `bevy_ui`'s plugin, since `bevy::math` does not contain a plugin.
- `bevy_render`
- `struct Color`
- `struct PipelineSpecialization`
- `struct ShaderSpecialization`
- `enum PrimitiveTopology`
- `enum IndexFormat`
Not Addressed:
- I am not searching for components in Bevy that are _not_ reflected. So if there are components that are not reflected that should be reflected, that will need to be figured out in another PR.
- I only added `#[reflect(...)]` or `#[reflect_value(...)]` entries for the set of four traits { `Serialize`, `Deserialize`, `PartialEq`, `Hash` } _if they were derived via `#[derive(...)]`_. I did not look for manual trait implementations of the same set of four, nor did I consider any traits outside the four. Are those other possibilities something that needs to be looked into?
* Systems can now have more than one label attached to them.
* System labels no longer have to be unique in the stage.
Code like this is now possible:
```rust
SystemStage::parallel()
.with_system(system_0.system().label("group one").label("first"))
.with_system(system_1.system().label("group one").after("first"))
.with_system(system_2.system().after("group one"))
```
I've opted to use only the system name in ambiguity reporting, which previously was only a fallback; this, obviously, is because labels aren't one-to-one with systems anymore. We could allow users to name systems to improve this; we'll then have to think about whether or not we want to allow using the name as a label (this would, effectively, introduce implicit labelling, not all implications of which are clear to me yet wrt many-to-many labels).
Dependency cycle errors are reported using the system names and only the labels that form the cycle, with each system-system "edge" in the cycle represented as one or several labels.
Slightly unrelated: `.before()` and `.after()` with a label not attached to any system no longer crashes, and logs a warning instead. This is necessary to, for example, allow plugins to specify execution order with systems of potentially missing other plugins.