-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbvh_gensdf.html
395 lines (275 loc) · 10.5 KB
/
bvh_gensdf.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bvh_Colision_Sample</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
<body>
<script type="importmap">
{
"imports": {
"three": "./three.module.js",
"three/addons/": "./jsm/",
"three-mesh-bvh": "https://cdn.jsdelivr.net/npm/[email protected]/build/index.module.js",
"bvh-gensdf" : "./bvh_gensdf/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/GLTFLoader.js';
import { FullScreenQuad } from 'three/addons/Pass.js';
import { OrbitControls } from 'three/addons/OrbitControls.js';
import { GUI } from 'three/addons/lil-gui.module.min.js';
import Stats from 'three/addons/stats.module.js';
import { GenerateMeshBVHWorker } from 'https://cdn.jsdelivr.net/npm/[email protected]/src/workers/GenerateMeshBVHWorker.js';
import { StaticGeometryGenerator } from 'three-mesh-bvh';
import { GenerateSDFMaterial } from './bvh_gensdf/GenerateSDFMaterial.js';
import { RenderSDFLayerMaterial } from './bvh_gensdf/RenderSDFLayerMaterial.js';
import { RayMarchSDFMaterial } from './bvh_gensdf/RayMarchSDFMaterial.js';
import { MeshoptDecoder } from 'three/addons/meshopt_decoder.module.js';
const params = {
gpuGeneration: true,
resolution: 75,
margin: 0.2,
regenerate: () => updateSDF(),
mode: 'raymarching',
layer: 0,
surface: 0.1,
};
let renderer, camera, scene, gui, stats, boxHelper;
let outputContainer, bvh, geometry, sdfTex, mesh;
let generateSdfPass, layerPass, raymarchPass;
let bvhGenerationWorker;
const inverseBoundsMatrix = new THREE.Matrix4();
init();
render();
function init() {
outputContainer = document.getElementById( 'output' );
// renderer setup
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( 0, 0 );
document.body.appendChild( renderer.domElement );
// scene setup
scene = new THREE.Scene();
const light = new THREE.DirectionalLight( 0xffffff, 1 );
light.position.set( 1, 1, 1 );
scene.add( light );
scene.add( new THREE.AmbientLight( 0xffffff, 0.2 ) );
// camera setup
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 50 );
camera.position.set( 1, 1, 2 );
camera.far = 100;
camera.updateProjectionMatrix();
boxHelper = new THREE.Box3Helper( new THREE.Box3() );
scene.add( boxHelper );
new OrbitControls( camera, renderer.domElement );
// stats setup
stats = new Stats();
document.body.appendChild( stats.dom );
// sdf pass to generate the 3d texture
generateSdfPass = new FullScreenQuad( new GenerateSDFMaterial() );
// screen pass to render a single layer of the 3d texture
layerPass = new FullScreenQuad( new RenderSDFLayerMaterial() );
// screen pass to render the sdf ray marching
raymarchPass = new FullScreenQuad( new RayMarchSDFMaterial() );
// load model and generate bvh
bvhGenerationWorker = new GenerateMeshBVHWorker();
new GLTFLoader()
.setMeshoptDecoder( MeshoptDecoder )
.loadAsync( 'https://raw.githubusercontent.com/gkjohnson/3d-demo-data/main/models/stanford-bunny/bunny.glb' )
.then( gltf => {
gltf.scene.updateMatrixWorld( true );
const staticGen = new StaticGeometryGenerator( gltf.scene );
staticGen.attributes = [ 'position', 'normal' ];
staticGen.useGroups = false;
geometry = staticGen.generate().center();
return bvhGenerationWorker.generate( geometry, { maxLeafTris: 1 } );
} )
.then( result => {
bvh = result;
mesh = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial() );
scene.add( mesh );
updateSDF();
} );
rebuildGUI();
window.addEventListener( 'resize', function () {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}, false );
}
// build the gui with parameters based on the selected display mode
function rebuildGUI() {
if ( gui ) {
gui.destroy();
}
params.layer = Math.min( params.resolution, params.layer );
gui = new GUI();
const generationFolder = gui.addFolder( 'generation' );
generationFolder.add( params, 'gpuGeneration' );
generationFolder.add( params, 'resolution', 10, 200, 1 );
generationFolder.add( params, 'margin', 0, 1 );
generationFolder.add( params, 'regenerate' );
const displayFolder = gui.addFolder( 'display' );
displayFolder.add( params, 'mode', [ 'geometry', 'raymarching', 'layer', 'grid layers' ] ).onChange( () => {
rebuildGUI();
} );
if ( params.mode === 'layer' ) {
displayFolder.add( params, 'layer', 0, params.resolution, 1 );
}
if ( params.mode === 'raymarching' ) {
displayFolder.add( params, 'surface', - 0.2, 0.5 );
}
}
// update the sdf texture based on the selected parameters
function updateSDF() {
const dim = params.resolution;
const matrix = new THREE.Matrix4();
const center = new THREE.Vector3();
const quat = new THREE.Quaternion();
const scale = new THREE.Vector3();
// compute the bounding box of the geometry including the margin which is used to
// define the range of the SDF
geometry.boundingBox.getCenter( center );
scale.subVectors( geometry.boundingBox.max, geometry.boundingBox.min );
scale.x += 2 * params.margin;
scale.y += 2 * params.margin;
scale.z += 2 * params.margin;
matrix.compose( center, quat, scale );
inverseBoundsMatrix.copy( matrix ).invert();
// update the box helper
boxHelper.box.copy( geometry.boundingBox );
boxHelper.box.min.x -= params.margin;
boxHelper.box.min.y -= params.margin;
boxHelper.box.min.z -= params.margin;
boxHelper.box.max.x += params.margin;
boxHelper.box.max.y += params.margin;
boxHelper.box.max.z += params.margin;
// dispose of the existing sdf
if ( sdfTex ) {
sdfTex.dispose();
}
const pxWidth = 1 / dim;
const halfWidth = 0.5 * pxWidth;
const startTime = window.performance.now();
if ( params.gpuGeneration ) {
// create a new 3d render target texture
const floatLinearExtSupported = renderer.extensions.get( 'OES_texture_float_linear' );
sdfTex = new THREE.WebGL3DRenderTarget( dim, dim, dim );
sdfTex.texture.format = THREE.RedFormat;
sdfTex.texture.type = floatLinearExtSupported ? THREE.FloatType : THREE.HalfFloatType;
sdfTex.texture.minFilter = THREE.LinearFilter;
sdfTex.texture.magFilter = THREE.LinearFilter;
// prep the sdf generation material pass
generateSdfPass.material.uniforms.bvh.value.updateFrom( bvh );
generateSdfPass.material.uniforms.matrix.value.copy( matrix );
// render into each layer
for ( let i = 0; i < dim; i ++ ) {
generateSdfPass.material.uniforms.zValue.value = i * pxWidth + halfWidth;
renderer.setRenderTarget( sdfTex, i );
generateSdfPass.render( renderer );
}
// initiate read back to get a rough estimate of time taken to generate the sdf
renderer.readRenderTargetPixels( sdfTex, 0, 0, 1, 1, new Float32Array( 4 ) );
renderer.setRenderTarget( null );
} else {
// create a new 3d data texture
sdfTex = new THREE.Data3DTexture( new Float32Array( dim ** 3 ), dim, dim, dim );
sdfTex.format = THREE.RedFormat;
sdfTex.type = THREE.FloatType;
sdfTex.minFilter = THREE.LinearFilter;
sdfTex.magFilter = THREE.LinearFilter;
sdfTex.needsUpdate = true;
const point = new THREE.Vector3();
const ray = new THREE.Ray();
const target = {};
// iterate over all pixels and check distance
for ( let x = 0; x < dim; x ++ ) {
for ( let y = 0; y < dim; y ++ ) {
for ( let z = 0; z < dim; z ++ ) {
// adjust by half width of the pixel so we sample the pixel center
// and offset by half the box size.
point.set(
halfWidth + x * pxWidth - 0.5,
halfWidth + y * pxWidth - 0.5,
halfWidth + z * pxWidth - 0.5,
).applyMatrix4( matrix );
const index = x + y * dim + z * dim * dim;
const dist = bvh.closestPointToPoint( point, target ).distance;
// raycast inside the mesh to determine if the distance should be positive or negative
ray.origin.copy( point );
ray.direction.set( 0, 0, 1 );
const hit = bvh.raycastFirst( ray, THREE.DoubleSide );
const isInside = hit && hit.face.normal.dot( ray.direction ) > 0.0;
// set the distance in the texture data
sdfTex.image.data[ index ] = isInside ? - dist : dist;
}
}
}
}
// update the timing display
const delta = window.performance.now() - startTime;
outputContainer.innerText = `${ delta.toFixed( 2 ) }ms`;
rebuildGUI();
}
function render() {
stats.update();
requestAnimationFrame( render );
if ( ! sdfTex ) {
// render nothing
return;
} else if ( params.mode === 'geometry' ) {
// render the rasterized geometry
renderer.render( scene, camera );
} else if ( params.mode === 'layer' || params.mode === 'grid layers' ) {
// render a layer of the 3d texture
let tex;
const material = layerPass.material;
if ( sdfTex.isData3DTexture ) {
material.uniforms.layer.value = params.layer / sdfTex.image.width;
material.uniforms.sdfTex.value = sdfTex;
tex = sdfTex;
} else {
material.uniforms.layer.value = params.layer / sdfTex.width;
material.uniforms.sdfTex.value = sdfTex.texture;
tex = sdfTex.texture;
}
material.uniforms.layers.value = tex.image.width;
const gridMode = params.mode === 'layer' ? 0 : 1;
if ( gridMode !== material.defines.DISPLAY_GRID ) {
material.defines.DISPLAY_GRID = gridMode;
material.needsUpdate = true;
}
layerPass.render( renderer );
} else if ( params.mode === 'raymarching' ) {
// render the ray marched texture
camera.updateMatrixWorld();
mesh.updateMatrixWorld();
let tex;
if ( sdfTex.isData3DTexture ) {
tex = sdfTex;
} else {
tex = sdfTex.texture;
}
const { width, depth, height } = tex.image;
raymarchPass.material.uniforms.sdfTex.value = tex;
raymarchPass.material.uniforms.normalStep.value.set( 1 / width, 1 / height, 1 / depth );
raymarchPass.material.uniforms.surface.value = params.surface;
raymarchPass.material.uniforms.projectionInverse.value.copy( camera.projectionMatrixInverse );
raymarchPass.material.uniforms.sdfTransformInverse.value.copy( mesh.matrixWorld ).invert().premultiply( inverseBoundsMatrix ).multiply( camera.matrixWorld );
raymarchPass.render( renderer );
}
}
</script>
</body>
</html>