forked from Soft8Soft/verge3d-code-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebgl2_materials_texture3d_partialupdate.html
372 lines (267 loc) · 10.8 KB
/
webgl2_materials_texture3d_partialupdate.html
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
<!DOCTYPE html>
<html lang="en">
<head>
<title>Verge3D webgl2 - volume - cloud</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="main.css">
</head>
<body>
<div id="info">
<a href="https://www.soft8soft.com/verge3d" target="_blank" rel="noopener">Verge3D</a> webgl2 - volume - cloud
</div>
<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"v3d": "../build/v3d.module.js",
"v3d/addons/": "./jsm/"
}
}
</script>
<script type="module">
import * as v3d from 'v3d';
import { OrbitControls } from 'v3d/addons/controls/OrbitControls.js';
import { ImprovedNoise } from 'v3d/addons/math/ImprovedNoise.js';
import { GUI } from 'v3d/addons/libs/lil-gui.module.min.js';
import WebGL from 'v3d/addons/capabilities/WebGL.js';
if (WebGL.isWebGL2Available() === false) {
document.body.appendChild(WebGL.getWebGL2ErrorMessage());
}
const INITIAL_CLOUD_SIZE = 128;
let renderer, scene, camera;
let mesh;
let prevTime = performance.now();
let cloudTexture = null;
init();
animate();
function generateCloudTexture(size, scaleFactor = 1.0) {
const data = new Uint8Array(size * size * size);
const scale = scaleFactor * 10.0 / size;
let i = 0;
const perlin = new ImprovedNoise();
const vector = new v3d.Vector3();
for (let z = 0; z < size; z ++) {
for (let y = 0; y < size; y ++) {
for (let x = 0; x < size; x ++) {
const dist = vector.set(x, y, z).subScalar(size / 2).divideScalar(size).length();
const fadingFactor = (1.0 - dist) * (1.0 - dist);
data[i] = (128 + 128 * perlin.noise(x * scale / 1.5, y * scale, z * scale / 1.5)) * fadingFactor;
i++;
}
}
}
return new v3d.Data3DTexture(data, size, size, size);
}
function init() {
renderer = new v3d.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
scene = new v3d.Scene();
camera = new v3d.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(0, 0, 1.5);
new OrbitControls(camera, renderer.domElement);
// Sky
const canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 32;
const context = canvas.getContext('2d');
const gradient = context.createLinearGradient(0, 0, 0, 32);
gradient.addColorStop(0.0, '#014a84');
gradient.addColorStop(0.5, '#0561a0');
gradient.addColorStop(1.0, '#437ab6');
context.fillStyle = gradient;
context.fillRect(0, 0, 1, 32);
const sky = new v3d.Mesh(
new v3d.SphereGeometry(10),
new v3d.MeshBasicMaterial({ map: new v3d.CanvasTexture(canvas), side: v3d.BackSide })
);
scene.add(sky);
// Texture
const texture = new v3d.Data3DTexture(
new Uint8Array(INITIAL_CLOUD_SIZE * INITIAL_CLOUD_SIZE * INITIAL_CLOUD_SIZE).fill(0),
INITIAL_CLOUD_SIZE,
INITIAL_CLOUD_SIZE,
INITIAL_CLOUD_SIZE
);
texture.format = v3d.RedFormat;
texture.minFilter = v3d.LinearFilter;
texture.magFilter = v3d.LinearFilter;
texture.unpackAlignment = 1;
texture.needsUpdate = true;
cloudTexture = texture;
// Material
const vertexShader = /* glsl */`
in vec3 position;
uniform mat4 modelMatrix;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
uniform vec3 cameraPos;
out vec3 vOrigin;
out vec3 vDirection;
void main() {
vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
vOrigin = vec3(inverse(modelMatrix) * vec4(cameraPos, 1.0)).xyz;
vDirection = position - vOrigin;
gl_Position = projectionMatrix * mvPosition;
}
`;
const fragmentShader = /* glsl */`
precision highp float;
precision highp sampler3D;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
in vec3 vOrigin;
in vec3 vDirection;
out vec4 color;
uniform vec3 base;
uniform sampler3D map;
uniform float threshold;
uniform float range;
uniform float opacity;
uniform float steps;
uniform float frame;
uint wang_hash(uint seed)
{
seed = (seed ^ 61u) ^ (seed >> 16u);
seed *= 9u;
seed = seed ^ (seed >> 4u);
seed *= 0x27d4eb2du;
seed = seed ^ (seed >> 15u);
return seed;
}
float randomFloat(inout uint seed)
{
return float(wang_hash(seed)) / 4294967296.;
}
vec2 hitBox(vec3 orig, vec3 dir) {
const vec3 box_min = vec3(- 0.5);
const vec3 box_max = vec3(0.5);
vec3 inv_dir = 1.0 / dir;
vec3 tmin_tmp = (box_min - orig) * inv_dir;
vec3 tmax_tmp = (box_max - orig) * inv_dir;
vec3 tmin = min(tmin_tmp, tmax_tmp);
vec3 tmax = max(tmin_tmp, tmax_tmp);
float t0 = max(tmin.x, max(tmin.y, tmin.z));
float t1 = min(tmax.x, min(tmax.y, tmax.z));
return vec2(t0, t1);
}
float sample1(vec3 p) {
return texture(map, p).r;
}
float shading(vec3 coord) {
float step = 0.01;
return sample1(coord + vec3(- step)) - sample1(coord + vec3(step));
}
void main(){
vec3 rayDir = normalize(vDirection);
vec2 bounds = hitBox(vOrigin, rayDir);
if (bounds.x > bounds.y) discard;
bounds.x = max(bounds.x, 0.0);
vec3 p = vOrigin + bounds.x * rayDir;
vec3 inc = 1.0 / abs(rayDir);
float delta = min(inc.x, min(inc.y, inc.z));
delta /= steps;
// Jitter
// Nice little seed from
// https://blog.demofox.org/2020/05/25/casual-shadertoy-path-tracing-1-basic-camera-diffuse-emissive/
uint seed = uint(gl_FragCoord.x) * uint(1973) + uint(gl_FragCoord.y) * uint(9277) + uint(frame) * uint(26699);
vec3 size = vec3(textureSize(map, 0));
float randNum = randomFloat(seed) * 2.0 - 1.0;
p += rayDir * randNum * (1.0 / size);
//
vec4 ac = vec4(base, 0.0);
for (float t = bounds.x; t < bounds.y; t += delta) {
float d = sample1(p + 0.5);
d = smoothstep(threshold - range, threshold + range, d) * opacity;
float col = shading(p + 0.5) * 3.0 + ((p.x + p.y) * 0.25) + 0.2;
ac.rgb += (1.0 - ac.a) * d * col;
ac.a += (1.0 - ac.a) * d;
if (ac.a >= 0.95) break;
p += rayDir * delta;
}
color = ac;
if (color.a == 0.0) discard;
}
`;
const geometry = new v3d.BoxGeometry(1, 1, 1);
const material = new v3d.RawShaderMaterial({
glslVersion: v3d.GLSL3,
uniforms: {
base: { value: new v3d.Color(0x798aa0) },
map: { value: texture },
cameraPos: { value: new v3d.Vector3() },
threshold: { value: 0.25 },
opacity: { value: 0.25 },
range: { value: 0.1 },
steps: { value: 100 },
frame: { value: 0 }
},
vertexShader,
fragmentShader,
side: v3d.BackSide,
transparent: true
});
mesh = new v3d.Mesh(geometry, material);
scene.add(mesh);
//
const parameters = {
threshold: 0.25,
opacity: 0.25,
range: 0.1,
steps: 100
};
function update() {
material.uniforms.threshold.value = parameters.threshold;
material.uniforms.opacity.value = parameters.opacity;
material.uniforms.range.value = parameters.range;
material.uniforms.steps.value = parameters.steps;
}
const gui = new GUI();
gui.add(parameters, 'threshold', 0, 1, 0.01).onChange(update);
gui.add(parameters, 'opacity', 0, 1, 0.01).onChange(update);
gui.add(parameters, 'range', 0, 1, 0.01).onChange(update);
gui.add(parameters, 'steps', 0, 200, 1).onChange(update);
window.addEventListener('resize', onWindowResize);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
let curr = 0;
const countPerRow = 4;
const countPerSlice = countPerRow * countPerRow;
const sliceCount = 4;
const totalCount = sliceCount * countPerSlice;
const margins = 8;
const perElementPaddedSize = (INITIAL_CLOUD_SIZE - margins) / countPerRow;
const perElementSize = Math.floor((INITIAL_CLOUD_SIZE - 1) / countPerRow);
function animate() {
requestAnimationFrame(animate);
const time = performance.now();
if (time - prevTime > 1500.0 && curr < totalCount) {
const position = new v3d.Vector3(
Math.floor(curr % countPerRow) * perElementSize + margins * 0.5,
(Math.floor(((curr % countPerSlice) / countPerRow))) * perElementSize + margins * 0.5,
Math.floor(curr / countPerSlice) * perElementSize + margins * 0.5
).floor();
const maxDimension = perElementPaddedSize - 1;
const box = new v3d.Box3(new v3d.Vector3(0, 0, 0), new v3d.Vector3(maxDimension, maxDimension, maxDimension));
const scaleFactor = (Math.random() + 0.5) * 0.5;
const source = generateCloudTexture(perElementPaddedSize, scaleFactor);
renderer.copyTextureToTexture3D(box, position, source, cloudTexture);
prevTime = time;
curr ++;
}
mesh.material.uniforms.cameraPos.value.copy(camera.position);
// mesh.rotation.y = -performance.now() / 7500;
mesh.material.uniforms.frame.value ++;
renderer.render(scene, camera);
}
</script>
</body>
</html>