CCDIKSolver.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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 _quaternion = 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. * This class solves the Inverse Kinematics Problem with a [CCD Algorithm]{@link https://web.archive.org/web/20221206080850/https://sites.google.com/site/auraliusproject/ccd-algorithm}.
  28. *
  29. * `CCDIKSolver` is designed to work with instances of {@link SkinnedMesh}.
  30. *
  31. * @three_import import { CCDIKSolver } from 'three/addons/animation/CCDIKSolver.js';
  32. */
  33. class CCDIKSolver {
  34. /**
  35. * @param {SkinnedMesh} mesh - The skinned mesh.
  36. * @param {Array<CCDIKSolver~IK>} [iks=[]] - The IK objects.
  37. */
  38. constructor( mesh, iks = [] ) {
  39. /**
  40. * The skinned mesh.
  41. *
  42. * @type {SkinnedMesh}
  43. */
  44. this.mesh = mesh;
  45. /**
  46. * The IK objects.
  47. *
  48. * @type {SkinnedMesh}
  49. */
  50. this.iks = iks;
  51. this._initialQuaternions = [];
  52. this._workingQuaternion = new Quaternion();
  53. for ( const ik of iks ) {
  54. const chainQuats = [];
  55. for ( let i = 0; i < ik.links.length; i ++ ) {
  56. chainQuats.push( new Quaternion() );
  57. }
  58. this._initialQuaternions.push( chainQuats );
  59. }
  60. this._valid();
  61. }
  62. /**
  63. * Updates all IK bones by solving the CCD algorithm.
  64. *
  65. * @param {number} [globalBlendFactor=1.0] - Blend factor applied if an IK chain doesn't have its own .blendFactor.
  66. * @return {CCDIKSolver} A reference to this instance.
  67. */
  68. update( globalBlendFactor = 1.0 ) {
  69. const iks = this.iks;
  70. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  71. this.updateOne( iks[ i ], globalBlendFactor );
  72. }
  73. return this;
  74. }
  75. /**
  76. * Updates one IK bone solving the CCD algorithm.
  77. *
  78. * @param {CCDIKSolver~IK} ik - The IK to update.
  79. * @param {number} [overrideBlend=1.0] - If the IK object does not define `blendFactor`, this value is used.
  80. * @return {CCDIKSolver} A reference to this instance.
  81. */
  82. updateOne( ik, overrideBlend = 1.0 ) {
  83. const chainBlend = ik.blendFactor !== undefined ? ik.blendFactor : overrideBlend;
  84. const bones = this.mesh.skeleton.bones;
  85. const chainIndex = this.iks.indexOf( ik );
  86. const initialQuaternions = this._initialQuaternions[ chainIndex ];
  87. // for reference overhead reduction in loop
  88. const math = Math;
  89. const effector = bones[ ik.effector ];
  90. const target = bones[ ik.target ];
  91. // don't use getWorldPosition() here for the performance
  92. // because it calls updateMatrixWorld( true ) inside.
  93. _targetPos.setFromMatrixPosition( target.matrixWorld );
  94. const links = ik.links;
  95. const iteration = ik.iteration !== undefined ? ik.iteration : 1;
  96. if ( chainBlend < 1.0 ) {
  97. for ( let j = 0; j < links.length; j ++ ) {
  98. const linkIndex = links[ j ].index;
  99. initialQuaternions[ j ].copy( bones[ linkIndex ].quaternion );
  100. }
  101. }
  102. for ( let i = 0; i < iteration; i ++ ) {
  103. let rotated = false;
  104. for ( let j = 0, jl = links.length; j < jl; j ++ ) {
  105. const link = bones[ links[ j ].index ];
  106. // skip this link and following links
  107. if ( links[ j ].enabled === false ) break;
  108. const limitation = links[ j ].limitation;
  109. const rotationMin = links[ j ].rotationMin;
  110. const rotationMax = links[ j ].rotationMax;
  111. // don't use getWorldPosition/Quaternion() here for the performance
  112. // because they call updateMatrixWorld( true ) inside.
  113. link.matrixWorld.decompose( _linkPos, _invLinkQ, _linkScale );
  114. _invLinkQ.invert();
  115. _effectorPos.setFromMatrixPosition( effector.matrixWorld );
  116. // work in link world
  117. _effectorVec.subVectors( _effectorPos, _linkPos );
  118. _effectorVec.applyQuaternion( _invLinkQ );
  119. _effectorVec.normalize();
  120. _targetVec.subVectors( _targetPos, _linkPos );
  121. _targetVec.applyQuaternion( _invLinkQ );
  122. _targetVec.normalize();
  123. let angle = _targetVec.dot( _effectorVec );
  124. if ( angle > 1.0 ) {
  125. angle = 1.0;
  126. } else if ( angle < - 1.0 ) {
  127. angle = - 1.0;
  128. }
  129. angle = math.acos( angle );
  130. // skip if changing angle is too small to prevent vibration of bone
  131. if ( angle < 1e-5 ) continue;
  132. if ( ik.minAngle !== undefined && angle < ik.minAngle ) {
  133. angle = ik.minAngle;
  134. }
  135. if ( ik.maxAngle !== undefined && angle > ik.maxAngle ) {
  136. angle = ik.maxAngle;
  137. }
  138. _axis.crossVectors( _effectorVec, _targetVec );
  139. _axis.normalize();
  140. _quaternion.setFromAxisAngle( _axis, angle );
  141. link.quaternion.multiply( _quaternion );
  142. // TODO: re-consider the limitation specification
  143. if ( limitation !== undefined ) {
  144. let c = link.quaternion.w;
  145. if ( c > 1.0 ) c = 1.0;
  146. const c2 = math.sqrt( 1 - c * c );
  147. link.quaternion.set( limitation.x * c2,
  148. limitation.y * c2,
  149. limitation.z * c2,
  150. c );
  151. }
  152. if ( rotationMin !== undefined ) {
  153. link.rotation.setFromVector3( _vector.setFromEuler( link.rotation ).max( rotationMin ) );
  154. }
  155. if ( rotationMax !== undefined ) {
  156. link.rotation.setFromVector3( _vector.setFromEuler( link.rotation ).min( rotationMax ) );
  157. }
  158. link.updateMatrixWorld( true );
  159. rotated = true;
  160. }
  161. if ( ! rotated ) break;
  162. }
  163. if ( chainBlend < 1.0 ) {
  164. for ( let j = 0; j < links.length; j ++ ) {
  165. const linkIndex = links[ j ].index;
  166. const link = bones[ linkIndex ];
  167. this._workingQuaternion.copy( initialQuaternions[ j ] ).slerp( link.quaternion, chainBlend );
  168. link.quaternion.copy( this._workingQuaternion );
  169. link.updateMatrixWorld( true );
  170. }
  171. }
  172. return this;
  173. }
  174. /**
  175. * Creates a helper for visualizing the CCDIK.
  176. *
  177. * @param {number} sphereSize - The sphere size.
  178. * @return {CCDIKHelper} The created helper.
  179. */
  180. createHelper( sphereSize ) {
  181. return new CCDIKHelper( this.mesh, this.iks, sphereSize );
  182. }
  183. // private methods
  184. _valid() {
  185. const iks = this.iks;
  186. const bones = this.mesh.skeleton.bones;
  187. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  188. const ik = iks[ i ];
  189. const effector = bones[ ik.effector ];
  190. const links = ik.links;
  191. let link0, link1;
  192. link0 = effector;
  193. for ( let j = 0, jl = links.length; j < jl; j ++ ) {
  194. link1 = bones[ links[ j ].index ];
  195. if ( link0.parent !== link1 ) {
  196. console.warn( 'THREE.CCDIKSolver: bone ' + link0.name + ' is not the child of bone ' + link1.name );
  197. }
  198. link0 = link1;
  199. }
  200. }
  201. }
  202. }
  203. function getPosition( bone, matrixWorldInv ) {
  204. return _vector
  205. .setFromMatrixPosition( bone.matrixWorld )
  206. .applyMatrix4( matrixWorldInv );
  207. }
  208. function setPositionOfBoneToAttributeArray( array, index, bone, matrixWorldInv ) {
  209. const v = getPosition( bone, matrixWorldInv );
  210. array[ index * 3 + 0 ] = v.x;
  211. array[ index * 3 + 1 ] = v.y;
  212. array[ index * 3 + 2 ] = v.z;
  213. }
  214. /**
  215. * Helper for visualizing IK bones.
  216. *
  217. * @augments Object3D
  218. * @three_import import { CCDIKHelper } from 'three/addons/animation/CCDIKSolver.js';
  219. */
  220. class CCDIKHelper extends Object3D {
  221. /**
  222. * @param {SkinnedMesh} mesh - The skinned mesh.
  223. * @param {Array<CCDIKSolver~IK>} [iks=[]] - The IK objects.
  224. * @param {number} [sphereSize=0.25] - The sphere size.
  225. */
  226. constructor( mesh, iks = [], sphereSize = 0.25 ) {
  227. super();
  228. /**
  229. * The skinned mesh this helper refers to.
  230. *
  231. * @type {SkinnedMesh}
  232. */
  233. this.root = mesh;
  234. /**
  235. * The IK objects.
  236. *
  237. * @type {Array<CCDIKSolver~IK>}
  238. */
  239. this.iks = iks;
  240. this.matrix.copy( mesh.matrixWorld );
  241. this.matrixAutoUpdate = false;
  242. /**
  243. * The helpers sphere geometry.
  244. *
  245. * @type {SkinnedMesh}
  246. */
  247. this.sphereGeometry = new SphereGeometry( sphereSize, 16, 8 );
  248. /**
  249. * The material for the target spheres.
  250. *
  251. * @type {MeshBasicMaterial}
  252. */
  253. this.targetSphereMaterial = new MeshBasicMaterial( {
  254. color: new Color( 0xff8888 ),
  255. depthTest: false,
  256. depthWrite: false,
  257. transparent: true
  258. } );
  259. /**
  260. * The material for the effector spheres.
  261. *
  262. * @type {MeshBasicMaterial}
  263. */
  264. this.effectorSphereMaterial = new MeshBasicMaterial( {
  265. color: new Color( 0x88ff88 ),
  266. depthTest: false,
  267. depthWrite: false,
  268. transparent: true
  269. } );
  270. /**
  271. * The material for the link spheres.
  272. *
  273. * @type {MeshBasicMaterial}
  274. */
  275. this.linkSphereMaterial = new MeshBasicMaterial( {
  276. color: new Color( 0x8888ff ),
  277. depthTest: false,
  278. depthWrite: false,
  279. transparent: true
  280. } );
  281. /**
  282. * A global line material.
  283. *
  284. * @type {LineBasicMaterial}
  285. */
  286. this.lineMaterial = new LineBasicMaterial( {
  287. color: new Color( 0xff0000 ),
  288. depthTest: false,
  289. depthWrite: false,
  290. transparent: true
  291. } );
  292. this._init();
  293. }
  294. updateMatrixWorld( force ) {
  295. const mesh = this.root;
  296. if ( this.visible ) {
  297. let offset = 0;
  298. const iks = this.iks;
  299. const bones = mesh.skeleton.bones;
  300. _matrix.copy( mesh.matrixWorld ).invert();
  301. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  302. const ik = iks[ i ];
  303. const targetBone = bones[ ik.target ];
  304. const effectorBone = bones[ ik.effector ];
  305. const targetMesh = this.children[ offset ++ ];
  306. const effectorMesh = this.children[ offset ++ ];
  307. targetMesh.position.copy( getPosition( targetBone, _matrix ) );
  308. effectorMesh.position.copy( getPosition( effectorBone, _matrix ) );
  309. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  310. const link = ik.links[ j ];
  311. const linkBone = bones[ link.index ];
  312. const linkMesh = this.children[ offset ++ ];
  313. linkMesh.position.copy( getPosition( linkBone, _matrix ) );
  314. }
  315. const line = this.children[ offset ++ ];
  316. const array = line.geometry.attributes.position.array;
  317. setPositionOfBoneToAttributeArray( array, 0, targetBone, _matrix );
  318. setPositionOfBoneToAttributeArray( array, 1, effectorBone, _matrix );
  319. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  320. const link = ik.links[ j ];
  321. const linkBone = bones[ link.index ];
  322. setPositionOfBoneToAttributeArray( array, j + 2, linkBone, _matrix );
  323. }
  324. line.geometry.attributes.position.needsUpdate = true;
  325. }
  326. }
  327. this.matrix.copy( mesh.matrixWorld );
  328. super.updateMatrixWorld( force );
  329. }
  330. /**
  331. * Frees the GPU-related resources allocated by this instance.
  332. * Call this method whenever this instance is no longer used in your app.
  333. */
  334. dispose() {
  335. this.sphereGeometry.dispose();
  336. this.targetSphereMaterial.dispose();
  337. this.effectorSphereMaterial.dispose();
  338. this.linkSphereMaterial.dispose();
  339. this.lineMaterial.dispose();
  340. const children = this.children;
  341. for ( let i = 0; i < children.length; i ++ ) {
  342. const child = children[ i ];
  343. if ( child.isLine ) child.geometry.dispose();
  344. }
  345. }
  346. // private method
  347. _init() {
  348. const scope = this;
  349. const iks = this.iks;
  350. function createLineGeometry( ik ) {
  351. const geometry = new BufferGeometry();
  352. const vertices = new Float32Array( ( 2 + ik.links.length ) * 3 );
  353. geometry.setAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  354. return geometry;
  355. }
  356. function createTargetMesh() {
  357. return new Mesh( scope.sphereGeometry, scope.targetSphereMaterial );
  358. }
  359. function createEffectorMesh() {
  360. return new Mesh( scope.sphereGeometry, scope.effectorSphereMaterial );
  361. }
  362. function createLinkMesh() {
  363. return new Mesh( scope.sphereGeometry, scope.linkSphereMaterial );
  364. }
  365. function createLine( ik ) {
  366. return new Line( createLineGeometry( ik ), scope.lineMaterial );
  367. }
  368. for ( let i = 0, il = iks.length; i < il; i ++ ) {
  369. const ik = iks[ i ];
  370. this.add( createTargetMesh() );
  371. this.add( createEffectorMesh() );
  372. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  373. this.add( createLinkMesh() );
  374. }
  375. this.add( createLine( ik ) );
  376. }
  377. }
  378. }
  379. /**
  380. * This type represents IK configuration objects.
  381. *
  382. * @typedef {Object} CCDIKSolver~IK
  383. * @property {number} target - The target bone index which refers to a bone in the `Skeleton.bones` array.
  384. * @property {number} effector - The effector bone index which refers to a bone in the `Skeleton.bones` array.
  385. * @property {Array<CCDIKSolver~BoneLink>} links - An array of bone links.
  386. * @property {number} [iteration=1] - Iteration number of calculation. Smaller is faster but less precise.
  387. * @property {number} [minAngle] - Minimum rotation angle in a step in radians.
  388. * @property {number} [maxAngle] - Minimum rotation angle in a step in radians.
  389. * @property {number} [blendFactor] - The blend factor.
  390. **/
  391. /**
  392. * This type represents bone links.
  393. *
  394. * @typedef {Object} CCDIKSolver~BoneLink
  395. * @property {number} index - The index of a linked bone which refers to a bone in the `Skeleton.bones` array.
  396. * @property {number} [limitation] - Rotation axis.
  397. * @property {number} [rotationMin] - Rotation minimum limit.
  398. * @property {number} [rotationMax] - Rotation maximum limit.
  399. * @property {boolean} [enabled=true] - Whether the link is enabled or not.
  400. **/
  401. export { CCDIKSolver, CCDIKHelper };