Hazel

Shaders

How shader text becomes a Bevy Shader in Renzora: WESL as the language, the translation that keeps pre-0.20 shaders loading, the code-shader material and its language backends, and the checks a hand-written shader passes before the editor binds it.

This page is about shaders written by hand. Node-graph materials generate their shaders; see Material API. Fullscreen camera effects are effect files; see Post-Processing Effects.

WESL

Bevy 0.20 compiles shaders with WESL and no longer has naga_oil, the preprocessor that understood #import, #ifdef and #{NAME}. WESL is a superset of WGSL with imports and conditional compilation. Write new shaders as .wesl:

import bevy_pbr::render::forward_io::VertexOutput;
import super::noise::fbm;   // noise.wesl beside this file

@fragment
fn fragment(in: VertexOutput) -> @location(0) vec4<f32> {
    var coord = in.world_position.xz;
    @if(VERTEX_UVS_A)
    coord = in.uv;
    return vec4<f32>(vec3<f32>(fbm(coord)), 1.0);
}
  • Imports end with ; and come before any declaration.
  • A module's name is its path. Bevy's modules are under their crate and folder (bevy_pbr::render::forward_io, bevy_pbr::render::mesh_view_bindings). A project file imports its neighbours relative to itself, as super::noise; import super::noise::fbm; may name the item fbm in noise.wesl or the module noise/fbm.wesl.
  • @if(FLAG), @elif and @else gate a declaration, statement, struct member or parameter. Pipeline flags are the ones #ifdef tested (VERTEX_UVS_A, VERTEX_COLORS); a flag nothing sets is false.
  • Numeric pipeline values are constants::NAME (they were #{NAME}), for example @group(constants::MATERIAL_BIND_GROUP).

Building a shader from a string goes through renzora::shader_source::shader, never Shader::from_wgsl on text that might carry directives. That one function handles all three dialects.

One entry point for every dialect

renzora_shader_api::shader_source (reached by plugins as renzora::shader_source) decides what a source is and builds the right Shader:

pub enum Dialect { Wgsl, Wesl, Legacy }

pub fn dialect(source: &str, path: &str) -> Dialect;
pub fn to_wesl(source: &str) -> Translation;
pub fn shader(source: impl Into<String>, path: impl Into<String>) -> Shader;
pub fn wesl_import_files(shader: &Shader) -> Vec<String>;
pub fn report(path: &str, diagnostics: &[Diagnostic]);

dialect reads it in this order:

  1. Legacy if any line uses a naga_oil construct: #import, #ifdef, #ifndef, #if , #else, #endif, #define_import_path, or a #{NAME} substitution.
  2. Wesl if the path ends in .wesl, or the source has an import a::b; statement, the one WESL construct plain WGSL lacks.
  3. Wgsl otherwise. Plain WGSL is valid WESL, so only the file name says whether its author meant WESL.

shader then calls Shader::from_wgsl for WGSL, Shader::from_wesl for WESL, and for a legacy source translates it, logs the translator's warnings and errors under the path, and builds it as WESL. A .wgsl path is renamed .wesl for the WESL module path, so the two dialects stay apart in logs. The path is also the WESL module path, which is what a relative import super::x; resolves against.

A shader built in memory skips Bevy's asset loader, which is what normally loads the files a .wesl imports. wesl_import_files returns the candidate files for each relative import; the caller loads the ones that exist and pushes the handles into Shader::file_dependencies, which also keeps them alive.

The module also lives in the shared contract image, so a native plugin building a shader at runtime gets exactly the engine's treatment.

The legacy translator

renzora_legacy_shaders::translate ports a naga_oil shader to WESL:

  • #import lines become import ...; statements at the top, with Bevy's module paths moved to where 0.20 put them (bevy_pbr::forward_io becomes bevy_pbr::render::forward_io; the rename table is renzora_legacy_shaders::table).
  • #ifdef, #ifndef, #if, #else and #endif become @if(...) on each declaration, statement, struct member or parameter they wrap.
  • #{NAME} becomes constants::NAME.
  • #define_import_path is removed from the source and returned in Translation::module_name, so a loader can keep registering the module under its old name and the shaders that import it keep resolving.
pub struct Translation {
    pub source: String,              // the shader as WESL
    pub module_name: Option<String>, // the old #define_import_path, if any
    pub diagnostics: Vec<Diagnostic>,
}

pub struct Options {
    pub module_renames: Vec<(String, String)>, // extra (old, new) renames
    pub known_modules: Vec<String>,            // module names that keep their name
}

known_modules tells a module import (#import my::lib) apart from an item import (#import my::Thing) for the project's own modules.

What it cannot fix it reports as a Diagnostic { line, severity, message } instead of failing silently: a numeric #if comparison no pipeline supplies a flag for, a module path it does not know, or a call to a Bevy shader function 0.20 removed (which surfaces when the result compiles). Severity::Info notes are expected and not logged; Warning means the result compiles but may behave differently; Error means part of the shader could not be translated.

Where translation happens

Everything that may still be in the old dialect is translated as it loads:

  • .wgsl files. renzora_shader::legacy_loader::LegacyWgslLoader is registered after Bevy's own loader for the wgsl extension, so it is the one used (Bevy logs one "Duplicate AssetLoader" warning at startup). Plain WGSL loads exactly as Bevy's loader would. A .wgsl holding WESL imports, or one in the legacy dialect after translation, loads as WESL, and its relative imports are loaded as file dependencies the way Bevy's .wesl loader does. It keeps Bevy's ShaderSettings, so a .meta written for Bevy's loader still applies; numeric shader defs from it, readable as #{NAME} before, are constants::NAME after translation. This covers project shaders, theme shaders, effect files and the shaders inside plugins.
  • .material files saved before 0.20, whose embedded shader is in the old dialect. Material codegen now writes WESL.
  • Any string a plugin builds through renzora::shader_source::shader.

.wesl files go to Bevy's own WESL loader untouched.

The code-shader material

renzora_shader::ShaderPlugin (a Runtime plugin, so it runs in the editor and in games) sets up the hand-written shader path:

  • CodeShaderMaterial: a Bevy Material with one uniform block and a per-instance shader_handle. Material::specialize swaps the forward fragment shader for that handle, keyed by CodeShaderKey, so different meshes can run different code shaders at once. Prepass and shadow pipelines keep Bevy's own fragment shader: their VertexOutput differs from the forward one a code shader is written against, and swapping it in there made wgpu abort.
  • ShaderBackendRegistry: the language backends.
  • ShaderCache: compiled Handle<Shader>s by source hash, so identical sources share one shader.

A code shader is unlit: what fragment returns is the pixel colour. It writes only to @location(0), and discard; cuts holes.

Built-in uniforms

When the compiled output references uniforms. and declares nothing in the material group (@group(3) or MATERIAL_BIND_GROUP), the registry injects this block after the last import:

struct ShaderUniforms {
    time: f32,
    delta_time: f32,
    resolution: vec2<f32>,
    mouse: vec4<f32>,
    frame: u32,
    _pad: vec3<f32>,
}

@group(3) @binding(0) var<uniform> uniforms: ShaderUniforms;

time, delta_time and frame (wrapping) are updated every frame for every CodeShaderMaterial. resolution stays at its default of 512 by 512 and mouse at zero: nothing writes them yet. Bevy's globals.time, imported from bevy_pbr::render::mesh_view_bindings, works too and needs no injection.

The injection point is computed after the last import ...; statement (which may span lines) or the last #import line, because WESL requires imports first.

@param constants

// @param comments declare tunable values. file::extract_params parses them and registry.compile injects one const per parameter, after the uniforms block if there is one, otherwise after the imports:

// @param <name> <type> <default> [min max] [description]
TypeAliasesGenerated
floatf32const name: f32 = ...; (optional min max set the slider bounds)
inti32const name: i32 = ...;
boolconst name: bool = ...;
vec2, vec3, vec4const name: vecN<f32> = ...;
colorcolourconst name: vec4<f32> = ...;

They are constants, not uniforms: editing one in the Shader Properties panel re-injects the constants and recompiles. registry.transpile is the same compile without the parameter injection, for callers that inject edited values themselves.

Language backends

A backend implements one trait and returns WGSL (or WESL) Bevy can compile:

pub trait ShaderBackend: Send + Sync + 'static {
    fn name(&self) -> &str;
    fn file_extensions(&self) -> &[&str];
    fn to_wgsl(&self, source: &str) -> Result<String, ShaderCompileError>;
    fn builtin_uniforms(&self) -> &[UniformMapping] { &[] }
    fn syntax_tokens(&self) -> Option<&[SyntaxRule]> { None }
}

ShaderPlugin registers five, and a plugin can add more through ShaderBackendRegistry::register. Lookup is by name (case-insensitive) or by extension.

Backendname()ExtensionsWhat it does
BevyBackendBevybevy.wgslThe pre-0.20 dialect, translated to WESL.
WgslBackendWGSLwgslPlain WGSL, checked with naga up front.
WeslBackendWESLweslPassed through; imports resolve when Bevy builds the pipeline.
GlslBackendGLSLglsl, frag, vertA GLSL fragment shader parsed and validated with naga, written out as WGSL. Bevy 0.20 itself no longer reads GLSL.
ShaderToyBackendShaderToyshadertoyWraps a mainImage body as GLSL, expands #define macros, strips f float suffixes and rewrites mat2(vec4) constructors naga rejects, transpiles through the GLSL backend, then maps iTime, iTimeDelta, iResolution, iMouse and iFrame onto uniforms.

When a shader's language is not stored, file::detect_language guesses it in this order: mainImage, iResolution or iTime means ShaderToy; #version, void main or gl_Frag means GLSL; any legacy directive means Bevy; an import a::b; means WESL; uniform or varying means GLSL; @fragment, @vertex, @compute, var<uniform> or var<storage means WGSL; anything else is WESL.

Every WGSL check in the workspace goes through renzora::wgsl (parse, validate, check), so validation flags and capabilities are decided in one place: all flags, all capabilities, the way wgpu validates.

Binding a hand-written shader

A shader file (.wesl, .wgsl, .glsl, .frag, .vert) dropped on a mesh or sprite becomes its material: the material resolver builds a CodeShaderMaterial for a mesh, or a SpriteMaterial for a sprite. A shader file that is a post-process effect (it carries // @effect) is refused as a material: compiled as a surface shader it would bind the screen texture where the mesh pipeline puts the view uniform.

Which pipeline a shader is written for is read from its text: importing bevy_sprite_render makes it a sprite shader. One put on the wrong kind of target is refused with a message saying which it is.

The editor checks before it binds

A shader can compile and still disagree with the pipeline it goes into, and wgpu treats that as unrecoverable: it would close the editor. So in an editor session every hand-written shader is checked by ShaderValidator::code_shader_problems before the resolver binds it. The validator compiles the shader with WESL and naga in each pipeline configuration (no optional attributes; UVs and vertex colours; UVs, colours and an environment map), and compares it against a probe shader that stands in for the pipeline's own vertex stage. The shader is refused when:

  • it has no @fragment fn fragment;
  • it compiles in no configuration (one that only fails without UVs is accepted; Bevy skips that mesh);
  • it reads a @location the vertex stage does not write, reads it as a different type, or interpolates it differently;
  • it writes a colour output other than @location(0);
  • on a mesh, it declares a binding in any group but the material's, or anything in the material group other than one uniform block at @binding(0) no larger than ShaderUniforms;
  • on a sprite, it declares any binding or uses uniforms.

Each reason goes to the Console and the Problems panel, and the target keeps its previous material (after an edit, the last version that passed). Verdicts are cached by source, path, target and the number of shader libraries loaded, so one shader on a hundred meshes is checked once. While a project opens, the check waits until the set of loaded Bevy shader libraries has held still for a few frames, so a good shader is not refused for an import that has not arrived yet.

A shipped game binds without checking. It carries no validator, and its shaders are the ones the editor already accepted.

The .shader file

A .shader file is JSON (renzora_shader::file::ShaderFile):

FieldTypeMeaning
languagestringBackend name: "WESL" (the default), "Bevy", "WGSL", "GLSL" or "ShaderToy".
shader_typeenumFragment (default), Material or PostProcess. Only Fragment previews on a mesh.
shader_sourcestringThe source.
paramsmapParameter values; also recoverable from the @param comments.

compiled_wgsl is #[serde(skip)] and recomputed on load. A file saved with "language": "Bevy" keeps loading through the translation.

The shader editor

renzora_shader_editor is editor-only. Double-clicking a .wgsl, .wesl, .glsl, .vert or .frag file in the asset browser opens it in a Shader document tab, with three panels:

Panel idTitleShows
shader_previewShader PreviewThe shader on a preview mesh: Quad, Sphere (default), Cube, Cylinder, Capsule, Torus, Cone, Tetrahedron or Plane.
shader_compiler_logCompiler LogThe compile result, with [line:col] or [line N] positions where the backend reports them.
shader_propertiesShaderThe @param controls.

Auto-compile is on by default. WGSL, GLSL and ShaderToy are checked up front with naga; WESL and translated legacy shaders only resolve their imports against the running app, so their errors come from Bevy when the pipeline is built.

Related