Skip to content

Commit

Permalink
Fix wasm examples (bevyengine#4967)
Browse files Browse the repository at this point in the history
# Objective

Fix bevyengine#4958 

There was 4 issues:

- this is not true in WASM and on macOS: https://github.com/bevyengine/bevy/blob/f28b92120920f387020f3b3e858f0e7039b9c07e/examples/3d/split_screen.rs#L90
  - ~~I made sure the system was running at least once~~
  - I'm sending the event on window creation
- in webgl, setting a viewport has impacts on other render passes
  - only in webgl and when there is a custom viewport, I added a render pass without a custom viewport
- shaderdef NO_ARRAY_TEXTURES_SUPPORT was not used by the 2d pipeline
  - webgl feature was used but not declared in bevy_sprite, I added it to the Cargo.toml
- shaderdef NO_STORAGE_BUFFERS_SUPPORT was not used by the 2d pipeline
  - I added it based on the BufferBindingType

The last commit changes the two last fixes to add the shaderdefs in the shader cache directly instead of needing to do it in each pipeline

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
  • Loading branch information
2 people authored and LoipesMas committed Jun 12, 2022
1 parent 2717f9b commit 9ceaa96
Show file tree
Hide file tree
Showing 9 changed files with 107 additions and 59 deletions.
1 change: 1 addition & 0 deletions crates/bevy_core_pipeline/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ keywords = ["bevy"]

[features]
trace = []
webgl = []

[dependencies]
# bevy
Expand Down
78 changes: 52 additions & 26 deletions crates/bevy_core_pipeline/src/core_2d/main_pass_2d_node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ use bevy_render::{
renderer::RenderContext,
view::{ExtractedView, ViewTarget},
};
#[cfg(feature = "trace")]
use bevy_utils::tracing::info_span;

pub struct MainPass2dNode {
query: QueryState<
Expand Down Expand Up @@ -57,37 +59,61 @@ impl Node for MainPass2dNode {
// no target
return Ok(());
};
{
#[cfg(feature = "trace")]
let _main_pass_2d = info_span!("main_pass_2d").entered();
let pass_descriptor = RenderPassDescriptor {
label: Some("main_pass_2d"),
color_attachments: &[target.get_color_attachment(Operations {
load: match camera_2d.clear_color {
ClearColorConfig::Default => {
LoadOp::Clear(world.resource::<ClearColor>().0.into())
}
ClearColorConfig::Custom(color) => LoadOp::Clear(color.into()),
ClearColorConfig::None => LoadOp::Load,
},
store: true,
})],
depth_stencil_attachment: None,
};

let pass_descriptor = RenderPassDescriptor {
label: Some("main_pass_2d"),
color_attachments: &[target.get_color_attachment(Operations {
load: match camera_2d.clear_color {
ClearColorConfig::Default => {
LoadOp::Clear(world.resource::<ClearColor>().0.into())
}
ClearColorConfig::Custom(color) => LoadOp::Clear(color.into()),
ClearColorConfig::None => LoadOp::Load,
},
store: true,
})],
depth_stencil_attachment: None,
};

let draw_functions = world.resource::<DrawFunctions<Transparent2d>>();
let draw_functions = world.resource::<DrawFunctions<Transparent2d>>();

let render_pass = render_context
.command_encoder
.begin_render_pass(&pass_descriptor);
let render_pass = render_context
.command_encoder
.begin_render_pass(&pass_descriptor);

let mut draw_functions = draw_functions.write();
let mut tracked_pass = TrackedRenderPass::new(render_pass);
if let Some(viewport) = camera.viewport.as_ref() {
tracked_pass.set_camera_viewport(viewport);
let mut draw_functions = draw_functions.write();
let mut tracked_pass = TrackedRenderPass::new(render_pass);
if let Some(viewport) = camera.viewport.as_ref() {
tracked_pass.set_camera_viewport(viewport);
}
for item in &transparent_phase.items {
let draw_function = draw_functions.get_mut(item.draw_function).unwrap();
draw_function.draw(world, &mut tracked_pass, view_entity, item);
}
}
for item in &transparent_phase.items {
let draw_function = draw_functions.get_mut(item.draw_function).unwrap();
draw_function.draw(world, &mut tracked_pass, view_entity, item);

// WebGL2 quirk: if ending with a render pass with a custom viewport, the viewport isn't
// reset for the next render pass so add an empty render pass without a custom viewport
#[cfg(feature = "webgl")]
if camera.viewport.is_some() {
#[cfg(feature = "trace")]
let _reset_viewport_pass_2d = info_span!("reset_viewport_pass_2d").entered();
let pass_descriptor = RenderPassDescriptor {
label: Some("reset_viewport_pass_2d"),
color_attachments: &[target.get_color_attachment(Operations {
load: LoadOp::Load,
store: true,
})],
depth_stencil_attachment: None,
};

render_context
.command_encoder
.begin_render_pass(&pass_descriptor);
}

Ok(())
}
}
20 changes: 20 additions & 0 deletions crates/bevy_core_pipeline/src/core_3d/main_pass_3d_node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,26 @@ impl Node for MainPass3dNode {
}
}

// WebGL2 quirk: if ending with a render pass with a custom viewport, the viewport isn't
// reset for the next render pass so add an empty render pass without a custom viewport
#[cfg(feature = "webgl")]
if camera.viewport.is_some() {
#[cfg(feature = "trace")]
let _reset_viewport_pass_3d = info_span!("reset_viewport_pass_3d").entered();
let pass_descriptor = RenderPassDescriptor {
label: Some("reset_viewport_pass_3d"),
color_attachments: &[target.get_color_attachment(Operations {
load: LoadOp::Load,
store: true,
})],
depth_stencil_attachment: None,
};

render_context
.command_encoder
.begin_render_pass(&pass_descriptor);
}

Ok(())
}
}
2 changes: 1 addition & 1 deletion crates/bevy_internal/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ x11 = ["bevy_winit/x11"]
subpixel_glyph_atlas = ["bevy_text/subpixel_glyph_atlas"]

# Optimise for WebGL2
webgl = ["bevy_pbr/webgl", "bevy_render/webgl"]
webgl = ["bevy_core_pipeline/webgl", "bevy_pbr/webgl", "bevy_render/webgl"]

# enable systems that allow for automated testing on CI
bevy_ci_testing = ["bevy_app/bevy_ci_testing", "bevy_render/ci_limits"]
Expand Down
12 changes: 0 additions & 12 deletions crates/bevy_pbr/src/render/light.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,6 @@ pub struct ShadowPipeline {
pub skinned_mesh_layout: BindGroupLayout,
pub point_light_sampler: Sampler,
pub directional_light_sampler: Sampler,
pub clustered_forward_buffer_binding_type: BufferBindingType,
}

// TODO: this pattern for initializing the shaders / pipeline isn't ideal. this should be handled by the asset system
Expand All @@ -221,9 +220,6 @@ impl FromWorld for ShadowPipeline {
let world = world.cell();
let render_device = world.resource::<RenderDevice>();

let clustered_forward_buffer_binding_type = render_device
.get_supported_read_only_binding_type(CLUSTERED_FORWARD_STORAGE_BUFFER_COUNT);

let view_layout = render_device.create_bind_group_layout(&BindGroupLayoutDescriptor {
entries: &[
// View
Expand Down Expand Up @@ -268,7 +264,6 @@ impl FromWorld for ShadowPipeline {
compare: Some(CompareFunction::GreaterEqual),
..Default::default()
}),
clustered_forward_buffer_binding_type,
}
}
}
Expand Down Expand Up @@ -330,13 +325,6 @@ impl SpecializedMeshPipeline for ShadowPipeline {
bind_group_layout.push(self.mesh_layout.clone());
}

if !matches!(
self.clustered_forward_buffer_binding_type,
BufferBindingType::Storage { .. }
) {
shader_defs.push(String::from("NO_STORAGE_BUFFERS_SUPPORT"));
}

let vertex_buffer_layout = layout.get_layout(&vertex_attributes)?;

Ok(RenderPipelineDescriptor {
Expand Down
15 changes: 0 additions & 15 deletions crates/bevy_pbr/src/render/mesh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -582,18 +582,6 @@ impl SpecializedMeshPipeline for MeshPipeline {
vertex_attributes.push(Mesh::ATTRIBUTE_COLOR.at_shader_location(4));
}

// TODO: consider exposing this in shaders in a more generally useful way, such as:
// # if AVAILABLE_STORAGE_BUFFER_BINDINGS == 3
// /* use storage buffers here */
// # elif
// /* use uniforms here */
if !matches!(
self.clustered_forward_buffer_binding_type,
BufferBindingType::Storage { .. }
) {
shader_defs.push(String::from("NO_STORAGE_BUFFERS_SUPPORT"));
}

let mut bind_group_layout = vec![self.view_layout.clone()];
if layout.contains(Mesh::ATTRIBUTE_JOINT_INDEX)
&& layout.contains(Mesh::ATTRIBUTE_JOINT_WEIGHT)
Expand Down Expand Up @@ -624,9 +612,6 @@ impl SpecializedMeshPipeline for MeshPipeline {
depth_write_enabled = true;
}

#[cfg(feature = "webgl")]
shader_defs.push(String::from("NO_ARRAY_TEXTURES_SUPPORT"));

Ok(RenderPipelineDescriptor {
vertex: VertexState {
shader: MESH_SHADER_HANDLE.typed::<Shader>(),
Expand Down
24 changes: 22 additions & 2 deletions crates/bevy_render/src/render_resource/pipeline_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ use bevy_ecs::system::{Res, ResMut};
use bevy_utils::{default, tracing::error, Entry, HashMap, HashSet};
use std::{hash::Hash, iter::FusedIterator, mem, ops::Deref, sync::Arc};
use thiserror::Error;
use wgpu::{PipelineLayoutDescriptor, ShaderModule, VertexBufferLayout as RawVertexBufferLayout};
use wgpu::{
BufferBindingType, PipelineLayoutDescriptor, ShaderModule,
VertexBufferLayout as RawVertexBufferLayout,
};

enum PipelineDescriptor {
RenderPipelineDescriptor(Box<RenderPipelineDescriptor>),
Expand Down Expand Up @@ -117,9 +120,26 @@ impl ShaderCache {
let module = match data.processed_shaders.entry(shader_defs.to_vec()) {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => {
let mut shader_defs = shader_defs.to_vec();
#[cfg(feature = "webgl")]
shader_defs.push(String::from("NO_ARRAY_TEXTURES_SUPPORT"));

// TODO: 3 is the value from CLUSTERED_FORWARD_STORAGE_BUFFER_COUNT declared in bevy_pbr
// consider exposing this in shaders in a more generally useful way, such as:
// # if AVAILABLE_STORAGE_BUFFER_BINDINGS == 3
// /* use storage buffers here */
// # elif
// /* use uniforms here */
if !matches!(
render_device.get_supported_read_only_binding_type(3),
BufferBindingType::Storage { .. }
) {
shader_defs.push(String::from("NO_STORAGE_BUFFERS_SUPPORT"));
}

let processed = self.processor.process(
shader,
shader_defs,
&shader_defs,
&self.shaders,
&self.import_path_shaders,
)?;
Expand Down
3 changes: 0 additions & 3 deletions crates/bevy_sprite/src/mesh2d/mesh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,9 +323,6 @@ impl SpecializedMeshPipeline for Mesh2dPipeline {
vertex_attributes.push(Mesh::ATTRIBUTE_COLOR.at_shader_location(4));
}

#[cfg(feature = "webgl")]
shader_defs.push(String::from("NO_ARRAY_TEXTURES_SUPPORT"));

let vertex_buffer_layout = layout.get_layout(&vertex_attributes)?;

Ok(RenderPipelineDescriptor {
Expand Down
11 changes: 11 additions & 0 deletions crates/bevy_winit/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -637,12 +637,23 @@ fn handle_create_window_events(
let mut windows = world.resource_mut::<Windows>();
let create_window_events = world.resource::<Events<CreateWindow>>();
let mut window_created_events = world.resource_mut::<Events<WindowCreated>>();
#[cfg(not(any(target_os = "windows", target_feature = "x11")))]
let mut window_resized_events = world.resource_mut::<Events<WindowResized>>();
for create_window_event in create_window_event_reader.iter(&create_window_events) {
let window = winit_windows.create_window(
event_loop,
create_window_event.id,
&create_window_event.descriptor,
);
// This event is already sent on windows, x11, and xwayland.
// TODO: we aren't yet sure about native wayland, so we might be able to exclude it,
// but sending a duplicate event isn't problematic, as windows already does this.
#[cfg(not(any(target_os = "windows", target_feature = "x11")))]
window_resized_events.send(WindowResized {
id: create_window_event.id,
width: window.width(),
height: window.height(),
});
windows.add(window);
window_created_events.send(WindowCreated {
id: create_window_event.id,
Expand Down

0 comments on commit 9ceaa96

Please sign in to comment.