Custom Shaders

Writing a Custom Shader

With valora, you can shade each path with its own shader, and define custom uniforms. We'll start with this simple GLSL fragment shader:
1
#version 400
2
​
3
uniform vec3 color;
4
uniform float scale;
5
uniform float height;
6
uniform float width;
7
​
8
out vec4 frag;
9
​
10
void main() {
11
vec2 pos = gl_FragCoord.xy / scale;
12
​
13
vec3 white = vec3(1., 1., 1.);
14
​
15
frag = vec4(mix(white, color, pos.x / width), 1.);
16
}
Copied!
Save this to a file named pattern.frag.
Now, we'll use valora's shader API to define some uniforms and load the shader. A shader in valora is made of two parts:
  1. 1.
    The shader program. This is the GLSL above, which exposes an interface to provide uniforms.
  2. 2.
    The uniforms bound to the shader.
First let's define the uniforms type in Rust:
1
#[derive(UniformSet, Copy, Clone, Debug)]
2
struct Uniforms {
3
/// A solid color overlay on the shader pattern.
4
color: (f32, f32, f32),
5
/// The vector scale of the output.
6
scale: f32,
7
/// Width of the output.
8
width: f32,
9
/// Height of the output.
10
height: f32,
11
}
Copied!
The derive macro UniformSet will generate mappings from the field types to something we can send to the GPU, should such a mapping exist for the type.
Now let's load the shader and draw with it:
1
fn main() -> Result<()> {
2
run_fn(Options::from_args(), |gpu, world, _rng| {
3
let mut program = ShaderProgram::new(&gpu, "pattern.frag")?;
4
let uniforms = Uniforms {
5
color: Hsv::new(0., 0.7, 0.7).into_rgb::<Srgb>().into_components(),
6
scale: world.scale,
7
width: world.width,
8
height: world.height,
9
};
10
let shader = program.bind(uniforms);
11
​
12
Ok(move |ctx: Context, canvas: &mut Canvas| {
13
canvas.set_color(LinSrgb::new(1., 1., 1.));
14
canvas.paint(Filled(ctx.world));
15
​
16
canvas.set_shader(shader.clone());
17
let square = Ngon::square(world.center(), 200.);
18
​
19
canvas.paint(Filled(square));
20
})
21
})
22
}
Copied!
If you run the painting with cargo run --release, and change the GLSL, you'll notice that the view pane will update live!
A path rendered with a custom shader.

Updating Uniforms

We can update our uniform values each frame. Once the uniforms are updated, we can rebind with the shader program to make a new shader.
1
let hue = ctx.time.as_secs_f32().sin().abs() * 40.;
2
uniforms.color = Hsv::new(hue, 0.7, 0.7).into_rgb::<Srgb>().into_components();
3
canvas.set_shader(program.bind(uniforms));
Copied!
​