Merge remote-tracking branch 'remotes/origin/main' into erroring-single
# Conflicts: # crates/bevy_ecs/src/schedule/executor/mod.rs
This commit is contained in:
commit
2cf97b7ff9
9
.github/workflows/ci.yml
vendored
9
.github/workflows/ci.yml
vendored
@ -15,7 +15,7 @@ env:
|
||||
# If nightly is breaking CI, modify this variable to target a specific nightly version.
|
||||
NIGHTLY_TOOLCHAIN: nightly
|
||||
RUSTFLAGS: "-D warnings"
|
||||
BINSTALL_VERSION: "v1.12.3"
|
||||
BINSTALL_VERSION: "v1.14.1"
|
||||
|
||||
concurrency:
|
||||
group: ${{github.workflow}}-${{github.ref}}
|
||||
@ -95,7 +95,7 @@ jobs:
|
||||
- name: CI job
|
||||
# To run the tests one item at a time for troubleshooting, use
|
||||
# cargo --quiet test --lib -- --list | sed 's/: test$//' | MIRIFLAGS="-Zmiri-disable-isolation -Zmiri-disable-weak-memory-emulation" xargs -n1 cargo miri test -p bevy_ecs --lib -- --exact
|
||||
run: cargo miri test -p bevy_ecs
|
||||
run: cargo miri test -p bevy_ecs --features bevy_utils/debug
|
||||
env:
|
||||
# -Zrandomize-layout makes sure we dont rely on the layout of anything that might change
|
||||
RUSTFLAGS: -Zrandomize-layout
|
||||
@ -260,7 +260,7 @@ jobs:
|
||||
# Full git history is needed to get a proper list of changed files within `super-linter`
|
||||
fetch-depth: 0
|
||||
- name: Run Markdown Lint
|
||||
uses: super-linter/super-linter/slim@v7.3.0
|
||||
uses: super-linter/super-linter/slim@v7.4.0
|
||||
env:
|
||||
MULTI_STATUS: false
|
||||
VALIDATE_ALL_CODEBASE: false
|
||||
@ -272,7 +272,8 @@ jobs:
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: cargo-bins/cargo-binstall@v1.12.3
|
||||
# Update in sync with BINSTALL_VERSION
|
||||
- uses: cargo-bins/cargo-binstall@v1.14.1
|
||||
- name: Install taplo
|
||||
run: cargo binstall taplo-cli@0.9.3 --locked
|
||||
- name: Run Taplo
|
||||
|
||||
3
.github/workflows/post-release.yml
vendored
3
.github/workflows/post-release.yml
vendored
@ -49,7 +49,8 @@ jobs:
|
||||
--exclude ci \
|
||||
--exclude errors \
|
||||
--exclude bevy_mobile_example \
|
||||
--exclude build-wasm-example
|
||||
--exclude build-wasm-example \
|
||||
--exclude no_std_library
|
||||
|
||||
- name: Create PR
|
||||
uses: peter-evans/create-pull-request@v7
|
||||
|
||||
139
Cargo.toml
139
Cargo.toml
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "bevy"
|
||||
version = "0.16.0-dev"
|
||||
version = "0.17.0-dev"
|
||||
edition = "2024"
|
||||
categories = ["game-engines", "graphics", "gui", "rendering"]
|
||||
description = "A refreshingly simple data-driven game engine and app framework"
|
||||
@ -10,7 +10,7 @@ keywords = ["game", "engine", "gamedev", "graphics", "bevy"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/bevyengine/bevy"
|
||||
documentation = "https://docs.rs/bevy"
|
||||
rust-version = "1.86.0"
|
||||
rust-version = "1.88.0"
|
||||
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
@ -72,7 +72,6 @@ allow_attributes_without_reason = "warn"
|
||||
|
||||
[workspace.lints.rust]
|
||||
missing_docs = "warn"
|
||||
mismatched_lifetime_syntaxes = "allow"
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(docsrs_dep)'] }
|
||||
unsafe_code = "deny"
|
||||
unsafe_op_in_unsafe_fn = "warn"
|
||||
@ -152,6 +151,7 @@ default = [
|
||||
"bevy_text",
|
||||
"bevy_ui",
|
||||
"bevy_ui_picking_backend",
|
||||
"bevy_ui_render",
|
||||
"bevy_window",
|
||||
"bevy_winit",
|
||||
"custom_cursor",
|
||||
@ -165,6 +165,8 @@ default = [
|
||||
"vorbis",
|
||||
"webgl2",
|
||||
"x11",
|
||||
"debug",
|
||||
"zstd_rust",
|
||||
]
|
||||
|
||||
# Recommended defaults for no_std applications
|
||||
@ -278,6 +280,9 @@ bevy_ui = [
|
||||
"bevy_anti_aliasing",
|
||||
]
|
||||
|
||||
# Provides rendering functionality for bevy_ui
|
||||
bevy_ui_render = ["bevy_internal/bevy_ui_render", "bevy_render", "bevy_ui"]
|
||||
|
||||
# Windowing layer
|
||||
bevy_window = ["bevy_internal/bevy_window"]
|
||||
|
||||
@ -305,6 +310,9 @@ bevy_input_focus = ["bevy_internal/bevy_input_focus"]
|
||||
# Headless widget collection for Bevy UI.
|
||||
bevy_core_widgets = ["bevy_internal/bevy_core_widgets"]
|
||||
|
||||
# Feathers widget collection.
|
||||
experimental_bevy_feathers = ["bevy_internal/bevy_feathers"]
|
||||
|
||||
# Enable passthrough loading for SPIR-V shaders (Only supported on Vulkan, shader capabilities and extensions must agree with the platform implementation)
|
||||
spirv_shader_passthrough = ["bevy_internal/spirv_shader_passthrough"]
|
||||
|
||||
@ -330,6 +338,9 @@ trace = ["bevy_internal/trace", "dep:tracing"]
|
||||
# Basis Universal compressed texture support
|
||||
basis-universal = ["bevy_internal/basis-universal"]
|
||||
|
||||
# Enables compressed KTX2 UASTC texture output on the asset processor
|
||||
compressed_image_saver = ["bevy_internal/compressed_image_saver"]
|
||||
|
||||
# BMP image format support
|
||||
bmp = ["bevy_internal/bmp"]
|
||||
|
||||
@ -378,8 +389,11 @@ webp = ["bevy_internal/webp"]
|
||||
# For KTX2 supercompression
|
||||
zlib = ["bevy_internal/zlib"]
|
||||
|
||||
# For KTX2 supercompression
|
||||
zstd = ["bevy_internal/zstd"]
|
||||
# For KTX2 Zstandard decompression using pure rust [ruzstd](https://crates.io/crates/ruzstd). This is the safe default. For maximum performance, use "zstd_c".
|
||||
zstd_rust = ["bevy_internal/zstd_rust"]
|
||||
|
||||
# For KTX2 Zstandard decompression using [zstd](https://crates.io/crates/zstd). This is a faster backend, but uses unsafe C bindings. For the safe option, stick to the default backend with "zstd_rust".
|
||||
zstd_c = ["bevy_internal/zstd_c"]
|
||||
|
||||
# FLAC audio format support
|
||||
flac = ["bevy_internal/flac"]
|
||||
@ -448,7 +462,7 @@ android_shared_stdcxx = ["bevy_internal/android_shared_stdcxx"]
|
||||
detailed_trace = ["bevy_internal/detailed_trace"]
|
||||
|
||||
# Include tonemapping Look Up Tables KTX2 files. If everything is pink, you need to enable this feature or change the `Tonemapping` method for your `Camera2d` or `Camera3d`.
|
||||
tonemapping_luts = ["bevy_internal/tonemapping_luts", "ktx2", "zstd"]
|
||||
tonemapping_luts = ["bevy_internal/tonemapping_luts", "ktx2", "bevy_image/zstd"]
|
||||
|
||||
# Include SMAA Look Up Tables KTX2 Files
|
||||
smaa_luts = ["bevy_internal/smaa_luts"]
|
||||
@ -477,6 +491,12 @@ shader_format_wesl = ["bevy_internal/shader_format_wesl"]
|
||||
# Enable support for transmission-related textures in the `StandardMaterial`, at the risk of blowing past the global, per-shader texture limit on older/lower-end GPUs
|
||||
pbr_transmission_textures = ["bevy_internal/pbr_transmission_textures"]
|
||||
|
||||
# Enable support for Clustered Decals
|
||||
pbr_clustered_decals = ["bevy_internal/pbr_clustered_decals"]
|
||||
|
||||
# Enable support for Light Textures
|
||||
pbr_light_textures = ["bevy_internal/pbr_light_textures"]
|
||||
|
||||
# Enable support for multi-layer material textures in the `StandardMaterial`, at the risk of blowing past the global, per-shader texture limit on older/lower-end GPUs
|
||||
pbr_multi_layer_material_textures = [
|
||||
"bevy_internal/pbr_multi_layer_material_textures",
|
||||
@ -507,7 +527,10 @@ file_watcher = ["bevy_internal/file_watcher"]
|
||||
embedded_watcher = ["bevy_internal/embedded_watcher"]
|
||||
|
||||
# Enable stepping-based debugging of Bevy systems
|
||||
bevy_debug_stepping = ["bevy_internal/bevy_debug_stepping"]
|
||||
bevy_debug_stepping = [
|
||||
"bevy_internal/bevy_debug_stepping",
|
||||
"bevy_internal/debug",
|
||||
]
|
||||
|
||||
# Enables the meshlet renderer for dense high-poly scenes (experimental)
|
||||
meshlet = ["bevy_internal/meshlet"]
|
||||
@ -551,30 +574,38 @@ web = ["bevy_internal/web"]
|
||||
# Enable hotpatching of Bevy systems
|
||||
hotpatching = ["bevy_internal/hotpatching"]
|
||||
|
||||
# Enable converting glTF coordinates to Bevy's coordinate system by default. This will be Bevy's default behavior starting in 0.18.
|
||||
gltf_convert_coordinates_default = [
|
||||
"bevy_internal/gltf_convert_coordinates_default",
|
||||
]
|
||||
|
||||
# Enable collecting debug information about systems and components to help with diagnostics
|
||||
debug = ["bevy_internal/debug"]
|
||||
|
||||
[dependencies]
|
||||
bevy_internal = { path = "crates/bevy_internal", version = "0.16.0-dev", default-features = false }
|
||||
bevy_internal = { path = "crates/bevy_internal", version = "0.17.0-dev", default-features = false }
|
||||
tracing = { version = "0.1", default-features = false, optional = true }
|
||||
|
||||
# Wasm does not support dynamic linking.
|
||||
[target.'cfg(not(target_family = "wasm"))'.dependencies]
|
||||
bevy_dylib = { path = "crates/bevy_dylib", version = "0.16.0-dev", default-features = false, optional = true }
|
||||
bevy_dylib = { path = "crates/bevy_dylib", version = "0.17.0-dev", default-features = false, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
rand = "0.8.0"
|
||||
rand_chacha = "0.3.1"
|
||||
ron = "0.8.0"
|
||||
ron = "0.10"
|
||||
flate2 = "1.0"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1.0.140"
|
||||
bytemuck = "1.7"
|
||||
bevy_render = { path = "crates/bevy_render", version = "0.16.0-dev", default-features = false }
|
||||
bytemuck = "1"
|
||||
bevy_render = { path = "crates/bevy_render", version = "0.17.0-dev", default-features = false }
|
||||
# The following explicit dependencies are needed for proc macros to work inside of examples as they are part of the bevy crate itself.
|
||||
bevy_ecs = { path = "crates/bevy_ecs", version = "0.16.0-dev", default-features = false }
|
||||
bevy_state = { path = "crates/bevy_state", version = "0.16.0-dev", default-features = false }
|
||||
bevy_asset = { path = "crates/bevy_asset", version = "0.16.0-dev", default-features = false }
|
||||
bevy_reflect = { path = "crates/bevy_reflect", version = "0.16.0-dev", default-features = false }
|
||||
bevy_image = { path = "crates/bevy_image", version = "0.16.0-dev", default-features = false }
|
||||
bevy_gizmos = { path = "crates/bevy_gizmos", version = "0.16.0-dev", default-features = false }
|
||||
bevy_ecs = { path = "crates/bevy_ecs", version = "0.17.0-dev", default-features = false }
|
||||
bevy_state = { path = "crates/bevy_state", version = "0.17.0-dev", default-features = false }
|
||||
bevy_asset = { path = "crates/bevy_asset", version = "0.17.0-dev", default-features = false }
|
||||
bevy_reflect = { path = "crates/bevy_reflect", version = "0.17.0-dev", default-features = false }
|
||||
bevy_image = { path = "crates/bevy_image", version = "0.17.0-dev", default-features = false }
|
||||
bevy_gizmos = { path = "crates/bevy_gizmos", version = "0.17.0-dev", default-features = false }
|
||||
# Needed to poll Task examples
|
||||
futures-lite = "2.0.1"
|
||||
async-std = "1.13"
|
||||
@ -601,7 +632,7 @@ web-sys = { version = "0.3", features = ["Window"] }
|
||||
|
||||
[[example]]
|
||||
name = "context_menu"
|
||||
path = "examples/usages/context_menu.rs"
|
||||
path = "examples/usage/context_menu.rs"
|
||||
doc-scrape-examples = true
|
||||
|
||||
[package.metadata.example.context_menu]
|
||||
@ -839,6 +870,17 @@ description = "Generates a texture atlas (sprite sheet) from individual sprites"
|
||||
category = "2D Rendering"
|
||||
wasm = false
|
||||
|
||||
[[example]]
|
||||
name = "tilemap_chunk"
|
||||
path = "examples/2d/tilemap_chunk.rs"
|
||||
doc-scrape-examples = true
|
||||
|
||||
[package.metadata.example.tilemap_chunk]
|
||||
name = "Tilemap Chunk"
|
||||
description = "Renders a tilemap chunk"
|
||||
category = "2D Rendering"
|
||||
wasm = true
|
||||
|
||||
[[example]]
|
||||
name = "transparency_2d"
|
||||
path = "examples/2d/transparency_2d.rs"
|
||||
@ -1027,6 +1069,17 @@ description = "Showcases different blend modes"
|
||||
category = "3D Rendering"
|
||||
wasm = true
|
||||
|
||||
[[example]]
|
||||
name = "manual_material"
|
||||
path = "examples/3d/manual_material.rs"
|
||||
doc-scrape-examples = true
|
||||
|
||||
[package.metadata.example.manual_material]
|
||||
name = "Manual Material Implementation"
|
||||
description = "Demonstrates how to implement a material manually using the mid-level render APIs"
|
||||
category = "3D Rendering"
|
||||
wasm = true
|
||||
|
||||
[[example]]
|
||||
name = "edit_material_on_gltf"
|
||||
path = "examples/3d/edit_material_on_gltf.rs"
|
||||
@ -1278,9 +1331,9 @@ required-features = ["bevy_solari"]
|
||||
|
||||
[package.metadata.example.solari]
|
||||
name = "Solari"
|
||||
description = "Demonstrates realtime dynamic global illumination rendering using Bevy Solari."
|
||||
description = "Demonstrates realtime dynamic raytraced lighting using Bevy Solari."
|
||||
category = "3D Rendering"
|
||||
wasm = false
|
||||
wasm = false # Raytracing is not supported on the web
|
||||
|
||||
[[example]]
|
||||
name = "spherical_area_lights"
|
||||
@ -2043,12 +2096,6 @@ description = "Full guide to Bevy's ECS"
|
||||
category = "ECS (Entity Component System)"
|
||||
wasm = false
|
||||
|
||||
[package.metadata.example.apply_deferred]
|
||||
name = "Apply System Buffers"
|
||||
description = "Show how to use `ApplyDeferred` system"
|
||||
category = "ECS (Entity Component System)"
|
||||
wasm = false
|
||||
|
||||
[[example]]
|
||||
name = "change_detection"
|
||||
path = "examples/ecs/change_detection.rs"
|
||||
@ -2098,6 +2145,7 @@ wasm = false
|
||||
name = "dynamic"
|
||||
path = "examples/ecs/dynamic.rs"
|
||||
doc-scrape-examples = true
|
||||
required-features = ["debug"]
|
||||
|
||||
[package.metadata.example.dynamic]
|
||||
name = "Dynamic ECS"
|
||||
@ -4376,6 +4424,7 @@ wasm = true
|
||||
name = "clustered_decals"
|
||||
path = "examples/3d/clustered_decals.rs"
|
||||
doc-scrape-examples = true
|
||||
required-features = ["pbr_clustered_decals"]
|
||||
|
||||
[package.metadata.example.clustered_decals]
|
||||
name = "Clustered Decals"
|
||||
@ -4383,6 +4432,18 @@ description = "Demonstrates clustered decals"
|
||||
category = "3D Rendering"
|
||||
wasm = false
|
||||
|
||||
[[example]]
|
||||
name = "light_textures"
|
||||
path = "examples/3d/light_textures.rs"
|
||||
doc-scrape-examples = true
|
||||
required-features = ["pbr_light_textures"]
|
||||
|
||||
[package.metadata.example.light_textures]
|
||||
name = "Light Textures"
|
||||
description = "Demonstrates light textures"
|
||||
category = "3D Rendering"
|
||||
wasm = false
|
||||
|
||||
[[example]]
|
||||
name = "occlusion_culling"
|
||||
path = "examples/3d/occlusion_culling.rs"
|
||||
@ -4485,3 +4546,27 @@ name = "Core Widgets (w/Observers)"
|
||||
description = "Demonstrates use of core (headless) widgets in Bevy UI, with Observers"
|
||||
category = "UI (User Interface)"
|
||||
wasm = true
|
||||
|
||||
[[example]]
|
||||
name = "scrollbars"
|
||||
path = "examples/ui/scrollbars.rs"
|
||||
doc-scrape-examples = true
|
||||
|
||||
[package.metadata.example.scrollbars]
|
||||
name = "Scrollbars"
|
||||
description = "Demonstrates use of core scrollbar in Bevy UI"
|
||||
category = "UI (User Interface)"
|
||||
wasm = true
|
||||
|
||||
[[example]]
|
||||
name = "feathers"
|
||||
path = "examples/ui/feathers.rs"
|
||||
doc-scrape-examples = true
|
||||
required-features = ["experimental_bevy_feathers"]
|
||||
|
||||
[package.metadata.example.feathers]
|
||||
name = "Feathers Widgets"
|
||||
description = "Gallery of Feathers Widgets"
|
||||
category = "UI (User Interface)"
|
||||
wasm = true
|
||||
hidden = true
|
||||
|
||||
@ -9,20 +9,20 @@
|
||||
(
|
||||
node_type: Blend,
|
||||
mask: 0,
|
||||
weight: 1.0,
|
||||
weight: 0.5,
|
||||
),
|
||||
(
|
||||
node_type: Clip(AssetPath("models/animated/Fox.glb#Animation0")),
|
||||
node_type: Clip("models/animated/Fox.glb#Animation0"),
|
||||
mask: 0,
|
||||
weight: 1.0,
|
||||
),
|
||||
(
|
||||
node_type: Clip(AssetPath("models/animated/Fox.glb#Animation1")),
|
||||
node_type: Clip("models/animated/Fox.glb#Animation1"),
|
||||
mask: 0,
|
||||
weight: 1.0,
|
||||
),
|
||||
(
|
||||
node_type: Clip(AssetPath("models/animated/Fox.glb#Animation2")),
|
||||
node_type: Clip("models/animated/Fox.glb#Animation2"),
|
||||
mask: 0,
|
||||
weight: 1.0,
|
||||
),
|
||||
|
||||
BIN
assets/lightmaps/caustic_directional_texture.png
Normal file
BIN
assets/lightmaps/caustic_directional_texture.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 229 KiB |
BIN
assets/lightmaps/faces_pointlight_texture_blurred.png
Normal file
BIN
assets/lightmaps/faces_pointlight_texture_blurred.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 551 KiB |
BIN
assets/lightmaps/torch_spotlight_texture.png
Normal file
BIN
assets/lightmaps/torch_spotlight_texture.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 93 KiB |
BIN
assets/models/Faces/faces.glb
Normal file
BIN
assets/models/Faces/faces.glb
Normal file
Binary file not shown.
@ -7,8 +7,8 @@
|
||||
}
|
||||
#import bevy_core_pipeline::tonemapping::tone_mapping
|
||||
|
||||
@group(2) @binding(0) var my_array_texture: texture_2d_array<f32>;
|
||||
@group(2) @binding(1) var my_array_texture_sampler: sampler;
|
||||
@group(3) @binding(0) var my_array_texture: texture_2d_array<f32>;
|
||||
@group(3) @binding(1) var my_array_texture_sampler: sampler;
|
||||
|
||||
@fragment
|
||||
fn fragment(
|
||||
|
||||
@ -3,8 +3,8 @@
|
||||
view_transformations::position_world_to_clip
|
||||
}
|
||||
|
||||
@group(2) @binding(0) var texture: texture_2d<f32>;
|
||||
@group(2) @binding(1) var texture_sampler: sampler;
|
||||
@group(3) @binding(0) var texture: texture_2d<f32>;
|
||||
@group(3) @binding(1) var texture_sampler: sampler;
|
||||
|
||||
struct Vertex {
|
||||
@builtin(instance_index) instance_index: u32,
|
||||
|
||||
@ -15,12 +15,12 @@ struct MaterialBindings {
|
||||
}
|
||||
|
||||
#ifdef BINDLESS
|
||||
@group(2) @binding(0) var<storage> materials: array<MaterialBindings>;
|
||||
@group(2) @binding(10) var<storage> material_color: binding_array<Color>;
|
||||
@group(3) @binding(0) var<storage> materials: array<MaterialBindings>;
|
||||
@group(3) @binding(10) var<storage> material_color: binding_array<Color>;
|
||||
#else // BINDLESS
|
||||
@group(2) @binding(0) var<uniform> material_color: Color;
|
||||
@group(2) @binding(1) var material_color_texture: texture_2d<f32>;
|
||||
@group(2) @binding(2) var material_color_sampler: sampler;
|
||||
@group(3) @binding(0) var<uniform> material_color: Color;
|
||||
@group(3) @binding(1) var material_color_texture: texture_2d<f32>;
|
||||
@group(3) @binding(2) var material_color_sampler: sampler;
|
||||
#endif // BINDLESS
|
||||
|
||||
@fragment
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
#import bevy_pbr::forward_io::VertexOutput
|
||||
|
||||
#ifdef CUBEMAP_ARRAY
|
||||
@group(2) @binding(0) var base_color_texture: texture_cube_array<f32>;
|
||||
@group(3) @binding(0) var base_color_texture: texture_cube_array<f32>;
|
||||
#else
|
||||
@group(2) @binding(0) var base_color_texture: texture_cube<f32>;
|
||||
@group(3) @binding(0) var base_color_texture: texture_cube<f32>;
|
||||
#endif
|
||||
|
||||
@group(2) @binding(1) var base_color_sampler: sampler;
|
||||
@group(3) @binding(1) var base_color_sampler: sampler;
|
||||
|
||||
@fragment
|
||||
fn fragment(
|
||||
|
||||
@ -3,10 +3,10 @@ layout(location = 0) in vec2 v_Uv;
|
||||
|
||||
layout(location = 0) out vec4 o_Target;
|
||||
|
||||
layout(set = 2, binding = 0) uniform vec4 CustomMaterial_color;
|
||||
layout(set = 3, binding = 0) uniform vec4 CustomMaterial_color;
|
||||
|
||||
layout(set = 2, binding = 1) uniform texture2D CustomMaterial_texture;
|
||||
layout(set = 2, binding = 2) uniform sampler CustomMaterial_sampler;
|
||||
layout(set = 3, binding = 1) uniform texture2D CustomMaterial_texture;
|
||||
layout(set = 3, binding = 2) uniform sampler CustomMaterial_sampler;
|
||||
|
||||
// wgsl modules can be imported and used in glsl
|
||||
// FIXME - this doesn't work any more ...
|
||||
|
||||
@ -25,9 +25,9 @@ struct Mesh {
|
||||
};
|
||||
|
||||
#ifdef PER_OBJECT_BUFFER_BATCH_SIZE
|
||||
layout(set = 1, binding = 0) uniform Mesh Meshes[#{PER_OBJECT_BUFFER_BATCH_SIZE}];
|
||||
layout(set = 2, binding = 0) uniform Mesh Meshes[#{PER_OBJECT_BUFFER_BATCH_SIZE}];
|
||||
#else
|
||||
layout(set = 1, binding = 0) readonly buffer _Meshes {
|
||||
layout(set = 2, binding = 0) readonly buffer _Meshes {
|
||||
Mesh Meshes[];
|
||||
};
|
||||
#endif // PER_OBJECT_BUFFER_BATCH_SIZE
|
||||
|
||||
@ -10,7 +10,7 @@ struct CustomMaterial {
|
||||
time: vec4<f32>,
|
||||
}
|
||||
|
||||
@group(2) @binding(0) var<uniform> material: CustomMaterial;
|
||||
@group(3) @binding(0) var<uniform> material: CustomMaterial;
|
||||
|
||||
@fragment
|
||||
fn fragment(
|
||||
|
||||
@ -2,9 +2,9 @@
|
||||
// we can import items from shader modules in the assets folder with a quoted path
|
||||
#import "shaders/custom_material_import.wgsl"::COLOR_MULTIPLIER
|
||||
|
||||
@group(2) @binding(0) var<uniform> material_color: vec4<f32>;
|
||||
@group(2) @binding(1) var material_color_texture: texture_2d<f32>;
|
||||
@group(2) @binding(2) var material_color_sampler: sampler;
|
||||
@group(3) @binding(0) var<uniform> material_color: vec4<f32>;
|
||||
@group(3) @binding(1) var material_color_texture: texture_2d<f32>;
|
||||
@group(3) @binding(2) var material_color_sampler: sampler;
|
||||
|
||||
@fragment
|
||||
fn fragment(
|
||||
|
||||
@ -4,8 +4,8 @@
|
||||
utils::coords_to_viewport_uv,
|
||||
}
|
||||
|
||||
@group(2) @binding(0) var texture: texture_2d<f32>;
|
||||
@group(2) @binding(1) var texture_sampler: sampler;
|
||||
@group(3) @binding(0) var texture: texture_2d<f32>;
|
||||
@group(3) @binding(1) var texture_sampler: sampler;
|
||||
|
||||
@fragment
|
||||
fn fragment(
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
struct CustomMaterial {
|
||||
color: vec4<f32>,
|
||||
};
|
||||
@group(2) @binding(0) var<uniform> material: CustomMaterial;
|
||||
@group(3) @binding(0) var<uniform> material: CustomMaterial;
|
||||
|
||||
struct Vertex {
|
||||
@builtin(instance_index) instance_index: u32,
|
||||
|
||||
@ -19,7 +19,7 @@ struct MyExtendedMaterial {
|
||||
quantize_steps: u32,
|
||||
}
|
||||
|
||||
@group(2) @binding(100)
|
||||
@group(3) @binding(100)
|
||||
var<uniform> my_extended_material: MyExtendedMaterial;
|
||||
|
||||
@fragment
|
||||
|
||||
@ -42,19 +42,19 @@ struct ExampleBindlessExtendedMaterial {
|
||||
|
||||
// The indices of the bindless resources in the bindless resource arrays, for
|
||||
// the `ExampleBindlessExtension` fields.
|
||||
@group(2) @binding(100) var<storage> example_extended_material_indices:
|
||||
@group(3) @binding(100) var<storage> example_extended_material_indices:
|
||||
array<ExampleBindlessExtendedMaterialIndices>;
|
||||
// An array that holds the `ExampleBindlessExtendedMaterial` plain old data,
|
||||
// indexed by `ExampleBindlessExtendedMaterialIndices.material`.
|
||||
@group(2) @binding(101) var<storage> example_extended_material:
|
||||
@group(3) @binding(101) var<storage> example_extended_material:
|
||||
array<ExampleBindlessExtendedMaterial>;
|
||||
|
||||
#else // BINDLESS
|
||||
|
||||
// In non-bindless mode, we simply use a uniform for the plain old data.
|
||||
@group(2) @binding(50) var<uniform> example_extended_material: ExampleBindlessExtendedMaterial;
|
||||
@group(2) @binding(51) var modulate_texture: texture_2d<f32>;
|
||||
@group(2) @binding(52) var modulate_sampler: sampler;
|
||||
@group(3) @binding(50) var<uniform> example_extended_material: ExampleBindlessExtendedMaterial;
|
||||
@group(3) @binding(51) var modulate_texture: texture_2d<f32>;
|
||||
@group(3) @binding(52) var modulate_sampler: sampler;
|
||||
|
||||
#endif // BINDLESS
|
||||
|
||||
|
||||
@ -1,22 +1,22 @@
|
||||
#import bevy_pbr::forward_io::VertexOutput
|
||||
|
||||
@group(2) @binding(0) var test_texture_1d: texture_1d<f32>;
|
||||
@group(2) @binding(1) var test_texture_1d_sampler: sampler;
|
||||
@group(3) @binding(0) var test_texture_1d: texture_1d<f32>;
|
||||
@group(3) @binding(1) var test_texture_1d_sampler: sampler;
|
||||
|
||||
@group(2) @binding(2) var test_texture_2d: texture_2d<f32>;
|
||||
@group(2) @binding(3) var test_texture_2d_sampler: sampler;
|
||||
@group(3) @binding(2) var test_texture_2d: texture_2d<f32>;
|
||||
@group(3) @binding(3) var test_texture_2d_sampler: sampler;
|
||||
|
||||
@group(2) @binding(4) var test_texture_2d_array: texture_2d_array<f32>;
|
||||
@group(2) @binding(5) var test_texture_2d_array_sampler: sampler;
|
||||
@group(3) @binding(4) var test_texture_2d_array: texture_2d_array<f32>;
|
||||
@group(3) @binding(5) var test_texture_2d_array_sampler: sampler;
|
||||
|
||||
@group(2) @binding(6) var test_texture_cube: texture_cube<f32>;
|
||||
@group(2) @binding(7) var test_texture_cube_sampler: sampler;
|
||||
@group(3) @binding(6) var test_texture_cube: texture_cube<f32>;
|
||||
@group(3) @binding(7) var test_texture_cube_sampler: sampler;
|
||||
|
||||
@group(2) @binding(8) var test_texture_cube_array: texture_cube_array<f32>;
|
||||
@group(2) @binding(9) var test_texture_cube_array_sampler: sampler;
|
||||
@group(3) @binding(8) var test_texture_cube_array: texture_cube_array<f32>;
|
||||
@group(3) @binding(9) var test_texture_cube_array_sampler: sampler;
|
||||
|
||||
@group(2) @binding(10) var test_texture_3d: texture_3d<f32>;
|
||||
@group(2) @binding(11) var test_texture_3d_sampler: sampler;
|
||||
@group(3) @binding(10) var test_texture_3d: texture_3d<f32>;
|
||||
@group(3) @binding(11) var test_texture_3d_sampler: sampler;
|
||||
|
||||
@fragment
|
||||
fn fragment(in: VertexOutput) {}
|
||||
|
||||
@ -12,7 +12,7 @@ struct VoxelVisualizationIrradianceVolumeInfo {
|
||||
intensity: f32,
|
||||
}
|
||||
|
||||
@group(2) @binding(100)
|
||||
@group(3) @binding(100)
|
||||
var<uniform> irradiance_volume_info: VoxelVisualizationIrradianceVolumeInfo;
|
||||
|
||||
@fragment
|
||||
|
||||
@ -4,7 +4,7 @@ struct LineMaterial {
|
||||
color: vec4<f32>,
|
||||
};
|
||||
|
||||
@group(2) @binding(0) var<uniform> material: LineMaterial;
|
||||
@group(3) @binding(0) var<uniform> material: LineMaterial;
|
||||
|
||||
@fragment
|
||||
fn fragment(
|
||||
|
||||
11
assets/shaders/manual_material.wgsl
Normal file
11
assets/shaders/manual_material.wgsl
Normal file
@ -0,0 +1,11 @@
|
||||
#import bevy_pbr::forward_io::VertexOutput
|
||||
|
||||
@group(3) @binding(0) var material_color_texture: texture_2d<f32>;
|
||||
@group(3) @binding(1) var material_color_sampler: sampler;
|
||||
|
||||
@fragment
|
||||
fn fragment(
|
||||
mesh: VertexOutput,
|
||||
) -> @location(0) vec4<f32> {
|
||||
return textureSample(material_color_texture, material_color_sampler, mesh.uv);
|
||||
}
|
||||
@ -4,7 +4,7 @@ struct CustomMaterial {
|
||||
color: vec4<f32>,
|
||||
};
|
||||
|
||||
@group(2) @binding(0) var<uniform> material: CustomMaterial;
|
||||
@group(3) @binding(0) var<uniform> material: CustomMaterial;
|
||||
|
||||
@fragment
|
||||
fn fragment(
|
||||
|
||||
@ -11,7 +11,7 @@ struct ShowPrepassSettings {
|
||||
padding_1: u32,
|
||||
padding_2: u32,
|
||||
}
|
||||
@group(2) @binding(0) var<uniform> settings: ShowPrepassSettings;
|
||||
@group(3) @binding(0) var<uniform> settings: ShowPrepassSettings;
|
||||
|
||||
@fragment
|
||||
fn fragment(
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
view_transformations::position_world_to_clip
|
||||
}
|
||||
|
||||
@group(2) @binding(0) var<storage, read> colors: array<vec4<f32>, 5>;
|
||||
@group(3) @binding(0) var<storage, read> colors: array<vec4<f32>, 5>;
|
||||
|
||||
struct Vertex {
|
||||
@builtin(instance_index) instance_index: u32,
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
#import bevy_pbr::forward_io::VertexOutput
|
||||
|
||||
@group(2) @binding(0) var textures: binding_array<texture_2d<f32>>;
|
||||
@group(2) @binding(1) var nearest_sampler: sampler;
|
||||
@group(3) @binding(0) var textures: binding_array<texture_2d<f32>>;
|
||||
@group(3) @binding(1) var nearest_sampler: sampler;
|
||||
// We can also have array of samplers
|
||||
// var samplers: binding_array<sampler>;
|
||||
|
||||
|
||||
@ -23,9 +23,9 @@ struct WaterSettings {
|
||||
|
||||
@group(0) @binding(1) var<uniform> globals: Globals;
|
||||
|
||||
@group(2) @binding(100) var water_normals_texture: texture_2d<f32>;
|
||||
@group(2) @binding(101) var water_normals_sampler: sampler;
|
||||
@group(2) @binding(102) var<uniform> water_settings: WaterSettings;
|
||||
@group(3) @binding(100) var water_normals_texture: texture_2d<f32>;
|
||||
@group(3) @binding(101) var water_normals_sampler: sampler;
|
||||
@group(3) @binding(102) var<uniform> water_settings: WaterSettings;
|
||||
|
||||
// Samples a single octave of noise and returns the resulting normal.
|
||||
fn sample_noise_octave(uv: vec2<f32>, strength: f32) -> vec3<f32> {
|
||||
|
||||
@ -10,7 +10,7 @@ autobenches = false
|
||||
[dependencies]
|
||||
# The primary crate that runs and analyzes our benchmarks. This is a regular dependency because the
|
||||
# `bench!` macro refers to it in its documentation.
|
||||
criterion = { version = "0.5.1", features = ["html_reports"] }
|
||||
criterion = { version = "0.6.0", features = ["html_reports"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# Bevy crates
|
||||
|
||||
67
benches/benches/bevy_ecs/bundles/insert_many.rs
Normal file
67
benches/benches/bevy_ecs/bundles/insert_many.rs
Normal file
@ -0,0 +1,67 @@
|
||||
use benches::bench;
|
||||
use bevy_ecs::{component::Component, world::World};
|
||||
use criterion::Criterion;
|
||||
|
||||
const ENTITY_COUNT: usize = 2_000;
|
||||
|
||||
#[derive(Component)]
|
||||
struct C<const N: usize>(usize);
|
||||
|
||||
pub fn insert_many(criterion: &mut Criterion) {
|
||||
let mut group = criterion.benchmark_group(bench!("insert_many"));
|
||||
|
||||
group.bench_function("all", |bencher| {
|
||||
let mut world = World::new();
|
||||
bencher.iter(|| {
|
||||
for _ in 0..ENTITY_COUNT {
|
||||
world
|
||||
.spawn_empty()
|
||||
.insert(C::<0>(1))
|
||||
.insert(C::<1>(1))
|
||||
.insert(C::<2>(1))
|
||||
.insert(C::<3>(1))
|
||||
.insert(C::<4>(1))
|
||||
.insert(C::<5>(1))
|
||||
.insert(C::<6>(1))
|
||||
.insert(C::<7>(1))
|
||||
.insert(C::<8>(1))
|
||||
.insert(C::<9>(1))
|
||||
.insert(C::<10>(1))
|
||||
.insert(C::<11>(1))
|
||||
.insert(C::<12>(1))
|
||||
.insert(C::<13>(1))
|
||||
.insert(C::<14>(1));
|
||||
}
|
||||
world.clear_entities();
|
||||
});
|
||||
});
|
||||
|
||||
group.bench_function("only_last", |bencher| {
|
||||
let mut world = World::new();
|
||||
bencher.iter(|| {
|
||||
for _ in 0..ENTITY_COUNT {
|
||||
world
|
||||
.spawn((
|
||||
C::<0>(1),
|
||||
C::<1>(1),
|
||||
C::<2>(1),
|
||||
C::<3>(1),
|
||||
C::<4>(1),
|
||||
C::<5>(1),
|
||||
C::<6>(1),
|
||||
C::<7>(1),
|
||||
C::<8>(1),
|
||||
C::<9>(1),
|
||||
C::<10>(1),
|
||||
C::<11>(1),
|
||||
C::<12>(1),
|
||||
C::<13>(1),
|
||||
))
|
||||
.insert(C::<14>(1));
|
||||
}
|
||||
world.clear_entities();
|
||||
});
|
||||
});
|
||||
|
||||
group.finish();
|
||||
}
|
||||
14
benches/benches/bevy_ecs/bundles/mod.rs
Normal file
14
benches/benches/bevy_ecs/bundles/mod.rs
Normal file
@ -0,0 +1,14 @@
|
||||
use criterion::criterion_group;
|
||||
|
||||
mod insert_many;
|
||||
mod spawn_many;
|
||||
mod spawn_many_zst;
|
||||
mod spawn_one_zst;
|
||||
|
||||
criterion_group!(
|
||||
benches,
|
||||
spawn_one_zst::spawn_one_zst,
|
||||
spawn_many_zst::spawn_many_zst,
|
||||
spawn_many::spawn_many,
|
||||
insert_many::insert_many,
|
||||
);
|
||||
40
benches/benches/bevy_ecs/bundles/spawn_many.rs
Normal file
40
benches/benches/bevy_ecs/bundles/spawn_many.rs
Normal file
@ -0,0 +1,40 @@
|
||||
use benches::bench;
|
||||
use bevy_ecs::{component::Component, world::World};
|
||||
use criterion::Criterion;
|
||||
|
||||
const ENTITY_COUNT: usize = 2_000;
|
||||
|
||||
#[derive(Component)]
|
||||
struct C<const N: usize>(usize);
|
||||
|
||||
pub fn spawn_many(criterion: &mut Criterion) {
|
||||
let mut group = criterion.benchmark_group(bench!("spawn_many"));
|
||||
|
||||
group.bench_function("static", |bencher| {
|
||||
let mut world = World::new();
|
||||
bencher.iter(|| {
|
||||
for _ in 0..ENTITY_COUNT {
|
||||
world.spawn((
|
||||
C::<0>(1),
|
||||
C::<1>(1),
|
||||
C::<2>(1),
|
||||
C::<3>(1),
|
||||
C::<4>(1),
|
||||
C::<5>(1),
|
||||
C::<6>(1),
|
||||
C::<7>(1),
|
||||
C::<8>(1),
|
||||
C::<9>(1),
|
||||
C::<10>(1),
|
||||
C::<11>(1),
|
||||
C::<12>(1),
|
||||
C::<13>(1),
|
||||
C::<14>(1),
|
||||
));
|
||||
}
|
||||
world.clear_entities();
|
||||
});
|
||||
});
|
||||
|
||||
group.finish();
|
||||
}
|
||||
27
benches/benches/bevy_ecs/bundles/spawn_many_zst.rs
Normal file
27
benches/benches/bevy_ecs/bundles/spawn_many_zst.rs
Normal file
@ -0,0 +1,27 @@
|
||||
use benches::bench;
|
||||
use bevy_ecs::{component::Component, world::World};
|
||||
use criterion::Criterion;
|
||||
|
||||
const ENTITY_COUNT: usize = 2_000;
|
||||
|
||||
#[derive(Component)]
|
||||
struct C<const N: usize>;
|
||||
|
||||
pub fn spawn_many_zst(criterion: &mut Criterion) {
|
||||
let mut group = criterion.benchmark_group(bench!("spawn_many_zst"));
|
||||
|
||||
group.bench_function("static", |bencher| {
|
||||
let mut world = World::new();
|
||||
bencher.iter(|| {
|
||||
for _ in 0..ENTITY_COUNT {
|
||||
world.spawn((
|
||||
C::<0>, C::<1>, C::<2>, C::<3>, C::<4>, C::<5>, C::<6>, C::<7>, C::<8>, C::<9>,
|
||||
C::<10>, C::<11>, C::<12>, C::<13>, C::<14>,
|
||||
));
|
||||
}
|
||||
world.clear_entities();
|
||||
});
|
||||
});
|
||||
|
||||
group.finish();
|
||||
}
|
||||
24
benches/benches/bevy_ecs/bundles/spawn_one_zst.rs
Normal file
24
benches/benches/bevy_ecs/bundles/spawn_one_zst.rs
Normal file
@ -0,0 +1,24 @@
|
||||
use benches::bench;
|
||||
use bevy_ecs::{component::Component, world::World};
|
||||
use criterion::Criterion;
|
||||
|
||||
const ENTITY_COUNT: usize = 10_000;
|
||||
|
||||
#[derive(Component)]
|
||||
struct A;
|
||||
|
||||
pub fn spawn_one_zst(criterion: &mut Criterion) {
|
||||
let mut group = criterion.benchmark_group(bench!("spawn_one_zst"));
|
||||
|
||||
group.bench_function("static", |bencher| {
|
||||
let mut world = World::new();
|
||||
bencher.iter(|| {
|
||||
for _ in 0..ENTITY_COUNT {
|
||||
world.spawn(A);
|
||||
}
|
||||
world.clear_entities();
|
||||
});
|
||||
});
|
||||
|
||||
group.finish();
|
||||
}
|
||||
@ -49,6 +49,7 @@ impl BenchModify for Table {
|
||||
black_box(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl BenchModify for Sparse {
|
||||
fn bench_modify(&mut self) -> f32 {
|
||||
self.0 += 1f32;
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
use core::hint::black_box;
|
||||
|
||||
use benches::bench;
|
||||
use bevy_ecs::bundle::Bundle;
|
||||
use bevy_ecs::bundle::{Bundle, InsertMode};
|
||||
use bevy_ecs::component::ComponentCloneBehavior;
|
||||
use bevy_ecs::entity::EntityCloner;
|
||||
use bevy_ecs::hierarchy::ChildOf;
|
||||
@ -17,41 +17,15 @@ criterion_group!(
|
||||
hierarchy_tall,
|
||||
hierarchy_wide,
|
||||
hierarchy_many,
|
||||
filter
|
||||
);
|
||||
|
||||
#[derive(Component, Reflect, Default, Clone)]
|
||||
struct C1(Mat4);
|
||||
struct C<const N: usize>(Mat4);
|
||||
|
||||
#[derive(Component, Reflect, Default, Clone)]
|
||||
struct C2(Mat4);
|
||||
type ComplexBundle = (C<1>, C<2>, C<3>, C<4>, C<5>, C<6>, C<7>, C<8>, C<9>, C<10>);
|
||||
|
||||
#[derive(Component, Reflect, Default, Clone)]
|
||||
struct C3(Mat4);
|
||||
|
||||
#[derive(Component, Reflect, Default, Clone)]
|
||||
struct C4(Mat4);
|
||||
|
||||
#[derive(Component, Reflect, Default, Clone)]
|
||||
struct C5(Mat4);
|
||||
|
||||
#[derive(Component, Reflect, Default, Clone)]
|
||||
struct C6(Mat4);
|
||||
|
||||
#[derive(Component, Reflect, Default, Clone)]
|
||||
struct C7(Mat4);
|
||||
|
||||
#[derive(Component, Reflect, Default, Clone)]
|
||||
struct C8(Mat4);
|
||||
|
||||
#[derive(Component, Reflect, Default, Clone)]
|
||||
struct C9(Mat4);
|
||||
|
||||
#[derive(Component, Reflect, Default, Clone)]
|
||||
struct C10(Mat4);
|
||||
|
||||
type ComplexBundle = (C1, C2, C3, C4, C5, C6, C7, C8, C9, C10);
|
||||
|
||||
/// Sets the [`ComponentCloneHandler`] for all explicit and required components in a bundle `B` to
|
||||
/// Sets the [`ComponentCloneBehavior`] for all explicit and required components in a bundle `B` to
|
||||
/// use the [`Reflect`] trait instead of [`Clone`].
|
||||
fn reflection_cloner<B: Bundle + GetTypeRegistration>(
|
||||
world: &mut World,
|
||||
@ -71,7 +45,7 @@ fn reflection_cloner<B: Bundle + GetTypeRegistration>(
|
||||
// this bundle are saved.
|
||||
let component_ids: Vec<_> = world.register_bundle::<B>().contributed_components().into();
|
||||
|
||||
let mut builder = EntityCloner::build(world);
|
||||
let mut builder = EntityCloner::build_opt_out(world);
|
||||
|
||||
// Overwrite the clone handler for all components in the bundle to use `Reflect`, not `Clone`.
|
||||
for component in component_ids {
|
||||
@ -82,16 +56,15 @@ fn reflection_cloner<B: Bundle + GetTypeRegistration>(
|
||||
builder.finish()
|
||||
}
|
||||
|
||||
/// A helper function that benchmarks running the [`EntityCommands::clone_and_spawn()`] command on a
|
||||
/// bundle `B`.
|
||||
/// A helper function that benchmarks running [`EntityCloner::spawn_clone`] with a bundle `B`.
|
||||
///
|
||||
/// The bundle must implement [`Default`], which is used to create the first entity that gets cloned
|
||||
/// in the benchmark.
|
||||
///
|
||||
/// If `clone_via_reflect` is false, this will use the default [`ComponentCloneHandler`] for all
|
||||
/// components (which is usually [`ComponentCloneHandler::clone_handler()`]). If `clone_via_reflect`
|
||||
/// If `clone_via_reflect` is false, this will use the default [`ComponentCloneBehavior`] for all
|
||||
/// components (which is usually [`ComponentCloneBehavior::clone()`]). If `clone_via_reflect`
|
||||
/// is true, it will overwrite the handler for all components in the bundle to be
|
||||
/// [`ComponentCloneHandler::reflect_handler()`].
|
||||
/// [`ComponentCloneBehavior::reflect()`].
|
||||
fn bench_clone<B: Bundle + Default + GetTypeRegistration>(
|
||||
b: &mut Bencher,
|
||||
clone_via_reflect: bool,
|
||||
@ -114,8 +87,7 @@ fn bench_clone<B: Bundle + Default + GetTypeRegistration>(
|
||||
});
|
||||
}
|
||||
|
||||
/// A helper function that benchmarks running the [`EntityCommands::clone_and_spawn()`] command on a
|
||||
/// bundle `B`.
|
||||
/// A helper function that benchmarks running [`EntityCloner::spawn_clone`] with a bundle `B`.
|
||||
///
|
||||
/// As compared to [`bench_clone()`], this benchmarks recursively cloning an entity with several
|
||||
/// children. It does so by setting up an entity tree with a given `height` where each entity has a
|
||||
@ -135,7 +107,7 @@ fn bench_clone_hierarchy<B: Bundle + Default + GetTypeRegistration>(
|
||||
let mut cloner = if clone_via_reflect {
|
||||
reflection_cloner::<B>(&mut world, true)
|
||||
} else {
|
||||
let mut builder = EntityCloner::build(&mut world);
|
||||
let mut builder = EntityCloner::build_opt_out(&mut world);
|
||||
builder.linked_cloning(true);
|
||||
builder.finish()
|
||||
};
|
||||
@ -169,7 +141,7 @@ fn bench_clone_hierarchy<B: Bundle + Default + GetTypeRegistration>(
|
||||
|
||||
// Each benchmark runs twice: using either the `Clone` or `Reflect` traits to clone entities. This
|
||||
// constant represents this as an easy array that can be used in a `for` loop.
|
||||
const SCENARIOS: [(&str, bool); 2] = [("clone", false), ("reflect", true)];
|
||||
const CLONE_SCENARIOS: [(&str, bool); 2] = [("clone", false), ("reflect", true)];
|
||||
|
||||
/// Benchmarks cloning a single entity with 10 components and no children.
|
||||
fn single(c: &mut Criterion) {
|
||||
@ -178,7 +150,7 @@ fn single(c: &mut Criterion) {
|
||||
// We're cloning 1 entity.
|
||||
group.throughput(Throughput::Elements(1));
|
||||
|
||||
for (id, clone_via_reflect) in SCENARIOS {
|
||||
for (id, clone_via_reflect) in CLONE_SCENARIOS {
|
||||
group.bench_function(id, |b| {
|
||||
bench_clone::<ComplexBundle>(b, clone_via_reflect);
|
||||
});
|
||||
@ -194,9 +166,9 @@ fn hierarchy_tall(c: &mut Criterion) {
|
||||
// We're cloning both the root entity and its 50 descendents.
|
||||
group.throughput(Throughput::Elements(51));
|
||||
|
||||
for (id, clone_via_reflect) in SCENARIOS {
|
||||
for (id, clone_via_reflect) in CLONE_SCENARIOS {
|
||||
group.bench_function(id, |b| {
|
||||
bench_clone_hierarchy::<C1>(b, 50, 1, clone_via_reflect);
|
||||
bench_clone_hierarchy::<C<1>>(b, 50, 1, clone_via_reflect);
|
||||
});
|
||||
}
|
||||
|
||||
@ -210,9 +182,9 @@ fn hierarchy_wide(c: &mut Criterion) {
|
||||
// We're cloning both the root entity and its 50 direct children.
|
||||
group.throughput(Throughput::Elements(51));
|
||||
|
||||
for (id, clone_via_reflect) in SCENARIOS {
|
||||
for (id, clone_via_reflect) in CLONE_SCENARIOS {
|
||||
group.bench_function(id, |b| {
|
||||
bench_clone_hierarchy::<C1>(b, 1, 50, clone_via_reflect);
|
||||
bench_clone_hierarchy::<C<1>>(b, 1, 50, clone_via_reflect);
|
||||
});
|
||||
}
|
||||
|
||||
@ -228,7 +200,7 @@ fn hierarchy_many(c: &mut Criterion) {
|
||||
// of entities spawned in `bench_clone_hierarchy()` with a `println!()` statement. :)
|
||||
group.throughput(Throughput::Elements(364));
|
||||
|
||||
for (id, clone_via_reflect) in SCENARIOS {
|
||||
for (id, clone_via_reflect) in CLONE_SCENARIOS {
|
||||
group.bench_function(id, |b| {
|
||||
bench_clone_hierarchy::<ComplexBundle>(b, 5, 3, clone_via_reflect);
|
||||
});
|
||||
@ -236,3 +208,157 @@ fn hierarchy_many(c: &mut Criterion) {
|
||||
|
||||
group.finish();
|
||||
}
|
||||
|
||||
/// Filter scenario variant for bot opt-in and opt-out filters
|
||||
#[derive(Clone, Copy)]
|
||||
#[expect(
|
||||
clippy::enum_variant_names,
|
||||
reason = "'Opt' is not understood as an prefix but `OptOut'/'OptIn' are"
|
||||
)]
|
||||
enum FilterScenario {
|
||||
OptOutNone,
|
||||
OptOutNoneKeep(bool),
|
||||
OptOutAll,
|
||||
OptInNone,
|
||||
OptInAll,
|
||||
OptInAllWithoutRequired,
|
||||
OptInAllKeep(bool),
|
||||
OptInAllKeepWithoutRequired(bool),
|
||||
}
|
||||
|
||||
impl From<FilterScenario> for String {
|
||||
fn from(value: FilterScenario) -> Self {
|
||||
match value {
|
||||
FilterScenario::OptOutNone => "opt_out_none",
|
||||
FilterScenario::OptOutNoneKeep(true) => "opt_out_none_keep_none",
|
||||
FilterScenario::OptOutNoneKeep(false) => "opt_out_none_keep_all",
|
||||
FilterScenario::OptOutAll => "opt_out_all",
|
||||
FilterScenario::OptInNone => "opt_in_none",
|
||||
FilterScenario::OptInAll => "opt_in_all",
|
||||
FilterScenario::OptInAllWithoutRequired => "opt_in_all_without_required",
|
||||
FilterScenario::OptInAllKeep(true) => "opt_in_all_keep_none",
|
||||
FilterScenario::OptInAllKeep(false) => "opt_in_all_keep_all",
|
||||
FilterScenario::OptInAllKeepWithoutRequired(true) => {
|
||||
"opt_in_all_keep_none_without_required"
|
||||
}
|
||||
FilterScenario::OptInAllKeepWithoutRequired(false) => {
|
||||
"opt_in_all_keep_all_without_required"
|
||||
}
|
||||
}
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
/// Common scenarios for different filter to be benchmarked.
|
||||
const FILTER_SCENARIOS: [FilterScenario; 11] = [
|
||||
FilterScenario::OptOutNone,
|
||||
FilterScenario::OptOutNoneKeep(true),
|
||||
FilterScenario::OptOutNoneKeep(false),
|
||||
FilterScenario::OptOutAll,
|
||||
FilterScenario::OptInNone,
|
||||
FilterScenario::OptInAll,
|
||||
FilterScenario::OptInAllWithoutRequired,
|
||||
FilterScenario::OptInAllKeep(true),
|
||||
FilterScenario::OptInAllKeep(false),
|
||||
FilterScenario::OptInAllKeepWithoutRequired(true),
|
||||
FilterScenario::OptInAllKeepWithoutRequired(false),
|
||||
];
|
||||
|
||||
/// A helper function that benchmarks running [`EntityCloner::clone_entity`] with a bundle `B`.
|
||||
///
|
||||
/// The bundle must implement [`Default`], which is used to create the first entity that gets its components cloned
|
||||
/// in the benchmark. It may also be used to populate the target entity depending on the scenario.
|
||||
fn bench_filter<B: Bundle + Default>(b: &mut Bencher, scenario: FilterScenario) {
|
||||
let mut world = World::default();
|
||||
let mut spawn = |empty| match empty {
|
||||
false => world.spawn(B::default()).id(),
|
||||
true => world.spawn_empty().id(),
|
||||
};
|
||||
let source = spawn(false);
|
||||
let (target, mut cloner);
|
||||
|
||||
match scenario {
|
||||
FilterScenario::OptOutNone => {
|
||||
target = spawn(true);
|
||||
cloner = EntityCloner::default();
|
||||
}
|
||||
FilterScenario::OptOutNoneKeep(is_new) => {
|
||||
target = spawn(is_new);
|
||||
let mut builder = EntityCloner::build_opt_out(&mut world);
|
||||
builder.insert_mode(InsertMode::Keep);
|
||||
cloner = builder.finish();
|
||||
}
|
||||
FilterScenario::OptOutAll => {
|
||||
target = spawn(true);
|
||||
let mut builder = EntityCloner::build_opt_out(&mut world);
|
||||
builder.deny::<B>();
|
||||
cloner = builder.finish();
|
||||
}
|
||||
FilterScenario::OptInNone => {
|
||||
target = spawn(true);
|
||||
let builder = EntityCloner::build_opt_in(&mut world);
|
||||
cloner = builder.finish();
|
||||
}
|
||||
FilterScenario::OptInAll => {
|
||||
target = spawn(true);
|
||||
let mut builder = EntityCloner::build_opt_in(&mut world);
|
||||
builder.allow::<B>();
|
||||
cloner = builder.finish();
|
||||
}
|
||||
FilterScenario::OptInAllWithoutRequired => {
|
||||
target = spawn(true);
|
||||
let mut builder = EntityCloner::build_opt_in(&mut world);
|
||||
builder.without_required_components(|builder| {
|
||||
builder.allow::<B>();
|
||||
});
|
||||
cloner = builder.finish();
|
||||
}
|
||||
FilterScenario::OptInAllKeep(is_new) => {
|
||||
target = spawn(is_new);
|
||||
let mut builder = EntityCloner::build_opt_in(&mut world);
|
||||
builder.allow_if_new::<B>();
|
||||
cloner = builder.finish();
|
||||
}
|
||||
FilterScenario::OptInAllKeepWithoutRequired(is_new) => {
|
||||
target = spawn(is_new);
|
||||
let mut builder = EntityCloner::build_opt_in(&mut world);
|
||||
builder.without_required_components(|builder| {
|
||||
builder.allow_if_new::<B>();
|
||||
});
|
||||
cloner = builder.finish();
|
||||
}
|
||||
}
|
||||
|
||||
b.iter(|| {
|
||||
// clones the given entity into the target
|
||||
cloner.clone_entity(&mut world, black_box(source), black_box(target));
|
||||
world.flush();
|
||||
});
|
||||
}
|
||||
|
||||
/// Benchmarks filtering of cloning a single entity with 5 unclonable components (each requiring 1 unclonable component) into a target.
|
||||
fn filter(c: &mut Criterion) {
|
||||
#[derive(Component, Default)]
|
||||
#[component(clone_behavior = Ignore)]
|
||||
struct C<const N: usize>;
|
||||
|
||||
#[derive(Component, Default)]
|
||||
#[component(clone_behavior = Ignore)]
|
||||
#[require(C::<N>)]
|
||||
struct R<const N: usize>;
|
||||
|
||||
type RequiringBundle = (R<1>, R<2>, R<3>, R<4>, R<5>);
|
||||
|
||||
let mut group = c.benchmark_group(bench!("filter"));
|
||||
|
||||
// We're cloning 1 entity into a target.
|
||||
group.throughput(Throughput::Elements(1));
|
||||
|
||||
for scenario in FILTER_SCENARIOS {
|
||||
group.bench_function(scenario, |b| {
|
||||
bench_filter::<RequiringBundle>(b, scenario);
|
||||
});
|
||||
}
|
||||
|
||||
group.finish();
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
use bevy_ecs::prelude::*;
|
||||
|
||||
#[derive(Event)]
|
||||
#[derive(Event, BufferedEvent)]
|
||||
struct BenchEvent<const SIZE: usize>([u8; SIZE]);
|
||||
|
||||
pub struct Benchmark<const SIZE: usize>(Events<BenchEvent<SIZE>>);
|
||||
|
||||
@ -10,19 +10,19 @@ fn send(c: &mut Criterion) {
|
||||
group.warm_up_time(core::time::Duration::from_millis(500));
|
||||
group.measurement_time(core::time::Duration::from_secs(4));
|
||||
for count in [100, 1_000, 10_000] {
|
||||
group.bench_function(format!("size_4_events_{}", count), |b| {
|
||||
group.bench_function(format!("size_4_events_{count}"), |b| {
|
||||
let mut bench = send::Benchmark::<4>::new(count);
|
||||
b.iter(move || bench.run());
|
||||
});
|
||||
}
|
||||
for count in [100, 1_000, 10_000] {
|
||||
group.bench_function(format!("size_16_events_{}", count), |b| {
|
||||
group.bench_function(format!("size_16_events_{count}"), |b| {
|
||||
let mut bench = send::Benchmark::<16>::new(count);
|
||||
b.iter(move || bench.run());
|
||||
});
|
||||
}
|
||||
for count in [100, 1_000, 10_000] {
|
||||
group.bench_function(format!("size_512_events_{}", count), |b| {
|
||||
group.bench_function(format!("size_512_events_{count}"), |b| {
|
||||
let mut bench = send::Benchmark::<512>::new(count);
|
||||
b.iter(move || bench.run());
|
||||
});
|
||||
@ -35,19 +35,19 @@ fn iter(c: &mut Criterion) {
|
||||
group.warm_up_time(core::time::Duration::from_millis(500));
|
||||
group.measurement_time(core::time::Duration::from_secs(4));
|
||||
for count in [100, 1_000, 10_000] {
|
||||
group.bench_function(format!("size_4_events_{}", count), |b| {
|
||||
group.bench_function(format!("size_4_events_{count}"), |b| {
|
||||
let mut bench = iter::Benchmark::<4>::new(count);
|
||||
b.iter(move || bench.run());
|
||||
});
|
||||
}
|
||||
for count in [100, 1_000, 10_000] {
|
||||
group.bench_function(format!("size_16_events_{}", count), |b| {
|
||||
group.bench_function(format!("size_16_events_{count}"), |b| {
|
||||
let mut bench = iter::Benchmark::<4>::new(count);
|
||||
b.iter(move || bench.run());
|
||||
});
|
||||
}
|
||||
for count in [100, 1_000, 10_000] {
|
||||
group.bench_function(format!("size_512_events_{}", count), |b| {
|
||||
group.bench_function(format!("size_512_events_{count}"), |b| {
|
||||
let mut bench = iter::Benchmark::<512>::new(count);
|
||||
b.iter(move || bench.run());
|
||||
});
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
use bevy_ecs::prelude::*;
|
||||
|
||||
#[derive(Event)]
|
||||
#[derive(Event, BufferedEvent)]
|
||||
struct BenchEvent<const SIZE: usize>([u8; SIZE]);
|
||||
|
||||
impl<const SIZE: usize> Default for BenchEvent<SIZE> {
|
||||
|
||||
@ -42,6 +42,6 @@ impl Benchmark {
|
||||
|
||||
#[inline(never)]
|
||||
pub fn run(&mut self) {
|
||||
self.1.run((), &mut self.0);
|
||||
self.1.run((), &mut self.0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@ -130,7 +130,7 @@ fn par_iter_simple(c: &mut Criterion) {
|
||||
group.warm_up_time(core::time::Duration::from_millis(500));
|
||||
group.measurement_time(core::time::Duration::from_secs(4));
|
||||
for f in [0, 10, 100, 1000] {
|
||||
group.bench_function(format!("with_{}_fragment", f), |b| {
|
||||
group.bench_function(format!("with_{f}_fragment"), |b| {
|
||||
let mut bench = par_iter_simple::Benchmark::new(f);
|
||||
b.iter(move || bench.run());
|
||||
});
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
|
||||
use criterion::criterion_main;
|
||||
|
||||
mod bundles;
|
||||
mod change_detection;
|
||||
mod components;
|
||||
mod empty_archetypes;
|
||||
@ -18,6 +19,7 @@ mod scheduling;
|
||||
mod world;
|
||||
|
||||
criterion_main!(
|
||||
bundles::benches,
|
||||
change_detection::benches,
|
||||
components::benches,
|
||||
empty_archetypes::benches,
|
||||
|
||||
@ -61,14 +61,10 @@ pub fn event_propagation(criterion: &mut Criterion) {
|
||||
group.finish();
|
||||
}
|
||||
|
||||
#[derive(Clone, Component)]
|
||||
#[derive(Event, EntityEvent, Clone, Component)]
|
||||
#[entity_event(traversal = &'static ChildOf, auto_propagate)]
|
||||
struct TestEvent<const N: usize> {}
|
||||
|
||||
impl<const N: usize> Event for TestEvent<N> {
|
||||
type Traversal = &'static ChildOf;
|
||||
const AUTO_PROPAGATE: bool = true;
|
||||
}
|
||||
|
||||
fn send_events<const N: usize, const N_EVENTS: usize>(world: &mut World, leaves: &[Entity]) {
|
||||
let target = leaves.iter().choose(&mut rand::thread_rng()).unwrap();
|
||||
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
use core::hint::black_box;
|
||||
|
||||
use bevy_ecs::{
|
||||
event::Event,
|
||||
event::{EntityEvent, Event},
|
||||
observer::{On, TriggerTargets},
|
||||
world::World,
|
||||
};
|
||||
@ -13,7 +13,7 @@ fn deterministic_rand() -> ChaCha8Rng {
|
||||
ChaCha8Rng::seed_from_u64(42)
|
||||
}
|
||||
|
||||
#[derive(Clone, Event)]
|
||||
#[derive(Clone, Event, EntityEvent)]
|
||||
struct EventBase;
|
||||
|
||||
pub fn observe_simple(criterion: &mut Criterion) {
|
||||
|
||||
@ -24,7 +24,7 @@ pub fn run_condition_yes(criterion: &mut Criterion) {
|
||||
}
|
||||
// run once to initialize systems
|
||||
schedule.run(&mut world);
|
||||
group.bench_function(format!("{}_systems", amount), |bencher| {
|
||||
group.bench_function(format!("{amount}_systems"), |bencher| {
|
||||
bencher.iter(|| {
|
||||
schedule.run(&mut world);
|
||||
});
|
||||
@ -46,7 +46,7 @@ pub fn run_condition_no(criterion: &mut Criterion) {
|
||||
}
|
||||
// run once to initialize systems
|
||||
schedule.run(&mut world);
|
||||
group.bench_function(format!("{}_systems", amount), |bencher| {
|
||||
group.bench_function(format!("{amount}_systems"), |bencher| {
|
||||
bencher.iter(|| {
|
||||
schedule.run(&mut world);
|
||||
});
|
||||
@ -77,7 +77,7 @@ pub fn run_condition_yes_with_query(criterion: &mut Criterion) {
|
||||
}
|
||||
// run once to initialize systems
|
||||
schedule.run(&mut world);
|
||||
group.bench_function(format!("{}_systems", amount), |bencher| {
|
||||
group.bench_function(format!("{amount}_systems"), |bencher| {
|
||||
bencher.iter(|| {
|
||||
schedule.run(&mut world);
|
||||
});
|
||||
@ -105,7 +105,7 @@ pub fn run_condition_yes_with_resource(criterion: &mut Criterion) {
|
||||
}
|
||||
// run once to initialize systems
|
||||
schedule.run(&mut world);
|
||||
group.bench_function(format!("{}_systems", amount), |bencher| {
|
||||
group.bench_function(format!("{amount}_systems"), |bencher| {
|
||||
bencher.iter(|| {
|
||||
schedule.run(&mut world);
|
||||
});
|
||||
|
||||
@ -26,7 +26,7 @@ pub fn empty_systems(criterion: &mut Criterion) {
|
||||
schedule.add_systems(empty);
|
||||
}
|
||||
schedule.run(&mut world);
|
||||
group.bench_function(format!("{}_systems", amount), |bencher| {
|
||||
group.bench_function(format!("{amount}_systems"), |bencher| {
|
||||
bencher.iter(|| {
|
||||
schedule.run(&mut world);
|
||||
});
|
||||
@ -38,7 +38,7 @@ pub fn empty_systems(criterion: &mut Criterion) {
|
||||
schedule.add_systems((empty, empty, empty, empty, empty));
|
||||
}
|
||||
schedule.run(&mut world);
|
||||
group.bench_function(format!("{}_systems", amount), |bencher| {
|
||||
group.bench_function(format!("{amount}_systems"), |bencher| {
|
||||
bencher.iter(|| {
|
||||
schedule.run(&mut world);
|
||||
});
|
||||
@ -79,10 +79,7 @@ pub fn busy_systems(criterion: &mut Criterion) {
|
||||
}
|
||||
schedule.run(&mut world);
|
||||
group.bench_function(
|
||||
format!(
|
||||
"{:02}x_entities_{:02}_systems",
|
||||
entity_bunches, system_amount
|
||||
),
|
||||
format!("{entity_bunches:02}x_entities_{system_amount:02}_systems"),
|
||||
|bencher| {
|
||||
bencher.iter(|| {
|
||||
schedule.run(&mut world);
|
||||
@ -128,10 +125,7 @@ pub fn contrived(criterion: &mut Criterion) {
|
||||
}
|
||||
schedule.run(&mut world);
|
||||
group.bench_function(
|
||||
format!(
|
||||
"{:02}x_entities_{:02}_systems",
|
||||
entity_bunches, system_amount
|
||||
),
|
||||
format!("{entity_bunches:02}x_entities_{system_amount:02}_systems"),
|
||||
|bencher| {
|
||||
bencher.iter(|| {
|
||||
schedule.run(&mut world);
|
||||
|
||||
@ -37,7 +37,7 @@ pub fn spawn_commands(criterion: &mut Criterion) {
|
||||
group.measurement_time(core::time::Duration::from_secs(4));
|
||||
|
||||
for entity_count in [100, 1_000, 10_000] {
|
||||
group.bench_function(format!("{}_entities", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities"), |bencher| {
|
||||
let mut world = World::default();
|
||||
let mut command_queue = CommandQueue::default();
|
||||
|
||||
@ -68,7 +68,7 @@ pub fn nonempty_spawn_commands(criterion: &mut Criterion) {
|
||||
group.measurement_time(core::time::Duration::from_secs(4));
|
||||
|
||||
for entity_count in [100, 1_000, 10_000] {
|
||||
group.bench_function(format!("{}_entities", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities"), |bencher| {
|
||||
let mut world = World::default();
|
||||
let mut command_queue = CommandQueue::default();
|
||||
|
||||
@ -162,7 +162,7 @@ pub fn fake_commands(criterion: &mut Criterion) {
|
||||
group.measurement_time(core::time::Duration::from_secs(4));
|
||||
|
||||
for command_count in [100, 1_000, 10_000] {
|
||||
group.bench_function(format!("{}_commands", command_count), |bencher| {
|
||||
group.bench_function(format!("{command_count}_commands"), |bencher| {
|
||||
let mut world = World::default();
|
||||
let mut command_queue = CommandQueue::default();
|
||||
|
||||
@ -207,7 +207,7 @@ pub fn sized_commands_impl<T: Default + Command>(criterion: &mut Criterion) {
|
||||
group.measurement_time(core::time::Duration::from_secs(4));
|
||||
|
||||
for command_count in [100, 1_000, 10_000] {
|
||||
group.bench_function(format!("{}_commands", command_count), |bencher| {
|
||||
group.bench_function(format!("{command_count}_commands"), |bencher| {
|
||||
let mut world = World::default();
|
||||
let mut command_queue = CommandQueue::default();
|
||||
|
||||
|
||||
@ -13,7 +13,7 @@ pub fn world_despawn(criterion: &mut Criterion) {
|
||||
group.measurement_time(core::time::Duration::from_secs(4));
|
||||
|
||||
for entity_count in [1, 100, 10_000] {
|
||||
group.bench_function(format!("{}_entities", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities"), |bencher| {
|
||||
bencher.iter_batched_ref(
|
||||
|| {
|
||||
let mut world = World::default();
|
||||
|
||||
@ -13,7 +13,7 @@ pub fn world_despawn_recursive(criterion: &mut Criterion) {
|
||||
group.measurement_time(core::time::Duration::from_secs(4));
|
||||
|
||||
for entity_count in [1, 100, 10_000] {
|
||||
group.bench_function(format!("{}_entities", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities"), |bencher| {
|
||||
bencher.iter_batched_ref(
|
||||
|| {
|
||||
let mut world = World::default();
|
||||
|
||||
@ -13,7 +13,7 @@ pub fn world_spawn(criterion: &mut Criterion) {
|
||||
group.measurement_time(core::time::Duration::from_secs(4));
|
||||
|
||||
for entity_count in [1, 100, 10_000] {
|
||||
group.bench_function(format!("{}_entities", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities"), |bencher| {
|
||||
let mut world = World::default();
|
||||
bencher.iter(|| {
|
||||
for _ in 0..entity_count {
|
||||
|
||||
@ -49,7 +49,7 @@ pub fn world_entity(criterion: &mut Criterion) {
|
||||
group.measurement_time(core::time::Duration::from_secs(4));
|
||||
|
||||
for entity_count in RANGE.map(|i| i * 10_000) {
|
||||
group.bench_function(format!("{}_entities", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities"), |bencher| {
|
||||
let world = setup::<Table>(entity_count);
|
||||
|
||||
bencher.iter(|| {
|
||||
@ -72,7 +72,7 @@ pub fn world_get(criterion: &mut Criterion) {
|
||||
group.measurement_time(core::time::Duration::from_secs(4));
|
||||
|
||||
for entity_count in RANGE.map(|i| i * 10_000) {
|
||||
group.bench_function(format!("{}_entities_table", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities_table"), |bencher| {
|
||||
let world = setup::<Table>(entity_count);
|
||||
|
||||
bencher.iter(|| {
|
||||
@ -84,7 +84,7 @@ pub fn world_get(criterion: &mut Criterion) {
|
||||
}
|
||||
});
|
||||
});
|
||||
group.bench_function(format!("{}_entities_sparse", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities_sparse"), |bencher| {
|
||||
let world = setup::<Sparse>(entity_count);
|
||||
|
||||
bencher.iter(|| {
|
||||
@ -107,7 +107,7 @@ pub fn world_query_get(criterion: &mut Criterion) {
|
||||
group.measurement_time(core::time::Duration::from_secs(4));
|
||||
|
||||
for entity_count in RANGE.map(|i| i * 10_000) {
|
||||
group.bench_function(format!("{}_entities_table", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities_table"), |bencher| {
|
||||
let mut world = setup::<Table>(entity_count);
|
||||
let mut query = world.query::<&Table>();
|
||||
|
||||
@ -120,7 +120,7 @@ pub fn world_query_get(criterion: &mut Criterion) {
|
||||
}
|
||||
});
|
||||
});
|
||||
group.bench_function(format!("{}_entities_table_wide", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities_table_wide"), |bencher| {
|
||||
let mut world = setup_wide::<(
|
||||
WideTable<0>,
|
||||
WideTable<1>,
|
||||
@ -147,7 +147,7 @@ pub fn world_query_get(criterion: &mut Criterion) {
|
||||
}
|
||||
});
|
||||
});
|
||||
group.bench_function(format!("{}_entities_sparse", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities_sparse"), |bencher| {
|
||||
let mut world = setup::<Sparse>(entity_count);
|
||||
let mut query = world.query::<&Sparse>();
|
||||
|
||||
@ -160,37 +160,33 @@ pub fn world_query_get(criterion: &mut Criterion) {
|
||||
}
|
||||
});
|
||||
});
|
||||
group.bench_function(
|
||||
format!("{}_entities_sparse_wide", entity_count),
|
||||
|bencher| {
|
||||
let mut world = setup_wide::<(
|
||||
WideSparse<0>,
|
||||
WideSparse<1>,
|
||||
WideSparse<2>,
|
||||
WideSparse<3>,
|
||||
WideSparse<4>,
|
||||
WideSparse<5>,
|
||||
)>(entity_count);
|
||||
let mut query = world.query::<(
|
||||
&WideSparse<0>,
|
||||
&WideSparse<1>,
|
||||
&WideSparse<2>,
|
||||
&WideSparse<3>,
|
||||
&WideSparse<4>,
|
||||
&WideSparse<5>,
|
||||
)>();
|
||||
group.bench_function(format!("{entity_count}_entities_sparse_wide"), |bencher| {
|
||||
let mut world = setup_wide::<(
|
||||
WideSparse<0>,
|
||||
WideSparse<1>,
|
||||
WideSparse<2>,
|
||||
WideSparse<3>,
|
||||
WideSparse<4>,
|
||||
WideSparse<5>,
|
||||
)>(entity_count);
|
||||
let mut query = world.query::<(
|
||||
&WideSparse<0>,
|
||||
&WideSparse<1>,
|
||||
&WideSparse<2>,
|
||||
&WideSparse<3>,
|
||||
&WideSparse<4>,
|
||||
&WideSparse<5>,
|
||||
)>();
|
||||
|
||||
bencher.iter(|| {
|
||||
for i in 0..entity_count {
|
||||
// SAFETY: Range is exclusive.
|
||||
let entity = Entity::from_raw(EntityRow::new(unsafe {
|
||||
NonMaxU32::new_unchecked(i)
|
||||
}));
|
||||
assert!(query.get(&world, entity).is_ok());
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
bencher.iter(|| {
|
||||
for i in 0..entity_count {
|
||||
// SAFETY: Range is exclusive.
|
||||
let entity =
|
||||
Entity::from_raw(EntityRow::new(unsafe { NonMaxU32::new_unchecked(i) }));
|
||||
assert!(query.get(&world, entity).is_ok());
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
group.finish();
|
||||
@ -202,7 +198,7 @@ pub fn world_query_iter(criterion: &mut Criterion) {
|
||||
group.measurement_time(core::time::Duration::from_secs(4));
|
||||
|
||||
for entity_count in RANGE.map(|i| i * 10_000) {
|
||||
group.bench_function(format!("{}_entities_table", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities_table"), |bencher| {
|
||||
let mut world = setup::<Table>(entity_count);
|
||||
let mut query = world.query::<&Table>();
|
||||
|
||||
@ -216,7 +212,7 @@ pub fn world_query_iter(criterion: &mut Criterion) {
|
||||
assert_eq!(black_box(count), entity_count);
|
||||
});
|
||||
});
|
||||
group.bench_function(format!("{}_entities_sparse", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities_sparse"), |bencher| {
|
||||
let mut world = setup::<Sparse>(entity_count);
|
||||
let mut query = world.query::<&Sparse>();
|
||||
|
||||
@ -241,7 +237,7 @@ pub fn world_query_for_each(criterion: &mut Criterion) {
|
||||
group.measurement_time(core::time::Duration::from_secs(4));
|
||||
|
||||
for entity_count in RANGE.map(|i| i * 10_000) {
|
||||
group.bench_function(format!("{}_entities_table", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities_table"), |bencher| {
|
||||
let mut world = setup::<Table>(entity_count);
|
||||
let mut query = world.query::<&Table>();
|
||||
|
||||
@ -255,7 +251,7 @@ pub fn world_query_for_each(criterion: &mut Criterion) {
|
||||
assert_eq!(black_box(count), entity_count);
|
||||
});
|
||||
});
|
||||
group.bench_function(format!("{}_entities_sparse", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities_sparse"), |bencher| {
|
||||
let mut world = setup::<Sparse>(entity_count);
|
||||
let mut query = world.query::<&Sparse>();
|
||||
|
||||
@ -280,7 +276,7 @@ pub fn query_get(criterion: &mut Criterion) {
|
||||
group.measurement_time(core::time::Duration::from_secs(4));
|
||||
|
||||
for entity_count in RANGE.map(|i| i * 10_000) {
|
||||
group.bench_function(format!("{}_entities_table", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities_table"), |bencher| {
|
||||
let mut world = World::default();
|
||||
let mut entities: Vec<_> = world
|
||||
.spawn_batch((0..entity_count).map(|_| Table::default()))
|
||||
@ -299,7 +295,7 @@ pub fn query_get(criterion: &mut Criterion) {
|
||||
assert_eq!(black_box(count), entity_count);
|
||||
});
|
||||
});
|
||||
group.bench_function(format!("{}_entities_sparse", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_entities_sparse"), |bencher| {
|
||||
let mut world = World::default();
|
||||
let mut entities: Vec<_> = world
|
||||
.spawn_batch((0..entity_count).map(|_| Sparse::default()))
|
||||
@ -329,7 +325,7 @@ pub fn query_get_many<const N: usize>(criterion: &mut Criterion) {
|
||||
group.measurement_time(core::time::Duration::from_secs(2 * N as u64));
|
||||
|
||||
for entity_count in RANGE.map(|i| i * 10_000) {
|
||||
group.bench_function(format!("{}_calls_table", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_calls_table"), |bencher| {
|
||||
let mut world = World::default();
|
||||
let mut entity_groups: Vec<_> = (0..entity_count)
|
||||
.map(|_| [(); N].map(|_| world.spawn(Table::default()).id()))
|
||||
@ -352,7 +348,7 @@ pub fn query_get_many<const N: usize>(criterion: &mut Criterion) {
|
||||
assert_eq!(black_box(count), entity_count);
|
||||
});
|
||||
});
|
||||
group.bench_function(format!("{}_calls_sparse", entity_count), |bencher| {
|
||||
group.bench_function(format!("{entity_count}_calls_sparse"), |bencher| {
|
||||
let mut world = World::default();
|
||||
let mut entity_groups: Vec<_> = (0..entity_count)
|
||||
.map(|_| [(); N].map(|_| world.spawn(Sparse::default()).id()))
|
||||
|
||||
@ -155,6 +155,7 @@ fn bench(c: &mut Criterion) {
|
||||
&mesh.positions,
|
||||
Some(&mesh.normals),
|
||||
Some(&mesh.indices),
|
||||
None,
|
||||
backface_culling,
|
||||
);
|
||||
|
||||
|
||||
@ -142,7 +142,7 @@ fn concrete_map_apply(criterion: &mut Criterion) {
|
||||
|
||||
fn u64_to_n_byte_key(k: u64, n: usize) -> String {
|
||||
let mut key = String::with_capacity(n);
|
||||
write!(&mut key, "{}", k).unwrap();
|
||||
write!(&mut key, "{k}").unwrap();
|
||||
|
||||
// Pad key to n bytes.
|
||||
key.extend(iter::repeat_n('\0', n - key.len()));
|
||||
|
||||
@ -55,7 +55,7 @@ fn concrete_struct_field(criterion: &mut Criterion) {
|
||||
&s,
|
||||
|bencher, s| {
|
||||
let field_names = (0..field_count)
|
||||
.map(|i| format!("field_{}", i))
|
||||
.map(|i| format!("field_{i}"))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
bencher.iter(|| {
|
||||
@ -256,7 +256,7 @@ fn dynamic_struct_apply(criterion: &mut Criterion) {
|
||||
|
||||
let mut base = DynamicStruct::default();
|
||||
for i in 0..field_count {
|
||||
let field_name = format!("field_{}", i);
|
||||
let field_name = format!("field_{i}");
|
||||
base.insert(&field_name, 1u32);
|
||||
}
|
||||
|
||||
@ -283,7 +283,7 @@ fn dynamic_struct_apply(criterion: &mut Criterion) {
|
||||
let mut base = DynamicStruct::default();
|
||||
let mut patch = DynamicStruct::default();
|
||||
for i in 0..field_count {
|
||||
let field_name = format!("field_{}", i);
|
||||
let field_name = format!("field_{i}");
|
||||
base.insert(&field_name, 0u32);
|
||||
patch.insert(&field_name, 1u32);
|
||||
}
|
||||
@ -309,11 +309,11 @@ fn dynamic_struct_insert(criterion: &mut Criterion) {
|
||||
|bencher, field_count| {
|
||||
let mut s = DynamicStruct::default();
|
||||
for i in 0..*field_count {
|
||||
let field_name = format!("field_{}", i);
|
||||
let field_name = format!("field_{i}");
|
||||
s.insert(&field_name, ());
|
||||
}
|
||||
|
||||
let field = format!("field_{}", field_count);
|
||||
let field = format!("field_{field_count}");
|
||||
bencher.iter_batched(
|
||||
|| s.to_dynamic_struct(),
|
||||
|mut s| {
|
||||
@ -339,7 +339,7 @@ fn dynamic_struct_get_field(criterion: &mut Criterion) {
|
||||
|bencher, field_count| {
|
||||
let mut s = DynamicStruct::default();
|
||||
for i in 0..*field_count {
|
||||
let field_name = format!("field_{}", i);
|
||||
let field_name = format!("field_{i}");
|
||||
s.insert(&field_name, ());
|
||||
}
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "bevy_a11y"
|
||||
version = "0.16.0-dev"
|
||||
version = "0.17.0-dev"
|
||||
edition = "2024"
|
||||
description = "Provides accessibility support for Bevy Engine"
|
||||
homepage = "https://bevy.org"
|
||||
@ -40,10 +40,10 @@ critical-section = [
|
||||
|
||||
[dependencies]
|
||||
# bevy
|
||||
bevy_app = { path = "../bevy_app", version = "0.16.0-dev", default-features = false }
|
||||
bevy_derive = { path = "../bevy_derive", version = "0.16.0-dev" }
|
||||
bevy_ecs = { path = "../bevy_ecs", version = "0.16.0-dev", default-features = false }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.16.0-dev", default-features = false, optional = true }
|
||||
bevy_app = { path = "../bevy_app", version = "0.17.0-dev", default-features = false }
|
||||
bevy_derive = { path = "../bevy_derive", version = "0.17.0-dev" }
|
||||
bevy_ecs = { path = "../bevy_ecs", version = "0.17.0-dev", default-features = false }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.17.0-dev", default-features = false, optional = true }
|
||||
|
||||
# other
|
||||
accesskit = { version = "0.19", default-features = false }
|
||||
|
||||
@ -26,7 +26,8 @@ use accesskit::Node;
|
||||
use bevy_app::Plugin;
|
||||
use bevy_derive::{Deref, DerefMut};
|
||||
use bevy_ecs::{
|
||||
prelude::{Component, Event},
|
||||
component::Component,
|
||||
event::{BufferedEvent, Event},
|
||||
resource::Resource,
|
||||
schedule::SystemSet,
|
||||
};
|
||||
@ -44,7 +45,7 @@ use serde::{Deserialize, Serialize};
|
||||
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
|
||||
|
||||
/// Wrapper struct for [`accesskit::ActionRequest`]. Required to allow it to be used as an `Event`.
|
||||
#[derive(Event, Deref, DerefMut)]
|
||||
#[derive(Event, BufferedEvent, Deref, DerefMut)]
|
||||
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
|
||||
pub struct ActionRequest(pub accesskit::ActionRequest);
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "bevy_animation"
|
||||
version = "0.16.0-dev"
|
||||
version = "0.17.0-dev"
|
||||
edition = "2024"
|
||||
description = "Provides animation functionality for Bevy Engine"
|
||||
homepage = "https://bevy.org"
|
||||
@ -10,34 +10,34 @@ keywords = ["bevy"]
|
||||
|
||||
[dependencies]
|
||||
# bevy
|
||||
bevy_app = { path = "../bevy_app", version = "0.16.0-dev" }
|
||||
bevy_asset = { path = "../bevy_asset", version = "0.16.0-dev" }
|
||||
bevy_color = { path = "../bevy_color", version = "0.16.0-dev" }
|
||||
bevy_derive = { path = "../bevy_derive", version = "0.16.0-dev" }
|
||||
bevy_log = { path = "../bevy_log", version = "0.16.0-dev" }
|
||||
bevy_math = { path = "../bevy_math", version = "0.16.0-dev" }
|
||||
bevy_mesh = { path = "../bevy_mesh", version = "0.16.0-dev" }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.16.0-dev", features = [
|
||||
bevy_app = { path = "../bevy_app", version = "0.17.0-dev" }
|
||||
bevy_asset = { path = "../bevy_asset", version = "0.17.0-dev" }
|
||||
bevy_color = { path = "../bevy_color", version = "0.17.0-dev" }
|
||||
bevy_derive = { path = "../bevy_derive", version = "0.17.0-dev" }
|
||||
bevy_log = { path = "../bevy_log", version = "0.17.0-dev" }
|
||||
bevy_math = { path = "../bevy_math", version = "0.17.0-dev" }
|
||||
bevy_mesh = { path = "../bevy_mesh", version = "0.17.0-dev" }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.17.0-dev", features = [
|
||||
"petgraph",
|
||||
] }
|
||||
bevy_render = { path = "../bevy_render", version = "0.16.0-dev" }
|
||||
bevy_time = { path = "../bevy_time", version = "0.16.0-dev" }
|
||||
bevy_utils = { path = "../bevy_utils", version = "0.16.0-dev" }
|
||||
bevy_ecs = { path = "../bevy_ecs", version = "0.16.0-dev" }
|
||||
bevy_transform = { path = "../bevy_transform", version = "0.16.0-dev" }
|
||||
bevy_platform = { path = "../bevy_platform", version = "0.16.0-dev", default-features = false, features = [
|
||||
bevy_render = { path = "../bevy_render", version = "0.17.0-dev" }
|
||||
bevy_time = { path = "../bevy_time", version = "0.17.0-dev" }
|
||||
bevy_utils = { path = "../bevy_utils", version = "0.17.0-dev" }
|
||||
bevy_ecs = { path = "../bevy_ecs", version = "0.17.0-dev" }
|
||||
bevy_transform = { path = "../bevy_transform", version = "0.17.0-dev" }
|
||||
bevy_platform = { path = "../bevy_platform", version = "0.17.0-dev", default-features = false, features = [
|
||||
"std",
|
||||
"serialize",
|
||||
] }
|
||||
|
||||
# other
|
||||
petgraph = { version = "0.7", features = ["serde-1"] }
|
||||
ron = "0.8"
|
||||
petgraph = { version = "0.8", features = ["serde-1"] }
|
||||
ron = "0.10"
|
||||
serde = "1"
|
||||
blake3 = { version = "1.0" }
|
||||
downcast-rs = { version = "2", default-features = false, features = ["std"] }
|
||||
thiserror = { version = "2", default-features = false }
|
||||
derive_more = { version = "1", default-features = false, features = ["from"] }
|
||||
derive_more = { version = "2", default-features = false, features = ["from"] }
|
||||
either = "1.13"
|
||||
thread_local = "1"
|
||||
uuid = { version = "1.13.1", features = ["v4"] }
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
//! The animation graph, which allows animations to be blended together.
|
||||
|
||||
use core::{
|
||||
fmt::Write,
|
||||
iter,
|
||||
ops::{Index, IndexMut, Range},
|
||||
};
|
||||
use std::io::{self, Write};
|
||||
use std::io;
|
||||
|
||||
use bevy_asset::{
|
||||
io::Reader, Asset, AssetEvent, AssetId, AssetLoader, AssetPath, Assets, Handle, LoadContext,
|
||||
@ -18,7 +19,7 @@ use bevy_ecs::{
|
||||
system::{Res, ResMut},
|
||||
};
|
||||
use bevy_platform::collections::HashMap;
|
||||
use bevy_reflect::{prelude::ReflectDefault, Reflect, ReflectSerialize};
|
||||
use bevy_reflect::{prelude::ReflectDefault, Reflect};
|
||||
use derive_more::derive::From;
|
||||
use petgraph::{
|
||||
graph::{DiGraph, NodeIndex},
|
||||
@ -28,6 +29,7 @@ use ron::de::SpannedError;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use smallvec::SmallVec;
|
||||
use thiserror::Error;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::{AnimationClip, AnimationTargetId};
|
||||
|
||||
@ -107,9 +109,8 @@ use crate::{AnimationClip, AnimationTargetId};
|
||||
/// [RON]: https://github.com/ron-rs/ron
|
||||
///
|
||||
/// [RFC 51]: https://github.com/bevyengine/rfcs/blob/main/rfcs/51-animation-composition.md
|
||||
#[derive(Asset, Reflect, Clone, Debug, Serialize)]
|
||||
#[reflect(Serialize, Debug, Clone)]
|
||||
#[serde(into = "SerializedAnimationGraph")]
|
||||
#[derive(Asset, Reflect, Clone, Debug)]
|
||||
#[reflect(Debug, Clone)]
|
||||
pub struct AnimationGraph {
|
||||
/// The `petgraph` data structure that defines the animation graph.
|
||||
pub graph: AnimationDiGraph,
|
||||
@ -241,20 +242,40 @@ pub enum AnimationNodeType {
|
||||
#[derive(Default)]
|
||||
pub struct AnimationGraphAssetLoader;
|
||||
|
||||
/// Various errors that can occur when serializing or deserializing animation
|
||||
/// graphs to and from RON, respectively.
|
||||
/// Errors that can occur when serializing animation graphs to RON.
|
||||
#[derive(Error, Debug)]
|
||||
pub enum AnimationGraphSaveError {
|
||||
/// An I/O error occurred.
|
||||
#[error(transparent)]
|
||||
Io(#[from] io::Error),
|
||||
/// An error occurred in RON serialization.
|
||||
#[error(transparent)]
|
||||
Ron(#[from] ron::Error),
|
||||
/// An error occurred converting the graph to its serialization form.
|
||||
#[error(transparent)]
|
||||
ConvertToSerialized(#[from] NonPathHandleError),
|
||||
}
|
||||
|
||||
/// Errors that can occur when deserializing animation graphs from RON.
|
||||
#[derive(Error, Debug)]
|
||||
pub enum AnimationGraphLoadError {
|
||||
/// An I/O error occurred.
|
||||
#[error("I/O")]
|
||||
#[error(transparent)]
|
||||
Io(#[from] io::Error),
|
||||
/// An error occurred in RON serialization or deserialization.
|
||||
#[error("RON serialization")]
|
||||
/// An error occurred in RON deserialization.
|
||||
#[error(transparent)]
|
||||
Ron(#[from] ron::Error),
|
||||
/// An error occurred in RON deserialization, and the location of the error
|
||||
/// is supplied.
|
||||
#[error("RON serialization")]
|
||||
#[error(transparent)]
|
||||
SpannedRon(#[from] SpannedError),
|
||||
/// The deserialized graph contained legacy data that we no longer support.
|
||||
#[error(
|
||||
"The deserialized AnimationGraph contained an AnimationClip referenced by an AssetId, \
|
||||
which is no longer supported. Consider manually deserializing the SerializedAnimationGraph \
|
||||
type and determine how to migrate any SerializedAnimationClip::AssetId animation clips"
|
||||
)]
|
||||
GraphContainsLegacyAssetId,
|
||||
}
|
||||
|
||||
/// Acceleration structures for animation graphs that allows Bevy to evaluate
|
||||
@ -387,18 +408,32 @@ pub struct SerializedAnimationGraphNode {
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub enum SerializedAnimationNodeType {
|
||||
/// Corresponds to [`AnimationNodeType::Clip`].
|
||||
Clip(SerializedAnimationClip),
|
||||
Clip(MigrationSerializedAnimationClip),
|
||||
/// Corresponds to [`AnimationNodeType::Blend`].
|
||||
Blend,
|
||||
/// Corresponds to [`AnimationNodeType::Add`].
|
||||
Add,
|
||||
}
|
||||
|
||||
/// A version of `Handle<AnimationClip>` suitable for serializing as an asset.
|
||||
/// A type to facilitate migration from the legacy format of [`SerializedAnimationGraph`] to the
|
||||
/// new format.
|
||||
///
|
||||
/// This replaces any handle that has a path with an [`AssetPath`]. Failing
|
||||
/// that, the asset ID is serialized directly.
|
||||
/// By using untagged serde deserialization, we can try to deserialize the modern form, then
|
||||
/// fallback to the legacy form. Users must migrate to the modern form by Bevy 0.18.
|
||||
// TODO: Delete this after Bevy 0.17.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum MigrationSerializedAnimationClip {
|
||||
/// This is the new type of this field.
|
||||
Modern(AssetPath<'static>),
|
||||
/// This is the legacy type of this field. Users must migrate away from this.
|
||||
#[serde(skip_serializing)]
|
||||
Legacy(SerializedAnimationClip),
|
||||
}
|
||||
|
||||
/// The legacy form of serialized animation clips. This allows raw asset IDs to be deserialized.
|
||||
// TODO: Delete this after Bevy 0.17.
|
||||
#[derive(Deserialize)]
|
||||
pub enum SerializedAnimationClip {
|
||||
/// Records an asset path.
|
||||
AssetPath(AssetPath<'static>),
|
||||
@ -647,12 +682,13 @@ impl AnimationGraph {
|
||||
///
|
||||
/// If writing to a file, it can later be loaded with the
|
||||
/// [`AnimationGraphAssetLoader`] to reconstruct the graph.
|
||||
pub fn save<W>(&self, writer: &mut W) -> Result<(), AnimationGraphLoadError>
|
||||
pub fn save<W>(&self, writer: &mut W) -> Result<(), AnimationGraphSaveError>
|
||||
where
|
||||
W: Write,
|
||||
{
|
||||
let mut ron_serializer = ron::ser::Serializer::new(writer, None)?;
|
||||
Ok(self.serialize(&mut ron_serializer)?)
|
||||
let serialized_graph: SerializedAnimationGraph = self.clone().try_into()?;
|
||||
Ok(serialized_graph.serialize(&mut ron_serializer)?)
|
||||
}
|
||||
|
||||
/// Adds an animation target (bone) to the mask group with the given ID.
|
||||
@ -757,28 +793,55 @@ impl AssetLoader for AnimationGraphAssetLoader {
|
||||
let serialized_animation_graph = SerializedAnimationGraph::deserialize(&mut deserializer)
|
||||
.map_err(|err| deserializer.span_error(err))?;
|
||||
|
||||
// Load all `AssetPath`s to convert from a
|
||||
// `SerializedAnimationGraph` to a real `AnimationGraph`.
|
||||
Ok(AnimationGraph {
|
||||
graph: serialized_animation_graph.graph.map(
|
||||
|_, serialized_node| AnimationGraphNode {
|
||||
node_type: match serialized_node.node_type {
|
||||
SerializedAnimationNodeType::Clip(ref clip) => match clip {
|
||||
SerializedAnimationClip::AssetId(asset_id) => {
|
||||
AnimationNodeType::Clip(Handle::Weak(*asset_id))
|
||||
// Load all `AssetPath`s to convert from a `SerializedAnimationGraph` to a real
|
||||
// `AnimationGraph`. This is effectively a `DiGraph::map`, but this allows us to return
|
||||
// errors.
|
||||
let mut animation_graph = DiGraph::with_capacity(
|
||||
serialized_animation_graph.graph.node_count(),
|
||||
serialized_animation_graph.graph.edge_count(),
|
||||
);
|
||||
|
||||
let mut already_warned = false;
|
||||
for serialized_node in serialized_animation_graph.graph.node_weights() {
|
||||
animation_graph.add_node(AnimationGraphNode {
|
||||
node_type: match serialized_node.node_type {
|
||||
SerializedAnimationNodeType::Clip(ref clip) => match clip {
|
||||
MigrationSerializedAnimationClip::Modern(path) => {
|
||||
AnimationNodeType::Clip(load_context.load(path.clone()))
|
||||
}
|
||||
MigrationSerializedAnimationClip::Legacy(
|
||||
SerializedAnimationClip::AssetPath(path),
|
||||
) => {
|
||||
if !already_warned {
|
||||
let path = load_context.asset_path();
|
||||
warn!(
|
||||
"Loaded an AnimationGraph asset at \"{path}\" which contains a \
|
||||
legacy-style SerializedAnimationClip. Please re-save the asset \
|
||||
using AnimationGraph::save to automatically migrate to the new \
|
||||
format"
|
||||
);
|
||||
already_warned = true;
|
||||
}
|
||||
SerializedAnimationClip::AssetPath(asset_path) => {
|
||||
AnimationNodeType::Clip(load_context.load(asset_path))
|
||||
}
|
||||
},
|
||||
SerializedAnimationNodeType::Blend => AnimationNodeType::Blend,
|
||||
SerializedAnimationNodeType::Add => AnimationNodeType::Add,
|
||||
AnimationNodeType::Clip(load_context.load(path.clone()))
|
||||
}
|
||||
MigrationSerializedAnimationClip::Legacy(
|
||||
SerializedAnimationClip::AssetId(_),
|
||||
) => {
|
||||
return Err(AnimationGraphLoadError::GraphContainsLegacyAssetId);
|
||||
}
|
||||
},
|
||||
mask: serialized_node.mask,
|
||||
weight: serialized_node.weight,
|
||||
SerializedAnimationNodeType::Blend => AnimationNodeType::Blend,
|
||||
SerializedAnimationNodeType::Add => AnimationNodeType::Add,
|
||||
},
|
||||
|_, _| (),
|
||||
),
|
||||
mask: serialized_node.mask,
|
||||
weight: serialized_node.weight,
|
||||
});
|
||||
}
|
||||
for edge in serialized_animation_graph.graph.raw_edges() {
|
||||
animation_graph.add_edge(edge.source(), edge.target(), ());
|
||||
}
|
||||
Ok(AnimationGraph {
|
||||
graph: animation_graph,
|
||||
root: serialized_animation_graph.root,
|
||||
mask_groups: serialized_animation_graph.mask_groups,
|
||||
})
|
||||
@ -789,37 +852,50 @@ impl AssetLoader for AnimationGraphAssetLoader {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AnimationGraph> for SerializedAnimationGraph {
|
||||
fn from(animation_graph: AnimationGraph) -> Self {
|
||||
// If any of the animation clips have paths, then serialize them as
|
||||
// `SerializedAnimationClip::AssetPath` so that the
|
||||
// `AnimationGraphAssetLoader` can load them.
|
||||
Self {
|
||||
graph: animation_graph.graph.map(
|
||||
|_, node| SerializedAnimationGraphNode {
|
||||
weight: node.weight,
|
||||
mask: node.mask,
|
||||
node_type: match node.node_type {
|
||||
AnimationNodeType::Clip(ref clip) => match clip.path() {
|
||||
Some(path) => SerializedAnimationNodeType::Clip(
|
||||
SerializedAnimationClip::AssetPath(path.clone()),
|
||||
),
|
||||
None => SerializedAnimationNodeType::Clip(
|
||||
SerializedAnimationClip::AssetId(clip.id()),
|
||||
),
|
||||
},
|
||||
AnimationNodeType::Blend => SerializedAnimationNodeType::Blend,
|
||||
AnimationNodeType::Add => SerializedAnimationNodeType::Add,
|
||||
impl TryFrom<AnimationGraph> for SerializedAnimationGraph {
|
||||
type Error = NonPathHandleError;
|
||||
|
||||
fn try_from(animation_graph: AnimationGraph) -> Result<Self, NonPathHandleError> {
|
||||
// Convert all the `Handle<AnimationClip>` to AssetPath, so that
|
||||
// `AnimationGraphAssetLoader` can load them. This is effectively just doing a
|
||||
// `DiGraph::map`, except we need to return an error if any handles aren't associated to a
|
||||
// path.
|
||||
let mut serialized_graph = DiGraph::with_capacity(
|
||||
animation_graph.graph.node_count(),
|
||||
animation_graph.graph.edge_count(),
|
||||
);
|
||||
for node in animation_graph.graph.node_weights() {
|
||||
serialized_graph.add_node(SerializedAnimationGraphNode {
|
||||
weight: node.weight,
|
||||
mask: node.mask,
|
||||
node_type: match node.node_type {
|
||||
AnimationNodeType::Clip(ref clip) => match clip.path() {
|
||||
Some(path) => SerializedAnimationNodeType::Clip(
|
||||
MigrationSerializedAnimationClip::Modern(path.clone()),
|
||||
),
|
||||
None => return Err(NonPathHandleError),
|
||||
},
|
||||
AnimationNodeType::Blend => SerializedAnimationNodeType::Blend,
|
||||
AnimationNodeType::Add => SerializedAnimationNodeType::Add,
|
||||
},
|
||||
|_, _| (),
|
||||
),
|
||||
});
|
||||
}
|
||||
for edge in animation_graph.graph.raw_edges() {
|
||||
serialized_graph.add_edge(edge.source(), edge.target(), ());
|
||||
}
|
||||
Ok(Self {
|
||||
graph: serialized_graph,
|
||||
root: animation_graph.root,
|
||||
mask_groups: animation_graph.mask_groups,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Error for when only path [`Handle`]s are supported.
|
||||
#[derive(Error, Debug)]
|
||||
#[error("AnimationGraph contains a handle to an AnimationClip that does not correspond to an asset path")]
|
||||
pub struct NonPathHandleError;
|
||||
|
||||
/// A system that creates, updates, and removes [`ThreadedAnimationGraph`]
|
||||
/// structures for every changed [`AnimationGraph`].
|
||||
///
|
||||
|
||||
@ -324,13 +324,13 @@ impl AnimationClip {
|
||||
.push(variable_curve);
|
||||
}
|
||||
|
||||
/// Add a untargeted [`Event`] to this [`AnimationClip`].
|
||||
/// Add an [`EntityEvent`] with no [`AnimationTarget`] to this [`AnimationClip`].
|
||||
///
|
||||
/// The `event` will be cloned and triggered on the [`AnimationPlayer`] entity once the `time` (in seconds)
|
||||
/// is reached in the animation.
|
||||
///
|
||||
/// See also [`add_event_to_target`](Self::add_event_to_target).
|
||||
pub fn add_event(&mut self, time: f32, event: impl Event + Clone) {
|
||||
pub fn add_event(&mut self, time: f32, event: impl EntityEvent + Clone) {
|
||||
self.add_event_fn(
|
||||
time,
|
||||
move |commands: &mut Commands, entity: Entity, _time: f32, _weight: f32| {
|
||||
@ -339,7 +339,7 @@ impl AnimationClip {
|
||||
);
|
||||
}
|
||||
|
||||
/// Add an [`Event`] to an [`AnimationTarget`] named by an [`AnimationTargetId`].
|
||||
/// Add an [`EntityEvent`] to an [`AnimationTarget`] named by an [`AnimationTargetId`].
|
||||
///
|
||||
/// The `event` will be cloned and triggered on the entity matching the target once the `time` (in seconds)
|
||||
/// is reached in the animation.
|
||||
@ -349,7 +349,7 @@ impl AnimationClip {
|
||||
&mut self,
|
||||
target_id: AnimationTargetId,
|
||||
time: f32,
|
||||
event: impl Event + Clone,
|
||||
event: impl EntityEvent + Clone,
|
||||
) {
|
||||
self.add_event_fn_to_target(
|
||||
target_id,
|
||||
@ -360,19 +360,19 @@ impl AnimationClip {
|
||||
);
|
||||
}
|
||||
|
||||
/// Add a untargeted event function to this [`AnimationClip`].
|
||||
/// Add an event function with no [`AnimationTarget`] to this [`AnimationClip`].
|
||||
///
|
||||
/// The `func` will trigger on the [`AnimationPlayer`] entity once the `time` (in seconds)
|
||||
/// is reached in the animation.
|
||||
///
|
||||
/// For a simpler [`Event`]-based alternative, see [`AnimationClip::add_event`].
|
||||
/// For a simpler [`EntityEvent`]-based alternative, see [`AnimationClip::add_event`].
|
||||
/// See also [`add_event_to_target`](Self::add_event_to_target).
|
||||
///
|
||||
/// ```
|
||||
/// # use bevy_animation::AnimationClip;
|
||||
/// # let mut clip = AnimationClip::default();
|
||||
/// clip.add_event_fn(1.0, |commands, entity, time, weight| {
|
||||
/// println!("Animation Event Triggered {entity:#?} at time {time} with weight {weight}");
|
||||
/// println!("Animation event triggered {entity:#?} at time {time} with weight {weight}");
|
||||
/// })
|
||||
/// ```
|
||||
pub fn add_event_fn(
|
||||
@ -388,14 +388,14 @@ impl AnimationClip {
|
||||
/// The `func` will trigger on the entity matching the target once the `time` (in seconds)
|
||||
/// is reached in the animation.
|
||||
///
|
||||
/// For a simpler [`Event`]-based alternative, see [`AnimationClip::add_event_to_target`].
|
||||
/// For a simpler [`EntityEvent`]-based alternative, see [`AnimationClip::add_event_to_target`].
|
||||
/// Use [`add_event`](Self::add_event) instead if you don't have a specific target.
|
||||
///
|
||||
/// ```
|
||||
/// # use bevy_animation::{AnimationClip, AnimationTargetId};
|
||||
/// # let mut clip = AnimationClip::default();
|
||||
/// clip.add_event_fn_to_target(AnimationTargetId::from_iter(["Arm", "Hand"]), 1.0, |commands, entity, time, weight| {
|
||||
/// println!("Animation Event Triggered {entity:#?} at time {time} with weight {weight}");
|
||||
/// println!("Animation event triggered {entity:#?} at time {time} with weight {weight}");
|
||||
/// })
|
||||
/// ```
|
||||
pub fn add_event_fn_to_target(
|
||||
@ -1534,7 +1534,7 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Event, Reflect, Clone)]
|
||||
#[derive(Event, EntityEvent, Reflect, Clone)]
|
||||
struct A;
|
||||
|
||||
#[track_caller]
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "bevy_anti_aliasing"
|
||||
version = "0.16.0-dev"
|
||||
version = "0.17.0-dev"
|
||||
edition = "2024"
|
||||
description = "Provides various anti aliasing implementations for Bevy Engine"
|
||||
homepage = "https://bevy.org"
|
||||
@ -16,17 +16,17 @@ smaa_luts = ["bevy_render/ktx2", "bevy_image/ktx2", "bevy_image/zstd"]
|
||||
|
||||
[dependencies]
|
||||
# bevy
|
||||
bevy_asset = { path = "../bevy_asset", version = "0.16.0-dev" }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.16.0-dev" }
|
||||
bevy_render = { path = "../bevy_render", version = "0.16.0-dev" }
|
||||
bevy_math = { path = "../bevy_math", version = "0.16.0-dev" }
|
||||
bevy_utils = { path = "../bevy_utils", version = "0.16.0-dev" }
|
||||
bevy_app = { path = "../bevy_app", version = "0.16.0-dev" }
|
||||
bevy_image = { path = "../bevy_image", version = "0.16.0-dev" }
|
||||
bevy_derive = { path = "../bevy_derive", version = "0.16.0-dev" }
|
||||
bevy_ecs = { path = "../bevy_ecs", version = "0.16.0-dev" }
|
||||
bevy_core_pipeline = { path = "../bevy_core_pipeline", version = "0.16.0-dev" }
|
||||
bevy_diagnostic = { path = "../bevy_diagnostic", version = "0.16.0-dev" }
|
||||
bevy_asset = { path = "../bevy_asset", version = "0.17.0-dev" }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.17.0-dev" }
|
||||
bevy_render = { path = "../bevy_render", version = "0.17.0-dev" }
|
||||
bevy_math = { path = "../bevy_math", version = "0.17.0-dev" }
|
||||
bevy_utils = { path = "../bevy_utils", version = "0.17.0-dev" }
|
||||
bevy_app = { path = "../bevy_app", version = "0.17.0-dev" }
|
||||
bevy_image = { path = "../bevy_image", version = "0.17.0-dev" }
|
||||
bevy_derive = { path = "../bevy_derive", version = "0.17.0-dev" }
|
||||
bevy_ecs = { path = "../bevy_ecs", version = "0.17.0-dev" }
|
||||
bevy_core_pipeline = { path = "../bevy_core_pipeline", version = "0.17.0-dev" }
|
||||
bevy_diagnostic = { path = "../bevy_diagnostic", version = "0.17.0-dev" }
|
||||
|
||||
# other
|
||||
tracing = { version = "0.1", default-features = false, features = ["std"] }
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
use bevy_app::prelude::*;
|
||||
use bevy_asset::{embedded_asset, load_embedded_asset, Handle};
|
||||
use bevy_asset::{embedded_asset, load_embedded_asset, AssetServer, Handle};
|
||||
use bevy_core_pipeline::{
|
||||
core_2d::graph::{Core2d, Node2d},
|
||||
core_3d::graph::{Core3d, Node3d},
|
||||
fullscreen_vertex_shader::fullscreen_shader_vertex_state,
|
||||
FullscreenShader,
|
||||
};
|
||||
use bevy_ecs::{prelude::*, query::QueryItem};
|
||||
use bevy_image::BevyDefault as _;
|
||||
@ -11,15 +11,16 @@ use bevy_reflect::{std_traits::ReflectDefault, Reflect};
|
||||
use bevy_render::{
|
||||
extract_component::{ExtractComponent, ExtractComponentPlugin, UniformComponentPlugin},
|
||||
prelude::Camera,
|
||||
render_graph::RenderGraphApp,
|
||||
render_graph::RenderGraphExt,
|
||||
render_resource::{
|
||||
binding_types::{sampler, texture_2d, uniform_buffer},
|
||||
*,
|
||||
},
|
||||
renderer::RenderDevice,
|
||||
view::{ExtractedView, ViewTarget},
|
||||
Render, RenderApp, RenderSystems,
|
||||
Render, RenderApp, RenderStartup, RenderSystems,
|
||||
};
|
||||
use bevy_utils::default;
|
||||
|
||||
mod node;
|
||||
|
||||
@ -113,6 +114,7 @@ impl Plugin for CasPlugin {
|
||||
};
|
||||
render_app
|
||||
.init_resource::<SpecializedRenderPipelines<CasPipeline>>()
|
||||
.add_systems(RenderStartup, init_cas_pipeline)
|
||||
.add_systems(Render, prepare_cas_pipelines.in_set(RenderSystems::Prepare));
|
||||
|
||||
{
|
||||
@ -150,46 +152,46 @@ impl Plugin for CasPlugin {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&self, app: &mut App) {
|
||||
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
|
||||
return;
|
||||
};
|
||||
render_app.init_resource::<CasPipeline>();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct CasPipeline {
|
||||
texture_bind_group: BindGroupLayout,
|
||||
sampler: Sampler,
|
||||
shader: Handle<Shader>,
|
||||
fullscreen_shader: FullscreenShader,
|
||||
fragment_shader: Handle<Shader>,
|
||||
}
|
||||
|
||||
impl FromWorld for CasPipeline {
|
||||
fn from_world(render_world: &mut World) -> Self {
|
||||
let render_device = render_world.resource::<RenderDevice>();
|
||||
let texture_bind_group = render_device.create_bind_group_layout(
|
||||
"sharpening_texture_bind_group_layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::FRAGMENT,
|
||||
(
|
||||
texture_2d(TextureSampleType::Float { filterable: true }),
|
||||
sampler(SamplerBindingType::Filtering),
|
||||
// CAS Settings
|
||||
uniform_buffer::<CasUniform>(true),
|
||||
),
|
||||
pub fn init_cas_pipeline(
|
||||
mut commands: Commands,
|
||||
render_device: Res<RenderDevice>,
|
||||
fullscreen_shader: Res<FullscreenShader>,
|
||||
asset_server: Res<AssetServer>,
|
||||
) {
|
||||
let texture_bind_group = render_device.create_bind_group_layout(
|
||||
"sharpening_texture_bind_group_layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::FRAGMENT,
|
||||
(
|
||||
texture_2d(TextureSampleType::Float { filterable: true }),
|
||||
sampler(SamplerBindingType::Filtering),
|
||||
// CAS Settings
|
||||
uniform_buffer::<CasUniform>(true),
|
||||
),
|
||||
);
|
||||
),
|
||||
);
|
||||
|
||||
let sampler = render_device.create_sampler(&SamplerDescriptor::default());
|
||||
let sampler = render_device.create_sampler(&SamplerDescriptor::default());
|
||||
|
||||
CasPipeline {
|
||||
texture_bind_group,
|
||||
sampler,
|
||||
shader: load_embedded_asset!(render_world, "robust_contrast_adaptive_sharpening.wgsl"),
|
||||
}
|
||||
}
|
||||
commands.insert_resource(CasPipeline {
|
||||
texture_bind_group,
|
||||
sampler,
|
||||
fullscreen_shader: fullscreen_shader.clone(),
|
||||
fragment_shader: load_embedded_asset!(
|
||||
asset_server.as_ref(),
|
||||
"robust_contrast_adaptive_sharpening.wgsl"
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Hash, Clone, Copy)]
|
||||
@ -209,22 +211,18 @@ impl SpecializedRenderPipeline for CasPipeline {
|
||||
RenderPipelineDescriptor {
|
||||
label: Some("contrast_adaptive_sharpening".into()),
|
||||
layout: vec![self.texture_bind_group.clone()],
|
||||
vertex: fullscreen_shader_vertex_state(),
|
||||
vertex: self.fullscreen_shader.to_vertex_state(),
|
||||
fragment: Some(FragmentState {
|
||||
shader: self.shader.clone(),
|
||||
shader: self.fragment_shader.clone(),
|
||||
shader_defs,
|
||||
entry_point: "fragment".into(),
|
||||
targets: vec![Some(ColorTargetState {
|
||||
format: key.texture_format,
|
||||
blend: None,
|
||||
write_mask: ColorWrites::ALL,
|
||||
})],
|
||||
..default()
|
||||
}),
|
||||
primitive: PrimitiveState::default(),
|
||||
depth_stencil: None,
|
||||
multisample: MultisampleState::default(),
|
||||
push_constant_ranges: Vec::new(),
|
||||
zero_initialize_workgroup_memory: false,
|
||||
..default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
use bevy_app::prelude::*;
|
||||
use bevy_asset::{embedded_asset, load_embedded_asset, Handle};
|
||||
use bevy_asset::{embedded_asset, load_embedded_asset, AssetServer, Handle};
|
||||
use bevy_core_pipeline::{
|
||||
core_2d::graph::{Core2d, Node2d},
|
||||
core_3d::graph::{Core3d, Node3d},
|
||||
fullscreen_vertex_shader::fullscreen_shader_vertex_state,
|
||||
FullscreenShader,
|
||||
};
|
||||
use bevy_ecs::prelude::*;
|
||||
use bevy_image::BevyDefault as _;
|
||||
@ -11,14 +11,14 @@ use bevy_reflect::{std_traits::ReflectDefault, Reflect};
|
||||
use bevy_render::{
|
||||
extract_component::{ExtractComponent, ExtractComponentPlugin},
|
||||
prelude::Camera,
|
||||
render_graph::{RenderGraphApp, ViewNodeRunner},
|
||||
render_graph::{RenderGraphExt, ViewNodeRunner},
|
||||
render_resource::{
|
||||
binding_types::{sampler, texture_2d},
|
||||
*,
|
||||
},
|
||||
renderer::RenderDevice,
|
||||
view::{ExtractedView, ViewTarget},
|
||||
Render, RenderApp, RenderSystems,
|
||||
Render, RenderApp, RenderStartup, RenderSystems,
|
||||
};
|
||||
use bevy_utils::default;
|
||||
|
||||
@ -94,6 +94,7 @@ impl Plugin for FxaaPlugin {
|
||||
};
|
||||
render_app
|
||||
.init_resource::<SpecializedRenderPipelines<FxaaPipeline>>()
|
||||
.add_systems(RenderStartup, init_fxaa_pipeline)
|
||||
.add_systems(
|
||||
Render,
|
||||
prepare_fxaa_pipelines.in_set(RenderSystems::Prepare),
|
||||
@ -117,49 +118,46 @@ impl Plugin for FxaaPlugin {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
fn finish(&self, app: &mut App) {
|
||||
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
|
||||
return;
|
||||
};
|
||||
render_app.init_resource::<FxaaPipeline>();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct FxaaPipeline {
|
||||
texture_bind_group: BindGroupLayout,
|
||||
sampler: Sampler,
|
||||
shader: Handle<Shader>,
|
||||
fullscreen_shader: FullscreenShader,
|
||||
fragment_shader: Handle<Shader>,
|
||||
}
|
||||
|
||||
impl FromWorld for FxaaPipeline {
|
||||
fn from_world(render_world: &mut World) -> Self {
|
||||
let render_device = render_world.resource::<RenderDevice>();
|
||||
let texture_bind_group = render_device.create_bind_group_layout(
|
||||
"fxaa_texture_bind_group_layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::FRAGMENT,
|
||||
(
|
||||
texture_2d(TextureSampleType::Float { filterable: true }),
|
||||
sampler(SamplerBindingType::Filtering),
|
||||
),
|
||||
pub fn init_fxaa_pipeline(
|
||||
mut commands: Commands,
|
||||
render_device: Res<RenderDevice>,
|
||||
fullscreen_shader: Res<FullscreenShader>,
|
||||
asset_server: Res<AssetServer>,
|
||||
) {
|
||||
let texture_bind_group = render_device.create_bind_group_layout(
|
||||
"fxaa_texture_bind_group_layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::FRAGMENT,
|
||||
(
|
||||
texture_2d(TextureSampleType::Float { filterable: true }),
|
||||
sampler(SamplerBindingType::Filtering),
|
||||
),
|
||||
);
|
||||
),
|
||||
);
|
||||
|
||||
let sampler = render_device.create_sampler(&SamplerDescriptor {
|
||||
mipmap_filter: FilterMode::Linear,
|
||||
mag_filter: FilterMode::Linear,
|
||||
min_filter: FilterMode::Linear,
|
||||
..default()
|
||||
});
|
||||
let sampler = render_device.create_sampler(&SamplerDescriptor {
|
||||
mipmap_filter: FilterMode::Linear,
|
||||
mag_filter: FilterMode::Linear,
|
||||
min_filter: FilterMode::Linear,
|
||||
..default()
|
||||
});
|
||||
|
||||
FxaaPipeline {
|
||||
texture_bind_group,
|
||||
sampler,
|
||||
shader: load_embedded_asset!(render_world, "fxaa.wgsl"),
|
||||
}
|
||||
}
|
||||
commands.insert_resource(FxaaPipeline {
|
||||
texture_bind_group,
|
||||
sampler,
|
||||
fullscreen_shader: fullscreen_shader.clone(),
|
||||
fragment_shader: load_embedded_asset!(asset_server.as_ref(), "fxaa.wgsl"),
|
||||
});
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
@ -181,25 +179,21 @@ impl SpecializedRenderPipeline for FxaaPipeline {
|
||||
RenderPipelineDescriptor {
|
||||
label: Some("fxaa".into()),
|
||||
layout: vec![self.texture_bind_group.clone()],
|
||||
vertex: fullscreen_shader_vertex_state(),
|
||||
vertex: self.fullscreen_shader.to_vertex_state(),
|
||||
fragment: Some(FragmentState {
|
||||
shader: self.shader.clone(),
|
||||
shader: self.fragment_shader.clone(),
|
||||
shader_defs: vec![
|
||||
format!("EDGE_THRESH_{}", key.edge_threshold.get_str()).into(),
|
||||
format!("EDGE_THRESH_MIN_{}", key.edge_threshold_min.get_str()).into(),
|
||||
],
|
||||
entry_point: "fragment".into(),
|
||||
targets: vec![Some(ColorTargetState {
|
||||
format: key.texture_format,
|
||||
blend: None,
|
||||
write_mask: ColorWrites::ALL,
|
||||
})],
|
||||
..default()
|
||||
}),
|
||||
primitive: PrimitiveState::default(),
|
||||
depth_stencil: None,
|
||||
multisample: MultisampleState::default(),
|
||||
push_constant_ranges: Vec::new(),
|
||||
zero_initialize_workgroup_memory: false,
|
||||
..default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -32,7 +32,7 @@
|
||||
use bevy_app::{App, Plugin};
|
||||
#[cfg(feature = "smaa_luts")]
|
||||
use bevy_asset::load_internal_binary_asset;
|
||||
use bevy_asset::{embedded_asset, load_embedded_asset, weak_handle, Handle};
|
||||
use bevy_asset::{embedded_asset, load_embedded_asset, uuid_handle, AssetServer, Handle};
|
||||
#[cfg(not(feature = "smaa_luts"))]
|
||||
use bevy_core_pipeline::tonemapping::lut_placeholder;
|
||||
use bevy_core_pipeline::{
|
||||
@ -48,9 +48,9 @@ use bevy_ecs::{
|
||||
resource::Resource,
|
||||
schedule::IntoScheduleConfigs as _,
|
||||
system::{lifetimeless::Read, Commands, Query, Res, ResMut},
|
||||
world::{FromWorld, World},
|
||||
world::World,
|
||||
};
|
||||
use bevy_image::{BevyDefault, Image};
|
||||
use bevy_image::{BevyDefault, Image, ToExtents};
|
||||
use bevy_math::{vec4, Vec4};
|
||||
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
|
||||
use bevy_render::{
|
||||
@ -58,34 +58,33 @@ use bevy_render::{
|
||||
extract_component::{ExtractComponent, ExtractComponentPlugin},
|
||||
render_asset::RenderAssets,
|
||||
render_graph::{
|
||||
NodeRunError, RenderGraphApp as _, RenderGraphContext, ViewNode, ViewNodeRunner,
|
||||
NodeRunError, RenderGraphContext, RenderGraphExt as _, ViewNode, ViewNodeRunner,
|
||||
},
|
||||
render_resource::{
|
||||
binding_types::{sampler, texture_2d, uniform_buffer},
|
||||
AddressMode, BindGroup, BindGroupEntries, BindGroupLayout, BindGroupLayoutEntries,
|
||||
CachedRenderPipelineId, ColorTargetState, ColorWrites, CompareFunction, DepthStencilState,
|
||||
DynamicUniformBuffer, Extent3d, FilterMode, FragmentState, LoadOp, MultisampleState,
|
||||
Operations, PipelineCache, PrimitiveState, RenderPassColorAttachment,
|
||||
RenderPassDepthStencilAttachment, RenderPassDescriptor, RenderPipeline,
|
||||
RenderPipelineDescriptor, SamplerBindingType, SamplerDescriptor, Shader, ShaderDefVal,
|
||||
ShaderStages, ShaderType, SpecializedRenderPipeline, SpecializedRenderPipelines,
|
||||
StencilFaceState, StencilOperation, StencilState, StoreOp, TextureDescriptor,
|
||||
TextureDimension, TextureFormat, TextureSampleType, TextureUsages, TextureView,
|
||||
VertexState,
|
||||
DynamicUniformBuffer, FilterMode, FragmentState, LoadOp, Operations, PipelineCache,
|
||||
RenderPassColorAttachment, RenderPassDepthStencilAttachment, RenderPassDescriptor,
|
||||
RenderPipeline, RenderPipelineDescriptor, SamplerBindingType, SamplerDescriptor, Shader,
|
||||
ShaderDefVal, ShaderStages, ShaderType, SpecializedRenderPipeline,
|
||||
SpecializedRenderPipelines, StencilFaceState, StencilOperation, StencilState, StoreOp,
|
||||
TextureDescriptor, TextureDimension, TextureFormat, TextureSampleType, TextureUsages,
|
||||
TextureView, VertexState,
|
||||
},
|
||||
renderer::{RenderContext, RenderDevice, RenderQueue},
|
||||
texture::{CachedTexture, GpuImage, TextureCache},
|
||||
view::{ExtractedView, ViewTarget},
|
||||
Render, RenderApp, RenderSystems,
|
||||
Render, RenderApp, RenderStartup, RenderSystems,
|
||||
};
|
||||
use bevy_utils::prelude::default;
|
||||
|
||||
/// The handle of the area LUT, a KTX2 format texture that SMAA uses internally.
|
||||
const SMAA_AREA_LUT_TEXTURE_HANDLE: Handle<Image> =
|
||||
weak_handle!("569c4d67-c7fa-4958-b1af-0836023603c0");
|
||||
uuid_handle!("569c4d67-c7fa-4958-b1af-0836023603c0");
|
||||
/// The handle of the search LUT, a KTX2 format texture that SMAA uses internally.
|
||||
const SMAA_SEARCH_LUT_TEXTURE_HANDLE: Handle<Image> =
|
||||
weak_handle!("43b97515-252e-4c8a-b9af-f2fc528a1c27");
|
||||
uuid_handle!("43b97515-252e-4c8a-b9af-f2fc528a1c27");
|
||||
|
||||
/// Adds support for subpixel morphological antialiasing, or SMAA.
|
||||
pub struct SmaaPlugin;
|
||||
@ -347,6 +346,7 @@ impl Plugin for SmaaPlugin {
|
||||
render_app
|
||||
.init_resource::<SmaaSpecializedRenderPipelines>()
|
||||
.init_resource::<SmaaInfoUniformBuffer>()
|
||||
.add_systems(RenderStartup, init_smaa_pipelines)
|
||||
.add_systems(
|
||||
Render,
|
||||
(
|
||||
@ -375,86 +375,79 @@ impl Plugin for SmaaPlugin {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
fn finish(&self, app: &mut App) {
|
||||
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
|
||||
render_app.init_resource::<SmaaPipelines>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromWorld for SmaaPipelines {
|
||||
fn from_world(world: &mut World) -> Self {
|
||||
let render_device = world.resource::<RenderDevice>();
|
||||
|
||||
// Create the postprocess bind group layout (all passes, bind group 0).
|
||||
let postprocess_bind_group_layout = render_device.create_bind_group_layout(
|
||||
"SMAA postprocess bind group layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::FRAGMENT,
|
||||
(
|
||||
texture_2d(TextureSampleType::Float { filterable: true }),
|
||||
uniform_buffer::<SmaaInfoUniform>(true)
|
||||
.visibility(ShaderStages::VERTEX_FRAGMENT),
|
||||
),
|
||||
pub fn init_smaa_pipelines(
|
||||
mut commands: Commands,
|
||||
render_device: Res<RenderDevice>,
|
||||
asset_server: Res<AssetServer>,
|
||||
) {
|
||||
// Create the postprocess bind group layout (all passes, bind group 0).
|
||||
let postprocess_bind_group_layout = render_device.create_bind_group_layout(
|
||||
"SMAA postprocess bind group layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::FRAGMENT,
|
||||
(
|
||||
texture_2d(TextureSampleType::Float { filterable: true }),
|
||||
uniform_buffer::<SmaaInfoUniform>(true).visibility(ShaderStages::VERTEX_FRAGMENT),
|
||||
),
|
||||
);
|
||||
),
|
||||
);
|
||||
|
||||
// Create the edge detection bind group layout (pass 1, bind group 1).
|
||||
let edge_detection_bind_group_layout = render_device.create_bind_group_layout(
|
||||
"SMAA edge detection bind group layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::FRAGMENT,
|
||||
(sampler(SamplerBindingType::Filtering),),
|
||||
// Create the edge detection bind group layout (pass 1, bind group 1).
|
||||
let edge_detection_bind_group_layout = render_device.create_bind_group_layout(
|
||||
"SMAA edge detection bind group layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::FRAGMENT,
|
||||
(sampler(SamplerBindingType::Filtering),),
|
||||
),
|
||||
);
|
||||
|
||||
// Create the blending weight calculation bind group layout (pass 2, bind group 1).
|
||||
let blending_weight_calculation_bind_group_layout = render_device.create_bind_group_layout(
|
||||
"SMAA blending weight calculation bind group layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::FRAGMENT,
|
||||
(
|
||||
texture_2d(TextureSampleType::Float { filterable: true }), // edges texture
|
||||
sampler(SamplerBindingType::Filtering), // edges sampler
|
||||
texture_2d(TextureSampleType::Float { filterable: true }), // search texture
|
||||
texture_2d(TextureSampleType::Float { filterable: true }), // area texture
|
||||
),
|
||||
);
|
||||
),
|
||||
);
|
||||
|
||||
// Create the blending weight calculation bind group layout (pass 2, bind group 1).
|
||||
let blending_weight_calculation_bind_group_layout = render_device.create_bind_group_layout(
|
||||
"SMAA blending weight calculation bind group layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::FRAGMENT,
|
||||
(
|
||||
texture_2d(TextureSampleType::Float { filterable: true }), // edges texture
|
||||
sampler(SamplerBindingType::Filtering), // edges sampler
|
||||
texture_2d(TextureSampleType::Float { filterable: true }), // search texture
|
||||
texture_2d(TextureSampleType::Float { filterable: true }), // area texture
|
||||
),
|
||||
// Create the neighborhood blending bind group layout (pass 3, bind group 1).
|
||||
let neighborhood_blending_bind_group_layout = render_device.create_bind_group_layout(
|
||||
"SMAA neighborhood blending bind group layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::FRAGMENT,
|
||||
(
|
||||
texture_2d(TextureSampleType::Float { filterable: true }),
|
||||
sampler(SamplerBindingType::Filtering),
|
||||
),
|
||||
);
|
||||
),
|
||||
);
|
||||
|
||||
// Create the neighborhood blending bind group layout (pass 3, bind group 1).
|
||||
let neighborhood_blending_bind_group_layout = render_device.create_bind_group_layout(
|
||||
"SMAA neighborhood blending bind group layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::FRAGMENT,
|
||||
(
|
||||
texture_2d(TextureSampleType::Float { filterable: true }),
|
||||
sampler(SamplerBindingType::Filtering),
|
||||
),
|
||||
),
|
||||
);
|
||||
let shader = load_embedded_asset!(asset_server.as_ref(), "smaa.wgsl");
|
||||
|
||||
let shader = load_embedded_asset!(world, "smaa.wgsl");
|
||||
|
||||
SmaaPipelines {
|
||||
edge_detection: SmaaEdgeDetectionPipeline {
|
||||
postprocess_bind_group_layout: postprocess_bind_group_layout.clone(),
|
||||
edge_detection_bind_group_layout,
|
||||
shader: shader.clone(),
|
||||
},
|
||||
blending_weight_calculation: SmaaBlendingWeightCalculationPipeline {
|
||||
postprocess_bind_group_layout: postprocess_bind_group_layout.clone(),
|
||||
blending_weight_calculation_bind_group_layout,
|
||||
shader: shader.clone(),
|
||||
},
|
||||
neighborhood_blending: SmaaNeighborhoodBlendingPipeline {
|
||||
postprocess_bind_group_layout,
|
||||
neighborhood_blending_bind_group_layout,
|
||||
shader,
|
||||
},
|
||||
}
|
||||
}
|
||||
commands.insert_resource(SmaaPipelines {
|
||||
edge_detection: SmaaEdgeDetectionPipeline {
|
||||
postprocess_bind_group_layout: postprocess_bind_group_layout.clone(),
|
||||
edge_detection_bind_group_layout,
|
||||
shader: shader.clone(),
|
||||
},
|
||||
blending_weight_calculation: SmaaBlendingWeightCalculationPipeline {
|
||||
postprocess_bind_group_layout: postprocess_bind_group_layout.clone(),
|
||||
blending_weight_calculation_bind_group_layout,
|
||||
shader: shader.clone(),
|
||||
},
|
||||
neighborhood_blending: SmaaNeighborhoodBlendingPipeline {
|
||||
postprocess_bind_group_layout,
|
||||
neighborhood_blending_bind_group_layout,
|
||||
shader,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Phase 1: edge detection.
|
||||
@ -483,21 +476,19 @@ impl SpecializedRenderPipeline for SmaaEdgeDetectionPipeline {
|
||||
vertex: VertexState {
|
||||
shader: self.shader.clone(),
|
||||
shader_defs: shader_defs.clone(),
|
||||
entry_point: "edge_detection_vertex_main".into(),
|
||||
entry_point: Some("edge_detection_vertex_main".into()),
|
||||
buffers: vec![],
|
||||
},
|
||||
fragment: Some(FragmentState {
|
||||
shader: self.shader.clone(),
|
||||
shader_defs,
|
||||
entry_point: "luma_edge_detection_fragment_main".into(),
|
||||
entry_point: Some("luma_edge_detection_fragment_main".into()),
|
||||
targets: vec![Some(ColorTargetState {
|
||||
format: TextureFormat::Rg8Unorm,
|
||||
blend: None,
|
||||
write_mask: ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
push_constant_ranges: vec![],
|
||||
primitive: PrimitiveState::default(),
|
||||
depth_stencil: Some(DepthStencilState {
|
||||
format: TextureFormat::Stencil8,
|
||||
depth_write_enabled: false,
|
||||
@ -510,8 +501,7 @@ impl SpecializedRenderPipeline for SmaaEdgeDetectionPipeline {
|
||||
},
|
||||
bias: default(),
|
||||
}),
|
||||
multisample: MultisampleState::default(),
|
||||
zero_initialize_workgroup_memory: false,
|
||||
..default()
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -543,21 +533,19 @@ impl SpecializedRenderPipeline for SmaaBlendingWeightCalculationPipeline {
|
||||
vertex: VertexState {
|
||||
shader: self.shader.clone(),
|
||||
shader_defs: shader_defs.clone(),
|
||||
entry_point: "blending_weight_calculation_vertex_main".into(),
|
||||
entry_point: Some("blending_weight_calculation_vertex_main".into()),
|
||||
buffers: vec![],
|
||||
},
|
||||
fragment: Some(FragmentState {
|
||||
shader: self.shader.clone(),
|
||||
shader_defs,
|
||||
entry_point: "blending_weight_calculation_fragment_main".into(),
|
||||
entry_point: Some("blending_weight_calculation_fragment_main".into()),
|
||||
targets: vec![Some(ColorTargetState {
|
||||
format: TextureFormat::Rgba8Unorm,
|
||||
blend: None,
|
||||
write_mask: ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
push_constant_ranges: vec![],
|
||||
primitive: PrimitiveState::default(),
|
||||
depth_stencil: Some(DepthStencilState {
|
||||
format: TextureFormat::Stencil8,
|
||||
depth_write_enabled: false,
|
||||
@ -570,8 +558,7 @@ impl SpecializedRenderPipeline for SmaaBlendingWeightCalculationPipeline {
|
||||
},
|
||||
bias: default(),
|
||||
}),
|
||||
multisample: MultisampleState::default(),
|
||||
zero_initialize_workgroup_memory: false,
|
||||
..default()
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -591,24 +578,20 @@ impl SpecializedRenderPipeline for SmaaNeighborhoodBlendingPipeline {
|
||||
vertex: VertexState {
|
||||
shader: self.shader.clone(),
|
||||
shader_defs: shader_defs.clone(),
|
||||
entry_point: "neighborhood_blending_vertex_main".into(),
|
||||
entry_point: Some("neighborhood_blending_vertex_main".into()),
|
||||
buffers: vec![],
|
||||
},
|
||||
fragment: Some(FragmentState {
|
||||
shader: self.shader.clone(),
|
||||
shader_defs,
|
||||
entry_point: "neighborhood_blending_fragment_main".into(),
|
||||
entry_point: Some("neighborhood_blending_fragment_main".into()),
|
||||
targets: vec![Some(ColorTargetState {
|
||||
format: key.texture_format,
|
||||
blend: None,
|
||||
write_mask: ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
push_constant_ranges: vec![],
|
||||
primitive: PrimitiveState::default(),
|
||||
depth_stencil: None,
|
||||
multisample: MultisampleState::default(),
|
||||
zero_initialize_workgroup_memory: false,
|
||||
..default()
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -704,18 +687,12 @@ fn prepare_smaa_textures(
|
||||
continue;
|
||||
};
|
||||
|
||||
let texture_size = Extent3d {
|
||||
width: texture_size.x,
|
||||
height: texture_size.y,
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
|
||||
// Create the two-channel RG texture for phase 1 (edge detection).
|
||||
let edge_detection_color_texture = texture_cache.get(
|
||||
&render_device,
|
||||
TextureDescriptor {
|
||||
label: Some("SMAA edge detection color texture"),
|
||||
size: texture_size,
|
||||
size: texture_size.to_extents(),
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: TextureDimension::D2,
|
||||
@ -730,7 +707,7 @@ fn prepare_smaa_textures(
|
||||
&render_device,
|
||||
TextureDescriptor {
|
||||
label: Some("SMAA edge detection stencil texture"),
|
||||
size: texture_size,
|
||||
size: texture_size.to_extents(),
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: TextureDimension::D2,
|
||||
@ -746,7 +723,7 @@ fn prepare_smaa_textures(
|
||||
&render_device,
|
||||
TextureDescriptor {
|
||||
label: Some("SMAA blend texture"),
|
||||
size: texture_size,
|
||||
size: texture_size.to_extents(),
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: TextureDimension::D2,
|
||||
@ -847,7 +824,7 @@ impl ViewNode for SmaaNode {
|
||||
view_smaa_uniform_offset,
|
||||
smaa_textures,
|
||||
view_smaa_bind_groups,
|
||||
): QueryItem<'w, Self::ViewQuery>,
|
||||
): QueryItem<'w, '_, Self::ViewQuery>,
|
||||
world: &'w World,
|
||||
) -> Result<(), NodeRunError> {
|
||||
let pipeline_cache = world.resource::<PipelineCache>();
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
use bevy_app::{App, Plugin};
|
||||
use bevy_asset::{embedded_asset, load_embedded_asset, Handle};
|
||||
use bevy_asset::{embedded_asset, load_embedded_asset, AssetServer, Handle};
|
||||
use bevy_core_pipeline::{
|
||||
core_3d::graph::{Core3d, Node3d},
|
||||
fullscreen_vertex_shader::fullscreen_shader_vertex_state,
|
||||
prelude::Camera3d,
|
||||
prepass::{DepthPrepass, MotionVectorPrepass, ViewPrepassTextures},
|
||||
FullscreenShader,
|
||||
};
|
||||
use bevy_diagnostic::FrameCount;
|
||||
use bevy_ecs::{
|
||||
@ -13,31 +13,32 @@ use bevy_ecs::{
|
||||
resource::Resource,
|
||||
schedule::IntoScheduleConfigs,
|
||||
system::{Commands, Query, Res, ResMut},
|
||||
world::{FromWorld, World},
|
||||
world::World,
|
||||
};
|
||||
use bevy_image::BevyDefault as _;
|
||||
use bevy_image::{BevyDefault as _, ToExtents};
|
||||
use bevy_math::vec2;
|
||||
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
|
||||
use bevy_render::{
|
||||
camera::{ExtractedCamera, MipBias, TemporalJitter},
|
||||
prelude::{Camera, Projection},
|
||||
render_graph::{NodeRunError, RenderGraphApp, RenderGraphContext, ViewNode, ViewNodeRunner},
|
||||
render_graph::{NodeRunError, RenderGraphContext, RenderGraphExt, ViewNode, ViewNodeRunner},
|
||||
render_resource::{
|
||||
binding_types::{sampler, texture_2d, texture_depth_2d},
|
||||
BindGroupEntries, BindGroupLayout, BindGroupLayoutEntries, CachedRenderPipelineId,
|
||||
ColorTargetState, ColorWrites, Extent3d, FilterMode, FragmentState, MultisampleState,
|
||||
Operations, PipelineCache, PrimitiveState, RenderPassColorAttachment, RenderPassDescriptor,
|
||||
RenderPipelineDescriptor, Sampler, SamplerBindingType, SamplerDescriptor, Shader,
|
||||
ShaderStages, SpecializedRenderPipeline, SpecializedRenderPipelines, TextureDescriptor,
|
||||
TextureDimension, TextureFormat, TextureSampleType, TextureUsages,
|
||||
ColorTargetState, ColorWrites, FilterMode, FragmentState, Operations, PipelineCache,
|
||||
RenderPassColorAttachment, RenderPassDescriptor, RenderPipelineDescriptor, Sampler,
|
||||
SamplerBindingType, SamplerDescriptor, Shader, ShaderStages, SpecializedRenderPipeline,
|
||||
SpecializedRenderPipelines, TextureDescriptor, TextureDimension, TextureFormat,
|
||||
TextureSampleType, TextureUsages,
|
||||
},
|
||||
renderer::{RenderContext, RenderDevice},
|
||||
sync_component::SyncComponentPlugin,
|
||||
sync_world::RenderEntity,
|
||||
texture::{CachedTexture, TextureCache},
|
||||
view::{ExtractedView, Msaa, ViewTarget},
|
||||
ExtractSchedule, MainWorld, Render, RenderApp, RenderSystems,
|
||||
ExtractSchedule, MainWorld, Render, RenderApp, RenderStartup, RenderSystems,
|
||||
};
|
||||
use bevy_utils::default;
|
||||
use tracing::warn;
|
||||
|
||||
/// Plugin for temporal anti-aliasing.
|
||||
@ -58,6 +59,7 @@ impl Plugin for TemporalAntiAliasPlugin {
|
||||
};
|
||||
render_app
|
||||
.init_resource::<SpecializedRenderPipelines<TaaPipeline>>()
|
||||
.add_systems(RenderStartup, init_taa_pipeline)
|
||||
.add_systems(ExtractSchedule, extract_taa_settings)
|
||||
.add_systems(
|
||||
Render,
|
||||
@ -79,14 +81,6 @@ impl Plugin for TemporalAntiAliasPlugin {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
fn finish(&self, app: &mut App) {
|
||||
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
|
||||
return;
|
||||
};
|
||||
|
||||
render_app.init_resource::<TaaPipeline>();
|
||||
}
|
||||
}
|
||||
|
||||
/// Component to apply temporal anti-aliasing to a 3D perspective camera.
|
||||
@ -238,54 +232,57 @@ struct TaaPipeline {
|
||||
taa_bind_group_layout: BindGroupLayout,
|
||||
nearest_sampler: Sampler,
|
||||
linear_sampler: Sampler,
|
||||
shader: Handle<Shader>,
|
||||
fullscreen_shader: FullscreenShader,
|
||||
fragment_shader: Handle<Shader>,
|
||||
}
|
||||
|
||||
impl FromWorld for TaaPipeline {
|
||||
fn from_world(world: &mut World) -> Self {
|
||||
let render_device = world.resource::<RenderDevice>();
|
||||
fn init_taa_pipeline(
|
||||
mut commands: Commands,
|
||||
render_device: Res<RenderDevice>,
|
||||
fullscreen_shader: Res<FullscreenShader>,
|
||||
asset_server: Res<AssetServer>,
|
||||
) {
|
||||
let nearest_sampler = render_device.create_sampler(&SamplerDescriptor {
|
||||
label: Some("taa_nearest_sampler"),
|
||||
mag_filter: FilterMode::Nearest,
|
||||
min_filter: FilterMode::Nearest,
|
||||
..SamplerDescriptor::default()
|
||||
});
|
||||
let linear_sampler = render_device.create_sampler(&SamplerDescriptor {
|
||||
label: Some("taa_linear_sampler"),
|
||||
mag_filter: FilterMode::Linear,
|
||||
min_filter: FilterMode::Linear,
|
||||
..SamplerDescriptor::default()
|
||||
});
|
||||
|
||||
let nearest_sampler = render_device.create_sampler(&SamplerDescriptor {
|
||||
label: Some("taa_nearest_sampler"),
|
||||
mag_filter: FilterMode::Nearest,
|
||||
min_filter: FilterMode::Nearest,
|
||||
..SamplerDescriptor::default()
|
||||
});
|
||||
let linear_sampler = render_device.create_sampler(&SamplerDescriptor {
|
||||
label: Some("taa_linear_sampler"),
|
||||
mag_filter: FilterMode::Linear,
|
||||
min_filter: FilterMode::Linear,
|
||||
..SamplerDescriptor::default()
|
||||
});
|
||||
|
||||
let taa_bind_group_layout = render_device.create_bind_group_layout(
|
||||
"taa_bind_group_layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::FRAGMENT,
|
||||
(
|
||||
// View target (read)
|
||||
texture_2d(TextureSampleType::Float { filterable: true }),
|
||||
// TAA History (read)
|
||||
texture_2d(TextureSampleType::Float { filterable: true }),
|
||||
// Motion Vectors
|
||||
texture_2d(TextureSampleType::Float { filterable: true }),
|
||||
// Depth
|
||||
texture_depth_2d(),
|
||||
// Nearest sampler
|
||||
sampler(SamplerBindingType::NonFiltering),
|
||||
// Linear sampler
|
||||
sampler(SamplerBindingType::Filtering),
|
||||
),
|
||||
let taa_bind_group_layout = render_device.create_bind_group_layout(
|
||||
"taa_bind_group_layout",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::FRAGMENT,
|
||||
(
|
||||
// View target (read)
|
||||
texture_2d(TextureSampleType::Float { filterable: true }),
|
||||
// TAA History (read)
|
||||
texture_2d(TextureSampleType::Float { filterable: true }),
|
||||
// Motion Vectors
|
||||
texture_2d(TextureSampleType::Float { filterable: true }),
|
||||
// Depth
|
||||
texture_depth_2d(),
|
||||
// Nearest sampler
|
||||
sampler(SamplerBindingType::NonFiltering),
|
||||
// Linear sampler
|
||||
sampler(SamplerBindingType::Filtering),
|
||||
),
|
||||
);
|
||||
),
|
||||
);
|
||||
|
||||
TaaPipeline {
|
||||
taa_bind_group_layout,
|
||||
nearest_sampler,
|
||||
linear_sampler,
|
||||
shader: load_embedded_asset!(world, "taa.wgsl"),
|
||||
}
|
||||
}
|
||||
commands.insert_resource(TaaPipeline {
|
||||
taa_bind_group_layout,
|
||||
nearest_sampler,
|
||||
linear_sampler,
|
||||
fullscreen_shader: fullscreen_shader.clone(),
|
||||
fragment_shader: load_embedded_asset!(asset_server.as_ref(), "taa.wgsl"),
|
||||
});
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Hash, Clone)]
|
||||
@ -314,11 +311,10 @@ impl SpecializedRenderPipeline for TaaPipeline {
|
||||
RenderPipelineDescriptor {
|
||||
label: Some("taa_pipeline".into()),
|
||||
layout: vec![self.taa_bind_group_layout.clone()],
|
||||
vertex: fullscreen_shader_vertex_state(),
|
||||
vertex: self.fullscreen_shader.to_vertex_state(),
|
||||
fragment: Some(FragmentState {
|
||||
shader: self.shader.clone(),
|
||||
shader: self.fragment_shader.clone(),
|
||||
shader_defs,
|
||||
entry_point: "taa".into(),
|
||||
targets: vec![
|
||||
Some(ColorTargetState {
|
||||
format,
|
||||
@ -331,12 +327,9 @@ impl SpecializedRenderPipeline for TaaPipeline {
|
||||
write_mask: ColorWrites::ALL,
|
||||
}),
|
||||
],
|
||||
..default()
|
||||
}),
|
||||
primitive: PrimitiveState::default(),
|
||||
depth_stencil: None,
|
||||
multisample: MultisampleState::default(),
|
||||
push_constant_ranges: Vec::new(),
|
||||
zero_initialize_workgroup_memory: false,
|
||||
..default()
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -418,11 +411,7 @@ fn prepare_taa_history_textures(
|
||||
if let Some(physical_target_size) = camera.physical_target_size {
|
||||
let mut texture_descriptor = TextureDescriptor {
|
||||
label: None,
|
||||
size: Extent3d {
|
||||
depth_or_array_layers: 1,
|
||||
width: physical_target_size.x,
|
||||
height: physical_target_size.y,
|
||||
},
|
||||
size: physical_target_size.to_extents(),
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: TextureDimension::D2,
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "bevy_app"
|
||||
version = "0.16.0-dev"
|
||||
version = "0.17.0-dev"
|
||||
edition = "2024"
|
||||
description = "Provides core App functionality for Bevy Engine"
|
||||
homepage = "https://bevy.org"
|
||||
@ -79,12 +79,12 @@ hotpatching = [
|
||||
|
||||
[dependencies]
|
||||
# bevy
|
||||
bevy_derive = { path = "../bevy_derive", version = "0.16.0-dev" }
|
||||
bevy_ecs = { path = "../bevy_ecs", version = "0.16.0-dev", default-features = false }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.16.0-dev", default-features = false, optional = true }
|
||||
bevy_utils = { path = "../bevy_utils", version = "0.16.0-dev", default-features = false }
|
||||
bevy_tasks = { path = "../bevy_tasks", version = "0.16.0-dev", default-features = false }
|
||||
bevy_platform = { path = "../bevy_platform", version = "0.16.0-dev", default-features = false }
|
||||
bevy_derive = { path = "../bevy_derive", version = "0.17.0-dev" }
|
||||
bevy_ecs = { path = "../bevy_ecs", version = "0.17.0-dev", default-features = false }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.17.0-dev", default-features = false, optional = true }
|
||||
bevy_utils = { path = "../bevy_utils", version = "0.17.0-dev", default-features = false }
|
||||
bevy_tasks = { path = "../bevy_tasks", version = "0.17.0-dev", default-features = false }
|
||||
bevy_platform = { path = "../bevy_platform", version = "0.17.0-dev", default-features = false }
|
||||
|
||||
# other
|
||||
downcast-rs = { version = "2", default-features = false }
|
||||
|
||||
@ -344,7 +344,7 @@ impl App {
|
||||
self
|
||||
}
|
||||
|
||||
/// Initializes `T` event handling by inserting an event queue resource ([`Events::<T>`])
|
||||
/// Initializes [`BufferedEvent`] handling for `T` by inserting an event queue resource ([`Events::<T>`])
|
||||
/// and scheduling an [`event_update_system`] in [`First`].
|
||||
///
|
||||
/// See [`Events`] for information on how to define events.
|
||||
@ -355,7 +355,7 @@ impl App {
|
||||
/// # use bevy_app::prelude::*;
|
||||
/// # use bevy_ecs::prelude::*;
|
||||
/// #
|
||||
/// # #[derive(Event)]
|
||||
/// # #[derive(Event, BufferedEvent)]
|
||||
/// # struct MyEvent;
|
||||
/// # let mut app = App::new();
|
||||
/// #
|
||||
@ -363,7 +363,7 @@ impl App {
|
||||
/// ```
|
||||
pub fn add_event<T>(&mut self) -> &mut Self
|
||||
where
|
||||
T: Event,
|
||||
T: BufferedEvent,
|
||||
{
|
||||
self.main_mut().add_event::<T>();
|
||||
self
|
||||
@ -1325,7 +1325,7 @@ impl App {
|
||||
/// # friends_allowed: bool,
|
||||
/// # };
|
||||
/// #
|
||||
/// # #[derive(Event)]
|
||||
/// # #[derive(Event, EntityEvent)]
|
||||
/// # struct Invite;
|
||||
/// #
|
||||
/// # #[derive(Component)]
|
||||
@ -1407,7 +1407,7 @@ fn run_once(mut app: App) -> AppExit {
|
||||
app.should_exit().unwrap_or(AppExit::Success)
|
||||
}
|
||||
|
||||
/// An event that indicates the [`App`] should exit. If one or more of these are present at the end of an update,
|
||||
/// A [`BufferedEvent`] that indicates the [`App`] should exit. If one or more of these are present at the end of an update,
|
||||
/// the [runner](App::set_runner) will end and ([maybe](App::run)) return control to the caller.
|
||||
///
|
||||
/// This event can be used to detect when an exit is requested. Make sure that systems listening
|
||||
@ -1417,7 +1417,7 @@ fn run_once(mut app: App) -> AppExit {
|
||||
/// This type is roughly meant to map to a standard definition of a process exit code (0 means success, not 0 means error). Due to portability concerns
|
||||
/// (see [`ExitCode`](https://doc.rust-lang.org/std/process/struct.ExitCode.html) and [`process::exit`](https://doc.rust-lang.org/std/process/fn.exit.html#))
|
||||
/// we only allow error codes between 1 and [255](u8::MAX).
|
||||
#[derive(Event, Debug, Clone, Default, PartialEq, Eq)]
|
||||
#[derive(Event, BufferedEvent, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub enum AppExit {
|
||||
/// [`App`] exited without any problems.
|
||||
#[default]
|
||||
@ -1485,7 +1485,7 @@ mod tests {
|
||||
change_detection::{DetectChanges, ResMut},
|
||||
component::Component,
|
||||
entity::Entity,
|
||||
event::{Event, EventWriter, Events},
|
||||
event::{BufferedEvent, Event, EventWriter, Events},
|
||||
lifecycle::RemovedComponents,
|
||||
query::With,
|
||||
resource::Resource,
|
||||
@ -1582,7 +1582,7 @@ mod tests {
|
||||
app.add_systems(EnterMainMenu, (foo, bar));
|
||||
|
||||
app.world_mut().run_schedule(EnterMainMenu);
|
||||
assert_eq!(app.world().entities().len(), 2);
|
||||
assert_eq!(app.world().entity_count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -1851,7 +1851,7 @@ mod tests {
|
||||
}
|
||||
#[test]
|
||||
fn events_should_be_updated_once_per_update() {
|
||||
#[derive(Event, Clone)]
|
||||
#[derive(Event, BufferedEvent, Clone)]
|
||||
struct TestEvent;
|
||||
|
||||
let mut app = App::new();
|
||||
|
||||
@ -88,6 +88,7 @@ impl<C: Component + Clone + PartialEq> core::fmt::Debug for PropagateSet<C> {
|
||||
}
|
||||
|
||||
impl<C: Component + Clone + PartialEq> Eq for PropagateSet<C> {}
|
||||
|
||||
impl<C: Component + Clone + PartialEq> core::hash::Hash for PropagateSet<C> {
|
||||
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self._p.hash(state);
|
||||
|
||||
@ -338,7 +338,7 @@ impl SubApp {
|
||||
/// See [`App::add_event`].
|
||||
pub fn add_event<T>(&mut self) -> &mut Self
|
||||
where
|
||||
T: Event,
|
||||
T: BufferedEvent,
|
||||
{
|
||||
if !self.world.contains_resource::<Events<T>>() {
|
||||
EventRegistry::register_event::<T>(self.world_mut());
|
||||
|
||||
@ -160,7 +160,7 @@ impl TaskPoolOptions {
|
||||
pub fn create_default_pools(&self) {
|
||||
let total_threads = bevy_tasks::available_parallelism()
|
||||
.clamp(self.min_total_threads, self.max_total_threads);
|
||||
trace!("Assigning {} cores to default task pools", total_threads);
|
||||
trace!("Assigning {total_threads} cores to default task pools");
|
||||
|
||||
let mut remaining_threads = total_threads;
|
||||
|
||||
@ -170,7 +170,7 @@ impl TaskPoolOptions {
|
||||
.io
|
||||
.get_number_of_threads(remaining_threads, total_threads);
|
||||
|
||||
trace!("IO Threads: {}", io_threads);
|
||||
trace!("IO Threads: {io_threads}");
|
||||
remaining_threads = remaining_threads.saturating_sub(io_threads);
|
||||
|
||||
IoTaskPool::get_or_init(|| {
|
||||
@ -200,7 +200,7 @@ impl TaskPoolOptions {
|
||||
.async_compute
|
||||
.get_number_of_threads(remaining_threads, total_threads);
|
||||
|
||||
trace!("Async Compute Threads: {}", async_compute_threads);
|
||||
trace!("Async Compute Threads: {async_compute_threads}");
|
||||
remaining_threads = remaining_threads.saturating_sub(async_compute_threads);
|
||||
|
||||
AsyncComputeTaskPool::get_or_init(|| {
|
||||
@ -231,7 +231,7 @@ impl TaskPoolOptions {
|
||||
.compute
|
||||
.get_number_of_threads(remaining_threads, total_threads);
|
||||
|
||||
trace!("Compute Threads: {}", compute_threads);
|
||||
trace!("Compute Threads: {compute_threads}");
|
||||
|
||||
ComputeTaskPool::get_or_init(|| {
|
||||
let builder = TaskPoolBuilder::default()
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "bevy_asset"
|
||||
version = "0.16.0-dev"
|
||||
version = "0.17.0-dev"
|
||||
edition = "2024"
|
||||
description = "Provides asset functionality for Bevy Engine"
|
||||
homepage = "https://bevy.org"
|
||||
@ -19,19 +19,19 @@ watch = []
|
||||
trace = []
|
||||
|
||||
[dependencies]
|
||||
bevy_app = { path = "../bevy_app", version = "0.16.0-dev", default-features = false, features = [
|
||||
bevy_app = { path = "../bevy_app", version = "0.17.0-dev", default-features = false, features = [
|
||||
"bevy_reflect",
|
||||
] }
|
||||
bevy_asset_macros = { path = "macros", version = "0.16.0-dev" }
|
||||
bevy_ecs = { path = "../bevy_ecs", version = "0.16.0-dev", default-features = false }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.16.0-dev", default-features = false, features = [
|
||||
bevy_asset_macros = { path = "macros", version = "0.17.0-dev" }
|
||||
bevy_ecs = { path = "../bevy_ecs", version = "0.17.0-dev", default-features = false }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.17.0-dev", default-features = false, features = [
|
||||
"uuid",
|
||||
] }
|
||||
bevy_tasks = { path = "../bevy_tasks", version = "0.16.0-dev", default-features = false, features = [
|
||||
bevy_tasks = { path = "../bevy_tasks", version = "0.17.0-dev", default-features = false, features = [
|
||||
"async_executor",
|
||||
] }
|
||||
bevy_utils = { path = "../bevy_utils", version = "0.16.0-dev", default-features = false }
|
||||
bevy_platform = { path = "../bevy_platform", version = "0.16.0-dev", default-features = false, features = [
|
||||
bevy_utils = { path = "../bevy_utils", version = "0.17.0-dev", default-features = false }
|
||||
bevy_platform = { path = "../bevy_platform", version = "0.17.0-dev", default-features = false, features = [
|
||||
"std",
|
||||
] }
|
||||
|
||||
@ -54,10 +54,10 @@ parking_lot = { version = "0.12", default-features = false, features = [
|
||||
"arc_lock",
|
||||
"send_guard",
|
||||
] }
|
||||
ron = { version = "0.8", default-features = false }
|
||||
ron = { version = "0.10", default-features = false }
|
||||
serde = { version = "1", default-features = false, features = ["derive"] }
|
||||
thiserror = { version = "2", default-features = false }
|
||||
derive_more = { version = "1", default-features = false, features = ["from"] }
|
||||
derive_more = { version = "2", default-features = false, features = ["from"] }
|
||||
uuid = { version = "1.13.1", default-features = false, features = [
|
||||
"v4",
|
||||
"serde",
|
||||
@ -65,7 +65,7 @@ uuid = { version = "1.13.1", default-features = false, features = [
|
||||
tracing = { version = "0.1", default-features = false }
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
bevy_window = { path = "../bevy_window", version = "0.16.0-dev" }
|
||||
bevy_window = { path = "../bevy_window", version = "0.17.0-dev" }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
# TODO: Assuming all wasm builds are for the browser. Require `no_std` support to break assumption.
|
||||
@ -78,13 +78,13 @@ web-sys = { version = "0.3", features = [
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
uuid = { version = "1.13.1", default-features = false, features = ["js"] }
|
||||
bevy_app = { path = "../bevy_app", version = "0.16.0-dev", default-features = false, features = [
|
||||
bevy_app = { path = "../bevy_app", version = "0.17.0-dev", default-features = false, features = [
|
||||
"web",
|
||||
] }
|
||||
bevy_tasks = { path = "../bevy_tasks", version = "0.16.0-dev", default-features = false, features = [
|
||||
bevy_tasks = { path = "../bevy_tasks", version = "0.17.0-dev", default-features = false, features = [
|
||||
"web",
|
||||
] }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.16.0-dev", default-features = false, features = [
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.17.0-dev", default-features = false, features = [
|
||||
"web",
|
||||
] }
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "bevy_asset_macros"
|
||||
version = "0.16.0-dev"
|
||||
version = "0.17.0-dev"
|
||||
edition = "2024"
|
||||
description = "Derive implementations for bevy_asset"
|
||||
homepage = "https://bevy.org"
|
||||
@ -12,7 +12,7 @@ keywords = ["bevy"]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
bevy_macro_utils = { path = "../../bevy_macro_utils", version = "0.16.0-dev" }
|
||||
bevy_macro_utils = { path = "../../bevy_macro_utils", version = "0.17.0-dev" }
|
||||
|
||||
syn = "2.0"
|
||||
proc-macro2 = "1.0"
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
#![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")]
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
|
||||
//! Macros for deriving asset traits.
|
||||
|
||||
use bevy_macro_utils::BevyManifest;
|
||||
use proc_macro::{Span, TokenStream};
|
||||
use quote::{format_ident, quote};
|
||||
@ -12,6 +13,7 @@ pub(crate) fn bevy_asset_path() -> Path {
|
||||
|
||||
const DEPENDENCY_ATTRIBUTE: &str = "dependency";
|
||||
|
||||
/// Implement the `Asset` trait.
|
||||
#[proc_macro_derive(Asset, attributes(dependency))]
|
||||
pub fn derive_asset(input: TokenStream) -> TokenStream {
|
||||
let ast = parse_macro_input!(input as DeriveInput);
|
||||
@ -30,6 +32,7 @@ pub fn derive_asset(input: TokenStream) -> TokenStream {
|
||||
})
|
||||
}
|
||||
|
||||
/// Implement the `VisitAssetDependencies` trait.
|
||||
#[proc_macro_derive(VisitAssetDependencies, attributes(dependency))]
|
||||
pub fn derive_asset_dependency_visitor(input: TokenStream) -> TokenStream {
|
||||
let ast = parse_macro_input!(input as DeriveInput);
|
||||
|
||||
@ -158,9 +158,9 @@ unsafe impl<A: AsAssetId> WorldQuery for AssetChanged<A> {
|
||||
fetch
|
||||
}
|
||||
|
||||
unsafe fn init_fetch<'w>(
|
||||
unsafe fn init_fetch<'w, 's>(
|
||||
world: UnsafeWorldCell<'w>,
|
||||
state: &Self::State,
|
||||
state: &'s Self::State,
|
||||
last_run: Tick,
|
||||
this_run: Tick,
|
||||
) -> Self::Fetch<'w> {
|
||||
@ -201,9 +201,9 @@ unsafe impl<A: AsAssetId> WorldQuery for AssetChanged<A> {
|
||||
|
||||
const IS_DENSE: bool = <&A>::IS_DENSE;
|
||||
|
||||
unsafe fn set_archetype<'w>(
|
||||
unsafe fn set_archetype<'w, 's>(
|
||||
fetch: &mut Self::Fetch<'w>,
|
||||
state: &Self::State,
|
||||
state: &'s Self::State,
|
||||
archetype: &'w Archetype,
|
||||
table: &'w Table,
|
||||
) {
|
||||
@ -215,7 +215,11 @@ unsafe impl<A: AsAssetId> WorldQuery for AssetChanged<A> {
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn set_table<'w>(fetch: &mut Self::Fetch<'w>, state: &Self::State, table: &'w Table) {
|
||||
unsafe fn set_table<'w, 's>(
|
||||
fetch: &mut Self::Fetch<'w>,
|
||||
state: &Self::State,
|
||||
table: &'w Table,
|
||||
) {
|
||||
if let Some(inner) = &mut fetch.inner {
|
||||
// SAFETY: We delegate to the inner `set_table` for `A`
|
||||
unsafe {
|
||||
@ -265,6 +269,7 @@ unsafe impl<A: AsAssetId> QueryFilter for AssetChanged<A> {
|
||||
|
||||
#[inline]
|
||||
unsafe fn filter_fetch(
|
||||
state: &Self::State,
|
||||
fetch: &mut Self::Fetch<'_>,
|
||||
entity: Entity,
|
||||
table_row: TableRow,
|
||||
@ -272,7 +277,7 @@ unsafe impl<A: AsAssetId> QueryFilter for AssetChanged<A> {
|
||||
fetch.inner.as_mut().is_some_and(|inner| {
|
||||
// SAFETY: We delegate to the inner `fetch` for `A`
|
||||
unsafe {
|
||||
let handle = <&A>::fetch(inner, entity, table_row);
|
||||
let handle = <&A>::fetch(&state.asset_id, inner, entity, table_row);
|
||||
fetch.check.has_changed(handle)
|
||||
}
|
||||
})
|
||||
|
||||
@ -20,6 +20,7 @@ pub trait DirectAssetAccessExt {
|
||||
settings: impl Fn(&mut S) + Send + Sync + 'static,
|
||||
) -> Handle<A>;
|
||||
}
|
||||
|
||||
impl DirectAssetAccessExt for World {
|
||||
/// Insert an asset similarly to [`Assets::add`].
|
||||
///
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
use crate::{Asset, AssetId, AssetLoadError, AssetPath, UntypedAssetId};
|
||||
use bevy_ecs::event::Event;
|
||||
use bevy_ecs::event::{BufferedEvent, Event};
|
||||
use bevy_reflect::Reflect;
|
||||
use core::fmt::Debug;
|
||||
|
||||
/// An event emitted when a specific [`Asset`] fails to load.
|
||||
/// A [`BufferedEvent`] emitted when a specific [`Asset`] fails to load.
|
||||
///
|
||||
/// For an untyped equivalent, see [`UntypedAssetLoadFailedEvent`].
|
||||
#[derive(Event, Clone, Debug)]
|
||||
#[derive(Event, BufferedEvent, Clone, Debug)]
|
||||
pub struct AssetLoadFailedEvent<A: Asset> {
|
||||
/// The stable identifier of the asset that failed to load.
|
||||
pub id: AssetId<A>,
|
||||
@ -24,7 +24,7 @@ impl<A: Asset> AssetLoadFailedEvent<A> {
|
||||
}
|
||||
|
||||
/// An untyped version of [`AssetLoadFailedEvent`].
|
||||
#[derive(Event, Clone, Debug)]
|
||||
#[derive(Event, BufferedEvent, Clone, Debug)]
|
||||
pub struct UntypedAssetLoadFailedEvent {
|
||||
/// The stable identifier of the asset that failed to load.
|
||||
pub id: UntypedAssetId,
|
||||
@ -44,9 +44,9 @@ impl<A: Asset> From<&AssetLoadFailedEvent<A>> for UntypedAssetLoadFailedEvent {
|
||||
}
|
||||
}
|
||||
|
||||
/// Events that occur for a specific loaded [`Asset`], such as "value changed" events and "dependency" events.
|
||||
/// [`BufferedEvent`]s that occur for a specific loaded [`Asset`], such as "value changed" events and "dependency" events.
|
||||
#[expect(missing_docs, reason = "Documenting the id fields is unhelpful.")]
|
||||
#[derive(Event, Reflect)]
|
||||
#[derive(Event, BufferedEvent, Reflect)]
|
||||
pub enum AssetEvent<A: Asset> {
|
||||
/// Emitted whenever an [`Asset`] is added.
|
||||
Added { id: AssetId<A> },
|
||||
|
||||
@ -7,10 +7,12 @@ use bevy_reflect::{std_traits::ReflectDefault, Reflect, TypePath};
|
||||
use core::{
|
||||
any::TypeId,
|
||||
hash::{Hash, Hasher},
|
||||
marker::PhantomData,
|
||||
};
|
||||
use crossbeam_channel::{Receiver, Sender};
|
||||
use disqualified::ShortName;
|
||||
use thiserror::Error;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Provides [`Handle`] and [`UntypedHandle`] _for a specific asset type_.
|
||||
/// This should _only_ be used for one specific asset type.
|
||||
@ -117,7 +119,7 @@ impl core::fmt::Debug for StrongHandle {
|
||||
/// avoiding the need to store multiple copies of the same data.
|
||||
///
|
||||
/// If a [`Handle`] is [`Handle::Strong`], the [`Asset`] will be kept
|
||||
/// alive until the [`Handle`] is dropped. If a [`Handle`] is [`Handle::Weak`], it does not necessarily reference a live [`Asset`],
|
||||
/// alive until the [`Handle`] is dropped. If a [`Handle`] is [`Handle::Uuid`], it does not necessarily reference a live [`Asset`],
|
||||
/// nor will it keep assets alive.
|
||||
///
|
||||
/// Modifying a *handle* will change which existing asset is referenced, but modifying the *asset*
|
||||
@ -133,16 +135,16 @@ pub enum Handle<A: Asset> {
|
||||
/// A "strong" reference to a live (or loading) [`Asset`]. If a [`Handle`] is [`Handle::Strong`], the [`Asset`] will be kept
|
||||
/// alive until the [`Handle`] is dropped. Strong handles also provide access to additional asset metadata.
|
||||
Strong(Arc<StrongHandle>),
|
||||
/// A "weak" reference to an [`Asset`]. If a [`Handle`] is [`Handle::Weak`], it does not necessarily reference a live [`Asset`],
|
||||
/// nor will it keep assets alive.
|
||||
Weak(AssetId<A>),
|
||||
/// A reference to an [`Asset`] using a stable-across-runs / const identifier. Dropping this
|
||||
/// handle will not result in the asset being dropped.
|
||||
Uuid(Uuid, #[reflect(ignore, clone)] PhantomData<fn() -> A>),
|
||||
}
|
||||
|
||||
impl<T: Asset> Clone for Handle<T> {
|
||||
fn clone(&self) -> Self {
|
||||
match self {
|
||||
Handle::Strong(handle) => Handle::Strong(handle.clone()),
|
||||
Handle::Weak(id) => Handle::Weak(*id),
|
||||
Handle::Uuid(uuid, ..) => Handle::Uuid(*uuid, PhantomData),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -153,7 +155,7 @@ impl<A: Asset> Handle<A> {
|
||||
pub fn id(&self) -> AssetId<A> {
|
||||
match self {
|
||||
Handle::Strong(handle) => handle.id.typed_unchecked(),
|
||||
Handle::Weak(id) => *id,
|
||||
Handle::Uuid(uuid, ..) => AssetId::Uuid { uuid: *uuid },
|
||||
}
|
||||
}
|
||||
|
||||
@ -162,14 +164,14 @@ impl<A: Asset> Handle<A> {
|
||||
pub fn path(&self) -> Option<&AssetPath<'static>> {
|
||||
match self {
|
||||
Handle::Strong(handle) => handle.path.as_ref(),
|
||||
Handle::Weak(_) => None,
|
||||
Handle::Uuid(..) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if this is a weak handle.
|
||||
/// Returns `true` if this is a uuid handle.
|
||||
#[inline]
|
||||
pub fn is_weak(&self) -> bool {
|
||||
matches!(self, Handle::Weak(_))
|
||||
pub fn is_uuid(&self) -> bool {
|
||||
matches!(self, Handle::Uuid(..))
|
||||
}
|
||||
|
||||
/// Returns `true` if this is a strong handle.
|
||||
@ -178,18 +180,9 @@ impl<A: Asset> Handle<A> {
|
||||
matches!(self, Handle::Strong(_))
|
||||
}
|
||||
|
||||
/// Creates a [`Handle::Weak`] clone of this [`Handle`], which will not keep the referenced [`Asset`] alive.
|
||||
#[inline]
|
||||
pub fn clone_weak(&self) -> Self {
|
||||
match self {
|
||||
Handle::Strong(handle) => Handle::Weak(handle.id.typed_unchecked::<A>()),
|
||||
Handle::Weak(id) => Handle::Weak(*id),
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this [`Handle`] to an "untyped" / "generic-less" [`UntypedHandle`], which stores the [`Asset`] type information
|
||||
/// _inside_ [`UntypedHandle`]. This will return [`UntypedHandle::Strong`] for [`Handle::Strong`] and [`UntypedHandle::Weak`] for
|
||||
/// [`Handle::Weak`].
|
||||
/// _inside_ [`UntypedHandle`]. This will return [`UntypedHandle::Strong`] for [`Handle::Strong`] and [`UntypedHandle::Uuid`] for
|
||||
/// [`Handle::Uuid`].
|
||||
#[inline]
|
||||
pub fn untyped(self) -> UntypedHandle {
|
||||
self.into()
|
||||
@ -198,7 +191,7 @@ impl<A: Asset> Handle<A> {
|
||||
|
||||
impl<A: Asset> Default for Handle<A> {
|
||||
fn default() -> Self {
|
||||
Handle::Weak(AssetId::default())
|
||||
Handle::Uuid(AssetId::<A>::DEFAULT_UUID, PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
@ -214,7 +207,7 @@ impl<A: Asset> core::fmt::Debug for Handle<A> {
|
||||
handle.path
|
||||
)
|
||||
}
|
||||
Handle::Weak(id) => write!(f, "WeakHandle<{name}>({:?})", id.internal()),
|
||||
Handle::Uuid(uuid, ..) => write!(f, "UuidHandle<{name}>({uuid:?})"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -284,8 +277,13 @@ impl<A: Asset> From<&mut Handle<A>> for UntypedAssetId {
|
||||
pub enum UntypedHandle {
|
||||
/// A strong handle, which will keep the referenced [`Asset`] alive until all strong handles are dropped.
|
||||
Strong(Arc<StrongHandle>),
|
||||
/// A weak handle, which does not keep the referenced [`Asset`] alive.
|
||||
Weak(UntypedAssetId),
|
||||
/// A UUID handle, which does not keep the referenced [`Asset`] alive.
|
||||
Uuid {
|
||||
/// An identifier that records the underlying asset type.
|
||||
type_id: TypeId,
|
||||
/// The UUID provided during asset registration.
|
||||
uuid: Uuid,
|
||||
},
|
||||
}
|
||||
|
||||
impl UntypedHandle {
|
||||
@ -294,7 +292,10 @@ impl UntypedHandle {
|
||||
pub fn id(&self) -> UntypedAssetId {
|
||||
match self {
|
||||
UntypedHandle::Strong(handle) => handle.id,
|
||||
UntypedHandle::Weak(id) => *id,
|
||||
UntypedHandle::Uuid { type_id, uuid } => UntypedAssetId::Uuid {
|
||||
uuid: *uuid,
|
||||
type_id: *type_id,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@ -303,16 +304,7 @@ impl UntypedHandle {
|
||||
pub fn path(&self) -> Option<&AssetPath<'static>> {
|
||||
match self {
|
||||
UntypedHandle::Strong(handle) => handle.path.as_ref(),
|
||||
UntypedHandle::Weak(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an [`UntypedHandle::Weak`] clone of this [`UntypedHandle`], which will not keep the referenced [`Asset`] alive.
|
||||
#[inline]
|
||||
pub fn clone_weak(&self) -> UntypedHandle {
|
||||
match self {
|
||||
UntypedHandle::Strong(handle) => UntypedHandle::Weak(handle.id),
|
||||
UntypedHandle::Weak(id) => UntypedHandle::Weak(*id),
|
||||
UntypedHandle::Uuid { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
@ -321,7 +313,7 @@ impl UntypedHandle {
|
||||
pub fn type_id(&self) -> TypeId {
|
||||
match self {
|
||||
UntypedHandle::Strong(handle) => handle.id.type_id(),
|
||||
UntypedHandle::Weak(id) => id.type_id(),
|
||||
UntypedHandle::Uuid { type_id, .. } => *type_id,
|
||||
}
|
||||
}
|
||||
|
||||
@ -330,7 +322,7 @@ impl UntypedHandle {
|
||||
pub fn typed_unchecked<A: Asset>(self) -> Handle<A> {
|
||||
match self {
|
||||
UntypedHandle::Strong(handle) => Handle::Strong(handle),
|
||||
UntypedHandle::Weak(id) => Handle::Weak(id.typed_unchecked::<A>()),
|
||||
UntypedHandle::Uuid { uuid, .. } => Handle::Uuid(uuid, PhantomData),
|
||||
}
|
||||
}
|
||||
|
||||
@ -345,10 +337,7 @@ impl UntypedHandle {
|
||||
TypeId::of::<A>(),
|
||||
"The target Handle<A>'s TypeId does not match the TypeId of this UntypedHandle"
|
||||
);
|
||||
match self {
|
||||
UntypedHandle::Strong(handle) => Handle::Strong(handle),
|
||||
UntypedHandle::Weak(id) => Handle::Weak(id.typed_unchecked::<A>()),
|
||||
}
|
||||
self.typed_unchecked()
|
||||
}
|
||||
|
||||
/// Converts to a typed Handle. This will panic if the internal [`TypeId`] does not match the given asset type `A`
|
||||
@ -376,7 +365,7 @@ impl UntypedHandle {
|
||||
pub fn meta_transform(&self) -> Option<&MetaTransform> {
|
||||
match self {
|
||||
UntypedHandle::Strong(handle) => handle.meta_transform.as_ref(),
|
||||
UntypedHandle::Weak(_) => None,
|
||||
UntypedHandle::Uuid { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -409,12 +398,9 @@ impl core::fmt::Debug for UntypedHandle {
|
||||
handle.path
|
||||
)
|
||||
}
|
||||
UntypedHandle::Weak(id) => write!(
|
||||
f,
|
||||
"WeakHandle{{ type_id: {:?}, id: {:?} }}",
|
||||
id.type_id(),
|
||||
id.internal()
|
||||
),
|
||||
UntypedHandle::Uuid { type_id, uuid } => {
|
||||
write!(f, "UuidHandle{{ type_id: {type_id:?}, uuid: {uuid:?} }}",)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -474,7 +460,10 @@ impl<A: Asset> From<Handle<A>> for UntypedHandle {
|
||||
fn from(value: Handle<A>) -> Self {
|
||||
match value {
|
||||
Handle::Strong(handle) => UntypedHandle::Strong(handle),
|
||||
Handle::Weak(id) => UntypedHandle::Weak(id.into()),
|
||||
Handle::Uuid(uuid, _) => UntypedHandle::Uuid {
|
||||
type_id: TypeId::of::<A>(),
|
||||
uuid,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -490,36 +479,37 @@ impl<A: Asset> TryFrom<UntypedHandle> for Handle<A> {
|
||||
return Err(UntypedAssetConversionError::TypeIdMismatch { expected, found });
|
||||
}
|
||||
|
||||
match value {
|
||||
UntypedHandle::Strong(handle) => Ok(Handle::Strong(handle)),
|
||||
UntypedHandle::Weak(id) => {
|
||||
let Ok(id) = id.try_into() else {
|
||||
return Err(UntypedAssetConversionError::TypeIdMismatch { expected, found });
|
||||
};
|
||||
Ok(Handle::Weak(id))
|
||||
}
|
||||
}
|
||||
Ok(match value {
|
||||
UntypedHandle::Strong(handle) => Handle::Strong(handle),
|
||||
UntypedHandle::Uuid { uuid, .. } => Handle::Uuid(uuid, PhantomData),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a weak [`Handle`] from a string literal containing a UUID.
|
||||
/// Creates a [`Handle`] from a string literal containing a UUID.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # use bevy_asset::{Handle, weak_handle};
|
||||
/// # use bevy_asset::{Handle, uuid_handle};
|
||||
/// # type Shader = ();
|
||||
/// const SHADER: Handle<Shader> = weak_handle!("1347c9b7-c46a-48e7-b7b8-023a354b7cac");
|
||||
/// const SHADER: Handle<Shader> = uuid_handle!("1347c9b7-c46a-48e7-b7b8-023a354b7cac");
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! weak_handle {
|
||||
macro_rules! uuid_handle {
|
||||
($uuid:expr) => {{
|
||||
$crate::Handle::Weak($crate::AssetId::Uuid {
|
||||
uuid: $crate::uuid::uuid!($uuid),
|
||||
})
|
||||
$crate::Handle::Uuid($crate::uuid::uuid!($uuid), core::marker::PhantomData)
|
||||
}};
|
||||
}
|
||||
|
||||
#[deprecated = "Use uuid_handle! instead"]
|
||||
#[macro_export]
|
||||
macro_rules! weak_handle {
|
||||
($uuid:expr) => {
|
||||
uuid_handle!($uuid)
|
||||
};
|
||||
}
|
||||
|
||||
/// Errors preventing the conversion of to/from an [`UntypedHandle`] and a [`Handle`].
|
||||
#[derive(Error, Debug, PartialEq, Clone)]
|
||||
#[non_exhaustive]
|
||||
@ -559,15 +549,12 @@ mod tests {
|
||||
/// Typed and Untyped `Handles` should be equivalent to each other and themselves
|
||||
#[test]
|
||||
fn equality() {
|
||||
let typed = AssetId::<TestAsset>::Uuid { uuid: UUID_1 };
|
||||
let untyped = UntypedAssetId::Uuid {
|
||||
let typed = Handle::<TestAsset>::Uuid(UUID_1, PhantomData);
|
||||
let untyped = UntypedHandle::Uuid {
|
||||
type_id: TypeId::of::<TestAsset>(),
|
||||
uuid: UUID_1,
|
||||
};
|
||||
|
||||
let typed = Handle::Weak(typed);
|
||||
let untyped = UntypedHandle::Weak(untyped);
|
||||
|
||||
assert_eq!(
|
||||
Ok(typed.clone()),
|
||||
Handle::<TestAsset>::try_from(untyped.clone())
|
||||
@ -585,22 +572,17 @@ mod tests {
|
||||
fn ordering() {
|
||||
assert!(UUID_1 < UUID_2);
|
||||
|
||||
let typed_1 = AssetId::<TestAsset>::Uuid { uuid: UUID_1 };
|
||||
let typed_2 = AssetId::<TestAsset>::Uuid { uuid: UUID_2 };
|
||||
let untyped_1 = UntypedAssetId::Uuid {
|
||||
let typed_1 = Handle::<TestAsset>::Uuid(UUID_1, PhantomData);
|
||||
let typed_2 = Handle::<TestAsset>::Uuid(UUID_2, PhantomData);
|
||||
let untyped_1 = UntypedHandle::Uuid {
|
||||
type_id: TypeId::of::<TestAsset>(),
|
||||
uuid: UUID_1,
|
||||
};
|
||||
let untyped_2 = UntypedAssetId::Uuid {
|
||||
let untyped_2 = UntypedHandle::Uuid {
|
||||
type_id: TypeId::of::<TestAsset>(),
|
||||
uuid: UUID_2,
|
||||
};
|
||||
|
||||
let typed_1 = Handle::Weak(typed_1);
|
||||
let typed_2 = Handle::Weak(typed_2);
|
||||
let untyped_1 = UntypedHandle::Weak(untyped_1);
|
||||
let untyped_2 = UntypedHandle::Weak(untyped_2);
|
||||
|
||||
assert!(typed_1 < typed_2);
|
||||
assert!(untyped_1 < untyped_2);
|
||||
|
||||
@ -617,15 +599,12 @@ mod tests {
|
||||
/// Typed and Untyped `Handles` should be equivalently hashable to each other and themselves
|
||||
#[test]
|
||||
fn hashing() {
|
||||
let typed = AssetId::<TestAsset>::Uuid { uuid: UUID_1 };
|
||||
let untyped = UntypedAssetId::Uuid {
|
||||
let typed = Handle::<TestAsset>::Uuid(UUID_1, PhantomData);
|
||||
let untyped = UntypedHandle::Uuid {
|
||||
type_id: TypeId::of::<TestAsset>(),
|
||||
uuid: UUID_1,
|
||||
};
|
||||
|
||||
let typed = Handle::Weak(typed);
|
||||
let untyped = UntypedHandle::Weak(untyped);
|
||||
|
||||
assert_eq!(
|
||||
hash(&typed),
|
||||
hash(&Handle::<TestAsset>::try_from(untyped.clone()).unwrap())
|
||||
@ -637,15 +616,12 @@ mod tests {
|
||||
/// Typed and Untyped `Handles` should be interchangeable
|
||||
#[test]
|
||||
fn conversion() {
|
||||
let typed = AssetId::<TestAsset>::Uuid { uuid: UUID_1 };
|
||||
let untyped = UntypedAssetId::Uuid {
|
||||
let typed = Handle::<TestAsset>::Uuid(UUID_1, PhantomData);
|
||||
let untyped = UntypedHandle::Uuid {
|
||||
type_id: TypeId::of::<TestAsset>(),
|
||||
uuid: UUID_1,
|
||||
};
|
||||
|
||||
let typed = Handle::Weak(typed);
|
||||
let untyped = UntypedHandle::Weak(untyped);
|
||||
|
||||
assert_eq!(typed, Handle::try_from(untyped.clone()).unwrap());
|
||||
assert_eq!(UntypedHandle::from(typed.clone()), untyped);
|
||||
}
|
||||
|
||||
@ -56,6 +56,7 @@ pub(crate) struct EmbeddedEventHandler {
|
||||
dir: Dir,
|
||||
last_event: Option<AssetSourceEvent>,
|
||||
}
|
||||
|
||||
impl FilesystemEventHandler for EmbeddedEventHandler {
|
||||
fn begin(&mut self) {
|
||||
self.last_event = None;
|
||||
|
||||
@ -141,16 +141,19 @@ impl EmbeddedAssetRegistry {
|
||||
pub trait GetAssetServer {
|
||||
fn get_asset_server(&self) -> &AssetServer;
|
||||
}
|
||||
|
||||
impl GetAssetServer for App {
|
||||
fn get_asset_server(&self) -> &AssetServer {
|
||||
self.world().get_asset_server()
|
||||
}
|
||||
}
|
||||
|
||||
impl GetAssetServer for World {
|
||||
fn get_asset_server(&self) -> &AssetServer {
|
||||
self.resource()
|
||||
}
|
||||
}
|
||||
|
||||
impl GetAssetServer for AssetServer {
|
||||
fn get_asset_server(&self) -> &AssetServer {
|
||||
self
|
||||
|
||||
@ -47,7 +47,7 @@ fn js_value_to_err(context: &str) -> impl FnOnce(JsValue) -> std::io::Error + '_
|
||||
}
|
||||
};
|
||||
|
||||
std::io::Error::new(std::io::ErrorKind::Other, message)
|
||||
std::io::Error::other(message)
|
||||
}
|
||||
}
|
||||
|
||||
@ -62,10 +62,7 @@ impl HttpWasmAssetReader {
|
||||
let worker: web_sys::WorkerGlobalScope = global.unchecked_into();
|
||||
worker.fetch_with_str(path.to_str().unwrap())
|
||||
} else {
|
||||
let error = std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
"Unsupported JavaScript global context",
|
||||
);
|
||||
let error = std::io::Error::other("Unsupported JavaScript global context");
|
||||
return Err(AssetReaderError::Io(error.into()));
|
||||
};
|
||||
let resp_value = JsFuture::from(promise)
|
||||
|
||||
@ -264,7 +264,7 @@ pub struct AssetPlugin {
|
||||
/// [`AssetSource`](io::AssetSource). Subfolders within these folders are also valid.
|
||||
///
|
||||
/// It is strongly discouraged to use [`Allow`](UnapprovedPathMode::Allow) if your
|
||||
/// app will include scripts or modding support, as it could allow allow arbitrary file
|
||||
/// app will include scripts or modding support, as it could allow arbitrary file
|
||||
/// access for malicious code.
|
||||
///
|
||||
/// See [`AssetPath::is_unapproved`](crate::AssetPath::is_unapproved)
|
||||
@ -272,10 +272,10 @@ pub struct AssetPlugin {
|
||||
pub enum UnapprovedPathMode {
|
||||
/// Unapproved asset loading is allowed. This is strongly discouraged.
|
||||
Allow,
|
||||
/// Fails to load any asset that is is unapproved, unless an override method is used, like
|
||||
/// Fails to load any asset that is unapproved, unless an override method is used, like
|
||||
/// [`AssetServer::load_override`].
|
||||
Deny,
|
||||
/// Fails to load any asset that is is unapproved.
|
||||
/// Fails to load any asset that is unapproved.
|
||||
#[default]
|
||||
Forbid,
|
||||
}
|
||||
@ -2000,4 +2000,92 @@ mod tests {
|
||||
|
||||
app.world_mut().run_schedule(Update);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "blocked on https://github.com/bevyengine/bevy/issues/11111"]
|
||||
fn same_asset_different_settings() {
|
||||
// Test loading the same asset twice with different settings. This should
|
||||
// produce two distinct assets.
|
||||
|
||||
// First, implement an asset that's a single u8, whose value is copied from
|
||||
// the loader settings.
|
||||
|
||||
#[derive(Asset, TypePath)]
|
||||
struct U8Asset(u8);
|
||||
|
||||
#[derive(Serialize, Deserialize, Default)]
|
||||
struct U8LoaderSettings(u8);
|
||||
|
||||
struct U8Loader;
|
||||
|
||||
impl AssetLoader for U8Loader {
|
||||
type Asset = U8Asset;
|
||||
type Settings = U8LoaderSettings;
|
||||
type Error = crate::loader::LoadDirectError;
|
||||
|
||||
async fn load(
|
||||
&self,
|
||||
_: &mut dyn Reader,
|
||||
settings: &Self::Settings,
|
||||
_: &mut LoadContext<'_>,
|
||||
) -> Result<Self::Asset, Self::Error> {
|
||||
Ok(U8Asset(settings.0))
|
||||
}
|
||||
|
||||
fn extensions(&self) -> &[&str] {
|
||||
&["u8"]
|
||||
}
|
||||
}
|
||||
|
||||
// Create a test asset.
|
||||
|
||||
let dir = Dir::default();
|
||||
dir.insert_asset(Path::new("test.u8"), &[]);
|
||||
|
||||
let asset_source = AssetSource::build()
|
||||
.with_reader(move || Box::new(MemoryAssetReader { root: dir.clone() }));
|
||||
|
||||
// Set up the app.
|
||||
|
||||
let mut app = App::new();
|
||||
|
||||
app.register_asset_source(AssetSourceId::Default, asset_source)
|
||||
.add_plugins((TaskPoolPlugin::default(), AssetPlugin::default()))
|
||||
.init_asset::<U8Asset>()
|
||||
.register_asset_loader(U8Loader);
|
||||
|
||||
let asset_server = app.world().resource::<AssetServer>();
|
||||
|
||||
// Load the test asset twice but with different settings.
|
||||
|
||||
fn load(asset_server: &AssetServer, path: &str, value: u8) -> Handle<U8Asset> {
|
||||
asset_server.load_with_settings::<U8Asset, U8LoaderSettings>(
|
||||
path,
|
||||
move |s: &mut U8LoaderSettings| s.0 = value,
|
||||
)
|
||||
}
|
||||
|
||||
let handle_1 = load(asset_server, "test.u8", 1);
|
||||
let handle_2 = load(asset_server, "test.u8", 2);
|
||||
|
||||
// Handles should be different.
|
||||
|
||||
assert_ne!(handle_1, handle_2);
|
||||
|
||||
run_app_until(&mut app, |world| {
|
||||
let (Some(asset_1), Some(asset_2)) = (
|
||||
world.resource::<Assets<U8Asset>>().get(&handle_1),
|
||||
world.resource::<Assets<U8Asset>>().get(&handle_2),
|
||||
) else {
|
||||
return None;
|
||||
};
|
||||
|
||||
// Values should match the settings.
|
||||
|
||||
assert_eq!(asset_1.0, 1);
|
||||
assert_eq!(asset_2.0, 2);
|
||||
|
||||
Some(())
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -480,7 +480,7 @@ impl<'a> AssetPath<'a> {
|
||||
}
|
||||
|
||||
pub(crate) fn iter_secondary_extensions(full_extension: &str) -> impl Iterator<Item = &str> {
|
||||
full_extension.chars().enumerate().filter_map(|(i, c)| {
|
||||
full_extension.char_indices().filter_map(|(i, c)| {
|
||||
if c == '.' {
|
||||
Some(&full_extension[i + 1..])
|
||||
} else {
|
||||
|
||||
@ -18,16 +18,16 @@ pub struct ReflectAsset {
|
||||
handle_type_id: TypeId,
|
||||
assets_resource_type_id: TypeId,
|
||||
|
||||
get: fn(&World, UntypedHandle) -> Option<&dyn Reflect>,
|
||||
get: fn(&World, UntypedAssetId) -> Option<&dyn Reflect>,
|
||||
// SAFETY:
|
||||
// - may only be called with an [`UnsafeWorldCell`] which can be used to access the corresponding `Assets<T>` resource mutably
|
||||
// - may only be used to access **at most one** access at once
|
||||
get_unchecked_mut: unsafe fn(UnsafeWorldCell<'_>, UntypedHandle) -> Option<&mut dyn Reflect>,
|
||||
get_unchecked_mut: unsafe fn(UnsafeWorldCell<'_>, UntypedAssetId) -> Option<&mut dyn Reflect>,
|
||||
add: fn(&mut World, &dyn PartialReflect) -> UntypedHandle,
|
||||
insert: fn(&mut World, UntypedHandle, &dyn PartialReflect),
|
||||
insert: fn(&mut World, UntypedAssetId, &dyn PartialReflect),
|
||||
len: fn(&World) -> usize,
|
||||
ids: for<'w> fn(&'w World) -> Box<dyn Iterator<Item = UntypedAssetId> + 'w>,
|
||||
remove: fn(&mut World, UntypedHandle) -> Option<Box<dyn Reflect>>,
|
||||
remove: fn(&mut World, UntypedAssetId) -> Option<Box<dyn Reflect>>,
|
||||
}
|
||||
|
||||
impl ReflectAsset {
|
||||
@ -42,15 +42,19 @@ impl ReflectAsset {
|
||||
}
|
||||
|
||||
/// Equivalent of [`Assets::get`]
|
||||
pub fn get<'w>(&self, world: &'w World, handle: UntypedHandle) -> Option<&'w dyn Reflect> {
|
||||
(self.get)(world, handle)
|
||||
pub fn get<'w>(
|
||||
&self,
|
||||
world: &'w World,
|
||||
asset_id: impl Into<UntypedAssetId>,
|
||||
) -> Option<&'w dyn Reflect> {
|
||||
(self.get)(world, asset_id.into())
|
||||
}
|
||||
|
||||
/// Equivalent of [`Assets::get_mut`]
|
||||
pub fn get_mut<'w>(
|
||||
&self,
|
||||
world: &'w mut World,
|
||||
handle: UntypedHandle,
|
||||
asset_id: impl Into<UntypedAssetId>,
|
||||
) -> Option<&'w mut dyn Reflect> {
|
||||
// SAFETY: unique world access
|
||||
#[expect(
|
||||
@ -58,7 +62,7 @@ impl ReflectAsset {
|
||||
reason = "Use of unsafe `Self::get_unchecked_mut()` function."
|
||||
)]
|
||||
unsafe {
|
||||
(self.get_unchecked_mut)(world.as_unsafe_world_cell(), handle)
|
||||
(self.get_unchecked_mut)(world.as_unsafe_world_cell(), asset_id.into())
|
||||
}
|
||||
}
|
||||
|
||||
@ -76,8 +80,8 @@ impl ReflectAsset {
|
||||
/// # let handle_1: UntypedHandle = unimplemented!();
|
||||
/// # let handle_2: UntypedHandle = unimplemented!();
|
||||
/// let unsafe_world_cell = world.as_unsafe_world_cell();
|
||||
/// let a = unsafe { reflect_asset.get_unchecked_mut(unsafe_world_cell, handle_1).unwrap() };
|
||||
/// let b = unsafe { reflect_asset.get_unchecked_mut(unsafe_world_cell, handle_2).unwrap() };
|
||||
/// let a = unsafe { reflect_asset.get_unchecked_mut(unsafe_world_cell, &handle_1).unwrap() };
|
||||
/// let b = unsafe { reflect_asset.get_unchecked_mut(unsafe_world_cell, &handle_2).unwrap() };
|
||||
/// // ^ not allowed, two mutable references through the same asset resource, even though the
|
||||
/// // handles are distinct
|
||||
///
|
||||
@ -96,10 +100,10 @@ impl ReflectAsset {
|
||||
pub unsafe fn get_unchecked_mut<'w>(
|
||||
&self,
|
||||
world: UnsafeWorldCell<'w>,
|
||||
handle: UntypedHandle,
|
||||
asset_id: impl Into<UntypedAssetId>,
|
||||
) -> Option<&'w mut dyn Reflect> {
|
||||
// SAFETY: requirements are deferred to the caller
|
||||
unsafe { (self.get_unchecked_mut)(world, handle) }
|
||||
unsafe { (self.get_unchecked_mut)(world, asset_id.into()) }
|
||||
}
|
||||
|
||||
/// Equivalent of [`Assets::add`]
|
||||
@ -107,13 +111,22 @@ impl ReflectAsset {
|
||||
(self.add)(world, value)
|
||||
}
|
||||
/// Equivalent of [`Assets::insert`]
|
||||
pub fn insert(&self, world: &mut World, handle: UntypedHandle, value: &dyn PartialReflect) {
|
||||
(self.insert)(world, handle, value);
|
||||
pub fn insert(
|
||||
&self,
|
||||
world: &mut World,
|
||||
asset_id: impl Into<UntypedAssetId>,
|
||||
value: &dyn PartialReflect,
|
||||
) {
|
||||
(self.insert)(world, asset_id.into(), value);
|
||||
}
|
||||
|
||||
/// Equivalent of [`Assets::remove`]
|
||||
pub fn remove(&self, world: &mut World, handle: UntypedHandle) -> Option<Box<dyn Reflect>> {
|
||||
(self.remove)(world, handle)
|
||||
pub fn remove(
|
||||
&self,
|
||||
world: &mut World,
|
||||
asset_id: impl Into<UntypedAssetId>,
|
||||
) -> Option<Box<dyn Reflect>> {
|
||||
(self.remove)(world, asset_id.into())
|
||||
}
|
||||
|
||||
/// Equivalent of [`Assets::len`]
|
||||
@ -137,17 +150,17 @@ impl<A: Asset + FromReflect> FromType<A> for ReflectAsset {
|
||||
ReflectAsset {
|
||||
handle_type_id: TypeId::of::<Handle<A>>(),
|
||||
assets_resource_type_id: TypeId::of::<Assets<A>>(),
|
||||
get: |world, handle| {
|
||||
get: |world, asset_id| {
|
||||
let assets = world.resource::<Assets<A>>();
|
||||
let asset = assets.get(&handle.typed_debug_checked());
|
||||
let asset = assets.get(asset_id.typed_debug_checked());
|
||||
asset.map(|asset| asset as &dyn Reflect)
|
||||
},
|
||||
get_unchecked_mut: |world, handle| {
|
||||
get_unchecked_mut: |world, asset_id| {
|
||||
// SAFETY: `get_unchecked_mut` must be called with `UnsafeWorldCell` having access to `Assets<A>`,
|
||||
// and must ensure to only have at most one reference to it live at all times.
|
||||
#[expect(unsafe_code, reason = "Uses `UnsafeWorldCell::get_resource_mut()`.")]
|
||||
let assets = unsafe { world.get_resource_mut::<Assets<A>>().unwrap().into_inner() };
|
||||
let asset = assets.get_mut(&handle.typed_debug_checked());
|
||||
let asset = assets.get_mut(asset_id.typed_debug_checked());
|
||||
asset.map(|asset| asset as &mut dyn Reflect)
|
||||
},
|
||||
add: |world, value| {
|
||||
@ -156,11 +169,11 @@ impl<A: Asset + FromReflect> FromType<A> for ReflectAsset {
|
||||
.expect("could not call `FromReflect::from_reflect` in `ReflectAsset::add`");
|
||||
assets.add(value).untyped()
|
||||
},
|
||||
insert: |world, handle, value| {
|
||||
insert: |world, asset_id, value| {
|
||||
let mut assets = world.resource_mut::<Assets<A>>();
|
||||
let value: A = FromReflect::from_reflect(value)
|
||||
.expect("could not call `FromReflect::from_reflect` in `ReflectAsset::set`");
|
||||
assets.insert(&handle.typed_debug_checked(), value);
|
||||
assets.insert(asset_id.typed_debug_checked(), value);
|
||||
},
|
||||
len: |world| {
|
||||
let assets = world.resource::<Assets<A>>();
|
||||
@ -170,9 +183,9 @@ impl<A: Asset + FromReflect> FromType<A> for ReflectAsset {
|
||||
let assets = world.resource::<Assets<A>>();
|
||||
Box::new(assets.ids().map(AssetId::untyped))
|
||||
},
|
||||
remove: |world, handle| {
|
||||
remove: |world, asset_id| {
|
||||
let mut assets = world.resource_mut::<Assets<A>>();
|
||||
let value = assets.remove(&handle.typed_debug_checked());
|
||||
let value = assets.remove(asset_id.typed_debug_checked());
|
||||
value.map(|value| Box::new(value) as Box<dyn Reflect>)
|
||||
},
|
||||
}
|
||||
@ -200,7 +213,7 @@ impl<A: Asset + FromReflect> FromType<A> for ReflectAsset {
|
||||
/// let reflect_asset = type_registry.get_type_data::<ReflectAsset>(reflect_handle.asset_type_id()).unwrap();
|
||||
///
|
||||
/// let handle = reflect_handle.downcast_handle_untyped(handle.as_any()).unwrap();
|
||||
/// let value = reflect_asset.get(world, handle).unwrap();
|
||||
/// let value = reflect_asset.get(world, &handle).unwrap();
|
||||
/// println!("{value:?}");
|
||||
/// }
|
||||
/// ```
|
||||
@ -210,6 +223,7 @@ pub struct ReflectHandle {
|
||||
downcast_handle_untyped: fn(&dyn Any) -> Option<UntypedHandle>,
|
||||
typed: fn(UntypedHandle) -> Box<dyn Reflect>,
|
||||
}
|
||||
|
||||
impl ReflectHandle {
|
||||
/// The [`TypeId`] of the asset
|
||||
pub fn asset_type_id(&self) -> TypeId {
|
||||
@ -247,7 +261,7 @@ mod tests {
|
||||
use alloc::{string::String, vec::Vec};
|
||||
use core::any::TypeId;
|
||||
|
||||
use crate::{Asset, AssetApp, AssetPlugin, ReflectAsset, UntypedHandle};
|
||||
use crate::{Asset, AssetApp, AssetPlugin, ReflectAsset};
|
||||
use bevy_app::App;
|
||||
use bevy_ecs::reflect::AppTypeRegistry;
|
||||
use bevy_reflect::Reflect;
|
||||
@ -281,7 +295,7 @@ mod tests {
|
||||
let handle = reflect_asset.add(app.world_mut(), &value);
|
||||
// struct is a reserved keyword, so we can't use it here
|
||||
let strukt = reflect_asset
|
||||
.get_mut(app.world_mut(), handle)
|
||||
.get_mut(app.world_mut(), &handle)
|
||||
.unwrap()
|
||||
.reflect_mut()
|
||||
.as_struct()
|
||||
@ -294,16 +308,12 @@ mod tests {
|
||||
assert_eq!(reflect_asset.len(app.world()), 1);
|
||||
let ids: Vec<_> = reflect_asset.ids(app.world()).collect();
|
||||
assert_eq!(ids.len(), 1);
|
||||
let id = ids[0];
|
||||
|
||||
let fetched_handle = UntypedHandle::Weak(ids[0]);
|
||||
let asset = reflect_asset
|
||||
.get(app.world(), fetched_handle.clone_weak())
|
||||
.unwrap();
|
||||
let asset = reflect_asset.get(app.world(), id).unwrap();
|
||||
assert_eq!(asset.downcast_ref::<AssetType>().unwrap().field, "edited");
|
||||
|
||||
reflect_asset
|
||||
.remove(app.world_mut(), fetched_handle)
|
||||
.unwrap();
|
||||
reflect_asset.remove(app.world_mut(), id).unwrap();
|
||||
assert_eq!(reflect_asset.len(app.world()), 0);
|
||||
}
|
||||
}
|
||||
|
||||
@ -553,7 +553,9 @@ impl AssetServer {
|
||||
path: impl Into<AssetPath<'a>>,
|
||||
) -> Result<UntypedHandle, AssetLoadError> {
|
||||
let path: AssetPath = path.into();
|
||||
self.load_internal(None, path, false, None).await
|
||||
self.load_internal(None, path, false, None)
|
||||
.await
|
||||
.map(|h| h.expect("handle must be returned, since we didn't pass in an input handle"))
|
||||
}
|
||||
|
||||
pub(crate) fn load_unknown_type_with_meta_transform<'a>(
|
||||
@ -643,21 +645,25 @@ impl AssetServer {
|
||||
|
||||
/// Performs an async asset load.
|
||||
///
|
||||
/// `input_handle` must only be [`Some`] if `should_load` was true when retrieving `input_handle`. This is an optimization to
|
||||
/// avoid looking up `should_load` twice, but it means you _must_ be sure a load is necessary when calling this function with [`Some`].
|
||||
/// `input_handle` must only be [`Some`] if `should_load` was true when retrieving
|
||||
/// `input_handle`. This is an optimization to avoid looking up `should_load` twice, but it
|
||||
/// means you _must_ be sure a load is necessary when calling this function with [`Some`].
|
||||
///
|
||||
/// Returns the handle of the asset if one was retrieved by this function. Otherwise, may return
|
||||
/// [`None`].
|
||||
async fn load_internal<'a>(
|
||||
&self,
|
||||
mut input_handle: Option<UntypedHandle>,
|
||||
input_handle: Option<UntypedHandle>,
|
||||
path: AssetPath<'a>,
|
||||
force: bool,
|
||||
meta_transform: Option<MetaTransform>,
|
||||
) -> Result<UntypedHandle, AssetLoadError> {
|
||||
let asset_type_id = input_handle.as_ref().map(UntypedHandle::type_id);
|
||||
) -> Result<Option<UntypedHandle>, AssetLoadError> {
|
||||
let input_handle_type_id = input_handle.as_ref().map(UntypedHandle::type_id);
|
||||
|
||||
let path = path.into_owned();
|
||||
let path_clone = path.clone();
|
||||
let (mut meta, loader, mut reader) = self
|
||||
.get_meta_loader_and_reader(&path_clone, asset_type_id)
|
||||
.get_meta_loader_and_reader(&path_clone, input_handle_type_id)
|
||||
.await
|
||||
.inspect_err(|e| {
|
||||
// if there was an input handle, a "load" operation has already started, so we must produce a "failure" event, if
|
||||
@ -674,76 +680,90 @@ impl AssetServer {
|
||||
if let Some(meta_transform) = input_handle.as_ref().and_then(|h| h.meta_transform()) {
|
||||
(*meta_transform)(&mut *meta);
|
||||
}
|
||||
// downgrade the input handle so we don't keep the asset alive just because we're loading it
|
||||
// note we can't just pass a weak handle in, as only strong handles contain the asset meta transform
|
||||
input_handle = input_handle.map(|h| h.clone_weak());
|
||||
|
||||
// This contains Some(UntypedHandle), if it was retrievable
|
||||
// If it is None, that is because it was _not_ retrievable, due to
|
||||
// 1. The handle was not already passed in for this path, meaning we can't just use that
|
||||
// 2. The asset has not been loaded yet, meaning there is no existing Handle for it
|
||||
// 3. The path has a label, meaning the AssetLoader's root asset type is not the path's asset type
|
||||
//
|
||||
// In the None case, the only course of action is to wait for the asset to load so we can allocate the
|
||||
// handle for that type.
|
||||
//
|
||||
// TODO: Note that in the None case, multiple asset loads for the same path can happen at the same time
|
||||
// (rather than "early out-ing" in the "normal" case)
|
||||
// This would be resolved by a universal asset id, as we would not need to resolve the asset type
|
||||
// to generate the ID. See this issue: https://github.com/bevyengine/bevy/issues/10549
|
||||
let handle_result = match input_handle {
|
||||
Some(handle) => {
|
||||
// if a handle was passed in, the "should load" check was already done
|
||||
Some((handle, true))
|
||||
}
|
||||
None => {
|
||||
let mut infos = self.data.infos.write();
|
||||
let result = infos.get_or_create_path_handle_internal(
|
||||
path.clone(),
|
||||
path.label().is_none().then(|| loader.asset_type_id()),
|
||||
HandleLoadingMode::Request,
|
||||
meta_transform,
|
||||
);
|
||||
unwrap_with_context(result, Either::Left(loader.asset_type_name()))
|
||||
}
|
||||
};
|
||||
let asset_id; // The asset ID of the asset we are trying to load.
|
||||
let fetched_handle; // The handle if one was looked up/created.
|
||||
let should_load; // Whether we need to load the asset.
|
||||
if let Some(input_handle) = input_handle {
|
||||
asset_id = Some(input_handle.id());
|
||||
// In this case, we intentionally drop the input handle so we can cancel loading the
|
||||
// asset if the handle gets dropped (externally) before it finishes loading.
|
||||
fetched_handle = None;
|
||||
// The handle was passed in, so the "should_load" check was already done.
|
||||
should_load = true;
|
||||
} else {
|
||||
// TODO: multiple asset loads for the same path can happen at the same time (rather than
|
||||
// "early out-ing" in the "normal" case). This would be resolved by a universal asset
|
||||
// id, as we would not need to resolve the asset type to generate the ID. See this
|
||||
// issue: https://github.com/bevyengine/bevy/issues/10549
|
||||
|
||||
let handle = if let Some((handle, should_load)) = handle_result {
|
||||
if path.label().is_none() && handle.type_id() != loader.asset_type_id() {
|
||||
let mut infos = self.data.infos.write();
|
||||
let result = infos.get_or_create_path_handle_internal(
|
||||
path.clone(),
|
||||
path.label().is_none().then(|| loader.asset_type_id()),
|
||||
HandleLoadingMode::Request,
|
||||
meta_transform,
|
||||
);
|
||||
match unwrap_with_context(result, Either::Left(loader.asset_type_name())) {
|
||||
// We couldn't figure out the correct handle without its type ID (which can only
|
||||
// happen if we are loading a subasset).
|
||||
None => {
|
||||
// We don't know the expected type since the subasset may have a different type
|
||||
// than the "root" asset (which is the type the loader will load).
|
||||
asset_id = None;
|
||||
fetched_handle = None;
|
||||
// If we couldn't find an appropriate handle, then the asset certainly needs to
|
||||
// be loaded.
|
||||
should_load = true;
|
||||
}
|
||||
Some((handle, result_should_load)) => {
|
||||
asset_id = Some(handle.id());
|
||||
fetched_handle = Some(handle);
|
||||
should_load = result_should_load;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Verify that the expected type matches the loader's type.
|
||||
if let Some(asset_type_id) = asset_id.map(|id| id.type_id()) {
|
||||
// If we are loading a subasset, then the subasset's type almost certainly doesn't match
|
||||
// the loader's type - and that's ok.
|
||||
if path.label().is_none() && asset_type_id != loader.asset_type_id() {
|
||||
error!(
|
||||
"Expected {:?}, got {:?}",
|
||||
handle.type_id(),
|
||||
asset_type_id,
|
||||
loader.asset_type_id()
|
||||
);
|
||||
return Err(AssetLoadError::RequestedHandleTypeMismatch {
|
||||
path: path.into_owned(),
|
||||
requested: handle.type_id(),
|
||||
requested: asset_type_id,
|
||||
actual_asset_name: loader.asset_type_name(),
|
||||
loader_name: loader.type_name(),
|
||||
});
|
||||
}
|
||||
if !should_load && !force {
|
||||
return Ok(handle);
|
||||
}
|
||||
Some(handle)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// if the handle result is None, we definitely need to load the asset
|
||||
}
|
||||
// Bail out earlier if we don't need to load the asset.
|
||||
if !should_load && !force {
|
||||
return Ok(fetched_handle);
|
||||
}
|
||||
|
||||
let (base_handle, base_path) = if path.label().is_some() {
|
||||
// We don't actually need to use _base_handle, but we do need to keep the handle alive.
|
||||
// Dropping it would cancel the load of the base asset, which would make the load of this
|
||||
// subasset never complete.
|
||||
let (base_asset_id, _base_handle, base_path) = if path.label().is_some() {
|
||||
let mut infos = self.data.infos.write();
|
||||
let base_path = path.without_label().into_owned();
|
||||
let (base_handle, _) = infos.get_or_create_path_handle_erased(
|
||||
base_path.clone(),
|
||||
loader.asset_type_id(),
|
||||
Some(loader.asset_type_name()),
|
||||
HandleLoadingMode::Force,
|
||||
None,
|
||||
);
|
||||
(base_handle, base_path)
|
||||
let base_handle = infos
|
||||
.get_or_create_path_handle_erased(
|
||||
base_path.clone(),
|
||||
loader.asset_type_id(),
|
||||
Some(loader.asset_type_name()),
|
||||
HandleLoadingMode::Force,
|
||||
None,
|
||||
)
|
||||
.0;
|
||||
(base_handle.id(), Some(base_handle), base_path)
|
||||
} else {
|
||||
(handle.clone().unwrap(), path.clone())
|
||||
(asset_id.unwrap(), None, path.clone())
|
||||
};
|
||||
|
||||
match self
|
||||
@ -760,7 +780,7 @@ impl AssetServer {
|
||||
Ok(loaded_asset) => {
|
||||
let final_handle = if let Some(label) = path.label_cow() {
|
||||
match loaded_asset.labeled_assets.get(&label) {
|
||||
Some(labeled_asset) => labeled_asset.handle.clone(),
|
||||
Some(labeled_asset) => Some(labeled_asset.handle.clone()),
|
||||
None => {
|
||||
let mut all_labels: Vec<String> = loaded_asset
|
||||
.labeled_assets
|
||||
@ -776,16 +796,15 @@ impl AssetServer {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// if the path does not have a label, the handle must exist at this point
|
||||
handle.unwrap()
|
||||
fetched_handle
|
||||
};
|
||||
|
||||
self.send_loaded_asset(base_handle.id(), loaded_asset);
|
||||
self.send_loaded_asset(base_asset_id, loaded_asset);
|
||||
Ok(final_handle)
|
||||
}
|
||||
Err(err) => {
|
||||
self.send_asset_event(InternalAssetEvent::Failed {
|
||||
id: base_handle.id(),
|
||||
id: base_asset_id,
|
||||
error: err.clone(),
|
||||
path: path.into_owned(),
|
||||
});
|
||||
@ -1931,7 +1950,7 @@ pub enum AssetLoadError {
|
||||
base_path,
|
||||
label,
|
||||
all_labels.len(),
|
||||
all_labels.iter().map(|l| format!("'{}'", l)).collect::<Vec<_>>().join(", "))]
|
||||
all_labels.iter().map(|l| format!("'{l}'")).collect::<Vec<_>>().join(", "))]
|
||||
MissingLabel {
|
||||
base_path: AssetPath<'static>,
|
||||
label: String,
|
||||
@ -1953,6 +1972,14 @@ impl AssetLoaderError {
|
||||
pub fn path(&self) -> &AssetPath<'static> {
|
||||
&self.path
|
||||
}
|
||||
|
||||
/// The error the loader reported when attempting to load the asset.
|
||||
///
|
||||
/// If you know the type of the error the asset loader returned, you can use
|
||||
/// [`BevyError::downcast_ref()`] to get it.
|
||||
pub fn error(&self) -> &BevyError {
|
||||
&self.error
|
||||
}
|
||||
}
|
||||
|
||||
/// An error that occurs while resolving an asset added by `add_async`.
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "bevy_audio"
|
||||
version = "0.16.0-dev"
|
||||
version = "0.17.0-dev"
|
||||
edition = "2024"
|
||||
description = "Provides audio functionality for Bevy Engine"
|
||||
homepage = "https://bevy.org"
|
||||
@ -10,13 +10,13 @@ keywords = ["bevy"]
|
||||
|
||||
[dependencies]
|
||||
# bevy
|
||||
bevy_app = { path = "../bevy_app", version = "0.16.0-dev" }
|
||||
bevy_asset = { path = "../bevy_asset", version = "0.16.0-dev" }
|
||||
bevy_ecs = { path = "../bevy_ecs", version = "0.16.0-dev" }
|
||||
bevy_math = { path = "../bevy_math", version = "0.16.0-dev" }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.16.0-dev" }
|
||||
bevy_transform = { path = "../bevy_transform", version = "0.16.0-dev" }
|
||||
bevy_derive = { path = "../bevy_derive", version = "0.16.0-dev" }
|
||||
bevy_app = { path = "../bevy_app", version = "0.17.0-dev" }
|
||||
bevy_asset = { path = "../bevy_asset", version = "0.17.0-dev" }
|
||||
bevy_ecs = { path = "../bevy_ecs", version = "0.17.0-dev" }
|
||||
bevy_math = { path = "../bevy_math", version = "0.17.0-dev" }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.17.0-dev" }
|
||||
bevy_transform = { path = "../bevy_transform", version = "0.17.0-dev" }
|
||||
bevy_derive = { path = "../bevy_derive", version = "0.17.0-dev" }
|
||||
|
||||
# other
|
||||
# TODO: Remove `coreaudio-sys` dep below when updating `cpal`.
|
||||
@ -36,10 +36,10 @@ coreaudio-sys = { version = "0.2.17", default-features = false }
|
||||
rodio = { version = "0.20", default-features = false, features = [
|
||||
"wasm-bindgen",
|
||||
] }
|
||||
bevy_app = { path = "../bevy_app", version = "0.16.0-dev", default-features = false, features = [
|
||||
bevy_app = { path = "../bevy_app", version = "0.17.0-dev", default-features = false, features = [
|
||||
"web",
|
||||
] }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.16.0-dev", default-features = false, features = [
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.17.0-dev", default-features = false, features = [
|
||||
"web",
|
||||
] }
|
||||
|
||||
|
||||
@ -57,6 +57,7 @@ pub struct PlaybackRemoveMarker;
|
||||
pub(crate) struct EarPositions<'w, 's> {
|
||||
pub(crate) query: Query<'w, 's, (Entity, &'static GlobalTransform, &'static SpatialListener)>,
|
||||
}
|
||||
|
||||
impl<'w, 's> EarPositions<'w, 's> {
|
||||
/// Gets a set of transformed ear positions.
|
||||
///
|
||||
|
||||
@ -344,17 +344,11 @@ mod tests {
|
||||
|
||||
assert!(
|
||||
db_delta.abs() < 1e-2,
|
||||
"Expected ~{}dB, got {}dB (delta {})",
|
||||
db,
|
||||
db_test,
|
||||
db_delta
|
||||
"Expected ~{db}dB, got {db_test}dB (delta {db_delta})",
|
||||
);
|
||||
assert!(
|
||||
linear_relative_delta.abs() < 1e-3,
|
||||
"Expected ~{}, got {} (relative delta {})",
|
||||
linear,
|
||||
linear_test,
|
||||
linear_relative_delta
|
||||
"Expected ~{linear}, got {linear_test} (relative delta {linear_relative_delta})",
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -474,15 +468,11 @@ mod tests {
|
||||
match (a, b) {
|
||||
(Decibels(a), Decibels(b)) | (Linear(a), Linear(b)) => assert!(
|
||||
(a - b).abs() < EPSILON,
|
||||
"Expected {:?} to be approximately equal to {:?}",
|
||||
a,
|
||||
b
|
||||
"Expected {a:?} to be approximately equal to {b:?}",
|
||||
),
|
||||
(a, b) => assert!(
|
||||
(a.to_decibels() - b.to_decibels()).abs() < EPSILON,
|
||||
"Expected {:?} to be approximately equal to {:?}",
|
||||
a,
|
||||
b
|
||||
"Expected {a:?} to be approximately equal to {b:?}",
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "bevy_color"
|
||||
version = "0.16.0-dev"
|
||||
version = "0.17.0-dev"
|
||||
edition = "2024"
|
||||
description = "Types for representing and manipulating color values"
|
||||
homepage = "https://bevy.org"
|
||||
@ -10,17 +10,17 @@ keywords = ["bevy", "color"]
|
||||
rust-version = "1.85.0"
|
||||
|
||||
[dependencies]
|
||||
bevy_math = { path = "../bevy_math", version = "0.16.0-dev", default-features = false, features = [
|
||||
bevy_math = { path = "../bevy_math", version = "0.17.0-dev", default-features = false, features = [
|
||||
"curve",
|
||||
] }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.16.0-dev", default-features = false, optional = true }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.17.0-dev", default-features = false, optional = true }
|
||||
bytemuck = { version = "1", features = ["derive"] }
|
||||
serde = { version = "1.0", features = [
|
||||
"derive",
|
||||
], default-features = false, optional = true }
|
||||
thiserror = { version = "2", default-features = false }
|
||||
derive_more = { version = "1", default-features = false, features = ["from"] }
|
||||
wgpu-types = { version = "24", default-features = false, optional = true }
|
||||
derive_more = { version = "2", default-features = false, features = ["from"] }
|
||||
wgpu-types = { version = "25", default-features = false, optional = true }
|
||||
encase = { version = "0.10", default-features = false, optional = true }
|
||||
|
||||
[features]
|
||||
|
||||
@ -92,7 +92,7 @@ impl Hsla {
|
||||
/// // Palette with 5 distinct hues
|
||||
/// let palette = (0..5).map(Hsla::sequential_dispersed).collect::<Vec<_>>();
|
||||
/// ```
|
||||
pub fn sequential_dispersed(index: u32) -> Self {
|
||||
pub const fn sequential_dispersed(index: u32) -> Self {
|
||||
const FRAC_U32MAX_GOLDEN_RATIO: u32 = 2654435769; // (u32::MAX / Φ) rounded up
|
||||
const RATIO_360: f32 = 360.0 / u32::MAX as f32;
|
||||
|
||||
|
||||
@ -96,7 +96,7 @@ impl Lcha {
|
||||
/// // Palette with 5 distinct hues
|
||||
/// let palette = (0..5).map(Lcha::sequential_dispersed).collect::<Vec<_>>();
|
||||
/// ```
|
||||
pub fn sequential_dispersed(index: u32) -> Self {
|
||||
pub const fn sequential_dispersed(index: u32) -> Self {
|
||||
const FRAC_U32MAX_GOLDEN_RATIO: u32 = 2654435769; // (u32::MAX / Φ) rounded up
|
||||
const RATIO_360: f32 = 360.0 / u32::MAX as f32;
|
||||
|
||||
|
||||
@ -92,7 +92,7 @@ impl Oklcha {
|
||||
/// // Palette with 5 distinct hues
|
||||
/// let palette = (0..5).map(Oklcha::sequential_dispersed).collect::<Vec<_>>();
|
||||
/// ```
|
||||
pub fn sequential_dispersed(index: u32) -> Self {
|
||||
pub const fn sequential_dispersed(index: u32) -> Self {
|
||||
const FRAC_U32MAX_GOLDEN_RATIO: u32 = 2654435769; // (u32::MAX / Φ) rounded up
|
||||
const RATIO_360: f32 = 360.0 / u32::MAX as f32;
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "bevy_core_pipeline"
|
||||
version = "0.16.0-dev"
|
||||
version = "0.17.0-dev"
|
||||
edition = "2024"
|
||||
authors = [
|
||||
"Bevy Contributors <bevyengine@gmail.com>",
|
||||
@ -20,20 +20,20 @@ tonemapping_luts = ["bevy_render/ktx2", "bevy_image/ktx2", "bevy_image/zstd"]
|
||||
|
||||
[dependencies]
|
||||
# bevy
|
||||
bevy_app = { path = "../bevy_app", version = "0.16.0-dev" }
|
||||
bevy_asset = { path = "../bevy_asset", version = "0.16.0-dev" }
|
||||
bevy_color = { path = "../bevy_color", version = "0.16.0-dev" }
|
||||
bevy_derive = { path = "../bevy_derive", version = "0.16.0-dev" }
|
||||
bevy_diagnostic = { path = "../bevy_diagnostic", version = "0.16.0-dev" }
|
||||
bevy_ecs = { path = "../bevy_ecs", version = "0.16.0-dev" }
|
||||
bevy_image = { path = "../bevy_image", version = "0.16.0-dev" }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.16.0-dev" }
|
||||
bevy_render = { path = "../bevy_render", version = "0.16.0-dev" }
|
||||
bevy_transform = { path = "../bevy_transform", version = "0.16.0-dev" }
|
||||
bevy_math = { path = "../bevy_math", version = "0.16.0-dev" }
|
||||
bevy_utils = { path = "../bevy_utils", version = "0.16.0-dev" }
|
||||
bevy_window = { path = "../bevy_window", version = "0.16.0-dev" }
|
||||
bevy_platform = { path = "../bevy_platform", version = "0.16.0-dev", default-features = false, features = [
|
||||
bevy_app = { path = "../bevy_app", version = "0.17.0-dev" }
|
||||
bevy_asset = { path = "../bevy_asset", version = "0.17.0-dev" }
|
||||
bevy_color = { path = "../bevy_color", version = "0.17.0-dev" }
|
||||
bevy_derive = { path = "../bevy_derive", version = "0.17.0-dev" }
|
||||
bevy_diagnostic = { path = "../bevy_diagnostic", version = "0.17.0-dev" }
|
||||
bevy_ecs = { path = "../bevy_ecs", version = "0.17.0-dev" }
|
||||
bevy_image = { path = "../bevy_image", version = "0.17.0-dev" }
|
||||
bevy_reflect = { path = "../bevy_reflect", version = "0.17.0-dev" }
|
||||
bevy_render = { path = "../bevy_render", version = "0.17.0-dev" }
|
||||
bevy_transform = { path = "../bevy_transform", version = "0.17.0-dev" }
|
||||
bevy_math = { path = "../bevy_math", version = "0.17.0-dev" }
|
||||
bevy_utils = { path = "../bevy_utils", version = "0.17.0-dev" }
|
||||
bevy_window = { path = "../bevy_window", version = "0.17.0-dev" }
|
||||
bevy_platform = { path = "../bevy_platform", version = "0.17.0-dev", default-features = false, features = [
|
||||
"std",
|
||||
"serialize",
|
||||
] }
|
||||
|
||||
@ -196,6 +196,7 @@ impl RenderAsset for GpuAutoExposureCompensationCurve {
|
||||
source: Self::SourceAsset,
|
||||
_: AssetId<Self::SourceAsset>,
|
||||
(render_device, render_queue): &mut SystemParamItem<Self::Param>,
|
||||
_: Option<&Self>,
|
||||
) -> Result<Self, bevy_render::render_asset::PrepareAssetError<Self::SourceAsset>> {
|
||||
let texture = render_device.create_texture_with_data(
|
||||
render_queue,
|
||||
|
||||
@ -4,7 +4,7 @@ use bevy_ecs::prelude::*;
|
||||
use bevy_render::{
|
||||
extract_component::ExtractComponentPlugin,
|
||||
render_asset::RenderAssetPlugin,
|
||||
render_graph::RenderGraphApp,
|
||||
render_graph::RenderGraphExt,
|
||||
render_resource::{
|
||||
Buffer, BufferDescriptor, BufferUsages, PipelineCache, SpecializedComputePipelines,
|
||||
},
|
||||
|
||||
@ -10,6 +10,7 @@ use bevy_render::{
|
||||
renderer::RenderDevice,
|
||||
view::ViewUniform,
|
||||
};
|
||||
use bevy_utils::default;
|
||||
use core::num::NonZero;
|
||||
|
||||
#[derive(Resource)]
|
||||
@ -82,12 +83,11 @@ impl SpecializedComputePipeline for AutoExposurePipeline {
|
||||
layout: vec![self.histogram_layout.clone()],
|
||||
shader: self.histogram_shader.clone(),
|
||||
shader_defs: vec![],
|
||||
entry_point: match pass {
|
||||
entry_point: Some(match pass {
|
||||
AutoExposurePass::Histogram => "compute_histogram".into(),
|
||||
AutoExposurePass::Average => "compute_average".into(),
|
||||
},
|
||||
push_constant_ranges: vec![],
|
||||
zero_initialize_workgroup_memory: false,
|
||||
}),
|
||||
..default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
use crate::FullscreenShader;
|
||||
use bevy_app::{App, Plugin};
|
||||
use bevy_asset::{embedded_asset, load_embedded_asset, Handle};
|
||||
use bevy_ecs::prelude::*;
|
||||
@ -9,8 +10,7 @@ use bevy_render::{
|
||||
renderer::RenderDevice,
|
||||
RenderApp,
|
||||
};
|
||||
|
||||
use crate::fullscreen_vertex_shader::fullscreen_shader_vertex_state;
|
||||
use bevy_utils::default;
|
||||
|
||||
/// Adds support for specialized "blit pipelines", which can be used to write one texture to another.
|
||||
pub struct BlitPlugin;
|
||||
@ -38,7 +38,8 @@ impl Plugin for BlitPlugin {
|
||||
pub struct BlitPipeline {
|
||||
pub texture_bind_group: BindGroupLayout,
|
||||
pub sampler: Sampler,
|
||||
pub shader: Handle<Shader>,
|
||||
pub fullscreen_shader: FullscreenShader,
|
||||
pub fragment_shader: Handle<Shader>,
|
||||
}
|
||||
|
||||
impl FromWorld for BlitPipeline {
|
||||
@ -61,7 +62,8 @@ impl FromWorld for BlitPipeline {
|
||||
BlitPipeline {
|
||||
texture_bind_group,
|
||||
sampler,
|
||||
shader: load_embedded_asset!(render_world, "blit.wgsl"),
|
||||
fullscreen_shader: render_world.resource::<FullscreenShader>().clone(),
|
||||
fragment_shader: load_embedded_asset!(render_world, "blit.wgsl"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -80,25 +82,21 @@ impl SpecializedRenderPipeline for BlitPipeline {
|
||||
RenderPipelineDescriptor {
|
||||
label: Some("blit pipeline".into()),
|
||||
layout: vec![self.texture_bind_group.clone()],
|
||||
vertex: fullscreen_shader_vertex_state(),
|
||||
vertex: self.fullscreen_shader.to_vertex_state(),
|
||||
fragment: Some(FragmentState {
|
||||
shader: self.shader.clone(),
|
||||
shader_defs: vec![],
|
||||
entry_point: "fs_main".into(),
|
||||
shader: self.fragment_shader.clone(),
|
||||
targets: vec![Some(ColorTargetState {
|
||||
format: key.texture_format,
|
||||
blend: key.blend_state,
|
||||
write_mask: ColorWrites::ALL,
|
||||
})],
|
||||
..default()
|
||||
}),
|
||||
primitive: PrimitiveState::default(),
|
||||
depth_stencil: None,
|
||||
multisample: MultisampleState {
|
||||
count: key.samples,
|
||||
..Default::default()
|
||||
..default()
|
||||
},
|
||||
push_constant_ranges: Vec::new(),
|
||||
zero_initialize_workgroup_memory: false,
|
||||
..default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
use crate::FullscreenShader;
|
||||
|
||||
use super::{Bloom, BLOOM_TEXTURE_FORMAT};
|
||||
use crate::fullscreen_vertex_shader::fullscreen_shader_vertex_state;
|
||||
use bevy_asset::{load_embedded_asset, Handle};
|
||||
use bevy_ecs::{
|
||||
prelude::{Component, Entity},
|
||||
@ -15,6 +16,7 @@ use bevy_render::{
|
||||
},
|
||||
renderer::RenderDevice,
|
||||
};
|
||||
use bevy_utils::default;
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct BloomDownsamplingPipelineIds {
|
||||
@ -27,8 +29,10 @@ pub struct BloomDownsamplingPipeline {
|
||||
/// Layout with a texture, a sampler, and uniforms
|
||||
pub bind_group_layout: BindGroupLayout,
|
||||
pub sampler: Sampler,
|
||||
/// The shader asset handle.
|
||||
pub shader: Handle<Shader>,
|
||||
/// The asset handle for the fullscreen vertex shader.
|
||||
pub fullscreen_shader: FullscreenShader,
|
||||
/// The fragment shader asset handle.
|
||||
pub fragment_shader: Handle<Shader>,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Hash, Clone)]
|
||||
@ -81,7 +85,8 @@ impl FromWorld for BloomDownsamplingPipeline {
|
||||
BloomDownsamplingPipeline {
|
||||
bind_group_layout,
|
||||
sampler,
|
||||
shader: load_embedded_asset!(world, "bloom.wgsl"),
|
||||
fullscreen_shader: world.resource::<FullscreenShader>().clone(),
|
||||
fragment_shader: load_embedded_asset!(world, "bloom.wgsl"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -122,22 +127,18 @@ impl SpecializedRenderPipeline for BloomDownsamplingPipeline {
|
||||
.into(),
|
||||
),
|
||||
layout,
|
||||
vertex: fullscreen_shader_vertex_state(),
|
||||
vertex: self.fullscreen_shader.to_vertex_state(),
|
||||
fragment: Some(FragmentState {
|
||||
shader: self.shader.clone(),
|
||||
shader: self.fragment_shader.clone(),
|
||||
shader_defs,
|
||||
entry_point,
|
||||
entry_point: Some(entry_point),
|
||||
targets: vec![Some(ColorTargetState {
|
||||
format: BLOOM_TEXTURE_FORMAT,
|
||||
blend: None,
|
||||
write_mask: ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
primitive: PrimitiveState::default(),
|
||||
depth_stencil: None,
|
||||
multisample: MultisampleState::default(),
|
||||
push_constant_ranges: Vec::new(),
|
||||
zero_initialize_workgroup_memory: false,
|
||||
..default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,6 +2,7 @@ mod downsampling_pipeline;
|
||||
mod settings;
|
||||
mod upsampling_pipeline;
|
||||
|
||||
use bevy_image::ToExtents;
|
||||
pub use settings::{Bloom, BloomCompositeMode, BloomPrefilter};
|
||||
|
||||
use crate::{
|
||||
@ -19,7 +20,7 @@ use bevy_render::{
|
||||
extract_component::{
|
||||
ComponentUniforms, DynamicUniformIndex, ExtractComponentPlugin, UniformComponentPlugin,
|
||||
},
|
||||
render_graph::{NodeRunError, RenderGraphApp, RenderGraphContext, ViewNode, ViewNodeRunner},
|
||||
render_graph::{NodeRunError, RenderGraphContext, RenderGraphExt, ViewNode, ViewNodeRunner},
|
||||
render_resource::*,
|
||||
renderer::{RenderContext, RenderDevice},
|
||||
texture::{CachedTexture, TextureCache},
|
||||
@ -121,7 +122,7 @@ impl ViewNode for BloomNode {
|
||||
bloom_settings,
|
||||
upsampling_pipeline_ids,
|
||||
downsampling_pipeline_ids,
|
||||
): QueryItem<'w, Self::ViewQuery>,
|
||||
): QueryItem<'w, '_, Self::ViewQuery>,
|
||||
world: &'w World,
|
||||
) -> Result<(), NodeRunError> {
|
||||
if bloom_settings.intensity == 0.0 {
|
||||
@ -347,26 +348,22 @@ fn prepare_bloom_textures(
|
||||
views: Query<(Entity, &ExtractedCamera, &Bloom)>,
|
||||
) {
|
||||
for (entity, camera, bloom) in &views {
|
||||
if let Some(UVec2 {
|
||||
x: width,
|
||||
y: height,
|
||||
}) = camera.physical_viewport_size
|
||||
{
|
||||
if let Some(viewport) = camera.physical_viewport_size {
|
||||
// How many times we can halve the resolution minus one so we don't go unnecessarily low
|
||||
let mip_count = bloom.max_mip_dimension.ilog2().max(2) - 1;
|
||||
let mip_height_ratio = if height != 0 {
|
||||
bloom.max_mip_dimension as f32 / height as f32
|
||||
let mip_height_ratio = if viewport.y != 0 {
|
||||
bloom.max_mip_dimension as f32 / viewport.y as f32
|
||||
} else {
|
||||
0.
|
||||
};
|
||||
|
||||
let texture_descriptor = TextureDescriptor {
|
||||
label: Some("bloom_texture"),
|
||||
size: Extent3d {
|
||||
width: ((width as f32 * mip_height_ratio).round() as u32).max(1),
|
||||
height: ((height as f32 * mip_height_ratio).round() as u32).max(1),
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
size: (viewport.as_vec2() * mip_height_ratio)
|
||||
.round()
|
||||
.as_uvec2()
|
||||
.max(UVec2::ONE)
|
||||
.to_extents(),
|
||||
mip_level_count: mip_count,
|
||||
sample_count: 1,
|
||||
dimension: TextureDimension::D2,
|
||||
|
||||
@ -227,7 +227,7 @@ impl ExtractComponent for Bloom {
|
||||
type QueryFilter = With<Hdr>;
|
||||
type Out = (Self, BloomUniforms);
|
||||
|
||||
fn extract_component((bloom, camera): QueryItem<'_, Self::QueryData>) -> Option<Self::Out> {
|
||||
fn extract_component((bloom, camera): QueryItem<'_, '_, Self::QueryData>) -> Option<Self::Out> {
|
||||
match (
|
||||
camera.physical_viewport_rect(),
|
||||
camera.physical_viewport_size(),
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
use crate::FullscreenShader;
|
||||
|
||||
use super::{
|
||||
downsampling_pipeline::BloomUniforms, Bloom, BloomCompositeMode, BLOOM_TEXTURE_FORMAT,
|
||||
};
|
||||
use crate::fullscreen_vertex_shader::fullscreen_shader_vertex_state;
|
||||
use bevy_asset::{load_embedded_asset, Handle};
|
||||
use bevy_ecs::{
|
||||
prelude::{Component, Entity},
|
||||
@ -17,6 +18,7 @@ use bevy_render::{
|
||||
renderer::RenderDevice,
|
||||
view::ViewTarget,
|
||||
};
|
||||
use bevy_utils::default;
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct UpsamplingPipelineIds {
|
||||
@ -27,8 +29,10 @@ pub struct UpsamplingPipelineIds {
|
||||
#[derive(Resource)]
|
||||
pub struct BloomUpsamplingPipeline {
|
||||
pub bind_group_layout: BindGroupLayout,
|
||||
/// The shader asset handle.
|
||||
pub shader: Handle<Shader>,
|
||||
/// The asset handle for the fullscreen vertex shader.
|
||||
pub fullscreen_shader: FullscreenShader,
|
||||
/// The fragment shader asset handle.
|
||||
pub fragment_shader: Handle<Shader>,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Hash, Clone)]
|
||||
@ -58,7 +62,8 @@ impl FromWorld for BloomUpsamplingPipeline {
|
||||
|
||||
BloomUpsamplingPipeline {
|
||||
bind_group_layout,
|
||||
shader: load_embedded_asset!(world, "bloom.wgsl"),
|
||||
fullscreen_shader: world.resource::<FullscreenShader>().clone(),
|
||||
fragment_shader: load_embedded_asset!(world, "bloom.wgsl"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -108,11 +113,10 @@ impl SpecializedRenderPipeline for BloomUpsamplingPipeline {
|
||||
RenderPipelineDescriptor {
|
||||
label: Some("bloom_upsampling_pipeline".into()),
|
||||
layout: vec![self.bind_group_layout.clone()],
|
||||
vertex: fullscreen_shader_vertex_state(),
|
||||
vertex: self.fullscreen_shader.to_vertex_state(),
|
||||
fragment: Some(FragmentState {
|
||||
shader: self.shader.clone(),
|
||||
shader_defs: vec![],
|
||||
entry_point: "upsample".into(),
|
||||
shader: self.fragment_shader.clone(),
|
||||
entry_point: Some("upsample".into()),
|
||||
targets: vec![Some(ColorTargetState {
|
||||
format: texture_format,
|
||||
blend: Some(BlendState {
|
||||
@ -125,12 +129,9 @@ impl SpecializedRenderPipeline for BloomUpsamplingPipeline {
|
||||
}),
|
||||
write_mask: ColorWrites::ALL,
|
||||
})],
|
||||
..default()
|
||||
}),
|
||||
primitive: PrimitiveState::default(),
|
||||
depth_stencil: None,
|
||||
multisample: MultisampleState::default(),
|
||||
push_constant_ranges: Vec::new(),
|
||||
zero_initialize_workgroup_memory: false,
|
||||
..default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user