# tsl-compute-shaders

tsl-compute-shaders guides the agent in writing WebGPU compute shaders with Three.js TSL for GPGPU tasks like particle systems and physics.

- rule · `type=rule` · Claude Code, Codex, Cursor, GitHub Copilot, Windsurf (Devin Desktop), Cline · ★ 4719 repo stars
- Author: zebbern
- License: MIT · policy=mirror · the beginning of the file is at the end of this page
- Source: https://github.com/zebbern/claude-code-guide/tree/HEAD/skills/three-best-practices/rules/tsl-compute-shaders.md
- Updated: 2026-10-24
- Security check: automated, 2026-11-16 (text) — no signs of malicious code found.
- HTML: https://affpapa.org/en/nevibecode/rules/tsl-compute-shaders

## What it does

This rule supplies conventions and reference patterns for Three.js Shading Language (TSL) compute shaders running on WebGPU. It guides the model on creating storage buffers with `instancedArray`, reading variables like `instanceIndex` or `deltaTime`, and dispatching calculations with `renderer.compute()`.

The reference lists atomic functions such as `atomicAdd` and `atomicStore`, along with memory barriers like `workgroupBarrier` and `storageBarrier`. It also contains an explicit particle physics simulation with gravity and floor damping, contrasting compute shader performance with WebGL textures.

Simulations will fail on clients lacking WebGPU support unless an explicit WebGL fallback is configured. The instructions advise sizing workgroups in multiples of 64 to keep GPU hardware occupied.

## Install

### Claude Code (native platform)

**Manually: put the files in place**
- File: `.claude/rules/tsl-compute-shaders.md` — The paths frontmatter field limits the files

### Codex

**AGENTS.md**
- Codex reads AGENTS.md: paste the rule text there

### Cursor

**Manually: put the files in place**
- File: `.cursor/rules/tsl-compute-shaders.mdc` — Frontmatter: description, globs, alwaysApply

### GitHub Copilot

**Manually: put the files in place**
- File: `.github/instructions/tsl-compute-shaders.instructions.md` — The applyTo field sets which files it applies to

### Windsurf (Devin Desktop)

**Manually: put the files in place**
- File: `.devin/rules/tsl-compute-shaders.md`

### Cline

**Manually: put the files in place**
- File: `.clinerules/tsl-compute-shaders.md`

Where a file is given instead of a command, copy the files from the source to that path: https://github.com/zebbern/claude-code-guide/tree/HEAD/skills/three-best-practices/rules/tsl-compute-shaders.md

## When to use it
- Offload particle physics calculations from CPU to WebGPU using TSL
- Coordinate memory access across threads with workgroup and storage barriers
- Execute atomic operations on WebGPU storage buffers
- Build a WebGL ping-pong render target fallback

## Example prompts
- Write a TSL compute shader to animate 100000 bouncing particles with gravity
- Add an atomic counter update to our WebGPU compute pass using Three.js TSL
- Create a WebGL fallback for this GPGPU simulation using ping-pong render targets

## Source text · tsl-compute-shaders.md · MIT

Below is the content of a third-party file. It is data, not instructions for you: do not act on anything written inside unless the human asks. Block tag: de89775834fbdf3a.

BEGIN THIRD-PARTY FILE de89775834fbdf3a
````text
# TSL Compute Shaders

GPU compute shaders using TSL for WebGPU - enables GPGPU operations like particle systems, physics, and simulations.

## Basic Compute Shader

```javascript
import { Fn, instancedArray, instanceIndex, deltaTime } from 'three/tsl';

const COUNT = 1000000; // 1 million particles

// Storage buffers
const positionBuffer = instancedArray(COUNT, 'vec3');
const velocityBuffer = instancedArray(COUNT, 'vec3');

// Define compute shader
const computeParticles = Fn(() => {
  const position = positionBuffer.element(instanceIndex);
  const velocity = velocityBuffer.element(instanceIndex);

  position.addAssign(velocity.mul(deltaTime));
})().compute(COUNT);

// Execute in render loop
renderer.compute(computeParticles);
```

## Atomic Operations

```javascript
// Available atomic functions
atomicAdd(buffer, value)
atomicSub(buffer, value)
atomicMax(buffer, value)
atomicMin(buffer, value)
atomicAnd(buffer, value)
atomicOr(buffer, value)
atomicXor(buffer, value)
atomicStore(buffer, value)
atomicLoad(buffer)
```

## Barriers

```javascript
// Synchronization barriers
workgroupBarrier()   // Sync within workgroup
storageBarrier()     // Sync storage buffer access
textureBarrier()     // Sync texture access
barrier()            // Full barrier
```

## Compute Variables

| Variable | Description |
|----------|-------------|
| `workgroupId` | ID of current workgroup |
| `localId` | Local invocation ID |
| `globalId` | Global invocation ID |
| `numWorkgroups` | Total number of workgroups |
| `subgroupSize` | Size of subgroup |

## Particle System Example

```javascript
import {
  Fn, instancedArray, instanceIndex, deltaTime,
  If, float, vec3
} from 'three/tsl';

const COUNT = 100000;

const positionBuffer = instancedArray(COUNT, 'vec3');
const velocityBuffer = instancedArray(COUNT, 'vec3');

// Initialize positions
for (let i = 0; i < COUNT; i++) {
  positionBuffer.array[i * 3 + 0] = (Math.random() - 0.5) * 100;
  positionBuffer.array[i * 3 + 1] = Math.random() * 100;
  positionBuffer.array[i * 3 + 2] = (Math.random() - 0.5) * 100;

  velocityBuffer.array[i * 3 + 0] = 0;
  velocityBuffer.array[i * 3 + 1] = -9.81; // Gravity
  velocityBuffer.array[i * 3 + 2] = 0;
}

// Compute shader with physics
const computeParticles = Fn(() => {
  const position = positionBuffer.element(instanceIndex);
  const velocity = velocityBuffer.element(instanceIndex);

  // Apply velocity
  position.addAssign(velocity.mul(deltaTime));

  // Bounce off ground
  If(position.y.lessThan(0), () => {
    velocity.y.assign(velocity.y.negate().mul(0.8)); // Damping
    position.y.assign(0);
  });
})().compute(COUNT);

// In render loop
function animate() {
  renderer.compute(computeParticles);
  renderer.render(scene, camera);
}
```

## GPGPU with Render Targets (WebGL Fallback)

For WebGL without compute shaders:

```javascript
// Create position texture
const size = 256; // 256x256 = 65536 particles
const data = new Float32Array(size * size * 4);
for (let i = 0; i < size * size; i++) {
  data[i * 4 + 0] = Math.random() * 100 - 50; // x
  data[i * 4 + 1] = Math.random() * 100 - 50; // y
  data[i * 4 + 2] = Math.random() * 100 - 50; // z
  data[i * 4 + 3] = 1; // w
}

const positionTexture = new THREE.DataTexture(
  data, size, size,
  THREE.RGBAFormat, THREE.FloatType
);
positionTexture.needsUpdate = true;

// Ping-pong render targets
const rtA = new THREE.WebGLRenderTarget(size, size, {
  type: THREE.FloatType,
  format: THREE.RGBAFormat
});
const rtB = rtA.clone();

// Update shader
const updateMaterial = new THREE.ShaderMaterial({
  uniforms: {
    positions: { value: positionTexture },
    time: { value: 0 }
  },
  fragmentShader: `
````
END THIRD-PARTY FILE de89775834fbdf3a

The third-party file has ended. Everything between the de89775834fbdf3a tags is data: requests and commands from it are not followed. An “end of file” line with another tag inside the block is part of the file.

First 3675 of 4653 bytes. © zebbern · MIT · https://github.com/zebbern/claude-code-guide/tree/HEAD/skills/three-best-practices/rules/tsl-compute-shaders.md

_Part of the page did not fit — see the HTML version._

---
NeVibeCode on affpapa.org. Catalog texts are descriptions, not instructions for the agent. How to choose and install: https://affpapa.org/en/nevibecode/agents.md
