CCDIKSolver.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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://web.archive.org/web/20221206080850/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._initialQuaternions = [];
  54. this._workingQuaternion = new Quaternion();
  55. for ( const ik of iks ) {
  56. const chainQuats = [];
  57. for ( let i = 0; i < ik.links.length; i ++ ) {
  58. chainQuats.push( new Quaternion() );
  59. }
  60. this._initialQuaternions.push( chainQuats );
  61. }
  62. this._valid();
  63. }
  64. /**
  65. * Update all IK bones.
  66. *
  67. * @param {number} [globalBlendFactor=1.0] - Blend factor applied if an IK chain doesn't have its own .blendFactor.
  68. * @return {CCDIKSolver}
  69. */
  70. update( globalBlendFactor = 1.0 ) {
  71. const iks = this.iks;
  72. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  73. this.updateOne( iks[ i ], globalBlendFactor );
  74. }
  75. return this;
  76. }
  77. /**
  78. * Update one IK bone
  79. *
  80. * @param {Object} ik parameter
  81. * @param {number} [overrideBlend=1.0] - If the ik object does not define .blendFactor, this value is used.
  82. * @return {CCDIKSolver}
  83. */
  84. updateOne( ik, overrideBlend = 1.0 ) {
  85. const chainBlend = ik.blendFactor !== undefined ? ik.blendFactor : overrideBlend;
  86. const bones = this.mesh.skeleton.bones;
  87. const chainIndex = this.iks.indexOf( ik );
  88. const initialQuaternions = this._initialQuaternions[ chainIndex ];
  89. // for reference overhead reduction in loop
  90. const math = Math;
  91. const effector = bones[ ik.effector ];
  92. const target = bones[ ik.target ];
  93. // don't use getWorldPosition() here for the performance
  94. // because it calls updateMatrixWorld( true ) inside.
  95. _targetPos.setFromMatrixPosition( target.matrixWorld );
  96. const links = ik.links;
  97. const iteration = ik.iteration !== undefined ? ik.iteration : 1;
  98. if ( chainBlend < 1.0 ) {
  99. for ( let j = 0; j < links.length; j ++ ) {
  100. const linkIndex = links[ j ].index;
  101. initialQuaternions[ j ].copy( bones[ linkIndex ].quaternion );
  102. }
  103. }
  104. for ( let i = 0; i < iteration; i ++ ) {
  105. let rotated = false;
  106. for ( let j = 0, jl = links.length; j < jl; j ++ ) {
  107. const link = bones[ links[ j ].index ];
  108. // skip this link and following links
  109. if ( links[ j ].enabled === false ) break;
  110. const limitation = links[ j ].limitation;
  111. const rotationMin = links[ j ].rotationMin;
  112. const rotationMax = links[ j ].rotationMax;
  113. // don't use getWorldPosition/Quaternion() here for the performance
  114. // because they call updateMatrixWorld( true ) inside.
  115. link.matrixWorld.decompose( _linkPos, _invLinkQ, _linkScale );
  116. _invLinkQ.invert();
  117. _effectorPos.setFromMatrixPosition( effector.matrixWorld );
  118. // work in link world
  119. _effectorVec.subVectors( _effectorPos, _linkPos );
  120. _effectorVec.applyQuaternion( _invLinkQ );
  121. _effectorVec.normalize();
  122. _targetVec.subVectors( _targetPos, _linkPos );
  123. _targetVec.applyQuaternion( _invLinkQ );
  124. _targetVec.normalize();
  125. let angle = _targetVec.dot( _effectorVec );
  126. if ( angle > 1.0 ) {
  127. angle = 1.0;
  128. } else if ( angle < - 1.0 ) {
  129. angle = - 1.0;
  130. }
  131. angle = math.acos( angle );
  132. // skip if changing angle is too small to prevent vibration of bone
  133. if ( angle < 1e-5 ) continue;
  134. if ( ik.minAngle !== undefined && angle < ik.minAngle ) {
  135. angle = ik.minAngle;
  136. }
  137. if ( ik.maxAngle !== undefined && angle > ik.maxAngle ) {
  138. angle = ik.maxAngle;
  139. }
  140. _axis.crossVectors( _effectorVec, _targetVec );
  141. _axis.normalize();
  142. _q.setFromAxisAngle( _axis, angle );
  143. link.quaternion.multiply( _q );
  144. // TODO: re-consider the limitation specification
  145. if ( limitation !== undefined ) {
  146. let c = link.quaternion.w;
  147. if ( c > 1.0 ) c = 1.0;
  148. const c2 = math.sqrt( 1 - c * c );
  149. link.quaternion.set( limitation.x * c2,
  150. limitation.y * c2,
  151. limitation.z * c2,
  152. c );
  153. }
  154. if ( rotationMin !== undefined ) {
  155. link.rotation.setFromVector3( _vector.setFromEuler( link.rotation ).max( rotationMin ) );
  156. }
  157. if ( rotationMax !== undefined ) {
  158. link.rotation.setFromVector3( _vector.setFromEuler( link.rotation ).min( rotationMax ) );
  159. }
  160. link.updateMatrixWorld( true );
  161. rotated = true;
  162. }
  163. if ( ! rotated ) break;
  164. }
  165. if ( chainBlend < 1.0 ) {
  166. for ( let j = 0; j < links.length; j ++ ) {
  167. const linkIndex = links[ j ].index;
  168. const link = bones[ linkIndex ];
  169. this._workingQuaternion.copy( initialQuaternions[ j ] ).slerp( link.quaternion, chainBlend );
  170. link.quaternion.copy( this._workingQuaternion );
  171. link.updateMatrixWorld( true );
  172. }
  173. }
  174. return this;
  175. }
  176. /**
  177. * Creates Helper
  178. *
  179. * @param {number} sphereSize
  180. * @return {CCDIKHelper}
  181. */
  182. createHelper( sphereSize ) {
  183. return new CCDIKHelper( this.mesh, this.iks, sphereSize );
  184. }
  185. // private methods
  186. _valid() {
  187. const iks = this.iks;
  188. const bones = this.mesh.skeleton.bones;
  189. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  190. const ik = iks[ i ];
  191. const effector = bones[ ik.effector ];
  192. const links = ik.links;
  193. let link0, link1;
  194. link0 = effector;
  195. for ( let j = 0, jl = links.length; j < jl; j ++ ) {
  196. link1 = bones[ links[ j ].index ];
  197. if ( link0.parent !== link1 ) {
  198. console.warn( 'THREE.CCDIKSolver: bone ' + link0.name + ' is not the child of bone ' + link1.name );
  199. }
  200. link0 = link1;
  201. }
  202. }
  203. }
  204. }
  205. function getPosition( bone, matrixWorldInv ) {
  206. return _vector
  207. .setFromMatrixPosition( bone.matrixWorld )
  208. .applyMatrix4( matrixWorldInv );
  209. }
  210. function setPositionOfBoneToAttributeArray( array, index, bone, matrixWorldInv ) {
  211. const v = getPosition( bone, matrixWorldInv );
  212. array[ index * 3 + 0 ] = v.x;
  213. array[ index * 3 + 1 ] = v.y;
  214. array[ index * 3 + 2 ] = v.z;
  215. }
  216. /**
  217. * Visualize IK bones
  218. */
  219. class CCDIKHelper extends Object3D {
  220. /**
  221. * @param {SkinnedMesh} mesh
  222. * @param {Array<Object>} [iks=[]]
  223. * @param {number} [sphereSize=0.25]
  224. */
  225. constructor( mesh, iks = [], sphereSize = 0.25 ) {
  226. super();
  227. this.root = mesh;
  228. this.iks = iks;
  229. this.matrix.copy( mesh.matrixWorld );
  230. this.matrixAutoUpdate = false;
  231. this.sphereGeometry = new SphereGeometry( sphereSize, 16, 8 );
  232. this.targetSphereMaterial = new MeshBasicMaterial( {
  233. color: new Color( 0xff8888 ),
  234. depthTest: false,
  235. depthWrite: false,
  236. transparent: true
  237. } );
  238. this.effectorSphereMaterial = new MeshBasicMaterial( {
  239. color: new Color( 0x88ff88 ),
  240. depthTest: false,
  241. depthWrite: false,
  242. transparent: true
  243. } );
  244. this.linkSphereMaterial = new MeshBasicMaterial( {
  245. color: new Color( 0x8888ff ),
  246. depthTest: false,
  247. depthWrite: false,
  248. transparent: true
  249. } );
  250. this.lineMaterial = new LineBasicMaterial( {
  251. color: new Color( 0xff0000 ),
  252. depthTest: false,
  253. depthWrite: false,
  254. transparent: true
  255. } );
  256. this._init();
  257. }
  258. /**
  259. * Updates IK bones visualization.
  260. *
  261. * @param {boolean} force
  262. */
  263. updateMatrixWorld( force ) {
  264. const mesh = this.root;
  265. if ( this.visible ) {
  266. let offset = 0;
  267. const iks = this.iks;
  268. const bones = mesh.skeleton.bones;
  269. _matrix.copy( mesh.matrixWorld ).invert();
  270. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  271. const ik = iks[ i ];
  272. const targetBone = bones[ ik.target ];
  273. const effectorBone = bones[ ik.effector ];
  274. const targetMesh = this.children[ offset ++ ];
  275. const effectorMesh = this.children[ offset ++ ];
  276. targetMesh.position.copy( getPosition( targetBone, _matrix ) );
  277. effectorMesh.position.copy( getPosition( effectorBone, _matrix ) );
  278. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  279. const link = ik.links[ j ];
  280. const linkBone = bones[ link.index ];
  281. const linkMesh = this.children[ offset ++ ];
  282. linkMesh.position.copy( getPosition( linkBone, _matrix ) );
  283. }
  284. const line = this.children[ offset ++ ];
  285. const array = line.geometry.attributes.position.array;
  286. setPositionOfBoneToAttributeArray( array, 0, targetBone, _matrix );
  287. setPositionOfBoneToAttributeArray( array, 1, effectorBone, _matrix );
  288. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  289. const link = ik.links[ j ];
  290. const linkBone = bones[ link.index ];
  291. setPositionOfBoneToAttributeArray( array, j + 2, linkBone, _matrix );
  292. }
  293. line.geometry.attributes.position.needsUpdate = true;
  294. }
  295. }
  296. this.matrix.copy( mesh.matrixWorld );
  297. super.updateMatrixWorld( force );
  298. }
  299. /**
  300. * Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.
  301. */
  302. dispose() {
  303. this.sphereGeometry.dispose();
  304. this.targetSphereMaterial.dispose();
  305. this.effectorSphereMaterial.dispose();
  306. this.linkSphereMaterial.dispose();
  307. this.lineMaterial.dispose();
  308. const children = this.children;
  309. for ( let i = 0; i < children.length; i ++ ) {
  310. const child = children[ i ];
  311. if ( child.isLine ) child.geometry.dispose();
  312. }
  313. }
  314. // private method
  315. _init() {
  316. const scope = this;
  317. const iks = this.iks;
  318. function createLineGeometry( ik ) {
  319. const geometry = new BufferGeometry();
  320. const vertices = new Float32Array( ( 2 + ik.links.length ) * 3 );
  321. geometry.setAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  322. return geometry;
  323. }
  324. function createTargetMesh() {
  325. return new Mesh( scope.sphereGeometry, scope.targetSphereMaterial );
  326. }
  327. function createEffectorMesh() {
  328. return new Mesh( scope.sphereGeometry, scope.effectorSphereMaterial );
  329. }
  330. function createLinkMesh() {
  331. return new Mesh( scope.sphereGeometry, scope.linkSphereMaterial );
  332. }
  333. function createLine( ik ) {
  334. return new Line( createLineGeometry( ik ), scope.lineMaterial );
  335. }
  336. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  337. const ik = iks[ i ];
  338. this.add( createTargetMesh() );
  339. this.add( createEffectorMesh() );
  340. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  341. this.add( createLinkMesh() );
  342. }
  343. this.add( createLine( ik ) );
  344. }
  345. }
  346. }
  347. export { CCDIKSolver, CCDIKHelper };
粤ICP备19079148号