Chuyển đến nội dung

Bài 30 · Shaders and Post-processing

Post-processing in Three.js with EffectComposer

Add bloom, outlines, vignettes and custom full-screen effects to Three.js with EffectComposer, RenderPass, UnrealBloomPass, OutputPass and your own ShaderPass.

Film directors do not ship raw camera footage: they grade the color, add glow to bright lights, and soften the edges. In real-time 3D the same finishing happens in post-processing: after the scene is rendered to an image, a chain of full-screen shaders filters that image before it reaches the screen. Bloom, depth of field, outlines, color grading, film grain, pixelation and glitch effects are all post-processing passes.

Three.js provides this through EffectComposer and a library of ready-made passes in the add-ons. This lesson explains the pipeline, builds a glowing scene with bloom, writes a custom pass, and adds an outline for selected objects.

How the pipeline works

Instead of calling renderer.render(scene, camera), you call composer.render(). The composer owns two off-screen render targets and passes the image between them:

flowchart LR
  S["Scene + camera"] --> R["RenderPass"]
  R --> B["UnrealBloomPass"]
  B --> C["Custom ShaderPass"]
  C --> O["OutputPass (tone mapping + sRGB)"]
  O --> Screen["Canvas"]

Each pass reads the previous pass's image and writes a new one; the last pass writes to the canvas.

The first pass is nearly always a RenderPass, which renders your scene into the first target. Each next pass then reads that image as a texture (tDiffuse) and writes a result. Last, an OutputPass applies the renderer's tone mapping and converts to sRGB; without it, the image looks dark and dull because the earlier passes work in linear HDR color.

JavaScript
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';

const composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
composer.addPass(new UnrealBloomPass(new THREE.Vector2(w, h), 1.0, 0.4, 0.2)); // strength, radius, threshold
composer.addPass(new OutputPass());

renderer.setAnimationLoop(() => composer.render());

When the canvas resizes, call composer.setSize(w, h) (and composer.setPixelRatio) next to renderer.setSize, or the passes will render at the wrong resolution.

Bloom: making bright things glow

UnrealBloomPass takes the brightest parts of the image (above a threshold), blurs them at several scales and adds them back. The effect is a soft halo around anything bright, which sells neon signs, lasers, lava and magic.

Parameters:

Parameter Effect
strength How strong the glow is
radius How far it spreads
threshold Luminance above which pixels glow (0 = everything)

To make only some objects glow, give them colors brighter than 1: new THREE.Color(4, 1, 0.5) or an emissive material with emissiveIntensity: 3, and set the threshold just under 1 so ordinary surfaces stay below it. (Run on renderers with high-precision targets, which the composer uses by default.)

Neon cubes with bloom

Increase strength and the neon cubes wash out; lower threshold to 0.3 and even the grey cubes start to bloom. Tune these three numbers by eye.

Writing a custom ShaderPass

When no built-in pass does what you want, wrap a fragment shader in a ShaderPass. You provide a shader definition object with a tDiffuse uniform (the incoming image), a vertex shader that forwards UVs, and a fragment shader that reads the image with texture2D(tDiffuse, vUv):

JavaScript
const VignetteShader = {
  uniforms: { tDiffuse: { value: null }, uAmount: { value: 0.8 } },
  vertexShader: `varying vec2 vUv;
    void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,
  fragmentShader: `uniform sampler2D tDiffuse; uniform float uAmount; varying vec2 vUv;
    void main() {
      vec4 c = texture2D(tDiffuse, vUv);
      float d = distance(vUv, vec2(0.5));
      c.rgb *= 1.0 - smoothstep(0.35, 0.85, d) * uAmount;
      gl_FragColor = c;
    }`
};
composer.addPass(new ShaderPass(VignetteShader));

You update its uniforms through pass.uniforms.uAmount.value. Place color-space-sensitive passes carefully: passes before OutputPass work on linear HDR values, so a "gray level" threshold written for sRGB will behave differently there.

A custom pass with RGB split and a vignette

The red and blue channels are sampled at slightly shifted positions that grow toward the screen edges: this is how fake lens chromatic aberration is made. Because lens.uniforms.uSplit is an ordinary uniform, you can animate it, for example to punch on impact in a game.

Outlines and anti-aliasing

Two common needs are highlighting a selected object and keeping edges smooth.

OutlinePass draws a colored glowing outline around objects you put in selectedObjects. It is the standard "hover highlight" for editors and configurators.

Anti-aliasing is the catch. The renderer's antialias: true (MSAA) applies only when drawing straight to the canvas, not to the composer's off-screen targets, so passes make edges jagged again. Add an SMAAPass (good quality, moderate cost) or FXAAShader through a ShaderPass (cheap) as the last image pass, before OutputPass, or use a render target with MSAA samples: new EffectComposer(renderer, new THREE.WebGLRenderTarget(w, h, { samples: 4 })).

Outline the selected object

The outline hops from shape to shape every 1.5 seconds. In a real configurator you would assign selectedObjects from a raycast on pointer move (see raycasting).

Cost and choices

  • Every pass is a full-screen draw. Bloom is the expensive one (several blurs); limit the number of passes on mobile and render at a lower resolution with composer.setPixelRatio(1).
  • Order matters: bloom before tone mapping, anti-aliasing after.
  • The pmndrs/postprocessing library merges many effects into fewer passes and is faster than the stack of examples passes; it is the next step when you outgrow EffectComposer.
  • To render only part of the scene with an effect (selective bloom), render that part to a separate target and blend it, or use emissive values above the bloom threshold, as in the neon example.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does the first pass in an EffectComposer usually do?

    RenderPass draws your scene and camera into an off-screen image that the later passes process.
  2. 2. Why do you add an OutputPass at the end?

    Passes work in linear HDR space; OutputPass performs the final tone mapping and color space conversion.
  3. 3. Which UnrealBloomPass setting decides how bright a pixel must be before it glows?

    Pixels below the threshold luminance do not contribute to bloom; strength and radius control intensity and spread.
  4. 4. Why do edges look jagged after adding passes, even with antialias: true?

    Use an SMAA or FXAA pass, or give the composer a multisampled render target.

Summary

  • EffectComposer replaces renderer.render: a RenderPass, then effect passes, then an OutputPass.
  • UnrealBloomPass makes bright pixels glow; control it with strength, radius and threshold.
  • A ShaderPass wraps your own fragment shader that reads tDiffuse; update its uniforms for animation.
  • OutlinePass highlights selectedObjects; add an SMAAPass (or multisampled targets) because MSAA does not reach off-screen passes.
  • Every pass costs a full-screen draw, so keep the chain short, resize the composer with the renderer, and mind the order.

Next: Render Targets and Custom Passes

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.