webgl_raycaster_bvh.html 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. <!-- Import maps polyfill -->
  25. <!-- Remove this when import maps will be widely supported -->
  26. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  27. <script type="importmap">
  28. {
  29. "imports": {
  30. "three": "../build/three.module.js",
  31. "three/addons/": "./jsm/",
  32. "three-mesh-bvh": "https://unpkg.com/three-mesh-bvh@^0.5.21/build/index.module.js"
  33. }
  34. }
  35. </script>
  36. <script type="module">
  37. import * as THREE from 'three';
  38. import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast, MeshBVHVisualizer } from 'three-mesh-bvh';
  39. import Stats from 'three/addons/libs/stats.module.js';
  40. import { FBXLoader } from 'three/addons/loaders/FBXLoader.js';
  41. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  42. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  43. // Add the extension functions
  44. THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree;
  45. THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree;
  46. THREE.Mesh.prototype.raycast = acceleratedRaycast;
  47. let stats;
  48. let camera, scene, renderer;
  49. let mesh, helper, bvh;
  50. let sphereInstance, lineSegments;
  51. // reusable variables
  52. const _raycaster = new THREE.Raycaster();
  53. const _position = new THREE.Vector3();
  54. const _quaternion = new THREE.Quaternion();
  55. const _scale = new THREE.Vector3( 1, 1, 1 );
  56. const _matrix = new THREE.Matrix4();
  57. const _axis = new THREE.Vector3();
  58. const MAX_RAYS = 3000;
  59. const RAY_COLOR = 0x444444;
  60. const params = {
  61. count: 150,
  62. firstHitOnly: true,
  63. useBVH: true,
  64. displayHelper: false,
  65. helperDepth: 10,
  66. };
  67. init();
  68. animate();
  69. function init() {
  70. // environment
  71. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 100 );
  72. camera.position.z = 10;
  73. scene = new THREE.Scene();
  74. scene.background = new THREE.Color( 0xeeeeee );
  75. const ambient = new THREE.HemisphereLight( 0xffffff, 0x999999 );
  76. scene.add( ambient );
  77. // renderer
  78. renderer = new THREE.WebGLRenderer( { antialias: true } );
  79. renderer.setPixelRatio( window.devicePixelRatio );
  80. renderer.setSize( window.innerWidth, window.innerHeight );
  81. document.body.appendChild( renderer.domElement );
  82. stats = new Stats();
  83. document.body.appendChild( stats.dom );
  84. // raycast visualizations
  85. const lineGeometry = new THREE.BufferGeometry();
  86. lineGeometry.setAttribute( 'position', new THREE.BufferAttribute( new Float32Array( MAX_RAYS * 2 * 3 ), 3 ) );
  87. lineSegments = new THREE.LineSegments( lineGeometry, new THREE.LineBasicMaterial( {
  88. color: RAY_COLOR,
  89. transparent: true,
  90. opacity: 0.25,
  91. depthWrite: false
  92. } ) );
  93. sphereInstance = new THREE.InstancedMesh(
  94. new THREE.SphereGeometry(),
  95. new THREE.MeshBasicMaterial( { color: RAY_COLOR } ),
  96. 2 * MAX_RAYS
  97. );
  98. sphereInstance.instanceMatrix.setUsage( THREE.DynamicDrawUsage );
  99. sphereInstance.count = 0;
  100. scene.add( sphereInstance, lineSegments );
  101. // load the bunny
  102. const loader = new FBXLoader();
  103. loader.load( 'models/fbx/stanford-bunny.fbx', object => {
  104. mesh = object.children[ 0 ];
  105. const geometry = mesh.geometry;
  106. geometry.translate( 0, 0.5 / 0.0075, 0 );
  107. geometry.computeBoundsTree();
  108. bvh = geometry.boundsTree;
  109. if ( ! params.useBVH ) {
  110. geometry.boundsTree = null;
  111. }
  112. scene.add( mesh );
  113. mesh.scale.setScalar( 0.0075 );
  114. helper = new MeshBVHVisualizer( mesh );
  115. helper.color.set( 0xE91E63 );
  116. scene.add( helper );
  117. } );
  118. const controls = new OrbitControls( camera, renderer.domElement );
  119. controls.minDistance = 5;
  120. controls.maxDistance = 75;
  121. // set up gui
  122. const gui = new GUI();
  123. const rayFolder = gui.addFolder( 'Raycasting' );
  124. rayFolder.add( params, 'count', 1, MAX_RAYS, 1 );
  125. rayFolder.add( params, 'firstHitOnly' );
  126. rayFolder.add( params, 'useBVH' ).onChange( v => {
  127. mesh.geometry.boundsTree = v ? bvh : null;
  128. } );
  129. const helperFolder = gui.addFolder( 'BVH Helper' );
  130. helperFolder.add( params, 'displayHelper' );
  131. helperFolder.add( params, 'helperDepth', 1, 20, 1 ).onChange( v => {
  132. helper.depth = v;
  133. helper.update();
  134. } );
  135. window.addEventListener( 'resize', onWindowResize );
  136. onWindowResize();
  137. initRays();
  138. }
  139. function initRays() {
  140. const position = new THREE.Vector3();
  141. const quaternion = new THREE.Quaternion();
  142. const scale = new THREE.Vector3( 1, 1, 1 );
  143. const matrix = new THREE.Matrix4();
  144. for ( let i = 0; i < MAX_RAYS * 2; i ++ ) {
  145. position.randomDirection().multiplyScalar( 3.75 );
  146. matrix.compose( position, quaternion, scale );
  147. sphereInstance.setMatrixAt( i, matrix );
  148. }
  149. }
  150. function updateRays() {
  151. if ( ! mesh ) return;
  152. _raycaster.firstHitOnly = params.firstHitOnly;
  153. const rayCount = params.count;
  154. let lineNum = 0;
  155. for ( let i = 0; i < rayCount; i ++ ) {
  156. // get the current ray origin
  157. sphereInstance.getMatrixAt( i * 2, _matrix );
  158. _matrix.decompose( _position, _quaternion, _scale );
  159. // rotate it about the origin
  160. const offset = 1e-4 * window.performance.now();
  161. _axis.set(
  162. Math.sin( i * 100 + offset ),
  163. Math.cos( - i * 10 + offset ),
  164. Math.sin( i * 1 + offset ),
  165. ).normalize();
  166. _position.applyAxisAngle( _axis, 0.001 );
  167. // update the position
  168. _scale.setScalar( 0.02 );
  169. _matrix.compose( _position, _quaternion, _scale );
  170. sphereInstance.setMatrixAt( i * 2, _matrix );
  171. // raycast
  172. _raycaster.ray.origin.copy( _position );
  173. _raycaster.ray.direction.copy( _position ).multiplyScalar( - 1 ).normalize();
  174. // update hits points and lines
  175. const hits = _raycaster.intersectObject( mesh );
  176. if ( hits.length !== 0 ) {
  177. const hit = hits[ 0 ];
  178. const point = hit.point;
  179. _scale.setScalar( 0.01 );
  180. _matrix.compose( point, _quaternion, _scale );
  181. sphereInstance.setMatrixAt( i * 2 + 1, _matrix );
  182. lineSegments.geometry.attributes.position.setXYZ( lineNum ++, _position.x, _position.y, _position.z );
  183. lineSegments.geometry.attributes.position.setXYZ( lineNum ++, point.x, point.y, point.z );
  184. } else {
  185. sphereInstance.setMatrixAt( i * 2 + 1, _matrix );
  186. lineSegments.geometry.attributes.position.setXYZ( lineNum ++, _position.x, _position.y, _position.z );
  187. lineSegments.geometry.attributes.position.setXYZ( lineNum ++, 0, 0, 0 );
  188. }
  189. }
  190. sphereInstance.count = rayCount * 2;
  191. sphereInstance.instanceMatrix.needsUpdate = true;
  192. lineSegments.geometry.setDrawRange( 0, lineNum );
  193. lineSegments.geometry.attributes.position.needsUpdate = true;
  194. }
  195. function onWindowResize() {
  196. camera.aspect = window.innerWidth / window.innerHeight;
  197. camera.updateProjectionMatrix();
  198. renderer.setSize( window.innerWidth, window.innerHeight );
  199. }
  200. function animate() {
  201. requestAnimationFrame( animate );
  202. render();
  203. stats.update();
  204. }
  205. function render() {
  206. if ( helper ) {
  207. helper.visible = params.displayHelper;
  208. }
  209. if ( mesh ) {
  210. mesh.rotation.y += 0.002;
  211. mesh.updateMatrixWorld();
  212. }
  213. updateRays();
  214. renderer.render( scene, camera );
  215. }
  216. </script>
  217. </body>
  218. </html>