Commit graph

3443 commits

Author SHA1 Message Date
Ptipiak
919188074c Mention search filters in CONTRIBUTING.md (#6804)
* Adding a new section concerning the maintainers of the repo

# Objective

- Adding a few helpful links in the CONTRIBUTING.md files
- Fixes #6221 

## Solution

- Modifying CONTRIBUTING.md
- Adding a new section dedicated to maintainers  in CONTRIBUTING.md

---


Co-authored-by: Ptipiak <Ptipiak.off@gmail.com>
2022-12-02 18:22:25 +00:00
ira
c7d2cb14d0 Add methods intersect_plane and get_point to Ray (#6179)
Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-12-02 02:36:44 +00:00
Aleksandr Belkin
9b72780b82 Provide public EntityRef::get_change_ticks_by_id that takes ComponentId (#6683)
# Objective

Fixes #6682 

## Solution

Add `EntityRef::get_change_ticks_by_id`
Add `EntityMut::get_change_ticks_by_id`


Co-authored-by: Aleksandr Belkin <sQu1rr@users.noreply.github.com>
2022-12-02 02:21:22 +00:00
罗智芃
e89b043210 Fix material alpha_mode in example global_vs_local_translation (#6658)
# Objective

The global_vs_local_translation example tries to use transparency to identify static cubes, but the materials of those cubes aren't transparent.

## Solution

Change material alpha_mode to  `AlphaMode::Blend` for those cubes.
2022-12-01 15:19:54 +00:00
Mike
8faa12c5d6 pin nightly to 2022-11-28 to fix miri (#6808)
# Objective

- pin nightly to 2022-11-28 to fix miri
2022-12-01 01:30:55 +00:00
Mike
0e9c6dddb2 try to fix run-examples (#6810)
# Objective

- run examples is failing with `xvfb-run: error: Xvfb failed to start`

## Solution

- rollback ubuntu version for run-examples to 20.04. latest is 22.04

## Notes

- this is just a quick fix and someone should probably get it working on 22.04. I'll make an issue for that if this gets merged.
2022-12-01 00:27:54 +00:00
Marco Buono
b91356bd63 Add note about global .gitignore to CONTRIBUTING.md — Instead of ignoring .DS_Store files created by macOS Finder (#6499)
# Objective

Finder in macOS creates hidden `.DS_Store` files containing metadata (for icon positioning, view mode, etc) whenever you browse a directory. There's no point in committing these to git, and they're a common git + macOS nuisance.

## Solution

- ~~This PR adds `.DS_Store` files to `.gitignore`, improving the developer experience on macOS.~~
- This PR adds a note to the `CONTRIBUTING.md` file teaching how to use global git ignore.
2022-11-30 02:44:05 +00:00
James Liu
e954b8573c Lock down access to Entities (#6740)
# Objective
The soundness of the ECS `World` partially relies on the correctness of the state of `Entities` stored within it. We're currently allowing users to (unsafely) mutate it, as well as readily construct it without using a `World`. While this is not strictly unsound so long as users (including `bevy_render`) safely use the APIs, it's a fairly easy path to unsoundness without much of a guard rail.

Addresses #3362 for `bevy_ecs::entity`. Incorporates the changes from #3985.

## Solution
Remove `Entities`'s  `Default` implementation and force access to the type to only be through a properly constructed `World`.

Additional cleanup for other parts of `bevy_ecs::entity`:

 - `Entity::index` and `Entity::generation` are no longer `pub(crate)`, opting to force the rest of bevy_ecs to use the public interface to access these values.
 - `EntityMeta` is no longer `pub` and also not `pub(crate)` to attempt to cut down on updating `generation` without going through an `Entities` API. It's currently inaccessible except via the `pub(crate)` Vec on `Entities`, there was no way for an outside user to use it.
 - Added `Entities::set`, an unsafe `pub(crate)` API for setting the location of an Entity (parallel to `Entities::get`) that replaces the internal case where we need to set the location of an entity when it's been spawned, moved, or despawned.
 - `Entities::alloc_at_without_replacement` is only used in `World::get_or_spawn` within the first party crates, and I cannot find a public use of this API in any ecosystem crate that I've checked (via GitHub search).
 - Attempted to document the few remaining undocumented public APIs in the module.

---

## Changelog
Removed: `Entities`'s `Default` implementation.
Removed: `EntityMeta`
Removed: `Entities::alloc_at_without_replacement` and `AllocAtWithoutReplacement`.

Co-authored-by: james7132 <contact@jamessliu.com>
Co-authored-by: James Liu <contact@jamessliu.com>
2022-11-28 20:39:02 +00:00
François
9c79b39d73 set AVAILABLE_STORAGE_BUFFER_BINDINGS to the actual number of buffers available (#6787)
# Objective

- Since #5900 3d examples fail in wasm
```
ERROR crates/bevy_render/src/render_resource/pipeline_cache.rs:660 failed to process shader: Unknown shader def: 'AVAILABLE_STORAGE_BUFFER_BINDINGS'
```

## Solution

- Fix it by always adding the shaderdef `AVAILABLE_STORAGE_BUFFER_BINDINGS` with the actual value, instead of 3 when 3 or more were available
2022-11-28 19:27:04 +00:00
张林伟
0d833a3ebc Register Hash for glam types (#6786)
# Objective

- fixes https://github.com/bevyengine/bevy/issues/6736

## Solution

- Register `Hash` on all of glam's reflected integer vector types.
2022-11-28 14:55:26 +00:00
Griffin
295faa02fc Add support for Rgb9e5Ufloat textures (#6781)
# Objective

- Support textures in `Rgb9e5Ufloat` format.

## Solution

- Add `TextureFormatPixelInfo` for `Rgb9e5Ufloat`.

Tested this with a `Rgb9e5Ufloat` encoded KTX2 texture.
2022-11-28 14:14:08 +00:00
KazaniAvali
7963bb9ab3 Docs: amdgpu-pro-vulkan on Gentoo. (#6749)
When running Bevy on Gentoo using an AMD Radeon GPU, it panics unless `amdgpu-pro-vulkan` has been installed (and it took quite a bit of experimentation to find this information). This PR adds a mention of this to the linux dependencies documentation.
2022-11-28 13:54:15 +00:00
IceSentry
f119d9df8e Add DrawFunctionsInternals::id() (#6745)
# Objective

- Every usage of `DrawFunctionsInternals::get_id()` was followed by a `.unwrap()`. which just adds boilerplate.

## Solution

- Introduce a fallible version of `DrawFunctionsInternals::get_id()` and use it where possible.
- I also took the opportunity to improve the error message a little in the case where it fails.

---

## Changelog

- Added `DrawFunctionsInternals::id()`
2022-11-28 13:54:13 +00:00
James Liu
d79888bdae Document and lock down types in bevy_ecs::archetype (#6742)
# Objective
Document `bevy_ecs::archetype` and and declutter the public documentation for the module by making types non-`pub`.

Addresses #3362 for `bevy_ecs::archetype`.

## Solution
 - Add module level documentation.
 - Add type and API level documentation for all public facing types.
 - Make `ArchetypeId`, `ArchetypeGeneration`, and `ArchetypeComponentId` truly opaque IDs that are not publicly constructable. 
 - Make `AddBundle` non-pub, make `Edges::get_add_bundle` return a `Option<ArchetypeId>` and fork the existing function into `Edges::get_add_bundle_internal`.
 - Remove `pub(crate)` on fields that have a corresponding pub accessor function.
 - Removed the `Archetypes: Default` impl, opting for a `pub(crate) fn new` alternative instead.

---

## Changelog
Added: `ArchetypeGeneration` now implements `Ord` and `PartialOrd`.
Removed: `Archetypes`'s `Default` implementation.
Removed: `Archetype::new` and `Archetype::is_empty`.
Removed: `ArchetypeId::new` and `ArchetypeId::value`.
Removed: `ArchetypeGeneration::value`
Removed: `ArchetypeIdentity`.
Removed: `ArchetypeComponentId::new` and `ArchetypeComponentId::value`.
Removed: `AddBundle`. `Edges::get_add_bundle` now returns `Option<ArchetypeId>`
2022-11-28 13:54:12 +00:00
mareq
bbb652a438 Fix documentation on spawining an entity (#6775)
# Objective

- The documentation describing different ways to spawn an Entity is missing reference to "method" for "Spawn an entity with components".

## Solution

- Update the documentation to add the reference to `World::spawn`.
2022-11-28 13:40:31 +00:00
JoJoJet
1615834536 Fix an incorrect safety comment in World::get_resource (#6764)
# Objective

* Fix #6307

## Solution

* Rewrite the safety comment to reflect the actual invariants being asserted.
2022-11-28 13:40:26 +00:00
JoJoJet
70d7f80564 Make adding children idempotent (#6763)
# Objective

* Fix #6668
* There is no need to panic when a parenting operation is redundant, as no invalid state is entered.

## Solution

Make `push_children` idempotent.
2022-11-28 13:40:14 +00:00
JoJoJet
416a33e613 Add const Entity::PLACEHOLDER (#6761)
# Objective

One of the use-cases for the function `Entity::from_raw` is creating placeholder entity ids, which are meant to be overwritten later. If we use a constant for this instead of `from_raw`, it is more ergonomic and self-documenting.

## Solution

Add a constant that returns an entity ID with an index of `u32::MAX` and a generation of zero. Users are instructed to overwrite this value before using it.
2022-11-28 13:40:10 +00:00
SpecificProtagonist
2364a305c0 Clarify duplicate logger error (#6757)
# Objective

When a global tracing subscriber has already been set, `LogPlugin` panics with an error message explaining this. However, if a global logger has already been set, it simply panics on an unwrap.

#6426 mentiones the panic and has been fixed by unique plugins, but the panic can still occur if a logger has been set through different means or multiple apps are created, as in  #4934. The solution to that specific case isn't clear; this PR only fixes the missing error message.

## Solution

- ~add error message to panic~
- turn into warning
2022-11-28 13:39:47 +00:00
IceSentry
64642fbd3c Remove unnecessary struct in Material AsBindGroup example (#6701)
# Objective

- Reduce confusion around uniform bindings in materials. I've seen multiple people on discord get confused by it because it uses a struct that is named the same in the rust code and the wgsl code, but doesn't contain the same data. Also, the only reason this works is mostly by chance because the memory happens to align correctly.

## Solution

- Remove the confusing parts of the doc

## Notes

It's not super clear in the diff why this causes confusion, but essentially, the rust code defines a `CustomMaterial` struct with a color and a texture, but in the wgsl code the struct with the same name only contains the color. People are confused by it because the struct in wgsl doesn't need to be there.

You _can_ have complex structs on each side and the macro will even combine it for you if you reuse a binding index, but as it is now, this example seems to confuse more than help people.
2022-11-28 13:15:03 +00:00
Hennadii Chernyshchyk
523072902c Fix reflection for PathBuf and OsString (#6776)
# Objective

- `PathBuf` and `OsString` not reflected correctly.

## Solution

- Add missing registrations.
- Add FromReflect impls.
- Always implement `Reflect` for `OsString` just skip `Serialize` and `Deserialize` for unsupported platforms.

---

## Changelog

## Fixed

- Fix reflection for `PathBuf` and `OsString`.
2022-11-27 17:28:06 +00:00
Mitchell Henry
ca74271d07 Fix docs typo (#6771)
# Objective

- Fix a small typo

## Solution

- Type them correctly :D
2022-11-27 01:28:17 +00:00
IceSentry
17b7025a78 Fix set_cursor_grab_mode to try an alternative mode before giving an error (#6599)
# Objective

- Closes https://github.com/bevyengine/bevy/issues/6590
- The grab mode is platform dependent, this is problematic for bevy users since we can't easily use the recommended way to detect if the feature works like the winit docs recommend https://docs.rs/winit/0.27.5/winit/window/struct.Window.html#method.set_cursor_grab

## Solution

Try to use the grab mode that was requested, if it fails use the other one. Only then log an error if it fails after this step.
2022-11-26 13:10:11 +00:00
JoJoJet
03bde74766 impl Reflect for &'static Path (#6755)
# Objective

Fixes #6739 

## Solution

Implement the required traits. They cannot be implemented for `Path` directly, since it is a dynamically-sized type.
2022-11-25 23:49:26 +00:00
Rob Parrett
d1528dfbf8 Warn instead of erroring when max_font_atlases is exceeded (#6673)
# Objective

Fixes #6642

In a way that doesn't create any breaking changes, as a possible way to fix the above in a patch release.

## Solution

Don't actually remove font atlases when `max_font_atlases` is exceeded. Add a warning instead.

Keep `TextError::ExceedMaxTextAtlases` and `TextSettings` as-is so we don't break anything.

This is a bit of a cop-out, but the problems revealed by #6642 seem very challenging to fix properly.

Maybe follow up later with something more like https://github.com/rparrett/bevy/commits/remove-max-font-atlases later, if this is the direction we want to go.

## Note

See previous attempt at a "simple fix" that only solved some of the issues: #6666
2022-11-25 23:49:25 +00:00
Gino Valente
c8c6aba80e bevy_reflect: Remove ReflectSerialize and ReflectDeserialize registrations from most glam types (#6580)
# Objective

> Part of #6573

When serializing a `DynamicScene` we end up treating almost all non-value types as though their type data doesn't exist. This is because when creating the `DynamicScene` we call `Reflect::clone_value` on the components, which generates a Dynamic type for all non-value types.

What this means is that the `glam` types are treated as though their `ReflectSerialize` registrations don't exist. However, the deserializer _does_ pick up the registration and attempts to use that instead. This results in the deserializer trying to operate on "malformed" data, causing this error:

```
WARN bevy_asset::asset_server: encountered an error while loading an asset: Expected float
```

## Solution

Ideally, we should better handle the serialization of possibly-Dynamic types. However, this runs into issues where the `ReflectSerialize` expects the concrete type and not a Dynamic representation, resulting in a panic:

0aa4147af6/crates/bevy_reflect/src/type_registry.rs (L402-L413)

Since glam types are so heavily used in Bevy (specifically in `Transform` and `GlobalTransform`), it makes sense to just a quick fix in that enables them to be used properly in scenes while a proper solution is found.

This PR simply removes all `ReflectSerialize` and `ReflectDeserialize` registrations from the glam types that are reflected as structs.

---

## Changelog

- Remove `ReflectSerialize` and `ReflectDeserialize` registrations from most glam types

## Migration Guide

This PR removes `ReflectSerialize` and `ReflectDeserialize` registrations from most glam types. This means any code relying on either of those type data existing for those glam types will need to not do that.

This also means that some serialized glam types will need to be updated. For example, here is `Affine3A`:

```rust
// BEFORE
(
  "glam::f32::affine3a::Affine3A": (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0),

// AFTER
  "glam::f32::affine3a::Affine3A": (
    matrix3: (
      x_axis: (
        x: 1.0,
        y: 0.0,
        z: 0.0,
      ),
      y_axis: (
        x: 0.0,
        y: 1.0,
        z: 0.0,
      ),
      z_axis: (
        x: 0.0,
        y: 0.0,
        z: 1.0,
      ),
    ),
    translation: (
      x: 0.0,
      y: 0.0,
      z: 0.0,
    ),
  )
)
```
2022-11-25 23:30:21 +00:00
François
056272413f Move Android example to its own package (#6759)
# Objective

- Fix CI issue with updated `cargo-app`

## Solution

- Move the Android example to its own package. It's not necessary for the CI fix, but it's cleaner, mimic the iOS example, and easier to reuse for someone wanting to setup android support in their project
- Build the package in CI instead of the example


The Android example is still working on my android device with this change 👍
2022-11-25 23:02:56 +00:00
Gino Valente
3827316100 bevy_reflect: Register missing reflected types for bevy_render (#6725)
# Objective 

Many types in `bevy_render` implemented `Reflect` but were not registered.

## Solution

Register all types in `bevy_render` that impl `Reflect`.

This also registers additional dependent types (i.e. field types).

> Note: Adding these dependent types would not be needed using something like #5781 😉 

---

## Changelog

- Register missing `bevy_render` types in the `TypeRegistry`:
  - `camera::RenderTarget`
  - `globals::GlobalsUniform`
  - `texture::Image`
  - `view::ComputedVisibility`
  - `view::Visibility`
  - `view::VisibleEntities`
- Register additional dependent types:
  - `view::ComputedVisibilityFlags`
  - `Vec<Entity>`
2022-11-23 00:41:21 +00:00
Mike
8eb8ad5c4a await tasks to cancel (#6696)
# Objective

- Fixes https://github.com/bevyengine/bevy/issues/6603

## Solution

- `Task`s will cancel when dropped, but wait until they return Pending before they actually get canceled. That means that if a task panics, it's possible for that error to get propagated to the scope and the scope gets dropped, while scoped tasks in other threads are still running. This is a big problem since scoped task can hold life-timed values that are dropped as the scope is dropped leading to UB.

---

## Changelog

- changed `Scope` to use `FallibleTask` and await the cancellation of all remaining tasks when it's dropped.
2022-11-23 00:41:19 +00:00
Alice Cecile
3433a7bd68 Remove warning about missed events due to false positives (#6730)
# Objective

- Reverts #5730.
- Fixes #6173, fixes #6596.

## Solution

Remove the warning entirely.

## Changelog

You will no longer be spammed about

> Missed 31 `bevy_input:🐭:MouseMotion` events. Consider
reading from the `EventReader` more often (generally the best
solution) or calling Events::update() less frequently
(normally this is called once per frame). This problem is most
likely due to run criteria/fixed timesteps or consuming events
conditionally. See the Events documentation for
more information.

when you miss events. These warnings were often (but not always) a false positive. You can still check this manually by using `ManualEventReader::missed_events`
2022-11-23 00:27:29 +00:00
ira
7d57d7ac0c Remove BuildWorldChildren impl from WorldChildBuilder (#6727)
# Objective
Remove an obscure and inconsistent bit of API.
Simplify the `WorldChildBuilder` code.

No idea why this even exists.

An example of the removed API:
```rust
world.spawn_empty().with_children(|parent| {
    parent.spawn_empty();
    parent.push_children(&[some_entity]); // Does *not* add children to the parent.
    // It's actually identical to:
    parent.spawn_empty().push_children(&[some_entity]);
});

world.spawn_empty().with_children(|parent| {
    // This just panics.
    parent.push_children(&[some_entity]);
});
```
This exists only on `WorldChildBuilder`; `ChildBuilder` does not have this API.

Yeet.

## Migration Guide
Hierarchy editing methods such as `with_children` and `push_children` have been removed from `WorldChildBuilder`.
You can edit the hierarchy via `EntityMut` instead.

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-11-23 00:27:28 +00:00
Gino Valente
4e2374334f bevy_reflect: Fix binary deserialization not working for unit structs (#6722)
# Objective 

Fixes #6713

Binary deserialization is failing for unit structs as well as structs with all ignored/skipped fields.

## Solution

Add a check for the number of possible fields in a struct before deserializing. If empty, don't attempt to deserialize any fields (as there will be none).

Note: ~~This does not apply to enums as they do not properly handle skipped fields (see #6721).~~ Enums still do not properly handle skipped fields, but I decided to include the logic for it anyways to account for `#[reflect(ignore)]`'d fields in the meantime.

---

## Changelog

- Fix bug where deserializing unit structs would fail for non-self-describing formats
2022-11-23 00:01:36 +00:00
ira
a1607b8065 Rename EntityId to EntityIndex (#6732)
Continuation of #6107

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-11-22 20:38:35 +00:00
Aevyrie
c069c544a7 Fix missing sRGB conversion for dithering non-HDR pipelines (#6707)
# Objective

- Fixes #6706 

Zoom in on the shadow in the following images:

## Current bevy/main

### HDR On - correct
![current-hdron](https://user-images.githubusercontent.com/2632925/202943151-ecad3cbe-a76e-46df-bac9-9e590a31a9f3.png)

### HDR Off - incorrect
![current-hdroff](https://user-images.githubusercontent.com/2632925/202943154-34e3f527-a00e-4546-931d-0691204cc6a4.png)

## This PR

### HDR On - correct
![new-hdron](https://user-images.githubusercontent.com/2632925/202943383-081990de-9a14-45bd-ac52-febcc4289079.png)

### HDR Off - corrected
![new-hdroff](https://user-images.githubusercontent.com/2632925/202943388-a3b05d79-a0f3-4b1e-b114-0a9f03efe351.png)

## Close-up comparison

### New
![Screenshot from 2022-11-20 17-46-46](https://user-images.githubusercontent.com/2632925/202943552-d45c3a48-841e-47a6-981f-776c5a9563f6.png)

### Old
![Screenshot from 2022-11-20 17-46-41](https://user-images.githubusercontent.com/2632925/202943562-555cb5a2-2b20-45f9-b250-89f2bc87af5f.png)

## Solution

- It turns out there was an outright missing sRGB conversion for dithering non-HDR cameras.
- I also tried using a precise sRGB conversion, but it had no apparent effect on the final image.

---

## Changelog

- Fix deband dithering intensity for non-HDR pipelines.
2022-11-22 15:55:50 +00:00
Jakob Hellermann
cf46dd2e7e fix mutable aliases for a very short time if WorldCell is already borrowed (#6639)
# Objective

Consider the test
```rust
let cell = world.cell();
let _value_a = cell.resource_mut::<A>();
let _value_b = cell.resource_mut::<A>();
```

Currently, this will roughly execute

```rust
// first call
let value = unsafe {
    self.world
    .get_non_send_unchecked_mut_with_id(component_id)?
};
return Some(WorldBorrowMut::new(value, archetype_component_id, self.access)))

// second call
let value = unsafe {
    self.world
    .get_non_send_unchecked_mut_with_id(component_id)?
};
return Some(WorldBorrowMut::new(value, archetype_component_id, self.access)))
```
where `WorldBorrowMut::new` will panic if the resource is already borrowed.

This means, that `_value_a` will be created, the access checked (OK), then `value_b` will be created, and the access checked (`panic`).
For a moment, both `_value_a` and `_value_b` existed as `&mut T` to the same location, which is insta-UB as far as I understand it.

## Solution
Flip the order so that `WorldBorrowMut::new` first checks the access, _then_ fetches creates the value. To do that, we pass a `impl FnOnce() -> Mut<T>` instead of the `Mut<T>` directly:

```rust
let get_value = || unsafe {
    self.world
    .get_non_send_unchecked_mut_with_id(component_id)?
};
return Some(WorldBorrowMut::new(get_value, archetype_component_id, self.access)))
```
2022-11-22 15:31:18 +00:00
François
d44e86507f Shader defs can now have a value (#5900)
# Objective

- shaders defs can now have a `bool` or `int` value
- `#if SHADER_DEF <operator> 3`
  - ok if `SHADER_DEF` is defined, has the correct type and pass the comparison
  - `==`, `!=`, `>=`, `>`, `<`, `<=` supported
- `#SHADER_DEF` or `#{SHADER_DEF}`
  - will be replaced by the value in the shader code
---

## Migration Guide

- replace `shader_defs.push(String::from("NAME"));` by `shader_defs.push("NAME".into());`
- if you used shader def `NO_STORAGE_BUFFERS_SUPPORT`, check how `AVAILABLE_STORAGE_BUFFER_BINDINGS` is now used in Bevy default shaders
2022-11-21 22:38:29 +00:00
Torstein Grindvik
daa57fe489 Add try_* to add_slot_edge, add_node_edge (#6720)
# Objective

`add_node_edge` and `add_slot_edge` are fallible methods, but are always used with `.unwrap()`.
`input_node` is often unwrapped as well.
This points to having an infallible behaviour as default, with an alternative fallible variant if needed.

Improves readability and ergonomics.

## Solution

- Change `add_node_edge` and `add_slot_edge` to panic on error.
- Change `input_node` to panic on `None`.
- Add `try_add_node_edge` and `try_add_slot_edge` in case fallible methods are needed.
- Add `get_input_node` to still be able to get an `Option`.
---

## Changelog

### Added

- `try_add_node_edge`
- `try_add_slot_edge`
- `get_input_node`

### Changed

- `add_node_edge` is now infallible (panics on error)
- `add_slot_edge` is now infallible (panics on error)
- `input_node` now panics on `None`

## Migration Guide

Remove `.unwrap()` from `add_node_edge` and `add_slot_edge`.
For cases where the error was handled, use `try_add_node_edge` and `try_add_slot_edge` instead.

Remove `.unwrap()` from `input_node`.
For cases where the option was handled, use `get_input_node` instead.


Co-authored-by: Torstein Grindvik <52322338+torsteingrindvik@users.noreply.github.com>
2022-11-21 21:58:39 +00:00
Chris Juchem
e2d1d9dff8 Update dead links in DefaultPlugins docs (#6695)
# Objective

- Fix dead links on this docs page: https://docs.rs/bevy/0.9.0/bevy/struct.DefaultPlugins.html

## Solution

- Point links to the imported versions instead of the versions in external crates.
2022-11-21 20:12:31 +00:00
James Liu
eaeba0866d Parallelized transform propagation (#4775)
# Objective
Fixes #4697. Hierarchical propagation of properties, currently only Transform -> GlobalTransform, can be a very expensive operation. Transform propagation is a strict dependency for anything positioned in world-space. In large worlds, this can take quite a bit of time, so limiting it to a single thread can result in poor CPU utilization as it bottlenecks the rest of the frame's systems.

## Solution

 - Move transforms without a parent or a child (free-floating (Global)Transform) entities into a separate parallel system.
 - Chunk the hierarchy based on the root entities and process it in parallel with `Query::par_for_each_mut`. 
 - Utilize the hierarchy's specific properties introduced in #4717 to allow for safe use of `Query::get_unchecked` on multiple threads. Assuming each child is unique in the hierarchy, it is impossible to have an aliased `&mut GlobalTransform` so long as we verify that the parent for a child is the same one propagated from.

---

## Changelog
Removed: `transform_propagate_system` is no longer `pub`.
2022-11-21 18:18:38 +00:00
Chia-Hsiang Cheng
585dac0582 Remove auto-margin properties from the examples (#6535)
# Objective

Fixes #6498.

## Solution

Adding a parent node with properties AlignItems::Center and JustifyContent::Center to centered child nodes and removing their auto-margin properties.
2022-11-21 14:38:35 +00:00
Ida Iyes
96e09f004b Fix PipeSystem panicking with exclusive systems (#6698)
Without this fix, piped systems containing exclusive systems fail to run, giving a runtime panic.
With this PR, running piped systems that contain exclusive systems now works.

## Explanation of the bug

This is because, unless overridden, the default implementation of `run` from the `System` trait simply calls `run_unsafe`. That is not valid for exclusive systems. They must always be called via `run`, as `run_unsafe` takes `&World` instead of `&mut World`.

Trivial reproduction example:
```rust
fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_system(exclusive.pipe(another))
        .run();
}

fn exclusive(_world: &mut World) {}
fn another() {}
```
If you run this, you will get a panic 'Cannot run exclusive systems with a shared World reference' and the backtrace shows how bevy (correctly) tries to call the `run` method (because the system is exclusive), but it is the implementation from the `System` trait (because `PipeSystem` does not have its own), which calls `run_unsafe` (incorrect):
 - 3: <bevy_ecs::system::system_piping::PipeSystem<SystemA,SystemB> as bevy_ecs::system::system::System>::run_unsafe
 - 4: bevy_ecs::system::system::System::run
2022-11-21 14:23:21 +00:00
Torstein Grindvik
174819be83 ExtractComponent output optional associated type (#6699)
# Objective

Allow more use cases where the user may benefit from both `ExtractComponentPlugin` _and_ `UniformComponentPlugin`.

## Solution

Add an associated type to `ExtractComponent` in order to allow specifying the output component (or bundle).

Make `extract_component` return an `Option<_>` such that components can be extracted only when needed.

What problem does this solve?

`ExtractComponentPlugin` allows extracting components, but currently the output type is the same as the input.
This means that use cases such as having a settings struct which turns into a uniform is awkward.

For example we might have:

```rust
struct MyStruct {
    enabled: bool,
    val: f32
}

struct MyStructUniform {
    val: f32
}
```

With the new approach, we can extract `MyStruct` only when it is enabled, and turn it into its related uniform.

This chains well with `UniformComponentPlugin`.

The user may then:

```rust
app.add_plugin(ExtractComponentPlugin::<MyStruct>::default());
app.add_plugin(UniformComponentPlugin::<MyStructUniform>::default());
```

This then saves the user a fair amount of boilerplate.


## Changelog

### Changed

- `ExtractComponent` can specify output type, and outputting is optional.



Co-authored-by: Torstein Grindvik <52322338+torsteingrindvik@users.noreply.github.com>
2022-11-21 13:19:44 +00:00
ira
30070a926f Add Transform::look_to (#6692)
Add a method to rotate a transform to point towards a direction.

Also updated the docs to link to `forward` and `up` instead of mentioning local negative `Z` and local `Y`.

Unfortunately, links to methods don't work in rust-analyzer :(

Co-authored-by: Devil Ira <justthecooldude@gmail.com>
2022-11-21 13:19:43 +00:00
phuocthanhdo
ed2ea0d417 The update_frame_count system should be placed in CorePlugin (#6676)
# Objective

Latest Release, "bevy 0.9" move the FrameCount updater into RenderPlugin, it leads to user who only run app with Core/Minimal Plugin cannot get the right number of FrameCount, it always return 0.

As for use cases like a server app, we don't want to add render dependencies to the app.

More detail in #6656 

## Solution

- Move the `update_frame_count` into CorePlugin
2022-11-21 13:19:41 +00:00
Robin KAY
bdd5cee92a Add Box::from_corners method (#6672)
# Objective

This add a ctor to `Box` to aid the creation of non-centred boxes. The PR adopts @rezural's work on PR #3322, taking into account the feedback on that PR from @james7132.

## Solution

`Box::from_corners()` creates a `Box` from two opposing corners and automatically determines the min and max extents to ensure that the `Box` is well-formed.

Co-authored-by: rezural <rezural@protonmail.com>
2022-11-21 13:19:40 +00:00
Jer
b3e45b75d6 Expose set_cursor_hittest() from winit (#6664)
# Objective

- Bevy should be usable to create 'overlay' type apps, where the input is not captured by Bevy, but passed down/into a target app, or to allow passive displays/widgets etc.
 
## Solution

- the `winit:🪟:Window` already has a `set_cursor_hittest()` which basically does this for mouse input events, so I've exposed it (trying to copy the style laid out in the existing wrappings, and added a simple demo.

---

## Changelog

- Added `hittest` to `WindowAttributes`
- Added the `hittest`'s setters/getters
- Modified the `WindowBuilder`
- Modifed the `WindowDescriptor`'s `Default` impl.
- Added an example `cargo run --example fallthrough`
2022-11-21 12:59:10 +00:00
James Liu
55ca7fc88e Split Component Ticks (#6547)
# Objective
Fixes #4884. `ComponentTicks` stores both added and changed ticks contiguously in the same 8 bytes. This is convenient when passing around both together, but causes half the bytes fetched from memory for the purposes of change detection to effectively go unused. This is inefficient when most queries (no filter, mutating *something*) only write out to the changed ticks.

## Solution
Split the storage for change detection ticks into two separate `Vec`s inside `Column`. Fetch only what is needed during iteration.

This also potentially also removes one blocker from autovectorization of dense queries.

EDIT: This is confirmed to enable autovectorization of dense queries in `for_each` and `par_for_each`  where possible.  Unfortunately `iter` has other blockers that prevent it.

### TODO

 - [x] Microbenchmark
 - [x] Check if this allows query iteration to autovectorize simple loops.
 - [x] Clean up all of the spurious tuples now littered throughout the API

### Open Questions

 - ~~Is `Mut::is_added` absolutely necessary? Can we not just use `Added` or `ChangeTrackers`?~~ It's optimized out if unused.
 - ~~Does the fetch of the added ticks get optimized out if not used?~~ Yes it is.

---

## Changelog
Added: `Tick`, a wrapper around a single change detection tick.
Added: `Column::get_added_ticks`
Added: `Column::get_column_ticks`
Added: `SparseSet::get_added_ticks`
Added: `SparseSet::get_column_ticks`
Changed: `Column` now stores added and changed ticks separately internally.
Changed: Most APIs returning `&UnsafeCell<ComponentTicks>` now returns `TickCells` instead, which contains two separate `&UnsafeCell<Tick>` for either component ticks.
Changed: `Query::for_each(_mut)`, `Query::par_for_each(_mut)` will now leverage autovectorization to speed up query iteration where possible.

## Migration Guide
TODO
2022-11-21 12:59:09 +00:00
James Liu
210979f631 Fix panicking on another scope (#6524)
# Objective
Fix #6453. 

## Solution
Use the solution mentioned in the issue by catching the unwind and dropping the error. Wrap the `executor.try_tick` calls with `std::catch::unwind`.

Ideally this would be moved outside of the hot loop, but the mut ref to the `spawned` future is not `UnwindSafe`.

This PR only addresses the bug, we can address the perf issues (should there be any) later.
2022-11-21 12:59:08 +00:00
Nicola Papale
15ea93a348 Fix size_hint for partially consumed QueryIter and QueryCombinationIter (#5214)
# Objective

Fix #5149

## Solution

Instead of returning the **total count** of elements in the `QueryIter` in
`size_hint`, we return the **count of remaining elements**. This
Fixes #5149 even when #5148 gets merged.

- https://github.com/bevyengine/bevy/issues/5149
- https://github.com/bevyengine/bevy/pull/5148

---

## Changelog

- Fix partially consumed `QueryIter` and `QueryCombinationIter` having invalid `size_hint`


Co-authored-by: Nicola Papale <nicopap@users.noreply.github.com>
2022-11-21 12:37:31 +00:00
研究社交
e0c3c6d166 Make Core Pipeline Graph Nodes Public (#6605)
# Objective

Make core pipeline graphic nodes, including `BloomNode`, `FxaaNode`, `TonemappingNode` and `UpscalingNode` public.
This will allow users to construct their own render graphs with these build-in nodes.

## Solution

Make them public.
Also put node names into bevy's core namespace (`core_2d::graph::node`, `core_3d::graph::node`) which makes them consistent.
2022-11-18 22:16:55 +00:00