File size: 5,434 Bytes
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
// Ink outlines for the Toon renderer. Each view is drawn twice into render targets, once in colour and
// once as view-space normals with depth, and a full-screen pass darkens the pixels where the depth jumps
// (silhouettes) or the surface bends sharply (creases). Textures do not draw lines, only shapes do.
import * as THREE from "three";

const VERTEX = /* glsl */ `
varying vec2 vUv;
void main() {
  vUv = uv;
  gl_Position = vec4(position.xy, 0.0, 1.0);
}`;

const FRAGMENT = /* glsl */ `
#include <packing>
uniform sampler2D tColour;
uniform sampler2D tNormal;
uniform sampler2D tDepth;
uniform vec2 texel;
uniform float near;
uniform float far;
uniform vec3 ink;
uniform float strength;
varying vec2 vUv;

float distanceAt(vec2 uv) { return -perspectiveDepthToViewZ(texture2D(tDepth, uv).x, near, far); }
vec3 normalAt(vec2 uv) { return texture2D(tNormal, uv).xyz * 2.0 - 1.0; }

void main() {
  vec4 colour = texture2D(tColour, vUv);
  vec2 dx = vec2(texel.x, 0.0);
  vec2 dy = vec2(0.0, texel.y);
  // Depth: the second difference is ~0 across a plane and large at a step, relative to the distance.
  float z = distanceAt(vUv);
  float zx = abs(distanceAt(vUv - dx) + distanceAt(vUv + dx) - 2.0 * z);
  float zy = abs(distanceAt(vUv - dy) + distanceAt(vUv + dy) - 2.0 * z);
  float silhouette = smoothstep(0.025, 0.07, max(zx, zy) / z);
  // Normals: how far the neighbours turn away.
  vec3 n = normalAt(vUv);
  float bend = max(
    max(1.0 - dot(n, normalAt(vUv - dx)), 1.0 - dot(n, normalAt(vUv + dx))),
    max(1.0 - dot(n, normalAt(vUv - dy)), 1.0 - dot(n, normalAt(vUv + dy))));
  float crease = smoothstep(0.22, 0.5, bend);
  float edge = max(silhouette, crease) * strength;
  gl_FragColor = vec4(mix(colour.rgb, ink, edge), 1.0);
  #include <colorspace_fragment>
}`;

export class OutlinePass {
  constructor({ ink = 0x2e2a27, strength = 0.85 } = {}) {
    this.targets = new Map();
    this.normals = new THREE.MeshNormalMaterial();
    this.material = new THREE.ShaderMaterial({
      uniforms: {
        tColour: { value: null },
        tNormal: { value: null },
        tDepth: { value: null },
        texel: { value: new THREE.Vector2() },
        near: { value: 0.1 },
        far: { value: 100 },
        ink: { value: new THREE.Color(ink) },
        strength: { value: strength },
      },
      vertexShader: VERTEX,
      fragmentShader: FRAGMENT,
      depthTest: false,
      depthWrite: false,
    });
    const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), this.material);
    quad.frustumCulled = false;
    this.screen = new THREE.Scene();
    this.screen.add(quad);
    this.screenCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
    this.clear = new THREE.Color();
  }

  #targetsFor(key, w, h, samples) {
    let t = this.targets.get(key);
    if (t && t.colour.samples !== samples) {
      this.#dispose(t);
      t = null;
    }
    if (!t) {
      // 8-bit sRGB colour: half the memory traffic of half floats, and enough for flat toon shading.
      t = {
        colour: new THREE.WebGLRenderTarget(w, h, { colorSpace: THREE.SRGBColorSpace, samples }),
        normal: new THREE.WebGLRenderTarget(w, h, { depthTexture: new THREE.DepthTexture(w, h) }),
      };
      this.targets.set(key, t);
    }
    if (t.colour.width !== w || t.colour.height !== h) {
      t.colour.setSize(w, h);
      t.normal.setSize(w, h);
    }
    return t;
  }

  /**
   * Draw `scene` from `camera` with outlines into the canvas rectangle `rect` (CSS pixels from the top left;
   * null for the whole canvas). `key` names the view, which keeps its own render targets.
   */
  render(renderer, scene, camera, key, rect = null) {
    const size = renderer.getSize(new THREE.Vector2());
    const r = rect ?? { x: 0, y: 0, w: size.x, h: size.y };
    const pr = renderer.getPixelRatio();
    const w = Math.max(1, Math.round(r.w * pr));
    const h = Math.max(1, Math.round(r.h * pr));
    // Multisampling matters less on a dense screen, where it costs more.
    const t = this.#targetsFor(key, w, h, pr >= 1.75 ? 2 : 4);

    renderer.setRenderTarget(t.colour);
    renderer.render(scene, camera);

    const background = scene.background;
    const clearAlpha = renderer.getClearAlpha();
    renderer.getClearColor(this.clear);
    scene.background = null;
    scene.overrideMaterial = this.normals;
    renderer.setClearColor(0x8080ff, 1); // a normal facing the camera
    renderer.setRenderTarget(t.normal);
    renderer.render(scene, camera);
    scene.overrideMaterial = null;
    scene.background = background;
    renderer.setClearColor(this.clear, clearAlpha);

    const u = this.material.uniforms;
    u.tColour.value = t.colour.texture;
    u.tNormal.value = t.normal.texture;
    u.tDepth.value = t.normal.depthTexture;
    u.texel.value.set(Math.max(1, pr) / w, Math.max(1, pr) / h); // lines about one CSS pixel wide
    u.near.value = camera.near;
    u.far.value = camera.far;
    renderer.setRenderTarget(null);
    const y = size.y - r.y - r.h;
    renderer.setViewport(r.x, y, r.w, r.h);
    renderer.setScissor(r.x, y, r.w, r.h);
    renderer.setScissorTest(true);
    renderer.render(this.screen, this.screenCamera);
    renderer.setScissorTest(false);
  }

  #dispose(t) {
    t.colour.dispose();
    t.normal.depthTexture.dispose();
    t.normal.dispose();
  }

  dispose() {
    for (const t of this.targets.values()) this.#dispose(t);
    this.targets.clear();
  }
}