agentleFS
lklynelklyne/skills/tsl/SKILL.md

tsl

Skill0 starsChanged 7 months agoMITView on GitHub

Three.js Shading Language (TSL) — node-based shaders in JS/TS for Three.js WebGPU/WebGL. Use when the user is writing shaders with `three/tsl`, working with `*NodeMaterial` types, composing material slots (colorNode, positionNode, etc.), porting GLSL/WGSL to TSL, building WebGPU compute, or hits TSL-specific errors (immutability, `Fn()` control flow, frozen shaders). Includes TSL-specific React Three Fiber integration (uniform memoization, `.toInput()`, wrapping React state in TSL constructors).

The file

We split this skill into the rules it gives an agent

4 rules. About 0 are common, 3 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Nodes are immutable: Use .toVar() to get a writable variable, .assign() to mutate it.

    line 78
  2. Distinctive:

    Check cheatsheet.md for the exact node name or operator

    line 197
  3. Distinctive:

    Check errors.md for the failure mode

    line 199
  4. Distinctive:

    If using R3F and the shader looks frozen → r3f-integration.md (uniform memoization is the usual cause)

    line 201

≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

TSL — Three.js Shading Language

Node-based shaders authored in JS/TS. Everything is a Node that composes — no GLSL string manipulation.

Canonical docs (always current): https://raw.githubusercontent.com/wiki/mrdoob/three.js/Three.js-Shading-Language.md

WebFetch this URL when you need API specifics — node names, signatures, material slots, the full type system. The local references here are curated wisdom, not a doc mirror.

Quick start

Vanilla Three.js + TSL

import * as THREE from 'three/webgpu'
import { texture, uv, uniform } from 'three/tsl'

const renderer = new THREE.WebGPURenderer()
await renderer.init()                            // required — silent failure otherwise

const material = new THREE.MeshStandardNodeMaterial()
material.colorNode = texture(map, uv())
material.roughnessNode = uniform(0.5)

React Three Fiber + TSL

import { useMemo } from 'react'
import { useFrame } from '@react-three/fiber'
import * as THREE from 'three/webgpu'
import { uniform, positionLocal, mx_noise_float, time } from 'three/tsl'

function Wave() {
  const uniforms = useMemo(() => ({
    speed: uniform(1.0),
    color: uniform(new THREE.Color('#88f')),
  }), [])                                        // stable refs — prevents frozen shader

  const material = useMemo(() => {
    const m = new THREE.MeshStandardNodeMaterial()
    m.positionNode = positionLocal.add(
      mx_noise_float(positionLocal.add(time.mul(uniforms.speed))).mul(0.2)
    )
    m.colorNode = uniforms.color
    return m
  }, [uniforms])

  useFrame((_, delta) => {
    uniforms.speed.value = 1 + Math.sin(performance.now() * 0.001) * 0.5
    // mutate .value only — never setState in useFrame
  })

  return <mesh material={material}><sphereGeometry args={[1, 64, 64]} /></mesh>
}

R3F integration has its own pitfalls — see r3f-integration.md.

Mental model

Build-time vs run-time — TSL code lives in two places:

// BUILD TIME — JS runs once when the shader compiles
if (material.transparent) return transparentShader  // shader variant

// RUN TIME — TSL executes on the GPU per pixel/vertex
If(value.greaterThan(0.5), () => { result.assign(1.0) })

JS if = build-time branching. TSL If (capitalized) = GPU branching. Confusing them is the most common conceptual error.

Nodes are immutable. Use .toVar() to get a writable variable, .assign() to mutate it.

const pos = positionLocal.toVar()
pos.y.assign(pos.y.add(1))   // ok — pos is a writable var

Imports

import * as THREE from 'three/webgpu'           // WebGPU bundle includes TSL
import { Fn, vec3, float, uniform, texture, uv, time } from 'three/tsl'

import * as THREE from 'three' (the WebGL bundle) does not include TSL. import from 'three/nodes' is removed — use 'three/tsl'.

Initialization

const renderer = new THREE.WebGPURenderer()
await renderer.init()      // required — rendering before init fails silently
renderer.render(scene, camera)

Material slots (overview)

Assign TSL nodes to *NodeMaterial slots:

  • Core: colorNode, opacityNode, positionNode, normalNode, emissiveNode
  • PBR: roughnessNode, metalnessNode, aoNode, envNode
  • Physical: transmissionNode, thicknessNode, iorNode, clearcoatNode, sheenNode, anisotropyNode
  • Advanced: backdropNode, fragmentNode, outputNode, lightsNode

Full list and per-material-type details: WebFetch the wiki.

Control flow (inside Fn())

If(a.greaterThan(b), () => { result.assign(a) })
  .ElseIf(a.lessThan(c), () => { result.assign(c) })
  .Else(() => { result.assign(b) })

Loop(count, ({ i }) => { /* ... */ })
Switch(mode).Case(0, () => {}).Default(() => {})

const result = select(condition, a, b)   // works outside Fn() too

Performance — TSL layer

// Cache expensive ops with .toVar() when reused across slots
const noise = mx_noise_float(positionWorld.mul(10)).toVar('cachedNoise')
material.colorNode = noise.mul(0.5)
material.roughnessNode = noise.mul(0.3)

// vertexStage() forces fragment-shader work into the vertex shader (interpolated)
const cheap = vertexStage(expensiveCalc)

See optimization.md for .toVar() / .toConst() / vertexStage() rules.

GLSL → TSL migration

GLSLTSL
positionpositionGeometry
transformedpositionLocal
vWorldPositionpositionWorld
vNormalnormalView
transformedNormalnormalLocal
viewMatrixcameraViewMatrix
modelMatrixmodelWorldMatrix
projectionMatrixcameraProjectionMatrix
texture2D(t, uv)texture(t, uv)
textureCube(t, dir)cubeTexture(t, dir)
gl_FragCoordscreenCoordinate
gl_InstanceIDinstanceIndex
vUv / uvuv()
gl_FragColormaterial.fragmentNode

Swizzles (.xyz, .rgb) work as in GLSL.

Anti-patterns

  • ❌ String GLSL injection / .onBeforeCompile hacks → ✅ TSL nodes only, use material node slots
  • ❌ lowercase if() for GPU branching → ✅ capital If() inside Fn()
  • ❌ Mutating an immutable node (pos.y = ...) → ✅ .toVar() then .assign()
  • ❌ Rendering before await renderer.init() → ✅ always init first
  • ❌ Using the 'three' (WebGL) bundle with TSL → ✅ 'three/webgpu'
  • ❌ Using a JS number where TSL expects a Node (e.g., in mix, step) → ✅ wrap with float() / vec2() / color()

Local references

  • cheatsheet.md — fast lookup: operators, math, geometry/camera/time nodes, material slots (avoid round-tripping the wiki for routine ops)
  • r3f-integration.md — TSL+R3F glue (uniform memoization, .toInput(), wrapping React state, frozen-shader fix)
  • errors.md — debugged failure modes (deprecations, type errors, compute buffer mistakes, control-flow scoping)
  • patterns.md — copy-paste recipes (fresnel, falloff, dissolve, hologram, scanlines, vignette, instance variation, etc.)
  • optimization.md — .toVar() / .toConst() / vertexStage() rules
  • webgpu.md — runtime concerns: renderer init, WebGPU availability, device loss, limits, DPR

Examples

Self-contained TypeScript files demonstrating end-to-end patterns. Vanilla Three.js (no R3F) so the TSL pattern is the focus.

Foundations

  • examples/basic-material.ts — MeshStandardNodeMaterial with TSL slots, animated noise, vertex displacement
  • examples/compute-particles.ts — GPU compute via instancedArray + per-frame kernel, rendered with PointsNodeMaterial
  • examples/post-processing.ts — r183+ RenderPipeline API with MRT and bloom

Advanced techniques

  • examples/compute-tree.ts — compute kernel with inter-element reads (each child reads its parent's position from the same buffer); two-pass init+update pattern
  • examples/compute-boids.ts — Reynolds boids with all-to-all neighbor reads (separation/alignment/cohesion); third major compute pattern after single-element and parent-child
  • examples/glass-refraction.ts — cheap stylized refraction via viewportSharedTexture UV-offset; vertex displacement with recomputed normals through varying
  • examples/glass-volume.ts — physically-motivated IBL volume refraction (Snell via tslRefract, Beer-Lambert attenuation, per-channel IOR for dispersion, anisotropic blur) — same algorithm as Three.js's MeshPhysicalMaterial.transmission, in readable TSL
  • examples/post-dither.ts — custom post-process pass (Bayer matrix ordered dithering) — pattern for building any full-screen effect from scratch

When stuck

  1. Check cheatsheet.md for the exact node name or operator
  2. WebFetch the wiki for full API specifics
  3. Check errors.md for the failure mode
  4. Name vars with .toVar('debugName') and console.log(material.fragmentNode) to read the generated shader
  5. If using R3F and the shader looks frozen → r3f-integration.md (uniform memoization is the usual cause)

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.