ConvexObjectBreaker.js 14 KB

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