Commit graph

513 commits

Author SHA1 Message Date
Dusty DeWeese
81d57e129b Add capability to render to a texture (#3412)
# Objective

Will fix #3377 and #3254

## Solution

Use an enum to represent either a `WindowId` or `Handle<Image>` in place of `Camera::window`.


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-02-24 00:40:24 +00:00
Carter Anderson
e369a8ad51 Mesh vertex buffer layouts (#3959)
This PR makes a number of changes to how meshes and vertex attributes are handled, which the goal of enabling easy and flexible custom vertex attributes:
* Reworks the `Mesh` type to use the newly added `VertexAttribute` internally
  * `VertexAttribute` defines the name, a unique `VertexAttributeId`, and a `VertexFormat`
  *  `VertexAttributeId` is used to produce consistent sort orders for vertex buffer generation, replacing the more expensive and often surprising "name based sorting"  
  * Meshes can be used to generate a `MeshVertexBufferLayout`, which defines the layout of the gpu buffer produced by the mesh. `MeshVertexBufferLayouts` can then be used to generate actual `VertexBufferLayouts` according to the requirements of a specific pipeline. This decoupling of "mesh layout" vs "pipeline vertex buffer layout" is what enables custom attributes. We don't need to standardize _mesh layouts_ or contort meshes to meet the needs of a specific pipeline. As long as the mesh has what the pipeline needs, it will work transparently. 
* Mesh-based pipelines now specialize on `&MeshVertexBufferLayout` via the new `SpecializedMeshPipeline` trait (which behaves like `SpecializedPipeline`, but adds `&MeshVertexBufferLayout`). The integrity of the pipeline cache is maintained because the `MeshVertexBufferLayout` is treated as part of the key (which is fully abstracted from implementers of the trait ... no need to add any additional info to the specialization key).    
* Hashing `MeshVertexBufferLayout` is too expensive to do for every entity, every frame. To make this scalable, I added a generalized "pre-hashing" solution to `bevy_utils`: `Hashed<T>` keys and `PreHashMap<K, V>` (which uses `Hashed<T>` internally) . Why didn't I just do the quick and dirty in-place "pre-compute hash and use that u64 as a key in a hashmap" that we've done in the past? Because its wrong! Hashes by themselves aren't enough because two different values can produce the same hash. Re-hashing a hash is even worse! I decided to build a generalized solution because this pattern has come up in the past and we've chosen to do the wrong thing. Now we can do the right thing! This did unfortunately require pulling in `hashbrown` and using that in `bevy_utils`, because avoiding re-hashes requires the `raw_entry_mut` api, which isn't stabilized yet (and may never be ... `entry_ref` has favor now, but also isn't available yet). If std's HashMap ever provides the tools we need, we can move back to that. Note that adding `hashbrown` doesn't increase our dependency count because it was already in our tree. I will probably break these changes out into their own PR.
* Specializing on `MeshVertexBufferLayout` has one non-obvious behavior: it can produce identical pipelines for two different MeshVertexBufferLayouts. To optimize the number of active pipelines / reduce re-binds while drawing, I de-duplicate pipelines post-specialization using the final `VertexBufferLayout` as the key.  For example, consider a pipeline that needs the layout `(position, normal)` and is specialized using two meshes: `(position, normal, uv)` and `(position, normal, other_vec2)`. If both of these meshes result in `(position, normal)` specializations, we can use the same pipeline! Now we do. Cool!

To briefly illustrate, this is what the relevant section of `MeshPipeline`'s specialization code looks like now:

```rust
impl SpecializedMeshPipeline for MeshPipeline {
    type Key = MeshPipelineKey;

    fn specialize(
        &self,
        key: Self::Key,
        layout: &MeshVertexBufferLayout,
    ) -> RenderPipelineDescriptor {
        let mut vertex_attributes = vec![
            Mesh::ATTRIBUTE_POSITION.at_shader_location(0),
            Mesh::ATTRIBUTE_NORMAL.at_shader_location(1),
            Mesh::ATTRIBUTE_UV_0.at_shader_location(2),
        ];

        let mut shader_defs = Vec::new();
        if layout.contains(Mesh::ATTRIBUTE_TANGENT) {
            shader_defs.push(String::from("VERTEX_TANGENTS"));
            vertex_attributes.push(Mesh::ATTRIBUTE_TANGENT.at_shader_location(3));
        }

        let vertex_buffer_layout = layout
            .get_layout(&vertex_attributes)
            .expect("Mesh is missing a vertex attribute");
```

Notice that this is _much_ simpler than it was before. And now any mesh with any layout can be used with this pipeline, provided it has vertex postions, normals, and uvs. We even got to remove `HAS_TANGENTS` from MeshPipelineKey and `has_tangents` from `GpuMesh`, because that information is redundant with `MeshVertexBufferLayout`.

This is still a draft because I still need to:

* Add more docs
* Experiment with adding error handling to mesh pipeline specialization (which would print errors at runtime when a mesh is missing a vertex attribute required by a pipeline). If it doesn't tank perf, we'll keep it.
* Consider breaking out the PreHash / hashbrown changes into a separate PR.
* Add an example illustrating this change
* Verify that the "mesh-specialized pipeline de-duplication code" works properly

Please dont yell at me for not doing these things yet :) Just trying to get this in peoples' hands asap.

Alternative to #3120
Fixes #3030


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-02-23 23:21:13 +00:00
François
e4203c3925 shader preprocessor - do not import if scope is not valid (#4012)
# Objective

- fix #4011 
- imports are not limited by the current `ifdef` they are in

## Solution

- process imports only if the current scope is enabled
2022-02-22 20:21:04 +00:00
Patrik Buhring
fb8af3aec3 Update Hexasphere to 7.0.0 (#4001)
The new update includes wireframe generation capabilities. 

I didn't integrate that in this PR, however with some guidance, I'd be happy to do so.
2022-02-21 23:49:07 +00:00
Carter Anderson
98938a8555 Internal Asset Hot Reloading (#3966)
Adds "hot reloading" of internal assets, which is normally not possible because they are loaded using `include_str` / direct Asset collection access.

This is accomplished via the following:
* Add a new `debug_asset_server` feature flag
* When that feature flag is enabled, create a second App with a second AssetServer that points to a configured location (by default the `crates` folder). Plugins that want to add hot reloading support for their assets can call the new `app.add_debug_asset::<T>()` and `app.init_debug_asset_loader::<T>()` functions.
* Load "internal" assets using the new `load_internal_asset` macro. By default this is identical to the current "include_str + register in asset collection" approach. But if the `debug_asset_server` feature flag is enabled, it will also load the asset dynamically in the debug asset server using the file path. It will then set up a correlation between the "debug asset" and the "actual asset" by listening for asset change events.

This is an alternative to #3673. The goal was to keep the boilerplate and features flags to a minimum for bevy plugin authors, and allow them to home their shaders near relevant code. 

This is a draft because I haven't done _any_ quality control on this yet. I'll probably rename things and remove a bunch of unwraps. I just got it working and wanted to use it to start a conversation.

Fixes #3660
2022-02-18 22:56:57 +00:00
Carter Anderson
e9f52b9dd2 Move import_path definitions into shader source (#3976)
This enables shaders to (optionally) define their import path inside their source. This has a number of benefits:

1. enables users to define their own custom paths directly in their assets
2. moves the import path "close" to the asset instead of centralized in the plugin definition, which seems "better" to me. 
3. makes "internal hot shader reloading" way more reasonable (see #3966)
4. logically opens the door to importing "parts" of a shader by defining "import_path blocks".

```rust
#define_import_path bevy_pbr::mesh_struct

struct Mesh {
    model: mat4x4<f32>;
    inverse_transpose_model: mat4x4<f32>;
    // 'flags' is a bit field indicating various options. u32 is 32 bits so we have up to 32 options.
    flags: u32;
};

let MESH_FLAGS_SHADOW_RECEIVER_BIT: u32 = 1u;
```
2022-02-18 21:54:03 +00:00
Carter Anderson
b3a1db60f2 Proper prehashing (#3963)
For some keys, it is too expensive to hash them on every lookup. Historically in Bevy, we have regrettably done the "wrong" thing in these cases (pre-computing hashes, then re-hashing them) because Rust's built in hashed collections don't give us the tools we need to do otherwise. Doing this is "wrong" because two different values can result in the same hash. Hashed collections generally get around this by falling back to equality checks on hash collisions. You can't do that if the key _is_ the hash. Additionally, re-hashing a hash increase the odds of collision!
 
#3959 needs pre-hashing to be viable, so I decided to finally properly solve the problem. The solution involves two different changes:

1. A new generalized "pre-hashing" solution in bevy_utils: `Hashed<T>` types, which store a value alongside a pre-computed hash. And `PreHashMap<K, V>` (which uses `Hashed<T>` internally) . `PreHashMap` is just an alias for a normal HashMap that uses `Hashed<T>` as the key and a new `PassHash` implementation as the Hasher. 
2. Replacing the `std::collections` re-exports in `bevy_utils` with equivalent `hashbrown` impls. Avoiding re-hashes requires the `raw_entry_mut` api, which isn't stabilized yet (and may never be ... `entry_ref` has favor now, but also isn't available yet). If std's HashMap ever provides the tools we need, we can move back to that. The latest version of `hashbrown` adds support for the `entity_ref` api, so we can move to that in preparation for an std migration, if thats the direction they seem to be going in. Note that adding hashbrown doesn't increase our dependency count because it was already in our tree.

In addition to providing these core tools, I also ported the "table identity hashing" in `bevy_ecs` to `raw_entry_mut`, which was a particularly egregious case.

The biggest outstanding case is `AssetPathId`, which stores a pre-hash. We need AssetPathId to be cheaply clone-able (and ideally Copy), but `Hashed<AssetPath>` requires ownership of the AssetPath, which makes cloning ids way more expensive. We could consider doing `Hashed<Arc<AssetPath>>`, but cloning an arc is still a non-trivial expensive that needs to be considered. I would like to handle this in a separate PR. And given that we will be re-evaluating the Bevy Assets implementation in the very near future, I'd prefer to hold off until after that conversation is concluded.
2022-02-18 03:26:01 +00:00
Robert Swain
936468aa1e bevy_render: Use RenderDevice to get limits/features and expose AdapterInfo (#3931)
# Objective

- `WgpuOptions` is mutated to be updated with the actual device limits and features, but this information is readily available to both the main and render worlds through the `RenderDevice` which has .limits() and .features() methods
- Information about the adapter in terms of its name, the backend in use, etc were not being exposed but have clear use cases for being used to take decisions about what rendering code to use. For example, if something works well on AMD GPUs but poorly on Intel GPUs. Or perhaps something works well in Vulkan but poorly in DX12.

## Solution

- Stop mutating `WgpuOptions `and don't insert the updated values into the main and render worlds
- Return `AdapterInfo` from `initialize_renderer` and insert it into the main and render worlds
- Use `RenderDevice` limits in the lighting code that was using `WgpuOptions.limits`.
- Renamed `WgpuOptions` to `WgpuSettings`
2022-02-16 21:17:37 +00:00
danieleades
d8974e7c3d small and mostly pointless refactoring (#2934)
What is says on the tin.

This has got more to do with making `clippy` slightly more *quiet* than it does with changing anything that might greatly impact readability or performance.

that said, deriving `Default` for a couple of structs is a nice easy win
2022-02-13 22:33:55 +00:00
Robert Swain
803e8cdf80 bevy_render: Support overriding wgpu features and limits (#3912)
# Objective

- Support overriding wgpu features and limits that were calculated from default values or queried from the adapter/backend.
- Fixes #3686

## Solution

- Add `disabled_features: Option<wgpu::Features>` to `WgpuOptions`
- Add `constrained_limits: Option<wgpu::Limits>` to `WgpuOptions`
- After maybe obtaining updated features and limits from the adapter/backend in the case of `WgpuOptionsPriority::Functionality`, enable the `WgpuOptions` `features`, disable the `disabled_features`, and constrain the `limits` by `constrained_limits`.
  - Note that constraining the limits means for `wgpu::Limits` members named `max_.*` we take the minimum of that which was configured/queried for the backend/adapter and the specified constrained limit value. This means the configured/queried value is used if the constrained limit is larger as that is as much as the device/API supports, or the constrained limit value is used if it is smaller as we are imposing an artificial constraint. For members named `min_.*` we take the maximum instead. For example, a minimum stride might be 256 but we set constrained limit value of 1024, then 1024 is the more conservative value. If the constrained limit value were 16, then 256 would be the more conservative.
2022-02-13 04:24:52 +00:00
dataphract
5bb4201f2e add informative panic message when adding render commands to a DrawFunctions that does not exist (#3924)
# Objective

If a user attempts to `.add_render_command::<P, C>()` on a world that does not contain `DrawFunctions<P>`, the engine panics with a generic `Option::unwrap` message:

```
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', /[redacted]/bevy/crates/bevy_render/src/render_phase/draw.rs:318:76
```

## Solution

This PR adds a panic message describing the problem:

```
thread 'main' panicked at 'DrawFunctions<outline::MeshStencil> must be added to the world as a resource before adding render commands to it', /[redacted]/bevy/crates/bevy_render/src/render_phase/draw.rs:322:17
```
2022-02-13 00:14:37 +00:00
Robert Swain
0ccb9dd07e bevy_render: Fix Quad flip (#3741)
# Objective

The documentation was unclear but it seemed like it was intended to _only_ flip the texture coordinates of the quad. However, it was also swapping the vertex positions, which resulted in inverted winding order so the front became a back face, and the normal was pointing into the face instead of out of it.

## Solution

- This change makes the only difference the UVs being horizontally flipped.
2022-02-12 00:46:04 +00:00
Loch Wansbrough
56b0e88b53 Add view transform to view uniform (#3885)
(cherry picked from commit de943381bd2a8b242c94db99e6c7bbd70006d7c3)

# Objective

The view uniform lacks view transform information. The inverse transform is currently provided but this is not sufficient if you do not have access to an `inverse` function (such as in WGSL).

## Solution

Grab the view transform, put it in the view uniform, use the same matrix to compute the inverse as well.
2022-02-08 04:14:34 +00:00
Daniel McNab
6615b7bf64 Deprecate .system (#3302)
# Objective

- Using `.system()` is no longer idiomatic.

## Solution

- Give a warning when using it
2022-02-08 04:00:58 +00:00
dataphract
f7478f448a doc: remove mention of void return type in entry_point docs (#3881)
# Objective

The docs for `{VertexState, FragmentState}::entry_point` stipulate that the entry point function in the shader must return void. This seems to be specific to GLSL; WGSL has no `void` type and its entry point functions return values that describe their output.

## Solution

Remove the mention of the `void` return type.
2022-02-07 22:07:43 +00:00
TheRawMeatball
865698548f Fix HDR asset support (#3795)
The HDR texture loader was never added to the app, this PR makes sure it is added when the relevant feature is enabled.
2022-02-04 21:22:12 +00:00
aloucks
1477765f62 Replace VSync with PresentMode (#3812)
# Objective

Enable the user to specify any presentation modes (including `Mailbox`).

Fixes #3807

## Solution

I've added a new `PresentMode` enum in `bevy_window` that mirrors the `wgpu` enum 1:1. Alternatively, I could add a new dependency on `wgpu-types` if that would be preferred.
2022-02-04 03:37:44 +00:00
Jakob Hellermann
b7dfe1677f include sources in shader validation error (#3724)
## Objective

When print shader validation error messages, we didn't print the sources and error message text, which led to some confusing error messages.

```cs
error: 
   ┌─ wgsl:15:11
   │
15 │     return material.color + 1u;
   │           ^^^^^^^^^^^^^^^^^^^^ naga::Expression [11]
```

## Solution

New error message:
```cs
error: Entry point fragment at Vertex is invalid
   ┌─ wgsl:15:11
   │
15 │     return material.color + 1u;
   │           ^^^^^^^^^^^^^^^^^^^^ naga::Expression [11]
   │
   = Expression [11] is invalid
   = Operation Add can't work with [8] and [10]
```
2022-02-04 03:37:38 +00:00
Boutillier
aa7b158893 Add a size method on Image. (#3696)
# Objective

Add a simple way for user to get the size of a loaded texture in an Image object.
Aims to solve #3689

## Solution

Add a `size() -> Vec2` method
Add two simple tests for this method.

Updates:
. method named changed from `size_2d` to `size`
2022-02-04 03:21:33 +00:00
Robert Swain
33ef5b5039 bevy_render: Only auto-disable mappable primary buffers for discrete GPUs (#3803)
# Objective

- While it is not safe to enable mappable primary buffers for all GPUs, it should be preferred for integrated GPUs where an integrated GPU is one that is sharing system memory.

## Solution

- Auto-disable mappable primary buffers only for discrete GPUs. If the GPU is integrated and mappable primary buffers are supported, use them.
2022-01-31 01:22:17 +00:00
sark
ca029ef0eb Naga export (#3714)
# Objective

In order to create a glsl shader, we must provide the `naga::ShaderStage` type which is not exported by bevy, meaning a user would have to manually include naga just to access this type.

`pub fn from_glsl(source: impl Into<Cow<'static, str>>, stage: naga::ShaderStage) -> Shader {`

## Solution

Re-rexport naga::ShaderStage from `render_resources`
2022-01-31 00:32:47 +00:00
François
cb2ba19d97 rename Texture to Image in doc of from_buffer function (#3713)
This doc link was missed when changing the type name.

Noticed in https://github.com/bevyengine/bevy/pull/3706 which will not be merged
2022-01-18 01:28:09 +00:00
Robert Swain
55da315432 bevy_render: Provide a way to opt-out of the built-in frustum culling (#3711)
# Objective

- Allow opting-out of the built-in frustum culling for cases where its behaviour would be incorrect
- Make use of the this in the shader_instancing example that uses a custom instancing method. The built-in frustum culling breaks the custom instancing in the shader_instancing example if the camera is moved to:

```rust
    commands.spawn_bundle(PerspectiveCameraBundle {
        transform: Transform::from_xyz(12.0, 0.0, 15.0)
            .looking_at(Vec3::new(12.0, 0.0, 0.0), Vec3::Y),
        ..Default::default()
    });
```

...such that the Aabb of the cube Mesh that is at the origin goes completely out of view. This incorrectly (for the purpose of the custom instancing) culls the `Mesh` and so culls all instances even though some may be visible.


## Solution

- Add a `NoFrustumCulling` marker component
- Do not compute and add an `Aabb` to `Mesh` entities without an `Aabb` if they have a `NoFrustumCulling` marker component
- Do not apply frustum culling to entities with the `NoFrustumCulling` marker component
2022-01-17 22:55:44 +00:00
Robert Swain
ef823d369f bevy_render: Do not automatically enable MAPPABLE_PRIMARY_BUFFERS (#3698)
# Objective

- When using `WgpuOptionsPriority::Functionality`, which is the default, wgpu::Features::MAPPABLE_PRIMARY_BUFFERS would be automatically enabled. This feature can and does have a significant negative impact on performance for discrete GPUs where resizable bar is not supported, which is a common case. As such, this feature should not be automatically enabled.
- Fixes the performance regression part of https://github.com/bevyengine/bevy/issues/3686 and at least some, if not all cases of https://github.com/bevyengine/bevy/issues/3687

## Solution

- When using `WgpuOptionsPriority::Functionality`, use the adapter-supported features, enable `TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES` and disable `MAPPABLE_PRIMARY_BUFFERS`
2022-01-17 22:03:14 +00:00
Linden Krouse
d11cd63452 Fixed doc comment with render Node input/output methods (#3642)
Fixed doc comment where render Node input/output methods refered to using `RenderContext` for interaction instead of `RenderGraphContext`

# Objective

The doc comments for `Node` refer to `RenderContext` for slots instead of `RenderGraphContext`, which is only confusing because `Node::run` is passed both `RenderContext` and `RenderGraphContext`

## Solution

Fixed the typo
2022-01-17 20:44:22 +00:00
Wybe Westra
3fcdc5a492 Expanded Msaa documentation. (#3693)
- Added default value.
- Links to the explanation of Msaa on wikipedia.
- Added a short example to show how to use the struct on an app.

Fixes #3167.
2022-01-16 21:09:15 +00:00
Pascal Hertleif
bc499591c2 Use use instead of lots of full paths (#3564)
Super tiny thing. Found this while reviewing #3479.

# Objective

- Simplify code
- Fix the link in the doc comment

## Solution

- Import a single item :)


Co-authored-by: Pascal Hertleif <pascal@technocreatives.com>
2022-01-11 01:08:39 +00:00
Michael Dorst
130953c717 Enable the doc_markdown clippy lint (#3457)
# Objective

CI should check for missing backticks in doc comments.

Fixes #3435

## Solution

`clippy` has a lint for this: `doc_markdown`. This enables that lint in the CI script.

Of course, enabling this lint in CI causes a bunch of lint errors, so I've gone through and fixed all of them. This was a huge edit that touched a ton of files, so I split the PR up by crate.

When all of the following are merged, the CI should pass and this can be merged.

+ [x] #3467
+ [x] #3468
+ [x] #3470 
+ [x] #3469
+ [x] #3471 
+ [x] #3472 
+ [x] #3473 
+ [x] #3474 
+ [x] #3475 
+ [x] #3476 
+ [x] #3477 
+ [x] #3478 
+ [x] #3479 
+ [x] #3480 
+ [x] #3481 
+ [x] #3482 
+ [x] #3483 
+ [x] #3484 
+ [x] #3485 
+ [x] #3486
2022-01-09 23:20:13 +00:00
François
600ee7eee6 support all line endings in shader preprocessor (#3603)
# Objective

- Advance uses of shaders seems to often fail for Windows users
- Bevy split lines on `'\n'` which messes with windows line endings

## Solution

- Uses Rust built in https://doc.rust-lang.org/std/primitive.str.html#method.lines
2022-01-09 18:52:18 +00:00
Michael Dorst
e56685370b Fix doc_markdown lints in bevy_render (#3479)
#3457 adds the `doc_markdown` clippy lint, which checks doc comments to make sure code identifiers are escaped with backticks. This causes a lot of lint errors, so this is one of a number of PR's that will fix those lint errors one crate at a time.

This PR fixes lints in the `bevy_render` crate.
2022-01-09 11:09:46 +00:00
Hennadii Chernyshchyk
458cb7a9e9 Add headless mode (#3439)
# Objective

In this PR I added the ability to opt-out graphical backends. Closes #3155.

## Solution

I turned backends into `Option` ~~and removed panicking sub app API to force users handle the error (was suggested by `@cart`)~~.
2022-01-08 10:39:43 +00:00
Carter Anderson
2ee38cb9e0 Release 0.6.0 (#3587) 2022-01-08 10:18:22 +00:00
davier
c2da7800e3 Add 2d meshes and materials (#3460)
# Objective

The current 2d rendering is specialized to render sprites, we need a generic way to render 2d items, using meshes and materials like we have for 3d.

## Solution

I cloned a good part of `bevy_pbr` into `bevy_sprite/src/mesh2d`, removed lighting and pbr itself, adapted it to 2d rendering, added a `ColorMaterial`, and modified the sprite rendering to break batches around 2d meshes.

~~The PR is a bit crude; I tried to change as little as I could in both the parts copied from 3d and the current sprite rendering to make reviewing easier. In the future, I expect we could make the sprite rendering a normal 2d material, cleanly integrated with the rest.~~ _edit: see <https://github.com/bevyengine/bevy/pull/3460#issuecomment-1003605194>_

## Remaining work

- ~~don't require mesh normals~~ _out of scope_
- ~~add an example~~ _done_
- support 2d meshes & materials in the UI?
- bikeshed names (I didn't think hard about naming, please check if it's fine)

## Remaining questions

- ~~should we add a depth buffer to 2d now that there are 2d meshes?~~ _let's revisit that when we have an opaque render phase_
- ~~should we add MSAA support to the sprites, or remove it from the 2d meshes?~~ _I added MSAA to sprites since it's really needed for 2d meshes_
- ~~how to customize vertex attributes?~~ _#3120_



Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-01-08 01:29:08 +00:00
Niklas Eicker
fbab01a40d Add missing closing ticks for inline examples and some cleanup (#3573)
# Objective

- clean up documentation and inline examples

## Solution

- add missing closing "```"
- remove stray "```"
- remove whitespace in inline examples
- unify inline examples (remove some `rust` labels)
2022-01-07 09:25:12 +00:00
yetanothercheer
fda0b2c911 Fix typo (#3578) 2022-01-07 06:25:38 +00:00
TheRawMeatball
f3fba09615 Add MapMode to wgpu reexports (#3558)
This type can be needed by API s on other reexported types, so it should be included too
2022-01-05 19:19:22 +00:00
Rob Parrett
24b21ea35e Fix torus normals (#3549)
# Objective

Fixes #3547 

## Solution

Normal calc adapted from https://web.cs.ucdavis.edu/~amenta/s12/findnorm.pdf

## Before
<img width="1392" alt="before" src="https://user-images.githubusercontent.com/200550/148125212-fb1c083e-3c57-4330-a656-df34513c36ab.png">

## After
<img width="1392" alt="after" src="https://user-images.githubusercontent.com/200550/148125223-174dc956-37df-4ac2-8983-b18e1e2a9a7d.png">

I'm assuming that the greyness and the self-shadowing artifacts are... normal for the new renderer.
2022-01-04 21:30:46 +00:00
Robert Swain
b9c623e4f3 Configurable wgpu features/limits priority (#3452)
# Objective

- Allow the user to specify the priority when configuring wgpu features/limits and by default use the maximum capabilities of the chosen adapter.

## Solution

- Add a `WgpuOptionsPriority` enum with `Compatibility`, `Functionality` and `WebGL2` options.
- Add a `priority: WgpuOptionsPriority` member to `WgpuOptions`.
- When initialising the renderer, if `WgpuOptions::priority == WgpuOptionsPriority::Functionality`, query the adapter for the available features and limits, use them when creating a device, and update `WgpuOptions` with those values. If `Compatibility` use the behaviour as before this PR. If `WebGL2` then use the WebGL2 downlevel limits as used when when building for wasm, for convenience of testing WebGL2 limits without having to build for wasm.
- Add an environment variable `WGPU_OPTIONS_PRIO` that takes `compatibility`, `functionality`, `webgl2`.
- Default to `WgpuOptionsPriority::Functionality`.
- Insert updated `WgpuOptions` into render app world as well. This is useful for applying the limits when rendering, such as limiting the directional light shadow map texture to 2048x2048 when using WebGL2 downlevel limits but not on wasm.
- Reduced `draw_state` logs from `debug` to `trace` and added `debug` level logs for the wgpu features and limits. Use `RUST_LOG=bevy_render=debug` to see the output.
2022-01-04 20:08:12 +00:00
yetanothercheer
1bae879bf3 Fix typo (#3538) 2022-01-03 08:51:44 +00:00
Robert Swain
85b7589388 bevy_gltf: Add support for loading lights (#3506)
# Objective

- Add support for loading lights from glTF 2.0 files

## Solution

- This adds support for the KHR_punctual_lights extension which supports point, directional, and spot lights, though we don't yet support spot lights.
- Inserting light bundles when creating scenes required registering some more light bundle component types.
2022-01-03 07:59:25 +00:00
James Liu
dc8fefe27f Remove Bytes, FromBytes, Labels, EntityLabels. Document rest of bevy_core and enable warning on missing docs. (#3521)
This PR is part of the issue #3492.

# Objective

 - Clean up dead code in `bevy_core`.
 - Add and update the `bevy_core` documentation to achieve a 100% documentation coverage.
 - Add the #![warn(missing_docs)] lint to keep the documentation coverage for the future.

# Solution

 - Remove unused `Bytes`, `FromBytes`, `Labels`, and `EntityLabels` types and associated systems.
 - Made several types private that really only have use as internal types, mostly pertaining to fixed timestep execution.
 - Add and update the bevy_core documentation.
 - Add the #![warn(missing_docs)] lint.

# Open Questions

Should more of the internal states of `FixedTimestep` be public? Seems mostly to be an implementation detail unless someone really needs that fixed timestep state.
2022-01-02 20:36:40 +00:00
Jerome Humbert
e43e36696d Minor docs edit/add in bevy_render (#3447)
# Objective

Docs updates.

## Solution

- Detail what `OrthographicCameraBundle::new_2d()` creates.
- Fix a few renamed parameters in comments of `TrackedRenderPass`.
- Add missing comments for viewport and debug markers.

Co-authored-by: Jerome Humbert <djeedai@gmail.com>
2022-01-02 17:40:03 +00:00
Minghao Liu
3ac55f0bcf load spirv using correct API (#3466)
# Objective

currently spirv source loading parse then desterilize it to make wgpu happy.

## Solution

Use the right API to get spirv
2021-12-30 19:55:01 +00:00
François
db68704231 Enable Msaa for webgl by default (#3489)
# Objective

- `Msaa` was disabled in webgl due to a bug in wgpu
- Bug has been fixed (https://github.com/gfx-rs/wgpu/pull/2307) and backported (https://github.com/gfx-rs/wgpu/pull/2327), and updates for [`wgpu-core`](https://crates.io/crates/wgpu-core/0.12.1) and [`wgpu-hal`](https://crates.io/crates/wgpu-hal/0.12.1) have been released

## Solution

- Remove custom config for `Msaa` in webgl
- I also changed two options that were using the arch instead of the `webgl` feature. it shouldn't change much for webgl, but could help if someone wants to target wasm but not webgl2


Co-authored-by: François <8672791+mockersf@users.noreply.github.com>
2021-12-29 21:04:28 +00:00
Jakob Hellermann
66b517ef81 fix shader compilation error reporting for non-wgsl shaders (#3441)
in #3289 I accidentally only logged errors for wgsl shaders, this PR expands the error reporting the the other supported shader types.
2021-12-29 21:04:27 +00:00
davier
06d9384447 Add FromReflect trait to convert dynamic types to concrete types (#1395)
Dynamic types (`DynamicStruct`, `DynamicTupleStruct`, `DynamicTuple`, `DynamicList` and `DynamicMap`) are used when deserializing scenes, but currently they can only be applied to existing concrete types. This leads to issues when trying to spawn non trivial deserialized scene.
For components, the issue is avoided by requiring that reflected components implement ~~`FromResources`~~ `FromWorld` (or `Default`). When spawning, a new concrete type is created that way, and the dynamic type is applied to it. Unfortunately, some components don't have any valid implementation of these traits.
In addition, any `Vec` or `HashMap` inside a component will panic when a dynamic type is pushed into it (for instance, `Text` panics when adding a text section).

To solve this issue, this PR adds the `FromReflect` trait that creates a concrete type from a dynamic type that represent it, derives the trait alongside the `Reflect` trait, drops the ~~`FromResources`~~ `FromWorld` requirement on reflected components, ~~and enables reflection for UI and Text bundles~~. It also adds the requirement that fields ignored with `#[reflect(ignore)]` implement `Default`, since we need to initialize them somehow.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-12-26 18:49:01 +00:00
François
22c665fa39 re-export BufferBinding and BufferDescriptor (#3429)
# Objective

- I want to port `bevy_egui` to Bevy main and only reuse re-exports from Bevy

## Solution

- Add exports for `BufferBinding` and `BufferDescriptor`


Co-authored-by: François <8672791+mockersf@users.noreply.github.com>
2021-12-24 16:53:49 +00:00
davier
76ec709ede Add Visibility component to UI (#3426)
# Objective

Fixes #3422 

## Solution

Adds the existing `Visibility` component to UI bundles and checks for it in the extract phase of the render app.

The `ComputedVisibility` component was not added. I don't think the UI camera needs frustum culling, but having `RenderLayers` work may be desirable. However I think we would need to change `check_visibility()` to differentiate between 2d, 3d and UI entities.
2021-12-24 07:10:12 +00:00
Jakob Hellermann
adb3ad399c make sub_app return an &App and add sub_app_mut() -> &mut App (#3309)
It's sometimes useful to have a reference to an app a sub app at the same time, which is only possible with an immutable reference.
2021-12-24 06:57:30 +00:00
François
79d36e7c28 Prepare crevice for vendored release (#3394)
# Objective

- Our crevice is still called "crevice", which we can't use for a release
- Users would need to use our "crevice" directly to be able to use the derive macro

## Solution

- Rename crevice to bevy_crevice, and crevice-derive to bevy-crevice-derive
- Re-export it from bevy_render, and use it from bevy_render everywhere
- Fix derive macro to work either from bevy_render, from bevy_crevice, or from bevy

## Remaining

- It is currently re-exported as `bevy::render::bevy_crevice`, is it the path we want?
- After a brief suggestion to Cart, I changed the version to follow Bevy version instead of crevice, do we want that?
- Crevice README.md need to be updated
- in the `Cargo.toml`, there are a few things to change. How do we want to change them? How do we keep attributions to original Crevice?
```
authors = ["Lucien Greathouse <me@lpghatguy.com>"]
documentation = "https://docs.rs/crevice"
homepage = "https://github.com/LPGhatguy/crevice"
repository = "https://github.com/LPGhatguy/crevice"
```


Co-authored-by: François <8672791+mockersf@users.noreply.github.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-12-23 22:49:12 +00:00