A double-sided `StandardMaterial` without a normal map shades back faces with the front normal when the mesh has tangents
Maintainers usually reply within 2 days
Nobody has claimed this yet.
Assessment
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Newbie friendliness
- 72/100
- Issue type
- Bug
- Clarity
- Clearly specified
- Activity status
- Active
- Tech stack
- rust
- Domain
- computer-graphics
Research direction
Read crates/bevy_pbr/src/render/pbr_functions.wesl, especially prepare_world_normal, and compare its back-face normal flip condition with the fragment shader and prepass calls to apply_normal_mapping. The issue identifies the missing case: meshes with tangents and no normal map. Adjust the condition so the normal is flipped whenever normal mapping does not handle it, then verify that the provided reproduction shades both back faces consistently.
Written by the indexing model from the issue text.
Description
Bevy version and features
0.20.1, with the features in the Cargo.toml below. The shaders involved are unchanged on main (42265b2).
What you did
Rendered two quads with one lit, double-sided StandardMaterial without a normal map (double_sided: true, cull_mode: None), lit and viewed from +Z: the left quad's mesh has no tangents, the right quad's mesh has them from with_generated_tangents(). Then turned both quads 180 degrees to show their back faces.
What went wrong
The back face of the quad with tangents shades black, while the one without tangents shades white, as both front faces do:
=== Bevy 0.20.1 Reproduction 03: Double-Sided Back-Face Shading With vs Without Tangents ===
material: StandardMaterial { double_sided: true, cull_mode: None, normal_map_texture: None, roughness: 1.0, reflectance: 0.0 }
light_and_camera: +Z looking toward -Z (GlobalAmbientLight brightness = 0.0, Tonemapping::None)
front_face (rot_y = 0 deg, is_front = true): without_tangents_srgb = [255, 255, 255], with_tangents_srgb = [255, 255, 255]
back_face (rot_y = 180 deg, is_front = false): without_tangents_srgb = [255, 255, 255], with_tangents_srgb = [0, 0, 0]
back_face_mean_channel_delta: 255 (without tangents = 255, with tangents = 0)
prepare_world_normal (crates/bevy_pbr/src/render/pbr_functions.wesl) flips a double-sided back face's normal only @if(!VERTEX_TANGENTS && !STANDARD_MATERIAL_NORMAL_MAP), leaving the flip to apply_normal_mapping otherwise; but the fragment shader and the prepass call apply_normal_mapping only @if(VERTEX_UVS && VERTEX_TANGENTS && STANDARD_MATERIAL_NORMAL_MAP). A mesh with tangents and a material without a normal map falls between the two, and its back faces keep the front face's normal. glTF meshes exported with tangents meet this.
Additional information
Making prepare_world_normal's condition the complement of the one that calls apply_normal_mapping, @if(!(VERTEX_UVS && VERTEX_TANGENTS && STANDARD_MATERIAL_NORMAL_MAP)), flips the normal whenever nothing else does.
Reproduction: Cargo.toml and src/main.rs
[package]
name = "bevy-repros"
version = "0.1.0"
edition = "2024"
publish = false
[dependencies]
bevy = { version = "0.20.1", default-features = false, features = [
"std",
"async_executor",
"multi_threaded",
"reflect_auto_register",
"bevy_asset",
"bevy_camera",
"bevy_color",
"bevy_core_pipeline",
"bevy_image",
"bevy_light",
"bevy_log",
"bevy_material",
"bevy_mesh",
"bevy_mikktspace",
"bevy_pbr",
"bevy_post_process",
"bevy_render",
"bevy_shader",
"bevy_window",
"bevy_winit",
"bluenoise_texture",
"ktx2",
"tonemapping_luts",
"zstd_rust",
] }
//! Minimal headless reproduction for Bevy 0.20.1:
//! A lit double-sided `StandardMaterial` without a normal map shades its back faces
//! differently depending on whether its `Mesh` carries `Mesh::ATTRIBUTE_TANGENT`.
//!
//! Upstream root cause (`crates/bevy_pbr/src/render/pbr_functions.wesl:126-137`):
//! `prepare_world_normal` guards back-face normal negation (`if !is_front { N = -N; }`)
//! behind `@if(!VERTEX_TANGENTS && !STANDARD_MATERIAL_NORMAL_MAP)`, while
//! `apply_normal_mapping` only runs when `STANDARD_MATERIAL_NORMAL_MAP` is also defined.
//! Consequently, when `VERTEX_TANGENTS` is present and `STANDARD_MATERIAL_NORMAL_MAP` is
//! absent, neither function flips the normal for `!is_front` fragments.
use std::f32::consts::PI;
use bevy::{
camera::{RenderTarget, ScalingMode},
core_pipeline::tonemapping::Tonemapping,
log::LogPlugin,
prelude::*,
render::{
RenderApp,
gpu_readback::{Readback, ReadbackComplete},
pipelined_rendering::PipelinedRenderingPlugin,
render_resource::{PipelineCache, TextureFormat, TextureUsages},
},
window::ExitCondition,
winit::WinitPlugin,
};
const WIDTH: u32 = 128;
const HEIGHT: u32 = 64;
#[derive(Resource, Default)]
struct ReadbackCapture {
frames_received: u32,
pixels: Vec<u8>,
}
#[derive(Component)]
struct TestQuad;
fn sample_rgb(pixels: &[u8], x: u32, y: u32) -> [u8; 3] {
let idx = ((y * WIDTH + x) * 4) as usize;
[pixels[idx], pixels[idx + 1], pixels[idx + 2]]
}
fn render_and_capture(app: &mut App) -> Vec<u8> {
// Queue any newly needed pipelines and wait until async shader compilation finishes.
for _ in 0..3 {
app.update();
}
for _ in 0..200 {
let waiting = app
.sub_app(RenderApp)
.world()
.resource::<PipelineCache>()
.waiting_pipelines()
.count();
if waiting == 0 {
break;
}
std::thread::sleep(std::time::Duration::from_millis(5));
app.update();
}
// Run 4 post-compilation frames so GPU readback captures the fully rendered scene.
let baseline = app.world().resource::<ReadbackCapture>().frames_received;
for _ in 0..4 {
app.update();
}
let capture = app.world().resource::<ReadbackCapture>();
assert!(
capture.frames_received > baseline && capture.pixels.len() == (WIDTH * HEIGHT * 4) as usize,
"expected headless GPU readback buffer to populate"
);
capture.pixels.clone()
}
fn main() {
let mut app = App::new();
app.insert_resource(ClearColor(Color::BLACK))
.insert_resource(GlobalAmbientLight {
color: Color::WHITE,
brightness: 0.0,
affects_lightmapped_meshes: false,
})
.init_resource::<ReadbackCapture>()
.add_plugins(
DefaultPlugins
.set(WindowPlugin {
primary_window: None,
exit_condition: ExitCondition::DontExit,
..default()
})
.disable::<WinitPlugin>()
.disable::<PipelinedRenderingPlugin>()
.disable::<LogPlugin>(),
);
app.finish();
app.cleanup();
{
let world = app.world_mut();
let mut target =
Image::new_target_texture(WIDTH, HEIGHT, TextureFormat::Rgba8UnormSrgb, None);
target.texture_descriptor.usage |= TextureUsages::COPY_SRC;
let target_handle = world.resource_mut::<Assets<Image>>().add(target);
// Identical lit, double-sided, non-normal-mapped material shared by both quads.
let shared_material = world
.resource_mut::<Assets<StandardMaterial>>()
.add(StandardMaterial {
base_color: Color::WHITE,
perceptual_roughness: 1.0,
reflectance: 0.0,
double_sided: true,
cull_mode: None,
normal_map_texture: None,
..default()
});
// Left quad: no vertex tangents (`Rectangle` default: POSITION, NORMAL, UV_0).
let mesh_no_tangents: Mesh = Rectangle::new(1.6, 1.6).into();
let has_tangents_left = mesh_no_tangents.contains_attribute(Mesh::ATTRIBUTE_TANGENT);
// Right quad: exact same geometry with generated Mikktspace vertex tangents.
let mesh_with_tangents = mesh_no_tangents
.clone()
.with_generated_tangents()
.expect("rectangle tangents");
let has_tangents_right = mesh_with_tangents.contains_attribute(Mesh::ATTRIBUTE_TANGENT);
assert!(!has_tangents_left && has_tangents_right);
let left_handle = world.resource_mut::<Assets<Mesh>>().add(mesh_no_tangents);
let right_handle = world.resource_mut::<Assets<Mesh>>().add(mesh_with_tangents);
world.spawn((
TestQuad,
Mesh3d(left_handle),
MeshMaterial3d(shared_material.clone()),
Transform::from_xyz(-1.0, 0.0, 0.0),
));
world.spawn((
TestQuad,
Mesh3d(right_handle),
MeshMaterial3d(shared_material),
Transform::from_xyz(1.0, 0.0, 0.0),
));
// Directional light shining from +Z toward -Z (same side as the camera).
world.spawn((
DirectionalLight {
illuminance: 10_000.0,
shadow_maps_enabled: false,
..default()
},
Transform::from_xyz(0.0, 0.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
));
world.spawn((
Camera3d::default(),
Projection::from(OrthographicProjection {
scaling_mode: ScalingMode::FixedVertical {
viewport_height: 2.0,
},
..OrthographicProjection::default_3d()
}),
RenderTarget::Image(target_handle.clone().into()),
Tonemapping::None,
Transform::from_xyz(0.0, 0.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
));
world
.spawn(Readback::texture(target_handle))
.observe(|event: On<ReadbackComplete>, mut capture: ResMut<ReadbackCapture>| {
capture.frames_received += 1;
capture.pixels = event.data.clone();
});
}
// Pass 1: rotation_y = 0 rad (`is_front == true`, geometric +Z normal faces the light).
let front_pixels = render_and_capture(&mut app);
let front_no_tangents = sample_rgb(&front_pixels, WIDTH / 4, HEIGHT / 2);
let front_with_tangents = sample_rgb(&front_pixels, (WIDTH * 3) / 4, HEIGHT / 2);
// Pass 2: rotate both quads 180 deg around Y (`is_front == false`, back faces face the light).
{
let world = app.world_mut();
let mut query = world.query_filtered::<&mut Transform, With<TestQuad>>();
for mut transform in query.iter_mut(world) {
transform.rotation = Quat::from_rotation_y(PI);
}
}
let back_pixels = render_and_capture(&mut app);
let back_no_tangents = sample_rgb(&back_pixels, WIDTH / 4, HEIGHT / 2);
let back_with_tangents = sample_rgb(&back_pixels, (WIDTH * 3) / 4, HEIGHT / 2);
println!("=== Bevy 0.20.1 Reproduction 03: Double-Sided Back-Face Shading With vs Without Tangents ===");
println!("material: StandardMaterial {{ double_sided: true, cull_mode: None, normal_map_texture: None, roughness: 1.0, reflectance: 0.0 }}");
println!("light_and_camera: +Z looking toward -Z (GlobalAmbientLight brightness = 0.0, Tonemapping::None)");
println!(
"front_face (rot_y = 0 deg, is_front = true): without_tangents_srgb = {:?}, with_tangents_srgb = {:?}",
front_no_tangents, front_with_tangents
);
println!(
"back_face (rot_y = 180 deg, is_front = false): without_tangents_srgb = {:?}, with_tangents_srgb = {:?}",
back_no_tangents, back_with_tangents
);
let luma_back_no_tan =
(back_no_tangents[0] as i32 + back_no_tangents[1] as i32 + back_no_tangents[2] as i32) / 3;
let luma_back_with_tan = (back_with_tangents[0] as i32
+ back_with_tangents[1] as i32
+ back_with_tangents[2] as i32)
/ 3;
println!(
"back_face_mean_channel_delta: {} (without tangents = {}, with tangents = {})",
(luma_back_no_tan - luma_back_with_tan).abs(),
luma_back_no_tan,
luma_back_with_tan
);
assert_eq!(
front_no_tangents, front_with_tangents,
"front faces should shade identically"
);
assert!(
back_no_tangents[0] > 200 && back_with_tangents == [0, 0, 0],
"expected tangentless back face to be lit and tangent-carrying back face to shade dark (N dot L <= 0)"
);
}
- Dominant language
- Rust
- Stars
- 49.8k
- Forks
- 5.1k
- Avg merge
- 3d 4h
- Merged PRs (30d)
- 136
Getting set up
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from bevyengine/bevy
-
Difficulty 2/5 1-3 hours Newbie friendliness 70/100
bevyengine/bevy#26642 ·
Maintainers usually reply within 2 days
-
Difficulty 2/5 1-3 hours Newbie friendliness 70/100
bevyengine/bevy#26641 ·
Maintainers usually reply within 2 days
-
A-Animation AI-Assisted C-Bug D-Trivial S-Needs-Triage
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
bevyengine/bevy#26637 ·
Maintainers usually reply within 2 days
-
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
bevyengine/bevy#26635 ·
Maintainers usually reply within 2 days
-
Feathers checkbox outline should have flex_shrink: 0Possibly taken @Tatsuya0330 claimed this today. OpenC-Bug S-Needs-Triage
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
bevyengine/bevy#26630 ·
Maintainers usually reply within 2 days
Similar issues
-
go good first issue test
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
Maintainers usually reply within 2 days
-
bug triaged tui ux wontfix
Difficulty 2/5 Half a day Newbie friendliness 70/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
Maintainers usually reply within 1 day