DEV Community

Masahiro Morino
Masahiro Morino

Posted on AI-assisted

Making Grass Shadows Cheaper in Bevy: Why Gaussian Uses Nine Samples

I use Bevy to experiment with rendering and shaders. While working on grass, I noticed how much the filter setting changes the edges of the shadows falling across the blades. What changes in the renderer when you flip that one setting?

Changing the filter on grass and measuring the difference

In my vegetation lab, I switched the filter used by grass to receive shadows between Gaussian and Hardware2x2. The trees and ground kept using Gaussian.

The same vegetation scene with Gaussian on the left and Hardware2x2 on the right

The left image uses Gaussian, and the right uses Hardware2x2. Look at the grass in the foreground. The right image has thin, dark shadows across the blades. On the left, the transition from light to shade is smoother.

On the GPU, the main pass that draws opaque objects, including the grass, was about 0.96 ms shorter with Hardware2x2 when comparing the median results. The passes that draw the shadow maps took nearly the same time.

GPU pass Gaussian Hardware2x2
Main opaque pass 5.858 ms 4.898 ms
Shadow map pass (cascade 0) 0.251 ms 0.252 ms
Shadow map pass (cascade 1) 0.229 ms 0.232 ms

For this comparison I used Bevy's standard PBR lighting on the grass. I ran the same release build on an Apple M2 Pro using Metal. I fixed the camera and rendered offscreen at 2560×1600 with 4× MSAA. I used seed 42 for both grass layouts and turned off the wind.

I ran each filter four times, varying the order. The table gives the median of the four per-run medians. The main pass was shorter with Hardware2x2 in three of the four pairs. The order reversed in the final pair.

Drawing a shadow map and reading it

A shadow map is an image that stores the depth of the nearest surface seen from the light. If the sun sees a blade of grass in front of a patch of ground, the map records the depth of the blade. When drawing the ground, we can tell the blade blocks the light if the ground point is farther away than the stored depth.

In this scene, I split the view into two distance ranges from the camera and use a shadow map for each. The two passes labeled cascade 0 and cascade 1 in the table correspond to those ranges. Bevy's shadow pass

The main pass does the same depth comparison when lighting the grass. It transforms the position on the blade into light-space coordinates and looks up the shadow map. Switching the filter changes where those lookups happen and how their comparison results are combined.

Choosing a shadow filter in Bevy

Bevy is an open-source game engine written in Rust. The light controls whether to draw a shadow map, and the camera chooses the filter used to read it.

To enable shadows for a directional light, set DirectionalLight::shadow_maps_enabled to true. To choose a filter, add ShadowFilteringMethod to the same entity as Camera3d. Here is how to select Gaussian explicitly when creating a camera. Directional light settings · Camera setup example

use bevy::{light::ShadowFilteringMethod, prelude::*};

fn setup_camera(mut commands: Commands) {
    commands.spawn((Camera3d::default(), ShadowFilteringMethod::Gaussian));
}
Enter fullscreen mode Exit fullscreen mode

ShadowFilteringMethod offers three options. In the Bevy 0.19 setup I used, the camera falls back to Gaussian when the component is omitted. Filter definitions · Default selection

Filter How it smooths shadow edges
Hardware2x2 The GPU sampler interpolates the depth comparison results from a nearby 2×2 group of texels.
Gaussian Combines weighted comparison results across a wider area.
Temporal Varies the sample pattern across frames and works well with temporal anti-aliasing (TAA).

Overriding the shader definition for grass

In bevy_pbr 0.19.1, the camera's ShadowFilteringMethod becomes part of the pipeline key. For Gaussian, Bevy passes SHADOW_FILTER_METHOD_GAUSSIAN to the shader. That definition selects the #ifdef branch when Bevy assembles the shader. How Bevy selects the shader definition

I call the following function from the grass material's MaterialExtension::specialize method. defs is the list of definitions passed to the grass fragment shader.

fn grass_shadow_defs(defs: &mut Vec<ShaderDefVal>) {
    defs.retain(|def| {
        !matches!(def, ShaderDefVal::Bool(name, _) if name.starts_with("SHADOW_FILTER_METHOD_"))
    });
    defs.push("SHADOW_FILTER_METHOD_HARDWARE_2X2".into());
}
Enter fullscreen mode Exit fullscreen mode

The function removes the camera's filter definition and adds the one for Hardware2x2. With this applied to the grass material, trees and ground still use Gaussian, and grass uses Hardware2x2.

How many times does Bevy sample the map?

In WGSL, apply_pbr_lighting calls fetch_directional_shadow to look up the directional light's shadow. The shadow code selects a cascade, transforms the surface position into light space, and passes the shadow map coordinates and comparison depth to sample_shadow_map. Lighting call site · Light-space coordinates and cascades

Hardware2x2 calls sample_shadow_map_hardware once at the target coordinates. In this path it uses textureSampleCompareLevel. The comparison sampler gets a reference depth and uses linear filtering on the results of the depth comparisons for nearby texels. This is percentage-closer filtering (PCF). Near a shadow edge, some comparisons say the light reaches the surface and some say it is blocked, so the lighting is scaled by a value in between. Comparison sampler setup · WGSL sampling code

In this directional-light path, Gaussian uses sample_shadow_map_castano_thirteen. It calls the same sample_shadow_map_hardware function at nine nearby positions and takes a weighted sum. The wider footprint makes the lighting change more gradually as you move across the shadow edge. The two filter branches

How nine samples reproduce the 5×5 weights

This implementation is based on a method used in The Witness. The filter gives the center more weight than the edges and multiplies the horizontal and vertical weights to form a 5×5 kernel. When the input is at a texel center, the weights along each axis are [1, 3, 4, 3, 1]. Ignacio Castaño's derivation

Take the first two weights. Call the depth comparison results for those adjacent texels A and B. We want A + 3B.

A linear sample 75% of the way from A to B gives 0.25A + 0.75B. Multiply it by four and you get A + 3B. The sample position sets the ratio, and the multiplier sets the total weight. That lets us combine both terms with one sample.

A sample 75% of the way from A to B, and nine sample positions on a 5×5 texel grid

Split the horizontal weights into [1, 3], [4, 3], and [1]. Do the same vertically and you get 3×3 groups. On the right of the figure, the little gray dots are texel centers and the red dots are sample positions.

Bilinear filtering blends values along both axes in one lookup. Multiply the sampled value by the sum of its horizontal group and the sum of its vertical group. The top-left red dot, for example, combines the [1, 3] group on both axes, so its sample is multiplied by 4 × 4 = 16. Add the nine weighted samples and you recover the 5×5 kernel.

Here is how Bevy computes the leftmost group in WGSL. The variable s is the horizontal offset of the input coordinate from the reference texel center. Bevy's weights and sample positions

let uw0 = (4.0 - 3.0 * s);
let u0 = (3.0 - 2.0 * s) / uw0 - 2.0;
Enter fullscreen mode Exit fullscreen mode

When s = 0, uw0 is 4 and u0 is -2 + 0.75. If A is two texels to the left of the reference center, the lookup is 75% of the way from A to its right neighbor, B. There is the A + 3B from the diagram in two lines of WGSL. Between texel centers, interpolation can involve up to 6×6 texels. The sample positions and weights account for the horizontal offset s and vertical offset t. Derivation for coordinates between texel centers

Finally, divide the sum by 144. The weights add up to 1 + 3 + 4 + 3 + 1 = 12 on each axis, so the total weight in two dimensions is 12 × 12 = 144. The normalized result is what the lighting code uses.

Shadows also affect light passing through the blades

The grass material uses diffuse_transmission to represent light spreading through a blade. The grass entities also have TransmittedShadowReceiver. In Bevy's directional lighting code, the calculation for the surface calls fetch_directional_shadow, and the calculation for transmitted light can call it again with a different position and a flipped normal. Directional and transmitted lighting in Bevy

When both lighting calculations check for shadows and each reads one cascade, the shader issues two comparison samples with Hardware2x2 and 18 with Gaussian. Near a cascade boundary, it may also read the neighboring map and blend the results. Blending cascades

Picking a filter for the scene I want

In this grass scene, Gaussian took about 0.96 ms more in the main pass than Hardware2x2. In the shader, I could see the extra shadow map samples and the weighted sum.

Looking at the two images, I think the choice depends on the kind of scene I want to make. For a meadow in soft light, I would try Gaussian. If I want to keep the thin shadows where blades overlap, Hardware2x2 might suit the scene better.

In my own field map generator, I use Bevy's shadow maps and write the grass lighting in WGSL. For example, I reuse the same shadow lookup for light hitting the surface and light passing through the blade. Writing the shader also lets me choose how the shadow affects each part of the lighting.

Top comments (0)