CCDIKSolver.js 13 KB

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