Commit graph

2833 commits

Author SHA1 Message Date
François
89f4943157 exact sized event iterators (#3863)
# Objective

- Remove `Resource` binding on events, introduce a new `Event` trait
- Ensure event iterators are `ExactSizeIterator`

## Solution

- Builds on #2382 and #2969

## Changelog

- Events<T>, EventWriter<T>, EventReader<T> and so on now require that the underlying type is Event, rather than Resource. Both of these are trivial supertraits of Send + Sync + 'static with universal blanket implementations: this change is currently purely cosmetic.
- Event reader iterators now implement ExactSizeIterator
2022-05-09 13:19:32 +00:00
François
9cd6025ba1 fix re-adding a plugin to a plugin group (#2039)
In a `PluginGroupBuilder`, when adding a plugin that was already in the group (potentially disabled), it was then added twice to the app builder when calling `finish`. As the plugin is kept in an `HashMap`, it is not possible to have the same plugins twice with different configuration.

This PR updates the order of the plugin group so that each plugin is present only once.

Co-authored-by: François <8672791+mockersf@users.noreply.github.com>
2022-05-09 13:06:22 +00:00
Robert Swain
76829f938e Add a fun skinned mesh stress test based on the animated_fox example (#4674)
# Objective

- Add a stress test for skinned meshes

https://user-images.githubusercontent.com/302146/167111578-55a7d58a-0ec8-4735-a043-f084f0ff3939.mp4
2022-05-08 02:57:00 +00:00
Alice Cecile
d867b61688 Stop labeling PRs with Needs-Triage (#4686)
# Objective

- New PRs are labeled with Needs-Triage, but this is unhelpful and creates busy work: it's just as easy to check for unlabelled PRs, especially now that we no longer have an unlabelled backlog.

Note: this is not true for issues. Issues start with at least one label based on which template they use, and so there's no good way to filter for issues that need attention from the triage team.

## Solution

- Remove responsible CI tasks.
2022-05-07 06:20:13 +00:00
François
743bd30bc7 use const Vec2 in lights cluster and bounding box when possible (#4602)
# Objective

- noticed a few Vec3 and Vec2 that could be const

## Solution

- Declared them as const
- It seems to make a tiny improvement in example `many_light`, but given that the change is not complex at all it could still be worth it
2022-05-06 22:05:45 +00:00
Yutao Yuan
aabc47f290 Make public macros more robust with $crate (#4655)
# Objective

We have some macros that are public but only used internally for now. They fail on user's code due to the use of crate names like `bevy_utils`, while the user only has `bevy::utils`. There are two affected macros.

- `bevy_utils::define_label`: it may be useful in user's code for defining custom kinds of label traits (this is why I made this PR).
- `bevy_asset::load_internal_asset`: not useful currently due to limitations of the debug asset server, but this may change in the future.

## Solution

We can make them work by using `$crate` instead of names of their own crates, which can refer to the macro's defining crate regardless of the user's setup. Even though our objective is rather low-priority here, the solution adds no maintenance cost so it is still worthwhile.
2022-05-06 19:29:45 +00:00
François
068e9eaae8 simple tool to compare traces between executions (#4628)
# Objective

- Have an easy way to compare spans between executions

## Solution

- Add a tool to compare spans from chrome traces

```bash
> cargo run --release  -p spancmp -- --help
   Compiling spancmp v0.1.0
    Finished release [optimized] target(s) in 1.10s
     Running `target/release/spancmp --help`
spancmp

USAGE:
    spancmp [OPTIONS] <TRACE> [SECOND_TRACE]

ARGS:
    <TRACE>
    <SECOND_TRACE>

OPTIONS:
    -h, --help                     Print help information
    -p, --pattern <PATTERN>        Filter spans by name matching the pattern
    -t, --threshold <THRESHOLD>    Filter spans that have an average shorther than the threshold
                                   [default: 0]
```

for each span, it will display the count, minimum duration, average duration and max duration. It can be filtered by a pattern on the span name or by a minimum average duration.

just displaying a trace
![Screenshot 2022-04-28 at 21 56 21](https://user-images.githubusercontent.com/8672791/165835310-f465c6f2-9e6b-4808-803e-884b06e49292.png)

comparing two traces
![Screenshot 2022-04-28 at 21 56 55](https://user-images.githubusercontent.com/8672791/165835353-097d266b-a70c-41b8-a8c1-27804011dc97.png)



Co-authored-by: Robert Swain <robert.swain@gmail.com>
2022-05-06 19:29:44 +00:00
bjorn3
d46cf69b7b Add the license for the FiraMono font (#3589)
I copied the license from https://github.com/mozilla/Fira/blob/master/LICENSE. The fact that the license file was missing came up in a discussion on [discord](https://discord.com/channels/691052431525675048/695741366520512563/929332683149017119).
2022-05-06 19:29:43 +00:00
Jakob Hellermann
d63b7e9568 some cleanup for bevy_ptr (#4668)
1. change `PtrMut::as_ptr(self)` and `OwnedPtr::as_ptr(self)` to take `&self`, otherwise printing the pointer will prevent doing anything else afterwards
2. make all `as_ptr` methods safe. There's nothing unsafe about obtaining a pointer, these kinds of methods are safe in std as well [str::as_ptr](https://doc.rust-lang.org/stable/std/primitive.str.html#method.as_ptr), [Rc::as_ptr](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#method.as_ptr)
3. rename `offset`/`add` to `byte_offset`/`byte_add`. The unprefixed methods in std add in increments of `std::mem::size_of::<T>`, not in bytes. There's a PR for rust to add these byte_ methods https://github.com/rust-lang/rust/pull/95643 and at the call site it makes it much more clear that you need to do `.byte_add(i * layout_size)` instead of `.add(i)`
2022-05-06 19:15:24 +00:00
Daniel McNab
ec805e9e07 Apply buffers in ParamSet (#4677)
# Objective

- Fix https://github.com/bevyengine/bevy/issues/4676

## Solution

- Fixes https://github.com/bevyengine/bevy/issues/4676
- I have no reason to think this isn't sound, but `ParamSet` is a bit spooky
2022-05-06 18:52:26 +00:00
Boxy
96b4956126 Fix CI (#4675) 2022-05-06 18:27:37 +00:00
Daniel McNab
b731ebad1b Allow closing windows at runtime (#3575)
# Objective

Fixes #3180, builds from https://github.com/bevyengine/bevy/pull/2898

## Solution

Support requesting a window to be closed and closing a window in `bevy_window`, and handle this in `bevy_winit`.

This is a stopgap until we move to windows as entites, which I'm sure I'll get around to eventually.

## Changelog

### Added

- `Window::close` to allow closing windows.
- `WindowClosed` to allow reacting to windows being closed.

### Changed

Replaced `bevy::system::exit_on_esc_system` with `bevy:🪟:close_on_esc`.

## Fixed

The app no longer exits when any window is closed. This difference is only observable when there are multiple windows. 

## Migration Guide

`bevy::input::system::exit_on_esc_system` has been removed. Use `bevy:🪟:close_on_esc` instead.
`CloseWindow` has been removed. Use `Window::close` instead.
The `Close` variant has been added to `WindowCommand`. Handle this by closing the relevant window.
2022-05-05 13:35:43 +00:00
Nionidh
558530871d StorageBuffer uses wrong type to calculate the buffer size. (#4557)
# Objective
Fixes #4556

## Solution
StorageBuffer must use the Size of the std430 representation to calculate the buffer size, as the std430 representation is the data that will be written to it.
2022-05-05 02:12:16 +00:00
Dusty DeWeese
82d849d3dc Add support for vertex colors (#4528)
# Objective

Add support for vertex colors

## Solution

This change is modeled after how vertex tangents are handled, so the shader is conditionally compiled with vertex color support if the mesh has the corresponding attribute set.

Vertex colors are multiplied by the base color. I'm not sure if this is the best for all cases, but may be useful for modifying vertex colors without creating a new mesh.

I chose `VertexFormat::Float32x4`, but I'd prefer 16-bit floats if/when support is added.

## Changelog

### Added
- Vertex colors can be specified using the `Mesh::ATTRIBUTE_COLOR` mesh attribute.
2022-05-05 00:46:32 +00:00
Rob Parrett
f8e0fc190a Add RegularPolygon and Circle meshes (#3730)
# Objective

Bevy users often want to create circles and other simple shapes.

All the machinery is in place to accomplish this, and there are external crates that help. But when writing code for e.g. a new bevy example, it's not really possible to draw a circle without bringing in a new asset, writing a bunch of scary looking mesh code, or adding a dependency.

In particular, this PR was inspired by this interaction in another PR: https://github.com/bevyengine/bevy/pull/3721#issuecomment-1016774535

## Solution

This PR adds `shape::RegularPolygon` and `shape::Circle` (which is just a `RegularPolygon` that defaults to a large number of sides)

## Discussion

There's a lot of ongoing discussion about shapes in <https://github.com/bevyengine/rfcs/pull/12> and at least one other lingering shape PR (although it seems incomplete).

That RFC currently includes `RegularPolygon` and `Circle` shapes, so I don't think that having working mesh generation code in the engine for those shapes would add much burden to an author of an implementation.

But if we'd prefer not to add additional shapes until after that's sorted out, I'm happy to close this for now.

## Alternatives for users

For any users stumbling on this issue, here are some plugins that will help if you need more shapes.

https://github.com/Nilirad/bevy_prototype_lyon
https://github.com/johanhelsing/bevy_smud
https://github.com/Weasy666/bevy_svg
https://github.com/redpandamonium/bevy_more_shapes
https://github.com/ForesightMiningSoftwareCorporation/bevy_polyline
2022-05-05 00:03:47 +00:00
David Taralla
f02bea5bfc Make Wireframe respect visible entities (#4660)
# Objective

- Make meshes with a Wireframe component not render if they are not in the VisibleEntities list of a given camera
- See [discussion](https://discord.com/channels/691052431525675048/742884593551802431/971392761972527144) on the Bevy Engine Discord
- Fixes this kind of issues:
![image](https://user-images.githubusercontent.com/1733200/166746303-39003d57-8b07-4ae2-9ddf-bacdb04e7d84.png)
Camera for the RenderTexture in the bottom left is set to only see layer 1 entities. The three colored lines are on the render layer 1, but not the sphere (which has a Wireframe component).

## Solution

- Mimick what is done in [bevy_pbr/src/material.rs#L307](479f43bbf3/crates/bevy_pbr/src/material.rs (L307)) for [bevy_pbr/src/wireframe.rs#L106](2b6e67f4cb/crates/bevy_pbr/src/wireframe.rs (L106))
- Credits to beep for finding this out!
2022-05-04 22:28:16 +00:00
Charles
3f4ac65682 set alpha_mode based on alpha value (#4658)
# Objective

- When spawning a sprite the alpha is used for transparency, but when using the `Color::into()` implementation to spawn a `StandardMaterial`, the alpha is ignored.
- Pretty much everytime I want to make something transparent I started with a `Color::rgb().into()` and I'm always surprised that it doesn't work when changing it to  `Color::rgba().into()`
- It's possible there's an issue with this approach I am not thinking of, but I'm not sure what's the point of setting an alpha value without the goal of making a color transparent.

## Solution

- Set the alpha_mode to AlphaMode::Blend when the alpha is not the default value.

---

## Migration Guide

This is not a breaking change, but it can easily be migrated to reduce boilerplate

```rust
commands.spawn_bundle(PbrBundle {
    mesh: meshes.add(shape::Cube::default().into()),
    material: materials.add(StandardMaterial {
        base_color: Color::rgba(1.0, 0.0, 0.0, 0.75),
        alpha_mode: AlphaMode::Blend,
        ..default()
    }),
    ..default()
});

// becomes

commands.spawn_bundle(PbrBundle {
    mesh: meshes.add(shape::Cube::default().into()),
    material: materials.add(Color::rgba(1.0, 0.0, 0.0, 0.75).into()),
    ..default()
});
```


Co-authored-by: Charles <IceSentry@users.noreply.github.com>
2022-05-04 22:10:20 +00:00
Jakob Hellermann
1e322d9f76 bevy_ptr standalone crate (#4653)
# Objective

The pointer types introduced in #3001 are useful not just in `bevy_ecs`, but also in crates like `bevy_reflect` (#4475) or even outside of bevy.

## Solution

Extract `Ptr<'a>`, `PtrMut<'a>`, `OwnedPtr<'a>`, `ThinSlicePtr<'a, T>` and `UnsafeCellDeref` from `bevy_ecs::ptr` into `bevy_ptr`.

**Note:** `bevy_ecs` still reexports the `bevy_ptr` as `bevy_ecs::ptr` so that crates like `bevy_transform` can use the `Bundle` derive without needing to depend on `bevy_ptr` themselves.
2022-05-04 19:16:10 +00:00
Daniel McNab
9d440fbcb5 Make RunOnce a non-manual System impl (#3922)
# Objective

- `RunOnce` was a manual `System` implementation.
- Adding run criteria to stages was yet to be systemyoten

## Solution

- Make it a normal function
- yeet

##  Changelog

- Replaced `RunOnce` with `ShouldRun::once`

## Migration guide

The run criterion `RunOnce`, which would make the controlled systems run only once, has been replaced with a new run criterion function `ShouldRun::once`. Replace all instances of `RunOnce` with `ShouldRun::once`.
2022-05-04 18:41:37 +00:00
James Liu
3e24b725af Pointerfication followup: Type safety and cleanup (#4621)
# Objective
The `Ptr` types gives free access to the underlying `NonNull<u8>`, which adds more publicly visible pointer wrangling than there needs to be. There are also a few edge cases where Ptr types could be more readily utilized for properly validating the soundness of ECS operations.

## Solution
 - Replace `*Ptr(Mut)::inner` with `cast` which requires a concrete type to give the pointer. This function could also have a `debug_assert` with an alignment check to ensure that the pointer is aligned properly, but is currently not included.
 - Use `OwningPtr::read` in ECS macros over casting the inner pointer around.
2022-05-03 20:07:58 +00:00
François
4a9932fa8e simplified API to get NDC from camera and world position (#4041)
# Objective

- After #3412, `Camera::world_to_screen` got a little bit uglier to use by needing to provide both `Windows` and `Assets<Image>`, even though only one would be needed b697e73c3d/crates/bevy_render/src/camera/camera.rs (L117-L123)
- Some time, exact coordinates are not needed but normalized device coordinates is enough

## Solution

- Add a function to just get NDC
2022-05-03 19:51:18 +00:00
Jakob Hellermann
2b6e67f4cb add #[reflect(Default)] to create default value for reflected types (#3733)
### Problem
It currently isn't possible to construct the default value of a reflected type. Because of that, it isn't possible to use `add_component` of `ReflectComponent` to add a new component to an entity because you can't know what the initial value should be.

### Solution

1. add `ReflectDefault` type
```rust
#[derive(Clone)]
pub struct ReflectDefault {
    default: fn() -> Box<dyn Reflect>,
}

impl ReflectDefault {
    pub fn default(&self) -> Box<dyn Reflect> {
        (self.default)()
    }
}

impl<T: Reflect + Default> FromType<T> for ReflectDefault {
    fn from_type() -> Self {
        ReflectDefault {
            default: || Box::new(T::default()),
        }
    }
}
```

2. add `#[reflect(Default)]` to all component types that implement `Default` and are user facing (so not `ComputedSize`, `CubemapVisibleEntities` etc.)



This makes it possible to add the default value of a component to an entity without any compile-time information:

```rust
fn main() {
    let mut app = App::new();
    app.register_type::<Camera>();

    let type_registry = app.world.get_resource::<TypeRegistry>().unwrap();
    let type_registry = type_registry.read();

    let camera_registration = type_registry.get(std::any::TypeId::of::<Camera>()).unwrap();
    let reflect_default = camera_registration.data::<ReflectDefault>().unwrap();
    let reflect_component = camera_registration
        .data::<ReflectComponent>()
        .unwrap()
        .clone();

    let default = reflect_default.default();

    drop(type_registry);

    let entity = app.world.spawn().id();
    reflect_component.add_component(&mut app.world, entity, &*default);

    let camera = app.world.entity(entity).get::<Camera>().unwrap();
    dbg!(&camera);
}
```

### Open questions
- should we have `ReflectDefault` or `ReflectFromWorld` or both?
2022-05-03 19:20:13 +00:00
Robert Swain
479f43bbf3 Filter material handles on extraction (#4178)
# Objective

- While optimising many_cubes, I noticed that all material handles are extracted regardless of whether the entity to which the handle belongs is visible or not. As such >100k handles are extracted when only <20k are visible.

## Solution

- Only extract material handles of visible entities.
- This improves `many_cubes -- sphere` from ~42fps to ~48fps. It reduces not only the extraction time but also system commands time. `Handle<StandardMaterial>` extraction and its system commands went from 0.522ms + 3.710ms respectively, to 0.267ms + 0.227ms an 88% reduction for this system for this case. It's very view dependent but...
2022-05-03 18:28:04 +00:00
François
b5feb9ae9b can specify chrome tracing file (#4618)
# Objective

- I want to have the trace file at a predictable path

## Solution

- Adds an environment variable that is used as the path when it's set
2022-05-03 15:35:04 +00:00
Robert Swain
5cb6f7ffd2 Do not create nor execute render passes which have no phase items to draw (#4643)
# Objective

- Creating and executing render passes has GPU overhead. If there are no phase items in the render phase to draw, then this overhead should not be incurred as it has no benefit.

## Solution

- Check if there are no phase items to draw, and if not, do not construct not execute the render pass

---

## Changelog

- Changed: Do not create nor execute empty render passes
2022-05-02 20:22:30 +00:00
François
4dbf857393 CI tool usage (#3876)
# Objective

- Original objective was to add doc build warning check to the ci local execution
- I somewhat deviated and changed other things...

## Solution

`cargo run -p ci` can now take more parameters:
* `format` - cargo fmt
* `clippy` - clippy
* `compile-fail` - bevy_ecs_compile_fail_tests tests
* `test` - tests but not doc tests and do not build examples
* `doc-test` - doc tests
* `doc-check` - doc build and warnings
* `bench-check` - check that benches build
* `example-check` - check that examples build
* `lints` - group - run lints and format and clippy
* `doc` - group - run doc-test and doc-check
* `compile` - group - run compile-fail and bench-check and example-check
* not providing a parameter will run everything

Ci is using those when possible:
* `build` jobs now don't run doc tests and don't build examples. it makes this job faster, but doc tests and examples are not built for each architecture target
* `ci` job doesn't run the `compile-fail` part but only format and clippy, taking less time
* `check-benches` becomes `check-compiles` and runs the `compile` tasks. It takes longer. I also fixed how it was using cache
* `check-doc` job is now independent and also run the doc tests, so it takes longer. I commented out the deadlinks check as it takes 2.5 minutes (to install) and doesn't work
2022-05-02 19:13:34 +00:00
François
b863c90fe8 GitHub Actions: don't depend on patch versions (#4646)
# Objective

- don't depend on patch versions in GitHub Actions to avoid dependant frequent updates (like #4641, #4584)
2022-05-02 18:45:02 +00:00
Alice Cecile
241a61d2a5 Clean up advice on glob imports in style guide (#4644)
# Objective

- Example was misleading, as we never import `bevy` itself in the engine (except in integration tests).

## Solution

- Clean up wording.

## Context

Noticed by @mockersf in #4608.
2022-05-02 18:45:00 +00:00
TheRawMeatball
5ca78b1e27 Add get_change_ticks method to EntityRef and EntityMut (#2539)
Direct access to the change ticks is useful for integrating the reliable change detection with external stuff.
2022-05-02 18:44:58 +00:00
Alice Cecile
3fbe3683d9 Improve debugging tools for change detection (#4160)
# Objective

1. Previously, the `change_tick` and `last_change_tick` fields on `SystemChangeTick` [were `pub`](https://docs.rs/bevy/0.6.1/bevy/ecs/system/struct.SystemChangeTick.html).
   1.  This was actively misleading, as while this can be fetched as a `SystemParam`, a copy is returned instead
2. This information could be useful for debugging, but there was no way to investigate when data was changed.
3. There were no docs!

## Solution

1. Move these to a getter method.
2. Add `last_changed` method to the `DetectChanges` trait to enable inspection of when data was last changed.
3. Add docs.

# Changelog

 `SystemChangeTick` now provides getter methods for the current and previous change tick, rather than public fields.
 This can be combined with `DetectChanges::last_changed()` to debug the timing of changes.

# Migration guide

The `change_tick` and `last_change_tick` fields on `SystemChangeTick` are now private, use the corresponding getter method instead.
2022-05-02 18:26:52 +00:00
robtfm
b9f738da8d move system_param fetch struct into anonymous scope to avoid name collisions (#4100)
# Objective

avoid naming collisions with user structs when deriving ``system_param``.

## Solution

~rename the fetch struct created by ``#[derive(system_param)]`` from ``{}State`` to ``{}SysParamState``.~
place the fetch struct into an anonymous scope.

## Migration Guide

For code that was using a system param's fetch struct, such as ``EventReader``'s ``EventReaderState``, the fetch struct can now be identified via the SystemParam trait associated type ``Fetch``, e.g. for ``EventReader<T>`` it can be identified as ``<EventReader<'static, 'static, T> as SystemParam>::Fetch``
2022-05-02 18:26:50 +00:00
Daniel McNab
a011f4d53c Make Transform propagation correct in the presence of updated children (#4608)
Supercedes https://github.com/bevyengine/bevy/pull/3340, and absorbs the test from there.

# Objective

- Fixes #3329

## Solution

- If the `Children` component has changed, we currently do not have a way to know how it has changed.
- Therefore, we must update the hierarchy downwards  from that point to be correct.

Co-authored-by: Daniel McNab <36049421+DJMcNab@users.noreply.github.com>
2022-05-02 18:04:49 +00:00
MrGVSV
4c194084b4 bevy_reflect: Add GetTypeRegistration impl for reflected tuples (#4226)
# Objective

Reflected tuples do not implement `GetTypeRegistration`, preventing us from registering our tuples, like:

```rust
app.register_type::<(i32, i32)>();
```

This is especially important for things like using #4042 to improve the scene format or implementing #4154 to recursively register fields.

## Solution

Added an implementation to the tuple macro:

```rust
impl<$($name: Reflect + for<'de> Deserialize<'de>),*> GetTypeRegistration for ($($name,)*) {
  fn get_type_registration() -> TypeRegistration {
    let mut registration = TypeRegistration::of::<($($name,)*)>();
    registration.insert::<ReflectDeserialize>(FromType::<($($name,)*)>::from_type());
    registration
  }
}
```

This requires that the tuple's types implement `Deserialize`. This is exactly how `Vec` and `HashMap` handle it:

```rust
impl<T: FromReflect + for<'de> Deserialize<'de>> GetTypeRegistration for Vec<T> {
  fn get_type_registration() -> TypeRegistration {
    let mut registration = TypeRegistration::of::<Vec<T>>();
    registration.insert::<ReflectDeserialize>(FromType::<Vec<T>>::from_type());
    registration
  }
}
```
2022-05-02 18:04:48 +00:00
Johannes Hackel
e29bd50de8 Add file metadata to AssetIo (#2123)
This is a replacement for #2106

This adds a `Metadata` struct which contains metadata information about a file, at the moment only the file type.
It also adds a `get_metadata` to `AssetIo` trait and an `asset_io` accessor method to `AssetServer` and `LoadContext`

I am not sure about the changes in `AndroidAssetIo ` and `WasmAssetIo`.
2022-05-02 18:04:47 +00:00
Alice Cecile
8283db69b4 Remind users to initialize their systems before running them (#3947)
# Objective

- Manually running systems is a somewhat obscure process: systems must be initialized before they are run
- The unwrap is rather hard to debug.

## Solution

- Replace unwraps in `FunctionSystem` methods with expects (progress towards #3892).
- Briefly document this requirement.
2022-05-02 16:04:49 +00:00
Rob Parrett
61a3494a06 Add 3d shapes example (#4613)
# Objective

- As requested here: https://github.com/bevyengine/bevy/pull/4520#issuecomment-1109302039
- Make it easier to spot issues with built-in shapes

## Solution

https://user-images.githubusercontent.com/200550/165624709-c40dfe7e-0e1e-4bd3-ae52-8ae66888c171.mp4

- Add an example showcasing the built-in 3d shapes with lighting/shadows
- Rotate objects in such a way that all faces are seen by the camera
- Add a UV debug texture

## Discussion

I'm not sure if this is what @alice-i-cecile had in mind, but I adapted the little "torus playground" from the issue linked above to include all built-in shapes.

This exact arrangement might not be particularly scalable if many more shapes are added. Maybe a slow camera pan, or cycling with the keyboard or on a timer, or a sidebar with buttons would work better. If one of the latter options is used, options for showing wireframes or computed flat normals might add some additional utility.

Ideally, I think we'd have a better way of visualizing normals.

Happy to rework this or close it if there's not a consensus around it being useful.
2022-05-02 13:20:56 +00:00
KDecay
51509a9a3e Change gamepad.rs tuples to normal structs (#4519)
# Objective

- Part of the splitting process of #3692.

## Solution

- Remove / change the tuple structs inside of `gamepad.rs` of `bevy_input` to normal structs.

## Reasons

- It made the `gamepad_connection_system` cleaner.
- It made the `gamepad_input_events.rs` example cleaner (which is probably the most notable change for the user facing API).
- Tuple structs are not descriptive (`.0`, `.1`).
- Using tuple structs for more than 1 field is a bad idea (This means that the `Gamepad` type might be fine as a tuple struct, but I still prefer normal structs over tuple structs).

Feel free to discuss this change as this is more or less just a matter of taste.

## Changelog

### Changed

- The `Gamepad`, `GamepadButton`, `GamepadAxis`, `GamepadEvent` and `GamepadEventRaw` types are now normal structs instead of tuple structs and have a `new()` function.

## Migration Guide

- The `Gamepad`, `GamepadButton`, `GamepadAxis`, `GamepadEvent` and `GamepadEventRaw` types are now normal structs instead of tuple structs and have a `new()` function. To migrate change every instantiation to use the `new()` function instead and use the appropriate field names instead of `.0` and `.1`.
2022-05-02 13:20:55 +00:00
Ian Johnson
e9db69af81 Tidy up PluginGroupBuilder by moving Plugin index retrieval to it's own function (#4446)
# Objective

- Clean up duplicate code in the add_before/add_after functions in PluginGroupBuilder.

## Solution

- moved index retrieval code to a private function index_of() for the PluginGroupBuilder.
- change is just tidying up. No real change to functionality.
2022-05-02 13:20:54 +00:00
Yutao Yuan
2c145826a3 Fix type parameter name conflicts of derive(Bundle) (#4636)
# Objective

This code currently fails to compile with error ``the name `T` is already used for a generic parameter in this item's generic parameters``, because `T` is also used in code generated by `derive(Bundle)`.

```rust
#[derive(Bundle)]
struct MyBundle<T: Component> {
    component: T,
}
```

## Solution

Add double underscores to type parameter names in `derive(Bundle)`.
2022-05-02 11:58:51 +00:00
研究社交
e49542b026 Rename transparent_phase to opaque_phase in wireframe.rs (#4639)
# Objective

- Meshes are queued in opaque phase instead of transparent phase when drawing wireframes.
- There is a name mismatch.

## Solution

- Rename `transparent_phase` to `opaque_phase` in `wireframe.rs`.
2022-05-02 04:11:55 +00:00
Thomas Hansen
7d21ca3744 Add alsa-lib-devel to OpenSUSE dependencies (#4635)
Needed for compilation, tumbleweed. This PR adds the needed alsa package for OpenSUSE to the documentation.
2022-05-01 01:00:27 +00:00
Boxy
b9102b8836 Introduce tests for derive(WorldQuery) (#4625)
The only tests we had for `derive(WorldQuery)` checked that the derive doesnt panic/emit a `compiler_error!`. This PR adds tests that actually assert the returned values of a query using the derived `WorldQuery` impl. Also adds a compile fail test to check that we correctly error on read only world queries containing mutable world queries.
2022-04-28 21:06:20 +00:00
Olexorus
990d5c0879 Make AnimationClip::duration return value instead of reference (#4617)
Tiny follow-up to https://github.com/bevyengine/bevy/pull/4615 as discussed on Discord here: https://discord.com/channels/691052431525675048/692572690833473578/968945307767414855

Since f32 is `Copy` and smaller than a reference on most systems (or at least not larger), there's no reason not to copy it, which should be more convenient to use.
2022-04-27 23:44:06 +00:00
TheRawMeatball
73c78c3667 Use lifetimed, type erased pointers in bevy_ecs (#3001)
# Objective

`bevy_ecs` has large amounts of unsafe code which is hard to get right and makes it difficult to audit for soundness.

## Solution

Introduce lifetimed, type-erased pointers: `Ptr<'a>` `PtrMut<'a>` `OwningPtr<'a>'` and `ThinSlicePtr<'a, T>` which are newtypes around a raw pointer with a lifetime and conceptually representing strong invariants about the pointee and validity of the pointer.

The process of converting bevy_ecs to use these has already caught multiple cases of unsound behavior.

## Changelog

TL;DR for release notes: `bevy_ecs` now uses lifetimed, type-erased pointers internally, significantly improving safety and legibility without sacrificing performance. This should have approximately no end user impact, unless you were meddling with the (unfortunately public) internals of `bevy_ecs`.

- `Fetch`, `FilterFetch` and `ReadOnlyFetch` trait no longer have a `'state` lifetime
    - this was unneeded
- `ReadOnly/Fetch` associated types on `WorldQuery` are now on a new `WorldQueryGats<'world>` trait
    - was required to work around lack of Generic Associated Types (we wish to express `type Fetch<'a>: Fetch<'a>`)
- `derive(WorldQuery)` no longer requires `'w` lifetime on struct
    - this was unneeded, and improves the end user experience
- `EntityMut::get_unchecked_mut` returns `&'_ mut T` not `&'w mut T`
    - allows easier use of unsafe API with less footguns, and can be worked around via lifetime transmutery as a user
- `Bundle::from_components` now takes a `ctx` parameter to pass to the `FnMut` closure
    - required because closure return types can't borrow from captures
- `Fetch::init` takes `&'world World`, `Fetch::set_archetype` takes `&'world Archetype` and `&'world Tables`, `Fetch::set_table` takes `&'world Table`
    - allows types implementing `Fetch` to store borrows into world
- `WorldQuery` trait now has a `shrink` fn to shorten the lifetime in `Fetch::<'a>::Item`
    - this works around lack of subtyping of assoc types, rust doesnt allow you to turn `<T as Fetch<'static>>::Item'` into `<T as Fetch<'a>>::Item'`
    - `QueryCombinationsIter` requires this
- Most types implementing `Fetch` now have a lifetime `'w`
    - allows the fetches to store borrows of world data instead of using raw pointers

## Migration guide

- `EntityMut::get_unchecked_mut` returns a more restricted lifetime, there is no general way to migrate this as it depends on your code
- `Bundle::from_components` implementations must pass the `ctx` arg to `func`
- `Bundle::from_components` callers have to use a fn arg instead of closure captures for borrowing from world
- Remove lifetime args on `derive(WorldQuery)` structs as it is nonsensical
- `<Q as WorldQuery>::ReadOnly/Fetch` should be changed to either `RO/QueryFetch<'world>` or `<Q as WorldQueryGats<'world>>::ReadOnly/Fetch`
- `<F as Fetch<'w, 's>>` should be changed to `<F as Fetch<'w>>`
- Change the fn sigs of `Fetch::init/set_archetype/set_table` to match respective trait fn sigs
- Implement the required `fn shrink` on any `WorldQuery` implementations
- Move assoc types `Fetch` and `ReadOnlyFetch` on `WorldQuery` impls to `WorldQueryGats` impls
- Pass an appropriate `'world` lifetime to whatever fetch struct you are for some reason using

### Type inference regression

in some cases rustc may give spurrious errors when attempting to infer the `F` parameter on a query/querystate this can be fixed by manually specifying the type, i.e. `QueryState:🆕:<_, ()>(world)`. The error is rather confusing:

```rust=
error[E0271]: type mismatch resolving `<() as Fetch<'_>>::Item == bool`
    --> crates/bevy_pbr/src/render/light.rs:1413:30
     |
1413 |             main_view_query: QueryState::new(world),
     |                              ^^^^^^^^^^^^^^^ expected `bool`, found `()`
     |
     = note: required because of the requirements on the impl of `for<'x> FilterFetch<'x>` for `<() as WorldQueryGats<'x>>::Fetch`
note: required by a bound in `bevy_ecs::query::QueryState::<Q, F>::new`
    --> crates/bevy_ecs/src/query/state.rs:49:32
     |
49   |     for<'x> QueryFetch<'x, F>: FilterFetch<'x>,
     |                                ^^^^^^^^^^^^^^^ required by this bound in `bevy_ecs::query::QueryState::<Q, F>::new`
```

---

Made with help from @BoxyUwU and @alice-i-cecile 

Co-authored-by: Boxy <supbscripter@gmail.com>
2022-04-27 23:44:06 +00:00
bjorn3
ddce22b614 Decouple some dependencies (#3886)
# Objective

Reduce from scratch build time.

## Solution

Reduce the size of the critical path by removing dependencies between crates where not necessary. For `cargo check --no-default-features` this reduced build time from ~51s to ~45s. For some commits I am not completely sure if the tradeoff between build time reduction and convenience caused by the commit is acceptable. If not, I can drop them.
2022-04-27 19:08:11 +00:00
Nathan Pinard
f1aae380ab Added example of creating a system from a closure (#4327)
Fixes #4262
2022-04-27 18:02:07 +00:00
Nicola Papale
71a246ce9e Improve QueryIter size_hint hints (#4244)
## Objective

This fixes #1686.

`size_hint` can be useful even if a little niche. For example,
`collect::<Vec<_>>()` uses the `size_hint` of Iterator it collects from
to pre-allocate a memory slice large enough to not require re-allocating
when pushing all the elements of the iterator.

## Solution

To this effect I made the following changes:
* Add a `IS_ARCHETYPAL` associated constant to the `Fetch` trait,
  this constant tells us when it is safe to assume that the `Fetch`
  relies exclusively on archetypes to filter queried entities
* Add `IS_ARCHETYPAL` to all the implementations of `Fetch`
* Use that constant in `QueryIter::size_hint` to provide a more useful

## Migration guide

The new associated constant is an API breaking change. For the user,
if they implemented a custom `Fetch`, it means they have to add this
associated constant to their implementation. Either `true` if it doesn't limit
the number of entities returned in a query beyond that of archetypes, or
`false` for when it does.
2022-04-27 18:02:06 +00:00
Christopher Durham
3d4e0066f4 Move float_ord from bevy_core to bevy_utils (#4189)
# Objective

Reduce the catch-all grab-bag of functionality in bevy_core by moving FloatOrd to bevy_utils.

A step in addressing #2931 and splitting bevy_core into more specific locations.

## Solution

Move FloatOrd into bevy_utils. Fix the compile errors.

As a result, bevy_core_pipeline, bevy_pbr, bevy_sprite, bevy_text, and bevy_ui no longer depend on bevy_core (they were only using it for `FloatOrd` previously).
2022-04-27 18:02:05 +00:00
Spooky Th Ghost
8e03634457 Public access for AnimationClip.duration (#4615)
# Objective

- Small change that better facilitates custom animation systems

## Solution

- Added a public access function to `bevy::animation::AnimationClip`, making duration publicly readable

---
2022-04-27 17:37:30 +00:00
Daniel McNab
328c26d02c Add an example to test small window sizes (#3597)
# Objective

We keep getting issues where things break at small window sizes, e.g #3368 (caused by #3153), #3596 ('caused' by #3545)

## Solution

- Add a test that we can make small windows.


Currently, this fails on my machine with some quite scary vulkan errors: 
```
2022-01-08T22:55:13.770261Z ERROR wgpu_hal::vulkan::instance: VALIDATION [VUID-VkSwapchainCreateInfoKHR-imageExtent-01274 (0x7cd0911d)]
        Validation Error: [ VUID-VkSwapchainCreateInfoKHR-imageExtent-01274 ] Object 0: handle = 0x1adbd410a60, type = VK_OBJECT_TYPE_DEVICE; | MessageID = 0x7cd0911d | vkCreateSwapchainKHR() called with imageExtent = (225,60), which is outside the bounds returned by vkGetPhysicalDeviceSurfaceCapabilitiesKHR(): currentExtent = (225,56), minImageExtent = (225,56), maxImageExtent = (225,56). The Vulkan spec states: imageExtent must be between minImageExtent and maxImageExtent, inclusive, where minImageExtent and maxImageExtent are members of the VkSurfaceCapabilitiesKHR structure returned by vkGetPhysicalDeviceSurfaceCapabilitiesKHR for the surface (https://vulkan.lunarg.com/doc/view/1.2.198.1/windows/1.2-extensions/vkspec.html#VUID-VkSwapchainCreateInfoKHR-imageExtent-01274)
2022-01-08T22:55:13.770808Z ERROR wgpu_hal::vulkan::instance:   objects: (type: DEVICE, hndl: 0x1adbd410a60, name: ?)
2022-01-08T22:55:13.787403Z ERROR wgpu_hal::vulkan::instance: VALIDATION [VUID-VkSwapchainCreateInfoKHR-imageExtent-01274 (0x7cd0911d)]
        Validation Error: [ VUID-VkSwapchainCreateInfoKHR-imageExtent-01274 ] Object 0: handle = 0x1adbd410a60, type = VK_OBJECT_TYPE_DEVICE; | MessageID = 0x7cd0911d | vkCreateSwapchainKHR() called with imageExtent = (225,56), which is outside the bounds returned by vkGetPhysicalDeviceSurfaceCapabilitiesKHR(): currentExtent = (225,52), minImageExtent = (225,52), maxImageExtent = (225,52). The Vulkan spec states: imageExtent must be between minImageExtent and maxImageExtent, inclusive, where minImageExtent and maxImageExtent are members of the VkSurfaceCapabilitiesKHR structure returned by vkGetPhysicalDeviceSurfaceCapabilitiesKHR for the surface (https://vulkan.lunarg.com/doc/view/1.2.198.1/windows/1.2-extensions/vkspec.html#VUID-VkSwapchainCreateInfoKHR-imageExtent-01274)
```
etc.

This might be a new issue here, although I'm surprised it's vulkan giving this error; wgpu should stop it if this is illegal.
2022-04-26 22:15:24 +00:00