[WebGL] three.js: Soft Particles
Hello! I'm Fukasawa, a front-end engineer on the client work team. I handle web and Unity implementation.
Today I'd like to show how to implement soft particles in three.js.
Using soft particles, I made a scene of a fox running through a misty atmosphere.
You can see the demo here, and the demo's source in this repository.

About soft particles
What soft particles are
In a nutshell, it's a technique for "comparing depth values to adjust transparency and color".
Characteristics
First, let's compare these images.

The first has soft particles disabled, and the second has them enabled. Looking at the smoke, the difference is that in the first there's a line along the boundary with the floor (ground), while in the second it blends into the floor.
To create a sense of mist, I scattered textured billboard quads of smoke around the floor the fox runs on. Most of the smoke quads poke through the floor (in other words, the quads and the floor intersect), and left as is, the smoke texture gets cut off at the floor boundary as in the first image, which looks unnatural.
So we use soft particles as "a way to blend the boundary where something overlaps other objects".
Approach
If you look at the pixels near the boundary between the floor and the smoke as seen from the camera, the distances from the camera to the floor and to the smoke are very close. Exactly at the boundary, the two distances should be almost the same. We take advantage of this: close in distance means close in depth value.
First, draw the floor and get the floor's depth values. Then compute the depth values when drawing the smoke. At that point, in the smoke's pixel shader, compare the floor's depth value with the smoke's and make the smoke more transparent the closer the two are.
As a result, among the pixels where the smoke is drawn, it fades out from the parts far from the floor toward the parts close to it.
↓ If the area inside the red outline is the part of the quad visible above the floor,

↓ the idea is to make it more transparent where the red is darker (closer to the floor)

In this way, comparing depth values to adjust transparency and color lets you blend where things overlap other objects.
They're called soft "particles", but as in the demo below, you can of course get the same look with objects that aren't scattered around in large numbers like particles.
Implementation in three.js
Here's a simple demo. You should be able to see the fade where they overlap.
The red box has a material that outputs solid red, and the white box has a material with the soft particle shader. The materials use RawShaderMaterial.
See the Pen [test] three.js : soft particle by takumifukasawa (@takumifukasawa) on CodePen.
I also tried objects other than the white box.
↓ A white billboard quad

↓ A billboard quad with a smoke texture: soft particles disabled

↓ A billboard quad with a smoke texture: soft particles enabled

JavaScript
Here's an excerpt of the function run every frame by requestAnimationFrame, with comments added.
// the RenderTarget's width and height are updated separately
const renderTarget = new THREE.WebGLRenderTarget(1, 1);
renderTarget.texture.format = THREE.RGBAFormat;
renderTarget.texture.minFilter = THREE.NearestFilter;
renderTarget.texture.magFilter = THREE.NearestFilter;
renderTarget.texture.generateMipmaps = false;
renderTarget.stencilBuffer = false;
renderTarget.depthBuffer = true;
renderTarget.depthTexture = new THREE.DepthTexture();
renderTarget.depthTexture.type = THREE.UnsignedShortType;
renderTarget.depthTexture.format = THREE.DepthFormat;
...
const tick = () => {
...
const ctx = renderer.getContext();
// ----------------------------------------------------------------------------
// 1. draw the depth of everything except the soft particles (= the red box) into the depth texture
// ----------------------------------------------------------------------------
// hide the soft particle mesh
softParticleMesh.visible = false;
// assign the renderTarget to draw depth into
renderer.setRenderTarget(renderTarget);
// only depth is drawn to the renderTarget, so mask out color
ctx.colorMask(false, false, false, false);
renderer.render(scene, camera);
// ----------------------------------------------------------------------------
// 2. draw every object, including the soft particles
// ----------------------------------------------------------------------------
// unset the renderTarget so it is shown on screen
renderer.setRenderTarget(null);
// show the soft particle mesh
softParticleMesh.visible = true;
// pass the uniforms for depth comparison to the shader
softParticleMesh.material.uniforms.tDepth.value = renderTarget.depthTexture;
softParticleMesh.material.uniforms.cameraNear.value = camera.near;
softParticleMesh.material.uniforms.cameraFar.value = camera.far;
softParticleMesh.material.uniforms.depthFade.value = params.depthFade;
softParticleMesh.material.uniforms.resolution.value = new THREE.Vector2(
width * ratio, height * ratio
);
// remove the color mask and draw
ctx.colorMask(true, true, true, true);
renderer.render(scene, camera);
};
To sum up the flow:
bake the z-buffer of the objects other than the soft particles into a depth texture → pass the depth texture and other needed information to the soft particle shader → draw every object
When baking the z-buffer into the depth texture, I call the WebGL API gl.colorMask directly. This function lets you specify, as flags, which channels to write to the framebuffer.
When you only want depth information you don't need RGBA, so gl.colorMask(false, false, false, false) disables color writes to reduce the load.
WebGLRenderingContext.colorMask() - Web APIs | MDN
GLSL
Here are excerpts of the vertex shader and fragment shader of the white box, which has the soft particle processing. Again, I've added comments.
// ----------------------------------------------------------------------------
// vertex shader
// ----------------------------------------------------------------------------
attribute vec3 position;
attribute vec2 uv;
uniform mat4 projectionMatrix;
uniform mat4 modelViewMatrix;
varying vec4 vViewPosition;
void main() {
// pass the view-space position to the fragment shader
vViewPosition = modelViewMatrix * vec4(position, 1.);
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.);
}
// ----------------------------------------------------------------------------
// pixel shader
// ----------------------------------------------------------------------------
precision highp float;
#include <packing>
varying vec4 vViewPosition;
uniform sampler2D uDepthTexture;
uniform float uCameraNear;
uniform float uCameraFar;
uniform float uDepthFade;
uniform vec2 uResolution;
// refs: https://threejs.org/examples/webgl_depth_texture.html
float readDepth(sampler2D depthSampler, vec2 coord) {
float fragCoordZ = texture2D(depthSampler, coord).x;
float viewZ = perspectiveDepthToViewZ(fragCoordZ, cameraNear, cameraFar);
return viewZToOrthographicDepth(viewZ, cameraNear, cameraFar);
}
void main() {
// get the screen coordinate in 0~1
vec2 screenCoord = gl_FragCoord.xy / uResolution.xy;
// get the depth of the other objects (= the red box) at the current pixel from the depth texture
float sceneDepth = readDepth(uDepthTexture, screenCoord);
// get the depth of the object about to be drawn (= the white box) at the current pixel
float viewZ = vViewPosition.z;
float currentDepth = viewZToOrthographicDepth(viewZ, uCameraNear, uCameraFar);
// compare the depths and fade if the difference is below a threshold
// adjusted to avoid division by zero
float eps = .0001;
float fade = clamp(abs(currentDepth - sceneDepth) / max(uDepthFade, eps), 0., 1.);
gl_FragColor = vec4(vec3(1.), fade);
}
The key is the readDepth function. The function itself is taken from a three.js example.
First, the depth texture holds z-buffer values, and because of the nature of the z-buffer, the values are not linear. So when reading them you need to convert them back to linear based on the camera's near clip and far clip. That's what readDepth does.
I found these articles on the nature of the z-buffer very easy to understand.
Part 71: How precise is the depth buffer?
viewZToOrthographicDepth and perspectiveDepthToViewZ, called inside readDepth, are part of what #include <packing> at the top of the pixel shader expands to.
#include <...> is the notation for inserting three.js GLSL code. It's handy when you want to use shaders tied to three.js features such as fog.
float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
return ( viewZ + near ) / ( near - far );
}
float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {
return ( near * far ) / ( ( far - near ) * invClipZ - far );
}
Points to improve
- On iOS Safari and Chrome, there were artifacts that looked jittery. The cause seems to be a loss of precision when writing or reading the depth texture.
- Right now only the fade threshold can be adjusted, but making two things adjustable, the point where the fade starts and the fade threshold, would probably allow finer tuning.
Creating a mist effect
The demo with the running fox uses soft particles to create a misty atmosphere, but trying to build that atmosphere out of lots of smoke polygons also means more transparent drawing and more overlap, so rendering tends to get heavy.
So to strengthen the misty feel, I think it's a good idea to go easy on the particles (fewer of them, smaller, and so on) and combine them with other techniques, such as distance fog or height fog. The demo with the running fox combines them with three.js's fog (distance fog).

In closing
Thank you for reading this far!
Tomorrow's post is by @fujisawa-satoshi-carp, a very dependable Unity engineer who loves the Hiroshima Carp.