webgl_raycaster_bvh.html 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js raycaster - bvh</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. <style>
  9. body {
  10. background-color: #eeeeee;
  11. color: #333;
  12. }
  13. a {
  14. color: #E91E63;
  15. text-decoration: underline;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <div id="info">
  21. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> raycaster - <a href="https://github.com/gkjohnson/three-mesh-bvh" target="_blank" rel="noopener">three-mesh-bvh</a><br/>
  22. See <a href="https://github.com/gkjohnson/three-mesh-bvh" target="_blank" rel="noopener">main project repository</a> for more information and examples on high performance spatial queries.
  23. </div>
  24. <script type="importmap">
  25. {
  26. "imports": {
  27. "three": "../build/three.module.js",
  28. "three/addons/": "./jsm/",
  29. "three-mesh-bvh": "https://cdn.jsdelivr.net/npm/three-mesh-bvh@0.7.3/build/index.module.js"
  30. }
  31. }
  32. </script>
  33. <script type="module">
  34. import * as THREE from 'three';
  35. import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast, MeshBVHHelper } from 'three-mesh-bvh';
  36. import Stats from 'three/addons/libs/stats.module.js';
  37. import { FBXLoader } from 'three/addons/loaders/FBXLoader.js';
  38. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  39. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  40. // Add the extension functions
  41. THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree;
  42. THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree;
  43. THREE.Mesh.prototype.raycast = acceleratedRaycast;
  44. let stats;
  45. let camera, scene, renderer;
  46. let mesh, helper, bvh;
  47. let sphereInstance, lineSegments;
  48. // reusable variables
  49. const _raycaster = new THREE.Raycaster();
  50. const _position = new THREE.Vector3();
  51. const _quaternion = new THREE.Quaternion();
  52. const _scale = new THREE.Vector3( 1, 1, 1 );
  53. const _matrix = new THREE.Matrix4();
  54. const _axis = new THREE.Vector3();
  55. const MAX_RAYS = 3000;
  56. const RAY_COLOR = 0x444444;
  57. const params = {
  58. count: 150,
  59. firstHitOnly: true,
  60. useBVH: true,
  61. displayHelper: false,
  62. helperDepth: 10,
  63. };
  64. init();
  65. function init() {
  66. // environment
  67. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 100 );
  68. camera.position.z = 10;
  69. scene = new THREE.Scene();
  70. scene.background = new THREE.Color( 0xeeeeee );
  71. const ambient = new THREE.HemisphereLight( 0xffffff, 0x999999, 3 );
  72. scene.add( ambient );
  73. // renderer
  74. renderer = new THREE.WebGLRenderer( { antialias: true } );
  75. renderer.setPixelRatio( window.devicePixelRatio );
  76. renderer.setSize( window.innerWidth, window.innerHeight );
  77. renderer.setAnimationLoop( animate );
  78. document.body.appendChild( renderer.domElement );
  79. stats = new Stats();
  80. document.body.appendChild( stats.dom );
  81. // raycast visualizations
  82. const lineGeometry = new THREE.BufferGeometry();
  83. lineGeometry.setAttribute( 'position', new THREE.BufferAttribute( new Float32Array( MAX_RAYS * 2 * 3 ), 3 ) );
  84. lineSegments = new THREE.LineSegments( lineGeometry, new THREE.LineBasicMaterial( {
  85. color: RAY_COLOR,
  86. transparent: true,
  87. opacity: 0.25,
  88. depthWrite: false
  89. } ) );
  90. sphereInstance = new THREE.InstancedMesh(
  91. new THREE.SphereGeometry(),
  92. new THREE.MeshBasicMaterial( { color: RAY_COLOR } ),
  93. 2 * MAX_RAYS
  94. );
  95. sphereInstance.instanceMatrix.setUsage( THREE.DynamicDrawUsage );
  96. sphereInstance.count = 0;
  97. scene.add( sphereInstance, lineSegments );
  98. // load the bunny
  99. const loader = new FBXLoader();
  100. loader.load( 'models/fbx/stanford-bunny.fbx', object => {
  101. mesh = object.children[ 0 ];
  102. const geometry = mesh.geometry;
  103. geometry.translate( 0, 0.5 / 0.0075, 0 );
  104. geometry.computeBoundsTree();
  105. bvh = geometry.boundsTree;
  106. if ( ! params.useBVH ) {
  107. geometry.boundsTree = null;
  108. }
  109. scene.add( mesh );
  110. mesh.scale.setScalar( 0.0075 );
  111. helper = new MeshBVHHelper( mesh );
  112. helper.color.set( 0xE91E63 );
  113. scene.add( helper );
  114. } );
  115. const controls = new OrbitControls( camera, renderer.domElement );
  116. controls.minDistance = 5;
  117. controls.maxDistance = 75;
  118. // set up gui
  119. const gui = new GUI();
  120. const rayFolder = gui.addFolder( 'Raycasting' );
  121. rayFolder.add( params, 'count', 1, MAX_RAYS, 1 );
  122. rayFolder.add( params, 'firstHitOnly' );
  123. rayFolder.add( params, 'useBVH' ).onChange( v => {
  124. mesh.geometry.boundsTree = v ? bvh : null;
  125. } );
  126. const helperFolder = gui.addFolder( 'BVH Helper' );
  127. helperFolder.add( params, 'displayHelper' );
  128. helperFolder.add( params, 'helperDepth', 1, 20, 1 ).onChange( v => {
  129. helper.depth = v;
  130. helper.update();
  131. } );
  132. window.addEventListener( 'resize', onWindowResize );
  133. onWindowResize();
  134. initRays();
  135. }
  136. function initRays() {
  137. const position = new THREE.Vector3();
  138. const quaternion = new THREE.Quaternion();
  139. const scale = new THREE.Vector3( 1, 1, 1 );
  140. const matrix = new THREE.Matrix4();
  141. for ( let i = 0; i < MAX_RAYS * 2; i ++ ) {
  142. position.randomDirection().multiplyScalar( 3.75 );
  143. matrix.compose( position, quaternion, scale );
  144. sphereInstance.setMatrixAt( i, matrix );
  145. }
  146. }
  147. function updateRays() {
  148. if ( ! mesh ) return;
  149. _raycaster.firstHitOnly = params.firstHitOnly;
  150. const rayCount = params.count;
  151. let lineNum = 0;
  152. for ( let i = 0; i < rayCount; i ++ ) {
  153. // get the current ray origin
  154. sphereInstance.getMatrixAt( i * 2, _matrix );
  155. _matrix.decompose( _position, _quaternion, _scale );
  156. // rotate it about the origin
  157. const offset = 1e-4 * window.performance.now();
  158. _axis.set(
  159. Math.sin( i * 100 + offset ),
  160. Math.cos( - i * 10 + offset ),
  161. Math.sin( i * 1 + offset ),
  162. ).normalize();
  163. _position.applyAxisAngle( _axis, 0.001 );
  164. // update the position
  165. _scale.setScalar( 0.02 );
  166. _matrix.compose( _position, _quaternion, _scale );
  167. sphereInstance.setMatrixAt( i * 2, _matrix );
  168. // raycast
  169. _raycaster.ray.origin.copy( _position );
  170. _raycaster.ray.direction.copy( _position ).multiplyScalar( - 1 ).normalize();
  171. // update hits points and lines
  172. const hits = _raycaster.intersectObject( mesh );
  173. if ( hits.length !== 0 ) {
  174. const hit = hits[ 0 ];
  175. const point = hit.point;
  176. _scale.setScalar( 0.01 );
  177. _matrix.compose( point, _quaternion, _scale );
  178. sphereInstance.setMatrixAt( i * 2 + 1, _matrix );
  179. lineSegments.geometry.attributes.position.setXYZ( lineNum ++, _position.x, _position.y, _position.z );
  180. lineSegments.geometry.attributes.position.setXYZ( lineNum ++, point.x, point.y, point.z );
  181. } else {
  182. sphereInstance.setMatrixAt( i * 2 + 1, _matrix );
  183. lineSegments.geometry.attributes.position.setXYZ( lineNum ++, _position.x, _position.y, _position.z );
  184. lineSegments.geometry.attributes.position.setXYZ( lineNum ++, 0, 0, 0 );
  185. }
  186. }
  187. sphereInstance.count = rayCount * 2;
  188. sphereInstance.instanceMatrix.needsUpdate = true;
  189. lineSegments.geometry.setDrawRange( 0, lineNum );
  190. lineSegments.geometry.attributes.position.needsUpdate = true;
  191. }
  192. function onWindowResize() {
  193. camera.aspect = window.innerWidth / window.innerHeight;
  194. camera.updateProjectionMatrix();
  195. renderer.setSize( window.innerWidth, window.innerHeight );
  196. }
  197. function animate() {
  198. render();
  199. stats.update();
  200. }
  201. function render() {
  202. if ( helper ) {
  203. helper.visible = params.displayHelper;
  204. }
  205. if ( mesh ) {
  206. mesh.rotation.y += 0.002;
  207. mesh.updateMatrixWorld();
  208. }
  209. updateRays();
  210. renderer.render( scene, camera );
  211. }
  212. </script>
  213. </body>
  214. </html>