-
-
Notifications
You must be signed in to change notification settings - Fork 36.4k
Expand file tree
/
Copy pathwebgpu_volume_caustics.html
More file actions
336 lines (227 loc) · 10.2 KB
/
webgpu_volume_caustics.html
File metadata and controls
336 lines (227 loc) · 10.2 KB
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgpu - volumetric caustics</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link type="text/css" rel="stylesheet" href="example.css">
</head>
<body>
<div id="info">
<a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
<div class="title-wrapper">
<a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>Volumetric Caustics</span>
</div>
<small>Real-time volumetric caustics effects.</small>
</div>
<script type="importmap">
{
"imports": {
"three": "../build/three.webgpu.js",
"three/webgpu": "../build/three.webgpu.js",
"three/tsl": "../build/three.tsl.js",
"three/addons/": "./jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three/webgpu';
import { uniform, refract, div, frameId, lightViewPosition, float, positionView, positionViewDirection, screenUV, pass, texture3D, time, screenCoordinate, normalView, texture, Fn, vec2, vec3 } from 'three/tsl';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
import { ImprovedNoise } from 'three/addons/math/ImprovedNoise.js';
import { Inspector } from 'three/addons/inspector/Inspector.js';
import { bayer16 } from 'three/addons/tsl/math/Bayer.js';
import { bloom } from 'three/addons/tsl/display/BloomNode.js';
let camera, scene, renderer, controls;
let postProcessing;
let gltf;
init();
async function init() {
const LAYER_VOLUMETRIC_LIGHTING = 10;
camera = new THREE.PerspectiveCamera( 25, window.innerWidth / window.innerHeight, 0.025, 5 );
camera.position.set( - 0.7, 0.2, 0.2 );
scene = new THREE.Scene();
// Light
const spotLight = new THREE.SpotLight( 0xffffff, 1 );
spotLight.position.set( .2, .3, .2 );
spotLight.castShadow = true;
spotLight.angle = Math.PI / 6;
spotLight.penumbra = 1;
spotLight.decay = 2;
spotLight.distance = 0;
spotLight.shadow.mapType = THREE.HalfFloatType; // For HDR Caustics
spotLight.shadow.mapSize.width = 1024;
spotLight.shadow.mapSize.height = 1024;
spotLight.shadow.camera.near = .1;
spotLight.shadow.camera.far = 1;
spotLight.shadow.bias = - .003;
spotLight.shadow.intensity = .95;
spotLight.layers.enable( LAYER_VOLUMETRIC_LIGHTING );
scene.add( spotLight );
// Model / Textures
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath( 'jsm/libs/draco/' );
dracoLoader.setDecoderConfig( { type: 'js' } );
gltf = ( await new GLTFLoader().setDRACOLoader( dracoLoader ).loadAsync( './models/gltf/duck.glb' ) ).scene;
gltf.scale.setScalar( .5 );
scene.add( gltf );
const causticMap = new THREE.TextureLoader().load( './textures/opengameart/Caustic_Free.jpg' );
causticMap.wrapS = causticMap.wrapT = THREE.RepeatWrapping;
causticMap.colorSpace = THREE.SRGBColorSpace;
// Material
const duck = gltf.children[ 0 ];
duck.material = new THREE.MeshPhysicalNodeMaterial();
duck.material.side = THREE.DoubleSide;
duck.material.transparent = true;
duck.material.color = new THREE.Color( 0xFFD700 );
duck.material.transmission = 1;
duck.material.thickness = .25;
duck.material.ior = 1.5;
duck.material.metalness = 0;
duck.material.roughness = .1;
duck.castShadow = true;
// TSL Shader
const causticOcclusion = uniform( 1 );
const causticEffect = Fn( () => {
const refractionVector = refract( positionViewDirection.negate(), normalView, div( 1.0, duck.material.ior ) ).normalize();
const viewZ = normalView.z.pow( causticOcclusion );
const textureUV = refractionVector.xy.mul( .6 );
const causticColor = uniform( duck.material.color );
const chromaticAberrationOffset = normalView.z.pow( - .9 ).mul( .004 );
const causticProjection = vec3(
texture( causticMap, textureUV.add( vec2( chromaticAberrationOffset.negate(), 0 ) ) ).r,
texture( causticMap, textureUV.add( vec2( 0, chromaticAberrationOffset.negate() ) ) ).g,
texture( causticMap, textureUV.add( vec2( chromaticAberrationOffset, chromaticAberrationOffset ) ) ).b
);
return causticProjection.mul( viewZ.mul( 60 ) ).add( viewZ ).mul( causticColor );
} )().toVar();
duck.material.castShadowNode = causticEffect;
duck.material.emissiveNode = Fn( () => {
// Custom emissive for illuminating backside of the mesh based on the caustic effect and light direction
const thicknessPowerNode = float( 3.0 );
const scatteringHalf = lightViewPosition( spotLight ).sub( positionView ).normalize();
const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ) );
return causticEffect.mul( scatteringDot.add( .1 ) ).mul( .02 );
} )();
// Ground
const textureLoader = new THREE.TextureLoader();
const map = textureLoader.load( 'textures/hardwood2_diffuse.jpg' );
map.wrapS = map.wrapT = THREE.RepeatWrapping;
map.repeat.set( 10, 10 );
const geometry = new THREE.PlaneGeometry( 2, 2 );
const material = new THREE.MeshStandardMaterial( { color: 0 } );
const ground = new THREE.Mesh( geometry, material );
ground.rotation.x = - Math.PI / 2;
ground.receiveShadow = true;
scene.add( ground );
// Renderer
renderer = new THREE.WebGPURenderer( { antialias: true } );
renderer.shadowMap.enabled = true;
renderer.shadowMap.colored = true;
renderer.inspector = new Inspector();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setAnimationLoop( animate );
document.body.appendChild( renderer.domElement );
// GUI
const gui = renderer.inspector.createParameters( 'Volumetric Caustics' );
gui.add( causticOcclusion, 'value', 0, 20 ).name( 'caustic occlusion' );
gui.addColor( duck.material, 'color' ).name( 'material color' );
// Post-Processing
postProcessing = new THREE.PostProcessing( renderer );
// Layers
const volumetricLightingIntensity = uniform( .7 );
const volumetricLayer = new THREE.Layers();
volumetricLayer.disableAll();
volumetricLayer.enable( LAYER_VOLUMETRIC_LIGHTING );
// Volumetric Fog Area
function createTexture3D() {
let i = 0;
const size = 128;
const data = new Uint8Array( size * size * size );
const scale = 10;
const perlin = new ImprovedNoise();
const repeatFactor = 5.0;
for ( let z = 0; z < size; z ++ ) {
for ( let y = 0; y < size; y ++ ) {
for ( let x = 0; x < size; x ++ ) {
const nx = ( x / size ) * repeatFactor;
const ny = ( y / size ) * repeatFactor;
const nz = ( z / size ) * repeatFactor;
const noiseValue = perlin.noise( nx * scale, ny * scale, nz * scale );
data[ i ] = ( 128 + 128 * noiseValue );
i ++;
}
}
}
const texture = new THREE.Data3DTexture( data, size, size, size );
texture.format = THREE.RedFormat;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.unpackAlignment = 1;
texture.needsUpdate = true;
return texture;
}
const noiseTexture3D = createTexture3D();
const smokeAmount = uniform( 3 );
const volumetricMaterial = new THREE.VolumeNodeMaterial();
volumetricMaterial.steps = 20;
volumetricMaterial.offsetNode = bayer16( screenCoordinate.add( frameId ) ); // Add dithering to reduce banding
volumetricMaterial.scatteringNode = Fn( ( { positionRay } ) => {
// Return the amount of fog based on the noise texture
const timeScaled = vec3( time.mul( .01 ), 0, time.mul( .03 ) );
const sampleGrain = ( scale, timeScale = 1 ) => texture3D( noiseTexture3D, positionRay.add( timeScaled.mul( timeScale ) ).mul( scale ).mod( 1 ), 0 ).r.add( .5 );
let density = sampleGrain( 1 );
density = density.mul( sampleGrain( .5, 1 ) );
density = density.mul( sampleGrain( .2, 2 ) );
return smokeAmount.mix( 1, density );
} );
const volumetricMesh = new THREE.Mesh( new THREE.BoxGeometry( 1.5, .5, 1.5 ), volumetricMaterial );
volumetricMesh.receiveShadow = true;
volumetricMesh.position.y = .25;
volumetricMesh.layers.disableAll();
volumetricMesh.layers.enable( LAYER_VOLUMETRIC_LIGHTING );
scene.add( volumetricMesh );
// Scene Pass
const scenePass = pass( scene, camera ).toInspector();
scenePass.name = 'Scene';
const sceneDepth = scenePass.getTextureNode( 'depth' );
sceneDepth.name = 'Scene Depth';
// Material - Apply occlusion depth of volumetric lighting based on the scene depth
volumetricMaterial.depthNode = sceneDepth.sample( screenUV );
// Volumetric Lighting Pass
const volumetricPass = pass( scene, camera, { depthBuffer: false, samples: 0 } ).toInspector( 'Volumetric Lighting / Raw' );
volumetricPass.name = 'Volumetric Lighting';
volumetricPass.setLayers( volumetricLayer );
volumetricPass.setResolutionScale( .5 );
// Compose and Denoise
const bloomPass = bloom( volumetricPass, 1, 1, 0 ).toInspector( 'Volumetric Lighting / Mip-Chain Gaussian Blur' );
bloomPass.name = 'Bloom';
const scenePassColor = scenePass.add( bloomPass.mul( volumetricLightingIntensity ) );
postProcessing.outputNode = scenePassColor;
// Controls
controls = new OrbitControls( camera, renderer.domElement );
controls.target.z = - .05;
controls.target.y = .02;
controls.maxDistance = 1;
window.addEventListener( 'resize', onWindowResize );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
for ( const mesh of gltf.children ) {
mesh.rotation.y -= .01;
}
controls.update();
postProcessing.render();
}
</script>
</body>
</html>