Octree.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. import {
  2. Box3,
  3. Line3,
  4. Plane,
  5. Sphere,
  6. Triangle,
  7. Vector3,
  8. Layers
  9. } from 'three';
  10. import { Capsule } from '../math/Capsule.js';
  11. const _v1 = new Vector3();
  12. const _v2 = new Vector3();
  13. const _point1 = new Vector3();
  14. const _point2 = new Vector3();
  15. const _plane = new Plane();
  16. const _line1 = new Line3();
  17. const _line2 = new Line3();
  18. const _sphere = new Sphere();
  19. const _capsule = new Capsule();
  20. const _temp1 = new Vector3();
  21. const _temp2 = new Vector3();
  22. const _temp3 = new Vector3();
  23. const EPS = 1e-10;
  24. function lineToLineClosestPoints( line1, line2, target1 = null, target2 = null ) {
  25. const r = _temp1.copy( line1.end ).sub( line1.start );
  26. const s = _temp2.copy( line2.end ).sub( line2.start );
  27. const w = _temp3.copy( line2.start ).sub( line1.start );
  28. const a = r.dot( s ),
  29. b = r.dot( r ),
  30. c = s.dot( s ),
  31. d = s.dot( w ),
  32. e = r.dot( w );
  33. let t1, t2;
  34. const divisor = b * c - a * a;
  35. if ( Math.abs( divisor ) < EPS ) {
  36. const d1 = - d / c;
  37. const d2 = ( a - d ) / c;
  38. if ( Math.abs( d1 - 0.5 ) < Math.abs( d2 - 0.5 ) ) {
  39. t1 = 0;
  40. t2 = d1;
  41. } else {
  42. t1 = 1;
  43. t2 = d2;
  44. }
  45. } else {
  46. t1 = ( d * a + e * c ) / divisor;
  47. t2 = ( t1 * a - d ) / c;
  48. }
  49. t2 = Math.max( 0, Math.min( 1, t2 ) );
  50. t1 = Math.max( 0, Math.min( 1, t1 ) );
  51. if ( target1 ) {
  52. target1.copy( r ).multiplyScalar( t1 ).add( line1.start );
  53. }
  54. if ( target2 ) {
  55. target2.copy( s ).multiplyScalar( t2 ).add( line2.start );
  56. }
  57. }
  58. /**
  59. * An octree is a hierarchical tree data structure used to partition a three-dimensional
  60. * space by recursively subdividing it into eight octants.
  61. *
  62. * This particular implementation can have up to sixteen levels and stores up to eight triangles
  63. * in leaf nodes.
  64. *
  65. * `Octree` can be used in games to compute collision between the game world and colliders from
  66. * the player or other dynamic 3D objects.
  67. *
  68. *
  69. * ```js
  70. * const octree = new Octree().fromGraphNode( scene );
  71. * const result = octree.capsuleIntersect( playerCollider ); // collision detection
  72. * ```
  73. *
  74. * @three_import import { Octree } from 'three/addons/math/Octree.js';
  75. */
  76. class Octree {
  77. /**
  78. * Constructs a new Octree.
  79. *
  80. * @param {Box3} [box] - The base box with enclose the entire Octree.
  81. */
  82. constructor( box ) {
  83. /**
  84. * The base box with enclose the entire Octree.
  85. *
  86. * @type {Box3}
  87. */
  88. this.box = box;
  89. /**
  90. * The bounds of the Octree. Compared to {@link Octree#box}, no
  91. * margin is applied.
  92. *
  93. * @type {Box3}
  94. */
  95. this.bounds = new Box3();
  96. /**
  97. * Can by used for layers configuration for refine testing.
  98. *
  99. * @type {Layers}
  100. */
  101. this.layers = new Layers();
  102. // private
  103. this.subTrees = [];
  104. this.triangles = [];
  105. }
  106. /**
  107. * Adds the given triangle to the Octree. The triangle vertices are clamped if they exceed
  108. * the bounds of the Octree.
  109. *
  110. * @param {Triangle} triangle - The triangle to add.
  111. * @return {Octree} A reference to this Octree.
  112. */
  113. addTriangle( triangle ) {
  114. this.bounds.min.x = Math.min( this.bounds.min.x, triangle.a.x, triangle.b.x, triangle.c.x );
  115. this.bounds.min.y = Math.min( this.bounds.min.y, triangle.a.y, triangle.b.y, triangle.c.y );
  116. this.bounds.min.z = Math.min( this.bounds.min.z, triangle.a.z, triangle.b.z, triangle.c.z );
  117. this.bounds.max.x = Math.max( this.bounds.max.x, triangle.a.x, triangle.b.x, triangle.c.x );
  118. this.bounds.max.y = Math.max( this.bounds.max.y, triangle.a.y, triangle.b.y, triangle.c.y );
  119. this.bounds.max.z = Math.max( this.bounds.max.z, triangle.a.z, triangle.b.z, triangle.c.z );
  120. this.triangles.push( triangle );
  121. return this;
  122. }
  123. /**
  124. * Prepares {@link Octree#box} for the build.
  125. *
  126. * @return {Octree} A reference to this Octree.
  127. */
  128. calcBox() {
  129. this.box = this.bounds.clone();
  130. // offset small amount to account for regular grid
  131. this.box.min.x -= 0.01;
  132. this.box.min.y -= 0.01;
  133. this.box.min.z -= 0.01;
  134. return this;
  135. }
  136. /**
  137. * Splits the Octree. This method is used recursively when
  138. * building the Octree.
  139. *
  140. * @param {number} level - The current level.
  141. * @return {Octree} A reference to this Octree.
  142. */
  143. split( level ) {
  144. if ( ! this.box ) return;
  145. const subTrees = [];
  146. const halfsize = _v2.copy( this.box.max ).sub( this.box.min ).multiplyScalar( 0.5 );
  147. for ( let x = 0; x < 2; x ++ ) {
  148. for ( let y = 0; y < 2; y ++ ) {
  149. for ( let z = 0; z < 2; z ++ ) {
  150. const box = new Box3();
  151. const v = _v1.set( x, y, z );
  152. box.min.copy( this.box.min ).add( v.multiply( halfsize ) );
  153. box.max.copy( box.min ).add( halfsize );
  154. subTrees.push( new Octree( box ) );
  155. }
  156. }
  157. }
  158. let triangle;
  159. while ( triangle = this.triangles.pop() ) {
  160. for ( let i = 0; i < subTrees.length; i ++ ) {
  161. if ( subTrees[ i ].box.intersectsTriangle( triangle ) ) {
  162. subTrees[ i ].triangles.push( triangle );
  163. }
  164. }
  165. }
  166. for ( let i = 0; i < subTrees.length; i ++ ) {
  167. const len = subTrees[ i ].triangles.length;
  168. if ( len > 8 && level < 16 ) {
  169. subTrees[ i ].split( level + 1 );
  170. }
  171. if ( len !== 0 ) {
  172. this.subTrees.push( subTrees[ i ] );
  173. }
  174. }
  175. return this;
  176. }
  177. /**
  178. * Builds the Octree.
  179. *
  180. * @return {Octree} A reference to this Octree.
  181. */
  182. build() {
  183. this.calcBox();
  184. this.split( 0 );
  185. return this;
  186. }
  187. /**
  188. * Computes the triangles that potentially intersect with the given ray.
  189. *
  190. * @param {Ray} ray - The ray to test.
  191. * @param {Array<Triangle>} triangles - The target array that holds the triangles.
  192. */
  193. getRayTriangles( ray, triangles ) {
  194. for ( let i = 0; i < this.subTrees.length; i ++ ) {
  195. const subTree = this.subTrees[ i ];
  196. if ( ! ray.intersectsBox( subTree.box ) ) continue;
  197. if ( subTree.triangles.length > 0 ) {
  198. for ( let j = 0; j < subTree.triangles.length; j ++ ) {
  199. if ( triangles.indexOf( subTree.triangles[ j ] ) === - 1 ) triangles.push( subTree.triangles[ j ] );
  200. }
  201. } else {
  202. subTree.getRayTriangles( ray, triangles );
  203. }
  204. }
  205. }
  206. /**
  207. * Computes the intersection between the given capsule and triangle.
  208. *
  209. * @param {Capsule} capsule - The capsule to test.
  210. * @param {Triangle} triangle - The triangle to test.
  211. * @return {Object|false} The intersection object. If no intersection
  212. * is detected, the method returns `false`.
  213. */
  214. triangleCapsuleIntersect( capsule, triangle ) {
  215. triangle.getPlane( _plane );
  216. const d1 = _plane.distanceToPoint( capsule.start ) - capsule.radius;
  217. const d2 = _plane.distanceToPoint( capsule.end ) - capsule.radius;
  218. if ( ( d1 > 0 && d2 > 0 ) || ( d1 < - capsule.radius && d2 < - capsule.radius ) ) {
  219. return false;
  220. }
  221. const delta = Math.abs( d1 / ( Math.abs( d1 ) + Math.abs( d2 ) ) );
  222. const intersectPoint = _v1.copy( capsule.start ).lerp( capsule.end, delta );
  223. if ( triangle.containsPoint( intersectPoint ) ) {
  224. return { normal: _plane.normal.clone(), point: intersectPoint.clone(), depth: Math.abs( Math.min( d1, d2 ) ) };
  225. }
  226. const r2 = capsule.radius * capsule.radius;
  227. const line1 = _line1.set( capsule.start, capsule.end );
  228. const lines = [
  229. [ triangle.a, triangle.b ],
  230. [ triangle.b, triangle.c ],
  231. [ triangle.c, triangle.a ]
  232. ];
  233. for ( let i = 0; i < lines.length; i ++ ) {
  234. const line2 = _line2.set( lines[ i ][ 0 ], lines[ i ][ 1 ] );
  235. lineToLineClosestPoints( line1, line2, _point1, _point2 );
  236. if ( _point1.distanceToSquared( _point2 ) < r2 ) {
  237. return {
  238. normal: _point1.clone().sub( _point2 ).normalize(),
  239. point: _point2.clone(),
  240. depth: capsule.radius - _point1.distanceTo( _point2 )
  241. };
  242. }
  243. }
  244. return false;
  245. }
  246. /**
  247. * Computes the intersection between the given sphere and triangle.
  248. *
  249. * @param {Sphere} sphere - The sphere to test.
  250. * @param {Triangle} triangle - The triangle to test.
  251. * @return {Object|false} The intersection object. If no intersection
  252. * is detected, the method returns `false`.
  253. */
  254. triangleSphereIntersect( sphere, triangle ) {
  255. triangle.getPlane( _plane );
  256. if ( ! sphere.intersectsPlane( _plane ) ) return false;
  257. const depth = Math.abs( _plane.distanceToSphere( sphere ) );
  258. const r2 = sphere.radius * sphere.radius - depth * depth;
  259. const plainPoint = _plane.projectPoint( sphere.center, _v1 );
  260. if ( triangle.containsPoint( sphere.center ) ) {
  261. return { normal: _plane.normal.clone(), point: plainPoint.clone(), depth: Math.abs( _plane.distanceToSphere( sphere ) ) };
  262. }
  263. const lines = [
  264. [ triangle.a, triangle.b ],
  265. [ triangle.b, triangle.c ],
  266. [ triangle.c, triangle.a ]
  267. ];
  268. for ( let i = 0; i < lines.length; i ++ ) {
  269. _line1.set( lines[ i ][ 0 ], lines[ i ][ 1 ] );
  270. _line1.closestPointToPoint( plainPoint, true, _v2 );
  271. const d = _v2.distanceToSquared( sphere.center );
  272. if ( d < r2 ) {
  273. return { normal: sphere.center.clone().sub( _v2 ).normalize(), point: _v2.clone(), depth: sphere.radius - Math.sqrt( d ) };
  274. }
  275. }
  276. return false;
  277. }
  278. /**
  279. * Computes the triangles that potentially intersect with the given bounding sphere.
  280. *
  281. * @param {Sphere} sphere - The sphere to test.
  282. * @param {Array<Triangle>} triangles - The target array that holds the triangles.
  283. */
  284. getSphereTriangles( sphere, triangles ) {
  285. for ( let i = 0; i < this.subTrees.length; i ++ ) {
  286. const subTree = this.subTrees[ i ];
  287. if ( ! sphere.intersectsBox( subTree.box ) ) continue;
  288. if ( subTree.triangles.length > 0 ) {
  289. for ( let j = 0; j < subTree.triangles.length; j ++ ) {
  290. if ( triangles.indexOf( subTree.triangles[ j ] ) === - 1 ) triangles.push( subTree.triangles[ j ] );
  291. }
  292. } else {
  293. subTree.getSphereTriangles( sphere, triangles );
  294. }
  295. }
  296. }
  297. /**
  298. * Computes the triangles that potentially intersect with the given capsule.
  299. *
  300. * @param {Capsule} capsule - The capsule to test.
  301. * @param {Array<Triangle>} triangles - The target array that holds the triangles.
  302. */
  303. getCapsuleTriangles( capsule, triangles ) {
  304. for ( let i = 0; i < this.subTrees.length; i ++ ) {
  305. const subTree = this.subTrees[ i ];
  306. if ( ! capsule.intersectsBox( subTree.box ) ) continue;
  307. if ( subTree.triangles.length > 0 ) {
  308. for ( let j = 0; j < subTree.triangles.length; j ++ ) {
  309. if ( triangles.indexOf( subTree.triangles[ j ] ) === - 1 ) triangles.push( subTree.triangles[ j ] );
  310. }
  311. } else {
  312. subTree.getCapsuleTriangles( capsule, triangles );
  313. }
  314. }
  315. }
  316. /**
  317. * Performs a bounding sphere intersection test with this Octree.
  318. *
  319. * @param {Sphere} sphere - The bounding sphere to test.
  320. * @return {Object|boolean} The intersection object. If no intersection
  321. * is detected, the method returns `false`.
  322. */
  323. sphereIntersect( sphere ) {
  324. _sphere.copy( sphere );
  325. const triangles = [];
  326. let result, hit = false;
  327. this.getSphereTriangles( sphere, triangles );
  328. for ( let i = 0; i < triangles.length; i ++ ) {
  329. if ( result = this.triangleSphereIntersect( _sphere, triangles[ i ] ) ) {
  330. hit = true;
  331. _sphere.center.add( result.normal.multiplyScalar( result.depth ) );
  332. }
  333. }
  334. if ( hit ) {
  335. const collisionVector = _sphere.center.clone().sub( sphere.center );
  336. const depth = collisionVector.length();
  337. return { normal: collisionVector.normalize(), depth: depth };
  338. }
  339. return false;
  340. }
  341. /**
  342. * Performs a capsule intersection test with this Octree.
  343. *
  344. * @param {Capsule} capsule - The capsule to test.
  345. * @return {Object|boolean} The intersection object. If no intersection
  346. * is detected, the method returns `false`.
  347. */
  348. capsuleIntersect( capsule ) {
  349. _capsule.copy( capsule );
  350. const triangles = [];
  351. let result, hit = false;
  352. this.getCapsuleTriangles( _capsule, triangles );
  353. for ( let i = 0; i < triangles.length; i ++ ) {
  354. if ( result = this.triangleCapsuleIntersect( _capsule, triangles[ i ] ) ) {
  355. hit = true;
  356. _capsule.translate( result.normal.multiplyScalar( result.depth ) );
  357. }
  358. }
  359. if ( hit ) {
  360. const collisionVector = _capsule.getCenter( new Vector3() ).sub( capsule.getCenter( _v1 ) );
  361. const depth = collisionVector.length();
  362. return { normal: collisionVector.normalize(), depth: depth };
  363. }
  364. return false;
  365. }
  366. /**
  367. * Performs a ray intersection test with this Octree.
  368. *
  369. * @param {Ray} ray - The ray to test.
  370. * @return {Object|boolean} The nearest intersection object. If no intersection
  371. * is detected, the method returns `false`.
  372. */
  373. rayIntersect( ray ) {
  374. const triangles = [];
  375. let triangle, position, distance = 1e100;
  376. this.getRayTriangles( ray, triangles );
  377. for ( let i = 0; i < triangles.length; i ++ ) {
  378. const result = ray.intersectTriangle( triangles[ i ].a, triangles[ i ].b, triangles[ i ].c, true, _v1 );
  379. if ( result ) {
  380. const newdistance = result.sub( ray.origin ).length();
  381. if ( distance > newdistance ) {
  382. position = result.clone().add( ray.origin );
  383. distance = newdistance;
  384. triangle = triangles[ i ];
  385. }
  386. }
  387. }
  388. return distance < 1e100 ? { distance: distance, triangle: triangle, position: position } : false;
  389. }
  390. /**
  391. * Constructs the Octree from the given 3D object.
  392. *
  393. * @param {Object3D} group - The scene graph node.
  394. * @return {Octree} A reference to this Octree.
  395. */
  396. fromGraphNode( group ) {
  397. group.updateWorldMatrix( true, true );
  398. group.traverse( ( obj ) => {
  399. if ( obj.isMesh === true ) {
  400. if ( this.layers.test( obj.layers ) ) {
  401. let geometry, isTemp = false;
  402. if ( obj.geometry.index !== null ) {
  403. isTemp = true;
  404. geometry = obj.geometry.toNonIndexed();
  405. } else {
  406. geometry = obj.geometry;
  407. }
  408. const positionAttribute = geometry.getAttribute( 'position' );
  409. for ( let i = 0; i < positionAttribute.count; i += 3 ) {
  410. const v1 = new Vector3().fromBufferAttribute( positionAttribute, i );
  411. const v2 = new Vector3().fromBufferAttribute( positionAttribute, i + 1 );
  412. const v3 = new Vector3().fromBufferAttribute( positionAttribute, i + 2 );
  413. v1.applyMatrix4( obj.matrixWorld );
  414. v2.applyMatrix4( obj.matrixWorld );
  415. v3.applyMatrix4( obj.matrixWorld );
  416. this.addTriangle( new Triangle( v1, v2, v3 ) );
  417. }
  418. if ( isTemp ) {
  419. geometry.dispose();
  420. }
  421. }
  422. }
  423. } );
  424. this.build();
  425. return this;
  426. }
  427. /**
  428. * Clears the Octree by making it empty.
  429. *
  430. * @return {Octree} A reference to this Octree.
  431. */
  432. clear() {
  433. this.box = null;
  434. this.bounds.makeEmpty();
  435. this.subTrees.length = 0;
  436. this.triangles.length = 0;
  437. return this;
  438. }
  439. }
  440. export { Octree };