ConvexObjectBreaker.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. import {
  2. Line3,
  3. Mesh,
  4. Plane,
  5. Vector3
  6. } from '../../../build/three.module.js';
  7. import { ConvexGeometry } from '../geometries/ConvexGeometry.js';
  8. /**
  9. * @fileoverview This class can be used to subdivide a convex Geometry object into pieces.
  10. *
  11. * Usage:
  12. *
  13. * Use the function prepareBreakableObject to prepare a Mesh object to be broken.
  14. *
  15. * Then, call the various functions to subdivide the object (subdivideByImpact, cutByPlane)
  16. *
  17. * Sub-objects that are product of subdivision don't need prepareBreakableObject to be called on them.
  18. *
  19. * Requisites for the object:
  20. *
  21. * - Mesh object must have a BufferGeometry (not Geometry) and a Material
  22. *
  23. * - Vertex normals must be planar (not smoothed)
  24. *
  25. * - The geometry must be convex (this is not checked in the library). You can create convex
  26. * geometries with ConvexGeometry. The BoxGeometry, SphereGeometry and other convex primitives
  27. * can also be used.
  28. *
  29. * Note: This lib adds member variables to object's userData member (see prepareBreakableObject function)
  30. * Use with caution and read the code when using with other libs.
  31. *
  32. * @param {double} minSizeForBreak Min size a debris can have to break.
  33. * @param {double} smallDelta Max distance to consider that a point belongs to a plane.
  34. *
  35. */
  36. const _v1 = new Vector3();
  37. class ConvexObjectBreaker {
  38. constructor( minSizeForBreak = 1.4, smallDelta = 0.0001 ) {
  39. this.minSizeForBreak = minSizeForBreak;
  40. this.smallDelta = smallDelta;
  41. this.tempLine1 = new Line3();
  42. this.tempPlane1 = new Plane();
  43. this.tempPlane2 = new Plane();
  44. this.tempPlane_Cut = new Plane();
  45. this.tempCM1 = new Vector3();
  46. this.tempCM2 = new Vector3();
  47. this.tempVector3 = new Vector3();
  48. this.tempVector3_2 = new Vector3();
  49. this.tempVector3_3 = new Vector3();
  50. this.tempVector3_P0 = new Vector3();
  51. this.tempVector3_P1 = new Vector3();
  52. this.tempVector3_P2 = new Vector3();
  53. this.tempVector3_N0 = new Vector3();
  54. this.tempVector3_N1 = new Vector3();
  55. this.tempVector3_AB = new Vector3();
  56. this.tempVector3_CB = new Vector3();
  57. this.tempResultObjects = { object1: null, object2: null };
  58. this.segments = [];
  59. const n = 30 * 30;
  60. for ( let i = 0; i < n; i ++ ) this.segments[ i ] = false;
  61. }
  62. prepareBreakableObject( object, mass, velocity, angularVelocity, breakable ) {
  63. // object is a Object3d (normally a Mesh), must have a BufferGeometry, and it must be convex.
  64. // Its material property is propagated to its children (sub-pieces)
  65. // mass must be > 0
  66. if ( ! object.geometry.isBufferGeometry ) {
  67. console.error( 'THREE.ConvexObjectBreaker.prepareBreakableObject(): Parameter object must have a BufferGeometry.' );
  68. }
  69. const userData = object.userData;
  70. userData.mass = mass;
  71. userData.velocity = velocity.clone();
  72. userData.angularVelocity = angularVelocity.clone();
  73. userData.breakable = breakable;
  74. }
  75. /*
  76. * @param {int} maxRadialIterations Iterations for radial cuts.
  77. * @param {int} maxRandomIterations Max random iterations for not-radial cuts
  78. *
  79. * Returns the array of pieces
  80. */
  81. subdivideByImpact( object, pointOfImpact, normal, maxRadialIterations, maxRandomIterations ) {
  82. const debris = [];
  83. const tempPlane1 = this.tempPlane1;
  84. const tempPlane2 = this.tempPlane2;
  85. this.tempVector3.addVectors( pointOfImpact, normal );
  86. tempPlane1.setFromCoplanarPoints( pointOfImpact, object.position, this.tempVector3 );
  87. const maxTotalIterations = maxRandomIterations + maxRadialIterations;
  88. const scope = this;
  89. function subdivideRadial( subObject, startAngle, endAngle, numIterations ) {
  90. if ( Math.random() < numIterations * 0.05 || numIterations > maxTotalIterations ) {
  91. debris.push( subObject );
  92. return;
  93. }
  94. let angle = Math.PI;
  95. if ( numIterations === 0 ) {
  96. tempPlane2.normal.copy( tempPlane1.normal );
  97. tempPlane2.constant = tempPlane1.constant;
  98. } else {
  99. if ( numIterations <= maxRadialIterations ) {
  100. angle = ( endAngle - startAngle ) * ( 0.2 + 0.6 * Math.random() ) + startAngle;
  101. // Rotate tempPlane2 at impact point around normal axis and the angle
  102. scope.tempVector3_2.copy( object.position ).sub( pointOfImpact ).applyAxisAngle( normal, angle ).add( pointOfImpact );
  103. tempPlane2.setFromCoplanarPoints( pointOfImpact, scope.tempVector3, scope.tempVector3_2 );
  104. } else {
  105. angle = ( ( 0.5 * ( numIterations & 1 ) ) + 0.2 * ( 2 - Math.random() ) ) * Math.PI;
  106. // Rotate tempPlane2 at object position around normal axis and the angle
  107. scope.tempVector3_2.copy( pointOfImpact ).sub( subObject.position ).applyAxisAngle( normal, angle ).add( subObject.position );
  108. scope.tempVector3_3.copy( normal ).add( subObject.position );
  109. tempPlane2.setFromCoplanarPoints( subObject.position, scope.tempVector3_3, scope.tempVector3_2 );
  110. }
  111. }
  112. // Perform the cut
  113. scope.cutByPlane( subObject, tempPlane2, scope.tempResultObjects );
  114. const obj1 = scope.tempResultObjects.object1;
  115. const obj2 = scope.tempResultObjects.object2;
  116. if ( obj1 ) {
  117. subdivideRadial( obj1, startAngle, angle, numIterations + 1 );
  118. }
  119. if ( obj2 ) {
  120. subdivideRadial( obj2, angle, endAngle, numIterations + 1 );
  121. }
  122. }
  123. subdivideRadial( object, 0, 2 * Math.PI, 0 );
  124. return debris;
  125. }
  126. cutByPlane( object, plane, output ) {
  127. // Returns breakable objects in output.object1 and output.object2 members, the resulting 2 pieces of the cut.
  128. // object2 can be null if the plane doesn't cut the object.
  129. // object1 can be null only in case of internal error
  130. // Returned value is number of pieces, 0 for error.
  131. const geometry = object.geometry;
  132. const coords = geometry.attributes.position.array;
  133. const normals = geometry.attributes.normal.array;
  134. const numPoints = coords.length / 3;
  135. let numFaces = numPoints / 3;
  136. let indices = geometry.getIndex();
  137. if ( indices ) {
  138. indices = indices.array;
  139. numFaces = indices.length / 3;
  140. }
  141. function getVertexIndex( faceIdx, vert ) {
  142. // vert = 0, 1 or 2.
  143. const idx = faceIdx * 3 + vert;
  144. return indices ? indices[ idx ] : idx;
  145. }
  146. const points1 = [];
  147. const points2 = [];
  148. const delta = this.smallDelta;
  149. // Reset segments mark
  150. const numPointPairs = numPoints * numPoints;
  151. for ( let i = 0; i < numPointPairs; i ++ ) this.segments[ i ] = false;
  152. const p0 = this.tempVector3_P0;
  153. const p1 = this.tempVector3_P1;
  154. const n0 = this.tempVector3_N0;
  155. const n1 = this.tempVector3_N1;
  156. // Iterate through the faces to mark edges shared by coplanar faces
  157. for ( let i = 0; i < numFaces - 1; i ++ ) {
  158. const a1 = getVertexIndex( i, 0 );
  159. const b1 = getVertexIndex( i, 1 );
  160. const c1 = getVertexIndex( i, 2 );
  161. // Assuming all 3 vertices have the same normal
  162. n0.set( normals[ a1 ], normals[ a1 ] + 1, normals[ a1 ] + 2 );
  163. for ( let j = i + 1; j < numFaces; j ++ ) {
  164. const a2 = getVertexIndex( j, 0 );
  165. const b2 = getVertexIndex( j, 1 );
  166. const c2 = getVertexIndex( j, 2 );
  167. // Assuming all 3 vertices have the same normal
  168. n1.set( normals[ a2 ], normals[ a2 ] + 1, normals[ a2 ] + 2 );
  169. const coplanar = 1 - n0.dot( n1 ) < delta;
  170. if ( coplanar ) {
  171. if ( a1 === a2 || a1 === b2 || a1 === c2 ) {
  172. if ( b1 === a2 || b1 === b2 || b1 === c2 ) {
  173. this.segments[ a1 * numPoints + b1 ] = true;
  174. this.segments[ b1 * numPoints + a1 ] = true;
  175. } else {
  176. this.segments[ c1 * numPoints + a1 ] = true;
  177. this.segments[ a1 * numPoints + c1 ] = true;
  178. }
  179. } else if ( b1 === a2 || b1 === b2 || b1 === c2 ) {
  180. this.segments[ c1 * numPoints + b1 ] = true;
  181. this.segments[ b1 * numPoints + c1 ] = true;
  182. }
  183. }
  184. }
  185. }
  186. // Transform the plane to object local space
  187. const localPlane = this.tempPlane_Cut;
  188. object.updateMatrix();
  189. ConvexObjectBreaker.transformPlaneToLocalSpace( plane, object.matrix, localPlane );
  190. // Iterate through the faces adding points to both pieces
  191. for ( let i = 0; i < numFaces; i ++ ) {
  192. const va = getVertexIndex( i, 0 );
  193. const vb = getVertexIndex( i, 1 );
  194. const vc = getVertexIndex( i, 2 );
  195. for ( let segment = 0; segment < 3; segment ++ ) {
  196. const i0 = segment === 0 ? va : ( segment === 1 ? vb : vc );
  197. const i1 = segment === 0 ? vb : ( segment === 1 ? vc : va );
  198. const segmentState = this.segments[ i0 * numPoints + i1 ];
  199. if ( segmentState ) continue; // The segment already has been processed in another face
  200. // Mark segment as processed (also inverted segment)
  201. this.segments[ i0 * numPoints + i1 ] = true;
  202. this.segments[ i1 * numPoints + i0 ] = true;
  203. p0.set( coords[ 3 * i0 ], coords[ 3 * i0 + 1 ], coords[ 3 * i0 + 2 ] );
  204. p1.set( coords[ 3 * i1 ], coords[ 3 * i1 + 1 ], coords[ 3 * i1 + 2 ] );
  205. // mark: 1 for negative side, 2 for positive side, 3 for coplanar point
  206. let mark0 = 0;
  207. let d = localPlane.distanceToPoint( p0 );
  208. if ( d > delta ) {
  209. mark0 = 2;
  210. points2.push( p0.clone() );
  211. } else if ( d < - delta ) {
  212. mark0 = 1;
  213. points1.push( p0.clone() );
  214. } else {
  215. mark0 = 3;
  216. points1.push( p0.clone() );
  217. points2.push( p0.clone() );
  218. }
  219. // mark: 1 for negative side, 2 for positive side, 3 for coplanar point
  220. let mark1 = 0;
  221. d = localPlane.distanceToPoint( p1 );
  222. if ( d > delta ) {
  223. mark1 = 2;
  224. points2.push( p1.clone() );
  225. } else if ( d < - delta ) {
  226. mark1 = 1;
  227. points1.push( p1.clone() );
  228. } else {
  229. mark1 = 3;
  230. points1.push( p1.clone() );
  231. points2.push( p1.clone() );
  232. }
  233. if ( ( mark0 === 1 && mark1 === 2 ) || ( mark0 === 2 && mark1 === 1 ) ) {
  234. // Intersection of segment with the plane
  235. this.tempLine1.start.copy( p0 );
  236. this.tempLine1.end.copy( p1 );
  237. let intersection = new Vector3();
  238. intersection = localPlane.intersectLine( this.tempLine1, intersection );
  239. if ( intersection === null ) {
  240. // Shouldn't happen
  241. console.error( 'Internal error: segment does not intersect plane.' );
  242. output.segmentedObject1 = null;
  243. output.segmentedObject2 = null;
  244. return 0;
  245. }
  246. points1.push( intersection );
  247. points2.push( intersection.clone() );
  248. }
  249. }
  250. }
  251. // Calculate debris mass (very fast and imprecise):
  252. const newMass = object.userData.mass * 0.5;
  253. // Calculate debris Center of Mass (again fast and imprecise)
  254. this.tempCM1.set( 0, 0, 0 );
  255. let radius1 = 0;
  256. const numPoints1 = points1.length;
  257. if ( numPoints1 > 0 ) {
  258. for ( let i = 0; i < numPoints1; i ++ ) this.tempCM1.add( points1[ i ] );
  259. this.tempCM1.divideScalar( numPoints1 );
  260. for ( let i = 0; i < numPoints1; i ++ ) {
  261. const p = points1[ i ];
  262. p.sub( this.tempCM1 );
  263. radius1 = Math.max( radius1, p.x, p.y, p.z );
  264. }
  265. this.tempCM1.add( object.position );
  266. }
  267. this.tempCM2.set( 0, 0, 0 );
  268. let radius2 = 0;
  269. const numPoints2 = points2.length;
  270. if ( numPoints2 > 0 ) {
  271. for ( let i = 0; i < numPoints2; i ++ ) this.tempCM2.add( points2[ i ] );
  272. this.tempCM2.divideScalar( numPoints2 );
  273. for ( let i = 0; i < numPoints2; i ++ ) {
  274. const p = points2[ i ];
  275. p.sub( this.tempCM2 );
  276. radius2 = Math.max( radius2, p.x, p.y, p.z );
  277. }
  278. this.tempCM2.add( object.position );
  279. }
  280. let object1 = null;
  281. let object2 = null;
  282. let numObjects = 0;
  283. if ( numPoints1 > 4 ) {
  284. object1 = new Mesh( new ConvexGeometry( points1 ), object.material );
  285. object1.position.copy( this.tempCM1 );
  286. object1.quaternion.copy( object.quaternion );
  287. this.prepareBreakableObject( object1, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius1 > this.minSizeForBreak );
  288. numObjects ++;
  289. }
  290. if ( numPoints2 > 4 ) {
  291. object2 = new Mesh( new ConvexGeometry( points2 ), object.material );
  292. object2.position.copy( this.tempCM2 );
  293. object2.quaternion.copy( object.quaternion );
  294. this.prepareBreakableObject( object2, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius2 > this.minSizeForBreak );
  295. numObjects ++;
  296. }
  297. output.object1 = object1;
  298. output.object2 = object2;
  299. return numObjects;
  300. }
  301. static transformFreeVector( v, m ) {
  302. // input:
  303. // vector interpreted as a free vector
  304. // THREE.Matrix4 orthogonal matrix (matrix without scale)
  305. const x = v.x, y = v.y, z = v.z;
  306. const e = m.elements;
  307. v.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  308. v.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  309. v.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  310. return v;
  311. }
  312. static transformFreeVectorInverse( v, m ) {
  313. // input:
  314. // vector interpreted as a free vector
  315. // THREE.Matrix4 orthogonal matrix (matrix without scale)
  316. const x = v.x, y = v.y, z = v.z;
  317. const e = m.elements;
  318. v.x = e[ 0 ] * x + e[ 1 ] * y + e[ 2 ] * z;
  319. v.y = e[ 4 ] * x + e[ 5 ] * y + e[ 6 ] * z;
  320. v.z = e[ 8 ] * x + e[ 9 ] * y + e[ 10 ] * z;
  321. return v;
  322. }
  323. static transformTiedVectorInverse( v, m ) {
  324. // input:
  325. // vector interpreted as a tied (ordinary) vector
  326. // THREE.Matrix4 orthogonal matrix (matrix without scale)
  327. const x = v.x, y = v.y, z = v.z;
  328. const e = m.elements;
  329. v.x = e[ 0 ] * x + e[ 1 ] * y + e[ 2 ] * z - e[ 12 ];
  330. v.y = e[ 4 ] * x + e[ 5 ] * y + e[ 6 ] * z - e[ 13 ];
  331. v.z = e[ 8 ] * x + e[ 9 ] * y + e[ 10 ] * z - e[ 14 ];
  332. return v;
  333. }
  334. static transformPlaneToLocalSpace( plane, m, resultPlane ) {
  335. resultPlane.normal.copy( plane.normal );
  336. resultPlane.constant = plane.constant;
  337. const referencePoint = ConvexObjectBreaker.transformTiedVectorInverse( plane.coplanarPoint( _v1 ), m );
  338. ConvexObjectBreaker.transformFreeVectorInverse( resultPlane.normal, m );
  339. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  340. resultPlane.constant = - referencePoint.dot( resultPlane.normal );
  341. }
  342. }
  343. export { ConvexObjectBreaker };