Documentation / Fundamentals
Shaders
Render application-owned WGSL with reactive uniforms, image inputs, and animation on native GPUs and WebGPU.
Choose a shader view
Use shader(program) to display a bound Shader. Use shader_with(prepare) when uniforms or image inputs depend on graph-backed state or environment values. Both create a ShaderView with ordinary layout, events, and accessibility metadata.
A shader computes pixels across its allocated content box. Use Canvas for vector paths, fills, strokes, and drawing layers; use a shader for procedural textures, lighting, or image distortion written in WGSL. A shader does not capture the surrounding DOM or other views.
Import refract::prelude::* for the Rust API. The same WGSL source runs through wgpu and Vello on desktop and a WebGPU canvas in the browser. Browsers without a usable WebGPU device display your fallback color.
Write the pixel program
Define a Uniforms structure and fn shade(frame: ShaderFrame) -> vec4<f32> in your WGSL file. Refract supplies ShaderFrame, the uniforms global, the image sampler, resource bindings, and entry points. Do not declare additional GPU bindings or entry points.
Return straight-alpha sRGB RGBA with components in [0, 1]. The framework handles the output conversion for each renderer. For a program with no parameters, declare one unused f32 member in Uniforms.
struct Uniforms {
intensity: f32,
tint: vec4<f32>,
}
fn shade(frame: ShaderFrame) -> vec4<f32> {
let wave = 0.5 + 0.5 * sin(frame.uv.x * 12.0 + frame.time);
let light = wave * uniforms.intensity;
return vec4<f32>(uniforms.tint.rgb * light, uniforms.tint.a);
}Display the shader
Shader::wgsl(source) accepts an embedded or runtime string and returns Result<Shader, ViewError>. It parses and validates the program with Naga, including source diagnostics on failure. Keep the result in application state or a LazyLock so view evaluation does not parse the same program repeatedly; clones share the program.
Bind parameters by their WGSL member names, then pass the result to shader. Give the view dimensions or let its parent allocate them; shader pixels provide no intrinsic size. Configure shader-specific methods before wrapper modifiers such as padding, frame, or animation.
use refract::prelude::*;
use std::sync::LazyLock;
static WAVE: LazyLock<Shader> = LazyLock::new(|| {
Shader::wgsl(include_str!("wave.wgsl"))
.expect("valid embedded shader")
.fallback(Color::rgb(25, 35, 65))
});
fn illustration() -> impl View {
shader(WAVE.clone()
.uniform("intensity", 0.8_f32)
.uniform("tint", Color::BLUE))
.schedule(ShaderSchedule::Animation)
.width(320.0)
.height(180.0)
.radius(16.0)
.clipped()
.label("Animated blue waves")
}Use local coordinates and time
Refract draws a fullscreen triangle over the content box. ShaderFrame is a WGSL type available inside shade; its coordinates use a top-left origin. Padding and borders surround the content rather than changing the shader's coordinate system.
| Field | Meaning |
|---|---|
position: vec2<f32> | Position in local logical pixels. |
size: vec2<f32> | Content width and height in logical pixels. |
uv: vec2<f32> | Normalized coordinates, with the top-left corner at (0, 0). |
time: f32 | Accumulated visible scheduled time in seconds. |
Bind named uniforms
Shader::uniform(name, value) returns an updated Shader. Members may be f32, vec2<f32>, vec3<f32>, or vec4<f32>. Bind a Rust f32, [f32; 2], [f32; 3], [f32; 4], or Color; colors become normalized RGBA components.
The WGSL layout determines offsets and alignment, so no manual padding bytes are needed. Uniform storage is limited to 16 KiB. Unbound members are zero. Unknown names, mismatched dimensions, and nonfinite values fail validation before the host applies the update. Call Shader::validate() to check bindings explicitly before constructing a view.
Prepare tracked inputs
shader_with(prepare) gives preparation its own mounted dependency boundary. Read a binding with inputs.read(&binding) or inputs.with(&binding, |value| ...), and inherited values with inputs.environment::<K>(). Return a bound Shader; there is no separate Rust drawing callback.
Passing bindings into preparation avoids subscribing the parent to those values. GPU frames consume committed shader inputs without reading the graph, reevaluating view bodies, or rerunning layout. Preparation may be repeated or discarded before commit, so keep it free of effects and state writes.
use refract::prelude::*;
fn reactive_wave(program: Shader, intensity: Binding<f32>) -> impl View {
shader_with(move |inputs| {
program.clone()
.uniform("intensity", inputs.read(&intensity))
.uniform("tint", Color::BLUE)
})
.width(320.0)
.height(180.0)
}Animate uniforms
Add .animatable_inputs() before wrappers to interpolate bound scalar and vector components through existing animation transactions. Change the binding inside with_animation, or use a value-scoped .animation(...) wrapper. Opting in alone does not start motion.
Keep the bound uniform names and vector dimensions stable during an animation. Images and fallback colors switch immediately. Parameter transitions and the shader clock are independent: uniforms can continue interpolating while the clock is paused. See Animation for transactions and interruption behavior.
use refract::prelude::*;
fn animated_wave(program: Shader, intensity: Binding<f32>) -> impl View {
let input = intensity.clone();
shader_with(move |inputs| {
program.clone()
.uniform("intensity", inputs.read(&input))
.uniform("tint", Color::BLUE)
})
.animatable_inputs()
.schedule(ShaderSchedule::Paused)
.width(320.0)
.height(180.0)
.on_press(move |action| {
with_animation(action.runtime(), Animation::spring(), |rt| {
intensity.set(rt, 1.0_f32);
});
})
}As with canvas inputs, with_animation supplies the animation intent when an event updates the binding. The Paused schedule freezes frame.time, not parameter transitions.
Choose when frames run
ShaderSchedule is an alias of CanvasSchedule and follows the same visibility and reduced-motion policy. Hidden surfaces pause their clock. Web and macOS observe the system's reduced-motion preference and suppress continuous time; other native hosts do not yet bridge that preference. Explicit parameter animations still follow their transactions.
| Schedule | Behavior |
|---|---|
ShaderSchedule::OnChange | Default. Render when inputs or dimensions change, with time zero and no continuous frames. |
ShaderSchedule::Animation | Advance visible time and request frames while visible and motion is allowed. ShaderSchedule::animation() constructs this variant. |
ShaderSchedule::Paused | Keep the elapsed phase without requesting continuous frames. Inputs and dimensions can still update; Animation resumes from that phase. |
Sample an image
Bind one immutable image with program.image(ShaderImage::rgba(width, height, pixels)?). Supply straight-alpha sRGB RGBA8 bytes; the length must be exactly width * height * 4. Images must be nonempty and at most 8192 pixels on either axis. Clones share the pixel allocation.
Decode PNG, JPEG, or WebP before binding the image. The shader API performs no network requests or decoding while drawing. In WGSL, sample_image(uv) uses linear filtering and clamp-to-edge addressing and returns straight-alpha sRGB. Without an image, it returns transparent black.
use refract::prelude::*;
fn with_checkerboard(program: Shader) -> Result<Shader, ViewError> {
let pixels = vec![
240, 180, 125, 255, 43, 70, 115, 255,
43, 70, 115, 255, 240, 180, 125, 255,
];
Ok(program.image(ShaderImage::rgba(2, 2, pixels)?))
}Mix image and procedural color
This program uses the same intensity and tint bindings as the wave example, with the checkerboard attached to the program.
struct Uniforms {
intensity: f32,
tint: vec4<f32>,
}
fn shade(frame: ShaderFrame) -> vec4<f32> {
let image = sample_image(frame.uv);
return mix(image, uniforms.tint, clamp(uniforms.intensity, 0.0, 1.0));
}Compose layout, input, and semantics
A shader is one layout and event target. Use .radius(...) with .clipped() for rounded clipping, and ordinary view modifiers for borders, opacity, and transforms. Shader-specific schedule and animatable_inputs preserve ShaderView; configure them before wrapper modifiers. See View Modifiers.
Use ActionContext::local_position(event.position) and local_bounds() for pointer interaction. These describe the handler's border box, so remove padding and borders when mapping to shader content coordinates. Bind the resulting point as an f32 vector uniform. Label meaningful drawings; individual shader pixels are not separate controls. See Input & Focus.
Rendering and fallback
Desktop uses the existing wgpu device and composites the shader texture through Vello. The browser mounts a WebGPU canvas inside the view. Both retain GPU pipelines, uniform buffers, and image textures across updates; resizing recreates the necessary surfaces. Output dimensions are capped at 8192 or the GPU limit while preserving logical coordinates.
WebGPU requires HTTPS or localhost and a usable GPU adapter. Shader::fallback(color) is shown during initialization, in prerendered HTML, and after browser GPU failure; its default is transparent. There is no WebGL fallback. Hydration starts the live GPU surface from the initial view rather than serializing rendered shader pixels.
Removing a view or disposing its mount releases GPU resources. Browser exit transitions capture a static bitmap before releasing the live surface. Failed browser surfaces stop requesting continuous frames; recreating the view retries initialization.
For browser diagnostics, inspect data-refract-shader, whose values are pending, ready, or unavailable, and the error attribute on failure. The shared example in examples/shader demonstrates pointer interaction, clock controls, animated uniforms, and image distortion.
refract dev -p refract-shader
refract dev -p refract-shader --platform desktop