ConvexObjectBreaker.js 15 KB

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