Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Omnilight shadow map wgsl #15

Merged
merged 3 commits into from
Jul 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/bevy_wgpu/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ bevy_winit = { path = "../bevy_winit", optional = true, version = "0.5.0" }
bevy_utils = { path = "../bevy_utils", version = "0.5.0" }

# other
wgpu = "0.8"
wgpu = "0.9"
futures-lite = "1.4.0"
crossbeam-channel = "0.5.0"
crossbeam-utils = "0.8.1"
Expand Down
117 changes: 109 additions & 8 deletions examples/3d/3d_scene_pipelined.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ use bevy::{
diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
ecs::prelude::*,
input::Input,
math::Vec3,
pbr2::{OmniLightBundle, PbrBundle, StandardMaterial},
prelude::{App, Assets, KeyCode, Transform},
math::{Quat, Vec3},
pbr2::{OmniLight, OmniLightBundle, PbrBundle, StandardMaterial},
prelude::{App, Assets, BuildChildren, KeyCode, Transform},
render2::{
camera::PerspectiveCameraBundle,
color::Color,
Expand Down Expand Up @@ -42,6 +42,32 @@ fn setup(
}),
..Default::default()
});

let mut transform = Transform::from_xyz(2.5, 2.5, 0.0);
transform.rotate(Quat::from_rotation_z(std::f32::consts::FRAC_PI_2));
commands.spawn_bundle(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Plane { size: 5.0 })),
transform,
material: materials.add(StandardMaterial {
base_color: Color::INDIGO,
perceptual_roughness: 1.0,
..Default::default()
}),
..Default::default()
});

let mut transform = Transform::from_xyz(0.0, 2.5, -2.5);
transform.rotate(Quat::from_rotation_x(std::f32::consts::FRAC_PI_2));
commands.spawn_bundle(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Plane { size: 5.0 })),
transform,
material: materials.add(StandardMaterial {
base_color: Color::INDIGO,
perceptual_roughness: 1.0,
..Default::default()
}),
..Default::default()
});
// cube
commands
.spawn_bundle(PbrBundle {
Expand Down Expand Up @@ -69,14 +95,89 @@ fn setup(
..Default::default()
})
.insert(Movable);

// light
commands.spawn_bundle(OmniLightBundle {
transform: Transform::from_xyz(5.0, 8.0, 2.0),
..Default::default()
});
commands
.spawn_bundle(OmniLightBundle {
// transform: Transform::from_xyz(5.0, 8.0, 2.0),
transform: Transform::from_xyz(1.0, 2.0, 0.0),
omni_light: OmniLight {
color: Color::RED,
..Default::default()
},
..Default::default()
})
.with_children(|builder| {
builder.spawn_bundle(PbrBundle {
mesh: meshes.add(Mesh::from(shape::UVSphere {
radius: 0.1,
..Default::default()
})),
material: materials.add(StandardMaterial {
base_color: Color::RED,
emissive: Color::rgba_linear(100.0, 0.0, 0.0, 0.0),
..Default::default()
}),
..Default::default()
});
});

// light
commands
.spawn_bundle(OmniLightBundle {
// transform: Transform::from_xyz(5.0, 8.0, 2.0),
transform: Transform::from_xyz(-1.0, 2.0, 0.0),
omni_light: OmniLight {
color: Color::GREEN,
..Default::default()
},
..Default::default()
})
.with_children(|builder| {
builder.spawn_bundle(PbrBundle {
mesh: meshes.add(Mesh::from(shape::UVSphere {
radius: 0.1,
..Default::default()
})),
material: materials.add(StandardMaterial {
base_color: Color::GREEN,
emissive: Color::rgba_linear(0.0, 100.0, 0.0, 0.0),
..Default::default()
}),
..Default::default()
});
});

// light
commands
.spawn_bundle(OmniLightBundle {
// transform: Transform::from_xyz(5.0, 8.0, 2.0),
transform: Transform::from_xyz(0.0, 4.0, 0.0),
omni_light: OmniLight {
color: Color::BLUE,
..Default::default()
},
..Default::default()
})
.with_children(|builder| {
builder.spawn_bundle(PbrBundle {
mesh: meshes.add(Mesh::from(shape::UVSphere {
radius: 0.1,
..Default::default()
})),
material: materials.add(StandardMaterial {
base_color: Color::BLUE,
emissive: Color::rgba_linear(0.0, 0.0, 100.0, 0.0),
..Default::default()
}),
..Default::default()
});
});

// camera
commands.spawn_bundle(PerspectiveCameraBundle {
transform: Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
transform: Transform::from_xyz(-2.0, 5.0, 7.5)
.looking_at(Vec3::new(0.0, 2.0, 0.0), Vec3::Y),
..Default::default()
});
}
Expand Down
165 changes: 116 additions & 49 deletions pipelined/bevy_pbr2/src/render/light.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{AmbientLight, ExtractedMeshes, MeshMeta, OmniLight, PbrShaders};
use bevy_ecs::{prelude::*, system::SystemState};
use bevy_math::{Mat4, Vec3, Vec4};
use bevy_math::{const_vec3, Mat4, Vec3, Vec4};
use bevy_render2::{
color::Color,
core_pipeline::Transparent3dPhase,
Expand Down Expand Up @@ -34,10 +34,12 @@ pub struct ExtractedPointLight {
#[derive(Copy, Clone, AsStd140, Default, Debug)]
pub struct GpuLight {
color: Vec4,
range: f32,
radius: f32,
// proj: Mat4,
position: Vec3,
view_proj: Mat4,
inverse_square_range: f32,
radius: f32,
near: f32,
far: f32,
}

#[repr(C)]
Expand All @@ -54,7 +56,7 @@ pub const MAX_OMNI_LIGHTS: usize = 10;
pub const SHADOW_SIZE: Extent3d = Extent3d {
width: 1024,
height: 1024,
depth_or_array_layers: MAX_OMNI_LIGHTS as u32,
depth_or_array_layers: 6 * MAX_OMNI_LIGHTS as u32,
};
pub const SHADOW_FORMAT: TextureFormat = TextureFormat::Depth32Float;

Expand Down Expand Up @@ -148,7 +150,7 @@ impl FromWorld for ShadowShaders {
topology: PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: FrontFace::Ccw,
cull_mode: Some(Face::Back),
cull_mode: None,
polygon_mode: PolygonMode::Fill,
clamp_depth: false,
conservative: false,
Expand Down Expand Up @@ -193,8 +195,52 @@ pub fn extract_lights(
}
}

// Can't do `Vec3::Y * -1.0` because mul isn't const
const NEGATIVE_X: Vec3 = const_vec3!([-1.0, 0.0, 0.0]);
const NEGATIVE_Y: Vec3 = const_vec3!([0.0, -1.0, 0.0]);
const NEGATIVE_Z: Vec3 = const_vec3!([0.0, 0.0, -1.0]);

struct CubeMapFace {
target: Vec3,
up: Vec3,
}

// see https://www.khronos.org/opengl/wiki/Cubemap_Texture
const CUBE_MAP_FACES: [CubeMapFace; 6] = [
// 0 GL_TEXTURE_CUBE_MAP_POSITIVE_X
CubeMapFace {
target: NEGATIVE_X,
up: NEGATIVE_Y,
},
// 1 GL_TEXTURE_CUBE_MAP_NEGATIVE_X
CubeMapFace {
target: Vec3::X,
up: NEGATIVE_Y,
},
// 2 GL_TEXTURE_CUBE_MAP_POSITIVE_Y
CubeMapFace {
target: NEGATIVE_Y,
up: Vec3::Z,
},
// 3 GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
CubeMapFace {
target: Vec3::Y,
up: NEGATIVE_Z,
},
// 4 GL_TEXTURE_CUBE_MAP_POSITIVE_Z
CubeMapFace {
target: NEGATIVE_Z,
up: NEGATIVE_Y,
},
// 5 GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
CubeMapFace {
target: Vec3::Z,
up: NEGATIVE_Y,
},
];

pub struct ViewLight {
pub depth_texture: TextureView,
pub depth_texture_view: TextureView,
}

pub struct ViewLights {
Expand Down Expand Up @@ -248,59 +294,79 @@ pub fn prepare_lights(
};

// TODO: this should select lights based on relevance to the view instead of the first ones that show up in a query
for (i, light) in lights.iter().enumerate().take(MAX_OMNI_LIGHTS) {
let depth_texture_view =
light_depth_texture
.texture
.create_view(&TextureViewDescriptor {
label: None,
format: None,
dimension: Some(TextureViewDimension::D2),
aspect: TextureAspect::All,
base_mip_level: 0,
mip_level_count: None,
base_array_layer: i as u32,
array_layer_count: NonZeroU32::new(1),
});

let view_transform = GlobalTransform::from_translation(light.transform.translation)
.looking_at(Vec3::default(), Vec3::Y);
// TODO: configure light projection based on light configuration
for (light_index, light) in lights.iter().enumerate().take(MAX_OMNI_LIGHTS) {
let projection =
Mat4::perspective_rh(std::f32::consts::FRAC_PI_2, 1.0, 0.1, light.range);

gpu_lights.lights[i] = GpuLight {
// ignore scale because we don't want to effectively scale light radius and range
// by applying those as a view transform to shadow map rendering of objects
// and ignore rotation because we want the shadow map projections to align with the axes
let view_translation = GlobalTransform::from_translation(light.transform.translation);

for (face_index, CubeMapFace { target, up }) in CUBE_MAP_FACES.iter().enumerate() {
// use the cubemap projection direction
let view_rotation = GlobalTransform::identity().looking_at(*target, *up);

let depth_texture_view =
light_depth_texture
.texture
.create_view(&TextureViewDescriptor {
label: None,
format: None,
dimension: Some(TextureViewDimension::D2),
aspect: TextureAspect::All,
base_mip_level: 0,
mip_level_count: None,
base_array_layer: (light_index * 6 + face_index) as u32,
array_layer_count: NonZeroU32::new(1),
});

let view_light_entity = commands
.spawn()
.insert_bundle((
ViewLight { depth_texture_view },
ExtractedView {
width: SHADOW_SIZE.width,
height: SHADOW_SIZE.height,
transform: view_translation * view_rotation,
projection,
},
RenderPhase::<ShadowPhase>::default(),
))
.id();
view_lights.push(view_light_entity);
}

gpu_lights.lights[light_index] = GpuLight {
// premultiply color by intensity
// we don't use the alpha at all, so no reason to multiply only [0..3]
color: (light.color.as_rgba_linear() * light.intensity).into(),
radius: light.radius.into(),
position: light.transform.translation.into(),
range: 1.0 / (light.range * light.range),
// this could technically be copied to the gpu from the light's ViewUniforms
view_proj: projection * view_transform.compute_matrix().inverse(),
inverse_square_range: 1.0 / (light.range * light.range),
near: 0.1,
far: light.range,
// proj: projection,
};

let view_light_entity = commands
.spawn()
.insert_bundle((
ViewLight {
depth_texture: depth_texture_view,
},
ExtractedView {
width: SHADOW_SIZE.width,
height: SHADOW_SIZE.height,
transform: view_transform.clone(),
projection,
},
RenderPhase::<ShadowPhase>::default(),
))
.id();
view_lights.push(view_light_entity);
}

let light_depth_texture_view =
light_depth_texture
.texture
.create_view(&TextureViewDescriptor {
label: None,
format: None,
dimension: Some(TextureViewDimension::CubeArray),
aspect: TextureAspect::All,
base_mip_level: 0,
mip_level_count: None,
base_array_layer: 0 as u32,
array_layer_count: None,
});

commands.entity(entity).insert(ViewLights {
light_depth_texture: light_depth_texture.texture,
light_depth_texture_view: light_depth_texture.default_view,
light_depth_texture_view,
lights: view_lights,
gpu_light_binding_index: light_meta.view_gpu_lights.push(gpu_lights),
});
Expand Down Expand Up @@ -356,7 +422,7 @@ impl Node for ShadowPassNode {
label: Some("shadow_pass"),
color_attachments: &[],
depth_stencil_attachment: Some(RenderPassDepthStencilAttachment {
view: &view_light.depth_texture,
view: &view_light.depth_texture_view,
depth_ops: Some(Operations {
load: LoadOp::Clear(1.0),
store: true,
Expand Down Expand Up @@ -422,7 +488,8 @@ impl Draw for DrawShadowMesh {
self.params.get(world);
let view_uniform_offset = views.get(view).unwrap();
let extracted_mesh = &extracted_meshes.into_inner().meshes[draw_key];
pass.set_render_pipeline(&shadow_shaders.into_inner().pipeline);
let shadow_shaders = shadow_shaders.into_inner();
pass.set_render_pipeline(&shadow_shaders.pipeline);
pass.set_bind_group(
0,
light_meta
Expand Down
Loading