Octree.js 14 KB

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