File size: 4,603 Bytes
2b0432b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import * as THREE from 'three'

// Uniforms shared by every material in the world (updated once per frame).
export const U = {
  uTime: { value: 0 },
  uSunDir: { value: new THREE.Vector3(-1, 0.1, 0.2).normalize() },
  uFogSun: { value: new THREE.Color(1, 0.6, 0.35) },
  uFogAway: { value: new THREE.Color(0.5, 0.55, 0.65) },
  uFogDensity: { value: 0.004 },
  uFogFalloff: { value: 0.03 },
  uHaze: { value: 0.00025 },
  uNight: { value: 0 },
  uWind: { value: 1 },
  uWaterLevel: { value: 0 },
  uSunColor: { value: new THREE.Color(1, 0.7, 0.4) }, // colour * intensity (for leaf translucency)
}

const FOG_PARS_V = /* glsl */ `
varying vec3 vFogWorld;
`
const FOG_V = /* glsl */ `
{
  vec4 fw = vec4(transformed, 1.0);
  #ifdef USE_BATCHING
    fw = batchingMatrix * fw;
  #endif
  #ifdef USE_INSTANCING
    fw = instanceMatrix * fw;
  #endif
  vFogWorld = (modelMatrix * fw).xyz;
}
`

export const FOG_FUNC = /* glsl */ `
uniform vec3 uSunDir;
uniform vec3 uFogSun;
uniform vec3 uFogAway;
uniform float uFogDensity;
uniform float uFogFalloff;
uniform float uHaze;
vec3 applyWorldFog(vec3 col, vec3 wp) {
  vec3 rd = wp - cameraPosition;
  float dist = length(rd);
  rd /= max(dist, 1e-3);
  float b = uFogFalloff;
  float k = rd.y * b;
  float integ = abs(k * dist) < 1e-4 ? dist : (1.0 - exp(-k * dist)) / k;
  float fogAmt = uFogDensity * exp(-b * max(cameraPosition.y, -5.0)) * integ;
  float haze = dist * uHaze;
  float f = 1.0 - exp(-max(fogAmt + haze, 0.0));
  float sunAmt = pow(max(dot(rd, uSunDir), 0.0), 5.0);
  vec3 fogCol = mix(uFogAway, uFogSun, sunAmt);
  return mix(col, fogCol, clamp(f, 0.0, 1.0));
}
`

type Shader = THREE.WebGLProgramParametersWithUniforms

export interface PatchOpts {
  /** extra GLSL injected at the end of the vertex shader's begin_vertex (modify `transformed`) */
  vertex?: string
  vertexPars?: string
  /** extra GLSL after the emissivemap chunk (modify totalEmissiveRadiance / diffuseColor) */
  fragment?: string
  fragmentPars?: string
  /** GLSL replacing color multiplication after map sampling */
  colorFrag?: string
  uniforms?: Record<string, { value: unknown }>
  key?: string
  fog?: boolean
}

/** Install the shared height fog (and optional custom code) on a built-in material. */
export function patch<T extends THREE.Material>(mat: T, opts: PatchOpts = {}): T {
  const fog = opts.fog !== false
  const prev = mat.onBeforeCompile
  mat.onBeforeCompile = (shader: Shader, r) => {
    prev?.call(mat, shader, r)
    Object.assign(shader.uniforms, U, opts.uniforms || {})
    let vs = shader.vertexShader
    let fs = shader.fragmentShader
    vs = vs.replace('#include <common>', `#include <common>\nuniform float uTime;\nuniform float uWind;\nuniform float uNight;\n${FOG_PARS_V}\n${opts.vertexPars || ''}`)
    if (opts.vertex) vs = vs.replace('#include <begin_vertex>', `#include <begin_vertex>\n${opts.vertex}`)
    vs = vs.replace('#include <project_vertex>', `#include <project_vertex>\n${FOG_V}`)
    fs = fs.replace('#include <common>', `#include <common>\nuniform float uTime;\nuniform float uNight;\nvarying vec3 vFogWorld;\n${fog ? FOG_FUNC : ''}\n${opts.fragmentPars || ''}`)
    if (opts.colorFrag) fs = fs.replace('#include <color_fragment>', `#include <color_fragment>\n${opts.colorFrag}`)
    if (opts.fragment) fs = fs.replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>\n${opts.fragment}`)
    if (fog) fs = fs.replace('#include <fog_fragment>', `gl_FragColor.rgb = applyWorldFog(gl_FragColor.rgb, vFogWorld);`)
    else fs = fs.replace('#include <fog_fragment>', '')
    shader.vertexShader = vs
    shader.fragmentShader = fs
  }
  mat.customProgramCacheKey = () => 'jn-' + (opts.key || mat.type) + (fog ? 'f' : 'n')
  return mat
}

export function std(params: THREE.MeshStandardMaterialParameters, opts: PatchOpts = {}) {
  return patch(new THREE.MeshStandardMaterial(params), opts)
}

/** Wind sway for vegetation & cloth: needs attribute or uses height above origin. */
export const WIND_VERTEX = /* glsl */ `
{
  vec3 wpos = vec3(0.0);
  #ifdef USE_INSTANCING
    wpos = (modelMatrix * instanceMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;
  #else
    wpos = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;
  #endif
  float hgt = max(transformed.y, 0.0);
  float ph = wpos.x * 0.13 + wpos.z * 0.07;
  float sway = (sin(uTime * 1.3 + ph) * 0.6 + sin(uTime * 2.7 + ph * 1.7) * 0.25) * uWind;
  float flutter = sin(uTime * 7.0 + position.x * 3.0 + position.z * 2.0 + ph) * 0.03 * uWind;
  transformed.x += sway * 0.012 * hgt * hgt + flutter * hgt * 0.15;
  transformed.z += sway * 0.006 * hgt * hgt;
}
`