Octree.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112
  1. /*!
  2. *
  3. * threeoctree.js (r60) / https://github.com/collinhover/threeoctree
  4. * (sparse) dynamic 3D spatial representation structure for fast searches.
  5. *
  6. * @author Collin Hover / http://collinhover.com/
  7. * based on Dynamic Octree by Piko3D @ http://www.piko3d.com/ and Octree by Marek Pawlowski @ pawlowski.it
  8. *
  9. */
  10. ( function ( THREE ) { "use strict";
  11. /*===================================================
  12. utility
  13. =====================================================*/
  14. function isNumber ( n ) {
  15. return !isNaN( n ) && isFinite( n );
  16. }
  17. function isArray ( target ) {
  18. return Object.prototype.toString.call( target ) === '[object Array]';
  19. }
  20. function toArray ( target ) {
  21. return target ? ( isArray ( target ) !== true ? [ target ] : target ) : [];
  22. }
  23. function indexOfValue( array, value ) {
  24. for ( var i = 0, il = array.length; i < il; i++ ) {
  25. if ( array[ i ] === value ) {
  26. return i;
  27. }
  28. }
  29. return -1;
  30. }
  31. function indexOfPropertyWithValue( array, property, value ) {
  32. for ( var i = 0, il = array.length; i < il; i++ ) {
  33. if ( array[ i ][ property ] === value ) {
  34. return i;
  35. }
  36. }
  37. return -1;
  38. }
  39. /*===================================================
  40. octree
  41. =====================================================*/
  42. THREE.Octree = function ( parameters ) {
  43. // handle parameters
  44. parameters = parameters || {};
  45. parameters.tree = this;
  46. // static properties ( modification is not recommended )
  47. this.nodeCount = 0;
  48. this.INDEX_INSIDE_CROSS = -1;
  49. this.INDEX_OUTSIDE_OFFSET = 2;
  50. this.INDEX_OUTSIDE_POS_X = isNumber( parameters.INDEX_OUTSIDE_POS_X ) ? parameters.INDEX_OUTSIDE_POS_X : 0;
  51. this.INDEX_OUTSIDE_NEG_X = isNumber( parameters.INDEX_OUTSIDE_NEG_X ) ? parameters.INDEX_OUTSIDE_NEG_X : 1;
  52. this.INDEX_OUTSIDE_POS_Y = isNumber( parameters.INDEX_OUTSIDE_POS_Y ) ? parameters.INDEX_OUTSIDE_POS_Y : 2;
  53. this.INDEX_OUTSIDE_NEG_Y = isNumber( parameters.INDEX_OUTSIDE_NEG_Y ) ? parameters.INDEX_OUTSIDE_NEG_Y : 3;
  54. this.INDEX_OUTSIDE_POS_Z = isNumber( parameters.INDEX_OUTSIDE_POS_Z ) ? parameters.INDEX_OUTSIDE_POS_Z : 4;
  55. this.INDEX_OUTSIDE_NEG_Z = isNumber( parameters.INDEX_OUTSIDE_NEG_Z ) ? parameters.INDEX_OUTSIDE_NEG_Z : 5;
  56. this.INDEX_OUTSIDE_MAP = [];
  57. this.INDEX_OUTSIDE_MAP[ this.INDEX_OUTSIDE_POS_X ] = { index: this.INDEX_OUTSIDE_POS_X, count: 0, x: 1, y: 0, z: 0 };
  58. this.INDEX_OUTSIDE_MAP[ this.INDEX_OUTSIDE_NEG_X ] = { index: this.INDEX_OUTSIDE_NEG_X, count: 0, x: -1, y: 0, z: 0 };
  59. this.INDEX_OUTSIDE_MAP[ this.INDEX_OUTSIDE_POS_Y ] = { index: this.INDEX_OUTSIDE_POS_Y, count: 0, x: 0, y: 1, z: 0 };
  60. this.INDEX_OUTSIDE_MAP[ this.INDEX_OUTSIDE_NEG_Y ] = { index: this.INDEX_OUTSIDE_NEG_Y, count: 0, x: 0, y: -1, z: 0 };
  61. this.INDEX_OUTSIDE_MAP[ this.INDEX_OUTSIDE_POS_Z ] = { index: this.INDEX_OUTSIDE_POS_Z, count: 0, x: 0, y: 0, z: 1 };
  62. this.INDEX_OUTSIDE_MAP[ this.INDEX_OUTSIDE_NEG_Z ] = { index: this.INDEX_OUTSIDE_NEG_Z, count: 0, x: 0, y: 0, z: -1 };
  63. this.FLAG_POS_X = 1 << ( this.INDEX_OUTSIDE_POS_X + 1 );
  64. this.FLAG_NEG_X = 1 << ( this.INDEX_OUTSIDE_NEG_X + 1 );
  65. this.FLAG_POS_Y = 1 << ( this.INDEX_OUTSIDE_POS_Y + 1 );
  66. this.FLAG_NEG_Y = 1 << ( this.INDEX_OUTSIDE_NEG_Y + 1 );
  67. this.FLAG_POS_Z = 1 << ( this.INDEX_OUTSIDE_POS_Z + 1 );
  68. this.FLAG_NEG_Z = 1 << ( this.INDEX_OUTSIDE_NEG_Z + 1 );
  69. this.utilVec31Search = new THREE.Vector3();
  70. this.utilVec32Search = new THREE.Vector3();
  71. // pass scene to see octree structure
  72. this.scene = parameters.scene;
  73. if ( this.scene ) {
  74. this.visualGeometry = new THREE.BoxGeometry( 1, 1, 1 );
  75. this.visualMaterial = new THREE.MeshBasicMaterial( { color: 0xFF0066, wireframe: true, wireframeLinewidth: 1 } );
  76. }
  77. // properties
  78. this.objects = [];
  79. this.objectsMap = {};
  80. this.objectsData = [];
  81. this.objectsDeferred = [];
  82. this.depthMax = isNumber( parameters.depthMax ) ? parameters.depthMax : Infinity;
  83. this.objectsThreshold = isNumber( parameters.objectsThreshold ) ? parameters.objectsThreshold : 8;
  84. this.overlapPct = isNumber( parameters.overlapPct ) ? parameters.overlapPct : 0.15;
  85. this.undeferred = parameters.undeferred || false;
  86. this.root = parameters.root instanceof THREE.OctreeNode ? parameters.root : new THREE.OctreeNode( parameters );
  87. };
  88. THREE.Octree.prototype = {
  89. update: function () {
  90. // add any deferred objects that were waiting for render cycle
  91. if ( this.objectsDeferred.length > 0 ) {
  92. for ( var i = 0, il = this.objectsDeferred.length; i < il; i++ ) {
  93. var deferred = this.objectsDeferred[ i ];
  94. this.addDeferred( deferred.object, deferred.options );
  95. }
  96. this.objectsDeferred.length = 0;
  97. }
  98. },
  99. add: function ( object, options ) {
  100. // add immediately
  101. if ( this.undeferred ) {
  102. this.updateObject( object );
  103. this.addDeferred( object, options );
  104. } else {
  105. // defer add until update called
  106. this.objectsDeferred.push( { object: object, options: options } );
  107. }
  108. },
  109. addDeferred: function ( object, options ) {
  110. var i, l,
  111. geometry,
  112. faces,
  113. useFaces,
  114. vertices,
  115. useVertices,
  116. objectData;
  117. // ensure object is not object data
  118. if ( object instanceof THREE.OctreeObjectData ) {
  119. object = object.object;
  120. }
  121. // check uuid to avoid duplicates
  122. if ( !object.uuid ) {
  123. object.uuid = THREE.Math.generateUUID();
  124. }
  125. if ( !this.objectsMap[ object.uuid ] ) {
  126. // store
  127. this.objects.push( object );
  128. this.objectsMap[ object.uuid ] = object;
  129. // check options
  130. if ( options ) {
  131. useFaces = options.useFaces;
  132. useVertices = options.useVertices;
  133. }
  134. if ( useVertices === true ) {
  135. geometry = object.geometry;
  136. vertices = geometry.vertices;
  137. for ( i = 0, l = vertices.length; i < l; i++ ) {
  138. this.addObjectData( object, vertices[ i ] );
  139. }
  140. } else if ( useFaces === true ) {
  141. geometry = object.geometry;
  142. faces = geometry.faces;
  143. for ( i = 0, l = faces.length; i < l; i++ ) {
  144. this.addObjectData( object, faces[ i ] );
  145. }
  146. } else {
  147. this.addObjectData( object );
  148. }
  149. }
  150. },
  151. addObjectData: function ( object, part ) {
  152. var objectData = new THREE.OctreeObjectData( object, part );
  153. // add to tree objects data list
  154. this.objectsData.push( objectData );
  155. // add to nodes
  156. this.root.addObject( objectData );
  157. },
  158. remove: function ( object ) {
  159. var i, l,
  160. objectData = object,
  161. index,
  162. objectsDataRemoved;
  163. // ensure object is not object data for index search
  164. if ( object instanceof THREE.OctreeObjectData ) {
  165. object = object.object;
  166. }
  167. // check uuid
  168. if ( this.objectsMap[ object.uuid ] ) {
  169. this.objectsMap[ object.uuid ] = undefined;
  170. // check and remove from objects, nodes, and data lists
  171. index = indexOfValue( this.objects, object );
  172. if ( index !== -1 ) {
  173. this.objects.splice( index, 1 );
  174. // remove from nodes
  175. objectsDataRemoved = this.root.removeObject( objectData );
  176. // remove from objects data list
  177. for ( i = 0, l = objectsDataRemoved.length; i < l; i++ ) {
  178. objectData = objectsDataRemoved[ i ];
  179. index = indexOfValue( this.objectsData, objectData );
  180. if ( index !== -1 ) {
  181. this.objectsData.splice( index, 1 );
  182. }
  183. }
  184. }
  185. } else if ( this.objectsDeferred.length > 0 ) {
  186. // check and remove from deferred
  187. index = indexOfPropertyWithValue( this.objectsDeferred, 'object', object );
  188. if ( index !== -1 ) {
  189. this.objectsDeferred.splice( index, 1 );
  190. }
  191. }
  192. },
  193. extend: function ( octree ) {
  194. var i, l,
  195. objectsData,
  196. objectData;
  197. if ( octree instanceof THREE.Octree ) {
  198. // for each object data
  199. objectsData = octree.objectsData;
  200. for ( i = 0, l = objectsData.length; i < l; i++ ) {
  201. objectData = objectsData[ i ];
  202. this.add( objectData, { useFaces: objectData.faces, useVertices: objectData.vertices } );
  203. }
  204. }
  205. },
  206. rebuild: function () {
  207. var i, l,
  208. node,
  209. object,
  210. objectData,
  211. indexOctant,
  212. indexOctantLast,
  213. objectsUpdate = [];
  214. // check all object data for changes in position
  215. // assumes all object matrices are up to date
  216. for ( i = 0, l = this.objectsData.length; i < l; i++ ) {
  217. objectData = this.objectsData[ i ];
  218. node = objectData.node;
  219. // update object
  220. objectData.update();
  221. // if position has changed since last organization of object in tree
  222. if ( node instanceof THREE.OctreeNode && !objectData.positionLast.equals( objectData.position ) ) {
  223. // get octant index of object within current node
  224. indexOctantLast = objectData.indexOctant;
  225. indexOctant = node.getOctantIndex( objectData );
  226. // if object octant index has changed
  227. if ( indexOctant !== indexOctantLast ) {
  228. // add to update list
  229. objectsUpdate.push( objectData );
  230. }
  231. }
  232. }
  233. // update changed objects
  234. for ( i = 0, l = objectsUpdate.length; i < l; i++ ) {
  235. objectData = objectsUpdate[ i ];
  236. // remove object from current node
  237. objectData.node.removeObject( objectData );
  238. // add object to tree root
  239. this.root.addObject( objectData );
  240. }
  241. },
  242. updateObject: function ( object ) {
  243. var i, l,
  244. parentCascade = [ object ],
  245. parent,
  246. parentUpdate;
  247. // search all parents between object and root for world matrix update
  248. parent = object.parent;
  249. while( parent ) {
  250. parentCascade.push( parent );
  251. parent = parent.parent;
  252. }
  253. for ( i = 0, l = parentCascade.length; i < l; i++ ) {
  254. parent = parentCascade[ i ];
  255. if ( parent.matrixWorldNeedsUpdate === true ) {
  256. parentUpdate = parent;
  257. }
  258. }
  259. // update world matrix starting at uppermost parent that needs update
  260. if ( typeof parentUpdate !== 'undefined' ) {
  261. parentUpdate.updateMatrixWorld();
  262. }
  263. },
  264. search: function ( position, radius, organizeByObject, direction ) {
  265. var i, l,
  266. node,
  267. objects,
  268. objectData,
  269. object,
  270. results,
  271. resultData,
  272. resultsObjectsIndices,
  273. resultObjectIndex,
  274. directionPct;
  275. // add root objects
  276. objects = [].concat( this.root.objects );
  277. // ensure radius (i.e. distance of ray) is a number
  278. if ( !( radius > 0 ) ) {
  279. radius = Number.MAX_VALUE;
  280. }
  281. // if direction passed, normalize and find pct
  282. if ( direction instanceof THREE.Vector3 ) {
  283. direction = this.utilVec31Search.copy( direction ).normalize();
  284. directionPct = this.utilVec32Search.set( 1, 1, 1 ).divide( direction );
  285. }
  286. // search each node of root
  287. for ( i = 0, l = this.root.nodesIndices.length; i < l; i++ ) {
  288. node = this.root.nodesByIndex[ this.root.nodesIndices[ i ] ];
  289. objects = node.search( position, radius, objects, direction, directionPct );
  290. }
  291. // if should organize results by object
  292. if ( organizeByObject === true ) {
  293. results = [];
  294. resultsObjectsIndices = [];
  295. // for each object data found
  296. for ( i = 0, l = objects.length; i < l; i++ ) {
  297. objectData = objects[ i ];
  298. object = objectData.object;
  299. resultObjectIndex = indexOfValue( resultsObjectsIndices, object );
  300. // if needed, create new result data
  301. if ( resultObjectIndex === -1 ) {
  302. resultData = {
  303. object: object,
  304. faces: [],
  305. vertices: []
  306. };
  307. results.push( resultData );
  308. resultsObjectsIndices.push( object );
  309. } else {
  310. resultData = results[ resultObjectIndex ];
  311. }
  312. // object data has faces or vertices, add to list
  313. if ( objectData.faces ) {
  314. resultData.faces.push( objectData.faces );
  315. } else if ( objectData.vertices ) {
  316. resultData.vertices.push( objectData.vertices );
  317. }
  318. }
  319. } else {
  320. results = objects;
  321. }
  322. return results;
  323. },
  324. setRoot: function ( root ) {
  325. if ( root instanceof THREE.OctreeNode ) {
  326. // store new root
  327. this.root = root;
  328. // update properties
  329. this.root.updateProperties();
  330. }
  331. },
  332. getDepthEnd: function () {
  333. return this.root.getDepthEnd();
  334. },
  335. getNodeCountEnd: function () {
  336. return this.root.getNodeCountEnd();
  337. },
  338. getObjectCountEnd: function () {
  339. return this.root.getObjectCountEnd();
  340. },
  341. toConsole: function () {
  342. this.root.toConsole();
  343. }
  344. };
  345. /*===================================================
  346. object data
  347. =====================================================*/
  348. THREE.OctreeObjectData = function ( object, part ) {
  349. // properties
  350. this.object = object;
  351. // handle part by type
  352. if ( part instanceof THREE.Face3 ) {
  353. this.faces = part;
  354. this.face3 = true;
  355. this.utilVec31FaceBounds = new THREE.Vector3();
  356. } else if ( part instanceof THREE.Vector3 ) {
  357. this.vertices = part;
  358. }
  359. this.radius = 0;
  360. this.position = new THREE.Vector3();
  361. // initial update
  362. if ( this.object instanceof THREE.Object3D ) {
  363. this.update();
  364. }
  365. this.positionLast = this.position.clone();
  366. };
  367. THREE.OctreeObjectData.prototype = {
  368. update: function () {
  369. if ( this.face3 ) {
  370. this.radius = this.getFace3BoundingRadius( this.object, this.faces );
  371. this.position.copy( this.faces.centroid ).applyMatrix4( this.object.matrixWorld );
  372. } else if ( this.vertices ) {
  373. this.radius = this.object.material.size || 1;
  374. this.position.copy( this.vertices ).applyMatrix4( this.object.matrixWorld );
  375. } else {
  376. if ( this.object.geometry ) {
  377. if ( this.object.geometry.boundingSphere === null ) {
  378. this.object.geometry.computeBoundingSphere();
  379. }
  380. this.radius = this.object.geometry.boundingSphere.radius;
  381. this.position.copy( this.object.geometry.boundingSphere.center ).applyMatrix4( this.object.matrixWorld );
  382. } else {
  383. this.radius = this.object.boundRadius;
  384. this.position.setFromMatrixPosition( this.object.matrixWorld );
  385. }
  386. }
  387. this.radius = this.radius * Math.max( this.object.scale.x, this.object.scale.y, this.object.scale.z );
  388. },
  389. getFace3BoundingRadius: function ( object, face ) {
  390. var geometry = object.geometry || object,
  391. vertices = geometry.vertices,
  392. centroid = face.centroid,
  393. va = vertices[ face.a ], vb = vertices[ face.b ], vc = vertices[ face.c ],
  394. centroidToVert = this.utilVec31FaceBounds,
  395. radius;
  396. centroid.addVectors( va, vb ).add( vc ).divideScalar( 3 );
  397. radius = Math.max( centroidToVert.subVectors( centroid, va ).length(), centroidToVert.subVectors( centroid, vb ).length(), centroidToVert.subVectors( centroid, vc ).length() );
  398. return radius;
  399. }
  400. };
  401. /*===================================================
  402. node
  403. =====================================================*/
  404. THREE.OctreeNode = function ( parameters ) {
  405. // utility
  406. this.utilVec31Branch = new THREE.Vector3();
  407. this.utilVec31Expand = new THREE.Vector3();
  408. this.utilVec31Ray = new THREE.Vector3();
  409. // handle parameters
  410. parameters = parameters || {};
  411. // store or create tree
  412. if ( parameters.tree instanceof THREE.Octree ) {
  413. this.tree = parameters.tree;
  414. } else if ( parameters.parent instanceof THREE.OctreeNode !== true ) {
  415. parameters.root = this;
  416. this.tree = new THREE.Octree( parameters );
  417. }
  418. // basic properties
  419. this.id = this.tree.nodeCount++;
  420. this.position = parameters.position instanceof THREE.Vector3 ? parameters.position : new THREE.Vector3();
  421. this.radius = parameters.radius > 0 ? parameters.radius : 1;
  422. this.indexOctant = parameters.indexOctant;
  423. this.depth = 0;
  424. // reset and assign parent
  425. this.reset();
  426. this.setParent( parameters.parent );
  427. // additional properties
  428. this.overlap = this.radius * this.tree.overlapPct;
  429. this.radiusOverlap = this.radius + this.overlap;
  430. this.left = this.position.x - this.radiusOverlap;
  431. this.right = this.position.x + this.radiusOverlap;
  432. this.bottom = this.position.y - this.radiusOverlap;
  433. this.top = this.position.y + this.radiusOverlap;
  434. this.back = this.position.z - this.radiusOverlap;
  435. this.front = this.position.z + this.radiusOverlap;
  436. // visual
  437. if ( this.tree.scene ) {
  438. this.visual = new THREE.Mesh( this.tree.visualGeometry, this.tree.visualMaterial );
  439. this.visual.scale.set( this.radiusOverlap * 2, this.radiusOverlap * 2, this.radiusOverlap * 2 );
  440. this.visual.position.copy( this.position );
  441. this.tree.scene.add( this.visual );
  442. }
  443. };
  444. THREE.OctreeNode.prototype = {
  445. setParent: function ( parent ) {
  446. // store new parent
  447. if ( parent !== this && this.parent !== parent ) {
  448. this.parent = parent;
  449. // update properties
  450. this.updateProperties();
  451. }
  452. },
  453. updateProperties: function () {
  454. var i, l;
  455. // properties
  456. if ( this.parent instanceof THREE.OctreeNode ) {
  457. this.tree = this.parent.tree;
  458. this.depth = this.parent.depth + 1;
  459. } else {
  460. this.depth = 0;
  461. }
  462. // cascade
  463. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  464. this.nodesByIndex[ this.nodesIndices[ i ] ].updateProperties();
  465. }
  466. },
  467. reset: function ( cascade, removeVisual ) {
  468. var i, l,
  469. node,
  470. nodesIndices = this.nodesIndices || [],
  471. nodesByIndex = this.nodesByIndex;
  472. this.objects = [];
  473. this.nodesIndices = [];
  474. this.nodesByIndex = {};
  475. // unset parent in nodes
  476. for ( i = 0, l = nodesIndices.length; i < l; i++ ) {
  477. node = nodesByIndex[ nodesIndices[ i ] ];
  478. node.setParent( undefined );
  479. if ( cascade === true ) {
  480. node.reset( cascade, removeVisual );
  481. }
  482. }
  483. // visual
  484. if ( removeVisual === true && this.visual && this.visual.parent ) {
  485. this.visual.parent.remove( this.visual );
  486. }
  487. },
  488. addNode: function ( node, indexOctant ) {
  489. node.indexOctant = indexOctant;
  490. if ( indexOfValue( this.nodesIndices, indexOctant ) === -1 ) {
  491. this.nodesIndices.push( indexOctant );
  492. }
  493. this.nodesByIndex[ indexOctant ] = node;
  494. if ( node.parent !== this ) {
  495. node.setParent( this );
  496. }
  497. },
  498. removeNode: function ( indexOctant ) {
  499. var index,
  500. node;
  501. index = indexOfValue( this.nodesIndices, indexOctant );
  502. this.nodesIndices.splice( index, 1 );
  503. node = node || this.nodesByIndex[ indexOctant ];
  504. delete this.nodesByIndex[ indexOctant ];
  505. if ( node.parent === this ) {
  506. node.setParent( undefined );
  507. }
  508. },
  509. addObject: function ( object ) {
  510. var index,
  511. indexOctant,
  512. node;
  513. // get object octant index
  514. indexOctant = this.getOctantIndex( object );
  515. // if object fully contained by an octant, add to subtree
  516. if ( indexOctant > -1 && this.nodesIndices.length > 0 ) {
  517. node = this.branch( indexOctant );
  518. node.addObject( object );
  519. } else if ( indexOctant < -1 && this.parent instanceof THREE.OctreeNode ) {
  520. // if object lies outside bounds, add to parent node
  521. this.parent.addObject( object );
  522. } else {
  523. // add to this objects list
  524. index = indexOfValue( this.objects, object );
  525. if ( index === -1 ) {
  526. this.objects.push( object );
  527. }
  528. // node reference
  529. object.node = this;
  530. // check if need to expand, split, or both
  531. this.checkGrow();
  532. }
  533. },
  534. addObjectWithoutCheck: function ( objects ) {
  535. var i, l,
  536. object;
  537. for ( i = 0, l = objects.length; i < l; i++ ) {
  538. object = objects[ i ];
  539. this.objects.push( object );
  540. object.node = this;
  541. }
  542. },
  543. removeObject: function ( object ) {
  544. var i, l,
  545. nodesRemovedFrom,
  546. removeData;
  547. // cascade through tree to find and remove object
  548. removeData = this.removeObjectRecursive( object, { searchComplete: false, nodesRemovedFrom: [], objectsDataRemoved: [] } );
  549. // if object removed, try to shrink the nodes it was removed from
  550. nodesRemovedFrom = removeData.nodesRemovedFrom;
  551. if ( nodesRemovedFrom.length > 0 ) {
  552. for ( i = 0, l = nodesRemovedFrom.length; i < l; i++ ) {
  553. nodesRemovedFrom[ i ].shrink();
  554. }
  555. }
  556. return removeData.objectsDataRemoved;
  557. },
  558. removeObjectRecursive: function ( object, removeData ) {
  559. var i, l,
  560. index = -1,
  561. objectData,
  562. node,
  563. objectRemoved;
  564. // find index of object in objects list
  565. // search and remove object data (fast)
  566. if ( object instanceof THREE.OctreeObjectData ) {
  567. // remove from this objects list
  568. index = indexOfValue( this.objects, object );
  569. if ( index !== -1 ) {
  570. this.objects.splice( index, 1 );
  571. object.node = undefined;
  572. removeData.objectsDataRemoved.push( object );
  573. removeData.searchComplete = objectRemoved = true;
  574. }
  575. } else {
  576. // search each object data for object and remove (slow)
  577. for ( i = this.objects.length - 1; i >= 0; i-- ) {
  578. objectData = this.objects[ i ];
  579. if ( objectData.object === object ) {
  580. this.objects.splice( i, 1 );
  581. objectData.node = undefined;
  582. removeData.objectsDataRemoved.push( objectData );
  583. objectRemoved = true;
  584. if ( !objectData.faces && !objectData.vertices ) {
  585. removeData.searchComplete = true;
  586. break;
  587. }
  588. }
  589. }
  590. }
  591. // if object data removed and this is not on nodes removed from
  592. if ( objectRemoved === true ) {
  593. removeData.nodesRemovedFrom.push( this );
  594. }
  595. // if search not complete, search nodes
  596. if ( removeData.searchComplete !== true ) {
  597. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  598. node = this.nodesByIndex[ this.nodesIndices[ i ] ];
  599. // try removing object from node
  600. removeData = node.removeObjectRecursive( object, removeData );
  601. if ( removeData.searchComplete === true ) {
  602. break;
  603. }
  604. }
  605. }
  606. return removeData;
  607. },
  608. checkGrow: function () {
  609. // if object count above max
  610. if ( this.objects.length > this.tree.objectsThreshold && this.tree.objectsThreshold > 0 ) {
  611. this.grow();
  612. }
  613. },
  614. grow: function () {
  615. var indexOctant,
  616. object,
  617. objectsExpand = [],
  618. objectsExpandOctants = [],
  619. objectsSplit = [],
  620. objectsSplitOctants = [],
  621. objectsRemaining = [],
  622. i, l;
  623. // for each object
  624. for ( i = 0, l = this.objects.length; i < l; i++ ) {
  625. object = this.objects[ i ];
  626. // get object octant index
  627. indexOctant = this.getOctantIndex( object );
  628. // if lies within octant
  629. if ( indexOctant > -1 ) {
  630. objectsSplit.push( object );
  631. objectsSplitOctants.push( indexOctant );
  632. } else if ( indexOctant < -1 ) {
  633. // lies outside radius
  634. objectsExpand.push( object );
  635. objectsExpandOctants.push( indexOctant );
  636. } else {
  637. // lies across bounds between octants
  638. objectsRemaining.push( object );
  639. }
  640. }
  641. // if has objects to split
  642. if ( objectsSplit.length > 0) {
  643. objectsRemaining = objectsRemaining.concat( this.split( objectsSplit, objectsSplitOctants ) );
  644. }
  645. // if has objects to expand
  646. if ( objectsExpand.length > 0) {
  647. objectsRemaining = objectsRemaining.concat( this.expand( objectsExpand, objectsExpandOctants ) );
  648. }
  649. // store remaining
  650. this.objects = objectsRemaining;
  651. // merge check
  652. this.checkMerge();
  653. },
  654. split: function ( objects, octants ) {
  655. var i, l,
  656. indexOctant,
  657. object,
  658. node,
  659. objectsRemaining;
  660. // if not at max depth
  661. if ( this.depth < this.tree.depthMax ) {
  662. objects = objects || this.objects;
  663. octants = octants || [];
  664. objectsRemaining = [];
  665. // for each object
  666. for ( i = 0, l = objects.length; i < l; i++ ) {
  667. object = objects[ i ];
  668. // get object octant index
  669. indexOctant = octants[ i ];
  670. // if object contained by octant, branch this tree
  671. if ( indexOctant > -1 ) {
  672. node = this.branch( indexOctant );
  673. node.addObject( object );
  674. } else {
  675. objectsRemaining.push( object );
  676. }
  677. }
  678. // if all objects, set remaining as new objects
  679. if ( objects === this.objects ) {
  680. this.objects = objectsRemaining;
  681. }
  682. } else {
  683. objectsRemaining = this.objects;
  684. }
  685. return objectsRemaining;
  686. },
  687. branch: function ( indexOctant ) {
  688. var node,
  689. overlap,
  690. radius,
  691. radiusOffset,
  692. offset,
  693. position;
  694. // node exists
  695. if ( this.nodesByIndex[ indexOctant ] instanceof THREE.OctreeNode ) {
  696. node = this.nodesByIndex[ indexOctant ];
  697. } else {
  698. // properties
  699. radius = ( this.radiusOverlap ) * 0.5;
  700. overlap = radius * this.tree.overlapPct;
  701. radiusOffset = radius - overlap;
  702. offset = this.utilVec31Branch.set( indexOctant & 1 ? radiusOffset : -radiusOffset, indexOctant & 2 ? radiusOffset : -radiusOffset, indexOctant & 4 ? radiusOffset : -radiusOffset );
  703. position = new THREE.Vector3().addVectors( this.position, offset );
  704. // node
  705. node = new THREE.OctreeNode( {
  706. tree: this.tree,
  707. parent: this,
  708. position: position,
  709. radius: radius,
  710. indexOctant: indexOctant
  711. } );
  712. // store
  713. this.addNode( node, indexOctant );
  714. }
  715. return node;
  716. },
  717. expand: function ( objects, octants ) {
  718. var i, l,
  719. object,
  720. objectsRemaining,
  721. objectsExpand,
  722. indexOctant,
  723. flagsOutside,
  724. indexOutside,
  725. indexOctantInverse,
  726. iom = this.tree.INDEX_OUTSIDE_MAP,
  727. indexOutsideCounts,
  728. infoIndexOutside1,
  729. infoIndexOutside2,
  730. infoIndexOutside3,
  731. indexOutsideBitwise1,
  732. indexOutsideBitwise2,
  733. infoPotential1,
  734. infoPotential2,
  735. infoPotential3,
  736. indexPotentialBitwise1,
  737. indexPotentialBitwise2,
  738. octantX, octantY, octantZ,
  739. overlap,
  740. radius,
  741. radiusOffset,
  742. radiusParent,
  743. overlapParent,
  744. offset = this.utilVec31Expand,
  745. position,
  746. parent;
  747. // handle max depth down tree
  748. if ( this.tree.root.getDepthEnd() < this.tree.depthMax ) {
  749. objects = objects || this.objects;
  750. octants = octants || [];
  751. objectsRemaining = [];
  752. objectsExpand = [];
  753. // reset counts
  754. for ( i = 0, l = iom.length; i < l; i++ ) {
  755. iom[ i ].count = 0;
  756. }
  757. // for all outside objects, find outside octants containing most objects
  758. for ( i = 0, l = objects.length; i < l; i++ ) {
  759. object = objects[ i ];
  760. // get object octant index
  761. indexOctant = octants[ i ] ;
  762. // if object outside this, include in calculations
  763. if ( indexOctant < -1 ) {
  764. // convert octant index to outside flags
  765. flagsOutside = -indexOctant - this.tree.INDEX_OUTSIDE_OFFSET;
  766. // check against bitwise flags
  767. // x
  768. if ( flagsOutside & this.tree.FLAG_POS_X ) {
  769. iom[ this.tree.INDEX_OUTSIDE_POS_X ].count++;
  770. } else if ( flagsOutside & this.tree.FLAG_NEG_X ) {
  771. iom[ this.tree.INDEX_OUTSIDE_NEG_X ].count++;
  772. }
  773. // y
  774. if ( flagsOutside & this.tree.FLAG_POS_Y ) {
  775. iom[ this.tree.INDEX_OUTSIDE_POS_Y ].count++;
  776. } else if ( flagsOutside & this.tree.FLAG_NEG_Y ) {
  777. iom[ this.tree.INDEX_OUTSIDE_NEG_Y ].count++;
  778. }
  779. // z
  780. if ( flagsOutside & this.tree.FLAG_POS_Z ) {
  781. iom[ this.tree.INDEX_OUTSIDE_POS_Z ].count++;
  782. } else if ( flagsOutside & this.tree.FLAG_NEG_Z ) {
  783. iom[ this.tree.INDEX_OUTSIDE_NEG_Z ].count++;
  784. }
  785. // store in expand list
  786. objectsExpand.push( object );
  787. } else {
  788. objectsRemaining.push( object );
  789. }
  790. }
  791. // if objects to expand
  792. if ( objectsExpand.length > 0 ) {
  793. // shallow copy index outside map
  794. indexOutsideCounts = iom.slice( 0 );
  795. // sort outside index count so highest is first
  796. indexOutsideCounts.sort( function ( a, b ) {
  797. return b.count - a.count;
  798. } );
  799. // get highest outside indices
  800. // first is first
  801. infoIndexOutside1 = indexOutsideCounts[ 0 ];
  802. indexOutsideBitwise1 = infoIndexOutside1.index | 1;
  803. // second is ( one of next two bitwise OR 1 ) that is not opposite of ( first bitwise OR 1 )
  804. infoPotential1 = indexOutsideCounts[ 1 ];
  805. infoPotential2 = indexOutsideCounts[ 2 ];
  806. infoIndexOutside2 = ( infoPotential1.index | 1 ) !== indexOutsideBitwise1 ? infoPotential1 : infoPotential2;
  807. indexOutsideBitwise2 = infoIndexOutside2.index | 1;
  808. // third is ( one of next three bitwise OR 1 ) that is not opposite of ( first or second bitwise OR 1 )
  809. infoPotential1 = indexOutsideCounts[ 2 ];
  810. infoPotential2 = indexOutsideCounts[ 3 ];
  811. infoPotential3 = indexOutsideCounts[ 4 ];
  812. indexPotentialBitwise1 = infoPotential1.index | 1;
  813. indexPotentialBitwise2 = infoPotential2.index | 1;
  814. infoIndexOutside3 = indexPotentialBitwise1 !== indexOutsideBitwise1 && indexPotentialBitwise1 !== indexOutsideBitwise2 ? infoPotential1 : indexPotentialBitwise2 !== indexOutsideBitwise1 && indexPotentialBitwise2 !== indexOutsideBitwise2 ? infoPotential2 : infoPotential3;
  815. // get this octant normal based on outside octant indices
  816. octantX = infoIndexOutside1.x + infoIndexOutside2.x + infoIndexOutside3.x;
  817. octantY = infoIndexOutside1.y + infoIndexOutside2.y + infoIndexOutside3.y;
  818. octantZ = infoIndexOutside1.z + infoIndexOutside2.z + infoIndexOutside3.z;
  819. // get this octant indices based on octant normal
  820. indexOctant = this.getOctantIndexFromPosition( octantX, octantY, octantZ );
  821. indexOctantInverse = this.getOctantIndexFromPosition( -octantX, -octantY, -octantZ );
  822. // properties
  823. overlap = this.overlap;
  824. radius = this.radius;
  825. // radius of parent comes from reversing overlap of this, unless overlap percent is 0
  826. radiusParent = this.tree.overlapPct > 0 ? overlap / ( ( 0.5 * this.tree.overlapPct ) * ( 1 + this.tree.overlapPct ) ) : radius * 2;
  827. overlapParent = radiusParent * this.tree.overlapPct;
  828. // parent offset is difference between radius + overlap of parent and child
  829. radiusOffset = ( radiusParent + overlapParent ) - ( radius + overlap );
  830. offset.set( indexOctant & 1 ? radiusOffset : -radiusOffset, indexOctant & 2 ? radiusOffset : -radiusOffset, indexOctant & 4 ? radiusOffset : -radiusOffset );
  831. position = new THREE.Vector3().addVectors( this.position, offset );
  832. // parent
  833. parent = new THREE.OctreeNode( {
  834. tree: this.tree,
  835. position: position,
  836. radius: radiusParent
  837. } );
  838. // set self as node of parent
  839. parent.addNode( this, indexOctantInverse );
  840. // set parent as root
  841. this.tree.setRoot( parent );
  842. // add all expand objects to parent
  843. for ( i = 0, l = objectsExpand.length; i < l; i++ ) {
  844. this.tree.root.addObject( objectsExpand[ i ] );
  845. }
  846. }
  847. // if all objects, set remaining as new objects
  848. if ( objects === this.objects ) {
  849. this.objects = objectsRemaining;
  850. }
  851. } else {
  852. objectsRemaining = objects;
  853. }
  854. return objectsRemaining;
  855. },
  856. shrink: function () {
  857. // merge check
  858. this.checkMerge();
  859. // contract check
  860. this.tree.root.checkContract();
  861. },
  862. checkMerge: function () {
  863. var nodeParent = this,
  864. nodeMerge;
  865. // traverse up tree as long as node + entire subtree's object count is under minimum
  866. while ( nodeParent.parent instanceof THREE.OctreeNode && nodeParent.getObjectCountEnd() < this.tree.objectsThreshold ) {
  867. nodeMerge = nodeParent;
  868. nodeParent = nodeParent.parent;
  869. }
  870. // if parent node is not this, merge entire subtree into merge node
  871. if ( nodeParent !== this ) {
  872. nodeParent.merge( nodeMerge );
  873. }
  874. },
  875. merge: function ( nodes ) {
  876. var i, l,
  877. j, k,
  878. node;
  879. // handle nodes
  880. nodes = toArray( nodes );
  881. for ( i = 0, l = nodes.length; i < l; i++ ) {
  882. node = nodes[ i ];
  883. // gather node + all subtree objects
  884. this.addObjectWithoutCheck( node.getObjectsEnd() );
  885. // reset node + entire subtree
  886. node.reset( true, true );
  887. // remove node
  888. this.removeNode( node.indexOctant, node );
  889. }
  890. // merge check
  891. this.checkMerge();
  892. },
  893. checkContract: function () {
  894. var i, l,
  895. node,
  896. nodeObjectsCount,
  897. nodeHeaviest,
  898. nodeHeaviestObjectsCount,
  899. outsideHeaviestObjectsCount;
  900. // find node with highest object count
  901. if ( this.nodesIndices.length > 0 ) {
  902. nodeHeaviestObjectsCount = 0;
  903. outsideHeaviestObjectsCount = this.objects.length;
  904. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  905. node = this.nodesByIndex[ this.nodesIndices[ i ] ];
  906. nodeObjectsCount = node.getObjectCountEnd();
  907. outsideHeaviestObjectsCount += nodeObjectsCount;
  908. if ( nodeHeaviest instanceof THREE.OctreeNode === false || nodeObjectsCount > nodeHeaviestObjectsCount ) {
  909. nodeHeaviest = node;
  910. nodeHeaviestObjectsCount = nodeObjectsCount;
  911. }
  912. }
  913. // subtract heaviest count from outside count
  914. outsideHeaviestObjectsCount -= nodeHeaviestObjectsCount;
  915. // if should contract
  916. if ( outsideHeaviestObjectsCount < this.tree.objectsThreshold && nodeHeaviest instanceof THREE.OctreeNode ) {
  917. this.contract( nodeHeaviest );
  918. }
  919. }
  920. },
  921. contract: function ( nodeRoot ) {
  922. var i, l,
  923. node;
  924. // handle all nodes
  925. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  926. node = this.nodesByIndex[ this.nodesIndices[ i ] ];
  927. // if node is not new root
  928. if ( node !== nodeRoot ) {
  929. // add node + all subtree objects to root
  930. nodeRoot.addObjectWithoutCheck( node.getObjectsEnd() );
  931. // reset node + entire subtree
  932. node.reset( true, true );
  933. }
  934. }
  935. // add own objects to root
  936. nodeRoot.addObjectWithoutCheck( this.objects );
  937. // reset self
  938. this.reset( false, true );
  939. // set new root
  940. this.tree.setRoot( nodeRoot );
  941. // contract check on new root
  942. nodeRoot.checkContract();
  943. },
  944. getOctantIndex: function ( objectData ) {
  945. var i, l,
  946. positionObj,
  947. radiusObj,
  948. position = this.position,
  949. radiusOverlap = this.radiusOverlap,
  950. overlap = this.overlap,
  951. deltaX, deltaY, deltaZ,
  952. distX, distY, distZ,
  953. distance,
  954. indexOctant = 0;
  955. // handle type
  956. if ( objectData instanceof THREE.OctreeObjectData ) {
  957. radiusObj = objectData.radius;
  958. positionObj = objectData.position;
  959. // update object data position last
  960. objectData.positionLast.copy( positionObj );
  961. } else if ( objectData instanceof THREE.OctreeNode ) {
  962. positionObj = objectData.position;
  963. radiusObj = 0;
  964. }
  965. // find delta and distance
  966. deltaX = positionObj.x - position.x;
  967. deltaY = positionObj.y - position.y;
  968. deltaZ = positionObj.z - position.z;
  969. distX = Math.abs( deltaX );
  970. distY = Math.abs( deltaY );
  971. distZ = Math.abs( deltaZ );
  972. distance = Math.max( distX, distY, distZ );
  973. // if outside, use bitwise flags to indicate on which sides object is outside of
  974. if ( distance + radiusObj > radiusOverlap ) {
  975. // x
  976. if ( distX + radiusObj > radiusOverlap ) {
  977. indexOctant = indexOctant ^ ( deltaX > 0 ? this.tree.FLAG_POS_X : this.tree.FLAG_NEG_X );
  978. }
  979. // y
  980. if ( distY + radiusObj > radiusOverlap ) {
  981. indexOctant = indexOctant ^ ( deltaY > 0 ? this.tree.FLAG_POS_Y : this.tree.FLAG_NEG_Y );
  982. }
  983. // z
  984. if ( distZ + radiusObj > radiusOverlap ) {
  985. indexOctant = indexOctant ^ ( deltaZ > 0 ? this.tree.FLAG_POS_Z : this.tree.FLAG_NEG_Z );
  986. }
  987. objectData.indexOctant = -indexOctant - this.tree.INDEX_OUTSIDE_OFFSET;
  988. return objectData.indexOctant;
  989. }
  990. // return octant index from delta xyz
  991. if ( deltaX - radiusObj > -overlap ) {
  992. // x right
  993. indexOctant = indexOctant | 1;
  994. } else if ( !( deltaX + radiusObj < overlap ) ) {
  995. // x left
  996. objectData.indexOctant = this.tree.INDEX_INSIDE_CROSS;
  997. return objectData.indexOctant;
  998. }
  999. if ( deltaY - radiusObj > -overlap ) {
  1000. // y right
  1001. indexOctant = indexOctant | 2;
  1002. } else if ( !( deltaY + radiusObj < overlap ) ) {
  1003. // y left
  1004. objectData.indexOctant = this.tree.INDEX_INSIDE_CROSS;
  1005. return objectData.indexOctant;
  1006. }
  1007. if ( deltaZ - radiusObj > -overlap ) {
  1008. // z right
  1009. indexOctant = indexOctant | 4;
  1010. } else if ( !( deltaZ + radiusObj < overlap ) ) {
  1011. // z left
  1012. objectData.indexOctant = this.tree.INDEX_INSIDE_CROSS;
  1013. return objectData.indexOctant;
  1014. }
  1015. objectData.indexOctant = indexOctant;
  1016. return objectData.indexOctant;
  1017. },
  1018. getOctantIndexFromPosition: function ( x, y, z ) {
  1019. var indexOctant = 0;
  1020. if ( x > 0 ) {
  1021. indexOctant = indexOctant | 1;
  1022. }
  1023. if ( y > 0 ) {
  1024. indexOctant = indexOctant | 2;
  1025. }
  1026. if ( z > 0 ) {
  1027. indexOctant = indexOctant | 4;
  1028. }
  1029. return indexOctant;
  1030. },
  1031. search: function ( position, radius, objects, direction, directionPct ) {
  1032. var i, l,
  1033. node,
  1034. intersects;
  1035. // test intersects by parameters
  1036. if ( direction ) {
  1037. intersects = this.intersectRay( position, direction, radius, directionPct );
  1038. } else {
  1039. intersects = this.intersectSphere( position, radius );
  1040. }
  1041. // if intersects
  1042. if ( intersects === true ) {
  1043. // gather objects
  1044. objects = objects.concat( this.objects );
  1045. // search subtree
  1046. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  1047. node = this.nodesByIndex[ this.nodesIndices[ i ] ];
  1048. objects = node.search( position, radius, objects, direction );
  1049. }
  1050. }
  1051. return objects;
  1052. },
  1053. intersectSphere: function ( position, radius ) {
  1054. var distance = radius * radius,
  1055. px = position.x,
  1056. py = position.y,
  1057. pz = position.z;
  1058. if ( px < this.left ) {
  1059. distance -= Math.pow( px - this.left, 2 );
  1060. } else if ( px > this.right ) {
  1061. distance -= Math.pow( px - this.right, 2 );
  1062. }
  1063. if ( py < this.bottom ) {
  1064. distance -= Math.pow( py - this.bottom, 2 );
  1065. } else if ( py > this.top ) {
  1066. distance -= Math.pow( py - this.top, 2 );
  1067. }
  1068. if ( pz < this.back ) {
  1069. distance -= Math.pow( pz - this.back, 2 );
  1070. } else if ( pz > this.front ) {
  1071. distance -= Math.pow( pz - this.front, 2 );
  1072. }
  1073. return distance >= 0;
  1074. },
  1075. intersectRay: function ( origin, direction, distance, directionPct ) {
  1076. if ( typeof directionPct === 'undefined' ) {
  1077. directionPct = this.utilVec31Ray.set( 1, 1, 1 ).divide( direction );
  1078. }
  1079. var t1 = ( this.left - origin.x ) * directionPct.x,
  1080. t2 = ( this.right - origin.x ) * directionPct.x,
  1081. t3 = ( this.bottom - origin.y ) * directionPct.y,
  1082. t4 = ( this.top - origin.y ) * directionPct.y,
  1083. t5 = ( this.back - origin.z ) * directionPct.z,
  1084. t6 = ( this.front - origin.z ) * directionPct.z,
  1085. tmax = Math.min( Math.min( Math.max( t1, t2), Math.max( t3, t4) ), Math.max( t5, t6) ),
  1086. tmin;
  1087. // ray would intersect in reverse direction, i.e. this is behind ray
  1088. if (tmax < 0)
  1089. {
  1090. return false;
  1091. }
  1092. tmin = Math.max( Math.max( Math.min( t1, t2), Math.min( t3, t4)), Math.min( t5, t6));
  1093. // if tmin > tmax or tmin > ray distance, ray doesn't intersect AABB
  1094. if( tmin > tmax || tmin > distance ) {
  1095. return false;
  1096. }
  1097. return true;
  1098. },
  1099. getDepthEnd: function ( depth ) {
  1100. var i, l,
  1101. node;
  1102. if ( this.nodesIndices.length > 0 ) {
  1103. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  1104. node = this.nodesByIndex[ this.nodesIndices[ i ] ];
  1105. depth = node.getDepthEnd( depth );
  1106. }
  1107. } else {
  1108. depth = !depth || this.depth > depth ? this.depth : depth;
  1109. }
  1110. return depth;
  1111. },
  1112. getNodeCountEnd: function () {
  1113. return this.tree.root.getNodeCountRecursive() + 1;
  1114. },
  1115. getNodeCountRecursive: function () {
  1116. var i, l,
  1117. count = this.nodesIndices.length;
  1118. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  1119. count += this.nodesByIndex[ this.nodesIndices[ i ] ].getNodeCountRecursive();
  1120. }
  1121. return count;
  1122. },
  1123. getObjectsEnd: function ( objects ) {
  1124. var i, l,
  1125. node;
  1126. objects = ( objects || [] ).concat( this.objects );
  1127. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  1128. node = this.nodesByIndex[ this.nodesIndices[ i ] ];
  1129. objects = node.getObjectsEnd( objects );
  1130. }
  1131. return objects;
  1132. },
  1133. getObjectCountEnd: function () {
  1134. var i, l,
  1135. count = this.objects.length;
  1136. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  1137. count += this.nodesByIndex[ this.nodesIndices[ i ] ].getObjectCountEnd();
  1138. }
  1139. return count;
  1140. },
  1141. getObjectCountStart: function () {
  1142. var count = this.objects.length,
  1143. parent = this.parent;
  1144. while( parent instanceof THREE.OctreeNode ) {
  1145. count += parent.objects.length;
  1146. parent = parent.parent;
  1147. }
  1148. return count;
  1149. },
  1150. toConsole: function ( space ) {
  1151. var i, l,
  1152. node,
  1153. spaceAddition = ' ';
  1154. space = typeof space === 'string' ? space : spaceAddition;
  1155. console.log( ( this.parent ? space + ' octree NODE > ' : ' octree ROOT > ' ), this, ' // id: ', this.id, ' // indexOctant: ', this.indexOctant, ' // position: ', this.position.x, this.position.y, this.position.z, ' // radius: ', this.radius, ' // depth: ', this.depth );
  1156. console.log( ( this.parent ? space + ' ' : ' ' ), '+ objects ( ', this.objects.length, ' ) ', this.objects );
  1157. console.log( ( this.parent ? space + ' ' : ' ' ), '+ children ( ', this.nodesIndices.length, ' )', this.nodesIndices, this.nodesByIndex );
  1158. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  1159. node = this.nodesByIndex[ this.nodesIndices[ i ] ];
  1160. node.toConsole( space + spaceAddition );
  1161. }
  1162. }
  1163. };
  1164. /*===================================================
  1165. raycaster additional functionality
  1166. =====================================================*/
  1167. THREE.Raycaster.prototype.intersectOctreeObject = function ( object, recursive ) {
  1168. var intersects,
  1169. octreeObject,
  1170. facesAll,
  1171. facesSearch;
  1172. if ( object.object instanceof THREE.Object3D ) {
  1173. octreeObject = object;
  1174. object = octreeObject.object;
  1175. // temporarily replace object geometry's faces with octree object faces
  1176. facesSearch = octreeObject.faces;
  1177. facesAll = object.geometry.faces;
  1178. if ( facesSearch.length > 0 ) {
  1179. object.geometry.faces = facesSearch;
  1180. }
  1181. // intersect
  1182. intersects = this.intersectObject( object, recursive );
  1183. // revert object geometry's faces
  1184. if ( facesSearch.length > 0 ) {
  1185. object.geometry.faces = facesAll;
  1186. }
  1187. } else {
  1188. intersects = this.intersectObject( object, recursive );
  1189. }
  1190. return intersects;
  1191. };
  1192. THREE.Raycaster.prototype.intersectOctreeObjects = function ( objects, recursive ) {
  1193. var i, il,
  1194. intersects = [];
  1195. for ( i = 0, il = objects.length; i < il; i++ ) {
  1196. intersects = intersects.concat( this.intersectOctreeObject( objects[ i ], recursive ) );
  1197. }
  1198. return intersects;
  1199. };
  1200. }( THREE ) );