Hazel

Material API

How a material gets from a .material file onto a mesh: the components that point at it, the file format, the two compile paths, material instances and functions, and hand-written code shaders. Everything here is in crates/renzora_shader (src/material/ for graphs, src/backends/ and src/runtime.rs for code shaders) and the contract crate crates/api/renzora_material_api. For using the Material Editor, see Materials; for every node and pin, see the Material Nodes Reference.

Pointing an entity at a material

ComponentCratePurpose
MaterialRef(String)renzora_material_apiAsset-relative path to a .material, .shader, .wgsl, .wesl, .glsl, .frag or .vert file. Reflected and serialized, so an assignment survives save and load. Works on a Mesh3d and, for a Sprite-domain material or a sprite shader, on a Sprite
MaterialResolved { source_path }renzora_material_apiAdded by the resolver once the material is attached. Removing it is how any crate asks for the entity to be resolved again; it lives in the contract so editor panels that rebind a material need not link the shader crate
MaterialOwnedrenzora_material_apiMarks a mesh whose material belongs to the system that spawned it (a particle effect's draw mesh). The resolver never resolves a MaterialRef onto it, and tools that put a material on every mesh under a group pass it by
MaterialAlphaOverride { mode, cutoff }renzora_material_apiRenders this entity's shared material at a different alpha mode than the file declares
MaterialOverrides(HashMap<String, ParamValue>)renzora_shaderRegistered and serialized, but the resolver does not read it in this version. For per-object variation, use a material instance (below)

A plugin that spawns meshes with its own Bevy material must add MaterialOwned. A mesh drawn with two materials at once crashes the renderer: Bevy keeps one material per entity for drawing but specializes a pipeline for each, so a draw can pair one material's pipeline with the other's bind group.

commands.entity(draw).insert((MeshMaterial3d(my_material), MaterialOwned));

MaterialAlphaOverride exists for overlays: a terrain paint layer wears the same rock or water material a cliff does, but has to fade out at its edges through per-vertex alpha. Its mode is a PbrAlphaMode (Opaque, Mask, Blend); MaterialAlphaOverride::BLEND is the common case. The resolver clones the resolved asset and sets the mode on the clone, so the variant shares every texture, the compiled shader and the parameter block with the master: one asset entry, no recompile. Variants are keyed by the master's asset id, so saving the material re-derives them.

renzora_material_api::MaterialTarget::of_file(path) says whether a file can be worn by a mesh or a sprite, from the graph's domain or, for a shader, from whether it imports bevy_sprite_render. It returns None for a post-process effect, which compiled as a mesh surface would bind the screen texture where the mesh pipeline puts the view uniform and abort the process. Drop targets use it to refuse a mismatch before the drop.

How a graph is compiled

MaterialResolverPlugin resolves every entity with a MaterialRef and no MaterialResolved, and re-resolves one whose MaterialRef changed. Results are cached per file path in MaterialCache, so editing one material recompiles only that one. A graph takes one of two paths:

  • Trivial graphs compile to a plain StandardMaterial (standard_build.rs): textures and constants wired straight into output pins. Most imported materials land here.
  • Procedural graphs compile to a GraphMaterial, ExtendedMaterial<StandardMaterial, SurfaceGraphExt>, with a generated WESL fragment shader. Reads that depend on the pipeline (a prepass, the environment map, vertex colours) are gated with @if(FLAG) and fall back to a neutral value when the flag is off, so one shader serves every camera and mesh. Without the fallback the material would fail to compile for a camera lacking that prepass.

Three things on the Surface output force the procedural path even when everything is wired trivially: a stored ao constant (occlusion is texture-only on StandardMaterial), a stored reflectance constant (a Vec3 in the graph against an f32 on the material), and a wired displacement. StandardMaterial::depth_map is a depth (white is the bottom) while displacement is a height (white is the peak), and Bevy has no invert, so routing it there would render every relief inside out.

The embedded shader

Saving in the editor bakes the generated shader into the .material itself, under compiled, with the binding metadata the renderer needs. The resolver uses it, skipping codegen entirely, only when CompiledArtifact::is_usable_for holds:

  • meta.codegen_version equals codegen::CODEGEN_VERSION (currently 5), so a change to what codegen emits reaches every saved material without anyone re-saving it;
  • meta.alpha_mode and meta.double_sided match the graph;
  • meta.graph_hash is non-zero and equals graph_fingerprint(graph), an FNV-1a hash of the graph as it serializes, minus compiled and wgsl_path, with keys sorted.

Otherwise the graph is compiled live. The fingerprint is what catches a .material edited outside the editor, by hand or by a tool: the shader bakes every constant in, and without the check the edit would be ignored.

A material written by an older editor keeps a .wgsl and .wgsl.meta beside it and points at them with wgsl_path. It still loads, and the next save folds the shader in and deletes the pair. A shader saved before Bevy 0.20 is in the old #import dialect and is translated to WESL on load (see Shaders).

The base StandardMaterial

A GraphMaterial's generated shader runs in the forward pass. For a Surface graph it also carries a second branch, under @if(PREPASS_PIPELINE), that writes the result to the G-buffer with deferred_output instead of lighting it, so the graph looks the same in deferred mode and under Solari, which shades from the G-buffer. A graph keeps the forward-only shader when it reads something the G-buffer pass does not have: scene depth, scene normal or motion vectors (the targets that pass is writing), the transmission texture, or the environment map. Vegetation keeps it too, since its vertex stage is its own.

Every other pass shades from the base StandardMaterial of the extended material: the depth prepass, shadow maps, the G-buffer pass of a forward-only graph, a virtual geometry cut-out, and a ray tracer's hits. So standard_build::apply_base_approximation fills the base with as much of the graph as a StandardMaterial can hold: albedo and its alpha, normal map, metallic-roughness, occlusion and emissive. Anything procedural is invisible there. Without it, alpha-masked foliage would write the whole leaf quad into the depth prepass (no albedo texture to test against), and the forward pass, which depth-tests against that prepass, would never shade anything behind a leaf.

  • Two separate greyscale maps on Metallic and Roughness cannot ride StandardMaterial's single metallic_roughness_texture, so the base keeps the factors. Pack them into one glTF-style texture (G roughness, B metallic) for the other passes to see them.
  • When Roughness is wired to something the base cannot hold (a maths node, noise, a second texture), the base uses 0.5 rather than the pin's constant, which the generated shader never reads and which a spec-gloss import leaves near 0.0 (a perfect mirror).

While a ray tracer asks for stand-ins (TracedStandInsWanted), every mesh drawn with a GraphMaterial carries a TracedStandIn holding a copy of its base, one per graph material, kept in step when the material recompiles or a parameter changes. Solari traces the mesh with that. See Solari.

Vertex colours

A mesh with a COLOR attribute has it multiplied into base_color and alpha, as Bevy's StandardMaterial does, including when the graph wires base_color itself (@if(VERTEX_COLORS); white otherwise). That is what lets an overlay mesh carry its coverage in vertex alpha, and what keeps a graph tinting the same after it crosses from the trivial to the procedural path.

Limits

LimitValueWhy
Named parameters per graph32 (MAX_PARAMETER_SLOTS)The parameter uniform is array<vec4<f32>, 32>. Past it, each extra name aliases the last slot and the compile reports a warning
Distinct 2D images per graph16 (MAX_D2_TEXTURES)The texture_0 to texture_15 slots of SurfaceGraphExt. Nodes sampling the same image share a slot; a seventeenth image is a compile error
Distinct 2D images, Sprite domain6 (MAX_SPRITE_D2_TEXTURES)The slots of SpriteGraphExt
Samplersone, sharedEvery slot samples with the first 2D texture's sampler (or a default linear one). Metal allows 16 sampler states per stage and the mesh pipeline already uses many

The .material file

A master .material is a JSON MaterialGraph:

FieldTypeNotes
namestringDisplay name
domainenumSurface (default), Vegetation, Unlit or Sprite. The old TerrainLayer reads as Surface; a terrain is textured by an ordinary Surface graph built from the Landscape nodes
nodesarrayMaterialNodes
connectionsarrayConnections
next_idu64Next id the graph allocates (nodes and comments share the id space)
alpha_modeenum"Opaque" (default), { "Mask": { "cutoff": 0.5 } }, "Blend", "Premultiplied" or { "Dithered": { "low": 0.1, "high": 0.5 } }
double_sidedboolRender back faces too (default false)
compiledobjectThe baked CompiledArtifact; omitted when absent
wgsl_pathstringLegacy link to a .wgsl beside the material; read, never written; omitted when absent
commentsarrayComment boxes on the canvas
muted_slotsobjectTexture channels muted in the material inspector, keyed by slot, holding the sampler node the mute disconnected so it can be wired back

Premultiplied is glass: alpha says how much of what is behind is covered, but what the surface draws itself (its reflections) is added at full strength. Dithered is a cut-out with soft edges for hair and fur: alpha is sharpened between low and high, then each pixel is drawn whole or not at all against noise that changes every frame, so TAA averages the fringe back into a soft edge. Being a cut-out, it writes depth and casts shadows; passes that shade from the base see it as Mask at the midpoint of the ramp.

compiled is what the renderer loads:

FieldNotes
wgslThe generated fragment shader. WESL since Bevy 0.20, the old dialect before; the field keeps its name so older files still read
meta.domain, meta.alpha_mode, meta.double_sidedCopied from the graph at compile time, so the artifact is self-contained
meta.requires_transmissionTurns on Bevy's transmission pipeline for the base
meta.texture_bindings{ name, binding, asset_path, kind, linear } per sampled image. linear marks data textures (a normal map) to load without the sRGB decode
meta.parameters{ name, kind, default } per named parameter: what an instance may override
meta.node_line_map(node id, first line, last line), so a compile error can point at a node
meta.codegen_version, meta.graph_hashSee The embedded shader

A MaterialNode is { id, node_type, position, input_values }, where input_values maps an input pin name (or a node setting, such as a texture node's texture or Static Switch's use_a) to a constant. A Connection is { from_node, from_pin, to_node, to_pin }. An input pin takes one connection; connecting again replaces it. Output nodes cannot be removed.

Constants are PinValues, externally tagged: { "Float": 0.5 }, { "Vec2": [0, 0] }, { "Vec3": [0, 0, 0] }, { "Vec4": [0, 0, 0, 1] }, { "Color": [1, 0, 0, 1] }, { "Bool": true }, { "Int": 3 }, { "TexturePath": "textures/brick.png" }, { "String": "BaseColor" }. A null or non-finite float reads as 0.0 rather than failing the whole file.

{
  "name": "Brick",
  "domain": "Surface",
  "nodes": [
    { "id": 1, "node_type": "output/surface", "position": [300.0, 0.0], "input_values": {} },
    {
      "id": 2,
      "node_type": "param/color",
      "position": [0.0, 0.0],
      "input_values": {
        "name": { "String": "BaseColor" },
        "default": { "Color": [0.6, 0.2, 0.15, 1.0] }
      }
    }
  ],
  "connections": [
    { "from_node": 2, "from_pin": "value", "to_node": 1, "to_pin": "base_color" }
  ],
  "next_id": 3,
  "alpha_mode": "Opaque",
  "double_sided": false
}

Pin types

PinTypeWGSLNotes
Floatf32
Vec2vec2<f32>
Vec3vec3<f32>
Vec4vec4<f32>
Colorvec4<f32>Treated as Vec4 when casting
BoolboolConnects only to Bool
Texture2Dtexture_2d<f32>
Samplersampler
StringnoneEditor data (parameter names, code); never reaches the shader

Float, Vec2, Vec3, Vec4 and Color connect to each other freely; PinType::cast_expr inserts the coercion. Widening a scalar copies it into each component (into Vec4 as (s, s, s, 1.0)); widening a Vec2 or Vec3 pads with 0.0 and a final 1.0; narrowing takes the leading components. A Bool reaching a Float pin in a graph saved before the editor refused that wire compiles as select(0.0, 1.0, b).

Domains

Every graph has exactly one output node, set by its domain:

DomainOutput nodeCompiles to
Surfaceoutput/surfaceStandardMaterial or GraphMaterial
Vegetationoutput/vegetationGraphMaterial plus a generated vertex stage that moves each vertex by vertex_offset in world space
Unlitoutput/unlitGraphMaterial with unlit = true on the base, so lighting returns the colour unchanged
Spriteoutput/spriteSpriteMaterial<SpriteGraphExt>, Bevy 0.20's sprite material

The pins of each output node are in the node reference.

A Sprite material's shader ends in sprite_fn::get_final_color, so the sprite's own tint and alpha mode apply on top of the graph, and its flip, tiling and slicing apply to the texture the graph reads. The graph's alpha_mode is not used on a sprite. A Sprite-domain file on a mesh, or a mesh material on a sprite, is refused with an error rather than drawn wrong.

MaterialDomain::refuses_node is the one rule for which nodes a domain may hold: a Sprite graph cannot use the scene nodes that read the 3D view (scene depth, depth fade, scene normal, motion vector, scene colour, the two environment map nodes) or any Landscape node, and only a Sprite graph may use Sprite Color. Codegen refuses such a node with an error naming it, and the editor leaves it out of the add menu and marks one already in the graph.

Material instances

A material instance is a .material holding a master path and an overrides map instead of a graph. Masters and instances share the extension; the resolver tells them apart by content (a non-empty master). Files with the old .material_instance extension still load.

{
  "master": "models/Wood/materials/Wood.material",
  "overrides": {
    "BaseColor": { "Color": [0.45, 0.22, 0.10, 1.0] },
    "Roughness": { "Float": 0.85 }
  }
}
  • Keys are the name values authored on the master's param/* nodes (an unnamed one defaults to FloatParam, ColorParam, Vec2Param, Vec3Param, Vec4Param or BoolParam).
  • Unknown keys are ignored, so renaming a master parameter does not break every instance.
  • Values are ParamValues: Float, Vec2, Vec3, Vec4, Color, Int, Bool, tagged like PinValue.
  • Trivial master: the overrides are spliced into the matching parameter defaults and the graph classified again into a fresh StandardMaterial.
  • Procedural master: the master compiles once; each instance clones its GraphMaterial and rewrites only the parameter uniform's slots. The shader and texture bindings carry over, so wgpu reuses the same specialized pipeline for every instance.

Material functions

A reusable subgraph is a .material_function file: a JSON MaterialFunction, { name, graph }. Inside, the graph has a function/input_point (four Vec4 inputs) and a function/output_point (four Vec4 returns) instead of an output node. A function/call node in a material names the function in input_values["function"]; at compile time the function body is emitted once as a helper at module scope and called at each call site.

The resolver loads the .material_function files in the same folder as the material. An empty or unknown name, or a function that reaches itself, emits a comment in the shader and outputs zeros rather than failing the material.

Code shaders

MaterialRef can also point at a hand-written shader: a .shader file, or a .wgsl, .wesl, .glsl, .frag or .vert file directly. It renders with CodeShaderMaterial, one pipeline per compiled shader. Five backends compile source to what Bevy's pipeline takes:

BackendHandles
WESL.wesl: import ...;, @if(FLAG). The default for a new .shader
BevyThe pre-0.20 dialect (#import, #ifdef), translated as it loads
WGSLPlain WGSL
GLSL.glsl, .frag, .vert
ShaderToyShaderToy-style mainImage code, with iTime, iResolution, iMouse, iTimeDelta, iFrame mapped to the uniforms

A .wesl file is compiled as WESL; any other source has its language detected. A .wgsl with a .meta beside it is legacy compiled graph output and is assembled as a GraphMaterial instead.

A .shader file is a JSON ShaderFile:

FieldNotes
languageA backend name above
shader_typeFragment (default; previews on a mesh through CodeShaderMaterial), Material (a full Bevy material with its own bind groups; compile-checked only) or PostProcess
shader_sourceThe source
paramsParameters from @param annotations

When the compiled shader uses uniforms.* and declares no material bind group of its own, the registry injects ShaderUniforms at @group(3) @binding(0): time, delta_time, resolution, mouse (vec4) and frame. Each @param comment becomes a WGSL constant, so the name reads as a variable:

import bevy_pbr::render::forward_io::VertexOutput;

// @param speed float 1.0 0.1 5.0 Animation speed
// @param tint color 1.0 0.8 0.6 1.0

@fragment
fn fragment(in: VertexOutput) -> @location(0) vec4<f32> {
    let t = uniforms.time * speed;
    let r = 0.5 + 0.5 * cos(t + in.uv.x * 6.283);
    let g = 0.5 + 0.5 * cos(t + in.uv.y * 6.283 + 2.094);
    return vec4<f32>(r * tint.r, g * tint.g, 0.5, 1.0);
}

The syntax is // @param <name> <type> <default...> [min max] [description], where <type> is float, vec2, vec3, vec4, color, int or bool. A post-process effect file is refused as a material with an error telling you to add it to a Post Process component instead; see Post-Processing.

The node catalogue as data

renzora_shader publishes every node type into the MaterialNodeCatalog resource (renzora_material_api): node type, display name, category, description and each pin's name, label, type and direction. The node definitions themselves cannot leave renzora_shader (a pin template carries a PinValue, the compiler's own vocabulary), so this is how a plugin reads the catalogue without linking the compiler:

fn list_noises(catalogue: Res<renzora::MaterialNodeCatalog>) {
    for node in catalogue.iter().filter(|n| n.category == "Procedural") {
        let inputs: Vec<&str> = node.inputs().map(|pin| pin.name.as_str()).collect();
        info!("{} takes {inputs:?}", node.node_type);
    }
}

To add a node type to the engine, see Custom Material Nodes.

Testing

crates/renzora_shader/src/material/validate.rs compiles generated shaders the way the engine does: the WESL compiler over the app's own shader libraries, then naga. Its tests generate a graph exercising every node type in ALL_NODES (except output and function bracket nodes) and compile every .material under assets/materials/, so a node whose codegen drifts invalid fails CI instead of falling back at runtime. In the editor the same validator feeds the Problems panel.