Three WebGPU Renderer
The Three.js library has recently started to support the experimental WebGPU API. Threejs support is still under heavy development and not all browsers support it.
The WebGPU API offers enhanced performance and more direct access to GPU hardware. WebGPU is intended to be a successor to WebGL and WebGL2 offering more flexible capabilities.
In three.js we can use the WebGPU API by instantiating a THREE.WebGPURenderer
instead of a THREE.WebGLRenderer.
When using the THREE.WebGPURenderer
, we can also write our code using the new TSL (Three Shader Language) API. This will allow us to create custom shaders using a language more similar to JavaScript, while the transpiled output will be automatically converted to either GLSL or WGSL depending on the capabilities of our browser.
- GLSL is the shading language when using the WebGL or WebGL2 APIs, and is supported by most browsers.
- WGSL is the shading language when using the WebGPU API. WebGPU is newer and experimental, so not all browsers support it yet.
Below is an example of some shader code written using TSL. When the code is transpiled at runtime, your browser will execute either GLSL or WGSL depending on the capabilities of your browser. The TSL transpiler did this automatically.
The above working example is using importmaps and you can view the source.
Below is a script that you can paste into the TypeScript Vite boilerplate that was created in this course.
./src/main.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
|
To summarize when using a build tool such as vite.
- import * as THREE from 'three'
+ import * as THREE from 'three/webgpu'
- const renderer = new THREE.WebGLRenderer()
+ const renderer = new THREE.WebGPURenderer()
Using TSL is optional and can be imported separately. E.g.,
import { positionLocal, Fn, uniform, vec3, time, sin } from 'three/tsl'
Also note that instead of calling requestAnimationFrame(animate)
in an animation loop to continually re-render, you can remove the requestAnimationFrame
line and set your chosen animation loop function using the renderers own API.
//..
renderer.setAnimationLoop(animate) // add this line
//..
function animate() {
// requestAnimationFrame(animate) // delete this line.
renderer.render(scene, camera)
}