ConvexHull.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  1. import {
  2. Line3,
  3. Plane,
  4. Triangle,
  5. Vector3
  6. } from 'three';
  7. const Visible = 0;
  8. const Deleted = 1;
  9. const _v1 = new Vector3();
  10. const _line3 = new Line3();
  11. const _plane = new Plane();
  12. const _closestPoint = new Vector3();
  13. const _triangle = new Triangle();
  14. /**
  15. * Can be used to compute the convex hull in 3D space for a given set of points. It
  16. * is primarily intended for {@link ConvexGeometry}.
  17. *
  18. * This Quickhull 3D implementation is a port of [quickhull3d]{@link https://github.com/maurizzzio/quickhull3d/}
  19. * by Mauricio Poppe.
  20. */
  21. class ConvexHull {
  22. /**
  23. * Constructs a new convex hull.
  24. */
  25. constructor() {
  26. this.tolerance = - 1;
  27. this.faces = []; // the generated faces of the convex hull
  28. this.newFaces = []; // this array holds the faces that are generated within a single iteration
  29. // the vertex lists work as follows:
  30. //
  31. // let 'a' and 'b' be 'Face' instances
  32. // let 'v' be points wrapped as instance of 'Vertex'
  33. //
  34. // [v, v, ..., v, v, v, ...]
  35. // ^ ^
  36. // | |
  37. // a.outside b.outside
  38. //
  39. this.assigned = new VertexList();
  40. this.unassigned = new VertexList();
  41. this.vertices = []; // vertices of the hull (internal representation of given geometry data)
  42. }
  43. /**
  44. * Computes to convex hull for the given array of points.
  45. *
  46. * @param {Array<Vector3>} points - The array of points in 3D space.
  47. * @return {ConvexHull} A reference to this convex hull.
  48. */
  49. setFromPoints( points ) {
  50. // The algorithm needs at least four points.
  51. if ( points.length >= 4 ) {
  52. this.makeEmpty();
  53. for ( let i = 0, l = points.length; i < l; i ++ ) {
  54. this.vertices.push( new VertexNode( points[ i ] ) );
  55. }
  56. this._compute();
  57. }
  58. return this;
  59. }
  60. /**
  61. * Computes the convex hull of the given 3D object (including its descendants),
  62. * accounting for the world transforms of both the 3D object and its descendants.
  63. *
  64. * @param {Object3D} object - The 3D object to compute the convex hull for.
  65. * @return {ConvexHull} A reference to this convex hull.
  66. */
  67. setFromObject( object ) {
  68. const points = [];
  69. object.updateMatrixWorld( true );
  70. object.traverse( function ( node ) {
  71. const geometry = node.geometry;
  72. if ( geometry !== undefined ) {
  73. const attribute = geometry.attributes.position;
  74. if ( attribute !== undefined ) {
  75. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  76. const point = new Vector3();
  77. point.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  78. points.push( point );
  79. }
  80. }
  81. }
  82. } );
  83. return this.setFromPoints( points );
  84. }
  85. /**
  86. * Returns `true` if the given point lies in the convex hull.
  87. *
  88. * @param {Vector3} point - The point to test.
  89. * @return {boolean} Whether the given point lies in the convex hull or not.
  90. */
  91. containsPoint( point ) {
  92. const faces = this.faces;
  93. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  94. const face = faces[ i ];
  95. // compute signed distance and check on what half space the point lies
  96. if ( face.distanceToPoint( point ) > this.tolerance ) return false;
  97. }
  98. return true;
  99. }
  100. /**
  101. * Computes the intersections point of the given ray and this convex hull.
  102. *
  103. * @param {Ray} ray - The ray to test.
  104. * @param {Vector3} target - The target vector that is used to store the method's result.
  105. * @return {Vector3|null} The intersection point. Returns `null` if not intersection was detected.
  106. */
  107. intersectRay( ray, target ) {
  108. // based on "Fast Ray-Convex Polyhedron Intersection" by Eric Haines, GRAPHICS GEMS II
  109. const faces = this.faces;
  110. let tNear = - Infinity;
  111. let tFar = Infinity;
  112. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  113. const face = faces[ i ];
  114. // interpret faces as planes for the further computation
  115. const vN = face.distanceToPoint( ray.origin );
  116. const vD = face.normal.dot( ray.direction );
  117. // if the origin is on the positive side of a plane (so the plane can "see" the origin) and
  118. // the ray is turned away or parallel to the plane, there is no intersection
  119. if ( vN > 0 && vD >= 0 ) return null;
  120. // compute the distance from the ray’s origin to the intersection with the plane
  121. const t = ( vD !== 0 ) ? ( - vN / vD ) : 0;
  122. // only proceed if the distance is positive. a negative distance means the intersection point
  123. // lies "behind" the origin
  124. if ( t <= 0 ) continue;
  125. // now categorized plane as front-facing or back-facing
  126. if ( vD > 0 ) {
  127. // plane faces away from the ray, so this plane is a back-face
  128. tFar = Math.min( t, tFar );
  129. } else {
  130. // front-face
  131. tNear = Math.max( t, tNear );
  132. }
  133. if ( tNear > tFar ) {
  134. // if tNear ever is greater than tFar, the ray must miss the convex hull
  135. return null;
  136. }
  137. }
  138. // evaluate intersection point
  139. // always try tNear first since its the closer intersection point
  140. if ( tNear !== - Infinity ) {
  141. ray.at( tNear, target );
  142. } else {
  143. ray.at( tFar, target );
  144. }
  145. return target;
  146. }
  147. /**
  148. * Returns `true` if the given ray intersects with this convex hull.
  149. *
  150. * @param {Ray} ray - The ray to test.
  151. * @return {boolean} Whether the given ray intersects with this convex hull or not.
  152. */
  153. intersectsRay( ray ) {
  154. return this.intersectRay( ray, _v1 ) !== null;
  155. }
  156. /**
  157. * Makes the convex hull empty.
  158. *
  159. * @return {ConvexHull} A reference to this convex hull.
  160. */
  161. makeEmpty() {
  162. this.faces = [];
  163. this.vertices = [];
  164. return this;
  165. }
  166. // private
  167. /**
  168. * Adds a vertex to the 'assigned' list of vertices and assigns it to the given face.
  169. *
  170. * @private
  171. * @param {VertexNode} vertex - The vertex to add.
  172. * @param {Face} face - The target face.
  173. * @return {ConvexHull} A reference to this convex hull.
  174. */
  175. _addVertexToFace( vertex, face ) {
  176. vertex.face = face;
  177. if ( face.outside === null ) {
  178. this.assigned.append( vertex );
  179. } else {
  180. this.assigned.insertBefore( face.outside, vertex );
  181. }
  182. face.outside = vertex;
  183. return this;
  184. }
  185. /**
  186. * Removes a vertex from the 'assigned' list of vertices and from the given face.
  187. * It also makes sure that the link from 'face' to the first vertex it sees in 'assigned'
  188. * is linked correctly after the removal.
  189. *
  190. * @private
  191. * @param {VertexNode} vertex - The vertex to remove.
  192. * @param {Face} face - The target face.
  193. * @return {ConvexHull} A reference to this convex hull.
  194. */
  195. _removeVertexFromFace( vertex, face ) {
  196. if ( vertex === face.outside ) {
  197. // fix face.outside link
  198. if ( vertex.next !== null && vertex.next.face === face ) {
  199. // face has at least 2 outside vertices, move the 'outside' reference
  200. face.outside = vertex.next;
  201. } else {
  202. // vertex was the only outside vertex that face had
  203. face.outside = null;
  204. }
  205. }
  206. this.assigned.remove( vertex );
  207. return this;
  208. }
  209. /**
  210. * Removes all the visible vertices that a given face is able to see which are stored in
  211. * the 'assigned' vertex list.
  212. *
  213. * @private
  214. * @param {Face} face - The target face.
  215. * @return {VertexNode|undefined} A reference to this convex hull.
  216. */
  217. _removeAllVerticesFromFace( face ) {
  218. if ( face.outside !== null ) {
  219. // reference to the first and last vertex of this face
  220. const start = face.outside;
  221. let end = face.outside;
  222. while ( end.next !== null && end.next.face === face ) {
  223. end = end.next;
  224. }
  225. this.assigned.removeSubList( start, end );
  226. // fix references
  227. start.prev = end.next = null;
  228. face.outside = null;
  229. return start;
  230. }
  231. }
  232. /**
  233. * Removes all the visible vertices that `face` is able to see.
  234. *
  235. * - If `absorbingFace` doesn't exist, then all the removed vertices will be added to the 'unassigned' vertex list.
  236. * - If `absorbingFace` exists, then this method will assign all the vertices of 'face' that can see 'absorbingFace'.
  237. * - If a vertex cannot see `absorbingFace`, it's added to the 'unassigned' vertex list.
  238. *
  239. * @private
  240. * @param {Face} face - The given face.
  241. * @param {Face} [absorbingFace] - An optional face that tries to absorb the vertices of the first face.
  242. * @return {ConvexHull} A reference to this convex hull.
  243. */
  244. _deleteFaceVertices( face, absorbingFace ) {
  245. const faceVertices = this._removeAllVerticesFromFace( face );
  246. if ( faceVertices !== undefined ) {
  247. if ( absorbingFace === undefined ) {
  248. // mark the vertices to be reassigned to some other face
  249. this.unassigned.appendChain( faceVertices );
  250. } else {
  251. // if there's an absorbing face try to assign as many vertices as possible to it
  252. let vertex = faceVertices;
  253. do {
  254. // we need to buffer the subsequent vertex at this point because the 'vertex.next' reference
  255. // will be changed by upcoming method calls
  256. const nextVertex = vertex.next;
  257. const distance = absorbingFace.distanceToPoint( vertex.point );
  258. // check if 'vertex' is able to see 'absorbingFace'
  259. if ( distance > this.tolerance ) {
  260. this._addVertexToFace( vertex, absorbingFace );
  261. } else {
  262. this.unassigned.append( vertex );
  263. }
  264. // now assign next vertex
  265. vertex = nextVertex;
  266. } while ( vertex !== null );
  267. }
  268. }
  269. return this;
  270. }
  271. /**
  272. * Reassigns as many vertices as possible from the unassigned list to the new faces.
  273. *
  274. * @private
  275. * @param {Array<Face>} newFaces - The new faces.
  276. * @return {ConvexHull} A reference to this convex hull.
  277. */
  278. _resolveUnassignedPoints( newFaces ) {
  279. if ( this.unassigned.isEmpty() === false ) {
  280. let vertex = this.unassigned.first();
  281. do {
  282. // buffer 'next' reference, see ._deleteFaceVertices()
  283. const nextVertex = vertex.next;
  284. let maxDistance = this.tolerance;
  285. let maxFace = null;
  286. for ( let i = 0; i < newFaces.length; i ++ ) {
  287. const face = newFaces[ i ];
  288. if ( face.mark === Visible ) {
  289. const distance = face.distanceToPoint( vertex.point );
  290. if ( distance > maxDistance ) {
  291. maxDistance = distance;
  292. maxFace = face;
  293. }
  294. if ( maxDistance > 1000 * this.tolerance ) break;
  295. }
  296. }
  297. // 'maxFace' can be null e.g. if there are identical vertices
  298. if ( maxFace !== null ) {
  299. this._addVertexToFace( vertex, maxFace );
  300. }
  301. vertex = nextVertex;
  302. } while ( vertex !== null );
  303. }
  304. return this;
  305. }
  306. /**
  307. * Computes the extremes values (min/max vectors) which will be used to
  308. * compute the initial hull.
  309. *
  310. * @private
  311. * @return {Object} The extremes.
  312. */
  313. _computeExtremes() {
  314. const min = new Vector3();
  315. const max = new Vector3();
  316. const minVertices = [];
  317. const maxVertices = [];
  318. // initially assume that the first vertex is the min/max
  319. for ( let i = 0; i < 3; i ++ ) {
  320. minVertices[ i ] = maxVertices[ i ] = this.vertices[ 0 ];
  321. }
  322. min.copy( this.vertices[ 0 ].point );
  323. max.copy( this.vertices[ 0 ].point );
  324. // compute the min/max vertex on all six directions
  325. for ( let i = 0, l = this.vertices.length; i < l; i ++ ) {
  326. const vertex = this.vertices[ i ];
  327. const point = vertex.point;
  328. // update the min coordinates
  329. for ( let j = 0; j < 3; j ++ ) {
  330. if ( point.getComponent( j ) < min.getComponent( j ) ) {
  331. min.setComponent( j, point.getComponent( j ) );
  332. minVertices[ j ] = vertex;
  333. }
  334. }
  335. // update the max coordinates
  336. for ( let j = 0; j < 3; j ++ ) {
  337. if ( point.getComponent( j ) > max.getComponent( j ) ) {
  338. max.setComponent( j, point.getComponent( j ) );
  339. maxVertices[ j ] = vertex;
  340. }
  341. }
  342. }
  343. // use min/max vectors to compute an optimal epsilon
  344. this.tolerance = 3 * Number.EPSILON * (
  345. Math.max( Math.abs( min.x ), Math.abs( max.x ) ) +
  346. Math.max( Math.abs( min.y ), Math.abs( max.y ) ) +
  347. Math.max( Math.abs( min.z ), Math.abs( max.z ) )
  348. );
  349. return { min: minVertices, max: maxVertices };
  350. }
  351. /**
  352. * Computes the initial simplex assigning to its faces all the points that are
  353. * candidates to form part of the hull.
  354. *
  355. * @private
  356. * @return {ConvexHull} A reference to this convex hull.
  357. */
  358. _computeInitialHull() {
  359. const vertices = this.vertices;
  360. const extremes = this._computeExtremes();
  361. const min = extremes.min;
  362. const max = extremes.max;
  363. // 1. Find the two vertices 'v0' and 'v1' with the greatest 1d separation
  364. // (max.x - min.x)
  365. // (max.y - min.y)
  366. // (max.z - min.z)
  367. let maxDistance = 0;
  368. let index = 0;
  369. for ( let i = 0; i < 3; i ++ ) {
  370. const distance = max[ i ].point.getComponent( i ) - min[ i ].point.getComponent( i );
  371. if ( distance > maxDistance ) {
  372. maxDistance = distance;
  373. index = i;
  374. }
  375. }
  376. const v0 = min[ index ];
  377. const v1 = max[ index ];
  378. let v2;
  379. let v3;
  380. // 2. The next vertex 'v2' is the one farthest to the line formed by 'v0' and 'v1'
  381. maxDistance = 0;
  382. _line3.set( v0.point, v1.point );
  383. for ( let i = 0, l = this.vertices.length; i < l; i ++ ) {
  384. const vertex = vertices[ i ];
  385. if ( vertex !== v0 && vertex !== v1 ) {
  386. _line3.closestPointToPoint( vertex.point, true, _closestPoint );
  387. const distance = _closestPoint.distanceToSquared( vertex.point );
  388. if ( distance > maxDistance ) {
  389. maxDistance = distance;
  390. v2 = vertex;
  391. }
  392. }
  393. }
  394. // 3. The next vertex 'v3' is the one farthest to the plane 'v0', 'v1', 'v2'
  395. maxDistance = - 1;
  396. _plane.setFromCoplanarPoints( v0.point, v1.point, v2.point );
  397. for ( let i = 0, l = this.vertices.length; i < l; i ++ ) {
  398. const vertex = vertices[ i ];
  399. if ( vertex !== v0 && vertex !== v1 && vertex !== v2 ) {
  400. const distance = Math.abs( _plane.distanceToPoint( vertex.point ) );
  401. if ( distance > maxDistance ) {
  402. maxDistance = distance;
  403. v3 = vertex;
  404. }
  405. }
  406. }
  407. const faces = [];
  408. if ( _plane.distanceToPoint( v3.point ) < 0 ) {
  409. // the face is not able to see the point so 'plane.normal' is pointing outside the tetrahedron
  410. faces.push(
  411. Face.create( v0, v1, v2 ),
  412. Face.create( v3, v1, v0 ),
  413. Face.create( v3, v2, v1 ),
  414. Face.create( v3, v0, v2 )
  415. );
  416. // set the twin edge
  417. for ( let i = 0; i < 3; i ++ ) {
  418. const j = ( i + 1 ) % 3;
  419. // join face[ i ] i > 0, with the first face
  420. faces[ i + 1 ].getEdge( 2 ).setTwin( faces[ 0 ].getEdge( j ) );
  421. // join face[ i ] with face[ i + 1 ], 1 <= i <= 3
  422. faces[ i + 1 ].getEdge( 1 ).setTwin( faces[ j + 1 ].getEdge( 0 ) );
  423. }
  424. } else {
  425. // the face is able to see the point so 'plane.normal' is pointing inside the tetrahedron
  426. faces.push(
  427. Face.create( v0, v2, v1 ),
  428. Face.create( v3, v0, v1 ),
  429. Face.create( v3, v1, v2 ),
  430. Face.create( v3, v2, v0 )
  431. );
  432. // set the twin edge
  433. for ( let i = 0; i < 3; i ++ ) {
  434. const j = ( i + 1 ) % 3;
  435. // join face[ i ] i > 0, with the first face
  436. faces[ i + 1 ].getEdge( 2 ).setTwin( faces[ 0 ].getEdge( ( 3 - i ) % 3 ) );
  437. // join face[ i ] with face[ i + 1 ]
  438. faces[ i + 1 ].getEdge( 0 ).setTwin( faces[ j + 1 ].getEdge( 1 ) );
  439. }
  440. }
  441. // the initial hull is the tetrahedron
  442. for ( let i = 0; i < 4; i ++ ) {
  443. this.faces.push( faces[ i ] );
  444. }
  445. // initial assignment of vertices to the faces of the tetrahedron
  446. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  447. const vertex = vertices[ i ];
  448. if ( vertex !== v0 && vertex !== v1 && vertex !== v2 && vertex !== v3 ) {
  449. maxDistance = this.tolerance;
  450. let maxFace = null;
  451. for ( let j = 0; j < 4; j ++ ) {
  452. const distance = this.faces[ j ].distanceToPoint( vertex.point );
  453. if ( distance > maxDistance ) {
  454. maxDistance = distance;
  455. maxFace = this.faces[ j ];
  456. }
  457. }
  458. if ( maxFace !== null ) {
  459. this._addVertexToFace( vertex, maxFace );
  460. }
  461. }
  462. }
  463. return this;
  464. }
  465. /**
  466. * Removes inactive (e.g. deleted) faces from the internal face list.
  467. *
  468. * @private
  469. * @return {ConvexHull} A reference to this convex hull.
  470. */
  471. _reindexFaces() {
  472. const activeFaces = [];
  473. for ( let i = 0; i < this.faces.length; i ++ ) {
  474. const face = this.faces[ i ];
  475. if ( face.mark === Visible ) {
  476. activeFaces.push( face );
  477. }
  478. }
  479. this.faces = activeFaces;
  480. return this;
  481. }
  482. /**
  483. * Finds the next vertex to create faces with the current hull.
  484. *
  485. * - Let the initial face be the first face existing in the 'assigned' vertex list.
  486. * - If a face doesn't exist then return since there're no vertices left.
  487. * - Otherwise for each vertex that face sees find the one furthest away from it.
  488. *
  489. * @private
  490. * @return {?VertexNode} The next vertex to add.
  491. */
  492. _nextVertexToAdd() {
  493. // if the 'assigned' list of vertices is empty, no vertices are left. return with 'undefined'
  494. if ( this.assigned.isEmpty() === false ) {
  495. let eyeVertex, maxDistance = 0;
  496. // grab the first available face and start with the first visible vertex of that face
  497. const eyeFace = this.assigned.first().face;
  498. let vertex = eyeFace.outside;
  499. // now calculate the farthest vertex that face can see
  500. do {
  501. const distance = eyeFace.distanceToPoint( vertex.point );
  502. if ( distance > maxDistance ) {
  503. maxDistance = distance;
  504. eyeVertex = vertex;
  505. }
  506. vertex = vertex.next;
  507. } while ( vertex !== null && vertex.face === eyeFace );
  508. return eyeVertex;
  509. }
  510. }
  511. /**
  512. * Computes a chain of half edges in CCW order called the 'horizon'. For an edge
  513. * to be part of the horizon it must join a face that can see 'eyePoint' and a face
  514. * that cannot see 'eyePoint'.
  515. *
  516. * @private
  517. * @param {Vector3} eyePoint - The 3D-coordinates of a point.
  518. * @param {HalfEdge} crossEdge - The edge used to jump to the current face.
  519. * @param {Face} face - The current face being tested.
  520. * @param {Array<HalfEdge>} horizon - The edges that form part of the horizon in CCW order.
  521. * @return {ConvexHull} A reference to this convex hull.
  522. */
  523. _computeHorizon( eyePoint, crossEdge, face, horizon ) {
  524. // moves face's vertices to the 'unassigned' vertex list
  525. this._deleteFaceVertices( face );
  526. face.mark = Deleted;
  527. let edge;
  528. if ( crossEdge === null ) {
  529. edge = crossEdge = face.getEdge( 0 );
  530. } else {
  531. // start from the next edge since 'crossEdge' was already analyzed
  532. // (actually 'crossEdge.twin' was the edge who called this method recursively)
  533. edge = crossEdge.next;
  534. }
  535. do {
  536. const twinEdge = edge.twin;
  537. const oppositeFace = twinEdge.face;
  538. if ( oppositeFace.mark === Visible ) {
  539. if ( oppositeFace.distanceToPoint( eyePoint ) > this.tolerance ) {
  540. // the opposite face can see the vertex, so proceed with next edge
  541. this._computeHorizon( eyePoint, twinEdge, oppositeFace, horizon );
  542. } else {
  543. // the opposite face can't see the vertex, so this edge is part of the horizon
  544. horizon.push( edge );
  545. }
  546. }
  547. edge = edge.next;
  548. } while ( edge !== crossEdge );
  549. return this;
  550. }
  551. /**
  552. * Creates a face with the vertices 'eyeVertex.point', 'horizonEdge.tail' and 'horizonEdge.head'
  553. * in CCW order. All the half edges are created in CCW order thus the face is always pointing
  554. * outside the hull.
  555. *
  556. * @private
  557. * @param {VertexNode} eyeVertex - The vertex that is added to the hull.
  558. * @param {HalfEdge} horizonEdge - A single edge of the horizon.
  559. * @return {HalfEdge} The half edge whose vertex is the eyeVertex.
  560. */
  561. _addAdjoiningFace( eyeVertex, horizonEdge ) {
  562. // all the half edges are created in ccw order thus the face is always pointing outside the hull
  563. const face = Face.create( eyeVertex, horizonEdge.tail(), horizonEdge.head() );
  564. this.faces.push( face );
  565. // join face.getEdge( - 1 ) with the horizon's opposite edge face.getEdge( - 1 ) = face.getEdge( 2 )
  566. face.getEdge( - 1 ).setTwin( horizonEdge.twin );
  567. return face.getEdge( 0 ); // the half edge whose vertex is the eyeVertex
  568. }
  569. /**
  570. * Adds 'horizon.length' faces to the hull, each face will be linked with the horizon
  571. * opposite face and the face on the left/right.
  572. *
  573. * @private
  574. * @param {VertexNode} eyeVertex - The vertex that is added to the hull.
  575. * @param {Array<HalfEdge>} horizon - The horizon.
  576. * @return {ConvexHull} A reference to this convex hull.
  577. */
  578. _addNewFaces( eyeVertex, horizon ) {
  579. this.newFaces = [];
  580. let firstSideEdge = null;
  581. let previousSideEdge = null;
  582. for ( let i = 0; i < horizon.length; i ++ ) {
  583. const horizonEdge = horizon[ i ];
  584. // returns the right side edge
  585. const sideEdge = this._addAdjoiningFace( eyeVertex, horizonEdge );
  586. if ( firstSideEdge === null ) {
  587. firstSideEdge = sideEdge;
  588. } else {
  589. // joins face.getEdge( 1 ) with previousFace.getEdge( 0 )
  590. sideEdge.next.setTwin( previousSideEdge );
  591. }
  592. this.newFaces.push( sideEdge.face );
  593. previousSideEdge = sideEdge;
  594. }
  595. // perform final join of new faces
  596. firstSideEdge.next.setTwin( previousSideEdge );
  597. return this;
  598. }
  599. /**
  600. * Adds a vertex to the hull with the following algorithm:
  601. *
  602. * - Compute the 'horizon' which is a chain of half edges. For an edge to belong to this group
  603. * it must be the edge connecting a face that can see 'eyeVertex' and a face which cannot see 'eyeVertex'.
  604. * - All the faces that can see 'eyeVertex' have its visible vertices removed from the assigned vertex list.
  605. * - A new set of faces is created with each edge of the 'horizon' and 'eyeVertex'. Each face is connected
  606. * with the opposite horizon face and the face on the left/right.
  607. * - The vertices removed from all the visible faces are assigned to the new faces if possible.
  608. *
  609. * @private
  610. * @param {VertexNode} eyeVertex - The vertex to add.
  611. * @return {ConvexHull} A reference to this convex hull.
  612. */
  613. _addVertexToHull( eyeVertex ) {
  614. const horizon = [];
  615. this.unassigned.clear();
  616. // remove 'eyeVertex' from 'eyeVertex.face' so that it can't be added to the 'unassigned' vertex list
  617. this._removeVertexFromFace( eyeVertex, eyeVertex.face );
  618. this._computeHorizon( eyeVertex.point, null, eyeVertex.face, horizon );
  619. this._addNewFaces( eyeVertex, horizon );
  620. // reassign 'unassigned' vertices to the new faces
  621. this._resolveUnassignedPoints( this.newFaces );
  622. return this;
  623. }
  624. /**
  625. * Cleans up internal properties after computing the convex hull.
  626. *
  627. * @private
  628. * @return {ConvexHull} A reference to this convex hull.
  629. */
  630. _cleanup() {
  631. this.assigned.clear();
  632. this.unassigned.clear();
  633. this.newFaces = [];
  634. return this;
  635. }
  636. /**
  637. * Starts the execution of the quick hull algorithm.
  638. *
  639. * @private
  640. * @return {ConvexHull} A reference to this convex hull.
  641. */
  642. _compute() {
  643. let vertex;
  644. this._computeInitialHull();
  645. // add all available vertices gradually to the hull
  646. while ( ( vertex = this._nextVertexToAdd() ) !== undefined ) {
  647. this._addVertexToHull( vertex );
  648. }
  649. this._reindexFaces();
  650. this._cleanup();
  651. return this;
  652. }
  653. }
  654. /**
  655. * Represents a section bounded by a specific amount of half-edges.
  656. * The current implementation assumes that a face always consist of three edges.
  657. *
  658. * @private
  659. */
  660. class Face {
  661. /**
  662. * Constructs a new face.
  663. */
  664. constructor() {
  665. /**
  666. * The normal vector of the face.
  667. *
  668. * @private
  669. * @type {Vector3}
  670. */
  671. this.normal = new Vector3();
  672. /**
  673. * The midpoint or centroid of the face.
  674. *
  675. * @private
  676. * @type {Vector3}
  677. */
  678. this.midpoint = new Vector3();
  679. /**
  680. * The area of the face.
  681. *
  682. * @private
  683. * @type {number}
  684. * @default 0
  685. */
  686. this.area = 0;
  687. /**
  688. * Signed distance from face to the origin.
  689. *
  690. * @private
  691. * @type {number}
  692. * @default 0
  693. */
  694. this.constant = 0;
  695. /**
  696. * Reference to a vertex in a vertex list this face can see.
  697. *
  698. * @private
  699. * @type {?VertexNode}
  700. * @default null
  701. */
  702. this.outside = null; // reference to a vertex in a vertex list this face can see
  703. this.mark = Visible;
  704. /**
  705. * Reference to the base edge of a face. To retrieve all edges, you can use the
  706. * `next` reference of the current edge.
  707. *
  708. * @private
  709. * @type {?HalfEdge}
  710. * @default null
  711. */
  712. this.edge = null;
  713. }
  714. /**
  715. * Creates a face from the given vertex nodes.
  716. *
  717. * @private
  718. * @param {VertexNode} a - The first vertex node.
  719. * @param {VertexNode} b - The second vertex node.
  720. * @param {VertexNode} c - The third vertex node.
  721. * @return {Face} The created face.
  722. */
  723. static create( a, b, c ) {
  724. const face = new Face();
  725. const e0 = new HalfEdge( a, face );
  726. const e1 = new HalfEdge( b, face );
  727. const e2 = new HalfEdge( c, face );
  728. // join edges
  729. e0.next = e2.prev = e1;
  730. e1.next = e0.prev = e2;
  731. e2.next = e1.prev = e0;
  732. // main half edge reference
  733. face.edge = e0;
  734. return face.compute();
  735. }
  736. /**
  737. * Returns an edge by the given index.
  738. *
  739. * @private
  740. * @param {number} i - The edge index.
  741. * @return {HalfEdge} The edge.
  742. */
  743. getEdge( i ) {
  744. let edge = this.edge;
  745. while ( i > 0 ) {
  746. edge = edge.next;
  747. i --;
  748. }
  749. while ( i < 0 ) {
  750. edge = edge.prev;
  751. i ++;
  752. }
  753. return edge;
  754. }
  755. /**
  756. * Computes all properties of the face.
  757. *
  758. * @private
  759. * @return {Face} A reference to this face.
  760. */
  761. compute() {
  762. const a = this.edge.tail();
  763. const b = this.edge.head();
  764. const c = this.edge.next.head();
  765. _triangle.set( a.point, b.point, c.point );
  766. _triangle.getNormal( this.normal );
  767. _triangle.getMidpoint( this.midpoint );
  768. this.area = _triangle.getArea();
  769. this.constant = this.normal.dot( this.midpoint );
  770. return this;
  771. }
  772. /**
  773. * Returns the signed distance from a given point to the plane representation of this face.
  774. *
  775. * @private
  776. * @param {Vector3} point - The point to compute the distance to.
  777. * @return {number} The distance.
  778. */
  779. distanceToPoint( point ) {
  780. return this.normal.dot( point ) - this.constant;
  781. }
  782. }
  783. /**
  784. * The basis for a half-edge data structure, also known as doubly
  785. * connected edge list (DCEL).
  786. *
  787. * @private
  788. */
  789. class HalfEdge {
  790. /**
  791. * Constructs a new half edge.
  792. *
  793. * @param {VertexNode} vertex - A reference to its destination vertex.
  794. * @param {Face} face - A reference to its face.
  795. */
  796. constructor( vertex, face ) {
  797. /**
  798. * A reference to its destination vertex.
  799. *
  800. * @private
  801. * @type {VertexNode}
  802. */
  803. this.vertex = vertex;
  804. /**
  805. * Reference to the previous half-edge of the same face.
  806. *
  807. * @private
  808. * @type {?HalfEdge}
  809. * @default null
  810. */
  811. this.prev = null;
  812. /**
  813. * Reference to the next half-edge of the same face.
  814. *
  815. * @private
  816. * @type {?HalfEdge}
  817. * @default null
  818. */
  819. this.next = null;
  820. /**
  821. * Reference to the twin half-edge to reach the opposite face.
  822. *
  823. * @private
  824. * @type {?HalfEdge}
  825. * @default null
  826. */
  827. this.twin = null;
  828. /**
  829. * A reference to its face.
  830. *
  831. * @private
  832. * @type {Face}
  833. */
  834. this.face = face;
  835. }
  836. /**
  837. * Returns the destination vertex.
  838. *
  839. * @private
  840. * @return {VertexNode} The destination vertex.
  841. */
  842. head() {
  843. return this.vertex;
  844. }
  845. /**
  846. * Returns the origin vertex.
  847. *
  848. * @private
  849. * @return {VertexNode} The destination vertex.
  850. */
  851. tail() {
  852. return this.prev ? this.prev.vertex : null;
  853. }
  854. /**
  855. * Returns the Euclidean length (straight-line length) of the edge.
  856. *
  857. * @private
  858. * @return {number} The edge's length.
  859. */
  860. length() {
  861. const head = this.head();
  862. const tail = this.tail();
  863. if ( tail !== null ) {
  864. return tail.point.distanceTo( head.point );
  865. }
  866. return - 1;
  867. }
  868. /**
  869. * Returns the square of the Euclidean length (straight-line length) of the edge.
  870. *
  871. * @private
  872. * @return {number} The square of the edge's length.
  873. */
  874. lengthSquared() {
  875. const head = this.head();
  876. const tail = this.tail();
  877. if ( tail !== null ) {
  878. return tail.point.distanceToSquared( head.point );
  879. }
  880. return - 1;
  881. }
  882. /**
  883. * Sets the twin edge of this half-edge. It also ensures that the twin reference
  884. * of the given half-edge is correctly set.
  885. *
  886. * @private
  887. * @param {HalfEdge} edge - The twin edge to set.
  888. * @return {HalfEdge} A reference to this edge.
  889. */
  890. setTwin( edge ) {
  891. this.twin = edge;
  892. edge.twin = this;
  893. return this;
  894. }
  895. }
  896. /**
  897. * A vertex as a double linked list node.
  898. *
  899. * @private
  900. */
  901. class VertexNode {
  902. /**
  903. * Constructs a new vertex node.
  904. *
  905. * @param {Vector3} point - A point in 3D space.
  906. */
  907. constructor( point ) {
  908. /**
  909. * A point in 3D space.
  910. *
  911. * @private
  912. * @type {Vector3}
  913. */
  914. this.point = point;
  915. /**
  916. * Reference to the previous vertex in the double linked list.
  917. *
  918. * @private
  919. * @type {?VertexNode}
  920. * @default null
  921. */
  922. this.prev = null;
  923. /**
  924. * Reference to the next vertex in the double linked list.
  925. *
  926. * @private
  927. * @type {?VertexNode}
  928. * @default null
  929. */
  930. this.next = null;
  931. /**
  932. * Reference to the face that is able to see this vertex.
  933. *
  934. * @private
  935. * @type {?Face}
  936. * @default null
  937. */
  938. this.face = null;
  939. }
  940. }
  941. /**
  942. * A doubly linked list of vertices.
  943. *
  944. * @private
  945. */
  946. class VertexList {
  947. /**
  948. * Constructs a new vertex list.
  949. */
  950. constructor() {
  951. /**
  952. * Reference to the first vertex of the linked list.
  953. *
  954. * @private
  955. * @type {?VertexNode}
  956. * @default null
  957. */
  958. this.head = null;
  959. /**
  960. * Reference to the last vertex of the linked list.
  961. *
  962. * @private
  963. * @type {?VertexNode}
  964. * @default null
  965. */
  966. this.tail = null;
  967. }
  968. /**
  969. * Returns the head reference.
  970. *
  971. * @private
  972. * @return {VertexNode} The head reference.
  973. */
  974. first() {
  975. return this.head;
  976. }
  977. /**
  978. * Returns the tail reference.
  979. *
  980. * @private
  981. * @return {VertexNode} The tail reference.
  982. */
  983. last() {
  984. return this.tail;
  985. }
  986. /**
  987. * Clears the linked list.
  988. *
  989. * @private
  990. * @return {VertexList} A reference to this vertex list.
  991. */
  992. clear() {
  993. this.head = this.tail = null;
  994. return this;
  995. }
  996. /**
  997. * Inserts a vertex before a target vertex.
  998. *
  999. * @private
  1000. * @param {VertexNode} target - The target.
  1001. * @param {VertexNode} vertex - The vertex to insert.
  1002. * @return {VertexList} A reference to this vertex list.
  1003. */
  1004. insertBefore( target, vertex ) {
  1005. vertex.prev = target.prev;
  1006. vertex.next = target;
  1007. if ( vertex.prev === null ) {
  1008. this.head = vertex;
  1009. } else {
  1010. vertex.prev.next = vertex;
  1011. }
  1012. target.prev = vertex;
  1013. return this;
  1014. }
  1015. /**
  1016. * Inserts a vertex after a target vertex.
  1017. *
  1018. * @private
  1019. * @param {VertexNode} target - The target.
  1020. * @param {VertexNode} vertex - The vertex to insert.
  1021. * @return {VertexList} A reference to this vertex list.
  1022. */
  1023. insertAfter( target, vertex ) {
  1024. vertex.prev = target;
  1025. vertex.next = target.next;
  1026. if ( vertex.next === null ) {
  1027. this.tail = vertex;
  1028. } else {
  1029. vertex.next.prev = vertex;
  1030. }
  1031. target.next = vertex;
  1032. return this;
  1033. }
  1034. /**
  1035. * Appends a vertex to this vertex list.
  1036. *
  1037. * @private
  1038. * @param {VertexNode} vertex - The vertex to append.
  1039. * @return {VertexList} A reference to this vertex list.
  1040. */
  1041. append( vertex ) {
  1042. if ( this.head === null ) {
  1043. this.head = vertex;
  1044. } else {
  1045. this.tail.next = vertex;
  1046. }
  1047. vertex.prev = this.tail;
  1048. vertex.next = null; // the tail has no subsequent vertex
  1049. this.tail = vertex;
  1050. return this;
  1051. }
  1052. /**
  1053. * Appends a chain of vertices where the given vertex is the head.
  1054. *
  1055. * @private
  1056. * @param {VertexNode} vertex - The head vertex of a chain of vertices.
  1057. * @return {VertexList} A reference to this vertex list.
  1058. */
  1059. appendChain( vertex ) {
  1060. if ( this.head === null ) {
  1061. this.head = vertex;
  1062. } else {
  1063. this.tail.next = vertex;
  1064. }
  1065. vertex.prev = this.tail;
  1066. // ensure that the 'tail' reference points to the last vertex of the chain
  1067. while ( vertex.next !== null ) {
  1068. vertex = vertex.next;
  1069. }
  1070. this.tail = vertex;
  1071. return this;
  1072. }
  1073. /**
  1074. * Removes a vertex from the linked list.
  1075. *
  1076. * @private
  1077. * @param {VertexNode} vertex - The vertex to remove.
  1078. * @return {VertexList} A reference to this vertex list.
  1079. */
  1080. remove( vertex ) {
  1081. if ( vertex.prev === null ) {
  1082. this.head = vertex.next;
  1083. } else {
  1084. vertex.prev.next = vertex.next;
  1085. }
  1086. if ( vertex.next === null ) {
  1087. this.tail = vertex.prev;
  1088. } else {
  1089. vertex.next.prev = vertex.prev;
  1090. }
  1091. return this;
  1092. }
  1093. /**
  1094. * Removes a sublist of vertices from the linked list.
  1095. *
  1096. * @private
  1097. * @param {VertexNode} a - The head of the sublist.
  1098. * @param {VertexNode} b - The tail of the sublist.
  1099. * @return {VertexList} A reference to this vertex list.
  1100. */
  1101. removeSubList( a, b ) {
  1102. if ( a.prev === null ) {
  1103. this.head = b.next;
  1104. } else {
  1105. a.prev.next = b.next;
  1106. }
  1107. if ( b.next === null ) {
  1108. this.tail = a.prev;
  1109. } else {
  1110. b.next.prev = a.prev;
  1111. }
  1112. return this;
  1113. }
  1114. /**
  1115. * Returns `true` if the linked list is empty.
  1116. *
  1117. * @private
  1118. * @return {boolean} Whether the linked list is empty or not.
  1119. */
  1120. isEmpty() {
  1121. return this.head === null;
  1122. }
  1123. }
  1124. export { ConvexHull, Face, HalfEdge, VertexNode, VertexList };
粤ICP备19079148号