webgl_raycaster_bvh.html 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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/[email protected]/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, 3 );
  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. renderer.useLegacyLights = false;
  82. document.body.appendChild( renderer.domElement );
  83. stats = new Stats();
  84. document.body.appendChild( stats.dom );
  85. // raycast visualizations
  86. const lineGeometry = new THREE.BufferGeometry();
  87. lineGeometry.setAttribute( 'position', new THREE.BufferAttribute( new Float32Array( MAX_RAYS * 2 * 3 ), 3 ) );
  88. lineSegments = new THREE.LineSegments( lineGeometry, new THREE.LineBasicMaterial( {
  89. color: RAY_COLOR,
  90. transparent: true,
  91. opacity: 0.25,
  92. depthWrite: false
  93. } ) );
  94. sphereInstance = new THREE.InstancedMesh(
  95. new THREE.SphereGeometry(),
  96. new THREE.MeshBasicMaterial( { color: RAY_COLOR } ),
  97. 2 * MAX_RAYS
  98. );
  99. sphereInstance.instanceMatrix.setUsage( THREE.DynamicDrawUsage );
  100. sphereInstance.count = 0;
  101. scene.add( sphereInstance, lineSegments );
  102. // load the bunny
  103. const loader = new FBXLoader();
  104. loader.load( 'models/fbx/stanford-bunny.fbx', object => {
  105. mesh = object.children[ 0 ];
  106. const geometry = mesh.geometry;
  107. geometry.translate( 0, 0.5 / 0.0075, 0 );
  108. geometry.computeBoundsTree();
  109. bvh = geometry.boundsTree;
  110. if ( ! params.useBVH ) {
  111. geometry.boundsTree = null;
  112. }
  113. scene.add( mesh );
  114. mesh.scale.setScalar( 0.0075 );
  115. helper = new MeshBVHVisualizer( mesh );
  116. helper.color.set( 0xE91E63 );
  117. scene.add( helper );
  118. } );
  119. const controls = new OrbitControls( camera, renderer.domElement );
  120. controls.minDistance = 5;
  121. controls.maxDistance = 75;
  122. // set up gui
  123. const gui = new GUI();
  124. const rayFolder = gui.addFolder( 'Raycasting' );
  125. rayFolder.add( params, 'count', 1, MAX_RAYS, 1 );
  126. rayFolder.add( params, 'firstHitOnly' );
  127. rayFolder.add( params, 'useBVH' ).onChange( v => {
  128. mesh.geometry.boundsTree = v ? bvh : null;
  129. } );
  130. const helperFolder = gui.addFolder( 'BVH Helper' );
  131. helperFolder.add( params, 'displayHelper' );
  132. helperFolder.add( params, 'helperDepth', 1, 20, 1 ).onChange( v => {
  133. helper.depth = v;
  134. helper.update();
  135. } );
  136. window.addEventListener( 'resize', onWindowResize );
  137. onWindowResize();
  138. initRays();
  139. }
  140. function initRays() {
  141. const position = new THREE.Vector3();
  142. const quaternion = new THREE.Quaternion();
  143. const scale = new THREE.Vector3( 1, 1, 1 );
  144. const matrix = new THREE.Matrix4();
  145. for ( let i = 0; i < MAX_RAYS * 2; i ++ ) {
  146. position.randomDirection().multiplyScalar( 3.75 );
  147. matrix.compose( position, quaternion, scale );
  148. sphereInstance.setMatrixAt( i, matrix );
  149. }
  150. }
  151. function updateRays() {
  152. if ( ! mesh ) return;
  153. _raycaster.firstHitOnly = params.firstHitOnly;
  154. const rayCount = params.count;
  155. let lineNum = 0;
  156. for ( let i = 0; i < rayCount; i ++ ) {
  157. // get the current ray origin
  158. sphereInstance.getMatrixAt( i * 2, _matrix );
  159. _matrix.decompose( _position, _quaternion, _scale );
  160. // rotate it about the origin
  161. const offset = 1e-4 * window.performance.now();
  162. _axis.set(
  163. Math.sin( i * 100 + offset ),
  164. Math.cos( - i * 10 + offset ),
  165. Math.sin( i * 1 + offset ),
  166. ).normalize();
  167. _position.applyAxisAngle( _axis, 0.001 );
  168. // update the position
  169. _scale.setScalar( 0.02 );
  170. _matrix.compose( _position, _quaternion, _scale );
  171. sphereInstance.setMatrixAt( i * 2, _matrix );
  172. // raycast
  173. _raycaster.ray.origin.copy( _position );
  174. _raycaster.ray.direction.copy( _position ).multiplyScalar( - 1 ).normalize();
  175. // update hits points and lines
  176. const hits = _raycaster.intersectObject( mesh );
  177. if ( hits.length !== 0 ) {
  178. const hit = hits[ 0 ];
  179. const point = hit.point;
  180. _scale.setScalar( 0.01 );
  181. _matrix.compose( point, _quaternion, _scale );
  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 ++, point.x, point.y, point.z );
  185. } else {
  186. sphereInstance.setMatrixAt( i * 2 + 1, _matrix );
  187. lineSegments.geometry.attributes.position.setXYZ( lineNum ++, _position.x, _position.y, _position.z );
  188. lineSegments.geometry.attributes.position.setXYZ( lineNum ++, 0, 0, 0 );
  189. }
  190. }
  191. sphereInstance.count = rayCount * 2;
  192. sphereInstance.instanceMatrix.needsUpdate = true;
  193. lineSegments.geometry.setDrawRange( 0, lineNum );
  194. lineSegments.geometry.attributes.position.needsUpdate = true;
  195. }
  196. function onWindowResize() {
  197. camera.aspect = window.innerWidth / window.innerHeight;
  198. camera.updateProjectionMatrix();
  199. renderer.setSize( window.innerWidth, window.innerHeight );
  200. }
  201. function animate() {
  202. requestAnimationFrame( animate );
  203. render();
  204. stats.update();
  205. }
  206. function render() {
  207. if ( helper ) {
  208. helper.visible = params.displayHelper;
  209. }
  210. if ( mesh ) {
  211. mesh.rotation.y += 0.002;
  212. mesh.updateMatrixWorld();
  213. }
  214. updateRays();
  215. renderer.render( scene, camera );
  216. }
  217. </script>
  218. </body>
  219. </html>