Commit graph

1470 commits

Author SHA1 Message Date
François
7546624471
Improve gizmo axes example (#12335)
# Objective

- Improve example from #12299 
- Make it frame rate independent
- Make it not randomly random

## Solution

- Transitions between transforms will take 2 seconds instead of 100
frames
- Random is seeded
2024-03-08 23:05:11 +00:00
andristarr
432a4f1d85
Fix dim emissive values in lighting example (#12343)
# Objective

- Fixes #12330 

## Solution

- Increasing the emissive of the objects representing the lights.
2024-03-07 22:12:57 +00:00
Patrick Walton
dfdf2b9ea4
Implement the AnimationGraph, allowing for multiple animations to be blended together. (#11989)
This is an implementation of RFC #51:
https://github.com/bevyengine/rfcs/blob/main/rfcs/51-animation-composition.md

Note that the implementation strategy is different from the one outlined
in that RFC, because two-phase animation has now landed.

# Objective

Bevy needs animation blending. The RFC for this is [RFC 51].

## Solution

This is an implementation of the RFC. Note that the implementation
strategy is different from the one outlined there, because two-phase
animation has now landed.

This is just a draft to get the conversation started. Currently we're
missing a few things:

- [x] A fully-fleshed-out mechanism for transitions
- [x] A serialization format for `AnimationGraph`s
- [x] Examples are broken, other than `animated_fox`
- [x] Documentation

---

## Changelog

### Added

* The `AnimationPlayer` has been reworked to support blending multiple
animations together through an `AnimationGraph`, and as such will no
longer function unless a `Handle<AnimationGraph>` has been added to the
entity containing the player. See [RFC 51] for more details.

* Transition functionality has moved from the `AnimationPlayer` to a new
component, `AnimationTransitions`, which works in tandem with the
`AnimationGraph`.

## Migration Guide

* `AnimationPlayer`s can no longer play animations by themselves and
need to be paired with a `Handle<AnimationGraph>`. Code that was using
`AnimationPlayer` to play animations will need to create an
`AnimationGraph` asset first, add a node for the clip (or clips) you
want to play, and then supply the index of that node to the
`AnimationPlayer`'s `play` method.

* The `AnimationPlayer::play_with_transition()` method has been removed
and replaced with the `AnimationTransitions` component. If you were
previously using `AnimationPlayer::play_with_transition()`, add all
animations that you were playing to the `AnimationGraph`, and create an
`AnimationTransitions` component to manage the blending between them.

[RFC 51]:
https://github.com/bevyengine/rfcs/blob/main/rfcs/51-animation-composition.md

---------

Co-authored-by: Rob Parrett <robparrett@gmail.com>
2024-03-07 20:22:42 +00:00
BD103
713d91b721
Improve Bloom 3D lighting (#11981)
# Objective

- With the recent lighting changes, the default configuration in the
`bloom_3d` example is less clear what bloom actually does
- See [this
screenshot](4fdb1455d5 (r1494648414))
for a comparison.
- `bloom_3d` additionally uses a for-loop to spawn the spheres, which
can be turned into `commands::spawn_batch` call.
- The text is black, which is difficult to see on the gray background.

## Solution

- Increase emmisive values of materials.
- Set text to white.

## Showcase

Before:

<img width="1392" alt="before"
src="https://github.com/bevyengine/bevy/assets/59022059/757057ad-ed9f-4eed-b135-8e2032fcdeb5">

After:

<img width="1392" alt="image"
src="https://github.com/bevyengine/bevy/assets/59022059/3f9dc7a8-94b2-44b9-8ac3-deef1905221b">

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-03-07 15:20:38 +00:00
Antony
f67b17d80d
Use .register_asset_source() in extra_asset_source example (#12350)
# Objective

Fixes #12347.

## Solution

Use `.register_asset_source()` in `extra_asset_source` example instead
of writing part of the app state.
2024-03-07 05:44:52 +00:00
James Liu
512b7463a3
Disentangle bevy_utils/bevy_core's reexported dependencies (#12313)
# Objective
Make bevy_utils less of a compilation bottleneck. Tackle #11478.

## Solution
* Move all of the directly reexported dependencies and move them to
where they're actually used.
* Remove the UUID utilities that have gone unused since `TypePath` took
over for `TypeUuid`.
* There was also a extraneous bytemuck dependency on `bevy_core` that
has not been used for a long time (since `encase` became the primary way
to prepare GPU buffers).
* Remove the `all_tuples` macro reexport from bevy_ecs since it's
accessible from `bevy_utils`.

---

## Changelog
Removed: Many of the reexports from bevy_utils (petgraph, uuid, nonmax,
smallvec, and thiserror).
Removed: bevy_core's reexports of bytemuck.

## Migration Guide
bevy_utils' reexports of petgraph, uuid, nonmax, smallvec, and thiserror
have been removed.

bevy_core' reexports of bytemuck's types has been removed. 

Add them as dependencies in your own crate instead.
2024-03-07 02:30:15 +00:00
Turki Al-Marri
6f2ecdf822
We must have googly eyes (new Game example) (#12331)
# Objective

- We must have googly eyes.
- Also it would be nice if there was an example of a desk toy
application (like the old NEKO.EXE).

## Solution

- Created an example with googly eyed Bevy logo under
examples/games/desktoy.rs.

---

## Changelog
- Added "Desk Toy" game example showcasing window transparency and hit
test.

---------

Co-authored-by: Rob Parrett <robparrett@gmail.com>
2024-03-06 22:21:41 +00:00
François
f9e70abcac
Fix ios simulator support (#12339)
# Objective

- #12103 broke iOS simulator support, it doesn't even compile anymore

## Solution

- Fix the feature
2024-03-06 17:48:17 +00:00
James Liu
9e5db9abc7
Clean up type registrations (#12314)
# Objective
Fix #12304. Remove unnecessary type registrations thanks to #4154.

## Solution
Conservatively remove type registrations. Keeping the top level
components, resources, and events, but dropping everything else that is
a type of a member of those types.
2024-03-06 16:05:53 +00:00
NiseVoid
e3b318f599
Add extra_asset_source example (#11824)
# Objective

- Make it easier to figure out how to add asset sources

## Solution

- Add an example that adds an asset source, it functions almost
identical to the embedded_asset example
- Move the file from the embedded_asset example into a `files/` folder
2024-03-06 16:00:03 +00:00
Rob Parrett
d56e16754c
Fix "dark grey" colors becoming lighter in various examples (#12333)
# Objective

Fixes #12226

Prior to the `bevy_color` port, `DARK GRAY` used to mean "dark grey."
But it is now lighter than `GRAY`, matching the css4 spec.

## Solution

Change usages of `css::DARK_GRAY` to `Color::srgb(0.25, 0.25, 0.25)` to
restore the examples to their former colors.

With one exception: `display_and_visibility`. I think the new color is
an improvement.

## Note

A lot of these examples could use nicer colors. I'm not trying to revamp
everything here.

The css4 palette is truly a horror. See #12176 and #12080 for some
discussion about alternatives.
2024-03-06 05:19:59 +00:00
Rob Parrett
0746b8eb4c
Fix green colors becoming darker in various examples (#12328)
# Objective

Fixes #12225

Prior to the `bevy_color` port, `GREEN` used to mean "full green." But
it is now a much darker color matching the css1 spec.

## Solution

Change usages of `basic::GREEN` or `css::GREEN` to `LIME` to restore the
examples to their former colors.

This also removes the duplicate definition of `GREEN` from `css`. (it
was already re-exported from `basic`)

## Note

A lot of these examples could use nicer colors. I'm not trying to do
that here.

"Dark Grey" will be tackled separately and has its own tracking issue.
2024-03-05 23:42:03 +00:00
Rob Parrett
fea6f9d915
Use floats mathed from 8-bit values in basic color palette (#12323)
# Objective

Addresses one of the side-notes in #12225.

Colors in the `basic` palette are inconsistent in a few ways:
- `CYAN` was named `AQUA` in the referenced spec. (an alias was added in
a later spec)
- Colors are defined with e.g. "half green" having a `g` value of `0.5`.
But any spec would have been based on 8-bit color, so `0x80 / 0xFF` or
`128 / 255` or ~`0.502`. This precision is likely meaningful when doing
color math/rounding.

## Solution

Regenerate the colors from
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=37563bedc8858033bd8b8380328c5230
2024-03-05 18:05:27 +00:00
Félix Lescaudey de Maneville
fc202f2e3d
Slicing support for texture atlas (#12059)
# Objective

Follow up to #11600 and #10588 
https://github.com/bevyengine/bevy/issues/11944 made clear that some
people want to use slicing with texture atlases

## Changelog

* Added support for `TextureAtlas` slicing and tiling.
`SpriteSheetBundle` and `AtlasImageBundle` can now use `ImageScaleMode`
* Added new `ui_texture_atlas_slice` example using a texture sheet

<img width="798" alt="Screenshot 2024-02-23 at 11 58 35"
src="https://github.com/bevyengine/bevy/assets/26703856/47a8b764-127c-4a06-893f-181703777501">

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Pablo Reinhardt <126117294+pablo-lua@users.noreply.github.com>
2024-03-05 16:05:39 +00:00
James Liu
dc40cd134f
Remove ComponentStorage and associated types (#12311)
# Objective
When doing a final pass for #3362, it appeared that `ComponentStorage`
as a trait, the two types implementing it, and the associated type on
`Component` aren't really necessary anymore. This likely was due to an
earlier constraint on the use of consts in traits, but that definitely
doesn't seem to be a problem in Rust 1.76.

## Solution
Remove them.

---

## Changelog
Changed: `Component::Storage` has been replaced with
`Component::STORAGE_TYPE` as a const.
Removed: `bevy::ecs::component::ComponentStorage` trait
Removed: `bevy::ecs::component::TableStorage` struct
Removed: `bevy::ecs::component::SparseSetStorage` struct

## Migration Guide
If you were manually implementing `Component` instead of using the
derive macro, replace the associated `Storage` associated type with the
`STORAGE_TYPE` const:

```rust
// in Bevy 0.13
impl Component for MyComponent {
    type Storage = TableStorage;
}
// in Bevy 0.14
impl Component for MyComponent {
    const STORAGE_TYPE: StorageType = StorageType::Table;
}
```

Component is no longer object safe. If you were relying on `&dyn
Component`, `Box<dyn Component>`, etc. please [file an issue
](https://github.com/bevyengine/bevy/issues) to get [this
change](https://github.com/bevyengine/bevy/pull/12311) reverted.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-03-05 15:54:52 +00:00
François
9a6fc76148
remove background color from UI example image (#12306)
# Objective

- After https://github.com/bevyengine/bevy/pull/11165, example `ui` is
not pretty as it displays the Bevy logo on a white background, with a
comment that is now wrong

## Solution

- Remove the background color
2024-03-04 23:41:51 +00:00
Afonso Lage
15db61a1f8
Improve components hooks docs (#12295)
# Objective

- Closes #12256 

## Solution

- Improved component hooks docs.
- Improved component hooks example docs.

---------

Co-authored-by: James Liu <contact@jamessliu.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-03-04 19:31:10 +00:00
Matty
4673fb3e57
Example for axes gizmos (#12299)
# Objective

- Follow-up to #12211 
- Introduces an example project that demonstrates the implementation and
behavior of `Gizmos::axes` for an entity with a `Transform` component.

## Solution

In order to demonstrate how `Gizmo::axes` can be used and behaves in
practice, we introduce an example of a simple scene containing a pair of
cuboids locked in a grotesque, inscrutable dance: the two are repeatedly
given random `Transform`s which they interpolate to, showing how the
axes move with objects as they translate, rotate, and scale.

<img width="1023" alt="Screenshot 2024-03-04 at 1 16 33 PM"
src="https://github.com/bevyengine/bevy/assets/2975848/c1ff4794-6722-491c-8522-f59801645139">



On the implementation side, we demonstrate how to draw axes for
entities, automatically sizing them according to their bounding boxes
(so that the axes will be visible):
````rust
fn draw_axes(mut gizmos: Gizmos, query: Query<(&Transform, &Aabb), With<ShowAxes>>) {
    for (&transform, &aabb) in &query {
        let length = aabb.half_extents.length();
        gizmos.axes(transform, length);
    }
}
````

---

## Changelog

- Created examples/gizmos/axes.rs.
- Added 'axes' example to Cargo.toml.
2024-03-04 19:30:39 +00:00
Gino Valente
ccb9d0500f
bevy_reflect: Recursive registration (#5781)
# Objective

Resolves #4154

Currently, registration must all be done manually:

```rust
#[derive(Reflect)]
struct Foo(Bar);

#[derive(Reflect)]
struct Bar(Baz);

#[derive(Reflect)]
struct Baz(usize);

fn main() {
  // ...
  app
    .register_type::<Foo>()
    .register_type::<Bar>()
    .register_type::<Baz>()
    // .register_type::<usize>() <- This one is handled by Bevy, thankfully
  // ...
}
```

This can grow really quickly and become very annoying to add, remove,
and update as types change. It would be great if we could help reduce
the number of types that a user must manually implement themselves.

## Solution

As suggested in #4154, this PR adds automatic recursive registration.
Essentially, when a type is registered, it may now also choose to
register additional types along with it using the new
`GetTypeRegistration::register_type_dependencies` trait method.

The `Reflect` derive macro now automatically does this for all fields in
structs, tuple structs, struct variants, and tuple variants. This is
also done for tuples, arrays, `Vec<T>`, `HashMap<K, V>`, and
`Option<T>`.

This allows us to simplify the code above like:

```rust
#[derive(Reflect)]
struct Foo(Bar);

#[derive(Reflect)]
struct Bar(Baz);

#[derive(Reflect)]
struct Baz(usize);

fn main() {
  // ...
  app.register_type::<Foo>()
  // ...
}
```

This automatic registration only occurs if the type has not yet been
registered. If it has been registered, we simply skip it and move to the
next one. This reduces the cost of registration and prevents overwriting
customized registrations.

## Considerations

While this does improve ergonomics on one front, it's important to look
at some of the arguments against adopting a PR like this.

#### Generic Bounds

~~Since we need to be able to register the fields individually, we need
those fields to implement `GetTypeRegistration`. This forces users to
then add this trait as a bound on their generic arguments. This
annoyance could be relieved with something like #5772.~~

This is no longer a major issue as the `Reflect` derive now adds the
`GetTypeRegistration` bound by default. This should technically be okay,
since we already add the `Reflect` bound.

However, this can also be considered a breaking change for manual
implementations that left out a `GetTypeRegistration` impl ~~or for
items that contain dynamic types (e.g. `DynamicStruct`) since those also
do not implement `GetTypeRegistration`~~.

#### Registration Assumptions

By automatically registering fields, users might inadvertently be
relying on certain types to be automatically registered. If `Foo`
auto-registers `Bar`, but `Foo` is later removed from the code, then
anywhere that previously used or relied on `Bar`'s registration would
now fail.

---

## Changelog

- Added recursive type registration to structs, tuple structs, struct
variants, tuple variants, tuples, arrays, `Vec<T>`, `HashMap<K, V>`, and
`Option<T>`
- Added a new trait in the hidden `bevy_reflect::__macro_exports` module
called `RegisterForReflection`
- Added `GetTypeRegistration` impl for
`bevy_render::render_asset::RenderAssetUsages`

## Migration Guide

All types that derive `Reflect` will now automatically add
`GetTypeRegistration` as a bound on all (unignored) fields. This means
that all reflected fields will need to also implement
`GetTypeRegistration`.

If all fields **derive** `Reflect` or are implemented in `bevy_reflect`,
this should not cause any issues. However, manual implementations of
`Reflect` that excluded a `GetTypeRegistration` impl for their type will
need to add one.

```rust
#[derive(Reflect)]
struct Foo<T: FromReflect> {
  data: MyCustomType<T>
}

// OLD
impl<T: FromReflect> Reflect for MyCustomType<T> {/* ... */}

// NEW
impl<T: FromReflect + GetTypeRegistration> Reflect for MyCustomType<T> {/* ... */}
impl<T: FromReflect + GetTypeRegistration> GetTypeRegistration for MyCustomType<T> {/* ... */}
```

---------

Co-authored-by: James Liu <contact@jamessliu.com>
Co-authored-by: radiish <cb.setho@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2024-03-04 19:04:10 +00:00
François
b1a5aabce9
Fix failures of typos and check-cfg (#12293)
# Objective

- CI is green

## Solution

- Fix typos (#12045)
- Correctly declare features (#12100)
2024-03-04 07:48:09 +00:00
Doonv
14c20a6c9c
Add access to App within LogPlugin::update_subscriber (#12045)
# Objective

In my library,
[`bevy_dev_console`](https://github.com/doonv/bevy_dev_console) I need
access to `App` within `LogPlugin::update_subscriber` in order to
communicate with the `App` from my custom `Layer`.

## Solution

Give access to `App`.

---

## Changelog

- Added access to `App` within `LogPlugin::update_subscriber`

## Migration Guide

`LogPlugin::update_subscriber` now has a `&mut App` parameter. If you
don't need access to `App`, you can ignore the parameter with an
underscore (`_`).

```diff,rust
- fn update_subscriber(subscriber: BoxedSubscriber) -> BoxedSubscriber {
+ fn update_subscriber(_: &mut App, subscriber: BoxedSubscriber) -> BoxedSubscriber {
      Box::new(subscriber.with(CustomLayer))
  }
```
2024-03-04 00:01:05 +00:00
François
faa2ce4d55
fix example lightmaps after color migration (#12265)
# Objective

- Since #12163 example lightmaps is more dull
<img width="1280" alt="Screenshot 2024-03-02 at 23 04 36"
src="https://github.com/bevyengine/bevy/assets/8672791/7736f420-b9c5-4870-93f6-b5b992c4768a">


## Solution

- Use a srgba color, as it was before:

b24ab2e9fb/examples/3d/lightmaps.rs (L39)

b24ab2e9fb/crates/bevy_render/src/color/mod.rs (L132)

<img width="1280" alt="Screenshot 2024-03-02 at 23 05 09"
src="https://github.com/bevyengine/bevy/assets/8672791/451187ed-8612-456f-ad25-180d5f774188">
2024-03-03 21:36:11 +00:00
Ben Frankel
e8ae0d6c49
Decouple BackgroundColor from UiImage (#11165)
# Objective

Fixes https://github.com/bevyengine/bevy/issues/11157.

## Solution

Stop using `BackgroundColor` as a color tint for `UiImage`. Add a
`UiImage::color` field for color tint instead. Allow a UI node to
simultaneously include a solid-color background and an image, with the
image rendered on top of the background (this is already how it works
for e.g. text).


![2024-02-29_1709239666_563x520](https://github.com/bevyengine/bevy/assets/12173779/ec50c9ef-4c7f-4ab8-a457-d086ce5b3425)

---

## Changelog

- The `BackgroundColor` component now renders a solid-color background
behind `UiImage` instead of tinting its color.
- Removed `BackgroundColor` from `ImageBundle`, `AtlasImageBundle`, and
`ButtonBundle`.
- Added `UiImage::color`.
- Expanded `RenderUiSystem` variants.
- Renamed `bevy_ui::extract_text_uinodes` to `extract_uinodes_text` for
consistency.

## Migration Guide

- `BackgroundColor` no longer tints the color of UI images. Use
`UiImage::color` for that instead.
- For solid color buttons, replace `ButtonBundle { background_color:
my_color.into(), ... }` with `ButtonBundle { image:
UiImage::default().with_color(my_color), ... }`, and update button
interaction systems to use `UiImage::color` instead of `BackgroundColor`
as well.
- `bevy_ui::RenderUiSystem::ExtractNode` has been split into
`ExtractBackgrounds`, `ExtractImages`, `ExtractBorders`, and
`ExtractText`.
- `bevy_ui::extract_uinodes` has been split into
`bevy_ui::extract_uinode_background_colors` and
`bevy_ui::extract_uinode_images`.
- `bevy_ui::extract_text_uinodes` has been renamed to
`extract_uinode_text`.
2024-03-03 21:35:50 +00:00
Ben Frankel
6e83439a06
Deprecate SpriteSheetBundle and AtlasImageBundle (#12218)
# Objective

After the `TextureAtlas` changes that landed in 0.13,
`SpriteSheetBundle` is equivalent to `TextureAtlas` + `SpriteBundle` and
`AtlasImageBundle` is equivalent to `TextureAtlas` + `ImageBundle`. As
such, the atlas bundles aren't particularly useful / necessary additions
to the API anymore.

In addition, atlas bundles are inconsistent with `ImageScaleMode` (also
introduced in 0.13) which doesn't have its own version of each image
bundle.

## Solution

Deprecate `SpriteSheetBundle` and `AtlasImageBundle` in favor of
including `TextureAtlas` as a separate component alongside
`SpriteBundle` and `ImageBundle`, respectively.

---

## Changelog

- Deprecated `SpriteSheetBundle` and `AtlasImageBundle`.

## Migration Guide

- `SpriteSheetBundle` has been deprecated. Use `TextureAtlas` alongside
a `SpriteBundle` instead.
- `AtlasImageBundle` has been deprecated. Use `TextureAtlas` alongside
an `ImageBundle` instead.
2024-03-03 20:11:15 +00:00
Kanabenki
de0ed293fa
Add basic light gizmos (#12228)
# Objective

- Part of #9400.
- Add light gizmos for `SpotLight`, `PointLight` and `DirectionalLight`.

## Solution

- Add a `ShowLightGizmo` and its related gizmo group and plugin, that
shows a gizmo for all lights of an entities when inserted on it. Light
display can also be toggled globally through the gizmo config in the
same way it can already be done for `Aabb`s.
- Add distinct segment setters for height and base one `Cone3dBuilder`.
This allow having a properly rounded base without too much edges along
the height. The doc comments explain how to ensure height and base
connect when setting different values.

Gizmo for the three light types without radius with the depth bias set
to -1:

![without-radius](https://github.com/bevyengine/bevy/assets/18357657/699d0154-f367-4727-9b09-8b458d96a0e2)

With Radius:

![with-radius](https://github.com/bevyengine/bevy/assets/18357657/f3af003e-dbba-427a-a305-c5cc1676e340)

Possible future improvements:
- Add a billboarded sprite with a distinct sprite for each light type.
- Display the intensity of the light somehow (no idea how to represent
that apart from some text).

---

## Changelog

### Added

- The new `ShowLightGizmo`, part of the `LightGizmoPlugin` and
configurable globally with `LightGizmoConfigGroup`, allows drawing gizmo
for `PointLight`, `SpotLight` and `DirectionalLight`. The gizmos color
behavior can be controlled with the `LightGizmoColor` member of
`ShowLightGizmo` and `LightGizmoConfigGroup`.
- The cone gizmo builder (`Cone3dBuilder`) now allows setting a
differing number of segments for the base and height.

---------

Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
2024-03-03 18:50:46 +00:00
Thierry Berger
8cf5fbbf94
Fix fit_canvas_to_parent (#11278)
Follow up to #11057

Implemented suggestions from reviewers from: a simpler
fit_canvas_to_parent leads to an explicit CSS setting to the canvas.

From my understanding, it has do be set after wgpu creation due to wgpu
overriding the canvas width/height:
4400a58470/examples/src/utils.rs (L68-L74)


# Changelog

- Re-enable a `fit_canvas_to_parent`, it's removal from
https://github.com/bevyengine/bevy/pull/11057 was problematic. Still,
its inner working is more simple than before: bevy doesn't handle its
resizing, winit does.

## Migration Guide

- Cancels the migration from
https://github.com/bevyengine/bevy/pull/11057
2024-03-03 14:33:30 +00:00
geekvest
d5c32bdc23
remove repetitive code (#12270)
Signed-off-by: geekvest <cuimoman@sohu.com>
2024-03-03 07:58:22 +00:00
targrub
13cbb9cf10
Move commands module into bevy::ecs::world (#12234)
# Objective

Fixes https://github.com/bevyengine/bevy/issues/11628

## Migration Guide

`Command` and `CommandQueue` have migrated from `bevy_ecs::system` to
`bevy_ecs::world`, so `use bevy_ecs::world::{Command, CommandQueue};`
when necessary.
2024-03-02 23:13:45 +00:00
James O'Brien
bacd5e873b
Replace init_component_info with register_component_hooks (#12244)
# Objective

- Fix mismatch between the `Component` trait method and the `World`
method.

## Solution

- Replace init_component_info with register_component_hooks.
2024-03-02 05:27:48 +00:00
Kaur Kuut
165c360070
Update wgpu to v0.19.3 and unpin web-sys. (#12247)
# Objective

This PR unpins `web-sys` so that unrelated projects that have
`bevy_render` in their workspace can finally update their `web-sys`.
More details in and fixes #12246.

## Solution

* Update `wgpu` from 0.19.1 to 0.19.3.
* Remove the `web-sys` pin.
* Update docs and wasm helper to remove the now-stale
`--cfg=web_sys_unstable_apis` Rust flag.

---

## Changelog

Updated `wgpu` to v0.19.3 and removed `web-sys` pin.
2024-03-02 00:44:51 +00:00
Natalie Soltis
cc32610543
Add size and physical_size to window (#12238)
This is an implementation within `bevy_window::window` that fixes
#12229.

# Objective

Fixes #12229, allow users to retrieve the window's size and physical
size as Vectors without having to manually construct them using
`height()` and `width()` or `physical_height()` and `physical_width()`

## Solution

As suggested in #12229, created two public functions within `window`:
`size() -> Vec` and `physical_size() -> UVec` that return the needed
Vectors ready-to-go.

### Discussion

My first FOSS PRQ ever, so bear with me a bit. I'm new to this.

- I replaced instances of ```Vec2::new(window.width(),
window.height());``` or `UVec2::new(window.physical_width(),
window.physical_height());` within bevy examples be replaced with their
`size()`/`physical_size()` counterparts?
- Discussion within #12229 still holds: should these also be added to
WindowResolution?
2024-03-01 22:28:37 +00:00
Patrick Walton
f9cc91d5a1
Intern mesh vertex buffer layouts so that we don't have to compare them over and over. (#12216)
Although we cached hashes of `MeshVertexBufferLayout`, we were paying
the cost of `PartialEq` on `InnerMeshVertexBufferLayout` for every
entity, every frame. This patch changes that logic to place
`MeshVertexBufferLayout`s in `Arc`s so that they can be compared and
hashed by pointer. This results in a 28% speedup in the
`queue_material_meshes` phase of `many_cubes`, with frustum culling
disabled.

Additionally, this patch contains two minor changes:

1. This commit flattens the specialized mesh pipeline cache to one level
of hash tables instead of two. This saves a hash lookup.

2. The example `many_cubes` has been given a `--no-frustum-culling`
flag, to aid in benchmarking.

See the Tracy profile:

<img width="1064" alt="Screenshot 2024-02-29 144406"
src="https://github.com/bevyengine/bevy/assets/157897/18632f1d-1fdd-4ac7-90ed-2d10306b2a1e">

## Migration guide

* Duplicate `MeshVertexBufferLayout`s are now combined into a single
object, `MeshVertexBufferLayoutRef`, which contains an
atomically-reference-counted pointer to the layout. Code that was using
`MeshVertexBufferLayout` may need to be updated to use
`MeshVertexBufferLayoutRef` instead.
2024-03-01 20:56:21 +00:00
James O'Brien
94ff123d7f
Component Lifecycle Hooks and a Deferred World (#10756)
# Objective

- Provide a reliable and performant mechanism to allows users to keep
components synchronized with external sources: closing/opening sockets,
updating indexes, debugging etc.
- Implement a generic mechanism to provide mutable access to the world
without allowing structural changes; this will not only be used here but
is a foundational piece for observers, which are key for a performant
implementation of relations.

## Solution

- Implement a new type `DeferredWorld` (naming is not important,
`StaticWorld` is also suitable) that wraps a world pointer and prevents
user code from making any structural changes to the ECS; spawning
entities, creating components, initializing resources etc.
- Add component lifecycle hooks `on_add`, `on_insert` and `on_remove`
that can be assigned callbacks in user code.

---

## Changelog
- Add new `DeferredWorld` type.
- Add new world methods: `register_component::<T>` and
`register_component_with_descriptor`. These differ from `init_component`
in that they provide mutable access to the created `ComponentInfo` but
will panic if the component is already in any archetypes. These
restrictions serve two purposes:
1. Prevent users from defining hooks for components that may already
have associated hooks provided in another plugin. (a use case better
served by observers)
2. Ensure that when an `Archetype` is created it gets the appropriate
flags to early-out when triggering hooks.
- Add methods to `ComponentInfo`: `on_add`, `on_insert` and `on_remove`
to be used to register hooks of the form `fn(DeferredWorld, Entity,
ComponentId)`
- Modify `BundleInserter`, `BundleSpawner` and `EntityWorldMut` to
trigger component hooks when appropriate.
- Add bit flags to `Archetype` indicating whether or not any contained
components have each type of hook, this can be expanded for other flags
as needed.
- Add `component_hooks` example to illustrate usage. Try it out! It's
fun to mash keys.

## Safety
The changes to component insertion, removal and deletion involve a large
amount of unsafe code and it's fair for that to raise some concern. I
have attempted to document it as clearly as possible and have confirmed
that all the hooks examples are accepted by `cargo miri` as not causing
any undefined behavior. The largest issue is in ensuring there are no
outstanding references when passing a `DeferredWorld` to the hooks which
requires some use of raw pointers (as was already happening to some
degree in those places) and I have taken some time to ensure that is the
case but feel free to let me know if I've missed anything.

## Performance
These changes come with a small but measurable performance cost of
between 1-5% on `add_remove` benchmarks and between 1-3% on `insert`
benchmarks. One consideration to be made is the existence of the current
`RemovedComponents` which is on average more costly than the addition of
`on_remove` hooks due to the early-out, however hooks doesn't completely
remove the need for `RemovedComponents` as there is a chance you want to
respond to the removal of a component that already has an `on_remove`
hook defined in another plugin, so I have not removed it here. I do
intend to deprecate it with the introduction of observers in a follow up
PR.

## Discussion Questions
- Currently `DeferredWorld` implements `Deref` to `&World` which makes
sense conceptually, however it does cause some issues with rust-analyzer
providing autocomplete for `&mut World` references which is annoying.
There are alternative implementations that may address this but involve
more code churn so I have attempted them here. The other alternative is
to not implement `Deref` at all but that leads to a large amount of API
duplication.
- `DeferredWorld`, `StaticWorld`, something else?
- In adding support for hooks to `EntityWorldMut` I encountered some
unfortunate difficulties with my desired API. If commands are flushed
after each call i.e. `world.spawn() // flush commands .insert(A) //
flush commands` the entity may be despawned while `EntityWorldMut` still
exists which is invalid. An alternative was then to add
`self.world.flush_commands()` to the drop implementation for
`EntityWorldMut` but that runs into other problems for implementing
functions like `into_unsafe_entity_cell`. For now I have implemented a
`.flush()` which will flush the commands and consume `EntityWorldMut` or
users can manually run `world.flush_commands()` after using
`EntityWorldMut`.
- In order to allowing querying on a deferred world we need
implementations of `WorldQuery` to not break our guarantees of no
structural changes through their `UnsafeWorldCell`. All our
implementations do this, but there isn't currently any safety
documentation specifying what is or isn't allowed for an implementation,
just for the caller, (they also shouldn't be aliasing components they
didn't specify access for etc.) is that something we should start doing?
(see 10752)

Please check out the example `component_hooks` or the tests in
`bundle.rs` for usage examples. I will continue to expand this
description as I go.

See #10839 for a more ergonomic API built on top of this one that isn't
subject to the same restrictions and supports `SystemParam` dependency
injection.
2024-03-01 14:59:22 +00:00
Rob Parrett
bcdca068ad
Various improvements to the contributors example (#12217)
# Objective / Solution

- Use `Hsla` for the color constants (Fixes #12203)

And a few other improvements:

- Make contributor colors persistent between runs
- Move text to top left where the birbs can't reach and add padding
- Remove `Contributor:` text. It's obvious what is being shown from
context, and then we can remove `has_triggered`.
- Show the number of commits authored
- Some system names were postfixed with `_system` and some weren't.
Removed `_system` for consistency.
- Clean up collision code slightly with a bounding volume
- Someone accidentally typed "bird" instead of "birb" in one comment.
- Other misc. cleanup

## Before

<img width="1280" alt="image"
src="https://github.com/bevyengine/bevy/assets/200550/9c6229d6-313a-464d-8a97-0220aa16901f">

## After

<img width="1280" alt="image"
src="https://github.com/bevyengine/bevy/assets/200550/0c00e95b-2f50-4f50-b177-def4ca405313">
2024-03-01 14:53:48 +00:00
Alice Cecile
599e5e4e76
Migrate from LegacyColor to bevy_color::Color (#12163)
# Objective

- As part of the migration process we need to a) see the end effect of
the migration on user ergonomics b) check for serious perf regressions
c) actually migrate the code
- To accomplish this, I'm going to attempt to migrate all of the
remaining user-facing usages of `LegacyColor` in one PR, being careful
to keep a clean commit history.
- Fixes #12056.

## Solution

I've chosen to use the polymorphic `Color` type as our standard
user-facing API.

- [x] Migrate `bevy_gizmos`.
- [x] Take `impl Into<Color>` in all `bevy_gizmos` APIs
- [x] Migrate sprites
- [x] Migrate UI
- [x] Migrate `ColorMaterial`
- [x] Migrate `MaterialMesh2D`
- [x] Migrate fog
- [x] Migrate lights
- [x] Migrate StandardMaterial
- [x] Migrate wireframes
- [x] Migrate clear color
- [x] Migrate text
- [x] Migrate gltf loader
- [x] Register color types for reflection
- [x] Remove `LegacyColor`
- [x] Make sure CI passes

Incidental improvements to ease migration:

- added `Color::srgba_u8`, `Color::srgba_from_array` and friends
- added `set_alpha`, `is_fully_transparent` and `is_fully_opaque` to the
`Alpha` trait
- add and immediately deprecate (lol) `Color::rgb` and friends in favor
of more explicit and consistent `Color::srgb`
- standardized on white and black for most example text colors
- added vector field traits to `LinearRgba`: ~~`Add`, `Sub`,
`AddAssign`, `SubAssign`,~~ `Mul<f32>` and `Div<f32>`. Multiplications
and divisions do not scale alpha. `Add` and `Sub` have been cut from
this PR.
- added `LinearRgba` and `Srgba` `RED/GREEN/BLUE`
- added `LinearRgba_to_f32_array` and `LinearRgba::to_u32`

## Migration Guide

Bevy's color types have changed! Wherever you used a
`bevy::render::Color`, a `bevy::color::Color` is used instead.

These are quite similar! Both are enums storing a color in a specific
color space (or to be more precise, using a specific color model).
However, each of the different color models now has its own type.

TODO...

- `Color::rgba`, `Color::rgb`, `Color::rbga_u8`, `Color::rgb_u8`,
`Color::rgb_from_array` are now `Color::srgba`, `Color::srgb`,
`Color::srgba_u8`, `Color::srgb_u8` and `Color::srgb_from_array`.
- `Color::set_a` and `Color::a` is now `Color::set_alpha` and
`Color::alpha`. These are part of the `Alpha` trait in `bevy_color`.
- `Color::is_fully_transparent` is now part of the `Alpha` trait in
`bevy_color`
- `Color::r`, `Color::set_r`, `Color::with_r` and the equivalents for
`g`, `b` `h`, `s` and `l` have been removed due to causing silent
relatively expensive conversions. Convert your `Color` into the desired
color space, perform your operations there, and then convert it back
into a polymorphic `Color` enum.
- `Color::hex` is now `Srgba::hex`. Call `.into` or construct a
`Color::Srgba` variant manually to convert it.
- `WireframeMaterial`, `ExtractedUiNode`, `ExtractedDirectionalLight`,
`ExtractedPointLight`, `ExtractedSpotLight` and `ExtractedSprite` now
store a `LinearRgba`, rather than a polymorphic `Color`
- `Color::rgb_linear` and `Color::rgba_linear` are now
`Color::linear_rgb` and `Color::linear_rgba`
- The various CSS color constants are no longer stored directly on
`Color`. Instead, they're defined in the `Srgba` color space, and
accessed via `bevy::color::palettes::css`. Call `.into()` on them to
convert them into a `Color` for quick debugging use, and consider using
the much prettier `tailwind` palette for prototyping.
- The `LIME_GREEN` color has been renamed to `LIMEGREEN` to comply with
the standard naming.
- Vector field arithmetic operations on `Color` (add, subtract, multiply
and divide by a f32) have been removed. Instead, convert your colors
into `LinearRgba` space, and perform your operations explicitly there.
This is particularly relevant when working with emissive or HDR colors,
whose color channel values are routinely outside of the ordinary 0 to 1
range.
- `Color::as_linear_rgba_f32` has been removed. Call
`LinearRgba::to_f32_array` instead, converting if needed.
- `Color::as_linear_rgba_u32` has been removed. Call
`LinearRgba::to_u32` instead, converting if needed.
- Several other color conversion methods to transform LCH or HSL colors
into float arrays or `Vec` types have been removed. Please reimplement
these externally or open a PR to re-add them if you found them
particularly useful.
- Various methods on `Color` such as `rgb` or `hsl` to convert the color
into a specific color space have been removed. Convert into
`LinearRgba`, then to the color space of your choice.
- Various implicitly-converting color value methods on `Color` such as
`r`, `g`, `b` or `h` have been removed. Please convert it into the color
space of your choice, then check these properties.
- `Color` no longer implements `AsBindGroup`. Store a `LinearRgba`
internally instead to avoid conversion costs.

---------

Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com>
Co-authored-by: Afonso Lage <lage.afonso@gmail.com>
Co-authored-by: Rob Parrett <robparrett@gmail.com>
Co-authored-by: Zachary Harrold <zac@harrold.com.au>
2024-02-29 19:35:12 +00:00
Joona Aalto
f418de8eb6
Rename Direction2d/3d to Dir2/3 (#12189)
# Objective

Split up from #12017, rename Bevy's direction types.

Currently, Bevy has the `Direction2d`, `Direction3d`, and `Direction3dA`
types, which provide a type-level guarantee that their contained vectors
remain normalized. They can be very useful for a lot of APIs for safety,
explicitness, and in some cases performance, as they can sometimes avoid
unnecessary normalizations.

However, many consider them to be inconvenient to use, and opt for
standard vector types like `Vec3` because of this. One reason is that
the direction type names are a bit long and can be annoying to write (of
course you can use autocomplete, but just typing `Vec3` is still nicer),
and in some intances, the extra characters can make formatting worse.
The naming is also inconsistent with Glam's shorter type names, and
results in names like `Direction3dA`, which (in my opinion) are
difficult to read and even a bit ugly.

This PR proposes renaming the types to `Dir2`, `Dir3`, and `Dir3A`.
These names are nice and easy to write, consistent with Glam, and work
well for variants like the SIMD aligned `Dir3A`. As a bonus, it can also
result in nicer formatting in a lot of cases, which can be seen from the
diff of this PR.

Some examples of what it looks like: (copied from #12017)

```rust
// Before
let ray_cast = RayCast2d::new(Vec2::ZERO, Direction2d::X, 5.0);

// After
let ray_cast = RayCast2d::new(Vec2::ZERO, Dir2::X, 5.0);
```

```rust
// Before (an example using Bevy XPBD)
let hit = spatial_query.cast_ray(
    Vec3::ZERO,
    Direction3d::X,
    f32::MAX,
    true,
    SpatialQueryFilter::default(),
);

// After
let hit = spatial_query.cast_ray(
    Vec3::ZERO,
    Dir3::X,
    f32::MAX,
    true,
    SpatialQueryFilter::default(),
);
```

```rust
// Before
self.circle(
    Vec3::new(0.0, -2.0, 0.0),
    Direction3d::Y,
    5.0,
    Color::TURQUOISE,
);

// After (formatting is collapsed in this case)
self.circle(Vec3::new(0.0, -2.0, 0.0), Dir3::Y, 5.0, Color::TURQUOISE);
```

## Solution

Rename `Direction2d`, `Direction3d`, and `Direction3dA` to `Dir2`,
`Dir3`, and `Dir3A`.

---

## Migration Guide

The `Direction2d` and `Direction3d` types have been renamed to `Dir2`
and `Dir3`.

## Additional Context

This has been brought up on the Discord a few times, and we had a small
[poll](https://discord.com/channels/691052431525675048/1203087353850364004/1212465038711984158)
on this. `Dir2`/`Dir3`/`Dir3A` was quite unanimously chosen as the best
option, but of course it was a very small poll and inconclusive, so
other opinions are certainly welcome too.

---------

Co-authored-by: IceSentry <c.giguere42@gmail.com>
2024-02-28 22:48:43 +00:00
Rob Parrett
315e637bf5
Add tinting to the border in ui_texture_slice example (#11901)
# Objective

This is just a cool property of the full-white border texture we added
for this example that I think would be nice to show off.

## Solution

Add a tint to the border on hover / click.


![screenshot-100](https://github.com/bevyengine/bevy/assets/200550/a436c383-2cda-4578-999d-b89d244c993d)
2024-02-28 17:21:09 +00:00
Lynn
35cec8bd3a
Add Grid gizmos (#11988)
# Objective

- Implement grid gizmos, suggestion of #9400 

## Solution

- Added `gizmos.grid(...) ` and `gizmos.grid_2d(...)`
- The grids may be configured using `.outer_edges(...)` to specify
whether to draw the outer border/edges of the grid and `.skew(...)`to
specify the skew of the grid along the x or y directions.

---

## Changelog

- Added a `grid` module to `bevy_gizmos` containing `gizmos.grid(...) `
and `gizmos.grid_2d(...)` as well as assorted items.
- Updated the `2d_gizmos` and `3d_gizmos` examples to use grids.

## Additional

The 2D and 3D examples now look like this:
<img width="1440" alt="Screenshot 2024-02-20 at 15 09 40"
src="https://github.com/bevyengine/bevy/assets/62256001/ce04191e-d839-4faf-a6e3-49b6bb4b922b">
<img width="1440" alt="Screenshot 2024-02-20 at 15 10 07"
src="https://github.com/bevyengine/bevy/assets/62256001/317459ba-d452-42eb-ae95-7c84cdbd569b">
2024-02-28 00:18:26 +00:00
François
d261a86b9f
compute shader game of life example: use R32Float instead of Rgba8Unorm (#12155)
# Objective

- Fixes #9670 
- Avoid a crash in CI due to
```
thread 'Compute Task Pool (0)' panicked at /Users/runner/.cargo/registry/src/index.crates.io-6f17d22bba15001f/wgpu-0.19.1/src/backend/wgpu_core.rs:3009:5:
wgpu error: Validation Error

Caused by:
    In Device::create_bind_group
    The adapter does not support read access for storages texture of format Rgba8Unorm
```

## Solution

- Use an `R32Float` texture instead of an `Rgba8Unorm` as it's a tier 1
texture format https://github.com/gpuweb/gpuweb/issues/3838 and is more
supported
- This should also improve support for webgpu in the next wgpu version
2024-02-27 13:57:41 +00:00
IWonderWhatThisAPIDoes
8020805830
examples/ecs/iter_combinations: Initialize velocity using fixed timestep (#10673)
# Objective

On some platforms (observed on Windows and Linux, works fine on web),
velocity of all entities would be initialized to zero, making them
simply fall into the star.

## Solution

Using `Time<Fixed>::timestep` instead of `Time::delta_seconds` to
initialize velocity. Since the entities are generated in the startup
schedule, no time has elapsed yet and `Time::delta_seconds` would return
zero on some platforms. `Time<Fixed>::timestep` will always return the
expected time step of `FixedUpdate` schedule.
2024-02-27 01:44:50 +00:00
Nicola Papale
f7f7e326e5
Add methods to directly load assets from World (#12023)
# Objective

`FromWorld` is often used to group loading and creation of assets for
resources.

With this setup, users often end up repetitively calling
`.resource::<AssetServer>` and `.resource_mut::<Assets<T>>`, and may
have difficulties handling lifetimes of the returned references.

## Solution

Add extension methods to `World` to add and load assets, through a new
extension trait defined in `bevy_asset`.

### Other considerations

* This might be a bit too "magic", as it makes implicit the resource
access.
* We could also implement `DirectAssetAccessExt` on `App`, but it didn't
feel necessary, as `FromWorld` is the principal use-case here.

---

## Changelog

* Add the `DirectAssetAccessExt` trait, which adds the `add_asset`,
`load_asset` and `load_asset_with_settings` method to the `World` type.
2024-02-27 00:28:26 +00:00
BD103
b96193e6ca
Improve lighting in more examples (#12021)
# Objective

- #11868 changed the lighting system, forcing lights to increase their
intensity. The PR fixed most examples, but missed a few. These I later
caught in https://github.com/bevyengine/bevy-website/pull/1023.
- Related: #11982, #11981.
- While there, I noticed that the spotlight example could use a few easy
improvements.

## Solution

- Increase lighting in `skybox`, `spotlight`, `animated_transform`, and
`gltf_skinned_mesh`.
- Improve spotlight example.
- Make ground plane move with cubes, so they don't phase into each
other.
  - Batch spawn cubes.
  - Add controls text.
  - Change controls to allow rotating around spotlights.

## Showcase

### Skybox

Before:

<img width="1392" alt="image"
src="https://github.com/bevyengine/bevy/assets/59022059/8ba00d74-6d68-4414-97a8-28afb8305570">

After:

<img width="1392" alt="image"
src="https://github.com/bevyengine/bevy/assets/59022059/ad15c471-6979-4dda-9889-9189136d8404">

### Spotlight

Before:

<img width="1392" alt="image"
src="https://github.com/bevyengine/bevy/assets/59022059/53f966de-acf3-46b8-8299-0005c4cb8da0">

After:

<img width="1392" alt="image"
src="https://github.com/bevyengine/bevy/assets/59022059/05c73c1e-0739-4226-83d6-e4249a9105e0">

### Animated Transform

Before:

<img width="1392" alt="image"
src="https://github.com/bevyengine/bevy/assets/59022059/6d7d4ea0-e22e-42a5-9905-ea1731d474cf">

After:

<img width="1392" alt="image"
src="https://github.com/bevyengine/bevy/assets/59022059/f1ee08d6-d17a-4391-91a6-d903b9fbdc3c">

### gLTF Skinned Mesh

Before:

<img width="1392" alt="image"
src="https://github.com/bevyengine/bevy/assets/59022059/547569a6-d13b-4fe0-a8c1-e11f02c4f9a2">

After:

<img width="1392" alt="image"
src="https://github.com/bevyengine/bevy/assets/59022059/34517aba-09e4-4e9b-982a-a4a8b893c48a">

---

## Changelog

- Increased lighting in `skybox`, `spotlight`, `animated_transform`, and
`gltf_skinned_mesh` examples.
- Improved usability of `spotlight` example.
2024-02-26 17:32:23 +00:00
radiish
2b7a3b2a55
reflect: treat proxy types correctly when serializing (#12024)
# Objective

- Fixes #12001.
- Note this PR doesn't change any feature flags, however flaky the issue
revealed they are.

## Solution

- Use `FromReflect` to convert proxy types to concrete ones in
`ReflectSerialize::get_serializable`.
- Use `get_represented_type_info() -> type_id()` to get the correct type
id to interact with the registry in
`bevy_reflect::serde::ser::get_serializable`.

---

## Changelog

- Registering `ReflectSerialize` now imposes additional `FromReflect`
and `TypePath` bounds.

## Migration Guide

- If `ReflectSerialize` is registered on a type, but `TypePath` or
`FromReflect` implementations are omitted (perhaps by
`#[reflect(type_path = false)` or `#[reflect(from_reflect = false)]`),
the traits must now be implemented.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
2024-02-26 16:13:04 +00:00
Rob Parrett
5d941d5b91
Remove custom window size from flex_layout example (#11876)
# Objective

The example showcase doesn't seem to work well with the portrait aspect
ratio used in this example, which is possibly something to be fixed
there, but there's also no reason this *needs* a custom size.

This custom window size is also sightly too tall for my particular
display which is a very common display size when accounting for the
macOS task bar and window title, so the content at the bottom is
clipped.

## Solution

- Remove the custom window size
- Swap the order of the justify / align nested loops so that the content
fits the new aspect ratio
- Make the containers responsive to window size, and make all the gaps
even

## Before

<img width="870" alt="Screenshot 2024-02-15 at 10 56 11 AM"
src="https://github.com/bevyengine/bevy/assets/200550/803217dd-e311-4f9e-aabf-2656f7f67615">

## After

<img width="1280" alt="Screenshot 2024-02-15 at 10 56 25 AM"
src="https://github.com/bevyengine/bevy/assets/200550/bf1e4920-f053-4d42-ab0b-3efea6835cae">

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-02-26 16:04:02 +00:00
BD103
fa179ba475
Use spawn_batch in many_lights example (#11979)
# Objective

- The `many_lights` example uses a for-loop around `commands.spawn`.
- It is generally recommended to use `spawn_batch` instead to lazily
spawn entities, because it doesn't massively grow the command queue.

## Solution

- Use `spawn_batch` in `many_lights` example.

---

## Discussion

- `thread_rng` is called for each light spawned. This is a simple
thread-local `Rc` clone, so it should compile down to a copy and an
increment + decrement instruction.
- I created `golden_ration` outside of the closure and `move`d it in.
This should just be a copy and hopefully will get const-evaluated away.
Would it be better to just move it into the closure itself?

## Performance

Using `spawn_batch` seems to decrease time-to-first-`Update` by 0.1s:
1.3s to 1.2s.

<details>
  <summary>Raw data and how it was collected.</summary>

Before:

- 2024-02-19T15:18:57.650987Z to 2024-02-19T15:18:58.912244Z : 1.3
- 2024-02-19T15:19:25.277135Z to 2024-02-19T15:19:26.542092Z : 1.3
- 2024-02-19T15:19:46.841460Z to 2024-02-19T15:19:48.137560Z : 1.3

After:

- 2024-02-19T15:17:05.749521Z to 2024-02-19T15:17:06.993221Z : 1.2
- 2024-02-19T15:17:38.153049Z to 2024-02-19T15:17:39.393760Z : 1.2
- 2024-02-19T15:18:10.691562Z to 2024-02-19T15:18:11.891430Z : 1.2

To time performance, I tracked the time from the first `Startup` logged
message to the first `Update` logged message.

```shell
$ cargo run --release --example many_lights
Compiling bevy v0.13.0 (/Users/bdeep/dev/bevy/bevy)
    Finished release [optimized] target(s) in 1.54s
     Running `target/release/examples/many_lights`
# THIS TIME
2024-02-19T15:30:13.429609Z  INFO bevy_render::renderer: AdapterInfo { name: "Apple M1", vendor: 0, device: 0, device_type: IntegratedGpu, driver: "", driver_info: "", backend: Metal }
2024-02-19T15:30:13.566856Z  INFO bevy_winit::system: Creating new window "many_lights" (0v1)
2024-02-19T15:30:13.592371Z  WARN many_lights: This is a stress test used to push Bevy to its limit and debug performance issues. It is not representative of an actual game. It must be run in release mode using --release or it will be very slow.
2024-02-19T15:30:13.592572Z  INFO bevy_diagnostic::system_information_diagnostics_plugin::internal: SystemInfo { os: "MacOS 14.2.1 ", kernel: "23.2.0", cpu: "Apple M1", core_count: "8", memory: "16.0 GiB" }
# TO THIS TIME
2024-02-19T15:30:15.429900Z  INFO many_lights: Lights: 100000
2024-02-19T15:30:15.430139Z  INFO bevy diagnostic: fps        :    0.982693   (avg 43.026557)
2024-02-19T15:30:15.430157Z  INFO bevy diagnostic: frame_time : 1017.611750ms (avg 149.456476ms)
2024-02-19T15:30:15.430165Z  INFO bevy diagnostic: frame_count:   12.000000   (avg 6.000000)
```

</details>
2024-02-26 16:02:27 +00:00
Joona Aalto
9bd6cc0a5e
Add Direction3dA and move direction types out of primitives (#12018)
# Objective

Split up from #12017, add an aligned version of `Direction3d` for SIMD,
and move direction types out of `primitives`.

## Solution

Add `Direction3dA` and move direction types into a new `direction`
module.

---

## Migration Guide

The `Direction2d`, `Direction3d`, and `InvalidDirectionError` types have
been moved out of `bevy::math::primitives`.

Before:

```rust
use bevy::math::primitives::Direction3d;
```

After:

```rust
use bevy::math::Direction3d;
```

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-02-26 13:57:49 +00:00
Joshua Schlichting
a463d0c637
Fixed iOS documentation typo for xcrun command (#12112)
```
$ xcrun simctl devices list
Unrecognized subcommand: devices
usage: simctl [--set <path>] [--profiles <path>] <subcommand> ...
       simctl help [subcommand]
Command line utility to control the Simulator
```

# Objective

- The `examples/README.md` contains an invalid example command for
listing iOS devices using `xcrun`.
## Solution

- Update example command to omit the current invalid subcommand
"`devices`".
2024-02-26 04:59:19 +00:00
BD103
ff29c43916
Increase 3D Lighting example's light intensity (#11982)
# Objective

- The 3D Lighting example is meant to show using multiple lights in the
same scene.
- It currently looks very dark. (See [this
image](4fdb1455d5 (r1494653511)).)
- Resetting the physical camera properties sets the shutter speed to 1 /
125, even though it initially starts at 1 / 100.

## Solution

- Increase the intensity of all 3 lights in the example.
  - Now it is much closer to the example in Bevy 0.12.
- I had to remove the comment explaining the lightbulb equivalent of the
intensities because I don't know how it was calculated. Does anyone know
what light emits 100,000 lumens?
- Set the initial shutter speed to 1 / 125.

## Showcase

Before:

<img width="1392" alt="before"
src="https://github.com/bevyengine/bevy/assets/59022059/ac353e02-58e9-4661-aa6d-e5fdf0dcd2f6">

After:

<img width="1392" alt="after"
src="https://github.com/bevyengine/bevy/assets/59022059/4ff0beb6-0ced-4fb2-a953-04be2c77f437">

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-02-25 19:18:56 +00:00
Alex
a7be8a2655
Prefer UVec2 when working with texture dimensions (#11698)
# Objective

The physical width and height (pixels) of an image is always integers,
but for `GpuImage` bevy currently stores them as `Vec2` (`f32`).
Switching to `UVec2` makes this more consistent with the [underlying
texture data](https://docs.rs/wgpu/latest/wgpu/struct.Extent3d.html).

I'm not sure if this is worth the change in the surface level API. If
not, feel free to close this PR.

## Solution

- Replace uses of `Vec2` with `UVec2` when referring to texture
dimensions.
- Use integer types for the texture atlas dimensions and sections.


[`Sprite::rect`](a81a2d1da3/crates/bevy_sprite/src/sprite.rs (L29))
remains unchanged, so manually specifying a sub-pixel region of an image
is still possible.

---

## Changelog

- `GpuImage` now stores its size as `UVec2` instead of `Vec2`.
- Texture atlases store their size and sections as `UVec2` and `URect`
respectively.
- `UiImageSize` stores its size as `UVec2`.

## Migration Guide

- Change floating point types (`Vec2`, `Rect`) to their respective
unsigned integer versions (`UVec2`, `URect`) when using `GpuImage`,
`TextureAtlasLayout`, `TextureAtlasBuilder`,
`DynamicAtlasTextureBuilder` or `FontAtlas`.
2024-02-25 15:23:04 +00:00
eri
5f8f3b532c
Check cfg during CI and fix feature typos (#12103)
# Objective

- Add the new `-Zcheck-cfg` checks to catch more warnings
- Fixes #12091

## Solution

- Create a new `cfg-check` to the CI that runs `cargo check -Zcheck-cfg
--workspace` using cargo nightly (and fails if there are warnings)
- Fix all warnings generated by the new check

---

## Changelog

- Remove all redundant imports
- Fix cfg wasm32 targets
- Add 3 dead code exceptions (should StandardColor be unused?)
- Convert ios_simulator to a feature (I'm not sure if this is the right
way to do it, but the check complained before)

## Migration Guide

No breaking changes

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-02-25 15:19:27 +00:00