Make vertex colors work without textures in bevy_sprite (#5685)

# Objective

This PR changes it possible to use vertex colors without a texture using the bevy_sprite ColorMaterial.

Fixes #5679 

## Solution

- Made multiplication of the output color independent of the COLOR_MATERIAL_FLAGS_TEXTURE_BIT bit
- Extended mesh2d_vertex_color_texture example to show off both vertex colors and tinting

Not sure if extending the existing example was the right call but it seems to be reasonable to me.

I couldn't find any tests for the shaders and I think adding shader testing would be beyond the scope of this PR. So no tests in this PR. 😬 

Co-authored-by: Jonas Wagner <jonas@29a.ch>
This commit is contained in:
Jonas Wagner 2022-08-16 20:46:45 +00:00
parent bd317ea364
commit 110831150e
2 changed files with 25 additions and 8 deletions

View file

@ -26,12 +26,11 @@ struct FragmentInput {
@fragment
fn fragment(in: FragmentInput) -> @location(0) vec4<f32> {
var output_color: vec4<f32> = material.color;
if ((material.flags & COLOR_MATERIAL_FLAGS_TEXTURE_BIT) != 0u) {
#ifdef VERTEX_COLORS
output_color = output_color * textureSample(texture, texture_sampler, in.uv) * in.color;
#else
output_color = output_color * textureSample(texture, texture_sampler, in.uv);
output_color = output_color * in.color;
#endif
if ((material.flags & COLOR_MATERIAL_FLAGS_TEXTURE_BIT) != 0u) {
output_color = output_color * textureSample(texture, texture_sampler, in.uv);
}
return output_color;
}

View file

@ -1,7 +1,10 @@
//! Shows how to render a polygonal [`Mesh`], generated from a [`Quad`] primitive, in a 2D scene.
//! Adds a texture and colored vertices, giving per-vertex tinting.
use bevy::{prelude::*, sprite::MaterialMesh2dBundle};
use bevy::{
prelude::*,
sprite::{MaterialMesh2dBundle, Mesh2dHandle},
};
fn main() {
App::new()
@ -29,11 +32,26 @@ fn setup(
];
// Insert the vertex colors as an attribute
mesh.insert_attribute(Mesh::ATTRIBUTE_COLOR, vertex_colors);
// Spawn
let mesh_handle: Mesh2dHandle = meshes.add(mesh).into();
// Spawn camera
commands.spawn_bundle(Camera2dBundle::default());
// Spawn the quad with vertex colors
commands.spawn_bundle(MaterialMesh2dBundle {
mesh: meshes.add(mesh).into(),
transform: Transform::default().with_scale(Vec3::splat(128.)),
mesh: mesh_handle.clone(),
transform: Transform::from_translation(Vec3::new(-96., 0., 0.))
.with_scale(Vec3::splat(128.)),
material: materials.add(ColorMaterial::default()),
..default()
});
// Spawning the quad with vertex colors and a texture results in tinting
commands.spawn_bundle(MaterialMesh2dBundle {
mesh: mesh_handle,
transform: Transform::from_translation(Vec3::new(96., 0., 0.))
.with_scale(Vec3::splat(128.)),
material: materials.add(ColorMaterial::from(texture_handle)),
..default()
});