This site is one 3D scene, built for a computer: a wide window and a mouse. Open dioramajs.dev on a desktop or a laptop to see it.This site is one 3D scene, built for a wide window. Make this one wider, or open dioramajs.dev on a larger screen.
Diorama draws with the three.js WebGPURenderer, so its shaders are TSL nodes. @dioramajs/glsl converts GLSL written for ShaderMaterial, Shadertoy or The Book of Shaders into TSL at build time and turns the file into an effect. The converter runs in Node; the browser gets only the generated TSL. This guide ports rgb-shift, a channel split driven by scroll speed with noise and grain.
Add the plugin
Install the package and add its Vite plugin next to the Diorama plugin. With both, every .frag file in the effects folder is an effect, named after the file.
Terminal window
npminstall@dioramajs/glsl
Terminal window
pnpmadd@dioramajs/glsl
Terminal window
yarnadd@dioramajs/glsl
Terminal window
bunadd@dioramajs/glsl
vite.config.ts
import{
functionglsl(options?:GlslPluginOptions):Plugin
Vite plugin that turns GLSL files into TSL shaders and effects on import.
Vite plugin that turns GLSL files into TSL shaders and effects on import.
glsl()]}
astro.config.mjs
import{ glsl }from'@dioramajs/glsl/vite'
import diorama from'@dioramajs/diorama/astro'
exportdefault{
integrations:[diorama()],
vite:{plugins:[glsl()]},
}
nuxt.config.ts
import{ glsl }from'@dioramajs/glsl/vite'
exportdefaultdefineNuxtConfig({
modules:['@dioramajs/diorama/nuxt'],
vite:{plugins:[glsl()]},
})
Next.js builds with webpack or Turbopack, which use the loader instead of the Vite plugin. See Next.js and the CLI.
A page without a build converts its shaders ahead of time with the CLI. See Next.js and the CLI.
Add the import types to tsconfig.json, so TypeScript knows the ?shader, ?effect and ?entry imports used below.
tsconfig.json
{
"compilerOptions":{
"types":["vite/client","@dioramajs/glsl/client"]
}
}
Copy the shader
Save the GLSL as it is in the effects folder. src/effects/rgb-shift.frag becomes the effect rgb-shift; names are the file name in kebab case, so rgb_shift.frag gives the same name.
Live preview needs WebGPU or WebGL 2. A photo with the rgb-shift shader: scrolling the page fast splits its red and blue channels, at rest only the grain moves.
This example failed to draw.
Scroll this page fast to split the channels. The example uses the default strength of 0.02.
Uniforms bind by name. The plugin strips the u or u_ prefix, so uWaveSize and u_wave_size both read as waveSize, and binds a uniform to an input when the name and the type match. In development it prints one line per file on first load.
vUv and its usual spellings (vUV, v_uv, vTexCoord, vTextureCoord) are the box UV after the uv functions of other effects on the element. A param without // @default starts at 0 with a GLSL_PARAM_DEFAULT warning. uOpacity and uAlpha stay plain params, since the picture already follows the CSS opacity of the element.
Steer it with pragmas
A comment after a uniform overrides its binding. A // @diorama line sets options for the whole file. The file wins over the plugin options and the CLI flags.
@param reveal keeps a uniform named like an input as a param of your own, for a studio shader that tweens uProgress itself. @texture loads a second texture next to the shader. @media names the sampler that gets the element’s picture when the names do not tell.
The same line takes the options that decide where and how the effect runs: when (a media query, see Reduced motion), reducedMotion (static or off) and presence (fade or custom). Quote a media query with spaces.
A value outside these fails the conversion with GLSL_PRAGMA.
Check the frames
The converter picks the frame policy from what the shader reads. uTime draws every frame while the element is on screen, uHoverTime or uHover only around hover, and anything else only on input. rgb-shift reads time and velocity, so the converter adds the note GLSL_ANIMATE: a shader that moves only under the pointer saves frames with uHoverTime in place of uTime. Here the grain is meant to move at rest, so the policy stays.
It also adds GLSL_SEMANTICS for uVelocity. Diorama’s velocity runs from -1 to 1, while a shader written for Lenis may expect pixels per frame; scale the uniform if the split looks too weak or too strong.
Add a glue file
A TypeScript file with the same name as the shader takes its place in the folder. Use it for typed params and for effect options that a pragma cannot set, such as a frame cap.
src/effects/rgb-shift.ts
import{
functionglslEffect<
SextendsParamSpec,
constOextendsParamSpec=Empty
>(
shader:GlslSource<S>,
options?:
&GlslEffectOptions<MergeParams<S,O>>
&{readonly params?:O;}
&CheckParams<O>
):Effect<WidenSpec<MergeParams<S,O>>>
Wraps a GLSL stage pair as an effect. Bindings, params and varyings are checked up front and
reported together as one EFFECT_DEFINITION.
@throws ― {EffectError} EFFECT_DEFINITION with every problem found.
glslEffect}from'@dioramajs/glsl'
import
const shader:GlslShader<ParamSpec>
shaderfrom'./rgb-shift.frag?shader'
exportdefault
glslEffect<ParamSpec,U>(
shader: GlslSource<ParamSpec>,
options?:
|(
GlslEffectOptions<U>
&{ readonly params?: U |undefined; }
& CheckParams<U>
)
|undefined
): Effect<WidenSpec<U>>
typeU={
readonly strength:0.02;
readonly grain:0.06;
}
Wraps a GLSL stage pair as an effect. Bindings, params and varyings are checked up front and
reported together as one EFFECT_DEFINITION.
@throws ― {EffectError} EFFECT_DEFINITION with every problem found.
glslEffect(
const shader:GlslShader<ParamSpec>
shader,{
params?:
|(
{ readonly strength:0.02; readonly grain: 0.06; }
& CheckSpec<
{ readonly strength:0.02; readonly grain: 0.06; }
>
)
|undefined
Override the shader's pragma defaults. Their types become the param types.
params:{
strength:0.02
strength:0.02,
grain:0.06
grain:0.06},
// The grain moves at 24 frames a second; scroll frames run at full rate.
animate?:
| AnimatePolicy<
{ readonly strength:0.02; readonly grain:0.06;}
>
|undefined
Defaults to the update's answer when it returns a boolean, else to what the effect reads:
time animates every visible frame, hoverTime while hovered or hover decays, neither
means 'input'.
animate:{
fps:
| number
|(
(
ctx: EffectContext<
{ readonly strength:0.02; readonly grain: 0.06; }
>
)=> number
)
fps:24},
})
The params of the glue override the defaults of the shader, and the effect types in src/diorama.gen.d.ts now carry strength and grain as numbers. glslEffect takes the other options of effect() too: when, reducedMotion, presence, rebuild, bleed. uniforms rebinds a uniform by GLSL name, as a binding string such as 'input:hover' or as a function of the effect context.
src/effects/dissolve.ts
import{
functionglslEffect<
SextendsParamSpec,
constOextendsParamSpec=Empty
>(
shader:GlslSource<S>,
options?:
&GlslEffectOptions<MergeParams<S,O>>
&{readonly params?:O;}
&CheckParams<O>
):Effect<WidenSpec<MergeParams<S,O>>>
Wraps a GLSL stage pair as an effect. Bindings, params and varyings are checked up front and
reported together as one EFFECT_DEFINITION.
@throws ― {EffectError} EFFECT_DEFINITION with every problem found.
glslEffect}from'@dioramajs/glsl'
import
const shader:GlslShader<ParamSpec>
shaderfrom'./dissolve.frag?shader'
// A page transition fades the copy through
// u.presence; this shader draws it as a dissolve.
exportdefault
glslEffect<ParamSpec,Empty>(
shader: GlslSource<ParamSpec>,
options?:
|(
GlslEffectOptions<Empty>
&{ readonly params?: Empty |undefined; }
& CheckParams<Empty>
)
|undefined
): Effect<WidenSpec<Empty>>
Wraps a GLSL stage pair as an effect. Bindings, params and varyings are checked up front and
reported together as one EFFECT_DEFINITION.
@throws ― {EffectError} EFFECT_DEFINITION with every problem found.
glslEffect(
const shader:GlslShader<ParamSpec>
shader,{
presence?:"fade"|"custom"|undefined
Page transitions. 'fade' (default) multiplies the copy's alpha by u.presence. With
'custom' the effect reads u.presence or input.presence itself.
presence:'custom',
GlslEffectOptions<Empty>.uniforms?:{
readonly [uniform: string]: Binding
|((ctx:EffectContext<Empty>)=> Node);
}
|undefined
Binding overrides, keyed by GLSL uniform name.
uniforms:{
uPresence:(
ctx: EffectContext<Empty>
)=> UniformNode<"float">
uPresence:(
ctx: EffectContext<Empty>
ctx)=>
ctx: EffectContext<Empty>
ctx.
EffectContext<Empty>.u: Uniforms<Empty>
Input uniforms and one uniform per live param, for TSL graphs.
u.
InputUniforms.presence: UniformNode<"float">
1 at rest, 0..1 while the copy enters or leaves a page.
presence},
})
Fix what the converter reports
All errors of one file come together, each with the file, the line, the column and a one-line hint. In Vite they show in the error overlay. The development server checks every shader in the project at start and on save, so a broken shader on a distant page shows up at once.
Code
What happened
What to do
GLSL_SYNTAX
Invalid syntax, or a name that starts with _
Fix the line; if the GLSL is valid, port that function by hand
GLSL_NO_ENTRY
No main or mainImage
Bring a library file in with #include, not with an import
GLSL_INCLUDE
The file is missing, includes itself, or is a three.js #include <chunk>
Use a path relative to the file or a package; paste three.js chunks as text
GLSL_ARRAY
An array
Unroll it into variables or port the function by hand
GLSL_INOUT
An out or inout parameter
Return a value or a struct
GLSL_EARLY_RETURN
return inside a loop
Move the condition into the loop or use break
GLSL_GLOBAL_STATE
A global variable that changes
Make it local to main or a function parameter
GLSL_SAMPLER
It is not clear which sampler is the picture, or texelFetch reads it
A // @diorama line has a bad when, reducedMotion or presence
Use a listed value; quote a media query with spaces
Some GLSL turns into code that three.js r187 runs wrong without a word: a local changed later, an early return inside if, a write to a parameter’s component, mat2 from four numbers, integer division. The converter rewrites these itself and lists each fix as a note in the CLI output.
Supply one function from TypeScript
When one function does not convert, leave its prototype in the GLSL and give the body in TSL. The rest stays GLSL.
src/effects/mist.frag
floatnoise(vec2 p); // the body comes from TypeScript
voidmain(){
gl_FragColor =vec4(vec3(noise(vUv *8.0)),1.0);
}
src/effects/mist.ts
import{
functionglslEffect<
SextendsParamSpec,
constOextendsParamSpec=Empty
>(
shader:GlslSource<S>,
options?:
&GlslEffectOptions<MergeParams<S,O>>
&{readonly params?:O;}
&CheckParams<O>
):Effect<WidenSpec<MergeParams<S,O>>>
Wraps a GLSL stage pair as an effect. Bindings, params and varyings are checked up front and
reported together as one EFFECT_DEFINITION.
@throws ― {EffectError} EFFECT_DEFINITION with every problem found.
Wraps a GLSL stage pair as an effect. Bindings, params and varyings are checked up front and
reported together as one EFFECT_DEFINITION.
@throws ― {EffectError} EFFECT_DEFINITION with every problem found.
glslEffect(
const shader:GlslShader<ParamSpec>
shader,{
GlslEffectOptions<Empty>.functions?:{
readonly [name: string]: ShaderFunction;
}
|undefined
Bodies for GLSL prototypes, written in TSL.
functions:{
noise:(p:Node<"vec2">)=> Node<"float">
noise}})
Port it by hand
A hand port is an ordinary effect file, and it is the way to go when you want to change the shader in TypeScript from now on. Map each GLSL construct to TSL; the imports come from three/tsl.
GLSL
TSL
a + b, a * b, -a
a.add(b), a.mul(b), a.negate()
1.0 - x
x.oneMinus()
float x = 1.0; x += y;
const x = float(1).toVar(); x.addAssign(y)
float lum = dot(c.rgb, w);
const lum = dot(c.rgb, w).toConst() when c changes later
sample() returns linear color, while ShaderMaterial math usually runs on raw sRGB values. For a pixel-exact match, convert around the math with sRGBTransferOETF and sRGBTransferEOTF, as the port below does.
src/effects/rgb-shift.ts
import{
functioneffect(
setup:EffectSetup<Empty>
):Effect<Empty>(+2overloads)
Short form of defineEffect: defaults, optional options, setup. An unnamed effect takes its
registry key (the file name when a build plugin finds it).
The element's media at box UV with crop, contain and radius masks applied; vec4(0) without media.
sample(
uv: Node<"vec2">
Box UV after all uv transforms.
uv).
Swizzle1From4<"float">.a: Node<"float">
a)
})(),
)
},
)
hash and noise are plain TypeScript functions that build nodes, so they need no Fn. Long expressions inside fract(...) can lose their type in the three.js typings; a named variable in between fixes that. To start from the converter’s output instead, run the CLI on the file and read the .frag.js it writes.
Port a vertex shader
A .vert next to a .frag with the same name is part of the same effect, with the params of both. The vertex shader moves the plane of the element: its matrices are identity, x and y are fractions of the box from -0.5 to 0.5, and z is in CSS pixels, so an amplitude of 30 lifts the plane 30 pixels toward the viewer.
animate=hover keeps frames to hover even though the shader reads uTime. A shader that needs a real projection or depth gives wrong results with identity matrices, and the converter cannot detect that.
Know the stages
The converter sorts each shader into a stage, and the stage decides how it stacks with other effects on the element.
uv: the shader reads the picture once at bent coordinates, as its last statement. It becomes a surface.uv() function and adds to the other effects.
color: everything else. The shader sets the whole color and does not see the color of earlier effects, as in the original GLSL, so list it first in data-dio.
gl_FragCoord, iResolution and iMouse are in device pixels of the element’s box, counted from its bottom left corner, not of the screen. Output color matches ShaderMaterial by default, since the shader gets raw sRGB values and its result is encoded back. For a shader written for the linear pipeline of three.js, add // @diorama colorSpace=linear.
Next.js and the CLI
Next.js reads .frag imports through the webpack loader @dioramajs/glsl/loader. With webpack the mode goes in the import query, as in Vite; Turbopack matches rules by path, so the mode goes in the file name. withDiorama does not pick up shaders from the effects folder, so give each shader a glue file there.
Without a bundler, convert ahead of time. The CLI writes rgb-shift.frag.js and rgb-shift.frag.d.ts next to the file and prints the bindings and diagnostics; --check only reports and exits with 1 on an error or a stale .js, for CI.
Terminal window
npxdiorama-glslsrc/effects/*.frag--check
Terminal window
pnpmexecdiorama-glslsrc/effects/*.frag--check
Terminal window
yarndiorama-glslsrc/effects/*.frag--check
Terminal window
bunxdiorama-glslsrc/effects/*.frag--check
Other flags: --out-dir writes elsewhere and keeps the folder layout, --watch converts on save, --json prints the result with line counts and fixes, --bind uMouse=input:pointerNdc and --default uStrength=1 set bindings and defaults from the command line.
Use a shader inside your own effect
shaderNode() turns a fragment shader into a vec4 node for a material you build, and applyShader() adds a shader to the element’s picture from your own setup. Both take the effect context and the same uniforms, textures, functions and colorSpace options as glslEffect. applyShader() returns a function that removes the shader again.
src/effects/poster.ts
import{
functionapplyShader<PextendsParamSpec>(
ctx:EffectContext<P>,
shader:GlslSource,
options?:ApplyOptions
):Off
Adds a shader to the surface from a custom effect's setup. Call the result to remove it.
Needs the or as a texture. Implies on: 'img, video', ready before setup.
'optional' reads it when the element is one and runs without it on other elements.
media:true},(
ctx: EffectContext<
ColorsIn<{ readonly strength:0.5;}>
>
ctx)=>{
const
const material:MeshBasicNodeMaterial
material=new
newMeshBasicNodeMaterial(
parameters?: MeshBasicNodeMaterialParameters
): MeshBasicNodeMaterial
Constructs a new mesh basic node material.
@param ― parameters - The configuration parameter.
MeshBasicNodeMaterial({
transparent?: boolean |undefined
Defines whether this material is transparent. This has an effect on
rendering as transparent objects need special treatment and are rendered
after non-transparent objects.
When set to true, the extent to which the material is transparent is
controlled by
Material#opacity
.
@default ― false
transparent:true})
const material:MeshBasicNodeMaterial
material.
NodeMaterialNodeProperties.colorNode:
| Node<"vec2">
| Node<"vec4">
| Node<"float">
| Node<"vec3">
| Node<"color">
|null
The diffuse color of node materials is by default inferred from the
color and map properties. This node property allows to overwrite the default
and define the diffuse color with a node instead.
material.colorNode=color(0xff0000);// define red color
If you don't want to overwrite the diffuse color but modify the existing
values instead, use
materialColor
.
material.colorNode= materialColor.mul(color(0xff0000));// give diffuse colors a red tint
Adds a shader to the surface from a custom effect's setup. Call the result to remove it.
applyShader(
ctx: EffectContext<
ColorsIn<{ readonly strength:0.5;}>
>
ctx,
const tint:GlslShader<ParamSpec>
tint)
})
The whole port
The converter path is two files: the shader as it was, with two @default pragmas, and an optional glue file.
src/effects/rgb-shift.ts
import{
functionglslEffect<
SextendsParamSpec,
constOextendsParamSpec=Empty
>(
shader:GlslSource<S>,
options?:
&GlslEffectOptions<MergeParams<S,O>>
&{readonly params?:O;}
&CheckParams<O>
):Effect<WidenSpec<MergeParams<S,O>>>
Wraps a GLSL stage pair as an effect. Bindings, params and varyings are checked up front and
reported together as one EFFECT_DEFINITION.
@throws ― {EffectError} EFFECT_DEFINITION with every problem found.
glslEffect}from'@dioramajs/glsl'
import
const shader:GlslShader<ParamSpec>
shaderfrom'./rgb-shift.frag?shader'
exportdefault
glslEffect<ParamSpec,U>(
shader: GlslSource<ParamSpec>,
options?:
|(
GlslEffectOptions<U>
&{ readonly params?: U |undefined; }
& CheckParams<U>
)
|undefined
): Effect<WidenSpec<U>>
typeU={
readonly strength:0.02;
readonly grain:0.06;
}
Wraps a GLSL stage pair as an effect. Bindings, params and varyings are checked up front and
reported together as one EFFECT_DEFINITION.
@throws ― {EffectError} EFFECT_DEFINITION with every problem found.
glslEffect(
const shader:GlslShader<ParamSpec>
shader,{
params?:
|(
{ readonly strength:0.02; readonly grain: 0.06; }
& CheckSpec<
{ readonly strength:0.02; readonly grain: 0.06; }
>
)
|undefined
Override the shader's pragma defaults. Their types become the param types.
params:{
strength:0.02
strength:0.02,
grain:0.06
grain:0.06},
animate?:
| AnimatePolicy<
{ readonly strength:0.02; readonly grain:0.06;}
>
|undefined
Defaults to the update's answer when it returns a boolean, else to what the effect reads:
time animates every visible frame, hoverTime while hovered or hover decays, neither
means 'input'.
animate:{
fps:
| number
|(
(
ctx: EffectContext<
{ readonly strength:0.02; readonly grain: 0.06; }
>
)=> number
)
fps:24},
})
vite.config.ts
import{
functionglsl(options?:GlslPluginOptions):Plugin
Vite plugin that turns GLSL files into TSL shaders and effects on import.