Shaders
nano-ui supports typed, composable GPU fragment shaders on layout nodes across all three GPU backends: SDL (OpenGL 3.2+ via GLSL 150 on Windows, and SDL 3.4+ Metal/Vulkan via MSL and SPIR-V elsewhere), RGFW (OpenGL 3.2 via GLSL 150), and the browser backend (WebGL2 via GLSL ES 300).
The core nano-ui package defines the shader types, std140 uniform packing (Uniforms), and the two widget entry points (shaderBox and withShader). The companion nano-ui-shader package adds a pure-Haskell typed fragment EDSL, compilers for all four GPU formats plus a CPU reference evaluator, algebraic pass fusion, and 21 standard effects.
Two tiers
Every shader has a type-level kind (ShaderKind) that separates leaf fills from subtree post-processing:
Surface(Tier 1): Draws a single layout leaf (shaderBox,shaderConfigured) in one draw call with zero offscreen render targets. Use this for gradients, procedural textures, SDF shapes, and color wheels.ColorEffect,DistortionEffect, andLayerEffect(Tier 2): Wrap any widget subtree (withShader) by rendering its children into a pooled 64px-bucketed offscreen texture and compositing the result through one or more shader passes. Controls inside the subtree remain interactive.
Passing a Surface shader to withShader is a compile-time type error (IsNodeEffect).
Leaf surface shaders
Call shaderBox for a quick leaf fill or shaderConfigured when you need a corner radius, tint, or fallback color for backends without GPU shaders (such as SDL’s software renderer):
heroBanner :: NanoUI ()
heroBanner =
shaderConfigured cfg meshGradient4 params
where
cfg =
defaultShaderConfig
{ scLayout = fixedH 140 . fillW
, scCornerRadius = 12
, scFallback = colorRGB 40 80 180
}
params =
MeshGradientParams
{ mgTopLeft = colorRGB 40 90 220
, mgTopRight = colorRGB 220 60 150
, mgBottomLeft = colorRGB 20 180 160
, mgBottomRight = colorRGB 245 190 50
}
Define shaders as top-level bindings so the EDSL compiles once per shader, not on every frame. Changing the uniform value re-packs only the uniform bytes and triggers a local damage repaint on that node. Leaving the uniform unchanged produces zero damage, so idle windows remain asleep.
Custom shaders and uniforms
Uniform records derive Uniforms via GHC.Generics. nano-ui packs fields to exact std140 alignment, zero-pads every block to a 16-byte multiple, and hashes the packed bytes for damage diffing:
data PulseParams = PulseParams
{ ppColor :: !Color
, ppPhase :: !Float
, ppRings :: !Float
}
deriving (Eq, Generic, Uniforms)
Supported field types are Float, Int32, Word32, Bool, V2, V3, V4, Color (unpacked to normalized RGBA vec4), Rect, Size, tuples, and nested Generic records.
With OverloadedRecordDot, both uniform fields (u.ppColor) and GLSL-style vector swizzles (u.ppColor.rgb, ctx.uv.xy) resolve at compile time with no Template Haskell:
pulseRing :: Shader 'Surface PulseParams
pulseRing = surfaceShader $ \u ctx ->
let centered = ctx.uv *^ 2.0 - vec2 1.0 1.0
dist = vLength centered
wave = 0.5 + 0.5 * sin (dist * u.ppRings - u.ppPhase)
half = ctx.size *^ 0.5
edge = sdRoundedBox (ctx.pos - half) half ctx.cornerRadius
aa = 0.75 / maxE ctx.scale 1.0
mask = 1.0 - smoothstep (negate aa) aa edge
in vec4_31 (u.ppColor.rgb *^ wave) (u.ppColor.a * mask)
Every fragment shader receives a FragCtx containing ctx.uv (normalized [0, 1] over the node rect), ctx.pos (logical pixels from the node’s top-left corner), ctx.size (logical width and height), ctx.origin (window-space logical origin), ctx.scale (device pixels per logical unit), ctx.cornerRadius, and ctx.color (vertex tint).
Subtree effects and pass fusion
Wrap any view with withShader to apply a post-processing effect to the whole rendered subtree:
blurredCard :: Float -> NanoUI () -> NanoUI ()
blurredCard sigma body =
withShader gaussianBlur sigma (panel body)
gaussianBlur runs two separable 1D passes (horizontal then vertical) by alternating between pooled offscreen targets. Its bleed margin (3 * sigma pixels on each side) expands the offscreen target, cull test, and partial-damage region automatically so soft halos never clip at the widget edge. Use withShader' when you need both the subtree’s return value and its Response.
Compatible effects fuse into a single GPU pass with zero extra offscreen targets:
composeColor :: Shader 'ColorEffect u1 -> Shader 'ColorEffect u2 -> Shader 'ColorEffect (u1, u2)composeDistort :: Shader 'DistortionEffect u1 -> Shader 'DistortionEffect u2 -> Shader 'DistortionEffect (u1, u2)distortThenColor :: Shader 'DistortionEffect u1 -> Shader 'ColorEffect u2 -> Shader 'LayerEffect (u1, u2)chainLayerchains arbitrary multi-pass effects explicitly.
disabledTint :: Shader 'ColorEffect (Float, TintParams)
disabledTint = composeColor grayscale tint
dimmedPanel :: NanoUI () -> NanoUI ()
dimmedPanel body =
withShader disabledTint (0.85, TintParams (colorRGB 30 60 110) 0.25) (panel body)
Bounded loops in FragM
Iterative kernels (blurs, shadows, multi-octave noise) use the FragM builder (surfaceShaderM, colorEffectM, distortionEffectM, layerEffectM) with explicit bind, branchless selection (selectE), and structured forRange loops:
boxAverage5 :: Shader 'LayerEffect Float
boxAverage5 =
layerEffectM (\step -> V2 (2 * abs step) (2 * abs step)) $ \u ctx layer -> do
step <- bind (maxE (uVal u) 0.0)
zero <- bind (vec4 0.0 0.0 0.0 0.0)
acc <- forRange (-2) 3 zero $ \iy rowAcc ->
forRange (-2) 3 rowAcc $ \ix colAcc -> do
let offset = vec2 (intToFloat ix * step) (intToFloat iy * step)
sample = sampleLayer layer (ctx.pos + offset)
pure (colAcc + sample)
pure (acc *^ (1.0 / 25.0))
The first argument to layerEffectM reports the maximum sample offset in logical pixels (V2 marginX marginY) for the current uniform value. If you want to supply hand-written GLSL, MSL, or SPIR-V sources directly without the EDSL, import NanoUI.Shader.Raw from nano-ui.
Built-in effects
NanoUI.Shader ships 21 ready-to-use shaders:
| Category | Shaders |
|---|---|
Surface | meshGradient4, radialGlow, sdfRoundedBox, colorWheelHsv, noiseGrain, checkerboard |
ColorEffect | groupOpacity, grayscale, tint, brightnessContrast, colorMatrix, vignette, scanlines |
DistortionEffect | waveDistort, rippleDistort, pixelate |
LayerEffect | boxBlur, gaussianBlur, dropShadow, outerGlow, chromaticAberration |
Capabilities, fallbacks, and SVG export
Under RenderDriverAuto, Windows uses SDL’s "opengl" driver (which runs GLSL 150 shaders directly with higher frame rates and smooth live window resizing), while macOS and Linux prefer SDL 3.4’s "gpu" driver (falling back to standard drivers or software rendering when unavailable). Inspect live GPU support inside a view with askShaderCapabilities:
shaderStatus :: NanoUI ()
shaderStatus = do
caps <- askShaderCapabilities
if capSurfaceShaders caps
then label "GPU shaders active"
else label "Using flat fallback color"
When a backend lacks GPU shader support:
shaderBox/shaderConfigureddraws a flat rounded rectangle inscFallback(usingscCornerRadius).withShaderrenders its children directly without offscreen redirection.nano-ui-svgexportswithShader groupOpacity alphaas a native SVG<g opacity="...">group.
For a complete runnable program covering both tiers and animated uniforms, see packages/nano-ui-demo/examples/Shaders.hs (cabal run nano-ui-example-shaders).