NEOLearn

Custom materials and shaders

Write your own material with the Material trait and a WESL shader, extend StandardMaterial, use shader defs, and add a fullscreen effect.

Updated October 20, 2026

On this page

When StandardMaterial can't produce the look you want, write a material of your own: a Rust struct that holds the material's data and a shader that draws with it. Most custom looks (water, holograms, dissolves, stylised shading) need only a fragment shader.

Shaders in the NEO engine#

Shaders are written in WESL, which is WGSL (the WebGPU shading language) with modules, import statements and conditional compilation (@if). Files end in .wesl; plain .wgsl and SPIR-V (.spv) files load too. The renderer translates shaders for each GPU API, including WebGL 2 in web builds.

Shaders are assets: put them under your assets/ folder and refer to them by path. With the file_watcher cargo feature, which NEO's builds don't turn on by default, saving a shader reloads it while the game runs; see Hot reloading.

A material of your own#

src/main.rs
use neo::{prelude::*, reflect::TypePath, render::render_resource::AsBindGroup, shader::ShaderRef};

fn main() {
    App::new()
        .add_plugins((DefaultPlugins, MaterialPlugin::<CustomMaterial>::default()))
        .add_systems(Startup, setup)
        .run();
}

#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]
struct CustomMaterial {
    #[uniform(0)]
    color: LinearRgba,
    #[texture(1)]
    #[sampler(2)]
    color_texture: Option<Handle<Image>>,
    alpha_mode: AlphaMode,
}

impl Material for CustomMaterial {
    fn fragment_shader() -> ShaderRef {
        "shaders/custom_material.wesl".into()
    }
    fn alpha_mode(&self) -> AlphaMode {
        self.alpha_mode
    }
}

fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<CustomMaterial>>,
    asset_server: Res<AssetServer>,
) {
    commands.spawn((
        Mesh3d(meshes.add(Cuboid::default())),
        MeshMaterial3d(materials.add(CustomMaterial {
            color: LinearRgba::BLUE,
            color_texture: Some(asset_server.load("textures/pattern.png")),
            alpha_mode: AlphaMode::Blend,
        })),
    ));
    commands.spawn((Camera3d::default(), Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y)));
}
assets/shaders/custom_material.wesl
import neo_pbr::render::forward_io::VertexOutput;

@group(constants::MATERIAL_BIND_GROUP) @binding(0) var<uniform> material_color: vec4<f32>;
@group(constants::MATERIAL_BIND_GROUP) @binding(1) var material_color_texture: texture_2d<f32>;
@group(constants::MATERIAL_BIND_GROUP) @binding(2) var material_color_sampler: sampler;

@fragment
fn fragment(mesh: VertexOutput) -> @location(0) vec4<f32> {
    return material_color * textureSample(material_color_texture, material_color_sampler, mesh.uv);
}

Three things connect them:

  1. MaterialPlugin::<CustomMaterial> registers the material type with the renderer.
  2. AsBindGroup turns the struct's fields into shader bindings. The numbers in the attributes are the @binding numbers in the shader.
  3. Material::fragment_shader names the shader file.

Example: cargo run --example shader_material.

Binding attributes#

AttributeBinds
#[uniform(n)]A value or struct (f32, Vec4, LinearRgba, a ShaderType struct). Fields with the same n are packed into one uniform struct.
#[texture(n)]An Option<Handle<Image>> or Handle<Image>. Options such as dimension = "2d_array" or "cube" set the texture type.
#[sampler(n)]The sampler for the texture before it.
#[storage(n, read_only)]A storage buffer. Not available in web builds: WebGL 2 has no storage buffers.

What the Material trait can change#

Every method has a default; override only what you need.

MethodWhat it does
fragment_shader(), vertex_shader()The shaders for the main pass. The defaults are the standard mesh shaders.
alpha_mode(&self)Opaque, blended, masked and so on, as for StandardMaterial.
opaque_render_method(&self)Forward, deferred or automatic.
depth_bias(&self)Pushes the surface towards or away from the camera, against z-fighting.
enable_prepass(), enable_shadows()Whether the material takes part in prepasses and casts shadows.
prepass_fragment_shader(), deferred_fragment_shader()Shaders for the prepass and the deferred G-buffer.
specialize(..)Edit the render pipeline: add shader defs, change culling or blending.

Uniforms in web builds#

WebGL 2 needs uniform structs to be a multiple of 16 bytes. Pad small structs when building for the web, and use the SIXTEEN_BYTE_ALIGNMENT shader def, which the engine sets on WebGL 2, on the shader side:

Rust
#[derive(Asset, TypePath, AsBindGroup, Clone)]
struct Pulse {
    #[uniform(0)]
    speed: f32,
    #[cfg(target_arch = "wasm32")]
    #[uniform(0)]
    _padding: Vec3,
}
Text
struct Pulse {
    speed: f32,
    @if(SIXTEEN_BYTE_ALIGNMENT)
    _padding: vec3<f32>,
}

Extend the standard material#

ExtendedMaterial<StandardMaterial, E> keeps all of StandardMaterial's lighting and adds your own data and shader code. Start the extension's bindings at 100 so they don't clash with the base material's:

Rust
use neo::pbr::{ExtendedMaterial, MaterialExtension};

#[derive(Asset, AsBindGroup, Reflect, Debug, Clone, Default)]
struct Toon {
    #[uniform(100)]
    steps: u32,
}

impl MaterialExtension for Toon {
    fn fragment_shader() -> ShaderRef {
        "shaders/toon.wesl".into()
    }
}

// app.add_plugins(MaterialPlugin::<ExtendedMaterial<StandardMaterial, Toon>>::default());
// materials.add(ExtendedMaterial { base: StandardMaterial { .. }, extension: Toon { steps: 4 } })

In the shader, build the PBR input from the standard material, change it, light it, then apply the usual post-lighting steps:

assets/shaders/toon.wesl
import neo_pbr::render::{
    pbr_fragment::pbr_input_from_standard_material,
    pbr_functions::{alpha_discard, apply_pbr_lighting, main_pass_post_lighting_processing},
    forward_io::{VertexOutput, FragmentOutput},
};

@group(constants::MATERIAL_BIND_GROUP) @binding(100) var<uniform> steps: u32;

@fragment
fn fragment(in: VertexOutput, @builtin(front_facing) is_front: bool) -> FragmentOutput {
    var pbr_input = pbr_input_from_standard_material(in, is_front);
    pbr_input.material.base_color = alpha_discard(pbr_input.material.flags, pbr_input.material.alpha_cutoff, pbr_input.material.base_color);
    var out: FragmentOutput;
    out.color = apply_pbr_lighting(pbr_input);
    out.color = floor(out.color * f32(steps)) / f32(steps);
    out.color = main_pass_post_lighting_processing(pbr_input, out.color);
    return out;
}

main_pass_post_lighting_processing applies fog and, when the camera tonemaps in its material shaders, tonemapping. The full example also handles the deferred path: cargo run --example extended_material.

Shader defs#

Shader defs switch parts of a shader on and off at compile time. Push one in specialize, then test it with @if:

Text
@fragment
fn fragment(mesh: VertexOutput) -> @location(0) vec4<f32> {
    @if(IS_RED)
    return vec4<f32>(1.0, 0.0, 0.0, 1.0);
    @else
    return material.color;
}

Each combination of defs is a separate pipeline, compiled the first time it's needed. Example: cargo run --example shader_defs.

Useful built-in values#

ImportWhat it gives you
neo_pbr::render::mesh_view_bindings::globalsglobals.time (seconds since start-up, wrapping after an hour), globals.delta_time, globals.frame_count. Example: animate_shader.
neo_pbr::render::mesh_view_bindings::viewThe camera: position, matrices, viewport.
neo_pbr::render::forward_io::VertexOutputThe interpolated vertex: world_position, world_normal, uv, color and more.

Fullscreen effects#

A fullscreen material draws over the whole camera image after the main pass, for custom post-processing. Implement FullscreenMaterial on a component, add its plugin and put the component on a camera:

Rust
use neo::core_pipeline::fullscreen_material::{FullscreenMaterial, FullscreenMaterialPlugin};
use neo::render::{extract_component::ExtractComponent, render_resource::ShaderType, RenderApp};

#[derive(Component, ExtractComponent, Clone, Copy, ShaderType, Default)]
#[extract_app(RenderApp)]
struct Wobble {
    intensity: f32,
    #[cfg(target_arch = "wasm32")]
    _padding: Vec3,
}

impl FullscreenMaterial for Wobble {
    fn fragment_shader() -> ShaderRef {
        "shaders/wobble.wesl".into()
    }
}

// App: .add_plugins(FullscreenMaterialPlugin::<Wobble>::default())
// Camera: commands.spawn((Camera3d::default(), Wobble { intensity: 0.01, ..default() }));

The shader gets the screen texture at binding 0, a sampler at 1 and your component at 2; import neo_core_pipeline::fullscreen_vertex_shader::FullscreenVertexOutput for the UVs. Example: cargo run --example fullscreen_material.

Going further#

The engine core's examples cover lower-level rendering too: instancing your own data (custom_shader_instancing, gpu_component_array_buffer), custom render phases (custom_render_phase, custom_phase_item), specialized mesh pipelines (specialized_mesh_pipeline) and compute shaders (compute_shader_game_of_life, gpu_readback). Compute shaders, storage buffers, binding arrays and mesh shaders aren't available in web builds.

Next steps#