Commit graph

748 commits

Author SHA1 Message Date
Alice Cecile
b5d7ff2d75 Do not panic on failed setting of GameOver state in AlienCakeAddict (#3411)
# Objective

- Tentatively fixes #2525.

## Solution

- The panic seems to occur when the game-over state occurs nearly instantly.
- Discard the `Result`, rather than panicking. We could probably handle this better, but I want to see if this works first. Ping @qarmin.
2021-12-22 00:49:15 +00:00
MrGVSV
5479047aa2 Added set_cursor_icon(...) to Window (#3395)
# Objective

The window's cursor should be settable without having to implement a custom cursor icon solution. This will especially be helpful when creating user-interfaces that might like to use the cursor to denote some meaning (e.g., _clickable_, _resizable_, etc.).

## Solution

Added a `CursorIcon` enum that maps one-to-one to winit's `CursorIcon` enum, as well as a method to set/get it for the given `Window`.
2021-12-20 22:04:45 +00:00
davier
c79ec9cad6 Fix custom mesh pipelines (#3381)
# Objective

Fixes #3379 

## Solution

The custom mesh pipelines needed to be specialized on each mesh's primitive topology, as done in `queue_meshes()`

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-12-20 20:33:39 +00:00
研究社交
46c1480f42 Fix hierarchy example panic (#3378)
# Objective
Fixes #3321 

## Solution
Uses `despawn_recursive()` instead of `despawn()` when removing children.
2021-12-20 20:33:38 +00:00
davier
340957994d Implement the Overflow::Hidden style property for UI (#3296)
# Objective

This PR implements the `overflow` style property in `bevy_ui`. When set to `Overflow::Hidden`, the children of that node are clipped so that overflowing parts are not rendered. This is an important building block for UI widgets.

## Solution

Clipping is done on the CPU so that it does not break batching.

The clip regions update was implemented as a separate system for clarity, but it could be merged with the other UI systems to avoid doing an additional tree traversal. (I don't think it's important until we fix the layout performance issues though).

A scrolling list was added to the `ui_pipelined` example to showcase `Overflow::Hidden`. For the sake of simplicity, it can only be scrolled with a mouse.
2021-12-19 05:44:28 +00:00
François
6eb8e15e3d Improved bevymark: no bouncing offscreen and spawn waves from CLI (#3364)
# Objective

- In bevymark, bevies were very bouncy and could go off screen after a while, skewing the FPS

https://user-images.githubusercontent.com/8672791/146540848-282fa11b-d058-4da9-8e95-688ae67d9406.mp4

## Solution

- Make bevies bounce also on top of the screen
- I also changed how the examples read args from CLI to be able to spawn waves: `cargo run --example bevymark --release -- 5 100` (first is number of bevy per wave, second is number of wave, with one wave every 0.2 seconds). This makes it easier to reproduce some exact situations

https://user-images.githubusercontent.com/8672791/146542857-2f953fa0-7b8d-4772-93f8-b8d7a31259dc.mp4




Co-authored-by: François <8672791+mockersf@users.noreply.github.com>
2021-12-18 20:13:59 +00:00
Daniel McNab
ed9d45fae5 Add an example 'showcasing' using multiple windows (#3367)
# Objective

- The multiple windows example which was viciously murdered in #3175.
- cart asked me to

## Solution

- Rework the example to work on pipelined-rendering, based on the work from #2898
2021-12-18 19:38:05 +00:00
r00ster
11f52b8c72 Add an example to draw a rectangle (#2957)
# Objective

Every time I come back to Bevy I face the same issue: how do I draw a rectangle again? How did that work? So I go to https://github.com/bevyengine/bevy/tree/main/examples in the hope of finding literally the simplest possible example that draws something on the screen without any dependency such as an image. I don't want to have to add some image first, I just quickly want to get something on the screen with `main.rs` alone so that I can continue building on from that point on. Such an example is particularly helpful for a quick start for smaller projects that don't even need any assets such as images (this is my case currently).

Currently every single example of https://github.com/bevyengine/bevy/tree/main/examples#2d-rendering (which is the first section after hello world that beginners will look for for very minimalistic and quick examples) depends on at least an asset or is too complex. This PR solves this.
It also serves as a great comparison for a beginner to realize what Bevy is really like and how different it is from what they may expect Bevy to be. For example for someone coming from [LÖVE](https://love2d.org/), they will have something like this in their head when they think of drawing a rectangle:
```lua
function love.draw()
    love.graphics.setColor(0.25, 0.25, 0.75);
    love.graphics.rectangle("fill", 0, 0, 50, 50);
end
```
This, of course, differs quite a lot from what you do in Bevy. I imagine there will be people that just want to see something as simple as this in comparison to have a better understanding for the amount of differences.

## Solution

Add a dead simple example drawing a blue 50x50 rectangle in the center with no more and no less than needed.
2021-12-18 00:52:37 +00:00
Tobenaii
d3749a98f8 Use updated window size in bevymark example (#3335)
# Objective

Have the bird spawning/collision systems in bevymark use the proper window size, instead of the size set in WindowDescriptor which isn't updated when the window is resized.

## Solution

Use the Windows resource to grab the width/height from the primary window. This is consistent with the other examples.
2021-12-18 00:29:36 +00:00
Hennadii Chernyshchyk
70c9165886 Fix crash with disabled winit (#3330)
# Objective

This PR fixes a crash when winit is enabled when there is a camera in the world. Part of #3155

## Solution

In this PR, I removed two unwraps and added an example for regression testing.
2021-12-15 00:15:47 +00:00
Carter Anderson
ffecb05a0a Replace old renderer with new renderer (#3312)
This makes the [New Bevy Renderer](#2535) the default (and only) renderer. The new renderer isn't _quite_ ready for the final release yet, but I want as many people as possible to start testing it so we can identify bugs and address feedback prior to release.

The examples are all ported over and operational with a few exceptions:

* I removed a good portion of the examples in the `shader` folder. We still have some work to do in order to make these examples possible / ergonomic / worthwhile: #3120 and "high level shader material plugins" are the big ones. This is a temporary measure.
* Temporarily removed the multiple_windows example: doing this properly in the new renderer will require the upcoming "render targets" changes. Same goes for the render_to_texture example.
* Removed z_sort_debug: entity visibility sort info is no longer available in app logic. we could do this on the "render app" side, but i dont consider it a priority.
2021-12-14 03:58:23 +00:00
davier
25b62f9577 Port bevy_ui to pipelined-rendering (#2653)
# Objective

Port bevy_ui to pipelined-rendering (see #2535 )

## Solution

I did some changes during the port:
- [X] separate color from the texture asset (as suggested [here](https://discord.com/channels/691052431525675048/743663924229963868/874353914525413406))
- [X] ~give the vertex shader a per-instance buffer instead of per-vertex buffer~ (incompatible with batching)

Remaining features to implement to reach parity with the old renderer:
- [x] textures
- [X] TextBundle

I'd also like to add these features, but they need some design discussion:
- [x] batching
- [ ] separate opaque and transparent phases
- [ ] multiple windows
- [ ] texture atlases
- [ ] (maybe) clipping
2021-12-10 22:21:23 +00:00
loui
3ca8844c90 Added transparency to window builder (#3105)
Applogies, had to recreate this pr because of branching issue.
Old PR: https://github.com/bevyengine/bevy/pull/3033

# Objective

Fixes #3032

Allowing a user to create a transparent window 

## Solution

I've allowed the transparent bool to be passed to the winit window builder
2021-12-08 20:53:35 +00:00
Rostyslav Toch
01e2141ce3 Add Gamepads resource (#3257)
# Objective

Fixes #3245 

## Solution

- Move GamepadLobby to lib
- Add connection_system to InputPlugin
- Updated gamepad_input example


Co-authored-by: CrazyRoka <rokarostuk@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-12-08 20:28:08 +00:00
Rostyslav Toch
ca80fe65ed Improve contributors example quality (#3258)
# Objective

Fixes #3181

## Solution

Refactored `contributors.rs` example:
- Renamed unclear variables
- Split setup system into two separate systems 


Co-authored-by: CrazyRoka <rokarostuk@gmail.com>
2021-12-08 20:09:53 +00:00
François
ccee658436 Fix iOS CI on Intel (for real this time) (#3232)
# Objective

- iOS CI has linker issues https://github.com/bevyengine/bevy/runs/4388921574?check_suite_focus=true

## Solution

- Building for iOS actually requires ~~both iOS SDK for target and~~ macOS SDK for build scripts. ~~I added them both when needed~~ I replaced the iOS SDK with the maOS. This was not an issue on m1 as they are compatible enough to make the build pass.
- This completely confused `shader-sys` which fails to build in this configuration. Luckily as the example now uses the new renderer, I was able to remove the old renderer and depend no more on this lib.

This is confirmed to work:
- on intel mac with simulator
- on m1 mac with simulator
- on m1 mac with real iphone
2021-12-02 07:44:40 +00:00
François
2def9027d7 Fix iOS CI (#3228)
# Objective

- With #3109 I broke iOS CI: https://github.com/bevyengine/bevy/runs/4374891646?check_suite_focus=true

## Solution

- Fix indentation in makefile
- Adds scheme that is now needed

With this, `make install` works on my m1 Mac but still fails on my intel Mac unless I run something like `make install; cargo build --target x86_64-apple-ios; make install; cargo build --target x86_64-apple-ios; make install`. It seems something is off when executing cargo through `xcodebuild` on my setup but not sure what. So this PR will probably not fix iOS CI 😞
2021-12-01 21:44:29 +00:00
François
d59a3ddd61 iOS: replace cargo-lipo, and update for new macOS (#3109)
# Objective

- Remove `cargo-lipo` as [it's deprecated](https://github.com/TimNN/cargo-lipo#maintenance-status) and doesn't work on new Apple processors
- Fix CI that will fail as soon as GitHub update the worker used by Bevy to macOS 11

## Solution

- Replace `cargo-lipo` with building with the correct target
- Setup the correct path to libraries by using `xcrun --show-sdk-path`
- Also try and fix path to cmake in case it's not found but available through homebrew
2021-11-29 23:25:22 +00:00
François
eb15f81e17 enable alpha mode for textures materials that are transparent (#3202)
# Objective

- Transparent materials used in 3d are not transparent by default

## Solution

- Enable transparency in example
2021-11-29 21:22:53 +00:00
François
3de391be21 fix calls to as_rgba_linear (#3200)
# Objective

- After #3192, some places where `as_rgba_linear` was called were doing too many conversions

## Solution

- Fix the conversions
2021-11-28 10:40:42 +00:00
François
e8412df021 add shadows in examples (#3201)
# Objective

- As mentioned in #3126, shadows need to be readded in examples

## Solution

- Add shadows in examples
2021-11-27 10:12:47 +00:00
François
7ced541cb2 increase light intensity in pbr_pipelined example (#3182)
# Objective

- example `pbr_pipelined` doesn't look like example `pbr`

`pbr`:
![pbr](https://user-images.githubusercontent.com/8672791/143328022-83797197-233c-4824-8daa-4d7bd092938d.png)


`pbr_pipelined`:
![pbr_pipelined](https://user-images.githubusercontent.com/8672791/143328034-8a8bdb39-0d75-472b-8880-7bb7cd48f448.png)


## Solution

- set the light intensity to a higher value

`pbr_pipelined` with this pr:
![pbr_pipelined_fixed](https://user-images.githubusercontent.com/8672791/143328040-4149e96c-dada-4940-9f6f-f8925e48b22e.png)
2021-11-27 10:12:45 +00:00
Carter Anderson
8009af3879 Merge New Renderer 2021-11-22 23:57:42 -08:00
Carter Anderson
2e79951659 Shader Imports. Decouple Mesh logic from PBR (#3137)
## Shader Imports

This adds "whole file" shader imports. These come in two flavors:

### Asset Path Imports

```rust
// /assets/shaders/custom.wgsl

#import "shaders/custom_material.wgsl"

[[stage(fragment)]]
fn fragment() -> [[location(0)]] vec4<f32> {
    return get_color();
}
```

```rust
// /assets/shaders/custom_material.wgsl

[[block]]
struct CustomMaterial {
    color: vec4<f32>;
};
[[group(1), binding(0)]]
var<uniform> material: CustomMaterial;
```

### Custom Path Imports

Enables defining custom import paths. These are intended to be used by crates to export shader functionality:

```rust
// bevy_pbr2/src/render/pbr.wgsl

#import bevy_pbr::mesh_view_bind_group
#import bevy_pbr::mesh_bind_group

[[block]]
struct StandardMaterial {
    base_color: vec4<f32>;
    emissive: vec4<f32>;
    perceptual_roughness: f32;
    metallic: f32;
    reflectance: f32;
    flags: u32;
};

/* rest of PBR fragment shader here */
```

```rust
impl Plugin for MeshRenderPlugin {
    fn build(&self, app: &mut bevy_app::App) {
        let mut shaders = app.world.get_resource_mut::<Assets<Shader>>().unwrap();
        shaders.set_untracked(
            MESH_BIND_GROUP_HANDLE,
            Shader::from_wgsl(include_str!("mesh_bind_group.wgsl"))
                .with_import_path("bevy_pbr::mesh_bind_group"),
        );
        shaders.set_untracked(
            MESH_VIEW_BIND_GROUP_HANDLE,
            Shader::from_wgsl(include_str!("mesh_view_bind_group.wgsl"))
                .with_import_path("bevy_pbr::mesh_view_bind_group"),
        );
```

By convention these should use rust-style module paths that start with the crate name. Ultimately we might enforce this convention.

Note that this feature implements _run time_ import resolution. Ultimately we should move the import logic into an asset preprocessor once Bevy gets support for that.

## Decouple Mesh Logic from PBR Logic via MeshRenderPlugin

This breaks out mesh rendering code from PBR material code, which improves the legibility of the code, decouples mesh logic from PBR logic, and opens the door for a future `MaterialPlugin<T: Material>` that handles all of the pipeline setup for arbitrary shader materials.

## Removed `RenderAsset<Shader>` in favor of extracting shaders into RenderPipelineCache

This simplifies the shader import implementation and removes the need to pass around `RenderAssets<Shader>`.

##  RenderCommands are now fallible

This allows us to cleanly handle pipelines+shaders not being ready yet. We can abort a render command early in these cases, preventing bevy from trying to bind group / do draw calls for pipelines that couldn't be bound. This could also be used in the future for things like "components not existing on entities yet". 

# Next Steps

* Investigate using Naga for "partial typed imports" (ex: `#import bevy_pbr::material::StandardMaterial`, which would import only the StandardMaterial struct)
* Implement `MaterialPlugin<T: Material>` for low-boilerplate custom material shaders
* Move shader import logic into the asset preprocessor once bevy gets support for that.

Fixes #3132
2021-11-18 03:45:02 +00:00
Niklas Eicker
94db0176fe Add readme to errors crate and clean up cargo files (#3125)
# Objective

- Document that the error codes will be rendered on the bevy website (see bevyengine/bevy-website#216)
- Some Cargo.toml files did not include the license or a description field

## Solution

- Readme for the errors crate
- Mark internal/development crates with `publish = false`
- Add missing license/descriptions to some crates

- [x] merge bevyengine/bevy-website#216
2021-11-13 23:06:48 +00:00
Carter Anderson
9a4cc42b38 EntityRenderCommand and PhaseItemRenderCommand (#3111)
Adds new `EntityRenderCommand`, `EntityPhaseItem`, and `CachedPipelinePhaseItem` traits to make it possible to reuse RenderCommands across phases. This should be helpful for features like #3072 . It also makes the trait impls slightly less generic-ey in the common cases.

This also fixes the custom shader examples to account for the recent Frustum Culling and MSAA changes (the UX for these things will be improved later).
2021-11-12 22:27:17 +00:00
Carter Anderson
85487707ef Sprite Batching (#3060)
This implements the following:

* **Sprite Batching**: Collects sprites in a vertex buffer to draw many sprites with a single draw call. Sprites are batched by their `Handle<Image>` within a specific z-level. When possible, sprites are opportunistically batched _across_ z-levels (when no sprites with a different texture exist between two sprites with the same texture on different z levels). With these changes, I can now get ~130,000 sprites at 60fps on the `bevymark_pipelined` example.
* **Sprite Color Tints**: The `Sprite` type now has a `color` field. Non-white color tints result in a specialized render pipeline that passes the color in as a vertex attribute. I chose to specialize this because passing vertex colors has a measurable price (without colors I get ~130,000 sprites on bevymark, with colors I get ~100,000 sprites). "Colored" sprites cannot be batched with "uncolored" sprites, but I think this is fine because the chance of a "colored" sprite needing to batch with other "colored" sprites is generally probably way higher than an "uncolored" sprite needing to batch with a "colored" sprite.
* **Sprite Flipping**: Sprites can be flipped on their x or y axis using `Sprite::flip_x` and `Sprite::flip_y`. This is also true for `TextureAtlasSprite`.
* **Simpler BufferVec/UniformVec/DynamicUniformVec Clearing**:  improved the clearing interface by removing the need to know the size of the final buffer at the initial clear.

![image](https://user-images.githubusercontent.com/2694663/140001821-99be0d96-025d-489e-9bfa-ba19c1dc9548.png)


Note that this moves sprites away from entity-driven rendering and back to extracted lists. We _could_ use entities here, but it necessitates that an intermediate list is allocated / populated to collect and sort extracted sprites. This redundant copy, combined with the normal overhead of spawning extracted sprite entities, brings bevymark down to ~80,000 sprites at 60fps. I think making sprites a bit more fixed (by default) is worth it. I view this as acceptable because batching makes normal entity-driven rendering pretty useless anyway (and we would want to batch most custom materials too). We can still support custom shaders with custom bindings, we'll just need to define a specific interface for it.
2021-11-04 20:28:53 +00:00
Robert Swain
2f22f5ca21 MSAA example (#3049)
Add an example that demonstrates the difference between no MSAA and MSAA 4x. This is also useful for testing panics when resizing the window using MSAA. This is on top of #3042 .

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-11-03 22:20:23 +00:00
Mike
95032a3f97 change texture atlas sprite indexing to usize (#2887)
Per this comment https://github.com/bevyengine/bevy/pull/2864#discussion_r717947232,
I have done a pass at changing all the public facing indexes for `TextureAtlas` to usize.
2021-11-01 21:28:50 +00:00
Carter Anderson
015617a774 Pipeline Specialization, Shader Assets, and Shader Preprocessing (#3031)
## New Features
This adds the following to the new renderer:

* **Shader Assets**
  * Shaders are assets again! Users no longer need to call `include_str!` for their shaders
  * Shader hot-reloading
* **Shader Defs / Shader Preprocessing**
  * Shaders now support `# ifdef NAME`, `# ifndef NAME`, and `# endif` preprocessor directives
* **Bevy RenderPipelineDescriptor and RenderPipelineCache**
  * Bevy now provides its own `RenderPipelineDescriptor` and the wgpu version is now exported as `RawRenderPipelineDescriptor`. This allows users to define pipelines with `Handle<Shader>` instead of needing to manually compile and reference `ShaderModules`, enables passing in shader defs to configure the shader preprocessor, makes hot reloading possible (because the descriptor can be owned and used to create new pipelines when a shader changes), and opens the doors to pipeline specialization.
  * The `RenderPipelineCache` now handles compiling and re-compiling Bevy RenderPipelineDescriptors. It has internal PipelineLayout and ShaderModule caches. Users receive a `CachedPipelineId`, which can be used to look up the actual `&RenderPipeline` during rendering. 
* **Pipeline Specialization**
  * This enables defining per-entity-configurable pipelines that specialize on arbitrary custom keys. In practice this will involve specializing based on things like MSAA values, Shader Defs, Bind Group existence, and Vertex Layouts.
  * Adds a `SpecializedPipeline` trait and `SpecializedPipelines<MyPipeline>` resource. This is a simple layer that generates Bevy RenderPipelineDescriptors based on a custom key defined for the pipeline.
  * Specialized pipelines are also hot-reloadable.
  * This was the result of experimentation with two different approaches:
    1. **"generic immediate mode multi-key hash pipeline specialization"**
      * breaks up the pipeline into multiple "identities" (the core pipeline definition, shader defs, mesh layout, bind group layout). each of these identities has its own key. looking up / compiling a specific version of a pipeline requires composing all of these keys together
      * the benefit of this approach is that it works for all pipelines / the pipeline is fully identified by the keys. the multiple keys allow pre-hashing parts of the pipeline identity where possible (ex: pre compute the mesh identity for all meshes)
      * the downside is that any per-entity data that informs the values of these keys could require expensive re-hashes. computing each key for each sprite tanked bevymark performance (sprites don't actually need this level of specialization yet ... but things like pbr and future sprite scenarios might). 
      * this is the approach rafx used last time i checked
    2. **"custom key specialization"**
      * Pipelines by default are not specialized
      * Pipelines that need specialization implement a SpecializedPipeline trait with a custom key associated type
      * This allows specialization keys to encode exactly the amount of information required (instead of needing to be a combined hash of the entire pipeline). Generally this should fit in a small number of bytes. Per-entity specialization barely registers anymore on things like bevymark. It also makes things like "shader defs" way cheaper to hash because we can use context specific bitflags instead of strings.
      * Despite the extra trait, it actually generally makes pipeline definitions + lookups simpler: managing multiple keys (and making the appropriate calls to manage these keys) was way more complicated.
  * I opted for custom key specialization. It performs better generally and in my opinion is better UX. Fortunately the way this is implemented also allows for custom caches as this all builds on a common abstraction: the RenderPipelineCache. The built in custom key trait is just a simple / pre-defined way to interact with the cache 

## Callouts

* The SpecializedPipeline trait makes it easy to inherit pipeline configuration in custom pipelines. The changes to `custom_shader_pipelined` and the new `shader_defs_pipelined` example illustrate how much simpler it is to define custom pipelines based on the PbrPipeline.
* The shader preprocessor is currently pretty naive (it just uses regexes to process each line). Ultimately we might want to build a more custom parser for more performance + better error handling, but for now I'm happy to optimize for "easy to implement and understand". 

## Next Steps

* Port compute pipelines to the new system
* Add more preprocessor directives (else, elif, import)
* More flexible vertex attribute specialization / enable cheaply specializing on specific mesh vertex layouts
2021-10-28 19:07:47 +00:00
Yoh Deadfall
ffde86efa0 Update to edition 2021 on master (#3028)
Objective
During work on #3009 I've found that not all jobs use actions-rs, and therefore, an previous version of Rust is used for them. So while compilation and other stuff can pass, checking markup and Android build may fail with compilation errors.

Solution
This PR adds `action-rs` for any job running cargo, and updates the edition to 2021.
2021-10-27 00:12:14 +00:00
François
2f4bcc5bf7 Update for edition 2021 (#2997)
# Objective

- update for Edition 2021

## Solution

- remove the `resolver = "2"`
- update for https://doc.rust-lang.org/edition-guide/rust-2021/reserving-syntax.html by adding a few ` `
2021-10-25 18:00:13 +00:00
Carter Anderson
43e8a156fb Upgrade to wgpu 0.11 (#2933)
Upgrades both the old and new renderer to wgpu 0.11 (and naga 0.7). This builds on @zicklag's work here #2556.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-10-08 19:55:24 +00:00
Paweł Grabarz
07ed1d053e Implement and require #[derive(Component)] on all component structs (#2254)
This implements the most minimal variant of #1843 - a derive for marker trait. This is a prerequisite to more complicated features like statically defined storage type or opt-out component reflection.

In order to make component struct's purpose explicit and avoid misuse, it must be annotated with `#[derive(Component)]` (manual impl is discouraged for compatibility). Right now this is just a marker trait, but in the future it might be expanded. Making this change early allows us to make further changes later without breaking backward compatibility for derive macro users.

This already prevents a lot of issues, like using bundles in `insert` calls. Primitive types are no longer valid components as well. This can be easily worked around by adding newtype wrappers and deriving `Component` for them.

One funny example of prevented bad code (from our own tests) is when an newtype struct or enum variant is used. Previously, it was possible to write `insert(Newtype)` instead of `insert(Newtype(value))`. That code compiled, because function pointers (in this case newtype struct constructor) implement `Send + Sync + 'static`, so we allowed them to be used as components. This is no longer the case and such invalid code will trigger a compile error.


Co-authored-by: = <=>
Co-authored-by: TheRawMeatball <therawmeatball@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-10-03 19:23:44 +00:00
Carter Anderson
08969a24b8 Modular Rendering (#2831)
This changes how render logic is composed to make it much more modular. Previously, all extraction logic was centralized for a given "type" of rendered thing. For example, we extracted meshes into a vector of ExtractedMesh, which contained the mesh and material asset handles, the transform, etc. We looked up bindings for "drawn things" using their index in the `Vec<ExtractedMesh>`. This worked fine for built in rendering, but made it hard to reuse logic for "custom" rendering. It also prevented us from reusing things like "extracted transforms" across contexts.

To make rendering more modular, I made a number of changes:

* Entities now drive rendering:
  * We extract "render components" from "app components" and store them _on_ entities. No more centralized uber lists! We now have true "ECS-driven rendering"
  * To make this perform well, I implemented #2673 in upstream Bevy for fast batch insertions into specific entities. This was merged into the `pipelined-rendering` branch here: #2815
* Reworked the `Draw` abstraction:
  * Generic `PhaseItems`: each draw phase can define its own type of "rendered thing", which can define its own "sort key"
  * Ported the 2d, 3d, and shadow phases to the new PhaseItem impl (currently Transparent2d, Transparent3d, and Shadow PhaseItems)
  * `Draw` trait and and `DrawFunctions` are now generic on PhaseItem
  * Modular / Ergonomic `DrawFunctions` via `RenderCommands`
    * RenderCommand is a trait that runs an ECS query and produces one or more RenderPass calls. Types implementing this trait can be composed to create a final DrawFunction. For example the DrawPbr DrawFunction is created from the following DrawCommand tuple. Const generics are used to set specific bind group locations:
        ```rust
         pub type DrawPbr = (
            SetPbrPipeline,
            SetMeshViewBindGroup<0>,
            SetStandardMaterialBindGroup<1>,
            SetTransformBindGroup<2>,
            DrawMesh,
        );
        ```
    * The new `custom_shader_pipelined` example illustrates how the commands above can be reused to create a custom draw function:
       ```rust
       type DrawCustom = (
           SetCustomMaterialPipeline,
           SetMeshViewBindGroup<0>,
           SetTransformBindGroup<2>,
           DrawMesh,
       );
       ``` 
* ExtractComponentPlugin and UniformComponentPlugin:
  * Simple, standardized ways to easily extract individual components and write them to GPU buffers
* Ported PBR and Sprite rendering to the new primitives above.
* Removed staging buffer from UniformVec in favor of direct Queue usage
  * Makes UniformVec much easier to use and more ergonomic. Completely removes the need for custom render graph nodes in these contexts (see the PbrNode and view Node removals and the much simpler call patterns in the relevant Prepare systems).
* Added a many_cubes_pipelined example to benchmark baseline 3d rendering performance and ensure there were no major regressions during this port. Avoiding regressions was challenging given that the old approach of extracting into centralized vectors is basically the "optimal" approach. However thanks to a various ECS optimizations and render logic rephrasing, we pretty much break even on this benchmark!
* Lifetimeless SystemParams: this will be a bit divisive, but as we continue to embrace "trait driven systems" (ex: ExtractComponentPlugin, UniformComponentPlugin, DrawCommand), the ergonomics of `(Query<'static, 'static, (&'static A, &'static B, &'static)>, Res<'static, C>)` were getting very hard to bear. As a compromise, I added "static type aliases" for the relevant SystemParams. The previous example can now be expressed like this: `(SQuery<(Read<A>, Read<B>)>, SRes<C>)`. If anyone has better ideas / conflicting opinions, please let me know!
* RunSystem trait: a way to define Systems via a trait with a SystemParam associated type. This is used to implement the various plugins mentioned above. I also added SystemParamItem and QueryItem type aliases to make "trait stye" ecs interactions nicer on the eyes (and fingers).
* RenderAsset retrying: ensures that render assets are only created when they are "ready" and allows us to create bind groups directly inside render assets (which significantly simplified the StandardMaterial code). I think ultimately we should swap this out on "asset dependency" events to wait for dependencies to load, but this will require significant asset system changes.
* Updated some built in shaders to account for missing MeshUniform fields
2021-09-23 06:16:11 +00:00
Carter Anderson
11b41206eb Add upstream bevy_ecs and prepare for custom-shaders merge (#2815)
This updates the `pipelined-rendering` branch to use the latest `bevy_ecs` from `main`. This accomplishes a couple of goals:

1. prepares for upcoming `custom-shaders` branch changes, which were what drove many of the recent bevy_ecs changes on `main`
2. prepares for the soon-to-happen merge of `pipelined-rendering` into `main`. By including bevy_ecs changes now, we make that merge simpler / easier to review. 

I split this up into 3 commits:

1. **add upstream bevy_ecs**: please don't bother reviewing this content. it has already received thorough review on `main` and is a literal copy/paste of the relevant folders (the old folders were deleted so the directories are literally exactly the same as `main`).
2. **support manual buffer application in stages**: this is used to enable the Extract step. we've already reviewed this once on the `pipelined-rendering` branch, but its worth looking at one more time in the new context of (1).
3. **support manual archetype updates in QueryState**: same situation as (2).
2021-09-14 06:14:19 +00:00
MinerSebas
9effc3e9b3 Replace .insert_resource(T::default()) calls with init_resource::<T>() (#2807)
# Objective

I added the [INSERT_RESOURCE_WITH_DEFAULT](https://minersebas.github.io/bevy_lint/bevy_lint/static.INSERT_RESOURCE_WITH_DEFAULT.html) Lint to [bevy_lint](https://github.com/MinerSebas/bevy_lint) and while Testing it on bevy itself, I found several places where the Lint correctly triggered.



## Solution

Replace `.insert_resource(T::default())` calls with `init_resource::<T>()`
2021-09-13 14:02:28 +00:00
Charles Giguere
51a5070cd2 add get_single variant (#2793)
# Objective

The vast majority of `.single()` usage I've seen is immediately followed by a `.unwrap()`. Since it seems most people use it without handling the error, I think making it easier to just get what you want fast while also having a more verbose alternative when you want to handle the error could help.

## Solution

Instead of having a lot of `.unwrap()` everywhere, this PR introduces a `try_single()` variant that behaves like the current `.single()` and make the new `.single()` panic on error.
2021-09-10 20:23:50 +00:00
willolisp
5ff96b8e7e Improve many sprites example (#2785)
# Objective

My attempt at fixing #2075 .

This is my very first contribution to this repo. Also, I'm very new to both Rust and bevy, so any feedback is *deeply* appreciated.

## Solution
- Changed `move_camera_system` so it only targets the camera entity. My approach here differs from the one used in the [cheatbook](https://bevy-cheatbook.github.io/cookbook/cursor2world.html?highlight=maincamera#2d-games) (in which a marker component is used to track the camera), so please, let me know which of them is more idiomatic.
- `move_camera_system` does not require both `Position` and `Transform` anymore (I used `rotate` for rotating the `Transform` in place, but couldn't find an equivalent `translate` method).
- Changed `tick_system` so it only targets the timer entity.
- Sprites are now spawned via a single `spawn_batch` instead of multiple `spawn`s.
2021-09-10 19:13:14 +00:00
Caleb Boylan
ca54478569 Fix breakout example scoreboard (#2770)
# Objective

- The breakout scoreboard was not using the correct text section to display the score integer.

## Solution

- This updates the code to use the correct text section.
2021-09-04 18:52:10 +00:00
Daniel McNab
321d998615 Add convenience methods for checking a set of inputs (#2760)
# Objective

Make it easier to check if some set of inputs matches a key, such as if you want to allow all of space or up or w for jumping.

Currently, this requires:
```rust
if keyboard.pressed(KeyCode::Space)
            || keyboard.pressed(KeyCode::Up)
            || keyboard.pressed(KeyCode::W) {
    // ...
```

## Solution

Add an implementation of the helper methods, which very simply iterate through the items, used as:
```rust
if keyboard.any_pressed([KeyCode::Space, KeyCode::Up, KeyCode::W]) {
```
2021-09-01 21:21:41 +00:00
Robert Swain
045f324e97 Use the infinite reverse right-handed perspective projection (#2543)
# Objective

Forward perspective projections have poor floating point precision distribution over the depth range. Reverse projections fair much better, and instead of having to have a far plane, with the reverse projection, using an infinite far plane is not a problem. The infinite reverse perspective projection has become the industry standard. The renderer rework is a great time to migrate to it.

## Solution

All perspective projections, including point lights, have been moved to using `glam::Mat4::perspective_infinite_reverse_rh()` and so have no far plane. As various depth textures are shared between orthographic and perspective projections, a quirk of this PR is that the near and far planes of the orthographic projection are swapped when the Mat4 is computed. This has no impact on 2D/3D orthographic projection usage, and provides consistency in shaders, texture clear values, etc. throughout the codebase.

## Known issues

For some reason, when looking along -Z, all geometry is black. The camera can be translated up/down / strafed left/right and geometry will still be black. Moving forward/backward or rotating the camera away from looking exactly along -Z causes everything to work as expected.

I have tried to debug this issue but both in macOS and Windows I get crashes when doing pixel debugging. If anyone could reproduce this and debug it I would be very grateful. Otherwise I will have to try to debug it further without pixel debugging, though the projections and such all looked fine to me.
2021-08-27 20:15:09 +00:00
Zicklag
cea7db1050 Remove Need for Sprite Size Sync System (#2632)
# Objective

- Prevent the need to have a system that synchronizes sprite sizes with their images

## Solution

- Read the sprite size from the image asset when rendering the sprite
- Replace the `size` and `resize_mode` fields of `Sprite` with a `custom_size: Option<Vec2>` that will modify the sprite's rendered size to be different than the image size, but only if it is `Some(Vec2)`
2021-08-26 00:53:51 +00:00
Robert Swain
f4aa3284a8 bevy_pbr2: Add support for not casting/receiving shadows (#2726)
# Objective

Allow marking meshes as not casting / receiving shadows.

## Solution

- Added `NotShadowCaster` and `NotShadowReceiver` zero-sized type components.
- Extract these components into `bool`s in `ExtractedMesh`
- Only generate `DrawShadowMesh` `Drawable`s for meshes _without_ `NotShadowCaster`
- Add a `u32` bit `flags` member to `MeshUniform` with one flag indicating whether the mesh is a shadow receiver
- If a mesh does _not_ have the `NotShadowReceiver` component, then it is a shadow receiver, and so the bit in the `MeshUniform` is set, otherwise it is not set.
- Added an example illustrating the functionality.

NOTE: I wanted to have the default state of a mesh as being a shadow caster and shadow receiver, hence the `Not*` components. However, I am on the fence about this. I don't want to have a negative performance impact, nor have people wondering why their custom meshes don't have shadows because they forgot to add `ShadowCaster` and `ShadowReceiver` components, but I also really don't like the double negatives the `Not*` approach incurs. What do you think?

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-08-25 19:44:20 +00:00
Robert Swain
c3d3ae7f92 bevy_pbr2: Improve lighting units and documentation (#2704)
# Objective

A question was raised on Discord about the units of the `PointLight` `intensity` member.

After digging around in the bevy_pbr2 source code and [Google Filament documentation](https://google.github.io/filament/Filament.html#mjx-eqn-pointLightLuminousPower) I discovered that the intention by Filament was that the 'intensity' value for point lights would be in lumens. This makes a lot of sense as these are quite relatable units given basically all light bulbs I've seen sold over the past years are rated in lumens as people move away from thinking about how bright a bulb is relative to a non-halogen incandescent bulb.

However, it seems that the derivation of the conversion between luminous power (lumens, denoted `Φ` in the Filament formulae) and luminous intensity (lumens per steradian, `I` in the Filament formulae) was missed and I can see why as it is tucked right under equation 58 at the link above. As such, while the formula states that for a point light, `I = Φ / 4 π` we have been using `intensity` as if it were luminous intensity `I`.

Before this PR, the intensity field is luminous intensity in lumens per steradian. After this PR, the intensity field is luminous power in lumens, [as suggested by Filament](https://google.github.io/filament/Filament.html#table_lighttypesunits) (unfortunately the link jumps to the table's caption so scroll up to see the actual table).

I appreciate that it may be confusing to call this an intensity, but I think this is intended as more of a non-scientific, human-relatable general term with a bit of hand waving so that most light types can just have an intensity field and for most of them it works in the same way or at least with some relatable value. I'm inclined to think this is reasonable rather than throwing terms like luminous power, luminous intensity, blah at users.

## Solution

- Documented the `PointLight` `intensity` member as 'luminous power' in units of lumens.
- Added a table of examples relating from various types of household lighting to lumen values.
- Added in the mapping from luminous power to luminous intensity when premultiplying the intensity into the colour before it is made into a graphics uniform.
- Updated the documentation in `pbr.wgsl` to clarify the earlier confusion about the missing `/ 4 π`.
- Bumped the intensity of the point lights in `3d_scene_pipelined` to 1600 lumens.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-08-23 23:48:11 +00:00
Zicklag
3faca93f7b Add ClearColor Resource to Pipelined Renderer (#2631)
# Objective

- Allow the user to set the clear color when using the pipelined renderer

## Solution

- Add a `ClearColor` resource that can be added to the world to configure the clear color

## Remaining Issues

Currently the `ClearColor` resource is cloned from the app world to the render world every frame. There are two ways I can think of around this:

1. Figure out why `app_world.is_resource_changed::<ClearColor>()` always returns `true` in the `extract` step and fix it so that we are only updating the resource when it changes
2. Require the users to add the `ClearColor` resource to the render sub-app instead of the parent app. This is currently sub-optimal until we have labled sub-apps, and probably a helper funciton on `App` such as `app.with_sub_app(RenderApp, |app| { ... })`. Even if we had that, I think it would be more than we want the user to have to think about. They shouldn't have to know about the render sub-app I don't think.

I think the first option is the best, but I could really use some help figuring out the nuance of why `is_resource_changed` is always returning true in that context.
2021-08-19 20:34:31 +00:00
Carter Anderson
9d453530fa System Param Lifetime Split (#2605)
# Objective

Enable using exact World lifetimes during read-only access . This is motivated by the new renderer's need to allow read-only world-only queries to outlive the query itself (but still be constrained by the world lifetime).

For example:
115b170d1f/pipelined/bevy_pbr2/src/render/mod.rs (L774)

## Solution

Split out SystemParam state and world lifetimes and pipe those lifetimes up to read-only Query ops (and add into_inner for Res). According to every safety test I've run so far (except one), this is safe (see the temporary safety test commit). Note that changing the mutable variants to the new lifetimes would allow aliased mutable pointers (try doing that to see how it affects the temporary safety tests).

The new state lifetime on SystemParam does make `#[derive(SystemParam)]` more cumbersome (the current impl requires PhantomData if you don't use both lifetimes). We can make this better by detecting whether or not a lifetime is used in the derive and adjusting accordingly, but that should probably be done in its own pr.  

## Why is this a draft?

The new lifetimes break QuerySet safety in one very specific case (see the query_set system in system_safety_test). We need to solve this before we can use the lifetimes given.

This is due to the fact that QuerySet is just a wrapper over Query, which now relies on world lifetimes instead of `&self` lifetimes to prevent aliasing (but in systems, each Query has its own implied lifetime, not a centralized world lifetime).  I believe the fix is to rewrite QuerySet to have its own World lifetime (and own the internal reference). This will complicate the impl a bit, but I think it is doable. I'm curious if anyone else has better ideas.

Personally, I think these new lifetimes need to happen. We've gotta have a way to directly tie read-only World queries to the World lifetime. The new renderer is the first place this has come up, but I doubt it will be the last. Worst case scenario we can come up with a second `WorldLifetimeQuery<Q, F = ()>` parameter to enable these read-only scenarios, but I'd rather not add another type to the type zoo.
2021-08-15 20:51:53 +00:00
Carter Anderson
a89a954a17 Not me ... us (#2654)
I don't see much of a reason at this point to boost my name over anyone elses. We are all Bevy Contributors.
2021-08-15 20:08:52 +00:00
davier
6aedb2500a Cleanup FromResources (#2601)
## Objective

- Clean up remaining references to the trait `FromResources`, which was replaced in favor of `FromWorld` during the ECS rework.

## Solution

- Remove the derive macro for `FromResources`
- Change doc references of `FromResources` to `FromWorld`

(this is the first item in #2576)
2021-08-13 22:21:34 +00:00
Zicklag
c8330037e7 Re-implement Automatic Sprite Sizing (#2613)
# Objective

- Prevent the need to specify a sprite size when using the pipelined sprite renderer

## Solution

- Re-introduce the sprite auto resize system from the old renderer
2021-08-10 02:26:06 +00:00
Hoidigan
49038d03f5 Remove with bundle filter (#2623)
# Objective

Fixes #2620

## Solution

Remove WithBundle filter and temporarily remove example for query_bundle.
2021-08-10 01:55:52 +00:00
John
115b170d1f Add sprite atlases into the new renderer. (#2560)
# Objective
Restore the functionality of sprite atlases in the new renderer.

### **Note:** This PR relies on #2555 

## Solution
Mostly just a copy paste of the existing sprite atlas implementation, however I unified the rendering between sprites and atlases.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-08-04 01:16:25 +00:00
Robert Swain
ae4f809a52 Port bevy_gltf to pipelined-rendering (#2537)
# Objective

Port bevy_gltf to the pipelined-rendering branch.

## Solution

crates/bevy_gltf has been copied and pasted into pipelined/bevy_gltf2 and modifications were made to work with the pipelined-rendering branch. Notably vertex tangents and vertex colours are not supported.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-07-30 03:37:34 +00:00
Boxy
0b800e547b Fix some nightly clippy lints (#2522)
on nightly these two clippy lints fail:
- [needless_borrow](https://rust-lang.github.io/rust-clippy/master/#needless_borrow)
- [unused_unit](https://rust-lang.github.io/rust-clippy/master/#unused_unit)
2021-07-29 19:36:39 -07:00
Boxy
5ffff03b33 Fix some nightly clippy lints (#2522)
on nightly these two clippy lints fail:
- [needless_borrow](https://rust-lang.github.io/rust-clippy/master/#needless_borrow)
- [unused_unit](https://rust-lang.github.io/rust-clippy/master/#unused_unit)
2021-07-29 20:52:15 +00:00
François
b724a0f586 Down with the system! (#2496)
# Objective

- Remove all the `.system()` possible.
- Check for remaining missing cases.

## Solution

- Remove all `.system()`, fix compile errors
- 32 calls to `.system()` remains, mostly internals, the few others should be removed after #2446
2021-07-27 23:42:36 +00:00
bjorn3
6d6bc2a8b4 Merge AppBuilder into App (#2531)
This is extracted out of eb8f973646476b4a4926ba644a77e2b3a5772159 and includes some additional changes to remove all references to AppBuilder and fix examples that still used App::build() instead of App::new(). In addition I didn't extract the sub app feature as it isn't ready yet.

You can use `git diff --diff-filter=M eb8f973646476b4a4926ba644a77e2b3a5772159` to find all differences in this PR. The `--diff-filtered=M` filters all files added in the original commit but not in this commit away.

Co-Authored-By: Carter Anderson <mcanders1@gmail.com>
2021-07-27 20:21:06 +00:00
Carter Anderson
2e99d84cdc remove .system from pipelined code (#2538)
Now that we have main features, lets use them!
2021-07-26 23:44:23 +00:00
Robert Swain
618c9e94f0 Scale normal bias by texel size (#26)
* 3d_scene_pipelined: Use a shallower directional light angle to provoke acne

* cornell_box_pipelined: Remove bias tweaks

* bevy_pbr2: Simplify shadow biases by moving them to linear depth

* bevy_pbr2: Do not use DepthBiasState

* bevy_pbr2: Do not use bilinear filtering for sampling depth textures

* pbr.wgsl: Remove unnecessary comment

* bevy_pbr2: Do manual shadow map depth comparisons for more flexibility

* examples: Add shadow_biases_pipelined example

This is useful for stress testing biases.

* bevy_pbr2: Scale the point light normal bias by the shadow map texel size

This allows the normal bias to be small close to the light source where the
shadow map texel to screen texel ratio is high, but is appropriately large
further away from the light source where the shadow map texel can easily cover
multiple screen texels.

* shadow_biases_pipelined: Add support for toggling directional / point light

* shadow_biases_pipelined: Cleanup

* bevy_pbr2: Scale the directional light normal bias by the shadow map texel size

* shadow_biases_pipelined: Fit the orthographic projection around the scene

* bevy_pbr2: Directional lights should have no shadows outside their projection

Before this change, sampling a fragment position from outside the ndc volume
would result in the return sample being clamped to the edge in x,y or possibly
always casting a shadow for fragment positions past the orthographic
projection's far plane.

* bevy_pbr2: Fix the default directional light normal bias

* Revert "bevy_pbr2: Do manual shadow map depth comparisons for more flexibility"

This reverts commit 7df1bab38a42d8a33bc50ca583d4be37bd9c9f0d.

* shadow_biases_pipelined: Adjust directional light normal bias in 0.1 increments

* pbr.wgsl: Add a couple of clarifying comments

* Revert "bevy_pbr2: Do not use bilinear filtering for sampling depth textures"

This reverts commit f53baab0232ce218866a45cad6902b470f4cf2c4.

* shadow_biases_pipelined: Print usage to terminal
2021-07-24 16:43:37 -07:00
Robert Swain
44df4c1fae Better depth biases (#23)
* 3d_scene_pipelined: Use a shallower directional light angle to provoke acne

* cornell_box_pipelined: Remove bias tweaks

* bevy_pbr2: Simplify shadow biases by moving them to linear depth
2021-07-24 16:43:37 -07:00
Carter Anderson
e0205019ef fmt + clippy 2021-07-24 16:43:37 -07:00
Robert Swain
326b20643f Directional light and shadow (#6)
Directional light and shadow
2021-07-24 16:43:37 -07:00
Carter Anderson
ac6b27925e fix clippy 2021-07-24 16:43:37 -07:00
Carter Anderson
bc769d9641 omni light -> point light 2021-07-24 16:43:37 -07:00
Jonas Matser
4099ef6aa2 Omnilight shadow map wgsl (#15) 2021-07-24 16:43:37 -07:00
Carter Anderson
61c8475069 Begin WGSL port (sprites work, pbr lights are broken) 2021-07-24 16:43:37 -07:00
Robert Swain
b1a91a823f bevy_pbr2: Add support for most of the StandardMaterial textures (#4)
* bevy_pbr2: Add support for most of the StandardMaterial textures

Normal maps are not included here as they require tangents in a vertex attribute.

* bevy_pbr2: Ensure RenderCommandQueue is ready for PbrShaders init

* texture_pipelined: Add a light to the scene so we can see stuff

* WIP bevy_pbr2: back to front sorting hack

* bevy_pbr2: Uniform control flow for texture sampling in pbr.frag

From 'fintelia' on the Bevy Render Rework Round 2 discussion:

"My understanding is that GPUs these days never use the "execute both branches
and select the result" strategy. Rather, what they do is evaluate the branch
condition on all threads of a warp, and jump over it if all of them evaluate to
false. If even a single thread needs to execute the if statement body, however,
then the remaining threads are paused until that is completed."

* bevy_pbr2: Simplify texture and sampler names

The StandardMaterial_ prefix is no longer needed

* bevy_pbr2: Match default 'AmbientColor' of current bevy_pbr for now

* bevy_pbr2: Convert from non-linear to linear sRGB for the color uniform

* bevy_pbr2: Add pbr_pipelined example

* Fix view vector in pbr frag to work in ortho

* bevy_pbr2: Use a 90 degree y fov and light range projection for lights

* bevy_pbr2: Add AmbientLight resource

* bevy_pbr2: Convert PointLight color to linear sRGB for use in fragment shader

* bevy_pbr2: pbr.frag: Rename PointLight.projection to view_projection

The uniform contains the view_projection matrix so this was incorrect.

* bevy_pbr2: PointLight is an OmniLight as it has a radius

* bevy_pbr2: Factoring out duplicated code

* bevy_pbr2: Implement RenderAsset for StandardMaterial

* Remove unnecessary texture and sampler clones

* fix comment formatting

* remove redundant Buffer:from

* Don't extract meshes when their material textures aren't ready

* make missing textures in the queue step an error

Co-authored-by: Aevyrie <aevyrie@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-07-24 16:43:37 -07:00
Carter Anderson
25de2d1819 Port Mesh to RenderAsset, add Slab and FrameSlabMap garbage collection for Bind Groups 2021-07-24 16:43:37 -07:00
Carter Anderson
13ca00178a bevy_render now uses wgpu directly 2021-07-24 16:43:37 -07:00
Robert Swain
01116b1fdb StandardMaterial flat values (#3)
StandardMaterial flat values
2021-07-24 16:43:37 -07:00
Carter Anderson
3400fb4e61 SubGraphs, Views, Shadows, and more 2021-07-24 16:43:37 -07:00
Carter Anderson
4ac2ed7cc6 pipelined rendering proof of concept 2021-07-24 16:43:37 -07:00
François
57c021538e rename example change_detection to have unique name (#2419)
# Objective

Noticed a warning when running tests:
```
> cargo test --workspace
warning: output filename collision.
The example target `change_detection` in package `bevy_ecs v0.5.0 (/bevy/crates/bevy_ecs)` has the same output filename as the example target `change_detection` in package `bevy v0.5.0 (/bevy)`.
Colliding filename is: /bevy/target/debug/examples/change_detection
The targets should have unique names.
Consider changing their names to be unique or compiling them separately.
This may become a hard error in the future; see <https://github.com/rust-lang/cargo/issues/6313>.
warning: output filename collision.
The example target `change_detection` in package `bevy_ecs v0.5.0 (/bevy/crates/bevy_ecs)` has the same output filename as the example target `change_detection` in package `bevy v0.5.0 (/bevy)`.
Colliding filename is: /bevy/target/debug/examples/change_detection.dSYM
The targets should have unique names.
Consider changing their names to be unique or compiling them separately.
This may become a hard error in the future; see <https://github.com/rust-lang/cargo/issues/6313>.
```


## Solution

I renamed example `change_detection` to `component_change_detection`
2021-07-12 20:09:43 +00:00
Alexander Sepity
10f2dd3ec5 Optional .system(), part 2 (#2403)
# Objective

- Extend work done in #2398.
- Make `.system()` syntax optional when using system descriptor API.

## Solution

- Slight change to `ParallelSystemDescriptorCoercion` signature and implementors.

---

I haven't touched exclusive systems, because it looks like the only two other solutions are going back to doubling our system insertion methods, or starting to lean into stageless. The latter will invalidate the former, so I think exclusive systems should remian pariahs until stageless.

I can grep & nuke `.system()` thorughout the codebase now, which might take a while, or we can do that in subsequent PR(s).
2021-06-29 19:47:46 +00:00
Daniel McNab
c893b99224 Optional .system (#2398)
This can be your 6 months post-christmas present.

# Objective

- Make `.system` optional
- yeet
- It's ugly
- Alternative title: `.system` is dead; long live `.system`
- **yeet**

## Solution

- Use a higher ranked lifetime, and some trait magic.

N.B. This PR does not actually remove any `.system`s, except in a couple of examples. Once this is merged we can do that piecemeal across crates, and decide on syntax for labels.
2021-06-27 00:40:09 +00:00
Michael Hills
040ad7f5a4 Add audio to ios example (#1007)
I'm still here :) will try to land the ios audio support in cpal soon and then we can land this.

This PR also adds in assets as a directory reference and avoids the "Xcode is optimizing and breaking my PNGs" issue that I had earlier on during iOS testing on Bevy.

Re-testing this now.
2021-05-30 18:39:31 +00:00
Andreas Weibye
44f64a32f4 CI - Check that examples are listed in README and Cargo (#1650)
Closes #1581 

# Internal File/Link Consistency checker Action

This pull request adds an action to the CI that parses the [`./examples`](https://github.com/bevyengine/bevy/tree/main/examples) folder for files and cross references that with the links listed in [`README.md`](https://github.com/bevyengine/bevy/blob/main/examples/README.md) and [`Cargo.toml`](https://github.com/bevyengine/bevy/blob/main/Cargo.toml) to ensure the documentation actually reflects the examples currently in the repo. 

The primary reason for why we want this, is to prevent people from adding new examples but forgetting to also list them in the docs, or accidentally entering broken links (typos in docs).

For details on how the action is working: [Check out the README here](https://github.com/Weibye/action-internal-link-consistency/blob/main/README.md)

Co-authored-by: Andreas Weibye <13300393+Weibye@users.noreply.github.com>
2021-05-30 18:14:58 +00:00
Federico Rinaldi
4f34143046 Add iter_combinations to examples' README.md (#2266)
Added a short description of the example.

Fixes #2263.
2021-05-29 01:30:28 +00:00
Daniel Borges
5cccba5d21 Fixed a comment in the fixed timestep example (#2245)
Co-authored-by: Daniel Borges <daniel@manufacture43.com>
2021-05-24 20:05:36 +00:00
the-notable
9f94f7eb6c Example showing how to use AsyncComputeTaskPool and Tasks (#2180) 2021-05-23 20:13:55 +00:00
Paweł Grabarz
a81fb7aa7e Add a method iter_combinations on query to iterate over combinations of query results (#1763)
Related to [discussion on discord](https://discord.com/channels/691052431525675048/742569353878437978/824731187724681289)

With const generics, it is now possible to write generic iterator over multiple entities at once.

This enables patterns of query iterations like

```rust
for [e1, e2, e3] in query.iter_combinations() {
   // do something with relation of all three entities
}
```

The compiler is able to infer the correct iterator for given size of array, so either of those work
```rust
for [e1, e2] in query.iter_combinations()  { ... }
for [e1, e2, e3] in query.iter_combinations()  { ... }
```

This feature can be very useful for systems like collision detection.

When you ask for permutations of size K of N entities:
- if K == N, you get one result of all entities
- if K < N, you get all possible subsets of N with size K, without repetition
- if K > N, the result set is empty (no permutation of size K exist)

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-05-17 23:33:47 +00:00
Aevyrie
85b17294b9 Fix PBR regression for unlit materials (#2197)
Fixes the frag shader for unlit materials by correcting the scope of the `#ifndef` to include the light functions. Closes #2190, introduced in #2112.

Tested by changing materials in the the `3d_scene` example to be unlit. Unsure how to prevent future regressions without creating a test case scene that will catch these runtime panics.
2021-05-17 22:45:07 +00:00
Nathan Ward
e3435e5144 fix scenes-example unread field warning (#2179)
This should fix CI error: https://github.com/bevyengine/bevy/pull/2175/checks?check_run_id=2592736553
2021-05-16 18:09:47 +00:00
giusdp
cdae95b4b8 Add exit_on_esc_system to examples with window (#2121)
This covers issue #2110

It adds the line `.add_system(bevy::input::system::exit_on_esc_system.system())` before `.run()`
to every example that uses a window, so users have a quick way to close the examples.

I used the full name `bevy::input::system::exit_on_esc_system`, I thought it gave clarity about being a built-in system.

The examples excluded from the change are the ones in the android, ios, wasm folders, the headless 
examples and the ecs/system_sets example because it closes itself.
2021-05-14 20:15:54 +00:00
FlyingRatBull
ff4acee9e1 [DOC] Mention FPS in log_diagnostics example (#2150)
Closes #2076
2021-05-14 18:26:09 +00:00
Denis Laprise
7d0e98f34c Implement rotation for Text2d (#2084)
Fixes https://github.com/bevyengine/bevy/issues/2080

![CleanShot 2021-05-02 at 22 50 09](https://user-images.githubusercontent.com/11653/116844876-373ca780-ab99-11eb-8f61-8d93d929bff0.gif)


Co-authored-by: Nathan Stocks <cleancut@github.com>
Co-authored-by: Denis Laprise <nside@users.noreply.github.com>
2021-05-06 03:55:55 +00:00
François
afaf4ad3da update for wgpu 0.8 (#1959)
Changes to get Bevy to compile with wgpu master.

With this, on a Mac:
* 2d examples look fine
* ~~3d examples crash with an error specific to metal about a compilation error~~
* 3d examples work fine after enabling feature `wgpu/cross`


Feature `wgpu/cross` seems to be needed only on some platforms, not sure how to know which. It was introduced in https://github.com/gfx-rs/wgpu-rs/pull/826
2021-05-02 20:45:25 +00:00
FlyingRatBull
b399a374cb GitHub Action: Check local Markdown links on push (#2067)
Adds an GitHub Action to check all local (non http://, https:// ) links in all Markdown files of the repository for liveness.
Fails if a file is not found.

# Goal
This should help maintaining the quality of the documentation.

# Impact
Takes ~24 seconds currently and found 3 dead links (pull requests already created).

# Dependent PRs
* #2064 
* #2065 
* #2066

# Info
See [markdown-link-check](https://github.com/marketplace/actions/markdown-link-check).

# Example output
```
FILE: ./docs/profiling.md

1 links checked.

FILE: ./docs/plugins_guidelines.md

37 links checked.

FILE: ./docs/linters.md
[✖] ../.github/linters/markdown-lint.yml → Status: 400 [Error: ENOENT: no such file or directory, access '/github/workspace/.github/linters/markdown-lint.yml'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'access',
  path: '/github/workspace/.github/linters/markdown-lint.yml'
}
```

# Improvements
* Can also be used to check external links, but fails because of:
  * Too many requests (429) responses:
```
FILE: ./CHANGELOG.md
[✖] https://github.com/bevyengine/bevy/pull/1762 → Status: 429
```
   * crates.io links respond 404
```
FILE: ./README.md
[✖] https://crates.io/crates/bevy → Status: 404
```
2021-05-02 20:22:32 +00:00
FlyingRatBull
82014a3abd Fix broken link to touch_input_events example (#2066) 2021-05-01 18:51:55 +00:00
FlyingRatBull
4e5210f8e9 Fix broken link to PBR example in README.md (#2064) 2021-05-01 18:51:54 +00:00
CGMossa
86ad5bf420 Adding WorldQuery for WithBundle (#2024)
In response to #2023, here is a draft for a PR. 

Fixes #2023

I've added an example to show how to use `WithBundle`, and also to test it out. 

Right now there is a bug: If a bundle and a query are "the same", then it doesn't filter out
what it needs to filter out. 

Example: 

```
Print component initated from bundle.
[examples/ecs/query_bundle.rs:57] x = Dummy( <========= This should not get printed
    111,
)
[examples/ecs/query_bundle.rs:57] x = Dummy(
    222,
)
Show all components
[examples/ecs/query_bundle.rs:50] x = Dummy(
    111,
)
[examples/ecs/query_bundle.rs:50] x = Dummy(
    222,
)
```

However, it behaves the right way, if I add one more component to the bundle,
so the query and the bundle doesn't look the same:

```
Print component initated from bundle.
[examples/ecs/query_bundle.rs:57] x = Dummy(
    222,
)
Show all components
[examples/ecs/query_bundle.rs:50] x = Dummy(
    111,
)
[examples/ecs/query_bundle.rs:50] x = Dummy(
    222,
)
```

I hope this helps. I'm definitely up for tinkering with this, and adding anything that I'm asked to add
or change. 





Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-04-28 21:03:10 +00:00
Grindv1k
38feddb878 Add system sets and run criteria example (#1909)
If accepted, fixes #1694 .

I wanted to explore system sets and run criteria a bit, so made an example expanding a bit on the snippets shown in the 0.5 release post.

Shows a couple of system sets, uses system labels, run criterion, and a use of the interesting `RunCriterion::pipe` functionality.
2021-04-23 19:08:16 +00:00
François
e3fb23d4d3 add documentation on LogPlugin and more log usage (#1973)
Fixes #1895 

Changed most `println` to `info` in examples, some to `warn` when it was useful to differentiate from other more noisy logs.

Added doc on `LogPlugin`, how to configure it, and why (and how) you may need to disable it
2021-04-22 23:30:48 +00:00
Alice Cecile
e4e32598a9 Cargo fmt with unstable features (#1903)
Fresh version of #1670 off the latest main.

Mostly fixing documentation wrapping.
2021-04-21 23:19:34 +00:00
MinerSebas
458312236a Document setting "CARGO_MANIFEST_DIR" for asset root (#1950)
This was nowhere documented inside Bevy.
Should I also mention the use case of debugging a project?

Closes #810

Co-authored-by: MinerSebas <66798382+MinerSebas@users.noreply.github.com>
2021-04-19 22:16:23 +00:00
Mariusz Kryński
fa6d4dbd53 add render_to_texture example (#1927)
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-04-19 21:07:19 +00:00
Alister Lee
3d4b1b9ff2 Fix alien_cake_addict: cake should not be at height of player's location (#1954)
Just to avoid confusion to close readers of the example, this fix ensures cake is transformed to the height at the cake's cell, rather than the height at the player's cell.

Without this, cake may be floating or buried, depending on where the player is standing at time of spawning.

Love your work!
2021-04-19 20:45:41 +00:00
MinerSebas
20673dbe0e Doctest improvments (#1937) 2021-04-16 19:13:08 +00:00
Logan Magee
d508923eb7 Allow deriving SystemParam on private types (#1936)
Examples creating a public type to derive `SystemParam` on were updated
to create a private type where a public one is no longer needed.

Resolves #1869
2021-04-16 18:40:49 +00:00
Anselmo Sampietro
9b7ed18f72 Add animate shaders example (#1765)
This PR adds an example on how to animate a shader by passing the global `time.seconds_since_startup()` to a component, and accessing that component inside the shader.

Hopefully this is the current proper solution, please let me know if it should be solved in another way.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-04-15 19:49:31 +00:00