CCDIKSolver.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. import {
  2. BufferAttribute,
  3. BufferGeometry,
  4. Color,
  5. Line,
  6. LineBasicMaterial,
  7. Matrix4,
  8. Mesh,
  9. MeshBasicMaterial,
  10. Object3D,
  11. Quaternion,
  12. SphereGeometry,
  13. Vector3
  14. } from 'three';
  15. const _q = new Quaternion();
  16. const _targetPos = new Vector3();
  17. const _targetVec = new Vector3();
  18. const _effectorPos = new Vector3();
  19. const _effectorVec = new Vector3();
  20. const _linkPos = new Vector3();
  21. const _invLinkQ = new Quaternion();
  22. const _linkScale = new Vector3();
  23. const _axis = new Vector3();
  24. const _vector = new Vector3();
  25. const _matrix = new Matrix4();
  26. /**
  27. * CCD Algorithm
  28. * - https://sites.google.com/site/auraliusproject/ccd-algorithm
  29. *
  30. * // ik parameter example
  31. * //
  32. * // target, effector, index in links are bone index in skeleton.bones.
  33. * // the bones relation should be
  34. * // <-- parent child -->
  35. * // links[ n ], links[ n - 1 ], ..., links[ 0 ], effector
  36. * iks = [ {
  37. * target: 1,
  38. * effector: 2,
  39. * links: [ { index: 5, limitation: new Vector3( 1, 0, 0 ) }, { index: 4, enabled: false }, { index : 3 } ],
  40. * iteration: 10,
  41. * minAngle: 0.0,
  42. * maxAngle: 1.0,
  43. * } ];
  44. */
  45. class CCDIKSolver {
  46. /**
  47. * @param {THREE.SkinnedMesh} mesh
  48. * @param {Array<Object>} iks
  49. */
  50. constructor( mesh, iks = [] ) {
  51. this.mesh = mesh;
  52. this.iks = iks;
  53. this._valid();
  54. }
  55. /**
  56. * Update all IK bones.
  57. *
  58. * @return {CCDIKSolver}
  59. */
  60. update() {
  61. const iks = this.iks;
  62. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  63. this.updateOne( iks[ i ] );
  64. }
  65. return this;
  66. }
  67. /**
  68. * Update one IK bone
  69. *
  70. * @param {Object} ik parameter
  71. * @return {CCDIKSolver}
  72. */
  73. updateOne( ik ) {
  74. const bones = this.mesh.skeleton.bones;
  75. // for reference overhead reduction in loop
  76. const math = Math;
  77. const effector = bones[ ik.effector ];
  78. const target = bones[ ik.target ];
  79. // don't use getWorldPosition() here for the performance
  80. // because it calls updateMatrixWorld( true ) inside.
  81. _targetPos.setFromMatrixPosition( target.matrixWorld );
  82. const links = ik.links;
  83. const iteration = ik.iteration !== undefined ? ik.iteration : 1;
  84. for ( let i = 0; i < iteration; i ++ ) {
  85. let rotated = false;
  86. for ( let j = 0, jl = links.length; j < jl; j ++ ) {
  87. const link = bones[ links[ j ].index ];
  88. // skip this link and following links.
  89. // this skip is used for MMD performance optimization.
  90. if ( links[ j ].enabled === false ) break;
  91. const limitation = links[ j ].limitation;
  92. const rotationMin = links[ j ].rotationMin;
  93. const rotationMax = links[ j ].rotationMax;
  94. // don't use getWorldPosition/Quaternion() here for the performance
  95. // because they call updateMatrixWorld( true ) inside.
  96. link.matrixWorld.decompose( _linkPos, _invLinkQ, _linkScale );
  97. _invLinkQ.invert();
  98. _effectorPos.setFromMatrixPosition( effector.matrixWorld );
  99. // work in link world
  100. _effectorVec.subVectors( _effectorPos, _linkPos );
  101. _effectorVec.applyQuaternion( _invLinkQ );
  102. _effectorVec.normalize();
  103. _targetVec.subVectors( _targetPos, _linkPos );
  104. _targetVec.applyQuaternion( _invLinkQ );
  105. _targetVec.normalize();
  106. let angle = _targetVec.dot( _effectorVec );
  107. if ( angle > 1.0 ) {
  108. angle = 1.0;
  109. } else if ( angle < - 1.0 ) {
  110. angle = - 1.0;
  111. }
  112. angle = math.acos( angle );
  113. // skip if changing angle is too small to prevent vibration of bone
  114. if ( angle < 1e-5 ) continue;
  115. if ( ik.minAngle !== undefined && angle < ik.minAngle ) {
  116. angle = ik.minAngle;
  117. }
  118. if ( ik.maxAngle !== undefined && angle > ik.maxAngle ) {
  119. angle = ik.maxAngle;
  120. }
  121. _axis.crossVectors( _effectorVec, _targetVec );
  122. _axis.normalize();
  123. _q.setFromAxisAngle( _axis, angle );
  124. link.quaternion.multiply( _q );
  125. // TODO: re-consider the limitation specification
  126. if ( limitation !== undefined ) {
  127. let c = link.quaternion.w;
  128. if ( c > 1.0 ) c = 1.0;
  129. const c2 = math.sqrt( 1 - c * c );
  130. link.quaternion.set( limitation.x * c2,
  131. limitation.y * c2,
  132. limitation.z * c2,
  133. c );
  134. }
  135. if ( rotationMin !== undefined ) {
  136. link.rotation.setFromVector3(
  137. link.rotation
  138. .toVector3( _vector )
  139. .max( rotationMin ) );
  140. }
  141. if ( rotationMax !== undefined ) {
  142. link.rotation.setFromVector3(
  143. link.rotation
  144. .toVector3( _vector )
  145. .min( rotationMax ) );
  146. }
  147. link.updateMatrixWorld( true );
  148. rotated = true;
  149. }
  150. if ( ! rotated ) break;
  151. }
  152. return this;
  153. }
  154. /**
  155. * Creates Helper
  156. *
  157. * @return {CCDIKHelper}
  158. */
  159. createHelper() {
  160. return new CCDIKHelper( this.mesh, this.mesh.geometry.userData.MMD.iks );
  161. }
  162. // private methods
  163. _valid() {
  164. const iks = this.iks;
  165. const bones = this.mesh.skeleton.bones;
  166. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  167. const ik = iks[ i ];
  168. const effector = bones[ ik.effector ];
  169. const links = ik.links;
  170. let link0, link1;
  171. link0 = effector;
  172. for ( let j = 0, jl = links.length; j < jl; j ++ ) {
  173. link1 = bones[ links[ j ].index ];
  174. if ( link0.parent !== link1 ) {
  175. console.warn( 'THREE.CCDIKSolver: bone ' + link0.name + ' is not the child of bone ' + link1.name );
  176. }
  177. link0 = link1;
  178. }
  179. }
  180. }
  181. }
  182. function getPosition( bone, matrixWorldInv ) {
  183. return _vector
  184. .setFromMatrixPosition( bone.matrixWorld )
  185. .applyMatrix4( matrixWorldInv );
  186. }
  187. function setPositionOfBoneToAttributeArray( array, index, bone, matrixWorldInv ) {
  188. const v = getPosition( bone, matrixWorldInv );
  189. array[ index * 3 + 0 ] = v.x;
  190. array[ index * 3 + 1 ] = v.y;
  191. array[ index * 3 + 2 ] = v.z;
  192. }
  193. /**
  194. * Visualize IK bones
  195. *
  196. * @param {SkinnedMesh} mesh
  197. * @param {Array<Object>} iks
  198. */
  199. class CCDIKHelper extends Object3D {
  200. constructor( mesh, iks = [] ) {
  201. super();
  202. this.root = mesh;
  203. this.iks = iks;
  204. this.matrix.copy( mesh.matrixWorld );
  205. this.matrixAutoUpdate = false;
  206. this.sphereGeometry = new SphereGeometry( 0.25, 16, 8 );
  207. this.targetSphereMaterial = new MeshBasicMaterial( {
  208. color: new Color( 0xff8888 ),
  209. depthTest: false,
  210. depthWrite: false,
  211. transparent: true
  212. } );
  213. this.effectorSphereMaterial = new MeshBasicMaterial( {
  214. color: new Color( 0x88ff88 ),
  215. depthTest: false,
  216. depthWrite: false,
  217. transparent: true
  218. } );
  219. this.linkSphereMaterial = new MeshBasicMaterial( {
  220. color: new Color( 0x8888ff ),
  221. depthTest: false,
  222. depthWrite: false,
  223. transparent: true
  224. } );
  225. this.lineMaterial = new LineBasicMaterial( {
  226. color: new Color( 0xff0000 ),
  227. depthTest: false,
  228. depthWrite: false,
  229. transparent: true
  230. } );
  231. this._init();
  232. }
  233. /**
  234. * Updates IK bones visualization.
  235. */
  236. updateMatrixWorld( force ) {
  237. const mesh = this.root;
  238. if ( this.visible ) {
  239. let offset = 0;
  240. const iks = this.iks;
  241. const bones = mesh.skeleton.bones;
  242. _matrix.copy( mesh.matrixWorld ).invert();
  243. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  244. const ik = iks[ i ];
  245. const targetBone = bones[ ik.target ];
  246. const effectorBone = bones[ ik.effector ];
  247. const targetMesh = this.children[ offset ++ ];
  248. const effectorMesh = this.children[ offset ++ ];
  249. targetMesh.position.copy( getPosition( targetBone, _matrix ) );
  250. effectorMesh.position.copy( getPosition( effectorBone, _matrix ) );
  251. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  252. const link = ik.links[ j ];
  253. const linkBone = bones[ link.index ];
  254. const linkMesh = this.children[ offset ++ ];
  255. linkMesh.position.copy( getPosition( linkBone, _matrix ) );
  256. }
  257. const line = this.children[ offset ++ ];
  258. const array = line.geometry.attributes.position.array;
  259. setPositionOfBoneToAttributeArray( array, 0, targetBone, _matrix );
  260. setPositionOfBoneToAttributeArray( array, 1, effectorBone, _matrix );
  261. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  262. const link = ik.links[ j ];
  263. const linkBone = bones[ link.index ];
  264. setPositionOfBoneToAttributeArray( array, j + 2, linkBone, _matrix );
  265. }
  266. line.geometry.attributes.position.needsUpdate = true;
  267. }
  268. }
  269. this.matrix.copy( mesh.matrixWorld );
  270. super.updateMatrixWorld( force );
  271. }
  272. // private method
  273. _init() {
  274. const scope = this;
  275. const iks = this.iks;
  276. function createLineGeometry( ik ) {
  277. const geometry = new BufferGeometry();
  278. const vertices = new Float32Array( ( 2 + ik.links.length ) * 3 );
  279. geometry.setAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  280. return geometry;
  281. }
  282. function createTargetMesh() {
  283. return new Mesh( scope.sphereGeometry, scope.targetSphereMaterial );
  284. }
  285. function createEffectorMesh() {
  286. return new Mesh( scope.sphereGeometry, scope.effectorSphereMaterial );
  287. }
  288. function createLinkMesh() {
  289. return new Mesh( scope.sphereGeometry, scope.linkSphereMaterial );
  290. }
  291. function createLine( ik ) {
  292. return new Line( createLineGeometry( ik ), scope.lineMaterial );
  293. }
  294. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  295. const ik = iks[ i ];
  296. this.add( createTargetMesh() );
  297. this.add( createEffectorMesh() );
  298. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  299. this.add( createLinkMesh() );
  300. }
  301. this.add( createLine( ik ) );
  302. }
  303. }
  304. }
  305. export { CCDIKSolver };