Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

9311 lines
253 KiB

  1. //===== Copyright � 1996-2005, Valve Corporation, All rights reserved. ======//
  2. //
  3. // studiomdl.c: generates a studio .mdl file from a .qc script
  4. // models/<scriptname>.mdl.
  5. //
  6. // $NoKeywords: $
  7. //
  8. //===========================================================================//
  9. #pragma warning( disable : 4244 )
  10. #pragma warning( disable : 4237 )
  11. #pragma warning( disable : 4305 )
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <sys/stat.h>
  15. #include <math.h>
  16. #include <float.h>
  17. #include "cmdlib.h"
  18. #include "scriplib.h"
  19. #include "mathlib/mathlib.h"
  20. #include "studio.h"
  21. #include "studiomdl.h"
  22. #include "bone_setup.h"
  23. #include "tier1/strtools.h"
  24. #include "mathlib/vmatrix.h"
  25. #include "mdlobjects/dmeboneflexdriver.h"
  26. #include "tier1/utlspheretree.h"
  27. class CBoneRenderBounds
  28. {
  29. public:
  30. Vector m_Mins; // In bone space.
  31. Vector m_Maxs;
  32. };
  33. // this is computed once so render models and their physics hulls get translated by the same amount
  34. static Vector g_PropCenterOffset(0,0,0);
  35. //----------------------------------------------------------------------
  36. // underlay:
  37. // studiomdl : delta = new_anim * ( -1 * base_anim )
  38. // engine : result = (w * delta) * base_anim
  39. //
  40. // overlay
  41. //
  42. // studiomdl : delta = (-1 * base_anim ) * new_anim
  43. // engine : result = base_anim * (w * delta)
  44. //
  45. //----------------------------------------------------------------------
  46. void QuaternionSMAngles( float s, Quaternion const &p, Quaternion const &q, RadianEuler &angles )
  47. {
  48. Quaternion qt;
  49. QuaternionSM( s, p, q, qt );
  50. QuaternionAngles( qt, angles );
  51. }
  52. void QuaternionMAAngles( Quaternion const &p, float s, Quaternion const &q, RadianEuler &angles )
  53. {
  54. Quaternion qt;
  55. QuaternionMA( p, s, q, qt );
  56. QuaternionAngles( qt, angles );
  57. }
  58. // q = p * (-q * p)
  59. //-----------------------------------------------------------------------------
  60. // Purpose: subtract linear motion from root bone animations
  61. // fixup missing frames from looping animations
  62. // create "delta" animations
  63. //-----------------------------------------------------------------------------
  64. int g_rootIndex = 0;
  65. void buildAnimationWeights( void );
  66. void extractLinearMotion( s_animation_t *panim, int motiontype, int iStartFrame, int iEndFrame, int iSrcFrame, s_animation_t *pRefAnim, int iRefFrame /* , Vector pos, QAngle angles */ );
  67. void fixupMissingFrame( s_animation_t *panim );
  68. void realignLooping( s_animation_t *panim );
  69. void extractUnusedMotion( s_animation_t *panim );
  70. // TODO: psrc and pdest as terms are ambigious, replace with something better
  71. void setAnimationWeight( s_animation_t *panim, int index );
  72. void processMatch( s_animation_t *psrc, s_animation_t *pdest, int flags );
  73. void worldspaceBlend( s_animation_t *psrc, s_animation_t *pdest, int srcframe, int flags );
  74. void processAutoorigin( s_animation_t *psrc, s_animation_t *pdest, int flags, int srcframe, int destframe, int bone );
  75. void subtractBaseAnimations( s_animation_t *psrc, s_animation_t *pdest, int srcframe, int flags );
  76. void fixupLoopingDiscontinuities( s_animation_t *panim, int start, int end );
  77. void matchBlend( s_animation_t *pDestAnim, s_animation_t *pSrcAnimation, int iSrcFrame, int iDestFrame, int iPre, int iPost );
  78. void makeAngle( s_animation_t *panim, float angle );
  79. void fixupIKErrors( s_animation_t *panim, s_ikrule_t *pRule );
  80. void createDerivative( s_animation_t *panim, float scale );
  81. void clearAnimations( s_animation_t *panim, bool bRetainDuration = false );
  82. void counterRotateBone( s_animation_t *panim, int bone, QAngle target );
  83. void localHierarchy( s_animation_t *panim, char *pBonename, char *pParentname, int start, int peak, int tail, int end );
  84. void linearDelta( s_animation_t *psrc, s_animation_t *pdest, int srcframe, int flags );
  85. void splineDelta( s_animation_t *psrc, s_animation_t *pdest, int srcframe, int flags );
  86. void reencodeAnimation( s_animation_t *panim, int frameskip );
  87. void forceNumframes( s_animation_t *panim, int frames );
  88. void forceAnimationLoop( s_animation_t *panim );
  89. void solveBone( s_animation_t *panim, int iFrame, int iBone, matrix3x4_t* pBoneToWorld );
  90. void DumpDefineBones( void );
  91. void ClearModel (void)
  92. {
  93. }
  94. float DriverHelperRanges( int nTarget, int nStart, int nPeak, int nTail, int nEnd )
  95. {
  96. // returns a SMOOTH 0..1 scale of a target within start, peak, tail, end range values
  97. if ( nTarget <= nStart || nTarget >= nEnd )
  98. return 0;
  99. if ( nTarget >= nPeak && nTarget <= nTail )
  100. return 1;
  101. if ( nTarget > nStart && nTarget < nPeak )
  102. return clamp( smoothstep_bounds( (float)nStart, (float)nPeak, (float)nTarget ), 0, 1 );
  103. return clamp( smoothstep_bounds( (float)nEnd, (float)nTail, (float)nTarget ), 0, 1 );
  104. }
  105. void processAnimations()
  106. {
  107. int i, j;
  108. // find global root bone.
  109. if ( strlen( rootname ) )
  110. {
  111. g_rootIndex = findGlobalBone( rootname );
  112. if (g_rootIndex == -1)
  113. g_rootIndex = 0;
  114. }
  115. buildAnimationWeights( );
  116. for (i = 0; i < g_numani; i++)
  117. {
  118. s_animation_t *panim = g_panimation[i];
  119. extractUnusedMotion( panim ); // FIXME: this should be part of LinearMotion()
  120. setAnimationWeight( panim, 0 );
  121. int startframe = 0;
  122. if (panim->fudgeloop)
  123. {
  124. fixupMissingFrame( panim );
  125. }
  126. for (j = 0; j < panim->numcmds; j++)
  127. {
  128. s_animcmd_t *pcmd = &panim->cmds[j];
  129. switch( pcmd->cmd )
  130. {
  131. case CMD_WEIGHTS:
  132. setAnimationWeight( panim, pcmd->u.weightlist.index );
  133. break;
  134. case CMD_SUBTRACT:
  135. panim->flags |= STUDIO_DELTA;
  136. subtractBaseAnimations( pcmd->u.subtract.ref, panim, pcmd->u.subtract.frame, pcmd->u.subtract.flags );
  137. break;
  138. case CMD_AO:
  139. {
  140. int bone = g_rootIndex;
  141. if (pcmd->u.ao.pBonename != NULL)
  142. {
  143. bone = findGlobalBone( pcmd->u.ao.pBonename );
  144. if (bone == -1)
  145. {
  146. MdlError("unable to find bone %s to alignbone\n", pcmd->u.ao.pBonename );
  147. }
  148. }
  149. processAutoorigin( pcmd->u.ao.ref, panim, pcmd->u.ao.motiontype, pcmd->u.ao.srcframe, pcmd->u.ao.destframe, bone );
  150. }
  151. break;
  152. case CMD_MATCH:
  153. processMatch( pcmd->u.match.ref, panim, false );
  154. break;
  155. case CMD_FIXUP:
  156. fixupLoopingDiscontinuities( panim, pcmd->u.fixuploop.start, pcmd->u.fixuploop.end );
  157. break;
  158. case CMD_ANGLE:
  159. makeAngle( panim, pcmd->u.angle.angle );
  160. break;
  161. case CMD_IKFIXUP:
  162. break;
  163. case CMD_IKRULE:
  164. // processed later
  165. break;
  166. case CMD_MOTION:
  167. {
  168. extractLinearMotion(
  169. panim,
  170. pcmd->u.motion.motiontype,
  171. startframe,
  172. pcmd->u.motion.iEndFrame,
  173. pcmd->u.motion.iEndFrame,
  174. panim,
  175. startframe );
  176. startframe = pcmd->u.motion.iEndFrame;
  177. }
  178. break;
  179. case CMD_REFMOTION:
  180. {
  181. extractLinearMotion(
  182. panim,
  183. pcmd->u.motion.motiontype,
  184. startframe,
  185. pcmd->u.motion.iEndFrame,
  186. pcmd->u.motion.iSrcFrame,
  187. pcmd->u.motion.pRefAnim,
  188. pcmd->u.motion.iRefFrame );
  189. startframe = pcmd->u.motion.iEndFrame;
  190. }
  191. break;
  192. case CMD_DERIVATIVE:
  193. {
  194. createDerivative(
  195. panim,
  196. pcmd->u.derivative.scale );
  197. }
  198. break;
  199. case CMD_NOANIMATION:
  200. {
  201. clearAnimations( panim );
  202. }
  203. break;
  204. case CMD_NOANIM_KEEPDURATION:
  205. {
  206. clearAnimations( panim, true );
  207. }
  208. break;
  209. case CMD_LINEARDELTA:
  210. {
  211. panim->flags |= STUDIO_DELTA;
  212. linearDelta( panim, panim, panim->numframes - 1, pcmd->u.linear.flags );
  213. }
  214. break;
  215. case CMD_COMPRESS:
  216. {
  217. reencodeAnimation( panim, pcmd->u.compress.frames );
  218. }
  219. break;
  220. case CMD_NUMFRAMES:
  221. {
  222. forceNumframes( panim, pcmd->u.numframes.frames );
  223. }
  224. break;
  225. case CMD_COUNTERROTATE:
  226. {
  227. int bone = findGlobalBone( pcmd->u.counterrotate.pBonename );
  228. if (bone != -1)
  229. {
  230. QAngle target;
  231. if (!pcmd->u.counterrotate.bHasTarget)
  232. {
  233. matrix3x4_t rootxform;
  234. matrix3x4_t defaultBoneToWorld;
  235. AngleMatrix( panim->rotation, rootxform );
  236. ConcatTransforms( rootxform, g_bonetable[bone].boneToPose, defaultBoneToWorld );
  237. MatrixAngles( defaultBoneToWorld, target );
  238. }
  239. else
  240. {
  241. target.Init( pcmd->u.counterrotate.targetAngle[0], pcmd->u.counterrotate.targetAngle[1], pcmd->u.counterrotate.targetAngle[2] );
  242. }
  243. counterRotateBone( panim, bone, target );
  244. }
  245. else
  246. {
  247. MdlError("unable to find bone %s to counterrotate\n", pcmd->u.counterrotate.pBonename );
  248. }
  249. }
  250. break;
  251. case CMD_WORLDSPACEBLEND:
  252. worldspaceBlend( pcmd->u.world.ref, panim, pcmd->u.world.startframe, pcmd->u.world.loops );
  253. break;
  254. case CMD_MATCHBLEND:
  255. matchBlend( panim, pcmd->u.match.ref, pcmd->u.match.srcframe, pcmd->u.match.destframe, pcmd->u.match.destpre, pcmd->u.match.destpost );
  256. break;
  257. case CMD_LOCALHIERARCHY:
  258. localHierarchy( panim, pcmd->u.localhierarchy.pBonename, pcmd->u.localhierarchy.pParentname, pcmd->u.localhierarchy.start, pcmd->u.localhierarchy.peak, pcmd->u.localhierarchy.tail, pcmd->u.localhierarchy.end );
  259. // localHierarchy( panim, char *pBonename, char *pParentname, int start, int peak, int tail, int end );
  260. break;
  261. case CMD_FORCEBONEPOSROT:
  262. {
  263. int bone = findGlobalBone( pcmd->u.forceboneposrot.pBonename );
  264. if (bone != -1)
  265. {
  266. Vector vecPos = Vector( pcmd->u.forceboneposrot.pos[0], pcmd->u.forceboneposrot.pos[1], pcmd->u.forceboneposrot.pos[2] );
  267. QAngle angRot = QAngle( pcmd->u.forceboneposrot.rot[0], pcmd->u.forceboneposrot.rot[1], pcmd->u.forceboneposrot.rot[2] );
  268. matrix3x4_t matRot;
  269. AngleMatrix( angRot, matRot );
  270. for ( int i=0; i<panim->numframes; i++ )
  271. {
  272. if ( pcmd->u.forceboneposrot.bDoPos )
  273. panim->sanim[i][bone].pos = vecPos;
  274. if ( pcmd->u.forceboneposrot.bDoRot )
  275. {
  276. int nParent = g_bonetable[bone].parent;
  277. if ( nParent == -1 || pcmd->u.forceboneposrot.bRotIsLocal )
  278. {
  279. panim->sanim[i][bone].rot = RadianEuler( angRot );
  280. }
  281. else
  282. {
  283. matrix3x4_t srcBoneToWorld[MAXSTUDIOBONES];
  284. CalcBoneTransforms( panim, i, srcBoneToWorld );
  285. matrix3x4_t worldToBone;
  286. MatrixInvert( srcBoneToWorld[nParent], worldToBone );
  287. matrix3x4_t local;
  288. ConcatTransforms( worldToBone, matRot, local );
  289. RadianEuler angTemp;
  290. MatrixAngles( local, angTemp );
  291. panim->sanim[i][bone].rot = angTemp;
  292. }
  293. }
  294. }
  295. }
  296. else
  297. {
  298. MdlError("unable to find bone %s to foceboneposrot\n", pcmd->u.forceboneposrot.pBonename );
  299. }
  300. }
  301. break;
  302. case CMD_BONEDRIVER:
  303. {
  304. int bone = findGlobalBone( pcmd->u.bonedriver.pBonename );
  305. if (bone != -1)
  306. {
  307. for ( int i=0; i<panim->numframes; i++ )
  308. {
  309. float flCurrentValue = panim->sanim[i][bone].pos[pcmd->u.bonedriver.iAxis];
  310. if ( pcmd->u.bonedriver.all )
  311. {
  312. panim->sanim[i][bone].pos[pcmd->u.bonedriver.iAxis] = pcmd->u.bonedriver.value;
  313. }
  314. else
  315. {
  316. float flDriverWeightAtThisFrame = DriverHelperRanges( i, pcmd->u.bonedriver.start, pcmd->u.bonedriver.peak, pcmd->u.bonedriver.tail, pcmd->u.bonedriver.end );
  317. panim->sanim[i][bone].pos[pcmd->u.bonedriver.iAxis] = Lerp( flDriverWeightAtThisFrame, flCurrentValue, pcmd->u.bonedriver.value );
  318. }
  319. }
  320. }
  321. else
  322. {
  323. MdlError("unable to find bone %s\n", pcmd->u.bonedriver.pBonename );
  324. }
  325. }
  326. break;
  327. case CMD_REVERSE:
  328. {
  329. int iCountFrames = panim->numframes-1;
  330. for ( int i=0; i<iCountFrames/2; i++ )
  331. {
  332. for ( int n=g_numbones-1; n>=0; n-- )
  333. {
  334. Vector posTemp;
  335. RadianEuler rotTemp;
  336. VectorCopy( panim->sanim[i][n].pos, posTemp );
  337. VectorCopy( panim->sanim[i][n].rot, rotTemp );
  338. VectorCopy( panim->sanim[iCountFrames-i][n].pos, panim->sanim[i][n].pos );
  339. VectorCopy( panim->sanim[iCountFrames-i][n].rot, panim->sanim[i][n].rot );
  340. VectorCopy( posTemp, panim->sanim[iCountFrames-i][n].pos );
  341. VectorCopy( rotTemp, panim->sanim[iCountFrames-i][n].rot );
  342. }
  343. }
  344. }
  345. break;
  346. case CMD_APPENDANIM:
  347. {
  348. s_animation_t *pAppendAnimation = pcmd->u.appendanim.ref;
  349. int iPrevNumFrames = panim->numframes;
  350. forceNumframes( panim, panim->numframes + pAppendAnimation->numframes );
  351. for ( int i=iPrevNumFrames; i<panim->numframes; i++ )
  352. {
  353. for ( int n=g_numbones-1; n>=0; n-- )
  354. {
  355. VectorCopy( pAppendAnimation->sanim[i-iPrevNumFrames][n].pos, panim->sanim[i][n].pos );
  356. VectorCopy( pAppendAnimation->sanim[i-iPrevNumFrames][n].rot, panim->sanim[i][n].rot );
  357. }
  358. }
  359. }
  360. break;
  361. }
  362. }
  363. if (panim->motiontype)
  364. {
  365. int lastframe;
  366. if (!(panim->flags & STUDIO_LOOPING) )
  367. {
  368. // roll back 0.2 seconds to try to prevent popping
  369. int frames = panim->fps * panim->motionrollback;
  370. lastframe = MAX( MIN( startframe + 1, panim->numframes - 1), panim->numframes - frames - 1 );
  371. //printf("%s : %d %d (%d)\n", panim->name, startframe, lastframe, panim->numframes - 1 );
  372. }
  373. else
  374. {
  375. lastframe = panim->numframes - 1;
  376. }
  377. extractLinearMotion( panim, panim->motiontype, startframe, lastframe, panim->numframes - 1, panim, startframe );
  378. startframe = panim->numframes - 1;
  379. }
  380. realignLooping( panim );
  381. if ( !( panim->flags & STUDIO_NOFORCELOOP ) )
  382. {
  383. forceAnimationLoop( panim );
  384. }
  385. }
  386. // merge weightlists
  387. for (i = 0; i < g_sequence.Count(); i++)
  388. {
  389. int k, n;
  390. for (n = 0; n < g_numbones; n++)
  391. {
  392. g_sequence[i].weight[n] = 0.0;
  393. for (j = 0; j < g_sequence[i].groupsize[0]; j++)
  394. {
  395. for (k = 0; k < g_sequence[i].groupsize[1]; k++)
  396. {
  397. g_sequence[i].weight[n] = MAX( g_sequence[i].weight[n], g_sequence[i].panim[j][k]->weight[n] );
  398. }
  399. }
  400. }
  401. // force parent bones to non-zero weight if worldspace blend
  402. if (g_sequence[i].flags & STUDIO_WORLD)
  403. {
  404. for (n = g_numbones - 1; n >= 0; n--)
  405. {
  406. if (g_sequence[i].weight[n] && g_bonetable[n].parent != -1 && g_sequence[i].weight[g_bonetable[n].parent] == 0.0)
  407. {
  408. g_sequence[i].weight[g_bonetable[n].parent] = 1.0;
  409. // printf("%s : %d %d\n", g_sequence[i].name, n, g_bonetable[n].parent );
  410. }
  411. for (j = 0; j < g_sequence[i].groupsize[0]; j++)
  412. {
  413. for (k = 0; k < g_sequence[i].groupsize[1]; k++)
  414. {
  415. if (g_sequence[i].panim[j][k]->weight[n] && g_bonetable[n].parent != -1 && g_sequence[i].panim[j][k]->weight[g_bonetable[n].parent] == 0.0)
  416. {
  417. g_sequence[i].panim[j][k]->weight[g_bonetable[n].parent] = 0.001;
  418. // printf("%s : %d %d\n", g_sequence[i].panim[j][k]->name, n, g_bonetable[n].parent );
  419. }
  420. }
  421. }
  422. }
  423. }
  424. }
  425. }
  426. /*
  427. void lookupLinearMotion( s_animation_t *panim, int motiontype, int startframe, int endframe, Vector &p1, Vector &p2 )
  428. {
  429. Vector p0 = panim->sanim[startframe][g_rootIndex].pos;
  430. p2 = panim->sanim[endframe][g_rootIndex].pos[0];
  431. float fFrame = (startframe + endframe) / 2.0;
  432. int iFrame = (int)fFrame;
  433. float s = fFrame - iFrame;
  434. p1 = panim->sanim[iFrame][g_rootIndex].pos * (1 - s) + panim->sanim[iFrame+1][g_rootIndex].pos * s;
  435. }
  436. */
  437. // 0.375 * v1 + 0.125 * v2 - d2 = 0.5 * v1 + 0.5 * v2 - d3;
  438. // 0.375 * v1 - 0.5 * v1 = 0.5 * v2 - d3 - 0.125 * v2 + d2;
  439. // 0.375 * v1 - 0.5 * v1 = 0.5 * v2 - d3 - 0.125 * v2 + d2;
  440. // -0.125 * v1 = 0.375 * v2 - d3 + d2;
  441. // v1 = (0.375 * v2 - d3 + d2) / -0.125;
  442. // -3 * (0.375 * v2 - d3 + d2) + 0.125 * v2 - d2 = 0
  443. // -3 * (0.375 * v2 - d3 + d2) + 0.125 * v2 - d2 = 0
  444. // -1 * v2 + 3 * d3 - 3 * d2 - d2 = 0
  445. // v2 = 3 * d3 - 4 * d2
  446. // 0.5 * v1 + 0.5 * v2 - d3
  447. // -4 * (0.375 * v2 - d3 + d2) + 0.5 * v2 - d3 = 0
  448. // -1.5 * v2 + 4 * d3 - 4 * d2 + 0.5 * v2 - d3 = 0
  449. // v2 = 4 * d3 - 4 * d2 - d3
  450. // v2 = 3 * d3 - 4 * d2
  451. // 0.5 * v1 + 0.5 * (3 * d3 - 4 * d2) - d3 = 0
  452. // v1 + (3 * d3 - 4 * d2) - 2 * d3 = 0
  453. // v1 = -3 * d3 + 4 * d2 + 2 * d3
  454. // v1 = -1 * d3 + 4 * d2
  455. void ConvertToAnimLocal( s_animation_t *panim, Vector &pos, QAngle &angles )
  456. {
  457. matrix3x4_t bonematrix;
  458. matrix3x4_t adjmatrix;
  459. // convert explicit position/angle into animation relative values
  460. AngleMatrix( angles, pos, bonematrix );
  461. AngleMatrix( panim->rotation, panim->adjust, adjmatrix );
  462. MatrixInvert( adjmatrix, adjmatrix );
  463. ConcatTransforms( adjmatrix, bonematrix, bonematrix );
  464. MatrixAngles( bonematrix, angles, pos );
  465. // pos = pos * panim->scale;
  466. }
  467. //-----------------------------------------------------------------------------
  468. // Purpose: find the linear movement/rotation between two frames, subtract that
  469. // out of the animation and add it back on as a "piecewise movement" command
  470. // panim - current animation
  471. // motiontype - what to extract
  472. // iStartFrame - first frame to apply motion over
  473. // iEndFrame - last end frame to apply motion over
  474. // iSrcFrame - match refFrame against what frame of the current animation
  475. // pRefAnim - reference animtion
  476. // iRefFrame - frame of reference animation to match
  477. //-----------------------------------------------------------------------------
  478. void extractLinearMotion( s_animation_t *panim, int motiontype, int iStartFrame, int iEndFrame, int iSrcFrame, s_animation_t *pRefAnim, int iRefFrame /* , Vector pos, QAngle angles */ )
  479. {
  480. int j, k;
  481. matrix3x4_t adjmatrix;
  482. // Can't extract motion with only 1 frame of animation!
  483. if ( panim->numframes <= 1 )
  484. {
  485. MdlError( "Can't extract motion from sequence %s (%s). Check your " SRC_FILE_EXT " options!\n", panim->name, panim->filename );
  486. }
  487. if (panim->numpiecewisekeys >= MAXSTUDIOMOVEKEYS)
  488. {
  489. MdlError( "Too many piecewise movement keys in %s (%s)\n", panim->name, panim->filename );
  490. }
  491. if (iEndFrame > panim->numframes - 1)
  492. iEndFrame = panim->numframes - 1;
  493. if (iSrcFrame > panim->numframes - 1)
  494. iSrcFrame = panim->numframes - 1;
  495. if (iStartFrame >= iEndFrame)
  496. {
  497. MdlWarning("Motion extraction ignored, no frames remaining in %s (%s)\n", panim->name, panim->filename );
  498. return;
  499. }
  500. float fFrame = (iStartFrame + iSrcFrame) / 2.0;
  501. int iMidFrame = (int)fFrame;
  502. float s = fFrame - iMidFrame;
  503. // find rotation
  504. RadianEuler rot( 0, 0, 0 );
  505. int iRootIndex = g_rootIndex;
  506. int iCustomRootMotionBoneIndex = findGlobalBone( rootname );
  507. if ( iCustomRootMotionBoneIndex != -1 )
  508. {
  509. iRootIndex = iCustomRootMotionBoneIndex;
  510. }
  511. if (motiontype & (STUDIO_LXR | STUDIO_LYR | STUDIO_LZR))
  512. {
  513. Quaternion q0;
  514. Quaternion q1;
  515. Quaternion q2;
  516. AngleQuaternion( pRefAnim->sanim[iRefFrame][iRootIndex].rot, q0 );
  517. AngleQuaternion( panim->sanim[iMidFrame][iRootIndex].rot, q1 ); // only used for rotation checking
  518. AngleQuaternion( panim->sanim[iSrcFrame][iRootIndex].rot, q2 );
  519. Quaternion deltaQ1;
  520. QuaternionMA( q1, -1, q0, deltaQ1 );
  521. Quaternion deltaQ2;
  522. QuaternionMA( q2, -1, q0, deltaQ2 );
  523. // FIXME: this is still wrong, but it should be slightly more robust
  524. RadianEuler a3;
  525. if (motiontype & STUDIO_LXR)
  526. {
  527. Quaternion q4;
  528. q4.Init( deltaQ2.x, 0, 0, deltaQ2.w );
  529. QuaternionNormalize( q4 );
  530. QuaternionAngles( q4, a3 );
  531. rot.x = a3.x;
  532. }
  533. if (motiontype & STUDIO_LYR)
  534. {
  535. Quaternion q4;
  536. q4.Init( 0, deltaQ2.y, 0, deltaQ2.w );
  537. QuaternionNormalize( q4 );
  538. QuaternionAngles( q4, a3 );
  539. rot.y = a3.y;
  540. }
  541. if (motiontype & STUDIO_LZR)
  542. {
  543. Quaternion q4;
  544. q4.Init( 0, 0, deltaQ2.z, deltaQ2.w );
  545. QuaternionNormalize( q4 );
  546. QuaternionAngles( q4, a3 );
  547. // check for possible rotations >180 degrees by looking at the
  548. // halfway point and seeing if it's rotating a different direction
  549. // than the shortest path to the end point
  550. Quaternion q5;
  551. RadianEuler a5;
  552. q5.Init( 0, 0, deltaQ1.z, deltaQ1.w );
  553. QuaternionNormalize( q5 );
  554. QuaternionAngles( q5, a5 );
  555. if (a3.z > M_PI) a5.z -= 2*M_PI;
  556. if (a3.z < -M_PI) a5.z += 2*M_PI;
  557. if (a5.z > M_PI) a5.z -= 2*M_PI;
  558. if (a5.z < -M_PI) a5.z += 2*M_PI;
  559. if (a5.z > M_PI/4 && a3.z < 0)
  560. {
  561. a3.z += 2*M_PI;
  562. }
  563. if (a5.z < -M_PI/4 && a3.z > 0)
  564. {
  565. a3.z -= 2*M_PI;
  566. }
  567. rot.z = a3.z;
  568. }
  569. }
  570. // find movement
  571. Vector p0;
  572. AngleMatrix(rot, adjmatrix );
  573. VectorRotate( pRefAnim->sanim[iRefFrame][iRootIndex].pos, adjmatrix, p0 );
  574. Vector p2 = panim->sanim[iSrcFrame][iRootIndex].pos;
  575. Vector p1 = panim->sanim[iMidFrame][iRootIndex].pos * (1 - s) + panim->sanim[iMidFrame+1][iRootIndex].pos * s;
  576. // ConvertToAnimLocal( panim, pos, angles ); // FIXME: unused
  577. p2 = p2 - p0;
  578. p1 = p1 - p0;
  579. if (!(motiontype & STUDIO_LX)) { p2.x = 0; p1.x = 0; };
  580. if (!(motiontype & STUDIO_LY)) { p2.y = 0; p1.y = 0; };
  581. if (!(motiontype & STUDIO_LZ)) { p2.z = 0; p1.z = 0; };
  582. // printf("%s %.1f %.1f %.1f\n", g_bonetable[iRootIndex].name, p2.x, p2.y, p2.z );
  583. float d1 = p1.Length();
  584. float d2 = p2.Length();
  585. float v0 = -1 * d2 + 4 * d1;
  586. float v1 = 3 * d2 - 4 * d1;
  587. if ( g_verbose )
  588. {
  589. printf("%s : %d - %d : %.1f %.1f %.1f root: %s\n", panim->name, iStartFrame, iEndFrame, p2.x, p2.y, RAD2DEG( rot[2] ), g_bonetable[iRootIndex].name );
  590. }
  591. int numframes = iEndFrame - iStartFrame + 1;
  592. if (numframes < 1)
  593. return;
  594. float n = numframes - 1;
  595. //printf("%f %f : ", v0, v1 );
  596. if (motiontype & STUDIO_LINEAR)
  597. {
  598. v0 = v1 = p2.Length();
  599. }
  600. else if (v0 < 0.0f)
  601. {
  602. v0 = 0.0;
  603. v1 = p2.Length() * 2.0;
  604. }
  605. else if (v1 < 0.0)
  606. {
  607. v0 = p2.Length() * 2.0;
  608. v1 = 0.0;
  609. }
  610. else if ((v0+v1) > 0.01 && (fabs(v0-v1) / (v0+v1)) < 0.2)
  611. {
  612. // if they're within 10% of each other, assum no acceleration
  613. v0 = v1 = p2.Length();
  614. }
  615. //printf("%f %f\n", v0, v1 );
  616. Vector v = p2;
  617. VectorNormalize( v );
  618. Vector A, B, C;
  619. if (motiontype & STUDIO_QUADRATIC_MOTION)
  620. {
  621. SolveInverseQuadratic( 0, 0, 0.5, p1.x, 1.0, p2.x, A.x, B.x, C.x );
  622. SolveInverseQuadratic( 0, 0, 0.5, p1.y, 1.0, p2.y, A.y, B.y, C.y );
  623. SolveInverseQuadratic( 0, 0, 0.5, p1.z, 1.0, p2.z, A.z, B.z, C.z );
  624. }
  625. Vector adjpos;
  626. RadianEuler adjangle;
  627. matrix3x4_t bonematrix;
  628. for (j = 0; j < numframes; j++)
  629. {
  630. float t = (j / n);
  631. if (motiontype & STUDIO_QUADRATIC_MOTION)
  632. {
  633. adjpos.x = t * t * A.x + t * B.x + C.x;
  634. adjpos.y = t * t * A.y + t * B.y + C.y;
  635. adjpos.z = t * t * A.z + t * B.z + C.z;
  636. }
  637. else
  638. {
  639. VectorScale( v, v0 * t + 0.5 * (v1 - v0) * t * t, adjpos );
  640. }
  641. VectorScale( rot, t, adjangle );
  642. AngleMatrix( adjangle, adjpos, adjmatrix );
  643. MatrixInvert( adjmatrix, adjmatrix );
  644. for (k = 0; k < g_numbones; k++)
  645. {
  646. if (g_bonetable[k].parent == -1)
  647. {
  648. // printf(" %.1f %.1f %.1f : ", adjpos[0], adjpos[1], RAD2DEG( adjangle[2] ));
  649. // printf(" %.1f %.1f %.1f\n", adjpos[0], adjpos[1], adjpos[2] );
  650. AngleMatrix( panim->sanim[j+iStartFrame][k].rot, panim->sanim[j+iStartFrame][k].pos, bonematrix );
  651. ConcatTransforms( adjmatrix, bonematrix, bonematrix );
  652. MatrixAngles( bonematrix, panim->sanim[j+iStartFrame][k].rot, panim->sanim[j+iStartFrame][k].pos );
  653. // printf("%d : %.1f %.1f %.1f\n", j, panim->sanim[j+iStartFrame][k].pos.x, panim->sanim[j+iStartFrame][k].pos.y, RAD2DEG( panim->sanim[j+iStartFrame][k].rot.z ) );
  654. }
  655. }
  656. }
  657. for (; j+iStartFrame < panim->numframes; j++)
  658. {
  659. for (k = 0; k < g_numbones; k++)
  660. {
  661. if (g_bonetable[k].parent == -1)
  662. {
  663. AngleMatrix( panim->sanim[j+iStartFrame][k].rot, panim->sanim[j+iStartFrame][k].pos, bonematrix );
  664. ConcatTransforms( adjmatrix, bonematrix, bonematrix );
  665. MatrixAngles( bonematrix, panim->sanim[j+iStartFrame][k].rot, panim->sanim[j+iStartFrame][k].pos );
  666. }
  667. }
  668. }
  669. // create piecewise motion paths
  670. s_linearmove_t *pmove = &panim->piecewisemove[panim->numpiecewisekeys++];
  671. pmove->endframe = iEndFrame;
  672. pmove->flags = motiontype;
  673. // concatinate xforms
  674. if (panim->numpiecewisekeys > 1)
  675. {
  676. AngleMatrix( adjangle, adjpos, bonematrix );
  677. AngleMatrix( pmove[-1].rot, pmove[-1].pos, adjmatrix );
  678. ConcatTransforms( adjmatrix, bonematrix, bonematrix );
  679. MatrixAngles( bonematrix, pmove[0].rot, pmove[0].pos );
  680. pmove->vector = pmove[0].pos - pmove[-1].pos;
  681. }
  682. else
  683. {
  684. VectorCopy( adjpos, pmove[0].pos );
  685. VectorCopy( adjangle, pmove[0].rot );
  686. pmove->vector = pmove[0].pos;
  687. }
  688. VectorNormalize( pmove->vector );
  689. // printf("%d : %.1f %.1f %.1f\n", iEndFrame, pmove[0].pos.x, pmove[0].pos.y, RAD2DEG( pmove[0].rot.z ) );
  690. pmove->v0 = v0;
  691. pmove->v1 = v1;
  692. }
  693. //-----------------------------------------------------------------------------
  694. // Purpose: process the "piecewise movement" commands and return where the animation
  695. // would move to on a given frame (assuming frame 0 is at the origin)
  696. //-----------------------------------------------------------------------------
  697. Vector calcPosition( s_animation_t *panim, int iFrame )
  698. {
  699. Vector vecPos;
  700. vecPos.Init();
  701. if (panim->numpiecewisekeys == 0)
  702. return vecPos;
  703. if (panim->numframes == 1)
  704. return vecPos;
  705. int iLoops = 0;
  706. while (iFrame >= (panim->numframes - 1))
  707. {
  708. iLoops++;
  709. iFrame = iFrame - (panim->numframes - 1);
  710. }
  711. float prevframe = 0.0f;
  712. for (int i = 0; i < panim->numpiecewisekeys; i++)
  713. {
  714. s_linearmove_t *pmove = &panim->piecewisemove[i];
  715. if (pmove->endframe >= iFrame)
  716. {
  717. float f = (iFrame - prevframe) / (pmove->endframe - prevframe);
  718. float d = pmove->v0 * f + 0.5 * (pmove->v1 - pmove->v0) * f * f;
  719. vecPos = vecPos + d * pmove->vector;
  720. if (iLoops != 0)
  721. {
  722. s_linearmove_t *pmove = &panim->piecewisemove[panim->numpiecewisekeys - 1];
  723. vecPos = vecPos + iLoops * pmove->pos;
  724. }
  725. return vecPos;
  726. }
  727. else
  728. {
  729. prevframe = pmove->endframe;
  730. vecPos = pmove->pos;
  731. }
  732. }
  733. return vecPos;
  734. }
  735. //-----------------------------------------------------------------------------
  736. // Purpose: calculate how far an animation travels between two frames
  737. //-----------------------------------------------------------------------------
  738. Vector calcMovement( s_animation_t *panim, int iFrom, int iTo )
  739. {
  740. Vector p1 = calcPosition( panim, iFrom );
  741. Vector p2 = calcPosition( panim, iTo );
  742. return p2 - p1;
  743. }
  744. #if 0
  745. // FIXME: add in correct motion!!!
  746. int iFrame = pRule->peak - pRule->start - k;
  747. if (pRule->start + k > panim->numframes - 1)
  748. {
  749. iFrame = iFrame + 1;
  750. }
  751. Vector pos = footfall;
  752. if (panim->numframes > 1)
  753. pos = pos + panim->piecewisemove[0].pos * (iFrame) / (panim->numframes - 1.0f);
  754. #endif
  755. //-----------------------------------------------------------------------------
  756. // Purpose: try to calculate a "missing" frame of animation, i.e the overlapping frame
  757. //-----------------------------------------------------------------------------
  758. void fixupMissingFrame( s_animation_t *panim )
  759. {
  760. // the animations DIDN'T have the end frame the same as the start frame, so fudge it
  761. int size = g_numbones * sizeof( s_bone_t );
  762. int j = panim->numframes;
  763. float scale = 1 / (j - 1.0f);
  764. panim->sanim[j] = (s_bone_t *)calloc( 1, size );
  765. Vector deltapos;
  766. for (int k = 0; k < g_numbones; k++)
  767. {
  768. VectorSubtract( panim->sanim[j-1][k].pos, panim->sanim[0][k].pos, deltapos );
  769. VectorMA( panim->sanim[j-1][k].pos, scale, deltapos, panim->sanim[j][k].pos );
  770. VectorCopy( panim->sanim[0][k].rot, panim->sanim[j][k].rot );
  771. }
  772. panim->numframes = j + 1;
  773. }
  774. //-----------------------------------------------------------------------------
  775. // Purpose: shift the frames of the animation so that it starts on the desired frame
  776. //-----------------------------------------------------------------------------
  777. void realignLooping( s_animation_t *panim )
  778. {
  779. int j, k;
  780. // realign looping animations
  781. if (panim->numframes > 1 && ( panim->looprestart != 0 || panim->looprestartpercent != 0 ) )
  782. {
  783. if ( panim->looprestartpercent != 0 )
  784. {
  785. panim->looprestart = (int)((panim->looprestartpercent / 100.0f) * (float)panim->numframes);
  786. }
  787. if ( panim->looprestart < 0 )
  788. {
  789. panim->looprestart += panim->numframes;
  790. }
  791. if ( panim->looprestart >= panim->numframes )
  792. {
  793. panim->looprestart -= panim->numframes;
  794. }
  795. if ( panim->looprestart < 0 || panim->looprestart >= panim->numframes )
  796. {
  797. MdlError( "loopstart (%d) out of range for animation %s (%d)", panim->looprestart, panim->name, panim->numframes );
  798. }
  799. for (k = 0; k < g_numbones; k++)
  800. {
  801. int n;
  802. Vector shiftpos[MAXSTUDIOANIMFRAMES];
  803. RadianEuler shiftrot[MAXSTUDIOANIMFRAMES];
  804. // printf("%f %f %f\n", motion[0], motion[1], motion[2] );
  805. for (j = 0; j < panim->numframes - 1; j++)
  806. {
  807. n = (j + panim->looprestart) % (panim->numframes - 1);
  808. VectorCopy( panim->sanim[n][k].pos, shiftpos[j] );
  809. VectorCopy( panim->sanim[n][k].rot, shiftrot[j] );
  810. }
  811. n = panim->looprestart;
  812. j = panim->numframes - 1;
  813. VectorCopy( panim->sanim[n][k].pos, shiftpos[j] );
  814. VectorCopy( panim->sanim[n][k].rot, shiftrot[j] );
  815. for (j = 0; j < panim->numframes; j++)
  816. {
  817. VectorCopy( shiftpos[j], panim->sanim[j][k].pos );
  818. VectorCopy( shiftrot[j], panim->sanim[j][k].rot );
  819. }
  820. }
  821. }
  822. }
  823. void extractUnusedMotion( s_animation_t *panim )
  824. {
  825. int j, k;
  826. int type = panim->motiontype;
  827. for (k = 0; k < g_numbones; k++)
  828. {
  829. if (g_bonetable[k].parent == -1)
  830. {
  831. float motion[6];
  832. motion[0] = panim->sanim[0][k].pos[0];
  833. motion[1] = panim->sanim[0][k].pos[1];
  834. motion[2] = panim->sanim[0][k].pos[2];
  835. motion[3] = panim->sanim[0][k].rot[0];
  836. motion[4] = panim->sanim[0][k].rot[1];
  837. motion[5] = panim->sanim[0][k].rot[2];
  838. for (j = 0; j < panim->numframes; j++)
  839. {
  840. if (type & STUDIO_X)
  841. panim->sanim[j][k].pos[0] = motion[0];
  842. if (type & STUDIO_Y)
  843. panim->sanim[j][k].pos[1] = motion[1];
  844. if (type & STUDIO_Z)
  845. panim->sanim[j][k].pos[2] = motion[2];
  846. if (type & STUDIO_XR)
  847. panim->sanim[j][k].rot[0] = motion[3];
  848. if (type & STUDIO_YR)
  849. panim->sanim[j][k].rot[1] = motion[4];
  850. if (type & STUDIO_ZR)
  851. panim->sanim[j][k].rot[2] = motion[5];
  852. }
  853. }
  854. }
  855. }
  856. //-----------------------------------------------------------------------------
  857. // Purpose: find the difference between the src and dest animations, then add that
  858. // difference to all the frames of the dest animation.
  859. //-----------------------------------------------------------------------------
  860. void processMatch( s_animation_t *psrc, s_animation_t *pdest, int flags )
  861. {
  862. int j, k;
  863. // process "match"
  864. Vector delta_pos[MAXSTUDIOSRCBONES];
  865. Quaternion delta_q[MAXSTUDIOSRCBONES];
  866. for (k = 0; k < g_numbones; k++)
  867. {
  868. if (flags)
  869. VectorSubtract( psrc->sanim[0][k].pos, pdest->sanim[0][k].pos, delta_pos[k] );
  870. QuaternionSM( -1, Quaternion( pdest->sanim[0][k].rot ), Quaternion( psrc->sanim[0][k].rot ), delta_q[k] );
  871. }
  872. // printf("%.2f %.2f %.2f\n", adj.x, adj.y, adj.z );
  873. for (j = 0; j < pdest->numframes; j++)
  874. {
  875. for (k = 0; k < g_numbones; k++)
  876. {
  877. if (pdest->weight[k] > 0)
  878. {
  879. if (flags)
  880. VectorAdd( pdest->sanim[j][k].pos, delta_pos[k], pdest->sanim[j][k].pos );
  881. QuaternionMAAngles( Quaternion( pdest->sanim[j][k].rot ), 1.0, delta_q[k], pdest->sanim[j][k].rot );
  882. }
  883. }
  884. }
  885. }
  886. //-----------------------------------------------------------------------------
  887. // Purpose: blend the psrc animation overtop the pdest animation, but blend the
  888. // quaternions in world space instead of parent bone space.
  889. // Also, blend bone lengths, but only for non root animations.
  890. //-----------------------------------------------------------------------------
  891. void worldspaceBlend( s_animation_t *psrc, s_animation_t *pdest, int srcframe, int flags )
  892. {
  893. int j, k, n;
  894. // process "match"
  895. Quaternion srcQ[MAXSTUDIOSRCBONES];
  896. Vector srcPos[MAXSTUDIOSRCBONES];
  897. Vector tmp;
  898. matrix3x4_t srcBoneToWorld[MAXSTUDIOBONES];
  899. matrix3x4_t destBoneToWorld[MAXSTUDIOBONES];
  900. if (!flags)
  901. {
  902. CalcBoneTransforms( psrc, srcframe, srcBoneToWorld );
  903. for (k = 0; k < g_numbones; k++)
  904. {
  905. MatrixAngles( srcBoneToWorld[k], srcQ[k], tmp );
  906. srcPos[k] = psrc->sanim[srcframe][k].pos;
  907. }
  908. }
  909. Quaternion targetQ, destQ;
  910. // printf("%.2f %.2f %.2f\n", adj.x, adj.y, adj.z );
  911. for (j = 0; j < pdest->numframes; j++)
  912. {
  913. if (flags)
  914. {
  915. // pull from a looping source
  916. float flCycle = (float)j / (pdest->numframes - 1);
  917. flCycle += (float)srcframe / (psrc->numframes - 1);
  918. CalcBoneTransformsCycle( psrc, psrc, flCycle, srcBoneToWorld );
  919. for (k = 0; k < g_numbones; k++)
  920. {
  921. MatrixAngles( srcBoneToWorld[k], srcQ[k], tmp );
  922. n = g_bonetable[k].parent;
  923. if (n == -1)
  924. {
  925. MatrixPosition( srcBoneToWorld[k], srcPos[k] );
  926. }
  927. else
  928. {
  929. matrix3x4_t worldToBone;
  930. MatrixInvert( srcBoneToWorld[n], worldToBone );
  931. matrix3x4_t local;
  932. ConcatTransforms( worldToBone, srcBoneToWorld[k], local );
  933. MatrixPosition( local, srcPos[k] );
  934. }
  935. }
  936. }
  937. CalcBoneTransforms( pdest, j, destBoneToWorld );
  938. for (k = 0; k < g_numbones; k++)
  939. {
  940. if (pdest->weight[k] > 0)
  941. {
  942. // blend the boneToWorld transforms in world space
  943. MatrixAngles( destBoneToWorld[k], destQ, tmp );
  944. QuaternionSlerp( destQ, srcQ[k], pdest->weight[k], targetQ );
  945. AngleMatrix( RadianEuler( targetQ ), tmp, destBoneToWorld[k] );
  946. }
  947. // back solve
  948. n = g_bonetable[k].parent;
  949. if (n == -1)
  950. {
  951. MatrixAngles( destBoneToWorld[k], pdest->sanim[j][k].rot, tmp );
  952. // FIXME: it's not clear if this should blend position or not....it'd be
  953. // better if weight lists could do quat and pos independently.
  954. }
  955. else
  956. {
  957. matrix3x4_t worldToBone;
  958. MatrixInvert( destBoneToWorld[n], worldToBone );
  959. matrix3x4_t local;
  960. ConcatTransforms( worldToBone, destBoneToWorld[k], local );
  961. MatrixAngles( local, pdest->sanim[j][k].rot, tmp );
  962. // blend bone lengths (local space)
  963. pdest->sanim[j][k].pos = Lerp( pdest->posweight[k], pdest->sanim[j][k].pos, srcPos[k] );
  964. }
  965. }
  966. }
  967. }
  968. //-----------------------------------------------------------------------------
  969. // Purpose: match one animations position/orientation to another animations position/orientation
  970. //-----------------------------------------------------------------------------
  971. void processAutoorigin( s_animation_t *psrc, s_animation_t *pdest, int motiontype, int srcframe, int destframe, int bone )
  972. {
  973. int j, k;
  974. matrix3x4_t adjmatrix;
  975. matrix3x4_t srcBoneToWorld[MAXSTUDIOBONES];
  976. matrix3x4_t destBoneToWorld[MAXSTUDIOBONES];
  977. CalcBoneTransforms( psrc, srcframe, srcBoneToWorld );
  978. CalcBoneTransforms( pdest, destframe, destBoneToWorld );
  979. // find rotation
  980. RadianEuler rot( 0, 0, 0 );
  981. Quaternion q0;
  982. Quaternion q2;
  983. Vector srcPos;
  984. Vector destPos;
  985. MatrixAngles( srcBoneToWorld[bone], q0, srcPos );
  986. MatrixAngles( destBoneToWorld[bone], q2, destPos );
  987. if (motiontype & (STUDIO_LXR | STUDIO_LYR | STUDIO_LZR | STUDIO_XR | STUDIO_YR | STUDIO_ZR))
  988. {
  989. Quaternion deltaQ2;
  990. QuaternionMA( q2, -1, q0, deltaQ2 );
  991. RadianEuler a3;
  992. if (motiontype & (STUDIO_LXR | STUDIO_XR))
  993. {
  994. Quaternion q4;
  995. q4.Init( deltaQ2.x, 0, 0, deltaQ2.w );
  996. QuaternionNormalize( q4 );
  997. QuaternionAngles( q4, a3 );
  998. rot.x = a3.x;
  999. }
  1000. if (motiontype & (STUDIO_LYR | STUDIO_YR))
  1001. {
  1002. Quaternion q4;
  1003. q4.Init( 0, deltaQ2.y, 0, deltaQ2.w );
  1004. QuaternionNormalize( q4 );
  1005. QuaternionAngles( q4, a3 );
  1006. rot.y = a3.y;
  1007. }
  1008. if (motiontype & (STUDIO_LZR | STUDIO_ZR))
  1009. {
  1010. Quaternion q4;
  1011. q4.Init( 0, 0, deltaQ2.z, deltaQ2.w );
  1012. QuaternionNormalize( q4 );
  1013. QuaternionAngles( q4, a3 );
  1014. rot.z = a3.z;
  1015. }
  1016. if ((motiontype & STUDIO_XR) && (motiontype & STUDIO_YR) && (motiontype & STUDIO_ZR))
  1017. {
  1018. QuaternionAngles( deltaQ2, rot );
  1019. }
  1020. }
  1021. // find movement
  1022. Vector p0 = srcPos;
  1023. Vector p2;
  1024. AngleMatrix(rot, adjmatrix );
  1025. MatrixInvert( adjmatrix, adjmatrix );
  1026. VectorRotate( destPos, adjmatrix, p2 );
  1027. Vector adj = p0 - p2;
  1028. if (!(motiontype & (STUDIO_X | STUDIO_LX)))
  1029. adj.x = 0;
  1030. if (!(motiontype & (STUDIO_Y | STUDIO_LY)))
  1031. adj.y = 0;
  1032. if (!(motiontype & (STUDIO_Z | STUDIO_LZ)))
  1033. adj.z = 0;
  1034. PositionMatrix( adj, adjmatrix );
  1035. if (g_verbose && bone != g_rootIndex)
  1036. {
  1037. printf("%s aligning to %s - %.2f %.2f %.2f\n", pdest->name, g_bonetable[bone].name, adj.x, adj.y, adj.z );
  1038. }
  1039. for (k = 0; k < g_numbones; k++)
  1040. {
  1041. if (g_bonetable[k].parent == -1)
  1042. {
  1043. for (j = 0; j < pdest->numframes; j++)
  1044. {
  1045. matrix3x4_t bonematrix;
  1046. AngleMatrix( pdest->sanim[j][k].rot, pdest->sanim[j][k].pos, bonematrix );
  1047. ConcatTransforms( adjmatrix, bonematrix, bonematrix );
  1048. MatrixAngles( bonematrix, pdest->sanim[j][k].rot, pdest->sanim[j][k].pos );
  1049. }
  1050. }
  1051. }
  1052. }
  1053. //-----------------------------------------------------------------------------
  1054. // Purpose: subtract one animaiton from animation to create an animation of the "difference"
  1055. //-----------------------------------------------------------------------------
  1056. void subtractBaseAnimations( s_animation_t *psrc, s_animation_t *pdest, int srcframe, int flags )
  1057. {
  1058. int j, k;
  1059. // create delta animations
  1060. s_bone_t src[MAXSTUDIOSRCBONES];
  1061. if (srcframe >= psrc->numframes)
  1062. {
  1063. MdlError( "subtract frame %d out of range for %s\n", srcframe, psrc->name );
  1064. }
  1065. for (k = 0; k < g_numbones; k++)
  1066. {
  1067. VectorCopy( psrc->sanim[srcframe][k].pos, src[k].pos );
  1068. VectorCopy( psrc->sanim[srcframe][k].rot, src[k].rot );
  1069. }
  1070. for (k = 0; k < g_numbones; k++)
  1071. {
  1072. for (j = 0; j < pdest->numframes; j++)
  1073. {
  1074. if (pdest->weight[k] > 0)
  1075. {
  1076. /*
  1077. printf("%2d : %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f\n",
  1078. k,
  1079. src[k].pos[0], src[k].pos[1], src[k].pos[2],
  1080. src[k].rot[0], src[k].rot[1], src[k].rot[2] );
  1081. printf(" %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f\n",
  1082. RAD2DEG(pdest->sanim[j][k].pos[0]), RAD2DEG(pdest->sanim[j][k].pos[1]), RAD2DEG(pdest->sanim[j][k].pos[2]),
  1083. RAD2DEG(pdest->sanim[j][k].rot[0]), RAD2DEG(pdest->sanim[j][k].rot[1]), RAD2DEG(pdest->sanim[j][k].rot[2]) );
  1084. */
  1085. // calc differences between two rotations
  1086. if (flags & STUDIO_POST)
  1087. {
  1088. // find pdest in src's reference frame
  1089. QuaternionSMAngles( -1, Quaternion( src[k].rot ), Quaternion( pdest->sanim[j][k].rot ), pdest->sanim[j][k].rot );
  1090. VectorSubtract( pdest->sanim[j][k].pos, src[k].pos, pdest->sanim[j][k].pos );
  1091. }
  1092. else
  1093. {
  1094. // find src in pdest's reference frame?
  1095. QuaternionMAAngles( Quaternion( pdest->sanim[j][k].rot ), -1, Quaternion( src[k].rot ), pdest->sanim[j][k].rot );
  1096. VectorSubtract( src[k].pos, pdest->sanim[j][k].pos, pdest->sanim[j][k].pos );
  1097. }
  1098. /*
  1099. printf(" %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f\n",
  1100. pdest->sanim[j][k].pos[0], pdest->sanim[j][k].pos[1], pdest->sanim[j][k].pos[2],
  1101. RAD2DEG(pdest->sanim[j][k].rot[0]), RAD2DEG(pdest->sanim[j][k].rot[1]), RAD2DEG(pdest->sanim[j][k].rot[2]) );
  1102. */
  1103. }
  1104. }
  1105. }
  1106. #if 0
  1107. // cleanup weightlists
  1108. for (k = 0; k < g_numbones; k++)
  1109. {
  1110. panim->weight[k] = 0.0;
  1111. }
  1112. for (k = 0; k < g_numbones; k++)
  1113. {
  1114. if (g_weightlist[panim->weightlist].weight[k] > 0.0)
  1115. {
  1116. for (j = 0; j < panim->numframes; j++)
  1117. {
  1118. if (fabs(panim->sanim[j][k].pos[0]) > 0.001 ||
  1119. fabs(panim->sanim[j][k].pos[1]) > 0.001 ||
  1120. fabs(panim->sanim[j][k].pos[2]) > 0.001 ||
  1121. fabs(panim->sanim[j][k].rot[0]) > 0.001 ||
  1122. fabs(panim->sanim[j][k].rot[1]) > 0.001 ||
  1123. fabs(panim->sanim[j][k].rot[2]) > 0.001)
  1124. {
  1125. panim->weight[k] = g_weightlist[panim->weightlist].weight[k];
  1126. break;
  1127. }
  1128. }
  1129. }
  1130. }
  1131. #endif
  1132. }
  1133. //-----------------------------------------------------------------------------
  1134. // Purpose:
  1135. //-----------------------------------------------------------------------------
  1136. void QuaternionSlerp( const RadianEuler &r0, const RadianEuler &r1, float t, RadianEuler &r2 )
  1137. {
  1138. Quaternion q0, q1, q2;
  1139. AngleQuaternion( r0, q0 );
  1140. AngleQuaternion( r1, q1 );
  1141. QuaternionSlerp( q0, q1, t, q2 );
  1142. QuaternionAngles( q2, r2 );
  1143. }
  1144. //-----------------------------------------------------------------------------
  1145. // Purpose: subtract each frame running interpolation of the first frame to the last frame
  1146. //-----------------------------------------------------------------------------
  1147. void linearDelta( s_animation_t *psrc, s_animation_t *pdest, int srcframe, int flags )
  1148. {
  1149. int j, k;
  1150. // create delta animations
  1151. s_bone_t src0[MAXSTUDIOSRCBONES];
  1152. s_bone_t src1[MAXSTUDIOSRCBONES];
  1153. for (k = 0; k < g_numbones; k++)
  1154. {
  1155. VectorCopy( psrc->sanim[0][k].pos, src0[k].pos );
  1156. VectorCopy( psrc->sanim[0][k].rot, src0[k].rot );
  1157. VectorCopy( psrc->sanim[srcframe][k].pos, src1[k].pos );
  1158. VectorCopy( psrc->sanim[srcframe][k].rot, src1[k].rot );
  1159. }
  1160. if (pdest->numframes == 1)
  1161. {
  1162. MdlWarning( "%s too short for splinedelta\n", pdest->name );
  1163. }
  1164. for (k = 0; k < g_numbones; k++)
  1165. {
  1166. for (j = 0; j < pdest->numframes; j++)
  1167. {
  1168. float s = 1;
  1169. if (pdest->numframes > 1)
  1170. {
  1171. s = (float)j / (pdest->numframes - 1);
  1172. }
  1173. // make it a spline curve
  1174. if (flags & STUDIO_AL_SPLINE)
  1175. {
  1176. s = 3 * s * s - 2 * s * s * s;
  1177. }
  1178. if (pdest->weight[k] > 0)
  1179. {
  1180. /*
  1181. printf("%2d : %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f\n",
  1182. k,
  1183. src[k].pos[0], src[k].pos[1], src[k].pos[2],
  1184. src[k].rot[0], src[k].rot[1], src[k].rot[2] );
  1185. printf(" %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f\n",
  1186. RAD2DEG(pdest->sanim[j][k].pos[0]), RAD2DEG(pdest->sanim[j][k].pos[1]), RAD2DEG(pdest->sanim[j][k].pos[2]),
  1187. RAD2DEG(pdest->sanim[j][k].rot[0]), RAD2DEG(pdest->sanim[j][k].rot[1]), RAD2DEG(pdest->sanim[j][k].rot[2]) );
  1188. */
  1189. s_bone_t src;
  1190. src.pos = src0[k].pos * (1 - s) + src1[k].pos * s;
  1191. QuaternionSlerp( src0[k].rot, src1[k].rot, s, src.rot );
  1192. // calc differences between two rotations
  1193. if (flags & STUDIO_AL_POST)
  1194. {
  1195. // find pdest in src's reference frame
  1196. QuaternionSMAngles( -1, Quaternion( src.rot ), Quaternion( pdest->sanim[j][k].rot ), pdest->sanim[j][k].rot );
  1197. VectorSubtract( pdest->sanim[j][k].pos, src.pos, pdest->sanim[j][k].pos );
  1198. }
  1199. else
  1200. {
  1201. // find src in pdest's reference frame?
  1202. QuaternionMAAngles( Quaternion( pdest->sanim[j][k].rot ), -1, Quaternion( src.rot ), pdest->sanim[j][k].rot );
  1203. VectorSubtract( src.pos, pdest->sanim[j][k].pos, pdest->sanim[j][k].pos );
  1204. }
  1205. /*
  1206. printf(" %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f\n",
  1207. pdest->sanim[j][k].pos[0], pdest->sanim[j][k].pos[1], pdest->sanim[j][k].pos[2],
  1208. RAD2DEG(pdest->sanim[j][k].rot[0]), RAD2DEG(pdest->sanim[j][k].rot[1]), RAD2DEG(pdest->sanim[j][k].rot[2]) );
  1209. */
  1210. }
  1211. }
  1212. }
  1213. }
  1214. //-----------------------------------------------------------------------------
  1215. // Purpose: turn the animation into a lower fps encoded version
  1216. //-----------------------------------------------------------------------------
  1217. void reencodeAnimation( s_animation_t *panim, int frameskip )
  1218. {
  1219. int j, k, n;
  1220. n = 1;
  1221. for (j = frameskip; j < panim->numframes; j += frameskip)
  1222. {
  1223. for (k = 0; k < g_numbones; k++)
  1224. {
  1225. panim->sanim[n][k] = panim->sanim[j][k];
  1226. }
  1227. n++;
  1228. }
  1229. panim->numframes = n;
  1230. panim->fps = panim->fps / frameskip;
  1231. }
  1232. //-----------------------------------------------------------------------------
  1233. // Purpose: clip or pad the animation as nessesary to be a specified number of frames
  1234. //-----------------------------------------------------------------------------
  1235. void forceNumframes( s_animation_t *panim, int numframes )
  1236. {
  1237. int j;
  1238. int size = g_numbones * sizeof( s_bone_t );
  1239. // copy
  1240. for (j = panim->numframes; j < numframes; j++)
  1241. {
  1242. panim->sanim[j] = (s_bone_t *)calloc( 1, size );
  1243. memcpy( panim->sanim[j], panim->sanim[panim->numframes-1], size );
  1244. }
  1245. panim->numframes = numframes;
  1246. }
  1247. //-----------------------------------------------------------------------------
  1248. // Purpose: subtract each frame from the previous to calculate the animations derivative
  1249. //-----------------------------------------------------------------------------
  1250. void createDerivative( s_animation_t *panim, float scale )
  1251. {
  1252. int j, k;
  1253. s_bone_t orig[MAXSTUDIOSRCBONES];
  1254. j = panim->numframes - 1;
  1255. if (panim->flags & STUDIO_LOOPING)
  1256. {
  1257. j--;
  1258. }
  1259. for (k = 0; k < g_numbones; k++)
  1260. {
  1261. VectorCopy( panim->sanim[j][k].pos, orig[k].pos );
  1262. VectorCopy( panim->sanim[j][k].rot, orig[k].rot );
  1263. }
  1264. for (j = panim->numframes - 1; j >= 0; j--)
  1265. {
  1266. s_bone_t *psrc;
  1267. s_bone_t *pdest;
  1268. if (j - 1 >= 0)
  1269. {
  1270. psrc = panim->sanim[j-1];
  1271. }
  1272. else
  1273. {
  1274. psrc = orig;
  1275. }
  1276. pdest = panim->sanim[j];
  1277. for (k = 0; k < g_numbones; k++)
  1278. {
  1279. if (panim->weight[k] > 0)
  1280. {
  1281. /*
  1282. {
  1283. printf("%2d : %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f\n",
  1284. k,
  1285. psrc[k].pos[0], psrc[k].pos[1], psrc[k].pos[2],
  1286. RAD2DEG(psrc[k].rot[0]), RAD2DEG(psrc[k].rot[1]), RAD2DEG(psrc[k].rot[2]) );
  1287. printf(" %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f\n",
  1288. pdest[k].pos[0], pdest[k].pos[1], pdest[k].pos[2],
  1289. RAD2DEG(pdest[k].rot[0]), RAD2DEG(pdest[k].rot[1]), RAD2DEG(pdest[k].rot[2]) );
  1290. }
  1291. */
  1292. // find pdest in src's reference frame
  1293. QuaternionSMAngles( -1, Quaternion( psrc[k].rot ), Quaternion( pdest[k].rot ), pdest[k].rot );
  1294. VectorSubtract( pdest[k].pos, psrc[k].pos, pdest[k].pos );
  1295. // rescale results (not sure what basis physics system is expecting)
  1296. {
  1297. // QuaternionScale( pdest[k].rot, scale, pdest[k].rot );
  1298. Quaternion q;
  1299. AngleQuaternion( pdest[k].rot, q );
  1300. QuaternionScale( q, scale, q );
  1301. QuaternionAngles( q, pdest[k].rot );
  1302. VectorScale( pdest[k].pos, scale, pdest[k].pos );
  1303. }
  1304. /*
  1305. {
  1306. printf(" %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f\n",
  1307. pdest[k].pos[0], pdest[k].pos[1], pdest[k].pos[2],
  1308. RAD2DEG(pdest[k].rot[0]), RAD2DEG(pdest[k].rot[1]), RAD2DEG(pdest[k].rot[2]) );
  1309. }
  1310. */
  1311. }
  1312. }
  1313. }
  1314. }
  1315. //-----------------------------------------------------------------------------
  1316. // Purpose: subtract each frame from the previous to calculate the animations derivative
  1317. //-----------------------------------------------------------------------------
  1318. void clearAnimations( s_animation_t *panim, bool bRetainDuration )
  1319. {
  1320. panim->flags |= STUDIO_DELTA;
  1321. panim->flags |= STUDIO_ALLZEROS;
  1322. if ( !bRetainDuration )
  1323. {
  1324. panim->numframes = 1;
  1325. panim->startframe = 0;
  1326. panim->endframe = 1;
  1327. int k;
  1328. for (k = 0; k < g_numbones; k++)
  1329. {
  1330. panim->sanim[0][k].pos = Vector( 0, 0, 0 );
  1331. panim->sanim[0][k].rot = RadianEuler( 0, 0, 0 );
  1332. panim->weight[k] = 0.0;
  1333. panim->posweight[k] = 0.0;
  1334. }
  1335. }
  1336. else
  1337. {
  1338. // fixme: zero the bone data?
  1339. }
  1340. }
  1341. //-----------------------------------------------------------------------------
  1342. // Purpose: remove all world rotation from a bone
  1343. //-----------------------------------------------------------------------------
  1344. void counterRotateBone( s_animation_t *panim, int iBone, QAngle target )
  1345. {
  1346. matrix3x4_t boneToWorld[MAXSTUDIOBONES];
  1347. Vector pos;
  1348. matrix3x4_t defaultBoneToWorld;
  1349. int j;
  1350. AngleMatrix( target, defaultBoneToWorld );
  1351. for (j = 0; j < panim->numframes; j++)
  1352. {
  1353. CalcBoneTransforms( panim, j, boneToWorld );
  1354. MatrixPosition( boneToWorld[iBone], pos );
  1355. PositionMatrix( pos, defaultBoneToWorld );
  1356. boneToWorld[iBone] = defaultBoneToWorld;
  1357. solveBone( panim, j, iBone, boneToWorld );
  1358. }
  1359. }
  1360. //-----------------------------------------------------------------------------
  1361. // Purpose: build transforms in source space, assuming source bones
  1362. //-----------------------------------------------------------------------------
  1363. void BuildRawTransforms( const s_source_t *psource, const char *pAnimationName,
  1364. int frame, float scale, Vector const &shift, RadianEuler const &rotate, int flags, matrix3x4_t* boneToWorld )
  1365. {
  1366. int k;
  1367. Vector tmp;
  1368. Vector pos;
  1369. RadianEuler rot;
  1370. matrix3x4_t bonematrix;
  1371. matrix3x4_t rootxform;
  1372. AngleMatrix( rotate, rootxform );
  1373. const s_sourceanim_t *pSourceAnim = FindSourceAnim( psource, pAnimationName );
  1374. if ( !pSourceAnim )
  1375. {
  1376. MdlError( "Unknown animation name %s\n", pAnimationName );
  1377. return;
  1378. }
  1379. if ( flags & STUDIO_LOOPING )
  1380. {
  1381. if ( frame )
  1382. {
  1383. while ( frame < 0)
  1384. frame += pSourceAnim->numframes;
  1385. frame = frame % pSourceAnim->numframes;
  1386. }
  1387. }
  1388. else
  1389. {
  1390. frame = clamp( frame, 0, pSourceAnim->numframes - 1 );
  1391. }
  1392. // build source space local to world transforms
  1393. for (k = 0; k < psource->numbones; k++)
  1394. {
  1395. VectorScale( pSourceAnim->rawanim.Element(frame)[k].pos, scale, pos );
  1396. VectorCopy( pSourceAnim->rawanim.Element(frame)[k].rot, rot );
  1397. if ( psource->localBone[k].parent == -1 )
  1398. {
  1399. // translate
  1400. VectorSubtract( pos, shift, tmp );
  1401. // rotate
  1402. VectorRotate( tmp, rootxform, pos );
  1403. matrix3x4_t m;
  1404. AngleMatrix( rot, m );
  1405. ConcatTransforms( rootxform, m, bonematrix );
  1406. MatrixAngles( bonematrix, rot );
  1407. clip_rotations( rot );
  1408. }
  1409. AngleMatrix( rot, pos, bonematrix );
  1410. if ( psource->localBone[k].parent == -1 )
  1411. {
  1412. MatrixCopy( bonematrix, boneToWorld[k] );
  1413. }
  1414. else
  1415. {
  1416. ConcatTransforms( boneToWorld[psource->localBone[k].parent], bonematrix, boneToWorld[k] );
  1417. // ConcatTransforms( worldToBone[psource->localBone[k].parent], boneToWorld[k], bonematrix );
  1418. // B * C => A
  1419. // C <= B-1 * A
  1420. }
  1421. }
  1422. }
  1423. void BuildRawTransforms( const s_source_t *psource, const char *pAnimationName, int frame, matrix3x4_t* boneToWorld )
  1424. {
  1425. BuildRawTransforms( psource, pAnimationName, frame, 1.0f, Vector( 0, 0, 0 ), RadianEuler( 0, 0, 0 ), 0, boneToWorld );
  1426. }
  1427. //-----------------------------------------------------------------------------
  1428. // Purpose: convert source bone animation into global bone animation
  1429. //-----------------------------------------------------------------------------
  1430. void TranslateAnimations( const s_source_t *pSource, const matrix3x4_t *pSrcBoneToWorld, matrix3x4_t *pDestBoneToWorld )
  1431. {
  1432. matrix3x4_t bonematrix;
  1433. for (int k = 0; k < g_numbones; k++)
  1434. {
  1435. int q = pSource->boneGlobalToLocal[k];
  1436. if ( q == -1 )
  1437. {
  1438. // unknown bone, copy over defaults
  1439. if ( g_bonetable[k].parent >= 0 )
  1440. {
  1441. AngleMatrix( g_bonetable[k].rot, g_bonetable[k].pos, bonematrix );
  1442. ConcatTransforms( pDestBoneToWorld[g_bonetable[k].parent], bonematrix, pDestBoneToWorld[k] );
  1443. }
  1444. else
  1445. {
  1446. AngleMatrix( g_bonetable[k].rot, g_bonetable[k].pos, pDestBoneToWorld[k] );
  1447. }
  1448. }
  1449. else
  1450. {
  1451. ConcatTransforms( pSrcBoneToWorld[q], g_bonetable[k].srcRealign, pDestBoneToWorld[k] );
  1452. }
  1453. }
  1454. }
  1455. //-----------------------------------------------------------------------------
  1456. // Purpose: convert source bone animation into global bone animation
  1457. //-----------------------------------------------------------------------------
  1458. void ConvertAnimation( const s_source_t *psource, const char *pAnimationName, int frame, float scale, Vector const &shift, RadianEuler const &rotate, s_bone_t *dest )
  1459. {
  1460. int k;
  1461. matrix3x4_t srcBoneToWorld[MAXSTUDIOSRCBONES];
  1462. //matrix3x4_t srcWorldToBone[MAXSTUDIOSRCBONES];
  1463. matrix3x4_t destBoneToWorld[MAXSTUDIOSRCBONES];
  1464. matrix3x4_t destWorldToBone[MAXSTUDIOSRCBONES];
  1465. matrix3x4_t bonematrix;
  1466. BuildRawTransforms( psource, pAnimationName, frame, scale, shift, rotate, 0, srcBoneToWorld );
  1467. /*
  1468. for (k = 0; k < psource->numbones; k++)
  1469. {
  1470. MatrixInvert( srcBoneToWorld[k], srcWorldToBone[k] );
  1471. }
  1472. */
  1473. TranslateAnimations( psource, srcBoneToWorld, destBoneToWorld );
  1474. for (k = 0; k < g_numbones; k++)
  1475. {
  1476. MatrixInvert( destBoneToWorld[k], destWorldToBone[k] );
  1477. }
  1478. // convert source_space_local_to_world transforms to shared_space_local_to_world transforms
  1479. for (k = 0; k < g_numbones; k++)
  1480. {
  1481. if (g_bonetable[k].parent == -1)
  1482. {
  1483. MatrixCopy( destBoneToWorld[k], bonematrix );
  1484. }
  1485. else
  1486. {
  1487. // convert my transform into parent relative space
  1488. ConcatTransforms( destWorldToBone[g_bonetable[k].parent], destBoneToWorld[k], bonematrix );
  1489. // printf("%s : %s\n", psource->localBone[q2].name, psource->localBone[q].name );
  1490. // B * C => A
  1491. // C <= B-1 * A
  1492. }
  1493. MatrixAngles( bonematrix, dest[k].rot, dest[k].pos );
  1494. clip_rotations( dest[k].rot );
  1495. }
  1496. }
  1497. //-----------------------------------------------------------------------------
  1498. // Purpose: copy the raw animation data from the source files into the individual animations
  1499. //-----------------------------------------------------------------------------
  1500. void RemapAnimations(void)
  1501. {
  1502. int i, j;
  1503. // copy source animations
  1504. for (i = 0; i < g_numani; i++)
  1505. {
  1506. s_animation_t *panim = g_panimation[i];
  1507. s_source_t *psource = panim->source;
  1508. s_sourceanim_t *pSourceAnim = FindSourceAnim( psource, panim->animationname );
  1509. int size = g_numbones * sizeof( s_bone_t );
  1510. int n = panim->startframe - pSourceAnim->startframe;
  1511. // printf("%s %d:%d\n", g_panimation[i]->filename, g_panimation[i]->startframe, pSourceAnim->startframe );
  1512. for (j = 0; j < panim->numframes; j++)
  1513. {
  1514. panim->sanim[j] = (s_bone_t *)calloc( 1, size );
  1515. ConvertAnimation( psource, panim->animationname, n + j, panim->scale, panim->adjust, panim->rotation, panim->sanim[j] );
  1516. }
  1517. }
  1518. }
  1519. void buildAnimationWeights()
  1520. {
  1521. int i, j, k;
  1522. // rlink animation weights
  1523. for (i = 0; i < g_numweightlist; i++)
  1524. {
  1525. if (i == 0)
  1526. {
  1527. // initialize weights
  1528. for (j = 0; j < g_numbones; j++)
  1529. {
  1530. if (g_bonetable[j].parent != -1)
  1531. {
  1532. // set child bones to uninitialized
  1533. g_weightlist[i].weight[j] = -1;
  1534. }
  1535. else if (i == 0)
  1536. {
  1537. // set root bones to 1
  1538. g_weightlist[i].weight[j] = 1;
  1539. g_weightlist[i].posweight[j] = 1;
  1540. }
  1541. }
  1542. }
  1543. else
  1544. {
  1545. // initialize weights
  1546. for (j = 0; j < g_numbones; j++)
  1547. {
  1548. if (g_bonetable[j].parent != -1)
  1549. {
  1550. // set child bones to uninitialized
  1551. g_weightlist[i].weight[j] = g_weightlist[0].weight[j];
  1552. g_weightlist[i].posweight[j] = g_weightlist[0].posweight[j];
  1553. }
  1554. else
  1555. {
  1556. // set root bones to 0
  1557. g_weightlist[i].weight[j] = 0;
  1558. g_weightlist[i].posweight[j] = 0;
  1559. }
  1560. }
  1561. }
  1562. // match up weights
  1563. for (j = 0; j < g_weightlist[i].numbones; j++)
  1564. {
  1565. k = findGlobalBone( g_weightlist[i].bonename[j] );
  1566. if (k == -1)
  1567. {
  1568. MdlWarning("unknown bone reference '%s' in weightlist '%s'\n", g_weightlist[i].bonename[j], g_weightlist[i].name );
  1569. }
  1570. else
  1571. {
  1572. g_weightlist[i].weight[k] = g_weightlist[i].boneweight[j];
  1573. g_weightlist[i].posweight[k] = g_weightlist[i].boneposweight[j];
  1574. }
  1575. }
  1576. }
  1577. for (i = 0; i < g_numweightlist; i++)
  1578. {
  1579. // copy weights forward
  1580. for (j = 0; j < g_numbones; j++)
  1581. {
  1582. if (g_weightlist[i].weight[j] < 0.0)
  1583. {
  1584. if (g_bonetable[j].parent != -1)
  1585. {
  1586. g_weightlist[i].weight[j] = g_weightlist[i].weight[g_bonetable[j].parent];
  1587. g_weightlist[i].posweight[j] = g_weightlist[i].posweight[g_bonetable[j].parent];
  1588. }
  1589. }
  1590. }
  1591. }
  1592. }
  1593. void setAnimationWeight( s_animation_t *panim, int index )
  1594. {
  1595. // copy weightlists to animations
  1596. for (int k = 0; k < g_numbones; k++)
  1597. {
  1598. panim->weight[k] = g_weightlist[index].weight[k];
  1599. panim->posweight[k] = g_weightlist[index].posweight[k];
  1600. }
  1601. }
  1602. void addDeltas( s_animation_t *panim, int frame, float s, Vector delta_pos[], Quaternion delta_q[] )
  1603. {
  1604. for (int k = 0; k < g_numbones; k++)
  1605. {
  1606. if (panim->weight[k] > 0)
  1607. {
  1608. QuaternionSMAngles( s, delta_q[k], Quaternion( panim->sanim[frame][k].rot ), panim->sanim[frame][k].rot );
  1609. VectorMA( panim->sanim[frame][k].pos, s, delta_pos[k], panim->sanim[frame][k].pos );
  1610. }
  1611. }
  1612. }
  1613. //-----------------------------------------------------------------------------
  1614. // Purpose: find the difference between the overlapping frames and spread out
  1615. // the difference over multiple frames.
  1616. // start: negative number, specifies how far back from the end to start blending
  1617. // end: positive number, specifies how many frames from the beginning to blend
  1618. //-----------------------------------------------------------------------------
  1619. void fixupLoopingDiscontinuities( s_animation_t *panim, int start, int end )
  1620. {
  1621. int j, k, m, n;
  1622. // fix C0 errors on looping animations
  1623. m = panim->numframes - 1;
  1624. Vector delta_pos[MAXSTUDIOSRCBONES];
  1625. Quaternion delta_q[MAXSTUDIOSRCBONES];
  1626. // skip if there's nothing to smooth
  1627. if (m == 0)
  1628. return;
  1629. for (k = 0; k < g_numbones; k++)
  1630. {
  1631. VectorSubtract( panim->sanim[m][k].pos, panim->sanim[0][k].pos, delta_pos[k] );
  1632. QuaternionMA( Quaternion( panim->sanim[m][k].rot ), -1, Quaternion( panim->sanim[0][k].rot ), delta_q[k] );
  1633. QAngle ang;
  1634. QuaternionAngles( delta_q[k], ang );
  1635. // printf("%2d %.1f %.1f %.1f\n", k, ang.x, ang.y, ang.z );
  1636. }
  1637. // HACK: skip fixup for motion that'll be matched with linear extraction
  1638. // FIXME: remove when "global" extraction moved into normal ordered processing loop
  1639. for (k = 0; k < g_numbones; k++)
  1640. {
  1641. if (g_bonetable[k].parent == -1)
  1642. {
  1643. if (panim->motiontype & STUDIO_LX)
  1644. delta_pos[k].x = 0.0;
  1645. if (panim->motiontype & STUDIO_LY)
  1646. delta_pos[k].y = 0.0;
  1647. if (panim->motiontype & STUDIO_LZ)
  1648. delta_pos[k].z = 0.0;
  1649. // FIXME: add rotation
  1650. }
  1651. }
  1652. // make sure loop doesn't exceed animation length
  1653. if (end-start > panim->numframes)
  1654. {
  1655. end = panim->numframes + start;
  1656. if (end < 0)
  1657. {
  1658. end = 0;
  1659. start = -(panim->numframes - 1);
  1660. }
  1661. }
  1662. // FIXME: figure out S
  1663. float s = 0;
  1664. float nf = end - start;
  1665. for (j = start + 1; j <= 0; j++)
  1666. {
  1667. n = j - start;
  1668. s = (n / nf);
  1669. s = 3 * s * s - 2 * s * s * s;
  1670. // printf("%d : %d (%lf)\n", m+j, n, -s );
  1671. addDeltas( panim, m+j, -s, delta_pos, delta_q );
  1672. }
  1673. for (j = 0; j < end; j++)
  1674. {
  1675. n = end - j;
  1676. s = (n / nf);
  1677. s = 3 * s * s - 2 * s * s * s;
  1678. //printf("%d : %d (%lf)\n", j, n, s );
  1679. addDeltas( panim, j, s, delta_pos, delta_q );
  1680. }
  1681. }
  1682. void matchBlend( s_animation_t *pDestAnim, s_animation_t *pSrcAnimation, int iSrcFrame, int iDestFrame, int iPre, int iPost )
  1683. {
  1684. int j, k;
  1685. if (pDestAnim->flags & STUDIO_LOOPING)
  1686. {
  1687. iPre = MAX( iPre, -pDestAnim->numframes );
  1688. iPost = MIN( iPost, pDestAnim->numframes );
  1689. }
  1690. else
  1691. {
  1692. iPre = MAX( iPre, -iDestFrame );
  1693. iPost = MIN( iPost, pDestAnim->numframes - iDestFrame );
  1694. }
  1695. Vector delta_pos[MAXSTUDIOSRCBONES];
  1696. Quaternion delta_q[MAXSTUDIOSRCBONES];
  1697. for (k = 0; k < g_numbones; k++)
  1698. {
  1699. VectorSubtract( pSrcAnimation->sanim[iSrcFrame][k].pos, pDestAnim->sanim[iDestFrame][k].pos, delta_pos[k] );
  1700. QuaternionMA( Quaternion( pSrcAnimation->sanim[iSrcFrame][k].rot ), -1, Quaternion( pDestAnim->sanim[iDestFrame][k].rot ), delta_q[k] );
  1701. /*
  1702. QAngle ang;
  1703. QuaternionAngles( delta_q[k], ang );
  1704. printf("%2d %.1f %.1f %.1f\n", k, ang.x, ang.y, ang.z );
  1705. */
  1706. }
  1707. // HACK: skip fixup for motion that'll be matched with linear extraction
  1708. // FIXME: remove when "global" extraction moved into normal ordered processing loop
  1709. for (k = 0; k < g_numbones; k++)
  1710. {
  1711. if (g_bonetable[k].parent == -1)
  1712. {
  1713. if (pDestAnim->motiontype & STUDIO_LX)
  1714. delta_pos[k].x = 0.0;
  1715. if (pDestAnim->motiontype & STUDIO_LY)
  1716. delta_pos[k].y = 0.0;
  1717. if (pDestAnim->motiontype & STUDIO_LZ)
  1718. delta_pos[k].z = 0.0;
  1719. // FIXME: add rotation
  1720. }
  1721. }
  1722. // FIXME: figure out S
  1723. float s = 0;
  1724. for (j = iPre; j <= iPost; j++)
  1725. {
  1726. if (j < 0)
  1727. {
  1728. s = j / (float)(iPre-1);
  1729. }
  1730. else
  1731. {
  1732. s = j / (float)(iPost+1);
  1733. }
  1734. s = SimpleSpline( 1 - s );
  1735. k = iDestFrame + j;
  1736. if (k < 0)
  1737. {
  1738. k += (pDestAnim->numframes - 1);
  1739. }
  1740. else
  1741. {
  1742. k = k % (pDestAnim->numframes - 1);
  1743. }
  1744. //printf("%d : %d (%lf)\n", iDestFrame + j, k, s );
  1745. addDeltas( pDestAnim, k, s, delta_pos, delta_q );
  1746. // make sure final frame of a looping animation matches frame 0
  1747. if ((pDestAnim->flags & STUDIO_LOOPING) && k == 0)
  1748. {
  1749. addDeltas( pDestAnim, pDestAnim->numframes - 1, s, delta_pos, delta_q );
  1750. }
  1751. }
  1752. }
  1753. //-----------------------------------------------------------------------------
  1754. // Purpose: copy the first frame overtop the last frame
  1755. //-----------------------------------------------------------------------------
  1756. void forceAnimationLoop( s_animation_t *panim )
  1757. {
  1758. int k, m, n;
  1759. // force looping animations to be looping
  1760. if (panim->flags & STUDIO_LOOPING)
  1761. {
  1762. n = 0;
  1763. m = panim->numframes - 1;
  1764. for (k = 0; k < g_numbones; k++)
  1765. {
  1766. int type = panim->motiontype;
  1767. if (!(type & STUDIO_LX))
  1768. panim->sanim[m][k].pos[0] = panim->sanim[n][k].pos[0];
  1769. if (!(type & STUDIO_LY))
  1770. panim->sanim[m][k].pos[1] = panim->sanim[n][k].pos[1];
  1771. if (!(type & STUDIO_LZ))
  1772. panim->sanim[m][k].pos[2] = panim->sanim[n][k].pos[2];
  1773. if (!(type & STUDIO_LXR))
  1774. panim->sanim[m][k].rot[0] = panim->sanim[n][k].rot[0];
  1775. if (!(type & STUDIO_LYR))
  1776. panim->sanim[m][k].rot[1] = panim->sanim[n][k].rot[1];
  1777. if (!(type & STUDIO_LZR))
  1778. panim->sanim[m][k].rot[2] = panim->sanim[n][k].rot[2];
  1779. }
  1780. }
  1781. // printf("\n");
  1782. }
  1783. //-----------------------------------------------------------------------------
  1784. // Purpose: calculate an single bones animation in a different parent's reference frame
  1785. //-----------------------------------------------------------------------------
  1786. void localHierarchy( s_animation_t *panim, char *pBonename, char *pParentname, int start, int peak, int tail, int end )
  1787. {
  1788. s_localhierarchy_t *pRule;
  1789. pRule = &panim->localhierarchy[ panim->numlocalhierarchy ];
  1790. panim->numlocalhierarchy++;
  1791. pRule->start = start;
  1792. pRule->peak = peak;
  1793. pRule->tail = tail;
  1794. pRule->end = end;
  1795. if (pRule->start == 0 && pRule->peak == 0 && pRule->tail == 0 && pRule->end == 0)
  1796. {
  1797. pRule->tail = panim->numframes - 1;
  1798. pRule->end = panim->numframes - 1;
  1799. }
  1800. if (pRule->start != -1 && pRule->peak == -1 && pRule->tail == -1 && pRule->end != -1)
  1801. {
  1802. pRule->peak = (pRule->start + pRule->end) / 2;
  1803. pRule->tail = (pRule->start + pRule->end) / 2;
  1804. }
  1805. if (pRule->start != -1 && pRule->peak == -1 && pRule->tail != -1)
  1806. {
  1807. pRule->peak = (pRule->start + pRule->tail) / 2;
  1808. }
  1809. if (pRule->peak != -1 && pRule->tail == -1 && pRule->end != -1)
  1810. {
  1811. pRule->tail = (pRule->peak + pRule->end) / 2;
  1812. }
  1813. if (pRule->peak == -1)
  1814. {
  1815. pRule->start = 0;
  1816. pRule->peak = 0;
  1817. }
  1818. if (pRule->tail == -1)
  1819. {
  1820. pRule->tail = panim->numframes - 1;
  1821. pRule->end = panim->numframes - 1;
  1822. }
  1823. // check for wrapping
  1824. if (pRule->peak < pRule->start)
  1825. {
  1826. pRule->peak += panim->numframes - 1;
  1827. }
  1828. if (pRule->tail < pRule->peak)
  1829. {
  1830. pRule->tail += panim->numframes - 1;
  1831. }
  1832. if (pRule->end < pRule->tail)
  1833. {
  1834. pRule->end += panim->numframes - 1;
  1835. }
  1836. pRule->localData.numerror = pRule->end - pRule->start + 1;
  1837. if (pRule->end >= panim->numframes)
  1838. pRule->localData.numerror = pRule->localData.numerror + 2;
  1839. pRule->localData.pError = (s_streamdata_t *)calloc( pRule->localData.numerror, sizeof( s_streamdata_t ));
  1840. matrix3x4_t boneToWorld[MAXSTUDIOBONES];
  1841. matrix3x4_t worldToBone;
  1842. matrix3x4_t local;
  1843. pRule->bone = findGlobalBone( pBonename );
  1844. if (pRule->bone == -1)
  1845. {
  1846. MdlError("anim '%s' references unknown bone '%s' in localhierarchy\n", panim->name, pBonename );
  1847. }
  1848. if (strlen( pParentname ) == 0)
  1849. {
  1850. pRule->newparent = -1;
  1851. }
  1852. else
  1853. {
  1854. pRule->newparent = findGlobalBone( pParentname );
  1855. if (pRule->newparent == -1)
  1856. {
  1857. MdlError("anim '%s' references unknown bone '%s' in localhierarchy\n", panim->name, pParentname );
  1858. }
  1859. }
  1860. int k;
  1861. const char *pAnimationName = panim->animationname;
  1862. s_sourceanim_t *pSourceAnim = FindSourceAnim( panim->source, pAnimationName );
  1863. for (k = 0; k < pRule->localData.numerror; k++)
  1864. {
  1865. matrix3x4_t srcBoneToWorld[MAXSTUDIOSRCBONES];
  1866. BuildRawTransforms( panim->source, pAnimationName, k + pRule->start + panim->startframe - pSourceAnim->startframe, panim->scale, panim->adjust, panim->rotation, panim->flags, srcBoneToWorld );
  1867. TranslateAnimations( panim->source, srcBoneToWorld, boneToWorld );
  1868. if (pRule->newparent != -1)
  1869. {
  1870. MatrixInvert( boneToWorld[pRule->newparent], worldToBone );
  1871. ConcatTransforms( worldToBone, boneToWorld[pRule->bone], local );
  1872. }
  1873. else
  1874. {
  1875. MatrixCopy( boneToWorld[pRule->bone], local );
  1876. }
  1877. MatrixAngles( local, pRule->localData.pError[k].q, pRule->localData.pError[k].pos );
  1878. /*
  1879. QAngle ang;
  1880. QuaternionAngles( pRule->errorData.pError[k].q, ang );
  1881. printf("%d %.1f %.1f %.1f : %.1f %.1f %.1f\n",
  1882. k,
  1883. pRule->errorData.pError[k].pos.x, pRule->errorData.pError[k].pos.y, pRule->errorData.pError[k].pos.z,
  1884. ang.x, ang.y, ang.z );
  1885. */
  1886. }
  1887. }
  1888. //-----------------------------------------------------------------------------
  1889. // Purpose: rotate the animation so that it's moving in the specified angle
  1890. //-----------------------------------------------------------------------------
  1891. void makeAngle( s_animation_t *panim, float angle )
  1892. {
  1893. float da = 0.0f;
  1894. if (panim->numpiecewisekeys != 0)
  1895. {
  1896. // look for movement in total piecewise movement
  1897. Vector pos = panim->piecewisemove[panim->numpiecewisekeys-1].pos;
  1898. if (pos[0] != 0 || pos[1] != 0)
  1899. {
  1900. float a = atan2( pos[1], pos[0] ) * (180 / M_PI);
  1901. da = angle - a;
  1902. }
  1903. for (int i = 0; i < panim->numpiecewisekeys; i++)
  1904. {
  1905. VectorYawRotate( panim->piecewisemove[i].pos, da, panim->piecewisemove[i].pos );
  1906. VectorYawRotate( panim->piecewisemove[i].vector, da, panim->piecewisemove[i].vector );
  1907. }
  1908. }
  1909. else
  1910. {
  1911. // look for movement in root bone
  1912. Vector pos = panim->sanim[(panim->numframes - 1)][g_rootIndex].pos - panim->sanim[0][g_rootIndex].pos;
  1913. if (pos[0] != 0 || pos[1] != 0)
  1914. {
  1915. float a = atan2( pos[1], pos[0] ) * (180 / M_PI);
  1916. da = angle - a;
  1917. }
  1918. }
  1919. /*
  1920. if (da > -0.01 && da < 0.01)
  1921. return;
  1922. */
  1923. matrix3x4_t rootxform;
  1924. matrix3x4_t src;
  1925. matrix3x4_t dest;
  1926. AngleMatrix( QAngle( 0, da, 0), rootxform );
  1927. for (int j = 0; j < panim->numframes; j++)
  1928. {
  1929. for (int k = 0; k < g_numbones; k++)
  1930. {
  1931. if (g_bonetable[k].parent == -1)
  1932. {
  1933. AngleMatrix( panim->sanim[j][k].rot, panim->sanim[j][k].pos, src );
  1934. ConcatTransforms( rootxform, src, dest );
  1935. MatrixAngles( dest, panim->sanim[j][k].rot, panim->sanim[j][k].pos );
  1936. }
  1937. }
  1938. }
  1939. // FIXME: not finished
  1940. }
  1941. //-----------------------------------------------------------------------------
  1942. // Purpose: convert pBoneToWorld back into rot/pos data
  1943. //-----------------------------------------------------------------------------
  1944. void solveBone(
  1945. s_animation_t *panim,
  1946. int iFrame,
  1947. int iBone,
  1948. matrix3x4_t* pBoneToWorld
  1949. )
  1950. {
  1951. int iParent = g_bonetable[iBone].parent;
  1952. if (iParent == -1)
  1953. {
  1954. MatrixAngles( pBoneToWorld[iBone], panim->sanim[iFrame][iBone].rot, panim->sanim[iFrame][iBone].pos );
  1955. return;
  1956. }
  1957. matrix3x4_t worldToBone;
  1958. MatrixInvert( pBoneToWorld[iParent], worldToBone );
  1959. matrix3x4_t local;
  1960. ConcatTransforms( worldToBone, pBoneToWorld[iBone], local );
  1961. iFrame = iFrame % panim->numframes;
  1962. MatrixAngles( local, panim->sanim[iFrame][iBone].rot, panim->sanim[iFrame][iBone].pos );
  1963. }
  1964. //-----------------------------------------------------------------------------
  1965. // Purpose: calc the influence of a ik rule for a specific point in the animation cycle
  1966. //-----------------------------------------------------------------------------
  1967. float IKRuleWeight( s_ikrule_t *pRule, float flCycle )
  1968. {
  1969. if (pRule->end > 1.0f && flCycle < pRule->start)
  1970. {
  1971. flCycle = flCycle + 1.0f;
  1972. }
  1973. float value = 0.0f;
  1974. if (flCycle < pRule->start)
  1975. {
  1976. return 0.0f;
  1977. }
  1978. else if (flCycle < pRule->peak )
  1979. {
  1980. value = (flCycle - pRule->start) / (pRule->peak - pRule->start);
  1981. }
  1982. else if (flCycle < pRule->tail )
  1983. {
  1984. return 1.0f;
  1985. }
  1986. else if (flCycle < pRule->end )
  1987. {
  1988. value = 1.0f - ((flCycle - pRule->tail) / (pRule->end - pRule->tail));
  1989. }
  1990. return 3.0f * value * value - 2.0f * value * value * value;
  1991. }
  1992. //-----------------------------------------------------------------------------
  1993. // Purpose: Lock the ik target to a specific location in order to clean up bad animations (shouldn't be needed).
  1994. //-----------------------------------------------------------------------------
  1995. void fixupIKErrors( s_animation_t *panim, s_ikrule_t *pRule )
  1996. {
  1997. int k;
  1998. if (pRule->start == 0 && pRule->peak == 0 && pRule->tail == 0 && pRule->end == 0)
  1999. {
  2000. pRule->tail = panim->numframes - 1;
  2001. pRule->end = panim->numframes - 1;
  2002. }
  2003. // check for wrapping
  2004. if (pRule->peak < pRule->start)
  2005. {
  2006. pRule->peak += panim->numframes - 1;
  2007. }
  2008. if (pRule->tail < pRule->peak)
  2009. {
  2010. pRule->tail += panim->numframes - 1;
  2011. }
  2012. if (pRule->end < pRule->tail)
  2013. {
  2014. pRule->end += panim->numframes - 1;
  2015. }
  2016. if (pRule->contact == -1)
  2017. {
  2018. pRule->contact = pRule->peak;
  2019. }
  2020. if (panim->numframes <= 1)
  2021. return;
  2022. pRule->errorData.numerror = pRule->end - pRule->start + 1;
  2023. switch( pRule->type )
  2024. {
  2025. case IK_SELF:
  2026. #if 0
  2027. // this code has never been run.....
  2028. {
  2029. matrix3x4_t boneToWorld[MAXSTUDIOBONES];
  2030. matrix3x4_t worldToBone;
  2031. matrix3x4_t local;
  2032. Vector targetPos;
  2033. Quaternion targetQuat;
  2034. pRule->bone = findGlobalBone( pRule->bonename );
  2035. if (pRule->bone == -1)
  2036. {
  2037. MdlError("unknown bone '%s' in ikrule\n", pRule->bonename );
  2038. }
  2039. matrix3x4_t srcBoneToWorld[MAXSTUDIOSRCBONES];
  2040. BuildRawTransforms( panim->source, pRule->contact + panim->startframe - panim->source->startframe, srcBoneToWorld );
  2041. TranslateAnimations( panim->source, srcBoneToWorld, boneToWorld );
  2042. MatrixInvert( boneToWorld[pRule->bone], worldToBone );
  2043. ConcatTransforms( worldToBone, boneToWorld[g_ikchain[pRule->chain].link[2].bone], local );
  2044. MatrixAngles( local, targetQuat, targetPos );
  2045. for (k = 0; k < pRule->errorData.numerror; k++)
  2046. {
  2047. BuildRawTransforms( panim->source, k + pRule->start + panim->startframe - panim->source->startframe, srcBoneToWorld );
  2048. TranslateAnimations( panim->source, srcBoneToWorld, boneToWorld );
  2049. float cycle = (panim->numframes <= 1) ? 0 : (k + pRule->start) / (panim->numframes - 1);
  2050. float s = IKRuleWeight( pRule, cycle );
  2051. Quaternion curQuat;
  2052. Vector curPos;
  2053. // convert into rule bone space
  2054. MatrixInvert( boneToWorld[pRule->bone], worldToBone );
  2055. ConcatTransforms( worldToBone, boneToWorld[g_ikchain[pRule->chain].link[2].bone], local );
  2056. MatrixAngles( local, curQuat, curPos );
  2057. // find blended rule bone relative position
  2058. Vector rulePos = curPos * s + targetPos * (1.0 - s);
  2059. Quaternion ruleQuat;
  2060. QuaternionSlerp( curQuat, targetQuat, s, ruleQuat );
  2061. QuaternionMatrix( ruleQuat, rulePos, local );
  2062. Vector worldPos;
  2063. VectorTransform( rulePos, boneToWorld[pRule->bone], worldPos );
  2064. // printf("%d (%d) : %.1f %.1f %1.f\n", k + pRule->start, pRule->peak, pos.x, pos.y, pos.z );
  2065. Studio_SolveIK(
  2066. g_ikchain[pRule->chain].link[0].bone,
  2067. g_ikchain[pRule->chain].link[1].bone,
  2068. g_ikchain[pRule->chain].link[2].bone,
  2069. worldPos,
  2070. boneToWorld );
  2071. // slam final matrix
  2072. // FIXME: this isn't taking into account the IK may have failed
  2073. ConcatTransforms( boneToWorld[pRule->bone], local, boneToWorld[g_ikchain[pRule->chain].link[2].bone] );
  2074. solveBone( panim, k + pRule->start, g_ikchain[pRule->chain].link[0].bone, boneToWorld );
  2075. solveBone( panim, k + pRule->start, g_ikchain[pRule->chain].link[1].bone, boneToWorld );
  2076. solveBone( panim, k + pRule->start, g_ikchain[pRule->chain].link[2].bone, boneToWorld );
  2077. }
  2078. }
  2079. #endif
  2080. break;
  2081. case IK_WORLD:
  2082. case IK_GROUND:
  2083. {
  2084. matrix3x4a_t boneToWorld[MAXSTUDIOBONES];
  2085. int bone = g_ikchain[pRule->chain].link[2].bone;
  2086. CalcBoneTransforms( panim, pRule->contact, boneToWorld );
  2087. // FIXME: add in motion
  2088. Vector footfall;
  2089. MatrixGetColumn( boneToWorld[bone], 3, footfall );
  2090. //printf("%d %d %d %d (%d)\n", pRule->start, pRule->peak, pRule->tail, pRule->end, pRule->errorData.numerror );
  2091. for (k = 0; k < pRule->errorData.numerror; k++)
  2092. {
  2093. CalcBoneTransforms( panim, k + pRule->start, boneToWorld );
  2094. float cycle = (panim->numframes <= 1) ? 0 : (float)(k + pRule->start) / (panim->numframes - 1);
  2095. float s = IKRuleWeight( pRule, cycle );
  2096. s = 1.0; // FIXME - the weight rule is wrong
  2097. Vector orig;
  2098. MatrixPosition( boneToWorld[g_ikchain[pRule->chain].link[2].bone], orig );
  2099. Vector pos = (footfall + calcMovement( panim, k + pRule->start, pRule->contact )) * s + orig * (1.0 - s);
  2100. //printf("%d (%.1f:%.1f) : %.1f %.1f %1.f\n", k + pRule->start, cycle, s, pos.x, pos.y, pos.z );
  2101. Studio_SolveIK(
  2102. g_ikchain[pRule->chain].link[0].bone,
  2103. g_ikchain[pRule->chain].link[1].bone,
  2104. g_ikchain[pRule->chain].link[2].bone,
  2105. pos,
  2106. boneToWorld );
  2107. solveBone( panim, k + pRule->start, g_ikchain[pRule->chain].link[0].bone, boneToWorld );
  2108. solveBone( panim, k + pRule->start, g_ikchain[pRule->chain].link[1].bone, boneToWorld );
  2109. solveBone( panim, k + pRule->start, g_ikchain[pRule->chain].link[2].bone, boneToWorld );
  2110. }
  2111. }
  2112. }
  2113. forceAnimationLoop( panim ); // !!!
  2114. }
  2115. //-----------------------------------------------------------------------------
  2116. // Purpose: map the vertex animations to their equivalent vertex in the base animations
  2117. //-----------------------------------------------------------------------------
  2118. static void ComputeSideAndScale( const s_flexkey_t &flexKey, s_vertanim_t *pVAnim, float *pSide, float *pScale )
  2119. {
  2120. *pScale = 1.0f;
  2121. *pSide = 0.0f;
  2122. if ( flexKey.split > 0.0f )
  2123. {
  2124. if ( pVAnim->pos.x > flexKey.split )
  2125. {
  2126. *pScale = 0.0f;
  2127. }
  2128. else if ( pVAnim->pos.x < -flexKey.split )
  2129. {
  2130. *pScale = 1.0f;
  2131. }
  2132. else
  2133. {
  2134. float t = ( flexKey.split - pVAnim->pos.x ) / (2.0 * flexKey.split);
  2135. *pScale = 3.0f * t * t - 2.0f * t * t * t;
  2136. // printf( "%.1f : %.2f\n", pSrcAnim->pos.x, *pScale );
  2137. }
  2138. }
  2139. else if ( flexKey.split < 0.0f )
  2140. {
  2141. if ( pVAnim->pos.x < flexKey.split)
  2142. {
  2143. *pScale = 0.0f;
  2144. }
  2145. else if ( pVAnim->pos.x > -flexKey.split)
  2146. {
  2147. *pScale = 1.0f;
  2148. }
  2149. else
  2150. {
  2151. float t = ( flexKey.split - pVAnim->pos.x ) / ( 2.0f * flexKey.split );
  2152. *pScale = 3.0f * t * t - 2.0f * t * t * t;
  2153. // printf( "%.1f : %.2f\n", pSrcAnim->pos.x, *pScale );
  2154. }
  2155. }
  2156. if ( flexKey.flexpair != 0)
  2157. {
  2158. // paired flexes are full scale but variable side to side
  2159. *pSide = 1.0 - *pScale;
  2160. *pScale = 1.0;
  2161. }
  2162. else
  2163. {
  2164. // unpaired flexes are variable scale, one sided
  2165. *pSide = 0;
  2166. }
  2167. }
  2168. //-----------------------------------------------------------------------------
  2169. // Purpose: map the vertex animations to their equivalent vertex in the base animations
  2170. //-----------------------------------------------------------------------------
  2171. static void ComputeVertexAnimationSpeed( s_flexkey_t& flexKey )
  2172. {
  2173. // calc max total scale for deltas
  2174. float flScale = 0.0f;
  2175. for ( int m = 0; m < flexKey.numvanims; m++ )
  2176. {
  2177. float s =flexKey.vanim[m].pos.Length();
  2178. if ( s > flScale )
  2179. {
  2180. flScale = s;
  2181. }
  2182. }
  2183. if ( flScale == 0.0f )
  2184. {
  2185. flScale = 0.01f;
  2186. }
  2187. // set
  2188. for ( int m = 0; m < flexKey.numvanims; m++ )
  2189. {
  2190. if ( flexKey.decay == 0.0f )
  2191. {
  2192. flexKey.vanim[m].speed = 1.0f;
  2193. }
  2194. else
  2195. {
  2196. flexKey.vanim[m].speed = clamp( flexKey.vanim[m].pos.Length() / (flScale * flexKey.decay), 0.0f, 1.0f );
  2197. }
  2198. }
  2199. }
  2200. //-----------------------------------------------------------------------------
  2201. // Purpose: map the vertex animations to their equivalent vertex in the base animations
  2202. //-----------------------------------------------------------------------------
  2203. static void BuildVAnimFlags( s_source_t *pVSource, s_sourceanim_t *pVSourceAnim, int nCurrentFlexKey )
  2204. {
  2205. pVSourceAnim->vanim_flag = (int *)calloc( pVSource->numvertices, sizeof( int ));
  2206. for ( int n = nCurrentFlexKey; n < g_numflexkeys; n++ )
  2207. {
  2208. // make sure it's the current flex file and that it's not frame 0 (happens with eyeball stuff).
  2209. if ( g_flexkey[n].source != pVSource )
  2210. continue;
  2211. if ( Q_stricmp( g_flexkey[n].animationname, pVSourceAnim->animationname ) )
  2212. continue;
  2213. const s_sourceanim_t *pAnim = FindSourceAnim( g_flexkey[n].source, g_flexkey[n].animationname );
  2214. if ( !pAnim )
  2215. continue;
  2216. if ( pAnim->newStyleVertexAnimations != pVSourceAnim->newStyleVertexAnimations )
  2217. continue;
  2218. if ( !pAnim->newStyleVertexAnimations && g_flexkey[n].frame == 0 )
  2219. continue;
  2220. int k = g_flexkey[n].frame;
  2221. for ( int m = 0; m < pVSourceAnim->numvanims[k]; m++ )
  2222. {
  2223. pVSourceAnim->vanim_flag[ pVSourceAnim->vanim[k][m].vertex ] = 1;
  2224. }
  2225. }
  2226. }
  2227. #define MAX_VANIM_DIST 0.3873f
  2228. #define MAX_VANIM_DIST_SQR ( MAX_VANIM_DIST * MAX_VANIM_DIST )
  2229. //-----------------------------------------------------------------------------
  2230. // Purpose: Build an array indexed by model vertex which indicates which vanim vertex corresponds best to it
  2231. //-----------------------------------------------------------------------------
  2232. static void BuildModelToVAnimMap( s_source_t *pVSource, s_sourceanim_t *pVSourceAnim, s_loddata_t *pmLodSource, bool bNewVertexAnimations, int *pModelToVAnim )
  2233. {
  2234. static float imapdist[MAXSTUDIOSRCVERTS]; // distance from src vert to vanim vert
  2235. static float imapdot[MAXSTUDIOSRCVERTS]; // dot product of src norm to vanim normal
  2236. for ( int j = 0; j < pmLodSource->numvertices; j++ )
  2237. {
  2238. imapdist[j] = 1E30;
  2239. imapdot[j] = -1.0;
  2240. pModelToVAnim[j] = -1;
  2241. }
  2242. // Build a sphere tree to accelerate this search process:
  2243. CUtlSphereTree sphereTree;
  2244. int nMinLod = MIN( g_minLod, g_ScriptLODs.Count() - 1 );
  2245. for ( int k = 0; k < pmLodSource->numvertices; k++ )
  2246. {
  2247. // go ahead and skip vertices that are just going to be stripped later
  2248. // TODO: take this out when the lod clamping stuff gets moved into the LOD code instead of being a post process
  2249. s_lodvertexinfo_t &vertex = pmLodSource->vertex[k];
  2250. if ( nMinLod && !( vertex.lodFlag & (0xFFFFFF << nMinLod) ) )
  2251. continue;
  2252. Sphere_t sphere( vertex.position.x, vertex.position.y, vertex.position.z, 0 );
  2253. sphereTree.Insert( (void *)k, &sphere );
  2254. }
  2255. int nError = 0, nTests = 0, nBumps = 0;
  2256. float flErrorDist = 0.0f;
  2257. CUtlVector<void *> candidates;
  2258. float searchRadius = MAX_VANIM_DIST;
  2259. // TODO: this would be faster if we inserted the pVSource into the spheretree instead (we could avoid 'scatter' writes to imapdist[] and imapdot[] in the inner loop)
  2260. for ( int j = 0; j < pVSource->numvertices; j++ )
  2261. {
  2262. const Vector& vecModelPos = bNewVertexAnimations ? pVSource->m_GlobalVertices[j].position : pVSourceAnim->vanim[0][j].pos;
  2263. const Vector& vecModelNormal = bNewVertexAnimations ? pVSource->m_GlobalVertices[j].normal : pVSourceAnim->vanim[0][j].normal;
  2264. // Search for verts within a small radius (shrink the radius over time, to converge on a reasonable minimum search radius)
  2265. Sphere_t searchSphere( vecModelPos.x, vecModelPos.y, vecModelPos.z, searchRadius );
  2266. sphereTree.IntersectWithSphere( searchSphere, true, candidates, 0, NULL );
  2267. while( !candidates.Count() && ( searchRadius < MAX_VANIM_DIST ) )
  2268. {
  2269. searchRadius = MIN( MAX_VANIM_DIST, searchRadius*2 );
  2270. searchSphere.w = searchRadius;
  2271. sphereTree.IntersectWithSphere( searchSphere, true, candidates, 0, NULL );
  2272. nBumps++;
  2273. }
  2274. searchRadius = MAX( 0.001f*MAX_VANIM_DIST, searchRadius*0.95f );
  2275. float flMinDist = 1E30;
  2276. for ( int i = 0; i < candidates.Count(); i++ )
  2277. {
  2278. nTests++;
  2279. int index = (int)candidates[i];
  2280. s_lodvertexinfo_t &vertex = pmLodSource->vertex[index];
  2281. // TODO: Length() gives inconsistent results in release build
  2282. Vector tmp;
  2283. VectorSubtract( vertex.position, vecModelPos, tmp );
  2284. float flDist = tmp.LengthSqr();
  2285. float flDot = DotProduct( vertex.normal, vecModelNormal );
  2286. if ( flDist < flMinDist )
  2287. flMinDist = flDist;
  2288. // Smallest distance wins. In case of a distance tie, biggest dot wins. If both tie, lowest index wins.
  2289. if ( flDist < imapdist[index] || ( flDist == imapdist[index] && flDot > imapdot[index] ) )
  2290. {
  2291. imapdist[index] = flDist;
  2292. imapdot[index] = flDot;
  2293. pModelToVAnim[index] = j;
  2294. }
  2295. }
  2296. if ( flMinDist > 0.01 )
  2297. {
  2298. nError++;
  2299. flErrorDist += MIN( sqrtf( flMinDist ), MAX_VANIM_DIST ) ;
  2300. }
  2301. }
  2302. if (nError)
  2303. {
  2304. MdlWarning("unmatched vertex anims %d (%.2f)\n", nError, flErrorDist / nError );
  2305. }
  2306. }
  2307. //-----------------------------------------------------------------------------
  2308. // Purpose: Build an array indexed by model vertex which indicates which vanim vertex corresponds best to it
  2309. //-----------------------------------------------------------------------------
  2310. static void BuildVAnimMap( s_source_t *pVSource, s_sourceanim_t *pVSourceAnim, s_loddata_t *pmLodSource, const int *pModelToVAnim )
  2311. {
  2312. // indexed by vertex anim vertex index
  2313. static int *mapp[MAXSTUDIOVERTS*4];
  2314. // count number of times each vanim vert connectes to a model vert
  2315. int n = 0;
  2316. pVSourceAnim->vanim_mapcount = (int *)calloc( pVSource->numvertices, sizeof( int ) );
  2317. for ( int j = 0; j < pmLodSource->numvertices; j++ )
  2318. {
  2319. if ( pModelToVAnim[j] != -1 )
  2320. {
  2321. pVSourceAnim->vanim_mapcount[ pModelToVAnim[j] ]++;
  2322. n++;
  2323. }
  2324. }
  2325. pVSourceAnim->vanim_map = (int **)calloc( pVSource->numvertices, sizeof( int * ));
  2326. int *vmap = (int *)calloc( n, sizeof( int ) );
  2327. // build mapping arrays
  2328. for ( int j = 0; j < pVSource->numvertices; j++ )
  2329. {
  2330. if ( pVSourceAnim->vanim_mapcount[j] )
  2331. {
  2332. pVSourceAnim->vanim_map[j] = vmap;
  2333. mapp[j] = vmap;
  2334. vmap += pVSourceAnim->vanim_mapcount[j];
  2335. }
  2336. else if ( pVSourceAnim->vanim_flag[j] )
  2337. {
  2338. // printf("%d animates but no matching vertex\n", j );
  2339. }
  2340. }
  2341. for ( int j = 0; j < pmLodSource->numvertices; j++ )
  2342. {
  2343. if (pModelToVAnim[j] != -1)
  2344. {
  2345. *(mapp[ pModelToVAnim[j] ]++) = j;
  2346. }
  2347. }
  2348. }
  2349. //-----------------------------------------------------------------------------
  2350. // Computes the number of unique desination vanims, allocates space for it
  2351. //-----------------------------------------------------------------------------
  2352. static void AllocateDestVAnim( s_flexkey_t &flexKey, s_sourceanim_t *pVSourceAnim )
  2353. {
  2354. int nVAnimCount = pVSourceAnim->numvanims[ flexKey.frame ];
  2355. s_vertanim_t *pVAnim = pVSourceAnim->vanim[ flexKey.frame ];
  2356. // frame 0 is special. Always assume zero vertex animations
  2357. if ( !pVSourceAnim->newStyleVertexAnimations && flexKey.frame == 0 )
  2358. {
  2359. nVAnimCount = 0;
  2360. }
  2361. // count total possible remapped animations
  2362. int nNumDestVAnims = 0;
  2363. for ( int m = 0; m < nVAnimCount; m++)
  2364. {
  2365. nNumDestVAnims += pVSourceAnim->vanim_mapcount[ pVAnim[m].vertex ];
  2366. }
  2367. // allocate room to all possible resulting deltas
  2368. s_vertanim_t *pDestAnim = (s_vertanim_t *)calloc( nNumDestVAnims, sizeof( s_vertanim_t ) );
  2369. flexKey.vanim = pDestAnim;
  2370. flexKey.vanimtype = STUDIO_VERT_ANIM_NORMAL; // default
  2371. }
  2372. //-----------------------------------------------------------------------------
  2373. // Purpose: map the vertex animations to their equivalent vertex in the base animations
  2374. //-----------------------------------------------------------------------------
  2375. void RemapVertexAnimations(void)
  2376. {
  2377. int i, j, k;
  2378. int n, m;
  2379. s_source_t *pvsource; // vertex animation source
  2380. const char *pAnimationName;
  2381. s_sourceanim_t *pSourceAnim;
  2382. s_loddata_t *pmLodSource; // original model source
  2383. Vector tmp;
  2384. // index by vertex in targets root LOD
  2385. static int model_to_vanim_vert_imap[MAXSTUDIOSRCVERTS]; // model vert to vanim vert mapping
  2386. // for all the sources of flexes, find a mapping of vertex animations to base model.
  2387. // There can be multiple "vertices" in the base model for each animated vertex since vertices
  2388. // are duplicated along material boundaries.
  2389. for ( i = 0; i < g_numflexkeys; i++ )
  2390. {
  2391. s_source_t *pVSource = g_flexkey[i].source;
  2392. s_sourceanim_t *pVSourceAnim = FindSourceAnim( pVSource, g_flexkey[i].animationname );
  2393. // We only do old-style vertex animations
  2394. if ( pVSourceAnim->newStyleVertexAnimations )
  2395. continue;
  2396. // skip if it's already been done or if has doesn't have any animations
  2397. if ( pVSourceAnim->vanim_flag )
  2398. continue;
  2399. // flag all the vertices that animate (builds the vanim_flag field of the source anim)
  2400. BuildVAnimFlags( pVSource, pVSourceAnim, i );
  2401. s_loddata_t *pLodData = g_model[ g_flexkey[i].imodel ]->m_pLodData;
  2402. // Map vertex indices specified in the model to ones specified in the vanim data
  2403. BuildModelToVAnimMap( pVSource, pVSourceAnim, pLodData, false, model_to_vanim_vert_imap );
  2404. // Build the vanim_mapcount, vanim_map fields of the source anim
  2405. BuildVAnimMap( pVSource, pVSourceAnim, pLodData, model_to_vanim_vert_imap );
  2406. }
  2407. #if 0
  2408. s_vertanim_t *defaultanims = NULL;
  2409. if (g_defaultflexkey)
  2410. {
  2411. defaultanims = g_defaultflexkey->source->vanim[g_defaultflexkey->frame];
  2412. }
  2413. else
  2414. {
  2415. defaultanims = g_flexkey[0].source->vanim[0];
  2416. }
  2417. #endif
  2418. // reset model to be default animations
  2419. if ( g_defaultflexkey )
  2420. {
  2421. pvsource = g_defaultflexkey->source;
  2422. pAnimationName = g_defaultflexkey->animationname;
  2423. pSourceAnim = FindSourceAnim( pvsource, pAnimationName );
  2424. pmLodSource = g_model[g_defaultflexkey->imodel]->m_pLodData;
  2425. int numsrcanims = pSourceAnim->numvanims[g_defaultflexkey->frame];
  2426. s_vertanim_t *psrcanim = pSourceAnim->vanim[g_defaultflexkey->frame];
  2427. for (m = 0; m < numsrcanims; m++)
  2428. {
  2429. if ( pSourceAnim->vanim_mapcount[psrcanim->vertex]) // bah, only do it for ones that found a match!
  2430. {
  2431. for (n = 0; n < pSourceAnim->vanim_mapcount[psrcanim->vertex]; n++)
  2432. {
  2433. // copy "default" pos to original model
  2434. k = pSourceAnim->vanim_map[psrcanim->vertex][n];
  2435. VectorCopy( psrcanim->pos, pmLodSource->vertex[k].position );
  2436. VectorCopy( psrcanim->normal, pmLodSource->vertex[k].normal );
  2437. // copy "default" pos to frame 0 of vertex animation source
  2438. // FIXME: this needs to copy to all sources of vertex animation.
  2439. // FIXME: the "default" pose needs to be in each vertex animation source since it's likely that the vertices won't be numbered the same in each file.
  2440. VectorCopy( psrcanim->pos, pSourceAnim->vanim[0][psrcanim->vertex].pos );
  2441. VectorCopy( psrcanim->normal, pSourceAnim->vanim[0][psrcanim->vertex].normal );
  2442. }
  2443. }
  2444. psrcanim++;
  2445. }
  2446. }
  2447. static bool doesMove[MAXSTUDIOSRCVERTS];
  2448. int numMoved;
  2449. memset( doesMove, 0, MAXSTUDIOSRCVERTS * sizeof( bool ) );
  2450. numMoved = 0;
  2451. for (i = 0; i < g_numflexkeys; i++)
  2452. {
  2453. pvsource = g_flexkey[i].source;
  2454. pAnimationName = g_flexkey[i].animationname;
  2455. pSourceAnim = FindSourceAnim( pvsource, pAnimationName );
  2456. if ( pSourceAnim->newStyleVertexAnimations )
  2457. continue;
  2458. pmLodSource = g_model[g_flexkey[i].imodel]->m_pLodData;
  2459. // Allocate g_flexkey[i].vanim
  2460. AllocateDestVAnim( g_flexkey[i], pSourceAnim );
  2461. s_vertanim_t *psrcanim = pSourceAnim->vanim[g_flexkey[i].frame];
  2462. s_vertanim_t *pdestanim = g_flexkey[i].vanim;
  2463. // frame 0 is special. Always assume zero vertex animations
  2464. int numsrcanims = ( g_flexkey[i].frame != 0 ) ? pSourceAnim->numvanims[g_flexkey[i].frame] : 0;
  2465. for (m = 0; m < numsrcanims; m++, psrcanim++)
  2466. {
  2467. Vector delta, ndelta;
  2468. float flSide, flScale;
  2469. ComputeSideAndScale( g_flexkey[i], psrcanim, &flSide, &flScale );
  2470. // bah, only do it for ones that found a match!
  2471. if ( flScale <= 0.0f || !pSourceAnim->vanim_mapcount[psrcanim->vertex] )
  2472. continue;
  2473. j = pSourceAnim->vanim_map[psrcanim->vertex][0];
  2474. //VectorSubtract( psrcanim->pos, pSourceAnim->vanim[0][psrcanim->vertex].pos, tmp );
  2475. //VectorTransform( tmp, pmsource->bonefixup[k].im, delta );
  2476. VectorSubtract( psrcanim->pos, pSourceAnim->vanim[0][psrcanim->vertex].pos, delta );
  2477. //VectorSubtract( psrcanim->normal, pSourceAnim->vanim[0][psrcanim->vertex].normal, tmp );
  2478. //VectorTransform( tmp, pmsource->bonefixup[k].im, ndelta );
  2479. VectorSubtract( psrcanim->normal, pSourceAnim->vanim[0][psrcanim->vertex].normal, ndelta );
  2480. // if the changes are too small, skip 'em
  2481. // FIXME: the clamp needs to be paired with the other matching positions.
  2482. // currently this is set to the float16 min value. Sucky.
  2483. if (DotProduct( delta, delta ) <= (0.001f*0.001f) /* 0.0001 */ && DotProduct( ndelta, ndelta ) <= 0.001)
  2484. {
  2485. // printf("%4d %6.4f %6.4f %6.4f\n", pdestanim->vertex, delta.x, delta.y, delta.z );
  2486. continue;
  2487. }
  2488. for (n = 0; n < pSourceAnim->vanim_mapcount[psrcanim->vertex]; n++)
  2489. {
  2490. pdestanim->vertex = pSourceAnim->vanim_map[psrcanim->vertex][n];
  2491. VectorScale( delta, flScale, pdestanim->pos );
  2492. VectorScale( ndelta, flScale, pdestanim->normal );
  2493. pdestanim->side = flSide;
  2494. // count all the unique verts that actually move
  2495. if (!doesMove[pdestanim->vertex])
  2496. {
  2497. doesMove[pdestanim->vertex] = true;
  2498. numMoved++;
  2499. }
  2500. /*
  2501. printf("%4d %6.2f %6.2f %6.2f : %4d %5.2f %5.2f %5.2f\n",
  2502. pdestanim->vertex,
  2503. // pmsource->vertex[pdestanim->vertex][0], pmsource->vertex[pdestanim->vertex][1], pmsource->vertex[pdestanim->vertex][2],
  2504. modelpos[pdestanim->vertex][0], modelpos[pdestanim->vertex][1], modelpos[pdestanim->vertex][2],
  2505. psrcanim->vertex,
  2506. pdestanim->pos[0], pdestanim->pos[1], pdestanim->pos[2] );
  2507. */
  2508. g_flexkey[i].numvanims++;
  2509. pdestanim++;
  2510. }
  2511. }
  2512. ComputeVertexAnimationSpeed( g_flexkey[i] );
  2513. }
  2514. if (numMoved > MAXSTUDIOFLEXVERTS)
  2515. {
  2516. MdlError( "Too many flexed verts %d (%d)\n", numMoved, MAXSTUDIOFLEXVERTS );
  2517. }
  2518. else if (numMoved > 0 && !g_quiet)
  2519. {
  2520. printf("Max flex verts %d\n", numMoved );
  2521. }
  2522. }
  2523. //-----------------------------------------------------------------------------
  2524. // Purpose: map the vertex animations to their equivalent vertex in the base animations
  2525. //-----------------------------------------------------------------------------
  2526. static int FlexKeysSortFunc( const void *pv1, const void *pv2 )
  2527. {
  2528. const s_flexkey_t *pKey1 = (const s_flexkey_t*)pv1;
  2529. const s_flexkey_t *pKey2 = (const s_flexkey_t*)pv2;
  2530. if ( pKey1->source != pKey2->source )
  2531. return (size_t)pKey1->source - (size_t)pKey2->source;
  2532. return Q_stricmp( pKey1->animationname, pKey2->animationname );
  2533. }
  2534. static int SortFlexKeys( s_flexkey_t **ppSortedFlexKeys )
  2535. {
  2536. int nSortedFlexKeyCount = 0;
  2537. for ( int i = 0; i < g_numflexkeys; i++ )
  2538. {
  2539. s_source_t *pVSource = g_flexkey[i].source;
  2540. s_sourceanim_t *pVSourceAnim = FindSourceAnim( pVSource, g_flexkey[i].animationname );
  2541. // We only do new-style vertex animations
  2542. if ( !pVSourceAnim->newStyleVertexAnimations )
  2543. continue;
  2544. ppSortedFlexKeys[nSortedFlexKeyCount++] = &g_flexkey[i];
  2545. }
  2546. if ( nSortedFlexKeyCount > 0 )
  2547. {
  2548. qsort( ppSortedFlexKeys, nSortedFlexKeyCount, sizeof(s_flexkey_t*), FlexKeysSortFunc );
  2549. }
  2550. return nSortedFlexKeyCount;
  2551. }
  2552. static void RemapVertexAnimationsNewVersion(void)
  2553. {
  2554. // index by vertex in targets root LOD
  2555. static int model_to_vanim_vert_imap[MAXSTUDIOSRCVERTS];
  2556. // Sort flexkeys by source
  2557. s_flexkey_t **ppSortedFlexKeys = (s_flexkey_t**)_alloca( g_numflexkeys * sizeof(s_flexkey_t*) );
  2558. int nSortedFlexKeyCount = SortFlexKeys( ppSortedFlexKeys );
  2559. if ( nSortedFlexKeyCount == 0 )
  2560. return;
  2561. // for all the sources of flexes, find a mapping of vertex animations to base model.
  2562. // There can be multiple "vertices" in the base model for each animated vertex since vertices
  2563. // are duplicated along material boundaries.
  2564. s_source_t *pVLastSource = NULL;
  2565. for ( int i = 0; i < nSortedFlexKeyCount; i++ )
  2566. {
  2567. s_flexkey_t *pFlexKey = ppSortedFlexKeys[i];
  2568. s_source_t *pVSource = pFlexKey->source;
  2569. s_sourceanim_t *pVSourceAnim = FindSourceAnim( pVSource, pFlexKey->animationname );
  2570. s_loddata_t *pLodSource = g_model[ pFlexKey->imodel ]->m_pLodData;
  2571. if ( pVSource != pVLastSource )
  2572. {
  2573. // Map vertex indices specified in the model to ones specified in the vanim data
  2574. BuildModelToVAnimMap( pVSource, NULL, pLodSource, true, model_to_vanim_vert_imap );
  2575. pVLastSource = pVSource;
  2576. }
  2577. // We only do new-style vertex animations
  2578. Assert( pVSourceAnim->newStyleVertexAnimations );
  2579. // skip if it's already been done or if has doesn't have any animations
  2580. if ( pVSourceAnim->vanim_flag )
  2581. continue;
  2582. pVSourceAnim->vanim_flag = (int *)calloc( pVSource->numvertices, sizeof( int ));
  2583. // flag all the vertices that animate (builds the vanim_flag field of the source anim)
  2584. int j;
  2585. for ( j = i+1; j < nSortedFlexKeyCount; ++j )
  2586. {
  2587. if ( ( ppSortedFlexKeys[j]->source != pVSource ) ||
  2588. Q_stricmp( ppSortedFlexKeys[j]->animationname, pFlexKey->animationname ) )
  2589. break;
  2590. }
  2591. for ( ; i < j; ++i )
  2592. {
  2593. int k = ppSortedFlexKeys[i]->frame;
  2594. for ( int m = 0; m < pVSourceAnim->numvanims[k]; m++ )
  2595. {
  2596. pVSourceAnim->vanim_flag[ pVSourceAnim->vanim[k][m].vertex ] = 1;
  2597. }
  2598. }
  2599. --i;
  2600. // Build the vanim_mapcount, vanim_map fields of the source anim
  2601. BuildVAnimMap( pVSource, pVSourceAnim, pLodSource, model_to_vanim_vert_imap );
  2602. }
  2603. int nNumMoved = 0;
  2604. static bool pDoesMove[MAXSTUDIOSRCVERTS];
  2605. memset( pDoesMove, 0, MAXSTUDIOSRCVERTS * sizeof( bool ) );
  2606. for ( int i = 0; i < g_numflexkeys; i++ )
  2607. {
  2608. s_source_t *pVSource = g_flexkey[i].source;
  2609. s_sourceanim_t *pVSourceAnim = FindSourceAnim( pVSource, g_flexkey[i].animationname );
  2610. if ( !pVSourceAnim->newStyleVertexAnimations )
  2611. continue;
  2612. // Allocate g_flexkey[i].vanim
  2613. AllocateDestVAnim( g_flexkey[i], pVSourceAnim );
  2614. int nNumSrcVAnims = pVSourceAnim->numvanims[ g_flexkey[i].frame ];
  2615. s_vertanim_t *pSrcVAnim = pVSourceAnim->vanim[ g_flexkey[i].frame ];
  2616. s_vertanim_t *pDestVAnim = g_flexkey[i].vanim;
  2617. for ( int m = 0; m < nNumSrcVAnims; m++, pSrcVAnim++ )
  2618. {
  2619. // bah, only do it for ones that found a match!
  2620. if ( !pVSourceAnim->vanim_mapcount[pSrcVAnim->vertex] )
  2621. continue;
  2622. // if the changes are too small, skip 'em
  2623. // FIXME: the clamp needs to be paired with the other matching positions.
  2624. // currently this is set to the float16 min value. Sucky.
  2625. if ( DotProduct( pSrcVAnim->pos, pSrcVAnim->pos ) <= (0.001f*0.001f) /* 0.0001 */ && DotProduct( pSrcVAnim->normal, pSrcVAnim->normal ) <= 0.001f && pSrcVAnim->wrinkle <= 0.001f )
  2626. {
  2627. // printf("%4d %6.4f %6.4f %6.4f\n", pDestAnim->vertex, delta.x, delta.y, delta.z );
  2628. continue;
  2629. }
  2630. for ( int n = 0; n < pVSourceAnim->vanim_mapcount[pSrcVAnim->vertex]; n++ )
  2631. {
  2632. memcpy( pDestVAnim, pSrcVAnim, sizeof(s_vertanim_t) );
  2633. pDestVAnim->vertex = pVSourceAnim->vanim_map[pSrcVAnim->vertex][n];
  2634. if ( pDestVAnim->wrinkle != 0.0f )
  2635. {
  2636. g_flexkey[i].vanimtype = STUDIO_VERT_ANIM_WRINKLE;
  2637. }
  2638. // count all the unique verts that actually move
  2639. if ( !pDoesMove[pDestVAnim->vertex] )
  2640. {
  2641. pDoesMove[pDestVAnim->vertex] = true;
  2642. nNumMoved++;
  2643. }
  2644. g_flexkey[i].numvanims++;
  2645. pDestVAnim++;
  2646. }
  2647. }
  2648. }
  2649. if ( nNumMoved > MAXSTUDIOFLEXVERTS )
  2650. {
  2651. MdlError( "Too many flexed verts %d (%d)\n", nNumMoved, MAXSTUDIOFLEXVERTS );
  2652. }
  2653. else if ( nNumMoved > 0 && !g_quiet )
  2654. {
  2655. printf("Max flex verts %d\n", nNumMoved );
  2656. }
  2657. }
  2658. // Finds the bone index for a particular source
  2659. extern int FindLocalBoneNamed( const s_source_t *pSource, const char *pName );
  2660. //-----------------------------------------------------------------------------
  2661. // Purpose: finds the bone index in the global bone table
  2662. //-----------------------------------------------------------------------------
  2663. int findGlobalBone( const char *name )
  2664. {
  2665. name = RenameBone( name );
  2666. for ( int k = 0; k < g_numbones; k++ )
  2667. {
  2668. if ( !Q_stricmp( g_bonetable[k].name, name ) )
  2669. return k;
  2670. }
  2671. return -1;
  2672. }
  2673. bool IsGlobalBoneXSI( const char *name, const char *bonename )
  2674. {
  2675. name = RenameBone( name );
  2676. int len = strlen( name );
  2677. int len2 = strlen( bonename );
  2678. if ( len2 == len && strchr( bonename, '.' ) == NULL && stricmp( bonename, name ) == 0 )
  2679. return true;
  2680. if (len2 > len)
  2681. {
  2682. if (bonename[len2-len-1] == '.')
  2683. {
  2684. if (stricmp( &bonename[len2-len], name ) == 0)
  2685. {
  2686. return true;
  2687. }
  2688. }
  2689. }
  2690. return false;
  2691. }
  2692. int findGlobalBoneXSI( const char *name )
  2693. {
  2694. int k;
  2695. name = RenameBone( name );
  2696. for (k = 0; k < g_numbones; k++)
  2697. {
  2698. if (IsGlobalBoneXSI( name, g_bonetable[k].name ))
  2699. {
  2700. return k;
  2701. }
  2702. }
  2703. return -1;
  2704. }
  2705. //-----------------------------------------------------------------------------
  2706. // Purpose: Acculumate quaternions and try to find the swept area of rotation
  2707. // so that a "midpoint" of the rotation area can be found
  2708. //-----------------------------------------------------------------------------
  2709. void findAnimQuaternionAlignment( int k, int i, Quaternion &qBase, Quaternion &qMin, Quaternion &qMax )
  2710. {
  2711. int j;
  2712. AngleQuaternion( g_panimation[i]->sanim[0][k].rot, qBase );
  2713. qMin = qBase;
  2714. float dMin = 1.0;
  2715. qMax = qBase;
  2716. float dMax = 1.0;
  2717. for (j = 1; j < g_panimation[i]->numframes; j++)
  2718. {
  2719. Quaternion q;
  2720. AngleQuaternion( g_panimation[i]->sanim[j][k].rot, q );
  2721. QuaternionAlign( qBase, q, q );
  2722. float d0 = QuaternionDotProduct( q, qBase );
  2723. float d1 = QuaternionDotProduct( q, qMin );
  2724. float d2 = QuaternionDotProduct( q, qMax );
  2725. /*
  2726. if (i != 0)
  2727. printf("%f %f %f : %f\n", d0, d1, d2, QuaternionDotProduct( qMin, qMax ) );
  2728. */
  2729. if (d1 >= d0)
  2730. {
  2731. if (d0 < dMin)
  2732. {
  2733. qMin = q;
  2734. dMin = d0;
  2735. if (dMax == 1.0)
  2736. {
  2737. QuaternionMA( qBase, -0.01, qMin, qMax );
  2738. QuaternionAlign( qBase, qMax, qMax );
  2739. }
  2740. }
  2741. }
  2742. else if (d2 >= d0)
  2743. {
  2744. if (d0 < dMax)
  2745. {
  2746. qMax = q;
  2747. dMax = d0;
  2748. }
  2749. }
  2750. /*
  2751. if (i != 0)
  2752. printf("%f ", QuaternionDotProduct( qMin, qMax ) );
  2753. */
  2754. QuaternionSlerpNoAlign( qMin, qMax, 0.5, qBase );
  2755. Assert( qBase.IsValid() );
  2756. /*
  2757. if (i != 0)
  2758. {
  2759. QAngle ang;
  2760. QuaternionAngles( qMin, ang );
  2761. printf("(%.1f %.1f %.1f) ", ang.x, ang.y, ang.z );
  2762. QuaternionAngles( qMax, ang );
  2763. printf("(%.1f %.1f %.1f) ", ang.x, ang.y, ang.z );
  2764. QuaternionAngles( qBase, ang );
  2765. printf("(%.1f %.1f %.1f)\n", ang.x, ang.y, ang.z );
  2766. }
  2767. */
  2768. dMin = QuaternionDotProduct( qBase, qMin );
  2769. dMax = QuaternionDotProduct( qBase, qMax );
  2770. }
  2771. // printf("%s (%s): %.3f :%.3f\n", g_bonetable[k].name, g_panimation[i]->name, QuaternionDotProduct( qMin, qMax ), QuaternionDotProduct( qMin, qBase ) );
  2772. /*
  2773. if (i != 0)
  2774. exit(0);
  2775. */
  2776. }
  2777. //-----------------------------------------------------------------------------
  2778. // Purpose: For specific bones, try to find the total valid area of rotation so
  2779. // that their mid point of rotation can be used at run time to "pre-align"
  2780. // the quaternions so that rotations > 180 degrees don't get blended the
  2781. // "short way round".
  2782. //-----------------------------------------------------------------------------
  2783. void limitBoneRotations( void )
  2784. {
  2785. int i, j, k;
  2786. for (i = 0; i < g_numlimitrotation; i++)
  2787. {
  2788. Quaternion qBase;
  2789. k = findGlobalBone( g_limitrotation[i].name );
  2790. if (k == -1)
  2791. {
  2792. MdlError("unknown bone \"%s\" in $limitrotation\n", g_limitrotation[i].name );
  2793. }
  2794. AngleQuaternion( g_bonetable[k].rot, qBase );
  2795. if (g_limitrotation[i].numseq == 0)
  2796. {
  2797. for (j = 0; j < g_numani; j++)
  2798. {
  2799. if (!(g_panimation[j]->flags & STUDIO_DELTA) && g_panimation[j]->numframes > 3)
  2800. {
  2801. Quaternion qBase2, qMin2, qMax2;
  2802. findAnimQuaternionAlignment( k, j, qBase2, qMin2, qMax2 );
  2803. QuaternionAdd( qBase, qBase2, qBase );
  2804. }
  2805. }
  2806. QuaternionNormalize( qBase );
  2807. }
  2808. else
  2809. {
  2810. for (j = 0; j < g_limitrotation[i].numseq; j++)
  2811. {
  2812. }
  2813. }
  2814. /*
  2815. QAngle ang;
  2816. QuaternionAngles( qBase, ang );
  2817. printf("%s : (%.1f %.1f %.1f) \n", g_bonetable[k].name, ang.x, ang.y, ang.z );
  2818. */
  2819. g_bonetable[k].qAlignment = qBase;
  2820. g_bonetable[k].flags |= BONE_FIXED_ALIGNMENT;
  2821. // QuaternionAngles( qBase, g_panimation[0]->sanim[0][k].rot );
  2822. }
  2823. }
  2824. //-----------------------------------------------------------------------------
  2825. // Purpose: For specific bones, try to find the total valid area of rotation so
  2826. // that their mid point of rotation can be used at run time to "pre-align"
  2827. // the quaternions so that rotations > 180 degrees don't get blended the
  2828. // "short way round".
  2829. //-----------------------------------------------------------------------------
  2830. void limitIKChainLength( void )
  2831. {
  2832. int i, j, k;
  2833. matrix3x4_t boneToWorld[MAXSTUDIOSRCBONES]; // bone transformation matrix
  2834. for (k = 0; k < g_numikchains; k++)
  2835. {
  2836. bool needsFixup = false;
  2837. bool hasKnees = false;
  2838. Vector kneeDir = g_ikchain[k].link[0].kneeDir;
  2839. if (kneeDir.Length() > 0.0)
  2840. {
  2841. hasKnees = true;
  2842. }
  2843. else
  2844. {
  2845. for (i = 0; i < g_numani; i++)
  2846. {
  2847. s_animation_t *panim = g_panimation[i];
  2848. if (panim->flags & STUDIO_DELTA)
  2849. continue;
  2850. if (panim->flags & STUDIO_HIDDEN)
  2851. continue;
  2852. for (j = 0; j < panim->numframes; j++)
  2853. {
  2854. CalcBoneTransforms( panim, j, boneToWorld );
  2855. Vector worldThigh;
  2856. Vector worldKnee;
  2857. Vector worldFoot;
  2858. MatrixPosition( boneToWorld[ g_ikchain[k].link[0].bone ], worldThigh );
  2859. MatrixPosition( boneToWorld[ g_ikchain[k].link[1].bone ], worldKnee );
  2860. MatrixPosition( boneToWorld[ g_ikchain[k].link[2].bone ], worldFoot );
  2861. float l1 = (worldKnee-worldThigh).Length();
  2862. float l2 = (worldFoot-worldKnee).Length();
  2863. float l3 = (worldFoot-worldThigh).Length();
  2864. Vector ikHalf = (worldFoot+worldThigh) * 0.5;
  2865. // FIXME: what to do when the knee completely straight?
  2866. Vector ikKneeDir = worldKnee - ikHalf;
  2867. VectorNormalize( ikKneeDir );
  2868. // ikTargetKnee = ikKnee + ikKneeDir * l1;
  2869. // leg too straight to figure out knee?
  2870. if (l3 > (l1 + l2) * 0.999)
  2871. {
  2872. needsFixup = true;
  2873. }
  2874. else
  2875. {
  2876. // rotate knee into local space
  2877. Vector tmp;
  2878. VectorIRotate( ikKneeDir, boneToWorld[ g_ikchain[k].link[0].bone ], tmp );
  2879. float bend = (((DotProduct( worldThigh - worldKnee, worldFoot - worldKnee ) ) / (l1 * l3)) + 1) / 2.0;
  2880. kneeDir += tmp * bend;
  2881. hasKnees = true;
  2882. }
  2883. }
  2884. }
  2885. }
  2886. if (!needsFixup)
  2887. continue;
  2888. if (!hasKnees)
  2889. {
  2890. MdlWarning( "ik rules for %s but no clear knee direction\n", g_ikchain[k].name );
  2891. continue;
  2892. }
  2893. VectorNormalize( kneeDir );
  2894. g_ikchain[k].link[0].kneeDir = kneeDir;
  2895. if (g_verbose)
  2896. {
  2897. printf("knee %s %f %f %f\n", g_ikchain[k].name, kneeDir.x, kneeDir.y, kneeDir.z );
  2898. }
  2899. #if 0
  2900. // don't bother for now, storing the knee direction should fix the runtime problems.
  2901. for (i = 0; i < g_numani; i++)
  2902. {
  2903. s_animation_t *panim = g_panimation[i];
  2904. if (panim->flags & STUDIO_DELTA)
  2905. continue;
  2906. for (j = 0; j < panim->numframes; j++)
  2907. {
  2908. CalcBoneTransforms( panim, j, boneToWorld );
  2909. Vector worldFoot;
  2910. MatrixPosition( boneToWorld[ g_ikchain[k].link[2].bone ], worldFoot );
  2911. Vector targetKneeDir;
  2912. VectorRotate( kneeDir, boneToWorld[ g_ikchain[k].link[0].bone ], targetKneeDir );
  2913. // run it through the normal IK solver, this should move the foot positions to someplace legal
  2914. Studio_SolveIK( g_ikchain[k].link[0].bone, g_ikchain[k].link[1].bone, g_ikchain[k].link[2].bone, worldFoot, targetKneeDir, boneToWorld );
  2915. solveBone( panim, j, g_ikchain[k].link[0].bone, boneToWorld );
  2916. solveBone( panim, j, g_ikchain[k].link[1].bone, boneToWorld );
  2917. solveBone( panim, j, g_ikchain[k].link[2].bone, boneToWorld );
  2918. }
  2919. }
  2920. #endif
  2921. }
  2922. }
  2923. //-----------------------------------------------------------------------------
  2924. // Purpose: build "next node" table that links every transition "node" to
  2925. // every other transition "node", if possible
  2926. //-----------------------------------------------------------------------------
  2927. void MakeTransitions( )
  2928. {
  2929. int i, j, k;
  2930. bool iHit = g_bMultistageGraph;
  2931. // add in direct node transitions
  2932. for (i = 0; i < g_sequence.Count(); i++)
  2933. {
  2934. if (g_sequence[i].entrynode != g_sequence[i].exitnode)
  2935. {
  2936. g_xnode[g_sequence[i].entrynode-1][g_sequence[i].exitnode-1] = g_sequence[i].exitnode;
  2937. if (g_sequence[i].nodeflags)
  2938. {
  2939. g_xnode[g_sequence[i].exitnode-1][g_sequence[i].entrynode-1] = g_sequence[i].entrynode;
  2940. }
  2941. }
  2942. }
  2943. // calculate multi-stage transitions
  2944. while (iHit)
  2945. {
  2946. iHit = false;
  2947. for (i = 1; i <= g_numxnodes; i++)
  2948. {
  2949. for (j = 1; j <= g_numxnodes; j++)
  2950. {
  2951. // if I can't go there directly
  2952. if (i != j && g_xnode[i-1][j-1] == 0)
  2953. {
  2954. for (k = 1; k <= g_numxnodes; k++)
  2955. {
  2956. // but I found someone who knows how that I can get to
  2957. if (g_xnode[k-1][j-1] > 0 && g_xnode[i-1][k-1] > 0)
  2958. {
  2959. // then go to them
  2960. g_xnode[i-1][j-1] = -g_xnode[i-1][k-1];
  2961. iHit = true;
  2962. break;
  2963. }
  2964. }
  2965. }
  2966. }
  2967. }
  2968. // reset previous pass so the links can be used in the next pass
  2969. for (i = 1; i <= g_numxnodes; i++)
  2970. {
  2971. for (j = 1; j <= g_numxnodes; j++)
  2972. {
  2973. g_xnode[i-1][j-1] = abs( g_xnode[i-1][j-1] );
  2974. }
  2975. }
  2976. }
  2977. // add in allowed "skips"
  2978. for (i = 0; i < g_numxnodeskips; i++)
  2979. {
  2980. g_xnode[g_xnodeskip[i][0]-1][g_xnodeskip[i][1]-1] = 0;
  2981. }
  2982. if (g_bDumpGraph)
  2983. {
  2984. for (j = 1; j <= g_numxnodes; j++)
  2985. {
  2986. printf("%2d : %s\n", j, g_xnodename[j] );
  2987. }
  2988. printf(" " );
  2989. for (j = 1; j <= g_numxnodes; j++)
  2990. {
  2991. printf("%2d ", j );
  2992. }
  2993. printf("\n" );
  2994. for (i = 1; i <= g_numxnodes; i++)
  2995. {
  2996. printf("%2d: ", i );
  2997. for (j = 1; j <= g_numxnodes; j++)
  2998. {
  2999. printf("%2d ", g_xnode[i-1][j-1] );
  3000. }
  3001. printf("\n" );
  3002. }
  3003. }
  3004. }
  3005. int VectorCompareEpsilon(const Vector& v1, const Vector& v2, float epsilon)
  3006. {
  3007. int i;
  3008. for (i=0 ; i<3 ; i++)
  3009. if (fabs(v1[i] - v2[i]) > epsilon)
  3010. return 0;
  3011. return 1;
  3012. }
  3013. int RadianEulerCompareEpsilon(const RadianEuler& v1, const RadianEuler& v2, float epsilon)
  3014. {
  3015. int i;
  3016. for (i=0 ; i<3 ; i++)
  3017. {
  3018. // clamp to 2pi
  3019. float a1 = fmod(v1[i],(float) (2*M_PI));
  3020. float a2 = fmod(v2[i],(float) (2*M_PI));
  3021. float delta = fabs(a1-a2);
  3022. // use the smaller angle (359 == 1 degree off)
  3023. if ( delta > M_PI )
  3024. {
  3025. delta = 2*M_PI - delta;
  3026. }
  3027. if (delta > epsilon)
  3028. return 0;
  3029. }
  3030. return 1;
  3031. }
  3032. bool AnimationDifferent( const Vector& startPos, const RadianEuler& startRot, const Vector& pos, const RadianEuler& rot )
  3033. {
  3034. if ( !VectorCompareEpsilon( startPos, pos, 0.01 ) )
  3035. return true;
  3036. if ( !RadianEulerCompareEpsilon( startRot, rot, 0.01 ) )
  3037. return true;
  3038. return false;
  3039. }
  3040. bool BoneHasAnimation( const char *pName )
  3041. {
  3042. bool first = true;
  3043. Vector pos;
  3044. RadianEuler rot;
  3045. if ( !g_numani )
  3046. return false;
  3047. int globalIndex = findGlobalBone( pName );
  3048. // don't check root bones for animation
  3049. if (globalIndex >= 0 && g_bonetable[globalIndex].parent == -1)
  3050. return true;
  3051. // find used bones per g_model
  3052. for (int i = 0; i < g_numani; i++)
  3053. {
  3054. s_source_t *psource = g_panimation[i]->source;
  3055. const char *pAnimationName = g_panimation[i]->animationname;
  3056. s_sourceanim_t *pSourceAnim = FindSourceAnim( psource, pAnimationName );
  3057. int boneIndex = FindLocalBoneNamed(psource, pName);
  3058. // not in this source?
  3059. if (boneIndex < 0)
  3060. continue;
  3061. // this is not right, but enough of the bones are moved unintentionally between
  3062. // animations that I put this in to catch them.
  3063. first = true;
  3064. int n = g_panimation[i]->startframe - pSourceAnim->startframe;
  3065. // printf("%s %d:%d\n", g_panimation[i]->filename, g_panimation[i]->startframe, psource->startframe );
  3066. for (int j = 0; j < g_panimation[i]->numframes; j++)
  3067. {
  3068. if ( first )
  3069. {
  3070. VectorCopy( pSourceAnim->rawanim[j+n][boneIndex].pos, pos );
  3071. VectorCopy( pSourceAnim->rawanim[j+n][boneIndex].rot, rot );
  3072. first = false;
  3073. }
  3074. else
  3075. {
  3076. if ( AnimationDifferent( pos, rot, pSourceAnim->rawanim[j+n][boneIndex].pos, pSourceAnim->rawanim[j+n][boneIndex].rot ) )
  3077. return true;
  3078. }
  3079. }
  3080. }
  3081. return false;
  3082. }
  3083. bool BoneIsBonemerge( char const *pname )
  3084. {
  3085. for (int k = 0; k < g_BoneMerge.Count(); k++)
  3086. {
  3087. if ( !stricmp( g_BoneMerge[k].bonename, pname ) )
  3088. {
  3089. return true;
  3090. }
  3091. }
  3092. return false;
  3093. }
  3094. bool BoneShouldAlwaysSetup( char const *pname )
  3095. {
  3096. for (int k = 0; k < g_BoneAlwaysSetup.Count(); k++)
  3097. {
  3098. if ( !stricmp( g_BoneAlwaysSetup[k].bonename, pname ) )
  3099. {
  3100. return true;
  3101. }
  3102. }
  3103. return false;
  3104. }
  3105. bool BoneHasAttachments( char const *pname )
  3106. {
  3107. for (int k = 0; k < g_numattachments; k++)
  3108. {
  3109. if ( !stricmp( g_attachment[k].bonename, pname ) )
  3110. {
  3111. return true;
  3112. }
  3113. }
  3114. return false;
  3115. }
  3116. bool BoneIsProcedural( char const *pname )
  3117. {
  3118. int k;
  3119. for (k = 0; k < g_numaxisinterpbones; k++)
  3120. {
  3121. if (! stricmp( g_axisinterpbones[k].bonename, pname ) )
  3122. {
  3123. return true;
  3124. }
  3125. }
  3126. for (k = 0; k < g_numquatinterpbones; k++)
  3127. {
  3128. if (IsGlobalBoneXSI( g_quatinterpbones[k].bonename, pname ) )
  3129. {
  3130. return true;
  3131. }
  3132. }
  3133. for (k = 0; k < g_numaimatbones; k++)
  3134. {
  3135. if (IsGlobalBoneXSI( g_aimatbones[k].bonename, pname ) )
  3136. {
  3137. return true;
  3138. }
  3139. }
  3140. for (k = 0; k < g_numjigglebones; k++)
  3141. {
  3142. if (! stricmp( g_jigglebones[k].bonename, pname ) )
  3143. {
  3144. return true;
  3145. }
  3146. }
  3147. for ( k = 0; k < g_twistbones.Count(); ++k )
  3148. {
  3149. for ( int i = 0; i < g_twistbones[k].m_twistBoneTargets.Count(); ++i )
  3150. {
  3151. if ( IsGlobalBoneXSI( g_twistbones[k].m_twistBoneTargets[i].m_szBoneName, pname ) )
  3152. {
  3153. return true;
  3154. }
  3155. }
  3156. }
  3157. return false;
  3158. }
  3159. bool BoneIsIK( char const *pname )
  3160. {
  3161. int k;
  3162. // tag bones used by ikchains
  3163. for (k = 0; k < g_numikchains; k++)
  3164. {
  3165. if ( !stricmp( g_ikchain[k].bonename, pname ) )
  3166. {
  3167. return true;
  3168. }
  3169. }
  3170. return false;
  3171. }
  3172. bool BoneShouldCollapse( char const *pname )
  3173. {
  3174. int k;
  3175. for (k = 0; k < g_collapse.Count(); k++)
  3176. {
  3177. if (stricmp( g_collapse[k], pname ) == 0)
  3178. {
  3179. return true;
  3180. }
  3181. }
  3182. return ( !BoneHasAnimation( pname ) && !BoneIsProcedural( pname ) && !BoneIsIK( pname ) && !BoneHasAttachments( pname ) && !BoneIsBonemerge( pname ) );
  3183. }
  3184. //-----------------------------------------------------------------------------
  3185. // Purpose: Collapse vertex assignments up to parent on bones that are not needed
  3186. // This can optimize a model substantially if the animator is using
  3187. // lots of helper bones with no animation.
  3188. //-----------------------------------------------------------------------------
  3189. void CollapseBones( void )
  3190. {
  3191. int j, k;
  3192. int count = 0;
  3193. for (k = 0; k < g_numbones; k++)
  3194. {
  3195. if ( g_bonetable[k].bDontCollapse )
  3196. continue;
  3197. int sBoneFlags = g_bonetable[k].flags;
  3198. char szBoneReport[512] = "";
  3199. V_strcat_safe( szBoneReport, " [" );
  3200. V_strcat_safe( szBoneReport, g_bonetable[k].name );
  3201. if( sBoneFlags & BONE_USED_BY_ANYTHING )
  3202. {
  3203. V_strcat_safe( szBoneReport, "]\t\tflags: " );
  3204. if( sBoneFlags & BONE_USED_BY_ATTACHMENT )
  3205. V_strcat_safe( szBoneReport, "attachments, " );
  3206. if( sBoneFlags & BONE_USED_BY_HITBOX )
  3207. V_strcat_safe( szBoneReport, "hitboxes, " );
  3208. if( sBoneFlags & BONE_USED_BY_BONE_MERGE )
  3209. V_strcat_safe( szBoneReport, "bonemerges, " );
  3210. if( sBoneFlags & BONE_USED_BY_VERTEX_LOD0 )
  3211. V_strcat_safe( szBoneReport, "lod0, " );
  3212. if( sBoneFlags & BONE_USED_BY_VERTEX_LOD1 )
  3213. V_strcat_safe( szBoneReport, "lod1, " );
  3214. if( sBoneFlags & BONE_USED_BY_VERTEX_LOD2 )
  3215. V_strcat_safe( szBoneReport, "lod2, " );
  3216. if( sBoneFlags & BONE_USED_BY_VERTEX_LOD3 )
  3217. V_strcat_safe( szBoneReport, "lod3, " );
  3218. if( sBoneFlags & BONE_USED_BY_VERTEX_LOD4 )
  3219. V_strcat_safe( szBoneReport, "lod4, " );
  3220. if( sBoneFlags & BONE_USED_BY_VERTEX_LOD5 )
  3221. V_strcat_safe( szBoneReport, "lod5, " );
  3222. if( sBoneFlags & BONE_USED_BY_VERTEX_LOD6 )
  3223. V_strcat_safe( szBoneReport, "lod6, " );
  3224. if( sBoneFlags & BONE_USED_BY_VERTEX_LOD7 )
  3225. V_strcat_safe( szBoneReport, "lod7, " );
  3226. if( sBoneFlags & BONE_ALWAYS_SETUP )
  3227. V_strcat_safe( szBoneReport, "alwayssetup, " );
  3228. }
  3229. else
  3230. {
  3231. V_strcat_safe( szBoneReport, "] is unused." );
  3232. }
  3233. // if it's being used by something other than a vertex, collapse it.
  3234. if ( ((g_bonetable[k].flags & BONE_USED_BY_VERTEX_MASK) != 0) || !BoneShouldCollapse( g_bonetable[k].name ) )
  3235. {
  3236. if (g_collapse_bones_message)
  3237. {
  3238. Msg("[%08x] [keeping] %s \n", sBoneFlags, szBoneReport );
  3239. }
  3240. continue;
  3241. }
  3242. count++;
  3243. if( g_collapse_bones_message )
  3244. {
  3245. Msg("[%08x] [collapsing] %s \n", sBoneFlags, szBoneReport );
  3246. }
  3247. g_numbones--;
  3248. int m = g_bonetable[k].parent;
  3249. for (j = k; j < g_numbones; j++)
  3250. {
  3251. g_bonetable[j] = g_bonetable[j+1];
  3252. if (g_bonetable[j].parent == k)
  3253. {
  3254. g_bonetable[j].parent = m;
  3255. }
  3256. else if (g_bonetable[j].parent >= k)
  3257. {
  3258. g_bonetable[j].parent = g_bonetable[j].parent - 1;
  3259. }
  3260. }
  3261. k--;
  3262. }
  3263. if( !g_quiet && count)
  3264. {
  3265. Msg("Collapsed %d bones\n", count );
  3266. }
  3267. }
  3268. //-----------------------------------------------------------------------------
  3269. // Purpose: replace all animation, rotation and translation, etc. with a single bone
  3270. //-----------------------------------------------------------------------------
  3271. void MakeStaticProp()
  3272. {
  3273. int i, j, k;
  3274. matrix3x4_t rotated;
  3275. Vector tmp;
  3276. AngleMatrix( g_defaultrotation, rotated );
  3277. VectorTransform( -g_defaultadjust, rotated, tmp );
  3278. PositionMatrix( tmp, rotated );
  3279. // FIXME: missing attachment point recalcs!
  3280. // replace bone 0 with "static_prop" bone and attach everything to it.
  3281. for (i = 0; i < g_numsources; i++)
  3282. {
  3283. s_source_t *psource = g_source[i];
  3284. strcpy( psource->localBone[0].name, "static_prop" );
  3285. psource->localBone[0].parent = -1;
  3286. for (k = 1; k < psource->numbones; k++)
  3287. {
  3288. psource->localBone[k].parent = -1;
  3289. }
  3290. Vector mins, maxs;
  3291. ClearBounds( mins, maxs );
  3292. for (j = 0; j < psource->numvertices; j++)
  3293. {
  3294. for (k = 0; k < psource->vertex[j].boneweight.numbones; k++)
  3295. {
  3296. // attach everything to root
  3297. psource->vertex[j].boneweight.bone[k] = 0;
  3298. }
  3299. // **shift everything into identity space**
  3300. // position
  3301. Vector tmp;
  3302. VectorTransform( psource->vertex[j].position, rotated, tmp );
  3303. VectorCopy( tmp, psource->vertex[j].position );
  3304. // normal
  3305. VectorRotate( psource->vertex[j].normal, rotated, tmp );
  3306. VectorCopy( tmp, psource->vertex[j].normal );
  3307. // tangentS
  3308. VectorRotate( psource->vertex[j].tangentS.AsVector3D(), rotated, tmp );
  3309. VectorCopy( tmp, psource->vertex[j].tangentS.AsVector3D() );
  3310. // incrementally compute identity space bbox
  3311. AddPointToBounds( psource->vertex[j].position, mins, maxs );
  3312. }
  3313. if ( g_centerstaticprop )
  3314. {
  3315. const char *pAttachmentName = "placementOrigin";
  3316. bool bFound = false;
  3317. for ( k = 0; k < g_numattachments; k++ )
  3318. {
  3319. if ( !Q_stricmp( g_attachment[k].name, pAttachmentName ) )
  3320. {
  3321. bFound = true;
  3322. break;
  3323. }
  3324. }
  3325. if ( !bFound )
  3326. {
  3327. g_PropCenterOffset = -0.5f * (mins + maxs);
  3328. }
  3329. for ( j = 0; j < psource->numvertices; j++ )
  3330. {
  3331. psource->vertex[j].position += g_PropCenterOffset;
  3332. }
  3333. if ( !bFound )
  3334. {
  3335. // now add an attachment point to store this offset
  3336. Q_strncpy( g_attachment[g_numattachments].name, pAttachmentName, sizeof(g_attachment[g_numattachments].name) );
  3337. Q_strncpy( g_attachment[g_numattachments].bonename, "static_prop", sizeof(g_attachment[g_numattachments].name) );
  3338. g_attachment[g_numattachments].bone = 0;
  3339. g_attachment[g_numattachments].type = 0;
  3340. AngleMatrix( vec3_angle, g_PropCenterOffset, g_attachment[g_numattachments].local );
  3341. g_numattachments++;
  3342. }
  3343. }
  3344. // force the animation to be identity
  3345. s_sourceanim_t *pSourceAnim = FindSourceAnim( psource, "BindPose" );
  3346. if ( pSourceAnim )
  3347. {
  3348. pSourceAnim->rawanim[0][0].pos = Vector( 0, 0, 0 );
  3349. pSourceAnim->rawanim[0][0].rot = RadianEuler( 0, 0, 0 );
  3350. // make it all a single frame animation
  3351. pSourceAnim->numframes = 1;
  3352. pSourceAnim->startframe = 0;
  3353. pSourceAnim->endframe = 1;
  3354. }
  3355. // make an identity boneToPose transform
  3356. AngleMatrix( QAngle( 0, 0, 0 ), psource->boneToPose[0] );
  3357. }
  3358. // throw away all animations
  3359. g_numani = 1;
  3360. g_panimation[0]->numframes = 1;
  3361. g_panimation[0]->startframe = 0;
  3362. g_panimation[0]->endframe = 1;
  3363. Q_strncpy( g_panimation[0]->animationname, "BindPose", sizeof(g_panimation[0]->animationname) );
  3364. g_panimation[0]->rotation = RadianEuler( 0, 0, 0 );
  3365. g_panimation[0]->adjust = Vector( 0, 0, 0 );
  3366. // throw away all vertex animations
  3367. g_numflexkeys = 0;
  3368. g_defaultflexkey = NULL;
  3369. // Recalc attachment points:
  3370. for( i = 0; i < g_numattachments; i++ )
  3371. {
  3372. if( g_centerstaticprop && ( i == g_numattachments - 1 ) )
  3373. continue;
  3374. ConcatTransforms( rotated, g_attachment[i].local, g_attachment[i].local );
  3375. Q_strncpy( g_attachment[i].bonename, "static_prop", sizeof(g_attachment[i].name) );
  3376. g_attachment[i].bone = 0;
  3377. g_attachment[i].type = 0;
  3378. }
  3379. }
  3380. //-----------------------------------------------------------------------------
  3381. // Marks the boneref all the way up the bone hierarchy
  3382. //-----------------------------------------------------------------------------
  3383. static void UpdateBonerefRecursive( s_source_t *psource, int nBoneIndex, int nFlags )
  3384. {
  3385. if ( nFlags == 0 )
  3386. return;
  3387. psource->boneref[nBoneIndex] |= nFlags;
  3388. // Chain the flag up the parent
  3389. int n = psource->localBone[nBoneIndex].parent;
  3390. while (n != -1)
  3391. {
  3392. psource->boneref[n] |= psource->boneref[nBoneIndex];
  3393. n = psource->localBone[n].parent;
  3394. }
  3395. }
  3396. //-----------------------------------------------------------------------------
  3397. // Purpose: Returns the axis of the bone after remapping. Axis 0:X, 1:Y, 2:Z
  3398. // If the bone has a parent, axis is returned as is, if bone does not
  3399. // have a parent then the $upaxis determines how the axes are mapped.
  3400. // Only $upaxis Y is supported (see comment in Cmd_UpAxis).
  3401. //-----------------------------------------------------------------------------
  3402. int GetRemappedBoneAxis( int nBoneIndex, int nAxis )
  3403. {
  3404. if ( nBoneIndex < 0 || nBoneIndex >= g_numbones )
  3405. return nAxis;
  3406. if ( g_bonetable[nBoneIndex].parent >= 0 )
  3407. return nAxis;
  3408. // Y Up
  3409. if ( g_defaultrotation.x == static_cast< float >( M_PI / 2.0f ) && g_defaultrotation.y == 0.0f && g_defaultrotation.z == static_cast< float >( M_PI / 2.0f ) )
  3410. {
  3411. static const int nAxisMap[3] = { 1, 2, 0 };
  3412. return nAxisMap[ nAxis ];
  3413. }
  3414. // Default Z Up
  3415. return nAxis;
  3416. }
  3417. //-----------------------------------------------------------------------------
  3418. // Purpose: Map the flex driver bones to the global bone table
  3419. // Also cleans up any that do not match to a global bone
  3420. //-----------------------------------------------------------------------------
  3421. void MapFlexDriveBonesToGlobalBoneTable()
  3422. {
  3423. CDmeBoneFlexDriverList *pDmeBoneFlexDriverList = GetElement< CDmeBoneFlexDriverList >( g_hDmeBoneFlexDriverList );
  3424. if ( !pDmeBoneFlexDriverList )
  3425. return;
  3426. // Loop backwards so we can remove elements as we go
  3427. for ( int i = pDmeBoneFlexDriverList->m_eBoneFlexDriverList.Count() - 1; i >= 0; --i )
  3428. {
  3429. CDmeBoneFlexDriver *pDmeBoneFlexDriver = pDmeBoneFlexDriverList->m_eBoneFlexDriverList[i];
  3430. if ( !pDmeBoneFlexDriver )
  3431. {
  3432. pDmeBoneFlexDriverList->m_eBoneFlexDriverList.Remove( i );
  3433. continue;
  3434. }
  3435. for ( int j = 0; j < g_numbones; ++j )
  3436. {
  3437. if ( !Q_stricmp( g_bonetable[j].name, pDmeBoneFlexDriver->m_sBoneName.Get() ) )
  3438. {
  3439. if ( g_bonetable[j].flags & BONE_ALWAYS_PROCEDURAL )
  3440. {
  3441. MdlWarning( "DmeBoneFlexDriver Bone: %s is marked procedural, Ignoring flex drivers\n", pDmeBoneFlexDriver->m_sBoneName.Get() );
  3442. pDmeBoneFlexDriverList->m_eBoneFlexDriverList.Remove( i );
  3443. pDmeBoneFlexDriver = NULL;
  3444. }
  3445. pDmeBoneFlexDriver->SetValue( "__boneIndex", j );
  3446. // Map the axis for Y up stuff
  3447. for ( int k = 0; k < pDmeBoneFlexDriver->m_eControlList.Count(); ++k )
  3448. {
  3449. pDmeBoneFlexDriver->m_eControlList[k]->m_nBoneComponent = GetRemappedBoneAxis( j, pDmeBoneFlexDriver->m_eControlList[k]->m_nBoneComponent );
  3450. }
  3451. break;
  3452. }
  3453. }
  3454. // Was removed because it was referencing a procedural bone
  3455. if ( !pDmeBoneFlexDriver )
  3456. continue;
  3457. CDmAttribute *pBoneIndexAttr = pDmeBoneFlexDriver->GetAttribute( "__boneIndex" );
  3458. if ( pBoneIndexAttr )
  3459. {
  3460. pBoneIndexAttr->AddFlag( FATTRIB_DONTSAVE );
  3461. }
  3462. else
  3463. {
  3464. MdlWarning( "DmeBoneFlexDriver Bone: %s - No Bone Found With That Name, Ignoring\n", pDmeBoneFlexDriver->m_sBoneName.Get() );
  3465. pDmeBoneFlexDriverList->m_eBoneFlexDriverList.Remove( i );
  3466. }
  3467. }
  3468. }
  3469. //-----------------------------------------------------------------------------
  3470. // Purpose: Tag bones in the specified source that are used as a bone flex driver
  3471. // Also cleans up any empty bone flex driver elements
  3472. // Also tags the DmeBoneFlexDriverControl with
  3473. //-----------------------------------------------------------------------------
  3474. void TagFlexDriverBones( s_source_t *pSource )
  3475. {
  3476. CDmeBoneFlexDriverList *pDmeBoneFlexDriverList = GetElement< CDmeBoneFlexDriverList >( g_hDmeBoneFlexDriverList );
  3477. if ( !pDmeBoneFlexDriverList )
  3478. return;
  3479. // Loop backwards so we can remove elements as we go
  3480. for ( int i = pDmeBoneFlexDriverList->m_eBoneFlexDriverList.Count() - 1; i >= 0; --i )
  3481. {
  3482. CDmeBoneFlexDriver *pDmeBoneFlexDriver = pDmeBoneFlexDriverList->m_eBoneFlexDriverList[i];
  3483. if ( !pDmeBoneFlexDriver )
  3484. {
  3485. pDmeBoneFlexDriverList->m_eBoneFlexDriverList.Remove( i );
  3486. continue;
  3487. }
  3488. for ( int j = pDmeBoneFlexDriver->m_eControlList.Count() - 1; j >= 0; --j )
  3489. {
  3490. CDmeBoneFlexDriverControl *pDmeBoneFlexDriverControl = pDmeBoneFlexDriver->m_eControlList[j];
  3491. if ( !pDmeBoneFlexDriverControl )
  3492. {
  3493. pDmeBoneFlexDriver->m_eControlList.Remove( j );
  3494. continue;
  3495. }
  3496. if ( pDmeBoneFlexDriverControl->m_nBoneComponent < STUDIO_BONE_FLEX_TX || pDmeBoneFlexDriverControl->m_nBoneComponent > STUDIO_BONE_FLEX_TZ )
  3497. {
  3498. MdlWarning( "DmeBoneFlexDriver Bone: %s - Flex Controlle: %s, Bone Component Out Of Range: %d [0-2], Ignoring\n", pDmeBoneFlexDriver->m_sBoneName.Get(), pDmeBoneFlexDriverControl->m_sFlexControllerName.Get(), pDmeBoneFlexDriverControl->m_nBoneComponent );
  3499. pDmeBoneFlexDriver->m_eControlList.Remove( j );
  3500. continue;
  3501. }
  3502. for ( int k = 0; k < g_numflexcontrollers; ++k )
  3503. {
  3504. if ( !Q_stricmp( g_flexcontroller[k].name, pDmeBoneFlexDriverControl->m_sFlexControllerName.Get() ) )
  3505. {
  3506. pDmeBoneFlexDriverControl->SetValue( "__flexControlIndex", k );
  3507. break;
  3508. }
  3509. }
  3510. if ( !pDmeBoneFlexDriverControl->HasAttribute( "__flexControlIndex" ) )
  3511. {
  3512. MdlWarning( "DmeBoneFlexDriver Bone: %s - No Flex Controller Named: %s, Ignoring\n", pDmeBoneFlexDriver->m_sBoneName.Get(), pDmeBoneFlexDriverControl->m_sFlexControllerName.Get() );
  3513. pDmeBoneFlexDriver->m_eControlList.Remove( j );
  3514. }
  3515. }
  3516. if ( pDmeBoneFlexDriver->m_eControlList.Count() <= 0 )
  3517. {
  3518. MdlWarning( "DmeBoneFlexDriver Bone: %s - No Flex Controllers Defined, Ignoring\n", pDmeBoneFlexDriver->m_sBoneName.Get() );
  3519. pDmeBoneFlexDriverList->m_eBoneFlexDriverList.Remove( i );
  3520. continue;
  3521. }
  3522. for ( int j = 0; j < pSource->numbones; ++j )
  3523. {
  3524. if ( !Q_stricmp( pSource->localBone[j].name, pDmeBoneFlexDriver->m_sBoneName.Get() ) )
  3525. {
  3526. // Mark used by all LODs
  3527. pSource->boneflags[j] |= BONE_USED_BY_VERTEX_MASK;
  3528. }
  3529. }
  3530. }
  3531. }
  3532. //-----------------------------------------------------------------------------
  3533. // Purpose: set "boneref" for all the source bones used by vertices, attachments, eyeballs, etc.
  3534. //-----------------------------------------------------------------------------
  3535. void TagUsedBones( )
  3536. {
  3537. int i, j, k;
  3538. int n;
  3539. // find used bones per g_model
  3540. for (i = 0; i < g_numsources; i++)
  3541. {
  3542. s_source_t *psource = g_source[i];
  3543. for (k = 0; k < MAXSTUDIOSRCBONES; k++)
  3544. {
  3545. psource->boneflags[k] = 0;
  3546. psource->boneref[k] = 0;
  3547. }
  3548. if (!psource->isActiveModel)
  3549. continue;
  3550. // printf("active: %s\n", psource->filename );
  3551. for (j = 0; j < psource->numvertices; j++)
  3552. {
  3553. for (k = 0; k < psource->vertex[j].boneweight.numbones; k++)
  3554. {
  3555. psource->boneflags[psource->vertex[j].boneweight.bone[k]] |= BONE_USED_BY_VERTEX_LOD0;
  3556. }
  3557. }
  3558. }
  3559. // find used bones per g_model
  3560. for (i = 0; i < g_numsources; i++)
  3561. {
  3562. s_source_t *psource = g_source[i];
  3563. // FIXME: this is in the wrong place. The attachment may be rigid and it never defined in a reference file
  3564. for (k = 0; k < g_numattachments; k++)
  3565. {
  3566. for (j = 0; j < psource->numbones; j++)
  3567. {
  3568. if ( !stricmp( g_attachment[k].bonename, psource->localBone[j].name ) )
  3569. {
  3570. // this bone is a keeper with or without associated vertices
  3571. // because an attachment point depends on it.
  3572. if (g_attachment[k].type & IS_RIGID)
  3573. {
  3574. bool bBoneFlagged = false;
  3575. for (n = j; n != -1; n = psource->localBone[n].parent)
  3576. {
  3577. if ( psource->boneflags[n] & BONE_USED_BY_VERTEX_LOD0 )
  3578. {
  3579. psource->boneflags[n] |= BONE_USED_BY_ATTACHMENT;
  3580. bBoneFlagged = true;
  3581. break;
  3582. }
  3583. // Check to see if the ancestor bone is in g_importbones because
  3584. // all bones in g_importbones are kept
  3585. for ( int ib = 0; ib < g_numimportbones; ++ib )
  3586. {
  3587. if ( !Q_stricmp( psource->localBone[n].name, g_importbone[ib].name ) )
  3588. {
  3589. psource->boneflags[n] |= BONE_USED_BY_ATTACHMENT;
  3590. bBoneFlagged = true;
  3591. }
  3592. }
  3593. }
  3594. // If nothing was flagged, that means that no ancestor bone
  3595. // in the hierarchy is used by VERTEX_LOD0 so tag the bone
  3596. // itself because need to make sure at least one bone is
  3597. // left for the attachment to attach to
  3598. if ( !bBoneFlagged )
  3599. {
  3600. psource->boneflags[j] |= BONE_USED_BY_ATTACHMENT;
  3601. }
  3602. }
  3603. else
  3604. {
  3605. psource->boneflags[j] |= BONE_USED_BY_ATTACHMENT;
  3606. }
  3607. }
  3608. }
  3609. }
  3610. for (k = 0; k < g_numikchains; k++)
  3611. {
  3612. for (j = 0; j < psource->numbones; j++)
  3613. {
  3614. if ( !stricmp( g_ikchain[k].bonename, psource->localBone[j].name ) )
  3615. {
  3616. // this bone is a keeper with or without associated vertices
  3617. // because a ikchain depends on it.
  3618. psource->boneflags[j] |= BONE_USED_BY_ATTACHMENT;
  3619. }
  3620. }
  3621. }
  3622. for (k = 0; k < g_nummouths; k++)
  3623. {
  3624. for (j = 0; j < psource->numbones; j++)
  3625. {
  3626. if ( !stricmp( g_mouth[k].bonename, psource->localBone[j].name ) )
  3627. {
  3628. // this bone is a keeper with or without associated vertices
  3629. // because a mouth shader depends on it.
  3630. psource->boneflags[j] |= BONE_USED_BY_ATTACHMENT;
  3631. }
  3632. }
  3633. }
  3634. // Tag all bones marked as being used by bonemerge
  3635. int nBoneMergeCount = g_BoneMerge.Count();
  3636. for ( k = 0; k < nBoneMergeCount; ++k )
  3637. {
  3638. for ( j = 0; j < psource->numbones; j++ )
  3639. {
  3640. if ( stricmp( g_BoneMerge[k].bonename, psource->localBone[j].name ) )
  3641. continue;
  3642. psource->boneflags[j] |= BONE_USED_BY_BONE_MERGE;
  3643. }
  3644. }
  3645. // Tag bones used as bone flex drivers, these need to be client side only
  3646. TagFlexDriverBones( psource );
  3647. // NOTE: This must come last; after all flags have been set!
  3648. // tag bonerefs as being used the union of the boneflags all their children
  3649. for (k = 0; k < psource->numbones; k++)
  3650. {
  3651. UpdateBonerefRecursive( psource, k, psource->boneflags[k] );
  3652. }
  3653. // Tag all bones marked as being used by alwayssetup
  3654. // NOTE these are intentionally added without respect to parents,
  3655. // because they are intended to be used on data-driving bones that are aren't
  3656. // necessarily moving vertices or part of a hierarchy. They are NOT guaranteed
  3657. // to be positioned correctly relative to their parents!!!
  3658. int nBoneAlwaysSetupCount = g_BoneAlwaysSetup.Count();
  3659. for ( k = 0; k < nBoneAlwaysSetupCount; ++k )
  3660. {
  3661. for ( j = 0; j < psource->numbones; j++ )
  3662. {
  3663. if ( stricmp( g_BoneAlwaysSetup[k].bonename, psource->localBone[j].name ) )
  3664. continue;
  3665. psource->boneflags[j] |= BONE_ALWAYS_SETUP;
  3666. }
  3667. }
  3668. // don't add more flags here! Add them up above the UpdateBonerefRecursive call, so they get propagated up their parents!
  3669. }
  3670. // tag all eyeball bones
  3671. for (i = 0; i < g_nummodelsbeforeLOD; i++)
  3672. {
  3673. s_source_t *psource = g_model[i]->source;
  3674. for (k = 0; k < g_model[i]->numeyeballs; k++)
  3675. {
  3676. psource->boneref[g_model[i]->eyeball[k].bone] |= BONE_USED_BY_ATTACHMENT;
  3677. }
  3678. }
  3679. }
  3680. //-----------------------------------------------------------------------------
  3681. // Purpose: change the names in the source files for bones that max auto-renamed on us
  3682. //-----------------------------------------------------------------------------
  3683. void RenameBones( )
  3684. {
  3685. int i, j, k;
  3686. // rename source bones if needed
  3687. for (i = 0; i < g_numsources; i++)
  3688. {
  3689. for (j = 0; j < g_source[i]->numbones; j++)
  3690. {
  3691. for (k = 0; k < g_numRenameBoneSubstr; k++)
  3692. {
  3693. char temp[MAXSTUDIONAME];
  3694. if ( V_stristr( g_source[i]->localBone[j].name, g_szRenameBoneSubstr[k].from ) && !V_stristr( g_source[i]->localBone[j].name, g_szRenameBoneSubstr[k].to ) )
  3695. {
  3696. V_strcpy( temp, g_source[i]->localBone[j].name );
  3697. V_StrSubst( temp, g_szRenameBoneSubstr[k].from, g_szRenameBoneSubstr[k].to, g_source[i]->localBone[j].name, sizeof( g_source[i]->localBone[j].name ) );
  3698. continue;
  3699. }
  3700. }
  3701. for (k = 0; k < g_numrenamedbones; k++)
  3702. {
  3703. if (!stricmp( g_source[i]->localBone[j].name, g_renamedbone[k].from))
  3704. {
  3705. strcpy( g_source[i]->localBone[j].name, g_renamedbone[k].to );
  3706. break;
  3707. }
  3708. }
  3709. }
  3710. }
  3711. }
  3712. const char *RenameBone( const char *pName )
  3713. {
  3714. // check for prefixes to strip
  3715. for ( int k = 0; k < g_numStripBonePrefixes; k++)
  3716. {
  3717. if ( !Q_strncmp( pName, g_szStripBonePrefix[k], V_strlen( g_szStripBonePrefix[k] ) ) )
  3718. {
  3719. //Msg("Stripping bone prefix %s from %s\n", g_szStripBonePrefix[k], pName );
  3720. // recurse in case we're removing more than one prefix? Not sure if this is necessary, but maybe you want to remove "Alpha" then "Beta" from bone "AlphaBetaCharlie" ?
  3721. return RenameBone( pName + V_strlen( g_szStripBonePrefix[k] ) );
  3722. }
  3723. }
  3724. for ( int k = 0; k < g_numrenamedbones; k++)
  3725. {
  3726. if ( !Q_stricmp( pName, g_renamedbone[k].from ) )
  3727. return g_renamedbone[k].to;
  3728. }
  3729. return pName;
  3730. }
  3731. void InsertPredefinedBones( bool bUnlocked )
  3732. {
  3733. int i, k;
  3734. for (i = 0; i < g_numimportbones; i++)
  3735. {
  3736. if ( g_importbone[i].bUnlocked != bUnlocked )
  3737. continue;
  3738. k = findGlobalBone( g_importbone[i].name );
  3739. if (k == -1)
  3740. {
  3741. k = g_numbones;
  3742. strcpyn( g_bonetable[k].name, g_importbone[i].name );
  3743. if ( strlen( g_importbone[i].parent ) == 0 )
  3744. {
  3745. g_bonetable[k].parent = -1;
  3746. }
  3747. else
  3748. {
  3749. // FIXME: This won't work if the imported bone refers to
  3750. // another imported bone which is further along in the list
  3751. g_bonetable[k].parent = findGlobalBone( g_importbone[i].parent );
  3752. if ( g_bonetable[k].parent == -1 )
  3753. {
  3754. Warning("Imported bone %s tried to access parent bone %s and failed!\n",
  3755. g_importbone[i].name, g_importbone[i].parent );
  3756. }
  3757. }
  3758. g_bonetable[k].bPreDefined = true;
  3759. g_bonetable[k].rawLocal = g_importbone[i].rawLocal;
  3760. g_bonetable[k].rawLocalOriginal = g_bonetable[k].rawLocal;
  3761. g_numbones++;
  3762. }
  3763. g_bonetable[k].bDontCollapse = true;
  3764. g_bonetable[k].srcRealign = g_importbone[i].srcRealign;
  3765. g_bonetable[k].bPreAligned = g_importbone[i].bPreAligned;
  3766. }
  3767. // ensure bonemerged bones are tagged
  3768. for ( i = 0; i < g_numbones; i++ )
  3769. {
  3770. for ( k = 0; k < g_BoneMerge.Count(); k++ )
  3771. {
  3772. if ( !(g_bonetable[i].flags & BONE_USED_BY_BONE_MERGE) && !stricmp( g_BoneMerge[k].bonename, g_bonetable[i].name ) )
  3773. {
  3774. g_bonetable[i].flags |= BONE_USED_BY_BONE_MERGE;
  3775. }
  3776. }
  3777. }
  3778. // ensure alwayssetup bones are tagged
  3779. for ( i = 0; i < g_numbones; i++ )
  3780. {
  3781. for ( k = 0; k < g_BoneAlwaysSetup.Count(); k++ )
  3782. {
  3783. if ( !(g_bonetable[i].flags & BONE_ALWAYS_SETUP) && !stricmp( g_BoneAlwaysSetup[k].bonename, g_bonetable[i].name ) )
  3784. {
  3785. g_bonetable[i].flags |= BONE_ALWAYS_SETUP;
  3786. }
  3787. }
  3788. }
  3789. }
  3790. //-----------------------------------------------------------------------------
  3791. // Purpose: look through all the sources and build a table of used bones
  3792. //-----------------------------------------------------------------------------
  3793. int BuildGlobalBonetable( )
  3794. {
  3795. int i, j, k, n;
  3796. int iError = 0;
  3797. g_numbones = 0;
  3798. for (i = 0; i < MAXSTUDIOSRCBONES; i++)
  3799. {
  3800. SetIdentityMatrix( g_bonetable[i].srcRealign );
  3801. }
  3802. InsertPredefinedBones( false );
  3803. // union of all used bones
  3804. for ( i = 0; i < g_numsources; i++ )
  3805. {
  3806. s_source_t *psource = g_source[i];
  3807. // skip sources with no bones
  3808. if (psource->numbones == 0)
  3809. continue;
  3810. matrix3x4_t srcBoneToWorld[MAXSTUDIOSRCBONES];
  3811. s_sourceanim_t *pSourceAnim = FindSourceAnim( psource, "BindPose" );
  3812. if ( !pSourceAnim )
  3813. {
  3814. pSourceAnim = &psource->m_Animations[0];
  3815. }
  3816. BuildRawTransforms( psource, pSourceAnim->animationname, 0, srcBoneToWorld );
  3817. for ( j = 0; j < psource->numbones; j++ )
  3818. {
  3819. if ( g_collapse_bones_aggressive )
  3820. {
  3821. if ( psource->boneflags[j] == 0 )
  3822. continue;
  3823. }
  3824. else
  3825. {
  3826. if ( psource->boneref[j] == 0 )
  3827. continue;
  3828. }
  3829. k = findGlobalBone( psource->localBone[j].name );
  3830. if (k == -1)
  3831. {
  3832. // create new bone
  3833. k = g_numbones;
  3834. strcpyn( g_bonetable[k].name, psource->localBone[j].name );
  3835. if ((n = psource->localBone[j].parent) != -1)
  3836. g_bonetable[k].parent = findGlobalBone( psource->localBone[n].name );
  3837. else
  3838. g_bonetable[k].parent = -1;
  3839. g_bonetable[k].bonecontroller = 0;
  3840. g_bonetable[k].flags = psource->boneflags[j];
  3841. if ( g_bonetable[k].parent == -1 || !g_bonetable[g_bonetable[k].parent].bPreAligned )
  3842. {
  3843. AngleMatrix( pSourceAnim->rawanim[0][j].rot, pSourceAnim->rawanim[0][j].pos, g_bonetable[k].rawLocal );
  3844. g_bonetable[k].rawLocalOriginal = g_bonetable[k].rawLocal;
  3845. }
  3846. else
  3847. {
  3848. // convert the local relative position into a realigned relative position
  3849. matrix3x4_t srcParentBoneToWorld;
  3850. ConcatTransforms( srcBoneToWorld[n], g_bonetable[g_bonetable[k].parent].srcRealign, srcParentBoneToWorld );
  3851. matrix3x4_t invSrcParentBoneToWorld;
  3852. MatrixInvert( srcParentBoneToWorld, invSrcParentBoneToWorld );
  3853. ConcatTransforms( invSrcParentBoneToWorld, srcBoneToWorld[j], g_bonetable[k].rawLocal );
  3854. }
  3855. g_bonetable[k].boneToPose.Invalidate();
  3856. for (int n = 0; n < g_numimportbones; n++)
  3857. {
  3858. if (!Q_stricmp( g_bonetable[k].name, g_importbone[n].name ))
  3859. {
  3860. g_bonetable[k].bDontCollapse = true;
  3861. }
  3862. }
  3863. // printf("%d : %s (%s)\n", k, g_bonetable[k].name, g_bonetable[g_bonetable[k].parent].name );
  3864. g_numbones++;
  3865. continue;
  3866. }
  3867. // accumlate flags
  3868. g_bonetable[k].flags |= psource->boneflags[j];
  3869. }
  3870. }
  3871. InsertPredefinedBones( true );
  3872. return iError;
  3873. }
  3874. //-----------------------------------------------------------------------------
  3875. // Purpose:
  3876. //-----------------------------------------------------------------------------
  3877. void BuildGlobalBoneToPose( )
  3878. {
  3879. int k;
  3880. // build reference pose
  3881. for (k = 0; k < g_numbones; k++)
  3882. {
  3883. if (g_bonetable[k].parent == -1)
  3884. {
  3885. MatrixCopy( g_bonetable[k].rawLocal, g_bonetable[k].boneToPose );
  3886. }
  3887. else
  3888. {
  3889. ConcatTransforms (g_bonetable[g_bonetable[k].parent].boneToPose, g_bonetable[k].rawLocal, g_bonetable[k].boneToPose);
  3890. }
  3891. }
  3892. }
  3893. //-----------------------------------------------------------------------------
  3894. // Purpose:
  3895. //-----------------------------------------------------------------------------
  3896. void RebuildLocalPose( )
  3897. {
  3898. int k;
  3899. matrix3x4_t boneToPose[MAXSTUDIOBONES];
  3900. // build reference pose
  3901. for (k = 0; k < g_numbones; k++)
  3902. {
  3903. MatrixCopy( g_bonetable[k].boneToPose, boneToPose[k] );
  3904. }
  3905. matrix3x4_t poseToBone[MAXSTUDIOBONES];
  3906. // rebuild local pose
  3907. for (k = 0; k < g_numbones; k++)
  3908. {
  3909. if (g_bonetable[k].parent == -1)
  3910. {
  3911. MatrixCopy( boneToPose[k], g_bonetable[k].rawLocal );
  3912. }
  3913. else
  3914. {
  3915. ConcatTransforms (poseToBone[g_bonetable[k].parent], boneToPose[k], g_bonetable[k].rawLocal );
  3916. }
  3917. MatrixAngles( g_bonetable[k].rawLocal, g_bonetable[k].rot, g_bonetable[k].pos );
  3918. MatrixCopy( boneToPose[k], g_bonetable[k].boneToPose );
  3919. MatrixInvert( boneToPose[k], poseToBone[k] );
  3920. // printf("%d \"%s\" %d\n", k, g_bonetable[k].name, g_bonetable[k].parent );
  3921. }
  3922. //exit(0);
  3923. }
  3924. //-----------------------------------------------------------------------------
  3925. // Purpose: attach bones to different parents if needed
  3926. //-----------------------------------------------------------------------------
  3927. void EnforceHierarchy( )
  3928. {
  3929. int i, j, k;
  3930. // force changes to hierarchy
  3931. for (i = 0; i < g_numforcedhierarchy; i++)
  3932. {
  3933. j = findGlobalBone( g_forcedhierarchy[i].parentname );
  3934. k = findGlobalBone( g_forcedhierarchy[i].childname );
  3935. if (j == -1 && strlen( g_forcedhierarchy[i].parentname ) > 0 )
  3936. {
  3937. MdlError( "unknown bone: \"%s\" in forced hierarchy\n", g_forcedhierarchy[i].parentname );
  3938. }
  3939. if (k == -1)
  3940. {
  3941. MdlError( "unknown bone: \"%s\" in forced hierarchy\n", g_forcedhierarchy[i].childname );
  3942. }
  3943. /*
  3944. if (j > k)
  3945. {
  3946. MdlError( "parent \"%s\" declared after child \"%s\" in forced hierarchy\n", g_forcedhierarchy[i].parentname, g_forcedhierarchy[i].childname );
  3947. }
  3948. */
  3949. /*
  3950. if (strlen(g_forcedhierarchy[i].subparentname) != 0)
  3951. {
  3952. int n, m;
  3953. m = findGlobalBone( g_forcedhierarchy[i].subparentname );
  3954. if (m != -1)
  3955. {
  3956. MdlError( "inserted bone \"%s\" matches name of existing bone in hierarchy\n", g_forcedhierarchy[i].parentname, g_forcedhierarchy[i].subparentname );
  3957. }
  3958. printf("inserting bone \"%s\"\n", g_forcedhierarchy[i].subparentname );
  3959. // shift the bone list up
  3960. for (n = g_numbones; n > k; n--)
  3961. {
  3962. g_bonetable[n] = g_bonetable[n-1];
  3963. if (g_bonetable[n].parent >= k)
  3964. {
  3965. g_bonetable[n].parent = g_bonetable[n].parent + 1;
  3966. }
  3967. MatrixCopy( boneToPose[n-1], boneToPose[n] );
  3968. }
  3969. g_numbones++;
  3970. // add the bone
  3971. strcpy( g_bonetable[k].name, g_forcedhierarchy[i].subparentname );
  3972. g_bonetable[k].parent = j;
  3973. g_bonetable[k].split = true;
  3974. g_bonetable[k+1].parent = k;
  3975. // split the bone
  3976. Quaternion q1, q2;
  3977. Vector p;
  3978. MatrixAngles( boneToPose[k], q1, p ); // FIXME: badly named!
  3979. // !!!!
  3980. // QuaternionScale( q1, 0.5, q2 );
  3981. // q2.Init( 0, 0, 0, 1 );
  3982. // AngleQuaternion( QAngle( 0, 0, 0 ), q2 );
  3983. //QuaternionMatrix( q2, p, boneToPose[k] );
  3984. QuaternionMatrix( q1, p, boneToPose[k] );
  3985. QuaternionMatrix( q1, p, boneToPose[k+1] );
  3986. }
  3987. else
  3988. */
  3989. {
  3990. g_bonetable[k].parent = j;
  3991. }
  3992. }
  3993. // resort hierarchy
  3994. bool bSort = true;
  3995. int count = 0;
  3996. while (bSort)
  3997. {
  3998. count++;
  3999. bSort = false;
  4000. for (i = 0; i < g_numbones; i++)
  4001. {
  4002. if (g_bonetable[i].parent > i)
  4003. {
  4004. // swap
  4005. j = g_bonetable[i].parent;
  4006. s_bonetable_t tmp;
  4007. tmp = g_bonetable[i];
  4008. g_bonetable[i] = g_bonetable[j];
  4009. g_bonetable[j] = tmp;
  4010. // relink parents
  4011. for (k = i; k < g_numbones; k++)
  4012. {
  4013. if (g_bonetable[k].parent == i)
  4014. {
  4015. g_bonetable[k].parent = j;
  4016. }
  4017. else if (g_bonetable[k].parent == j)
  4018. {
  4019. g_bonetable[k].parent = i;
  4020. }
  4021. }
  4022. bSort = true;
  4023. }
  4024. }
  4025. if (count > 1000)
  4026. {
  4027. MdlError( "Circular bone hierarchy\n");
  4028. }
  4029. }
  4030. }
  4031. //-----------------------------------------------------------------------------
  4032. // Purpose: Find constraint bones and tag for inclusion
  4033. //-----------------------------------------------------------------------------
  4034. static void TagConstraintBones()
  4035. {
  4036. // Iterate backwards so invalid elements can be removed
  4037. for ( int i = g_constraintBones.Count() - 1; i >= 0; --i )
  4038. {
  4039. CConstraintBoneBase *pConstraintBone = g_constraintBones[i];
  4040. if ( !pConstraintBone )
  4041. {
  4042. g_constraintBones.Remove( i );
  4043. continue;
  4044. }
  4045. pConstraintBone->m_slave.m_nBone = findGlobalBone( pConstraintBone->m_slave.m_szBoneName );
  4046. if ( pConstraintBone->m_slave.m_nBone < 0 )
  4047. {
  4048. g_constraintBones.Remove( i );
  4049. continue;
  4050. }
  4051. g_bonetable[pConstraintBone->m_slave.m_nBone].flags |= BONE_ALWAYS_PROCEDURAL;
  4052. for ( int j = pConstraintBone->m_targets.Count() - 1; j >= 0; --j )
  4053. {
  4054. s_constraintbonetarget_t &target = pConstraintBone->m_targets[j];
  4055. target.m_nBone = findGlobalBone( target.m_szBoneName );
  4056. if ( target.m_nBone < 0 )
  4057. {
  4058. pConstraintBone->m_targets.Remove( j );
  4059. }
  4060. }
  4061. if ( pConstraintBone->m_targets.Count() <= 0 )
  4062. {
  4063. g_constraintBones.Remove( i );
  4064. }
  4065. CAimConstraint *pAimConstraint = dynamic_cast< CAimConstraint * >( pConstraintBone );
  4066. if ( pAimConstraint )
  4067. {
  4068. pAimConstraint->m_nUpSpaceTargetBone = findGlobalBone( pAimConstraint->m_szUpSpaceTargetBone );
  4069. }
  4070. }
  4071. }
  4072. //-----------------------------------------------------------------------------
  4073. // Purpose: find procedural bones and tag for inclusion even if they don't animate
  4074. //-----------------------------------------------------------------------------
  4075. void TagProceduralBones( )
  4076. {
  4077. int j;
  4078. // look for AxisInterp bone definitions
  4079. int numaxisinterpbones = 0;
  4080. for (j = 0; j < g_numaxisinterpbones; j++)
  4081. {
  4082. g_axisinterpbones[j].bone = findGlobalBone( g_axisinterpbones[j].bonename );
  4083. g_axisinterpbones[j].control = findGlobalBone( g_axisinterpbones[j].controlname );
  4084. if (g_axisinterpbones[j].bone == -1)
  4085. {
  4086. if (!g_quiet)
  4087. {
  4088. printf("axisinterpbone \"%s\" unused\n", g_axisinterpbones[j].bonename );
  4089. }
  4090. continue; // optimized out, don't complain
  4091. }
  4092. if (g_axisinterpbones[j].control == -1)
  4093. {
  4094. MdlError( "Missing control bone \"%s\" for procedural bone \"%s\"\n", g_axisinterpbones[j].bonename, g_axisinterpbones[j].controlname );
  4095. }
  4096. g_bonetable[g_axisinterpbones[j].bone].flags |= BONE_ALWAYS_PROCEDURAL; // ??? what about physics rules
  4097. g_axisinterpbonemap[numaxisinterpbones++] = j;
  4098. }
  4099. g_numaxisinterpbones = numaxisinterpbones;
  4100. // look for QuatInterp bone definitions
  4101. int numquatinterpbones = 0;
  4102. for (j = 0; j < g_numquatinterpbones; j++)
  4103. {
  4104. g_quatinterpbones[j].bone = findGlobalBoneXSI( g_quatinterpbones[j].bonename );
  4105. g_quatinterpbones[j].control = findGlobalBoneXSI( g_quatinterpbones[j].controlname );
  4106. if (g_quatinterpbones[j].bone == -1)
  4107. {
  4108. if (!g_quiet && !g_bCreateMakefile )
  4109. {
  4110. printf("quatinterpbone \"%s\" unused\n", g_quatinterpbones[j].bonename );
  4111. }
  4112. continue; // optimized out, don't complain
  4113. }
  4114. if (g_quatinterpbones[j].control == -1)
  4115. {
  4116. MdlError( "Missing control bone \"%s\" for procedural bone \"%s\"\n", g_quatinterpbones[j].bonename, g_quatinterpbones[j].controlname );
  4117. }
  4118. g_bonetable[g_quatinterpbones[j].bone].flags |= BONE_ALWAYS_PROCEDURAL; // ??? what about physics rules
  4119. g_quatinterpbonemap[numquatinterpbones++] = j;
  4120. }
  4121. g_numquatinterpbones = numquatinterpbones;
  4122. // look for AimAt bone definitions
  4123. int numaimatbones = 0;
  4124. for (j = 0; j < g_numaimatbones; j++)
  4125. {
  4126. g_aimatbones[j].bone = findGlobalBoneXSI( g_aimatbones[j].bonename );
  4127. if (g_aimatbones[j].bone == -1)
  4128. {
  4129. if (!g_quiet && !g_bCreateMakefile )
  4130. {
  4131. printf("<aimconstraint> \"%s\" unused\n", g_aimatbones[j].bonename );
  4132. }
  4133. continue; // optimized out, don't complain
  4134. }
  4135. g_aimatbones[j].parent = findGlobalBoneXSI( g_aimatbones[j].parentname );
  4136. if (g_aimatbones[j].parent == -1)
  4137. {
  4138. MdlError( "Missing parent control bone \"%s\" for procedural bone \"%s\"\n", g_aimatbones[j].parentname, g_aimatbones[j].bonename );
  4139. }
  4140. // Look for the aim bone as an attachment first
  4141. g_aimatbones[j].aimAttach = -1;
  4142. for ( int ai( 0 ); ai < g_numattachments; ++ai )
  4143. {
  4144. if ( strcmp( g_attachment[ ai ].name, g_aimatbones[j].aimname ) == 0 )
  4145. {
  4146. g_aimatbones[j].aimAttach = ai;
  4147. break;
  4148. }
  4149. }
  4150. if ( g_aimatbones[j].aimAttach == -1 )
  4151. {
  4152. g_aimatbones[j].aimBone = findGlobalBoneXSI( g_aimatbones[j].aimname );
  4153. if ( g_aimatbones[j].aimBone == -1 )
  4154. {
  4155. MdlError( "Missing aim control attachment or bone \"%s\" for procedural bone \"%s\"\n",
  4156. g_aimatbones[j].aimname, g_aimatbones[j].bonename );
  4157. }
  4158. }
  4159. g_bonetable[g_aimatbones[j].bone].flags |= BONE_ALWAYS_PROCEDURAL; // ??? what about physics rules
  4160. g_aimatbonemap[numaimatbones++] = j;
  4161. }
  4162. // look for Jiggle bone definitions
  4163. int numjigglebones = 0;
  4164. for (j = 0; j < g_numjigglebones; j++)
  4165. {
  4166. g_jigglebones[j].bone = findGlobalBone( g_jigglebones[j].bonename );
  4167. if (g_jigglebones[j].bone == -1)
  4168. {
  4169. if (!g_quiet)
  4170. {
  4171. printf("jigglebone \"%s\" unused\n", g_jigglebones[j].bonename );
  4172. }
  4173. continue; // optimized out, don't complain
  4174. }
  4175. g_bonetable[g_jigglebones[j].bone].flags |= BONE_ALWAYS_PROCEDURAL; // ??? what about physics rules
  4176. g_jigglebonemap[numjigglebones++] = j;
  4177. }
  4178. g_numjigglebones = numjigglebones;
  4179. // Look for twist bone defintions
  4180. // Iterate backwards so we can remove invalid elements
  4181. for ( j = g_twistbones.Count() - 1; j >= 0; --j )
  4182. {
  4183. CTwistBone &twistBone = g_twistbones.Element( j );
  4184. twistBone.m_nParentBone = findGlobalBone( twistBone.m_szParentBoneName );
  4185. if ( twistBone.m_nParentBone < 0 )
  4186. {
  4187. g_twistbones.Remove( j );
  4188. continue;
  4189. }
  4190. twistBone.m_nChildBone = findGlobalBone( twistBone.m_szChildBoneName );
  4191. if ( twistBone.m_nChildBone < 0 )
  4192. {
  4193. g_twistbones.Remove( j );
  4194. continue;
  4195. }
  4196. for ( int k = twistBone.m_twistBoneTargets.Count() - 1; k >= 0; --k )
  4197. {
  4198. s_constraintbonetarget_t &twistBoneTarget = twistBone.m_twistBoneTargets[k];
  4199. twistBoneTarget.m_nBone = findGlobalBone( twistBoneTarget.m_szBoneName );
  4200. if ( twistBoneTarget.m_nBone < 0 )
  4201. {
  4202. twistBone.m_twistBoneTargets.Remove( k );
  4203. }
  4204. else
  4205. {
  4206. g_bonetable[twistBoneTarget.m_nBone].flags |= BONE_ALWAYS_PROCEDURAL;
  4207. }
  4208. }
  4209. if ( twistBone.m_twistBoneTargets.Count() <= 0 )
  4210. {
  4211. g_twistbones.Remove( j );
  4212. }
  4213. }
  4214. TagConstraintBones();
  4215. }
  4216. //-----------------------------------------------------------------------------
  4217. //
  4218. //-----------------------------------------------------------------------------
  4219. void RealignBoneTranslation( Vector &vRealigned, int nBoneIndex, const Vector &vInput )
  4220. {
  4221. matrix3x4a_t mIdentity;
  4222. SetIdentityMatrix( mIdentity );
  4223. if ( nBoneIndex < 0 || nBoneIndex >= MAXSTUDIOSRCBONES )
  4224. return;
  4225. s_bonetable_t *pBone = &g_bonetable[ nBoneIndex ];
  4226. if ( !pBone )
  4227. return;
  4228. Vector vParentRealigned = vInput;
  4229. const int nParentBoneIndex = pBone->parent;
  4230. if ( nParentBoneIndex >= 0 && nBoneIndex < MAXSTUDIOSRCBONES )
  4231. {
  4232. s_bonetable_t *pParentBone = &g_bonetable[ nParentBoneIndex ];
  4233. if ( pParentBone )
  4234. {
  4235. if ( !MatricesAreEqual( mIdentity, pParentBone->srcRealign ) )
  4236. {
  4237. QuaternionAligned qParentSrcRealign;
  4238. MatrixQuaternion( pParentBone->srcRealign, qParentSrcRealign );
  4239. QuaternionAligned qParentSrcRealignInv;
  4240. QuaternionInvert( qParentSrcRealign, qParentSrcRealignInv );
  4241. VectorRotate( vInput, qParentSrcRealignInv, vParentRealigned );
  4242. }
  4243. }
  4244. }
  4245. vRealigned = vParentRealigned;
  4246. }
  4247. //-----------------------------------------------------------------------------
  4248. // Purpose: Realign Orientation of a rotation on a bone
  4249. // Applies the inverse of the parent's srcRealign and then the it's srcRealign
  4250. // if not the identity
  4251. //-----------------------------------------------------------------------------
  4252. void RealignBoneQuaternion( Quaternion &qRealigned, int nBoneIndex, const Quaternion &qInput )
  4253. {
  4254. matrix3x4a_t mIdentity;
  4255. SetIdentityMatrix( mIdentity );
  4256. if ( nBoneIndex < 0 || nBoneIndex >= MAXSTUDIOSRCBONES )
  4257. return;
  4258. s_bonetable_t *pBone = &g_bonetable[ nBoneIndex ];
  4259. if ( !pBone )
  4260. return;
  4261. Quaternion qParentRealigned = qInput;
  4262. const int nParentBoneIndex = pBone->parent;
  4263. if ( nParentBoneIndex >= 0 && nBoneIndex < MAXSTUDIOSRCBONES )
  4264. {
  4265. s_bonetable_t *pParentBone = &g_bonetable[ nParentBoneIndex ];
  4266. if ( pParentBone )
  4267. {
  4268. if ( !MatricesAreEqual( mIdentity, pParentBone->srcRealign ) )
  4269. {
  4270. matrix3x4a_t mSrcRealignInv;
  4271. MatrixInvert( pParentBone->srcRealign, mSrcRealignInv );
  4272. Quaternion qSrcRealignInv;
  4273. MatrixQuaternion( mSrcRealignInv, qSrcRealignInv );
  4274. QuaternionMult( qSrcRealignInv, qInput, qParentRealigned );
  4275. }
  4276. }
  4277. }
  4278. if ( !MatricesAreEqual( mIdentity, pBone->srcRealign ) )
  4279. {
  4280. Quaternion qSrcRealign;
  4281. MatrixQuaternion( pBone->srcRealign, qSrcRealign );
  4282. QuaternionMult( qParentRealigned, qSrcRealign, qRealigned );
  4283. }
  4284. else
  4285. {
  4286. qRealigned = qParentRealigned;
  4287. }
  4288. }
  4289. //-----------------------------------------------------------------------------
  4290. //
  4291. //-----------------------------------------------------------------------------
  4292. static void RemapConstraintBones()
  4293. {
  4294. const Quaternion qRot = Quaternion( g_defaultrotation );
  4295. Vector vTmp;
  4296. for ( int i = 0; i < g_constraintBones.Count(); ++i )
  4297. {
  4298. CConstraintBoneBase *pConstraintBone = g_constraintBones[i];
  4299. if ( !pConstraintBone )
  4300. continue;
  4301. for ( int j = 0; j < pConstraintBone->m_targets.Count(); ++j )
  4302. {
  4303. s_constraintbonetarget_t &target = pConstraintBone->m_targets[j];
  4304. const int nBoneIndex = findGlobalBone( target.m_szBoneName );
  4305. if ( nBoneIndex < 0 || nBoneIndex != target.m_nBone )
  4306. {
  4307. MdlError( "<constraintbone> Can't find target bone \"%s\"\n", target.m_szBoneName );
  4308. }
  4309. if ( !dynamic_cast< CPointConstraint * >( pConstraintBone ) )
  4310. {
  4311. RealignBoneTranslation( target.m_vOffset, nBoneIndex, target.m_vOffset );
  4312. RealignBoneQuaternion( target.m_qOffset, nBoneIndex, target.m_qOffset );
  4313. }
  4314. else
  4315. {
  4316. // target offsets are in world space...
  4317. }
  4318. }
  4319. {
  4320. s_constraintboneslave_t &slave = pConstraintBone->m_slave;
  4321. const int nBoneIndex = findGlobalBone( slave.m_szBoneName );
  4322. if ( nBoneIndex < 0 || nBoneIndex != slave.m_nBone )
  4323. {
  4324. MdlError( "<constraintbone> Can't find slave bone \"%s\"\n", slave.m_szBoneName );
  4325. }
  4326. s_bonetable_t *pBone = &g_bonetable[ nBoneIndex ];
  4327. if ( pBone )
  4328. {
  4329. if ( pBone->parent < 0 )
  4330. {
  4331. // No parent
  4332. VectorRotate( slave.m_vBaseTranslate, qRot, vTmp );
  4333. slave.m_vBaseTranslate = vTmp;
  4334. }
  4335. else
  4336. {
  4337. RealignBoneTranslation( slave.m_vBaseTranslate, nBoneIndex, slave.m_vBaseTranslate );
  4338. }
  4339. RealignBoneQuaternion( slave.m_qBaseRotation, nBoneIndex, slave.m_qBaseRotation );
  4340. }
  4341. }
  4342. }
  4343. }
  4344. //-----------------------------------------------------------------------------
  4345. // Purpose: convert original procedural bone info into correct values for existing skeleton
  4346. //-----------------------------------------------------------------------------
  4347. void RemapProceduralBones( )
  4348. {
  4349. int j;
  4350. // look for QuatInterp bone definitions
  4351. for (j = 0; j < g_numquatinterpbones; j++)
  4352. {
  4353. s_quatinterpbone_t *pInterp = &g_quatinterpbones[g_quatinterpbonemap[j]];
  4354. int origParent = findGlobalBoneXSI( pInterp->parentname );
  4355. int origControlParent = findGlobalBoneXSI( pInterp->controlparentname );
  4356. if (origParent == -1)
  4357. {
  4358. MdlError( "procedural bone \"%s\", can't find orig parent \"%s\"\n\n", pInterp->bonename, pInterp->parentname );
  4359. }
  4360. if (origControlParent == -1)
  4361. {
  4362. MdlError( "procedural bone \"%s\", can't find control parent \"%s\n\n", pInterp->bonename, pInterp->controlparentname );
  4363. }
  4364. if ( g_bonetable[pInterp->bone].parent != origParent)
  4365. {
  4366. MdlError( "unknown procedural bone parent remapping\n" );
  4367. }
  4368. if ( g_bonetable[pInterp->control].parent != origControlParent)
  4369. {
  4370. MdlError( "procedural bone \"%s\", parent remapping error, control parent was \"%s\", is now \"%s\"\n",
  4371. pInterp->bonename,
  4372. pInterp->controlparentname,
  4373. g_bonetable[g_bonetable[pInterp->control].parent].name );
  4374. }
  4375. // remap triggers and movements/rotations due to skeleton changes and realignment
  4376. for (int k = 0; k < pInterp->numtriggers; k++)
  4377. {
  4378. int parent = g_bonetable[pInterp->control].parent;
  4379. // triggers are the "control" bone relative to the control's parent bone
  4380. if (parent != -1)
  4381. {
  4382. matrix3x4_t invControlParentRealign;
  4383. MatrixInvert( g_bonetable[parent].srcRealign, invControlParentRealign );
  4384. matrix3x4_t srcControlParentBoneToPose;
  4385. ConcatTransforms( g_bonetable[parent].boneToPose, invControlParentRealign, srcControlParentBoneToPose );
  4386. matrix3x4_t srcControlRelative;
  4387. QuaternionMatrix( pInterp->trigger[k], srcControlRelative );
  4388. matrix3x4_t srcControlBoneToPose;
  4389. ConcatTransforms( srcControlParentBoneToPose, srcControlRelative, srcControlBoneToPose );
  4390. matrix3x4_t destControlParentBoneToPose;
  4391. ConcatTransforms( srcControlParentBoneToPose, g_bonetable[parent].srcRealign, destControlParentBoneToPose );
  4392. matrix3x4_t destControlBoneToPose;
  4393. ConcatTransforms( srcControlBoneToPose, g_bonetable[pInterp->control].srcRealign, destControlBoneToPose );
  4394. matrix3x4_t invDestControlParentBoneToPose;
  4395. MatrixInvert( destControlParentBoneToPose, invDestControlParentBoneToPose );
  4396. matrix3x4_t destControlRelative;
  4397. ConcatTransforms( invDestControlParentBoneToPose, destControlBoneToPose, destControlRelative );
  4398. Vector tmp;
  4399. MatrixAngles( destControlRelative, pInterp->trigger[k], tmp );
  4400. /*
  4401. Vector pos;
  4402. RadianEuler angles;
  4403. MatrixAngles( srcControlRelative, angles, pos );
  4404. printf("srcControlRelative : %7.2f %7.2f %7.2f\n", RAD2DEG( angles.x ), RAD2DEG( angles.y ), RAD2DEG( angles.z ) );
  4405. MatrixAngles( destControlRelative, angles, pos );
  4406. printf("destControlRelative : %7.2f %7.2f %7.2f\n", RAD2DEG( angles.x ), RAD2DEG( angles.y ), RAD2DEG( angles.z ) );
  4407. printf("\n");
  4408. */
  4409. }
  4410. // movements are relative to the bone's parent
  4411. parent = g_bonetable[pInterp->bone].parent;
  4412. if (parent != -1)
  4413. {
  4414. //printf("procedural bone \"%s\"\n", pInterp->bonename );
  4415. //printf("pre : %7.2f %7.2f %7.2f\n", pInterp->pos[k].x, pInterp->pos[k].y, pInterp->pos[k].z );
  4416. // get local transform
  4417. matrix3x4_t srcParentRelative;
  4418. QuaternionMatrix( pInterp->quat[k], pInterp->pos[k] + pInterp->basepos, srcParentRelative );
  4419. // get original boneToPose
  4420. matrix3x4_t invSrcRealign;
  4421. MatrixInvert( g_bonetable[parent].srcRealign, invSrcRealign );
  4422. matrix3x4_t origParentBoneToPose;
  4423. ConcatTransforms( g_bonetable[parent].boneToPose, invSrcRealign, origParentBoneToPose );
  4424. // move bone adjustment into world position
  4425. matrix3x4_t srcBoneToWorld;
  4426. ConcatTransforms( origParentBoneToPose, srcParentRelative, srcBoneToWorld );
  4427. // calculate local transform
  4428. matrix3x4_t parentPoseToBone;
  4429. MatrixInvert( g_bonetable[parent].boneToPose, parentPoseToBone );
  4430. matrix3x4_t destBoneToWorld;
  4431. ConcatTransforms( parentPoseToBone, srcBoneToWorld, destBoneToWorld );
  4432. // save out the local transform
  4433. MatrixAngles( destBoneToWorld, pInterp->quat[k], pInterp->pos[k] );
  4434. pInterp->pos[k] += g_bonetable[pInterp->control].pos * pInterp->percentage;
  4435. //printf("post : %7.2f %7.2f %7.2f\n", pInterp->pos[k].x, pInterp->pos[k].y, pInterp->pos[k].z );
  4436. }
  4437. }
  4438. }
  4439. // look for aimatbones
  4440. for (j = 0; j < g_numaimatbones; j++)
  4441. {
  4442. s_aimatbone_t *pAimAtBone = &g_aimatbones[g_aimatbonemap[j]];
  4443. int origParent = findGlobalBoneXSI( pAimAtBone->parentname );
  4444. if (origParent == -1)
  4445. {
  4446. MdlError( "<aimconstraint> bone \"%s\", can't find parent bone \"%s\"\n\n", pAimAtBone->bonename, pAimAtBone->parentname );
  4447. }
  4448. int origAim( -1 );
  4449. for ( int ai( 0 ); ai < g_numattachments; ++ai )
  4450. {
  4451. if ( strcmp( g_attachment[ ai ].name, pAimAtBone->aimname ) == 0 )
  4452. {
  4453. origAim = ai;
  4454. break;
  4455. }
  4456. }
  4457. if (origAim == -1)
  4458. {
  4459. MdlError( "<aimconstraint> bone \"%s\", can't find aim bone \"%s\n\n", pAimAtBone->bonename, pAimAtBone->aimname );
  4460. }
  4461. }
  4462. // Look at Twist bones
  4463. for ( j = g_twistbones.Count() - 1; j >= 0; --j )
  4464. {
  4465. CTwistBone &twistBone = g_twistbones[j];
  4466. const int nParent = findGlobalBoneXSI( twistBone.m_szParentBoneName );
  4467. if ( nParent < 0 )
  4468. {
  4469. MdlError( "<twistbone> Can't find parent bone \"%s\"\n", twistBone.m_szParentBoneName );
  4470. }
  4471. const int nChild = findGlobalBoneXSI( twistBone.m_szChildBoneName );
  4472. if ( nChild < 0 )
  4473. {
  4474. MdlError( "<twistbone> Can't find child bone \"%s\"\n", twistBone.m_szChildBoneName );
  4475. }
  4476. QuaternionAligned qParentSrcRealign;
  4477. MatrixQuaternion( g_bonetable[nParent].srcRealign, qParentSrcRealign );
  4478. QuaternionAligned qParentSrcRealignInv;
  4479. QuaternionInvert( qParentSrcRealign, qParentSrcRealignInv );
  4480. Vector vTmp;
  4481. QuaternionAligned qTmp;
  4482. if ( twistBone.m_bInverse )
  4483. {
  4484. RealignBoneQuaternion( twistBone.m_qBaseRotation, nParent, twistBone.m_qBaseRotation );
  4485. VectorRotate( twistBone.m_vUpVector, qParentSrcRealignInv, vTmp );
  4486. twistBone.m_vUpVector = vTmp;
  4487. }
  4488. else
  4489. {
  4490. QuaternionAligned qChildSrcRealign;
  4491. MatrixQuaternion( g_bonetable[nChild].srcRealign, qChildSrcRealign );
  4492. QuaternionAligned qChildSrcRealignInv;
  4493. QuaternionInvert( qChildSrcRealign, qChildSrcRealignInv );
  4494. RealignBoneQuaternion( twistBone.m_qBaseRotation, nChild, twistBone.m_qBaseRotation );
  4495. VectorRotate( twistBone.m_vUpVector, qChildSrcRealignInv, vTmp );
  4496. twistBone.m_vUpVector = vTmp;
  4497. }
  4498. for ( int k = twistBone.m_twistBoneTargets.Count() - 1; k >= 0; --k )
  4499. {
  4500. s_constraintbonetarget_t &twistBoneTarget = twistBone.m_twistBoneTargets[k];
  4501. const int nBoneIndex = findGlobalBoneXSI( twistBoneTarget.m_szBoneName );
  4502. if ( nBoneIndex < 0 )
  4503. {
  4504. MdlError( "<twistbone> Can't find target bone \"%s\"\n", twistBoneTarget.m_szBoneName );
  4505. }
  4506. VectorRotate( twistBoneTarget.m_vOffset, qParentSrcRealignInv, vTmp );
  4507. twistBoneTarget.m_vOffset = vTmp;
  4508. RealignBoneQuaternion( twistBoneTarget.m_qOffset, nBoneIndex, twistBoneTarget.m_qOffset );
  4509. }
  4510. }
  4511. // Handle constraint bones
  4512. RemapConstraintBones();
  4513. }
  4514. //-----------------------------------------------------------------------------
  4515. // Purpose: propogate procedural bone usage up its chain
  4516. //-----------------------------------------------------------------------------
  4517. void MarkProceduralBoneChain()
  4518. {
  4519. int j;
  4520. int k;
  4521. int fBoneFlags;
  4522. // look for QuatInterp bone definitions
  4523. for (j = 0; j < g_numquatinterpbones; j++)
  4524. {
  4525. s_quatinterpbone_t *pInterp = &g_quatinterpbones[g_quatinterpbonemap[j]];
  4526. fBoneFlags = g_bonetable[pInterp->bone].flags & BONE_USED_MASK;
  4527. // propogate the procedural bone usage up its hierarchy
  4528. k = pInterp->control;
  4529. while (k != -1)
  4530. {
  4531. g_bonetable[k].flags |= fBoneFlags;
  4532. k = g_bonetable[k].parent;
  4533. }
  4534. // propogate the procedural bone usage up its hierarchy
  4535. k = pInterp->bone;
  4536. while (k != -1)
  4537. {
  4538. g_bonetable[k].flags |= fBoneFlags;
  4539. k = g_bonetable[k].parent;
  4540. }
  4541. }
  4542. }
  4543. //-----------------------------------------------------------------------------
  4544. // Purpose: go through all source files and link local bone indices and global bonetable indicies
  4545. //-----------------------------------------------------------------------------
  4546. static int MapSourcesToGlobalBonetable( )
  4547. {
  4548. int i, j, k;
  4549. int iError = 0;
  4550. // map each source bone list to master list
  4551. for (i = 0; i < g_numsources; i++)
  4552. {
  4553. s_source_t *pSource = g_source[i];
  4554. memset( pSource->boneLocalToGlobal, 0xFF, sizeof(pSource->boneLocalToGlobal) );
  4555. memset( pSource->boneGlobalToLocal, 0xFF, sizeof(pSource->boneGlobalToLocal) );
  4556. for ( j = 0; j < pSource->numbones; j++ )
  4557. {
  4558. k = findGlobalBone( pSource->localBone[j].name );
  4559. if ( k >= 0 )
  4560. {
  4561. pSource->boneLocalToGlobal[j] = k;
  4562. pSource->boneGlobalToLocal[k] = j;
  4563. continue;
  4564. }
  4565. int m = pSource->localBone[j].parent;
  4566. while ( m != -1 && ( k = findGlobalBone( pSource->localBone[m].name ) ) == -1 )
  4567. {
  4568. m = pSource->localBone[m].parent;
  4569. }
  4570. if (k == -1)
  4571. {
  4572. /*
  4573. if (!g_quiet)
  4574. {
  4575. printf("unable to find connection for collapsed bone \"%s\" \n", pSource->localBone[j].name );
  4576. }
  4577. */
  4578. k = 0;
  4579. }
  4580. pSource->boneLocalToGlobal[j] = k;
  4581. }
  4582. }
  4583. return iError;
  4584. }
  4585. //-----------------------------------------------------------------------------
  4586. // Purpose: go through bone and find any that arent aligned on the X axis
  4587. //-----------------------------------------------------------------------------
  4588. void RealignBones( )
  4589. {
  4590. int k;
  4591. int childbone[MAXSTUDIOBONES];
  4592. for (k = 0; k < g_numbones; k++)
  4593. {
  4594. childbone[k] = -1;
  4595. }
  4596. // force bones with IK rules to realign themselves
  4597. for (int i = 0; i < g_numikchains; i++)
  4598. {
  4599. k = g_ikchain[i].link[0].bone;
  4600. if (childbone[k] == -1 || childbone[k] == g_ikchain[i].link[1].bone)
  4601. {
  4602. childbone[k] = g_ikchain[i].link[1].bone;
  4603. }
  4604. else
  4605. {
  4606. MdlError("Trying to realign bone \"%s\" with two children \"%s\", \"%s\"\n",
  4607. g_bonetable[k].name, g_bonetable[childbone[k]].name, g_bonetable[g_ikchain[i].link[1].bone].name );
  4608. }
  4609. k = g_ikchain[i].link[1].bone;
  4610. if (childbone[k] == -1 || childbone[k] == g_ikchain[i].link[2].bone)
  4611. {
  4612. childbone[k] = g_ikchain[i].link[2].bone;
  4613. }
  4614. else
  4615. {
  4616. MdlError("Trying to realign bone \"%s\" with two children \"%s\", \"%s\"\n",
  4617. g_bonetable[k].name, g_bonetable[childbone[k]].name, g_bonetable[g_ikchain[i].link[2].bone].name );
  4618. }
  4619. }
  4620. if (g_realignbones)
  4621. {
  4622. int children[MAXSTUDIOBONES];
  4623. // count children
  4624. for (k = 0; k < g_numbones; k++)
  4625. {
  4626. children[k] = 0;
  4627. }
  4628. for (k = 0; k < g_numbones; k++)
  4629. {
  4630. if (g_bonetable[k].parent != -1)
  4631. {
  4632. children[g_bonetable[k].parent]++;
  4633. }
  4634. }
  4635. // if my parent bone only has one child, then tell it to align to me
  4636. for (k = 0; k < g_numbones; k++)
  4637. {
  4638. if (g_bonetable[k].parent != -1 && children[g_bonetable[k].parent] == 1)
  4639. {
  4640. childbone[g_bonetable[k].parent] = k;
  4641. }
  4642. }
  4643. }
  4644. matrix3x4_t boneToPose[MAXSTUDIOBONES];
  4645. for (k = 0; k < g_numbones; k++)
  4646. {
  4647. MatrixCopy( g_bonetable[k].boneToPose, boneToPose[k] );
  4648. }
  4649. // look for bones that aren't on a primary X axis
  4650. for (k = 0; k < g_numbones; k++)
  4651. {
  4652. // printf("%s %.4f %.4f %.4f (%d)\n", g_bonetable[k].name, g_bonetable[k].pos.x, g_bonetable[k].pos.y, g_bonetable[k].pos.z, children[k] );
  4653. if (!g_bonetable[k].bPreAligned && childbone[k] != -1)
  4654. {
  4655. float d = g_bonetable[childbone[k]].pos.Length();
  4656. // check to see that it's on positive X
  4657. if (d - g_bonetable[childbone[k]].pos.x > 0.01)
  4658. {
  4659. Vector v2;
  4660. Vector v3;
  4661. // printf("%s:%s %.4f %.4f %.4f\n", g_bonetable[k].name, g_bonetable[childbone[k]].name, g_bonetable[childbone[k]].pos.x, g_bonetable[childbone[k]].pos.y, g_bonetable[childbone[k]].pos.z );
  4662. Vector forward, left, up;
  4663. // calc X axis
  4664. MatrixGetColumn( g_bonetable[childbone[k]].boneToPose, 3, v2 );
  4665. MatrixGetColumn( g_bonetable[k].boneToPose, 3, v3 );
  4666. forward = v2 - v3;
  4667. VectorNormalize( forward );
  4668. // try to align to existing bone/boundingbox by finding most perpendicular
  4669. // existing axis and aligning the new Z axis to it.
  4670. Vector forward2, left2, up2;
  4671. MatrixGetColumn( boneToPose[k], 0, forward2 );
  4672. MatrixGetColumn( boneToPose[k], 1, left2 );
  4673. MatrixGetColumn( boneToPose[k], 2, up2 );
  4674. float d1 = fabs(DotProduct( forward, forward2 ));
  4675. float d2 = fabs(DotProduct( forward, left2 ));
  4676. float d3 = fabs(DotProduct( forward, up2 ));
  4677. if (d1 <= d2 && d1 <= d3)
  4678. {
  4679. up = CrossProduct( forward, forward2 );
  4680. VectorNormalize( up );
  4681. }
  4682. else if (d2 <= d1 && d2 <= d3)
  4683. {
  4684. up = CrossProduct( forward, left2 );
  4685. VectorNormalize( up );
  4686. }
  4687. else
  4688. {
  4689. up = CrossProduct( forward, up2 );
  4690. VectorNormalize( up );
  4691. }
  4692. left = CrossProduct( up, forward );
  4693. // setup matrix
  4694. MatrixSetColumn( forward, 0, boneToPose[k] );
  4695. MatrixSetColumn( left, 1, boneToPose[k] );
  4696. MatrixSetColumn( up, 2, boneToPose[k] );
  4697. // check orthonormality of matrix
  4698. d = fabs( DotProduct( forward, left ) )
  4699. + fabs( DotProduct( left, up ) )
  4700. + fabs( DotProduct( up, forward ) )
  4701. + fabs( DotProduct( boneToPose[k][0], boneToPose[k][1] ) )
  4702. + fabs( DotProduct( boneToPose[k][1], boneToPose[k][2] ) )
  4703. + fabs( DotProduct( boneToPose[k][2], boneToPose[k][0] ) );
  4704. if (d > 0.0001)
  4705. {
  4706. MdlError( "error with realigning bone %s\n", g_bonetable[k].name );
  4707. }
  4708. // printf("%f %f %f\n", DotProduct( boneToPose[k][0], boneToPose[k][1] ), DotProduct( boneToPose[k][1], boneToPose[k][2] ), DotProduct( boneToPose[k][2], boneToPose[k][0] ) );
  4709. // printf("%f %f %f\n", DotProduct( forward, left ), DotProduct( left, up ), DotProduct( up, forward ) );
  4710. // VectorMatrix( forward, boneToPose[k] );
  4711. MatrixSetColumn( v3, 3, boneToPose[k] );
  4712. }
  4713. }
  4714. }
  4715. for (int i = 0; i < g_numforcedrealign; i++)
  4716. {
  4717. k = findGlobalBone( g_forcedrealign[i].name );
  4718. if (k == -1)
  4719. {
  4720. MdlWarning( "unknown bone %s in $forcedrealign\n", g_forcedrealign[i].name );
  4721. continue;
  4722. }
  4723. matrix3x4_t local;
  4724. matrix3x4_t tmp;
  4725. AngleMatrix( g_forcedrealign[i].rot, local );
  4726. ConcatTransforms( boneToPose[k], local, tmp );
  4727. MatrixCopy( tmp, boneToPose[k] );
  4728. }
  4729. // build realignment transforms
  4730. for (k = 0; k < g_numbones; k++)
  4731. {
  4732. if (!g_bonetable[k].bPreAligned)
  4733. {
  4734. matrix3x4_t poseToBone;
  4735. MatrixInvert( g_bonetable[k].boneToPose, poseToBone );
  4736. ConcatTransforms( poseToBone, boneToPose[k], g_bonetable[k].srcRealign );
  4737. MatrixCopy( boneToPose[k], g_bonetable[k].boneToPose );
  4738. }
  4739. }
  4740. // printf("\n");
  4741. // rebuild default angles, position, etc.
  4742. for (k = 0; k < g_numbones; k++)
  4743. {
  4744. if (!g_bonetable[k].bPreAligned)
  4745. {
  4746. matrix3x4_t bonematrix;
  4747. if (g_bonetable[k].parent == -1)
  4748. {
  4749. MatrixCopy( g_bonetable[k].boneToPose, bonematrix );
  4750. }
  4751. else
  4752. {
  4753. matrix3x4_t poseToBone;
  4754. // convert my transform into parent relative space
  4755. MatrixInvert( g_bonetable[g_bonetable[k].parent].boneToPose, poseToBone );
  4756. ConcatTransforms( poseToBone, g_bonetable[k].boneToPose, bonematrix );
  4757. }
  4758. MatrixAngles( bonematrix, g_bonetable[k].rot, g_bonetable[k].pos );
  4759. }
  4760. }
  4761. // exit(0);
  4762. // printf("\n");
  4763. // build reference pose
  4764. for (k = 0; k < g_numbones; k++)
  4765. {
  4766. matrix3x4_t bonematrix;
  4767. AngleMatrix( g_bonetable[k].rot, g_bonetable[k].pos, bonematrix );
  4768. // MatrixCopy( g_bonetable[k].rawLocal, bonematrix );
  4769. if (g_bonetable[k].parent == -1)
  4770. {
  4771. MatrixCopy( bonematrix, g_bonetable[k].boneToPose );
  4772. }
  4773. else
  4774. {
  4775. ConcatTransforms (g_bonetable[g_bonetable[k].parent].boneToPose, bonematrix, g_bonetable[k].boneToPose);
  4776. }
  4777. /*
  4778. Vector v1;
  4779. MatrixGetColumn( g_bonetable[k].boneToPose, 3, v1 );
  4780. printf("%s %.4f %.4f %.4f\n", g_bonetable[k].name, v1.x, v1.y, v1.z );
  4781. */
  4782. }
  4783. }
  4784. void CenterBonesOnVerts( void )
  4785. {
  4786. Vector bmin[MAXSTUDIOBONES];
  4787. Vector bmax[MAXSTUDIOBONES];
  4788. int i, j, k, n;
  4789. for (k = 0; k < g_numbones; k++)
  4790. {
  4791. bmin[k] = Vector( 1, 1, 1 ) * 99999999.0;
  4792. bmax[k] = Vector( 1, 1, 1 ) * -99999999.0;
  4793. }
  4794. // find domain of all the vertices
  4795. for (i = 0; i < g_numsources; i++)
  4796. {
  4797. s_source_t *pSource = g_source[i];
  4798. if ( !pSource->vertex )
  4799. continue;
  4800. s_sourceanim_t *pSourceAnim = FindSourceAnim( pSource, "BindPose" );
  4801. if ( !pSourceAnim )
  4802. {
  4803. pSourceAnim = &pSource->m_Animations[0];
  4804. }
  4805. pSource->m_GlobalVertices.AddMultipleToTail( pSource->numvertices );
  4806. Vector p;
  4807. for (j = 0; j < pSource->numvertices; j++)
  4808. {
  4809. for (n = 0; n < pSource->m_GlobalVertices[j].boneweight.numbones; n++)
  4810. {
  4811. k = pSource->m_GlobalVertices[j].boneweight.bone[n];
  4812. p = pSource->m_GlobalVertices[j].position;
  4813. bmin[k] = bmin[k].Min( p );
  4814. bmax[k] = bmax[k].Max( p );
  4815. }
  4816. }
  4817. }
  4818. // copy min/maxs up to parent
  4819. for (k = g_numbones - 1; k >= 0; k--)
  4820. {
  4821. if (bmin[k].x > bmax[k].x)
  4822. {
  4823. for (j = k + 1; j < g_numbones; j++)
  4824. {
  4825. if (g_bonetable[j].parent == k)
  4826. {
  4827. bmin[k] = bmin[k].Min( bmin[j] );
  4828. bmax[k] = bmax[k].Max( bmax[j] );
  4829. }
  4830. }
  4831. }
  4832. }
  4833. for (k = 0; k < g_numbones; k++)
  4834. {
  4835. if (bmin[k].x <= bmax[k].x)
  4836. {
  4837. Vector center = (bmin[k] + bmax[k]) * 0.5;
  4838. // printf("%d %.1f %.1f %.1f\n", k, center.x, center.y, center.z );
  4839. matrix3x4_t updateCenter;
  4840. MatrixCopy( g_bonetable[k].boneToPose, updateCenter );
  4841. PositionMatrix( center, updateCenter );
  4842. matrix3x4_t invPoseToBone;
  4843. MatrixInvert( g_bonetable[k].boneToPose, invPoseToBone );
  4844. ConcatTransforms( invPoseToBone, updateCenter, g_bonetable[k].srcRealign );
  4845. MatrixCopy( updateCenter, g_bonetable[k].boneToPose );
  4846. }
  4847. }
  4848. // rebuild default angles, position, etc.
  4849. for (k = 0; k < g_numbones; k++)
  4850. {
  4851. if (!g_bonetable[k].bPreAligned)
  4852. {
  4853. matrix3x4_t bonematrix;
  4854. if (g_bonetable[k].parent == -1)
  4855. {
  4856. MatrixCopy( g_bonetable[k].boneToPose, bonematrix );
  4857. }
  4858. else
  4859. {
  4860. matrix3x4_t poseToBone;
  4861. // convert my transform into parent relative space
  4862. MatrixInvert( g_bonetable[g_bonetable[k].parent].boneToPose, poseToBone );
  4863. ConcatTransforms( poseToBone, g_bonetable[k].boneToPose, bonematrix );
  4864. }
  4865. MatrixAngles( bonematrix, g_bonetable[k].rot, g_bonetable[k].pos );
  4866. }
  4867. }
  4868. }
  4869. //-----------------------------------------------------------------------------
  4870. // Purpose: Find all attachments that have matching names
  4871. // Remove those that are truly duplicates
  4872. // Leave ones that aren't duplicates but warn about them
  4873. //-----------------------------------------------------------------------------
  4874. void RemoveDuplicateAttachments()
  4875. {
  4876. for ( int i = 0; i < g_numattachments; ++i )
  4877. {
  4878. const s_attachment_t &iAtt = g_attachment[ i ];
  4879. for ( int j = g_numattachments - 1; j > i; --j )
  4880. {
  4881. const s_attachment_t &jAtt = g_attachment[ j ];
  4882. if ( Q_strcmp( iAtt.name, jAtt.name ) )
  4883. continue; // Not the same name
  4884. if ( Q_stricmp( iAtt.bonename, jAtt.bonename ) ||
  4885. iAtt.bone != jAtt.bone ||
  4886. iAtt.type != jAtt.type ||
  4887. iAtt.flags != jAtt.flags ||
  4888. Q_memcmp( iAtt.local.Base(), jAtt.local.Base(), sizeof( matrix3x4_t ) ) )
  4889. {
  4890. RadianEuler iEuler, jEuler;
  4891. Vector iPos, jPos;
  4892. MatrixAngles( iAtt.local, iEuler, iPos );
  4893. MatrixAngles( jAtt.local, jEuler, jPos );
  4894. MdlWarning(
  4895. "Attachments with the same name but different parameters found\n"
  4896. " %s: ParentBone: %s Type: %d Flags: 0x%08x P: %6.2f %6.2f %6.2f R: %6.2f %6.2f %6.2f\n"
  4897. " %s: ParentBone: %s Type: %d Flags: 0x%08x P: %6.2f %6.2f %6.2f R: %6.2f %6.2f %6.2f\n",
  4898. iAtt.name, iAtt.bonename, iAtt.type, iAtt.flags,
  4899. iPos.x, iPos.y, iPos.z, RAD2DEG( iEuler.x ), RAD2DEG( iEuler.y ), RAD2DEG( iEuler.z ),
  4900. jAtt.name, jAtt.bonename, jAtt.type, jAtt.flags,
  4901. jPos.x, jPos.y, jPos.z, RAD2DEG( jEuler.x ), RAD2DEG( jEuler.y ), RAD2DEG( jEuler.z ) );
  4902. continue;
  4903. }
  4904. // Delete attachment j by shifting j+1 to the end down overtop of j
  4905. Q_memcpy( &( g_attachment[ j ] ), &( g_attachment[ j + 1 ] ), ( g_numattachments - j - 1 ) * sizeof( s_attachment_t ) );
  4906. --g_numattachments;
  4907. }
  4908. }
  4909. }
  4910. //-----------------------------------------------------------------------------
  4911. // Purpose: find all the different bones used in all the source files and map everything
  4912. // to a common bonetable.
  4913. //-----------------------------------------------------------------------------
  4914. void RemapBones( )
  4915. {
  4916. int iError = 0;
  4917. if ( g_staticprop )
  4918. {
  4919. MakeStaticProp( );
  4920. }
  4921. else if ( g_centerstaticprop )
  4922. {
  4923. MdlWarning("Ignoring option $autocenter. Only supported on $staticprop models!!!\n" );
  4924. }
  4925. TagUsedBones( );
  4926. RenameBones( );
  4927. iError = BuildGlobalBonetable( );
  4928. BuildGlobalBoneToPose( );
  4929. EnforceHierarchy( );
  4930. {
  4931. int k, n;
  4932. for ( k = 0; k < g_numbones; k++ )
  4933. {
  4934. // tag parent bones as being in the same way as their children
  4935. n = g_bonetable[k].parent;
  4936. while (n != -1)
  4937. {
  4938. g_bonetable[n].flags |= g_bonetable[k].flags;
  4939. n = g_bonetable[n].parent;
  4940. }
  4941. }
  4942. }
  4943. if ( g_collapse_bones || g_numimportbones )
  4944. {
  4945. CollapseBones( );
  4946. }
  4947. if ( g_numbones >= MAXSTUDIOBONES )
  4948. {
  4949. // export bones
  4950. if (g_definebones)
  4951. {
  4952. DumpDefineBones();
  4953. }
  4954. MdlError( "Too many bones used in model, used %d, max %d\n", g_numbones, MAXSTUDIOBONES );
  4955. }
  4956. /*
  4957. for (i = 0; i < g_numbones; i++)
  4958. {
  4959. printf("%2d %s %d\n", i, g_bonetable[i].name, g_bonetable[i].parent );
  4960. }
  4961. */
  4962. RebuildLocalPose( );
  4963. TagProceduralBones( );
  4964. if ( iError && !(ignore_warnings) )
  4965. {
  4966. MdlError( "Exiting due to errors\n" );
  4967. }
  4968. MapSourcesToGlobalBonetable( );
  4969. if ( iError && !(ignore_warnings) )
  4970. {
  4971. MdlError( "Exiting due to errors\n" );
  4972. }
  4973. // Map the bone names to global bone indices for all BoneFlexDrivers
  4974. MapFlexDriveBonesToGlobalBoneTable();
  4975. }
  4976. //-----------------------------------------------------------------------------
  4977. // Purpose: calculate the bone to world transforms for a processed animation
  4978. //-----------------------------------------------------------------------------
  4979. void CalcBoneTransforms( s_animation_t *panimation, int frame, matrix3x4_t* pBoneToWorld )
  4980. {
  4981. CalcBoneTransforms( panimation, g_panimation[0], frame, pBoneToWorld );
  4982. }
  4983. void CalcBoneTransforms( s_animation_t *panimation, s_animation_t *pbaseanimation, int frame, matrix3x4_t* pBoneToWorld )
  4984. {
  4985. if ((panimation->flags & STUDIO_LOOPING) && panimation->numframes > 1)
  4986. {
  4987. while (frame >= (panimation->numframes - 1))
  4988. {
  4989. frame = frame - (panimation->numframes - 1);
  4990. }
  4991. }
  4992. if (frame < 0 || frame >= panimation->numframes)
  4993. {
  4994. MdlError("requested out of range frame on animation \"%s\" : %d (%d)\n", panimation->name, frame, panimation->numframes );
  4995. }
  4996. for (int k = 0; k < g_numbones; k++)
  4997. {
  4998. Vector angle;
  4999. matrix3x4_t bonematrix;
  5000. if (!(panimation->flags & STUDIO_DELTA))
  5001. {
  5002. AngleMatrix( panimation->sanim[frame][k].rot, panimation->sanim[frame][k].pos, bonematrix );
  5003. }
  5004. else if (pbaseanimation)
  5005. {
  5006. Quaternion q1, q2, q3;
  5007. Vector p3;
  5008. //AngleQuaternion( g_bonetable[k].rot, q1 );
  5009. AngleQuaternion( pbaseanimation->sanim[0][k].rot, q1 );
  5010. AngleQuaternion( panimation->sanim[frame][k].rot, q2 );
  5011. float s = panimation->weight[k];
  5012. QuaternionMA( q1, s, q2, q3 );
  5013. //p3 = g_bonetable[k].pos + s * panimation->sanim[frame][k].pos;
  5014. p3 = pbaseanimation->sanim[0][k].pos + s * panimation->sanim[frame][k].pos;
  5015. AngleMatrix( RadianEuler( q3 ), p3, bonematrix );
  5016. }
  5017. else
  5018. {
  5019. Quaternion q1, q2, q3;
  5020. Vector p3;
  5021. AngleQuaternion( g_bonetable[k].rot, q1 );
  5022. AngleQuaternion( panimation->sanim[frame][k].rot, q2 );
  5023. float s = panimation->weight[k];
  5024. QuaternionMA( q1, s, q2, q3 );
  5025. //p3 = g_bonetable[k].pos + s * panimation->sanim[frame][k].pos;
  5026. p3 = pbaseanimation->sanim[0][k].pos + s * g_bonetable[k].pos;
  5027. AngleMatrix( RadianEuler( q3 ), p3, bonematrix );
  5028. }
  5029. if (g_bonetable[k].parent == -1)
  5030. {
  5031. MatrixCopy( bonematrix, pBoneToWorld[k] );
  5032. }
  5033. else
  5034. {
  5035. ConcatTransforms (pBoneToWorld[g_bonetable[k].parent], bonematrix, pBoneToWorld[k]);
  5036. }
  5037. }
  5038. }
  5039. //-----------------------------------------------------------------------------
  5040. // Purpose: calculate the bone to world transforms for a processed animation
  5041. //-----------------------------------------------------------------------------
  5042. void CalcBoneTransformsCycle( s_animation_t *panimation, s_animation_t *pbaseanimation, float flCycle, matrix3x4_t* pBoneToWorld )
  5043. {
  5044. float fFrame = flCycle * (panimation->numframes - 1);
  5045. int iFrame = (int)fFrame;
  5046. float s = (fFrame - iFrame);
  5047. int iFrame1 = iFrame % (panimation->numframes - 1);
  5048. int iFrame2 = (iFrame + 1) % (panimation->numframes - 1);
  5049. for (int k = 0; k < g_numbones; k++)
  5050. {
  5051. Quaternion q1, q2, q3;
  5052. Vector p3;
  5053. matrix3x4_t bonematrix;
  5054. // if (!(panimation->flags & STUDIO_DELTA))
  5055. {
  5056. AngleQuaternion( panimation->sanim[iFrame1][k].rot, q1 );
  5057. AngleQuaternion( panimation->sanim[iFrame2][k].rot, q2 );
  5058. QuaternionSlerp( q1, q2, s, q3 );
  5059. VectorLerp( panimation->sanim[iFrame1][k].pos, panimation->sanim[iFrame2][k].pos, s, p3 );
  5060. AngleMatrix( RadianEuler( q3 ), p3, bonematrix );
  5061. }
  5062. /*
  5063. else
  5064. {
  5065. Vector p3;
  5066. //AngleQuaternion( g_bonetable[k].rot, q1 );
  5067. AngleQuaternion( pbaseanimation->sanim[0][k].rot, q1 );
  5068. AngleQuaternion( panimation->sanim[frame][k].rot, q2 );
  5069. float s = panimation->weight[k];
  5070. QuaternionMA( q1, s, q2, q3 );
  5071. //p3 = g_bonetable[k].pos + s * panimation->sanim[frame][k].pos;
  5072. p3 = pbaseanimation->sanim[0][k].pos + s * panimation->sanim[frame][k].pos;
  5073. AngleMatrix( q3, p3, bonematrix );
  5074. }
  5075. */
  5076. if (g_bonetable[k].parent == -1)
  5077. {
  5078. MatrixCopy( bonematrix, pBoneToWorld[k] );
  5079. }
  5080. else
  5081. {
  5082. ConcatTransforms (pBoneToWorld[g_bonetable[k].parent], bonematrix, pBoneToWorld[k]);
  5083. }
  5084. }
  5085. }
  5086. //-----------------------------------------------------------------------------
  5087. // Purpose: calculate the bone to world transforms for a processed sequence
  5088. //-----------------------------------------------------------------------------
  5089. void SlerpBones(
  5090. Quaternion q1[MAXSTUDIOBONES],
  5091. Vector pos1[MAXSTUDIOBONES],
  5092. int sequence,
  5093. const Quaternion q2[MAXSTUDIOBONES],
  5094. const Vector pos2[MAXSTUDIOBONES],
  5095. float s )
  5096. {
  5097. int i;
  5098. Quaternion q3, q4;
  5099. float s1, s2;
  5100. s_sequence_t *pseqdesc = &g_sequence[sequence];
  5101. if (s <= 0.0f)
  5102. {
  5103. return;
  5104. }
  5105. else if (s > 1.0f)
  5106. {
  5107. s = 1.0f;
  5108. }
  5109. if (pseqdesc->flags & STUDIO_DELTA)
  5110. {
  5111. for (i = 0; i < g_numbones; i++)
  5112. {
  5113. s2 = s * pseqdesc->weight[i]; // blend in based on this bones weight
  5114. if (s2 > 0.0)
  5115. {
  5116. if (pseqdesc->flags & STUDIO_POST)
  5117. {
  5118. QuaternionMA( q1[i], s2, q2[i], q1[i] );
  5119. // FIXME: are these correct?
  5120. pos1[i][0] = pos1[i][0] + pos2[i][0] * s2;
  5121. pos1[i][1] = pos1[i][1] + pos2[i][1] * s2;
  5122. pos1[i][2] = pos1[i][2] + pos2[i][2] * s2;
  5123. }
  5124. else
  5125. {
  5126. QuaternionSM( s2, q2[i], q1[i], q1[i] );
  5127. // FIXME: are these correct?
  5128. pos1[i][0] = pos1[i][0] + pos2[i][0] * s2;
  5129. pos1[i][1] = pos1[i][1] + pos2[i][1] * s2;
  5130. pos1[i][2] = pos1[i][2] + pos2[i][2] * s2;
  5131. }
  5132. }
  5133. }
  5134. }
  5135. else
  5136. {
  5137. for (i = 0; i <g_numbones; i++)
  5138. {
  5139. s2 = s * pseqdesc->weight[i]; // blend in based on this animations weights
  5140. if (s2 > 0.0)
  5141. {
  5142. s1 = 1.0 - s2;
  5143. if (g_bonetable[i].flags & BONE_FIXED_ALIGNMENT)
  5144. {
  5145. QuaternionSlerpNoAlign( q2[i], q1[i], s1, q3 );
  5146. }
  5147. else
  5148. {
  5149. QuaternionSlerp( q2[i], q1[i], s1, q3 );
  5150. }
  5151. q1[i][0] = q3[0];
  5152. q1[i][1] = q3[1];
  5153. q1[i][2] = q3[2];
  5154. q1[i][3] = q3[3];
  5155. pos1[i][0] = pos1[i][0] * s1 + pos2[i][0] * s2;
  5156. pos1[i][1] = pos1[i][1] * s1 + pos2[i][1] * s2;
  5157. pos1[i][2] = pos1[i][2] * s1 + pos2[i][2] * s2;
  5158. }
  5159. }
  5160. }
  5161. }
  5162. void CalcPoseSingle( Vector pos[], Quaternion q[], int sequence, float frame )
  5163. {
  5164. s_sequence_t *pseqdesc = &g_sequence[sequence];
  5165. s_animation_t *panim = pseqdesc->panim[0][0];
  5166. // FIXME: is this modulo correct?
  5167. int iframe = ((int)frame) % panim->numframes;
  5168. for (int k = 0; k < g_numbones; k++)
  5169. {
  5170. // FIXME: this isn't doing a fractional frame
  5171. AngleQuaternion( panim->sanim[iframe][k].rot, q[k] );
  5172. pos[k] = panim->sanim[iframe][k].pos;
  5173. }
  5174. }
  5175. void AccumulateSeqLayers( Vector pos[], Quaternion q[], int sequence, float frame, float flWeight );
  5176. void AccumulatePose( Vector pos[], Quaternion q[], int sequence, float frame, float flWeight )
  5177. {
  5178. Vector pos2[MAXSTUDIOBONES];
  5179. Quaternion q2[MAXSTUDIOBONES];
  5180. // printf("accumulate %s : %.1f\n", g_sequence[sequence].name, frame );
  5181. CalcPoseSingle( pos2, q2, sequence, frame );
  5182. SlerpBones( q, pos, sequence, q2, pos2, flWeight );
  5183. AccumulateSeqLayers( pos, q, sequence, frame, flWeight );
  5184. }
  5185. void AccumulateSeqLayers( Vector pos[], Quaternion q[], int sequence, float frame, float flWeight )
  5186. {
  5187. s_sequence_t *pseqdesc = &g_sequence[sequence];
  5188. for (int i = 0; i < pseqdesc->numautolayers; i++)
  5189. {
  5190. s_autolayer_t *pLayer = &pseqdesc->autolayer[i];
  5191. float layerFrame = frame;
  5192. float layerWeight = flWeight;
  5193. if (pLayer->start != pLayer->end)
  5194. {
  5195. float s = 1.0;
  5196. float index;
  5197. if (!(pLayer->flags & STUDIO_AL_POSE))
  5198. {
  5199. index = frame;
  5200. }
  5201. else
  5202. {
  5203. int iPose = pLayer->pose;
  5204. if (iPose != -1)
  5205. {
  5206. index = 0; // undefined?
  5207. }
  5208. else
  5209. {
  5210. index = 0;
  5211. }
  5212. }
  5213. if (index < pLayer->start)
  5214. continue;
  5215. if (index >= pLayer->end)
  5216. continue;
  5217. if (index < pLayer->peak && pLayer->start != pLayer->peak)
  5218. {
  5219. s = (index - pLayer->start) / (pLayer->peak - pLayer->start);
  5220. }
  5221. else if (index > pLayer->tail && pLayer->end != pLayer->tail)
  5222. {
  5223. s = (pLayer->end - index) / (pLayer->end - pLayer->tail);
  5224. }
  5225. if (pLayer->flags & STUDIO_AL_SPLINE)
  5226. {
  5227. s = 3 * s * s - 2 * s * s * s;
  5228. }
  5229. if ((pLayer->flags & STUDIO_AL_XFADE) && (frame > pLayer->tail))
  5230. {
  5231. layerWeight = ( s * flWeight ) / ( 1 - flWeight + s * flWeight );
  5232. }
  5233. else if (pLayer->flags & STUDIO_AL_NOBLEND)
  5234. {
  5235. layerWeight = s;
  5236. }
  5237. else
  5238. {
  5239. layerWeight = flWeight * s;
  5240. }
  5241. if (!(pLayer->flags & STUDIO_AL_POSE))
  5242. {
  5243. layerFrame = ((frame - pLayer->start) / (pLayer->end - pLayer->start)) * (g_sequence[pLayer->sequence].panim[0][0]->numframes - 1);
  5244. }
  5245. else
  5246. {
  5247. layerFrame = (frame / g_sequence[sequence].panim[0][0]->numframes - 1) * (g_sequence[pLayer->sequence].panim[0][0]->numframes - 1);
  5248. }
  5249. }
  5250. AccumulatePose( pos, q, pLayer->sequence, layerFrame, layerWeight );
  5251. }
  5252. }
  5253. void CalcSeqTransforms( int sequence, int frame, matrix3x4_t* pBoneToWorld )
  5254. {
  5255. int k;
  5256. Vector pos[MAXSTUDIOBONES];
  5257. Quaternion q[MAXSTUDIOBONES];
  5258. // CalcPoseSingle( pos, q, 0, 0 );
  5259. /*
  5260. for (k = 0; k < g_numbones; k++)
  5261. {
  5262. //AngleQuaternion( g_bonetable[k].rot, q[k] );
  5263. //pos[k] = g_bonetable[k].pos;
  5264. AngleQuaternion( g_bonetable[k].rot, q[k] );
  5265. pos[k] = g_bonetable[k].pos;
  5266. }
  5267. */
  5268. for (k = 0; k < g_numbones; k++)
  5269. {
  5270. //AngleQuaternion( g_bonetable[k].rot, q[k] );
  5271. //pos[k] = g_bonetable[k].pos;
  5272. AngleQuaternion( g_bonetable[k].rot, q[k] );
  5273. pos[k] = g_bonetable[k].pos;
  5274. }
  5275. AccumulatePose( pos, q, sequence, frame, 1.0 );
  5276. for (k = 0; k < g_numbones; k++)
  5277. {
  5278. matrix3x4_t bonematrix;
  5279. QuaternionMatrix( q[k], pos[k], bonematrix );
  5280. if (g_bonetable[k].parent == -1)
  5281. {
  5282. MatrixCopy( bonematrix, pBoneToWorld[k] );
  5283. }
  5284. else
  5285. {
  5286. ConcatTransforms (pBoneToWorld[g_bonetable[k].parent], bonematrix, pBoneToWorld[k]);
  5287. }
  5288. }
  5289. }
  5290. //-----------------------------------------------------------------------------
  5291. // Purpose:
  5292. //-----------------------------------------------------------------------------
  5293. void CalcBonePos( s_animation_t *panimation, int frame, int bone, Vector &pos )
  5294. {
  5295. matrix3x4_t boneToWorld[MAXSTUDIOSRCBONES]; // bone transformation matrix
  5296. CalcBoneTransforms( panimation, frame, boneToWorld );
  5297. pos.x = boneToWorld[bone][0][3];
  5298. pos.y = boneToWorld[bone][1][3];
  5299. pos.z = boneToWorld[bone][2][3];
  5300. }
  5301. #define SMALL_FLOAT 1e-12
  5302. // NOTE: This routine was taken (and modified) from NVidia's BlinnReflection demo
  5303. // Creates basis vectors, based on a vertex and index list.
  5304. // See the NVidia white paper 'GDC2K PerPixel Lighting' for a description
  5305. // of how this computation works
  5306. static void CalcTriangleTangentSpace( s_source_t *pSrc, int v1, int v2, int v3,
  5307. Vector &sVect, Vector &tVect )
  5308. {
  5309. /*
  5310. static bool firstTime = true;
  5311. static FILE *fp = NULL;
  5312. if( firstTime )
  5313. {
  5314. firstTime = false;
  5315. fp = fopen( "crap.out", "w" );
  5316. }
  5317. */
  5318. Vector2D t0( pSrc->vertex[v1].texcoord[0][0], pSrc->vertex[v1].texcoord[0][1] );
  5319. Vector2D t1( pSrc->vertex[v2].texcoord[0][0], pSrc->vertex[v2].texcoord[0][1] );
  5320. Vector2D t2( pSrc->vertex[v3].texcoord[0][0], pSrc->vertex[v3].texcoord[0][1] );
  5321. Vector p0( pSrc->vertex[v1].position[0], pSrc->vertex[v1].position[1], pSrc->vertex[v1].position[2] );
  5322. Vector p1( pSrc->vertex[v2].position[0], pSrc->vertex[v2].position[1], pSrc->vertex[v2].position[2] );
  5323. Vector p2( pSrc->vertex[v3].position[0], pSrc->vertex[v3].position[1], pSrc->vertex[v3].position[2] );
  5324. CalcTriangleTangentSpace( p0, p1, p2, t0, t1, t2, sVect, tVect );
  5325. /*
  5326. // Calculate flat normal
  5327. Vector flatNormal;
  5328. edge01 = p1 - p0;
  5329. edge02 = p2 - p0;
  5330. CrossProduct( edge02, edge01, flatNormal );
  5331. VectorNormalize( flatNormal );
  5332. // Get the average position
  5333. Vector avgPos = ( p0 + p1 + p2 ) / 3.0f;
  5334. // Draw the svect
  5335. Vector endS = avgPos + sVect * .2f;
  5336. fprintf( fp, "2\n" );
  5337. fprintf( fp, "%f %f %f 1.0 0.0 0.0\n", endS[0], endS[1], endS[2] );
  5338. fprintf( fp, "%f %f %f 1.0 0.0 0.0\n", avgPos[0], avgPos[1], avgPos[2] );
  5339. // Draw the tvect
  5340. Vector endT = avgPos + tVect * .2f;
  5341. fprintf( fp, "2\n" );
  5342. fprintf( fp, "%f %f %f 0.0 1.0 0.0\n", endT[0], endT[1], endT[2] );
  5343. fprintf( fp, "%f %f %f 0.0 1.0 0.0\n", avgPos[0], avgPos[1], avgPos[2] );
  5344. // Draw the normal
  5345. Vector endN = avgPos + flatNormal * .2f;
  5346. fprintf( fp, "2\n" );
  5347. fprintf( fp, "%f %f %f 0.0 0.0 1.0\n", endN[0], endN[1], endN[2] );
  5348. fprintf( fp, "%f %f %f 0.0 0.0 1.0\n", avgPos[0], avgPos[1], avgPos[2] );
  5349. // Draw the wireframe of the triangle in white.
  5350. fprintf( fp, "2\n" );
  5351. fprintf( fp, "%f %f %f 1.0 1.0 1.0\n", p0[0], p0[1], p0[2] );
  5352. fprintf( fp, "%f %f %f 1.0 1.0 1.0\n", p1[0], p1[1], p1[2] );
  5353. fprintf( fp, "2\n" );
  5354. fprintf( fp, "%f %f %f 1.0 1.0 1.0\n", p1[0], p1[1], p1[2] );
  5355. fprintf( fp, "%f %f %f 1.0 1.0 1.0\n", p2[0], p2[1], p2[2] );
  5356. fprintf( fp, "2\n" );
  5357. fprintf( fp, "%f %f %f 1.0 1.0 1.0\n", p2[0], p2[1], p2[2] );
  5358. fprintf( fp, "%f %f %f 1.0 1.0 1.0\n", p0[0], p0[1], p0[2] );
  5359. // Draw a slightly shrunken version of the geometry to hide surfaces
  5360. Vector tmp0 = p0 - flatNormal * .1f;
  5361. Vector tmp1 = p1 - flatNormal * .1f;
  5362. Vector tmp2 = p2 - flatNormal * .1f;
  5363. fprintf( fp, "3\n" );
  5364. fprintf( fp, "%f %f %f 0.1 0.1 0.1\n", tmp0[0], tmp0[1], tmp0[2] );
  5365. fprintf( fp, "%f %f %f 0.1 0.1 0.1\n", tmp1[0], tmp1[1], tmp1[2] );
  5366. fprintf( fp, "%f %f %f 0.1 0.1 0.1\n", tmp2[0], tmp2[1], tmp2[2] );
  5367. fflush( fp );
  5368. */
  5369. }
  5370. typedef CUtlVector<int> CIntVector;
  5371. void CalcModelTangentSpaces( s_source_t *pSrc )
  5372. {
  5373. // Build a map from vertex to a list of faces that share the vert
  5374. int meshID;
  5375. for( meshID = 0; meshID < pSrc->nummeshes; meshID++ )
  5376. {
  5377. s_mesh_t *pMesh = &pSrc->mesh[pSrc->meshindex[meshID]];
  5378. CUtlVector<CIntVector> vertToFaceMap;
  5379. vertToFaceMap.AddMultipleToTail( pMesh->numvertices );
  5380. for( int faceID = 0; faceID < pMesh->numfaces; faceID++ )
  5381. {
  5382. s_face_t *pFace = &pSrc->face[faceID + pMesh->faceoffset];
  5383. vertToFaceMap[pFace->a].AddToTail( faceID );
  5384. vertToFaceMap[pFace->b].AddToTail( faceID );
  5385. vertToFaceMap[pFace->c].AddToTail( faceID );
  5386. if ( pFace->d != 0xFFFFFFFF ) // SubD Quad face
  5387. {
  5388. vertToFaceMap[pFace->d].AddToTail( faceID );
  5389. }
  5390. }
  5391. // Calculate the tangent space for each face
  5392. CUtlVector<Vector> faceSVect;
  5393. CUtlVector<Vector> faceTVect;
  5394. faceSVect.AddMultipleToTail( pMesh->numfaces );
  5395. faceTVect.AddMultipleToTail( pMesh->numfaces );
  5396. for( int faceID = 0; faceID < pMesh->numfaces; faceID++ )
  5397. {
  5398. s_face_t *pFace = &pSrc->face[faceID + pMesh->faceoffset];
  5399. CalcTriangleTangentSpace( pSrc,
  5400. pMesh->vertexoffset + pFace->a,
  5401. pMesh->vertexoffset + pFace->b,
  5402. pMesh->vertexoffset + pFace->c,
  5403. faceSVect[faceID], faceTVect[faceID] );
  5404. }
  5405. // Calculate an average tangent space for each vertex.
  5406. for( int vertID = 0; vertID < pMesh->numvertices; vertID++ )
  5407. {
  5408. const Vector &normal = pSrc->vertex[vertID+pMesh->vertexoffset].normal;
  5409. Vector4D &finalSVect = pSrc->vertex[vertID+pMesh->vertexoffset].tangentS;
  5410. Vector sVect, tVect;
  5411. sVect.Init( 0.0f, 0.0f, 0.0f );
  5412. tVect.Init( 0.0f, 0.0f, 0.0f );
  5413. for( int faceID = 0; faceID < vertToFaceMap[vertID].Count(); faceID++ )
  5414. {
  5415. sVect += faceSVect[vertToFaceMap[vertID][faceID]];
  5416. tVect += faceTVect[vertToFaceMap[vertID][faceID]];
  5417. }
  5418. // In the case of zbrush, everything needs to be treated as smooth.
  5419. if( g_bZBrush )
  5420. {
  5421. Vector vertPos1( pSrc->vertex[vertID].position[0], pSrc->vertex[vertID].position[1], pSrc->vertex[vertID].position[2] );
  5422. for( int vertID2 = 0; vertID2 < pMesh->numvertices; vertID2++ )
  5423. {
  5424. if( vertID2 == vertID )
  5425. {
  5426. continue;
  5427. }
  5428. Vector vertPos2( pSrc->vertex[vertID2].position[0], pSrc->vertex[vertID2].position[1], pSrc->vertex[vertID2].position[2] );
  5429. if( vertPos1 == vertPos2 )
  5430. {
  5431. for( int faceID = 0; faceID < vertToFaceMap[vertID2].Count(); faceID++ )
  5432. {
  5433. sVect += faceSVect[vertToFaceMap[vertID2][faceID]];
  5434. tVect += faceTVect[vertToFaceMap[vertID2][faceID]];
  5435. }
  5436. }
  5437. }
  5438. }
  5439. // Make an orthonormal system.
  5440. // Need to check if we are left or right handed.
  5441. Vector tmpVect;
  5442. CrossProduct( sVect, tVect, tmpVect );
  5443. bool leftHanded = DotProduct( tmpVect, normal ) < 0.0f;
  5444. if( !leftHanded )
  5445. {
  5446. CrossProduct( normal, sVect, tVect );
  5447. CrossProduct( tVect, normal, sVect );
  5448. VectorNormalize( sVect );
  5449. VectorNormalize( tVect );
  5450. finalSVect[0] = sVect[0];
  5451. finalSVect[1] = sVect[1];
  5452. finalSVect[2] = sVect[2];
  5453. finalSVect[3] = 1.0f;
  5454. }
  5455. else
  5456. {
  5457. CrossProduct( sVect, normal, tVect );
  5458. CrossProduct( normal, tVect, sVect );
  5459. VectorNormalize( sVect );
  5460. VectorNormalize( tVect );
  5461. finalSVect[0] = sVect[0];
  5462. finalSVect[1] = sVect[1];
  5463. finalSVect[2] = sVect[2];
  5464. finalSVect[3] = -1.0f;
  5465. }
  5466. }
  5467. }
  5468. }
  5469. //-----------------------------------------------------------------------------
  5470. // Generate a model vertex from a source vertex
  5471. //-----------------------------------------------------------------------------
  5472. static void InitRemappedVertex( s_source_t *pSource, matrix3x4_t *pDestBoneToWorld, const s_vertexinfo_t &srcVertex, s_vertexinfo_t &dstVertex )
  5473. {
  5474. Vector tmp1, tmp2, vdest, ndest;
  5475. memcpy( &dstVertex, &srcVertex, sizeof(s_vertexinfo_t) );
  5476. dstVertex.boneweight.numbones = 0;
  5477. vdest.Init();
  5478. ndest.Init();
  5479. int n;
  5480. for ( n = 0; n < srcVertex.boneweight.numbones; n++ )
  5481. {
  5482. // src bone
  5483. int q = srcVertex.boneweight.bone[n];
  5484. // mapping to global bone
  5485. int k = pSource->boneLocalToGlobal[q];
  5486. if ( k == -1 )
  5487. {
  5488. VectorCopy( srcVertex.position, vdest );
  5489. VectorCopy( srcVertex.normal, ndest );
  5490. break;
  5491. // printf("%s:%s (%d) missing global\n", psource->filename, psource->localBone[q].name, q );
  5492. }
  5493. // If the global bone is already in the list, then this vertex
  5494. // contains influences from multiple local bones which have been collapsed
  5495. // into a single global bone
  5496. int m;
  5497. for ( m = 0; m < dstVertex.boneweight.numbones; m++ )
  5498. {
  5499. if ( k == dstVertex.boneweight.bone[m] )
  5500. {
  5501. // bone got collapsed out
  5502. dstVertex.boneweight.weight[m] += srcVertex.boneweight.weight[n];
  5503. break;
  5504. }
  5505. }
  5506. if ( m == dstVertex.boneweight.numbones )
  5507. {
  5508. // add new bone
  5509. dstVertex.boneweight.bone[m] = k;
  5510. dstVertex.boneweight.weight[m] = srcVertex.boneweight.weight[n];
  5511. dstVertex.boneweight.numbones++;
  5512. }
  5513. // convert vertex into original models' bone local space
  5514. VectorITransform( srcVertex.position, pDestBoneToWorld[k], tmp1 );
  5515. // convert that into global world space using stardard pose
  5516. VectorTransform( tmp1, g_bonetable[k].boneToPose, tmp2 );
  5517. // accumulate
  5518. VectorMA( vdest, srcVertex.boneweight.weight[n], tmp2, vdest );
  5519. // convert normal into original models' bone local space
  5520. VectorIRotate( srcVertex.normal, pDestBoneToWorld[k], tmp1 );
  5521. // convert that into global world space using stardard pose
  5522. VectorRotate( tmp1, g_bonetable[k].boneToPose, tmp2 );
  5523. // accumulate
  5524. VectorMA( ndest, srcVertex.boneweight.weight[n], tmp2, ndest );
  5525. }
  5526. // printf("%d %.2f %.2f %.2f\n", j, vdest.x, vdest.y, vdest.z );
  5527. // save, normalize
  5528. VectorCopy( vdest, dstVertex.position );
  5529. VectorNormalize( ndest );
  5530. VectorCopy( ndest, dstVertex.normal );
  5531. // FIXME: Remapping will whack tangentS. Need to recompute tangents after remapping
  5532. }
  5533. //-----------------------------------------------------------------------------
  5534. // When read off disk, s_source_t contains bone indices local to the source
  5535. // we need to make the bone indices use the global bone list
  5536. //-----------------------------------------------------------------------------
  5537. void RemapVerticesToGlobalBones( )
  5538. {
  5539. matrix3x4_t srcBoneToWorld[MAXSTUDIOSRCBONES];
  5540. matrix3x4_t destBoneToWorld[MAXSTUDIOSRCBONES];
  5541. s_vertexinfo_t vTmpSrc;
  5542. s_vertexinfo_t vTmpDst;
  5543. for (int i = 0; i < g_numsources; i++)
  5544. {
  5545. s_source_t *pSource = g_source[i];
  5546. if ( !pSource->vertex )
  5547. continue;
  5548. s_sourceanim_t *pSourceAnim = FindSourceAnim( pSource, "BindPose" );
  5549. if ( !pSourceAnim )
  5550. {
  5551. pSourceAnim = &pSource->m_Animations[0];
  5552. }
  5553. BuildRawTransforms( pSource, pSourceAnim->animationname, 0, srcBoneToWorld );
  5554. TranslateAnimations( pSource, srcBoneToWorld, destBoneToWorld );
  5555. pSource->m_GlobalVertices.AddMultipleToTail( pSource->numvertices );
  5556. for ( int j = 0; j < pSource->numvertices; j++ )
  5557. {
  5558. InitRemappedVertex( pSource, destBoneToWorld, pSource->vertex[j], pSource->m_GlobalVertices[j] );
  5559. }
  5560. // Loop through all animations on this source and remap vertex animations
  5561. for ( int nAnimIndex = 0; nAnimIndex < pSource->m_Animations.Count(); ++nAnimIndex )
  5562. {
  5563. s_sourceanim_t *pAnim = &pSource->m_Animations[ nAnimIndex ];
  5564. // Only remap newStyleVertexAnimations
  5565. if ( !pAnim->newStyleVertexAnimations )
  5566. continue;
  5567. for ( int nFrameIndex = 0; nFrameIndex < pAnim->numframes; ++nFrameIndex )
  5568. {
  5569. // Only process frames which have data
  5570. const int nVertexCount = pAnim->numvanims[ nFrameIndex ];
  5571. if ( nVertexCount <= 0 )
  5572. continue;
  5573. s_vertanim_t *pVertAnims = pAnim->vanim[ nFrameIndex ];
  5574. for ( int nVertexIndex = 0; nVertexIndex < nVertexCount; ++nVertexIndex )
  5575. {
  5576. s_vertanim_t &vertAnim = pVertAnims[ nVertexIndex ];
  5577. const s_vertexinfo_t &vertex = pSource->vertex[ vertAnim.vertex ];
  5578. memcpy( &vTmpSrc, &vertex, sizeof( s_vertexinfo_t ) );
  5579. VectorAdd( vertex.position, vertAnim.pos, vTmpSrc.position );
  5580. VectorAdd( vertex.normal, vertAnim.normal, vTmpSrc.normal );
  5581. InitRemappedVertex( pSource, destBoneToWorld, vTmpSrc, vTmpDst );
  5582. const s_vertexinfo_t &globalVertex = pSource->m_GlobalVertices[ vertAnim.vertex ];
  5583. VectorSubtract( vTmpDst.position, globalVertex.position, vertAnim.pos );
  5584. VectorSubtract( vTmpDst.normal, globalVertex.normal, vertAnim.normal );
  5585. }
  5586. }
  5587. }
  5588. }
  5589. }
  5590. //-----------------------------------------------------------------------------
  5591. // Links bone controllers
  5592. //-----------------------------------------------------------------------------
  5593. static void FindAutolayers()
  5594. {
  5595. int i;
  5596. for (i = 0; i < g_sequence.Count(); i++)
  5597. {
  5598. int k;
  5599. for (k = 0; k < g_sequence[i].numautolayers; k++)
  5600. {
  5601. int j;
  5602. for ( j = 0; j < g_sequence.Count(); j++)
  5603. {
  5604. if (stricmp( g_sequence[i].autolayer[k].name, g_sequence[j].name) == 0)
  5605. {
  5606. g_sequence[i].autolayer[k].sequence = j;
  5607. break;
  5608. }
  5609. }
  5610. if (j == g_sequence.Count())
  5611. {
  5612. MdlError( "sequence \"%s\" cannot find autolayer sequence \"%s\"\n",
  5613. g_sequence[i].name, g_sequence[i].autolayer[k].name );
  5614. }
  5615. }
  5616. }
  5617. }
  5618. //-----------------------------------------------------------------------------
  5619. // Links bone controllers
  5620. //-----------------------------------------------------------------------------
  5621. static void LinkBoneControllers()
  5622. {
  5623. for (int i = 0; i < g_numbonecontrollers; i++)
  5624. {
  5625. int j = findGlobalBone( g_bonecontroller[i].name );
  5626. if (j == -1)
  5627. {
  5628. MdlError("unknown g_bonecontroller link '%s'\n", g_bonecontroller[i].name );
  5629. }
  5630. g_bonecontroller[i].bone = j;
  5631. }
  5632. }
  5633. //-----------------------------------------------------------------------------
  5634. // Links screen aligned bones
  5635. //-----------------------------------------------------------------------------
  5636. static void TagScreenAlignedBones()
  5637. {
  5638. for (int i = 0; i < g_numscreenalignedbones; i++)
  5639. {
  5640. int j = findGlobalBone( g_screenalignedbone[i].name );
  5641. if (j == -1)
  5642. {
  5643. MdlError("unknown g_screenalignedbone link '%s'\n", g_screenalignedbone[i].name );
  5644. }
  5645. g_bonetable[j].flags |= g_screenalignedbone[i].flags;
  5646. printf("tagging bone: %s as screen aligned (index %i, flags:%x)\n", g_bonetable[j].name, j, g_bonetable[j].flags );
  5647. }
  5648. }
  5649. //-----------------------------------------------------------------------------
  5650. // world aligned bones
  5651. //-----------------------------------------------------------------------------
  5652. static void TagWorldAlignedBones()
  5653. {
  5654. for (int i = 0; i < g_numworldalignedbones; i++)
  5655. {
  5656. int j = findGlobalBone( g_worldalignedbone[i].name );
  5657. if (j == -1)
  5658. {
  5659. MdlError("unknown g_worldalignedbone link '%s'\n", g_worldalignedbone[i].name );
  5660. }
  5661. g_bonetable[j].flags |= g_worldalignedbone[i].flags;
  5662. printf("tagging bone: %s as world aligned (index %i, flags:%x)\n", g_bonetable[j].name, j, g_bonetable[j].flags );
  5663. }
  5664. }
  5665. //-----------------------------------------------------------------------------
  5666. // Links attachments
  5667. //-----------------------------------------------------------------------------
  5668. static void LinkAttachments()
  5669. {
  5670. int i, j, k;
  5671. // attachments may be connected to bones that can be optimized out
  5672. // so search through all the sources and move to a valid location
  5673. matrix3x4_t boneToPose;
  5674. matrix3x4_t world;
  5675. matrix3x4_t poseToBone;
  5676. for (i = 0; i < g_numattachments; i++)
  5677. {
  5678. bool found = false;
  5679. // search through known bones
  5680. for (k = 0; k < g_numbones; k++)
  5681. {
  5682. if ( !stricmp( g_attachment[i].bonename, g_bonetable[k].name ))
  5683. {
  5684. g_attachment[i].bone = k;
  5685. MatrixCopy( g_bonetable[k].boneToPose, boneToPose );
  5686. MatrixInvert( boneToPose, poseToBone );
  5687. // printf("%s : %d\n", g_bonetable[k].name, k );
  5688. found = true;
  5689. break;
  5690. }
  5691. }
  5692. if (!found)
  5693. {
  5694. // search all the loaded sources for the first occurance of the named bone
  5695. for (j = 0; j < g_numsources && !found; j++)
  5696. {
  5697. for (k = 0; k < g_source[j]->numbones && !found; k++)
  5698. {
  5699. if ( !stricmp( g_attachment[i].bonename, g_source[j]->localBone[k].name ) )
  5700. {
  5701. MatrixCopy( g_source[j]->boneToPose[k], boneToPose );
  5702. // check to make sure that this bone is actually referenced in the output model
  5703. // if not, try parent bone until we find a referenced bone in this chain
  5704. while (k != -1 && g_source[j]->boneGlobalToLocal[g_source[j]->boneLocalToGlobal[k]] != k)
  5705. {
  5706. k = g_source[j]->localBone[k].parent;
  5707. }
  5708. if (k == -1)
  5709. {
  5710. MdlError( "unable to find valid bone for attachment %s:%s\n",
  5711. g_attachment[i].name,
  5712. g_attachment[i].bonename );
  5713. }
  5714. MatrixInvert( g_source[j]->boneToPose[k], poseToBone );
  5715. g_attachment[i].bone = g_source[j]->boneLocalToGlobal[k];
  5716. found = true;
  5717. }
  5718. }
  5719. }
  5720. }
  5721. if (!found)
  5722. {
  5723. MdlError("unknown attachment link '%s'\n", g_attachment[i].bonename );
  5724. }
  5725. // printf("%s: %s / %s\n", g_attachment[i].name, g_attachment[i].bonename, g_bonetable[g_attachment[i].bone].name );
  5726. if (g_attachment[i].type & IS_ABSOLUTE)
  5727. {
  5728. MatrixCopy( g_attachment[i].local, world );
  5729. }
  5730. else
  5731. {
  5732. ConcatTransforms( boneToPose, g_attachment[i].local, world );
  5733. }
  5734. ConcatTransforms( poseToBone, world, g_attachment[i].local );
  5735. }
  5736. RemoveDuplicateAttachments();
  5737. // flag all bones used by attachments
  5738. for (i = 0; i < g_numattachments; i++)
  5739. {
  5740. j = g_attachment[i].bone;
  5741. while (j != -1)
  5742. {
  5743. g_bonetable[j].flags |= BONE_USED_BY_ATTACHMENT;
  5744. j = g_bonetable[j].parent;
  5745. }
  5746. }
  5747. }
  5748. //-----------------------------------------------------------------------------
  5749. // Links mouths
  5750. //-----------------------------------------------------------------------------
  5751. static void LinkMouths()
  5752. {
  5753. for (int i = 0; i < g_nummouths; i++)
  5754. {
  5755. int j;
  5756. for ( j = 0; j < g_numbones; j++)
  5757. {
  5758. if (g_mouth[i].bonename[0] && stricmp( g_mouth[i].bonename, g_bonetable[j].name) == 0)
  5759. break;
  5760. }
  5761. if (j >= g_numbones)
  5762. {
  5763. MdlError("unknown mouth link '%s'\n", g_mouth[i].bonename );
  5764. }
  5765. g_mouth[i].bone = j;
  5766. }
  5767. }
  5768. //-----------------------------------------------------------------------------
  5769. //
  5770. //-----------------------------------------------------------------------------
  5771. static float CalcPoseParameterValue( int control, RadianEuler &angle, Vector &pos )
  5772. {
  5773. switch( control )
  5774. {
  5775. case STUDIO_X:
  5776. return pos.x;
  5777. case STUDIO_Y:
  5778. return pos.y;
  5779. case STUDIO_Z:
  5780. return pos.z;
  5781. case STUDIO_XR:
  5782. return RAD2DEG( angle.x );
  5783. case STUDIO_YR:
  5784. return RAD2DEG( angle.y );
  5785. case STUDIO_ZR:
  5786. return RAD2DEG( angle.z );
  5787. }
  5788. return 0.0;
  5789. }
  5790. static void CalcPoseParameters( void )
  5791. {
  5792. int i;
  5793. matrix3x4_t boneToWorld[MAXSTUDIOBONES];
  5794. RadianEuler angles;
  5795. Vector pos;
  5796. for (i = 0; i < g_sequence.Count(); i++)
  5797. {
  5798. s_sequence_t *pseq = &g_sequence[i];
  5799. for (int iPose = 0; iPose < 2; iPose++)
  5800. {
  5801. if (pseq->groupsize[iPose] > 1)
  5802. {
  5803. if (pseq->paramattachment[iPose] != -1)
  5804. {
  5805. int j0 = pseq->paramindex[iPose];
  5806. int n0 = pseq->paramattachment[iPose];
  5807. int k0 = g_attachment[n0].bone;
  5808. matrix3x4_t boneToWorldRel;
  5809. matrix3x4_t boneToWorldMid;
  5810. matrix3x4_t worldToBoneMid;
  5811. matrix3x4_t boneRel;
  5812. // printf("%s\n", pseq->name );
  5813. if (pseq->paramanim == NULL)
  5814. {
  5815. pseq->paramanim = g_panimation[0];
  5816. }
  5817. if (pseq->paramcompanim == NULL)
  5818. {
  5819. pseq->paramcompanim = pseq->paramanim;
  5820. }
  5821. // calculate what "zero" looks like to the attachment
  5822. CalcBoneTransforms( pseq->paramanim, 0, boneToWorld );
  5823. ConcatTransforms( boneToWorld[k0], g_attachment[n0].local, boneToWorldMid );
  5824. MatrixAngles( boneToWorldMid, angles, pos );
  5825. // printf("%s : %s : %6.2f %6.2f %6.2f : %6.2f %6.2f %6.2f\n", pseq->name, g_pose[j0].name, RAD2DEG( angles.x ), RAD2DEG( angles.y ), RAD2DEG( angles.z ), pos.x, pos.y, pos.z );
  5826. MatrixInvert( boneToWorldMid, worldToBoneMid );
  5827. if ( g_verbose )
  5828. {
  5829. printf("%s : %s", pseq->name, g_pose[j0].name );
  5830. }
  5831. // for 2D animation, figure out what opposite row/column to use
  5832. // FIXME: make these 2D instead of 2 1D!
  5833. int m[2];
  5834. bool found = false;
  5835. if (pseq->paramcenter != NULL)
  5836. {
  5837. for (int i0 = 0; !found && i0 < pseq->groupsize[0]; i0++)
  5838. {
  5839. for (int i1 = 0; !found && i1 < pseq->groupsize[1]; i1++)
  5840. {
  5841. if (pseq->panim[i0][i1] == pseq->paramcenter)
  5842. {
  5843. m[0] = i0;
  5844. m[1] = i1;
  5845. found = true;
  5846. }
  5847. }
  5848. }
  5849. }
  5850. if (!found)
  5851. {
  5852. m[1-iPose] = (pseq->groupsize[1-iPose]) / 2;
  5853. }
  5854. // find changes to attachment
  5855. for (m[iPose] = 0; m[iPose] < pseq->groupsize[iPose]; m[iPose]++)
  5856. {
  5857. CalcBoneTransforms( pseq->panim[m[0]][m[1]], pseq->paramcompanim, 0, boneToWorld );
  5858. ConcatTransforms( boneToWorld[k0], g_attachment[n0].local, boneToWorldRel );
  5859. ConcatTransforms( worldToBoneMid, boneToWorldRel, boneRel );
  5860. MatrixAngles( boneRel, angles, pos );
  5861. // printf("%6.2f %6.2f %6.2f : %6.2f %6.2f %6.2f\n", RAD2DEG( angles.x ), RAD2DEG( angles.y ), RAD2DEG( angles.z ), pos.x, pos.y, pos.z );
  5862. float v = CalcPoseParameterValue( pseq->paramcontrol[iPose], angles, pos );
  5863. if ( g_verbose )
  5864. {
  5865. printf(" %6.2f", v );
  5866. }
  5867. if (iPose == 0)
  5868. {
  5869. pseq->param0[m[iPose]] = v;
  5870. }
  5871. else
  5872. {
  5873. pseq->param1[m[iPose]] = v;
  5874. }
  5875. // pseq->param1[i0][i1] = CalcPoseParameterValue( pseq->paramcontrol[1], angles, pos );
  5876. if (m[iPose] == 0)
  5877. {
  5878. pseq->paramstart[iPose] = (iPose == 0) ? pseq->param0[m[iPose]] : pseq->param1[m[iPose]];
  5879. }
  5880. if (m[iPose] == pseq->groupsize[iPose] - 1)
  5881. {
  5882. pseq->paramend[iPose] = (iPose == 0) ? pseq->param0[m[iPose]] : pseq->param1[m[iPose]];
  5883. }
  5884. }
  5885. if ( g_verbose )
  5886. {
  5887. printf("\n");
  5888. }
  5889. if (fabs( pseq->paramstart[iPose] - pseq->paramend[iPose]) < 0.01 )
  5890. {
  5891. MdlError( "calcblend failed in %s\n", pseq->name );
  5892. }
  5893. g_pose[j0].min = MIN( g_pose[j0].min, pseq->paramstart[iPose] );
  5894. g_pose[j0].max = MAX( g_pose[j0].max, pseq->paramstart[iPose] );
  5895. g_pose[j0].min = MIN( g_pose[j0].min, pseq->paramend[iPose] );
  5896. g_pose[j0].max = MAX( g_pose[j0].max, pseq->paramend[iPose] );
  5897. }
  5898. else
  5899. {
  5900. for (int m = 0; m < pseq->groupsize[iPose]; m++)
  5901. {
  5902. float f = (m / (float)(pseq->groupsize[iPose] - 1.0));
  5903. if (iPose == 0)
  5904. {
  5905. pseq->param0[m] = pseq->paramstart[iPose] * (1.0 - f) + pseq->paramend[iPose] * f;
  5906. }
  5907. else
  5908. {
  5909. pseq->param1[m] = pseq->paramstart[iPose] * (1.0 - f) + pseq->paramend[iPose] * f;
  5910. }
  5911. }
  5912. }
  5913. }
  5914. }
  5915. }
  5916. // exit(0);
  5917. }
  5918. //-----------------------------------------------------------------------------
  5919. // Link ikchains
  5920. //-----------------------------------------------------------------------------
  5921. static void LinkIKChains( )
  5922. {
  5923. int i, k;
  5924. // create IK links
  5925. for (i = 0; i < g_numikchains; i++)
  5926. {
  5927. g_ikchain[i].numlinks = 3;
  5928. k = findGlobalBone( g_ikchain[i].bonename );
  5929. if (k == -1)
  5930. {
  5931. MdlError("unknown bone '%s' in ikchain '%s'\n", g_ikchain[i].bonename, g_ikchain[i].name );
  5932. }
  5933. g_ikchain[i].link[2].bone = k;
  5934. g_bonetable[k].flags |= BONE_USED_BY_ATTACHMENT;
  5935. k = g_bonetable[k].parent;
  5936. if (k == -1)
  5937. {
  5938. MdlError("ikchain '%s' too close to root, no parent knee/elbow\n", g_ikchain[i].name );
  5939. }
  5940. g_ikchain[i].link[1].bone = k;
  5941. g_bonetable[k].flags |= BONE_USED_BY_ATTACHMENT;
  5942. k = g_bonetable[k].parent;
  5943. if (k == -1)
  5944. {
  5945. MdlError("ikchain '%s' too close to root, no parent hip/shoulder\n", g_ikchain[i].name );
  5946. }
  5947. g_ikchain[i].link[0].bone = k;
  5948. g_bonetable[k].flags |= BONE_USED_BY_ATTACHMENT;
  5949. // FIXME: search for toes
  5950. }
  5951. }
  5952. //-----------------------------------------------------------------------------
  5953. // Link ikchains
  5954. //-----------------------------------------------------------------------------
  5955. static void LinkIKLocks( )
  5956. {
  5957. int i, j;
  5958. // create IK links
  5959. for (i = 0; i < g_numikautoplaylocks; i++)
  5960. {
  5961. for (j = 0; j < g_numikchains; j++)
  5962. {
  5963. if (stricmp( g_ikchain[j].name, g_ikautoplaylock[i].name) == 0)
  5964. {
  5965. break;
  5966. }
  5967. }
  5968. if (j == g_numikchains)
  5969. {
  5970. MdlError("unknown chain '%s' in ikautoplaylock\n", g_ikautoplaylock[i].name );
  5971. }
  5972. g_ikautoplaylock[i].chain = j;
  5973. }
  5974. int k;
  5975. for (k = 0; k < g_sequence.Count(); k++)
  5976. {
  5977. for (i = 0; i < g_sequence[k].numiklocks; i++)
  5978. {
  5979. for (j = 0; j < g_numikchains; j++)
  5980. {
  5981. if (stricmp( g_ikchain[j].name, g_sequence[k].iklock[i].name) == 0)
  5982. {
  5983. break;
  5984. }
  5985. }
  5986. if (j == g_numikchains)
  5987. {
  5988. MdlError("unknown chain '%s' in sequence iklock\n", g_sequence[k].iklock[i].name );
  5989. }
  5990. g_sequence[k].iklock[i].chain = j;
  5991. }
  5992. }
  5993. }
  5994. //-----------------------------------------------------------------------------
  5995. // Process IK links
  5996. //-----------------------------------------------------------------------------
  5997. s_ikrule_t *FindPrevIKRule( s_animation_t *panim, int iRule )
  5998. {
  5999. int i, j;
  6000. s_ikrule_t *pRule = &panim->ikrule[iRule];
  6001. for (i = 1; i < panim->numikrules; i++)
  6002. {
  6003. j = ( iRule - i + panim->numikrules) % panim->numikrules;
  6004. if (panim->ikrule[j].chain == pRule->chain)
  6005. return &panim->ikrule[j];
  6006. }
  6007. return pRule;
  6008. }
  6009. s_ikrule_t *FindNextIKRule( s_animation_t *panim, int iRule )
  6010. {
  6011. int i, j;
  6012. s_ikrule_t *pRule = &panim->ikrule[iRule];
  6013. for (i = 1; i < panim->numikrules; i++)
  6014. {
  6015. j = (iRule + i ) % panim->numikrules;
  6016. if (panim->ikrule[j].chain == pRule->chain)
  6017. return &panim->ikrule[j];
  6018. }
  6019. return pRule;
  6020. }
  6021. //-----------------------------------------------------------------------------
  6022. // Purpose: don't allow bones to change their length if they're predefined.
  6023. // go through all the animations and reset them, but move anything on an ikchain back to where it was.
  6024. //-----------------------------------------------------------------------------
  6025. static void LockBoneLengths()
  6026. {
  6027. int i, j, k;
  6028. int n;
  6029. if (!g_bLockBoneLengths)
  6030. return;
  6031. Vector origLocalPos[MAXSTUDIOBONES];
  6032. // find original lengths
  6033. for (k = 0; k < g_numbones; k++)
  6034. {
  6035. MatrixPosition( g_bonetable[k].rawLocalOriginal, origLocalPos[k] );
  6036. if ( g_verbose )
  6037. {
  6038. Vector prev, delta;
  6039. MatrixPosition( g_bonetable[k].rawLocal, prev );
  6040. delta = prev - origLocalPos[k];
  6041. printf("%s - %f %f %f\n", g_bonetable[k].name, delta.x, delta.y, delta.z );
  6042. }
  6043. }
  6044. for (i = 0; i < g_numani; i++)
  6045. {
  6046. s_animation_t *panim = g_panimation[i];
  6047. if (panim->flags & STUDIO_DELTA)
  6048. continue;
  6049. for (j = 0; j < panim->numframes; j++)
  6050. {
  6051. matrix3x4a_t boneToWorldOriginal[MAXSTUDIOBONES];
  6052. matrix3x4a_t boneToWorld[MAXSTUDIOBONES];
  6053. // calc original transformations
  6054. CalcBoneTransforms( panim, j, boneToWorldOriginal );
  6055. // force bones back to original lengths
  6056. for (k = 0; k < g_numbones; k++)
  6057. {
  6058. if (g_bonetable[k].parent != -1)
  6059. {
  6060. //Vector delta = panim->sanim[j][k].pos - origLocalPos[k];
  6061. //printf("%f %f %f\n", delta.x, delta.y, delta.z );
  6062. panim->sanim[j][k].pos = origLocalPos[k];
  6063. }
  6064. }
  6065. // calc new transformations
  6066. CalcBoneTransforms( panim, j, boneToWorld );
  6067. for (n = 0; n < g_numikchains; n++)
  6068. {
  6069. if (panim->weight[g_ikchain[n].link[2].bone] > 0)
  6070. {
  6071. Vector worldPos;
  6072. MatrixPosition( boneToWorldOriginal[g_ikchain[n].link[2].bone], worldPos );
  6073. Studio_SolveIK(
  6074. g_ikchain[n].link[0].bone,
  6075. g_ikchain[n].link[1].bone,
  6076. g_ikchain[n].link[2].bone,
  6077. worldPos,
  6078. boneToWorld );
  6079. solveBone( panim, j, g_ikchain[n].link[0].bone, boneToWorld );
  6080. solveBone( panim, j, g_ikchain[n].link[1].bone, boneToWorld );
  6081. solveBone( panim, j, g_ikchain[n].link[2].bone, boneToWorld );
  6082. }
  6083. }
  6084. }
  6085. }
  6086. }
  6087. void WrapToFrameRange( int &inputFrame, const s_animation_t *panim )
  6088. {
  6089. inputFrame = (panim->numframes + inputFrame) % panim->numframes;
  6090. if ( inputFrame < 0 )
  6091. inputFrame += panim->numframes;
  6092. }
  6093. int SortPosAnim( const void *fl1, const void *fl2 )
  6094. {
  6095. if ( *(const float *)fl1 >= *(const float *)fl2 )
  6096. return 1;
  6097. return -1;
  6098. }
  6099. struct s_footdown_t
  6100. {
  6101. int nIndex;
  6102. int nLength;
  6103. s_footdown_t()
  6104. {
  6105. nIndex = -1;
  6106. nLength = 0;
  6107. }
  6108. };
  6109. //-----------------------------------------------------------------------------
  6110. // Purpose: go through all the IK rules and calculate the animated path the IK'd
  6111. // end point moves relative to its IK target.
  6112. //-----------------------------------------------------------------------------
  6113. static void ProcessIKRules( )
  6114. {
  6115. int i, j, k;
  6116. // copy source animations
  6117. for (i = 0; i < g_numani; i++)
  6118. {
  6119. s_animation_t *panim = g_panimation[i];
  6120. const char *pAnimationName = g_panimation[i]->animationname;
  6121. s_sourceanim_t *pSourceAnim = FindSourceAnim( panim->source, pAnimationName );
  6122. for (j = 0; j < panim->numcmds; j++)
  6123. {
  6124. if ( panim->cmds[j].cmd == CMD_IKFIXUP )
  6125. {
  6126. fixupIKErrors( panim, panim->cmds[j].u.ikfixup.pRule );
  6127. }
  6128. if (panim->cmds[j].cmd != CMD_IKRULE)
  6129. continue;
  6130. if (panim->numikrules >= MAXSTUDIOIKRULES)
  6131. {
  6132. MdlError("Too many IK rules in %s (%s)\n", panim->name, panim->filename );
  6133. }
  6134. s_ikrule_t *pRule = &panim->ikrule[panim->numikrules++];
  6135. // make a copy of the rule;
  6136. *pRule = *panim->cmds[j].u.ikrule.pRule;
  6137. // -2 is a hack to tag the rule as 'auto-detect footsteps'
  6138. if ( pRule->start == -2 )
  6139. {
  6140. // use the end var to store the step index
  6141. if ( pRule->end > 1 )
  6142. {
  6143. for (k=1; k<pRule->end; k++)
  6144. {
  6145. s_ikrule_t *pRuleSub = &panim->ikrule[panim->numikrules++];
  6146. // make a copy of the rule;
  6147. *pRuleSub = *panim->cmds[j].u.ikrule.pRule;
  6148. pRuleSub->peak = k;
  6149. }
  6150. }
  6151. pRule->peak = 0;
  6152. }
  6153. }
  6154. for (j = 0; j < panim->numikrules; j++)
  6155. {
  6156. s_ikrule_t *pRule = &panim->ikrule[j];
  6157. if ( pRule->start == -2 )
  6158. {
  6159. // automatically tag footsteps
  6160. //magic numbers
  6161. float flModuloClamp = 0.3f;
  6162. float flHeightFailsafe = 1;
  6163. int nStepIndex = pRule->peak;
  6164. int nNumSteps = pRule->end;
  6165. matrix3x4_t boneToWorld[MAXSTUDIOBONES];
  6166. int nBone = findGlobalBone( pRule->bonename );
  6167. CUtlVector<float> vecPosAnim;
  6168. CUtlVector<float> vecPosAnimSorted;
  6169. int nHighestIndex = INT_MIN;
  6170. float flHighestZ = FLT_MIN;
  6171. // gather z positions, find the lowest z
  6172. for ( int nFrame = 0; nFrame < panim->numframes; nFrame++ )
  6173. {
  6174. CalcBoneTransforms( panim, nFrame, boneToWorld );
  6175. Vector vecTemp;
  6176. MatrixPosition( boneToWorld[nBone], vecTemp );
  6177. vecPosAnim.AddToTail( vecTemp.z - fmod( vecTemp.z, flModuloClamp ) );
  6178. vecPosAnimSorted.AddToTail( vecTemp.z - fmod( vecTemp.z, flModuloClamp ) );
  6179. if ( vecTemp.z > flHighestZ )
  6180. {
  6181. nHighestIndex = nFrame;
  6182. flHighestZ = vecTemp.z;
  6183. }
  6184. }
  6185. qsort( vecPosAnimSorted.Base(), vecPosAnimSorted.Count(), sizeof(float), SortPosAnim );
  6186. // crawl up from the lowest z, finding the number of curve intersections.
  6187. // we want 2x nNumSteps intersections.
  6188. bool bFoundSteps = false;
  6189. float flCrawlHeight = vecPosAnimSorted[0];
  6190. int nCrawlIndex = -1;
  6191. for ( int nCrawl = 0; nCrawl < vecPosAnimSorted.Count(); nCrawl++ )
  6192. {
  6193. flCrawlHeight = vecPosAnimSorted[nCrawl];
  6194. if ( bFoundSteps && flCrawlHeight > vecPosAnimSorted[0] + flHeightFailsafe )
  6195. break;
  6196. int nNumCurveIntersections = 0;
  6197. for ( int nFrame = nHighestIndex; nFrame < panim->numframes+nHighestIndex; nFrame++ )
  6198. {
  6199. int nCurrent = nFrame;
  6200. WrapToFrameRange(nCurrent, panim);
  6201. int nNext = nFrame+1;
  6202. WrapToFrameRange(nNext, panim);
  6203. if ( (vecPosAnim[nCurrent] > flCrawlHeight && vecPosAnim[nNext] <= flCrawlHeight) || (vecPosAnim[nCurrent] <= flCrawlHeight && vecPosAnim[nNext] > flCrawlHeight) )
  6204. {
  6205. nNumCurveIntersections++;
  6206. }
  6207. }
  6208. if ( nNumCurveIntersections == nNumSteps * 2 )
  6209. {
  6210. bFoundSteps = true;
  6211. nCrawlIndex = nCrawl;
  6212. }
  6213. if ( bFoundSteps && nNumCurveIntersections != nNumSteps * 2 )
  6214. break;
  6215. }
  6216. Assert( nCrawlIndex != -1 );
  6217. if ( nCrawlIndex == -1 )
  6218. {
  6219. //for ( int nFrame = 0; nFrame < panim->numframes; nFrame++ )
  6220. //{
  6221. // char szTemp[128] = "";
  6222. // for ( int cc=0; cc<vecPosAnim[nFrame] * 5; cc++ )
  6223. // {
  6224. // V_strcat_safe( szTemp, "*" );
  6225. // }
  6226. // Msg( "%s\n", szTemp );
  6227. //}
  6228. MdlError( "Failed to detect exactly %i footsteps in %s.\n", nNumSteps, panim->name );
  6229. }
  6230. // extract footdowns from the last successful crawlheight
  6231. CUtlVector<s_footdown_t> vecFootDowns;
  6232. vecFootDowns.RemoveAll();
  6233. s_footdown_t temp;
  6234. flCrawlHeight = vecPosAnimSorted[nCrawlIndex];
  6235. for ( int nFrame = nHighestIndex; nFrame < panim->numframes+nHighestIndex; nFrame++ )
  6236. {
  6237. int nCurrent = nFrame;
  6238. WrapToFrameRange(nCurrent, panim);
  6239. int nNext = nFrame+1;
  6240. WrapToFrameRange(nNext, panim);
  6241. if ( (vecPosAnim[nCurrent] > flCrawlHeight && vecPosAnim[nNext] <= flCrawlHeight) )
  6242. {
  6243. temp.nIndex = nCurrent;
  6244. temp.nLength = 0;
  6245. }
  6246. if ( vecPosAnim[nCurrent] <= flCrawlHeight )
  6247. {
  6248. temp.nLength++;
  6249. }
  6250. if ( (vecPosAnim[nCurrent] <= flCrawlHeight && vecPosAnim[nNext] > flCrawlHeight) )
  6251. {
  6252. vecFootDowns.AddToTail(temp);
  6253. }
  6254. }
  6255. bool bSuccess = ( bFoundSteps && vecFootDowns.Count() > 0 && vecFootDowns.Count() == nNumSteps && vecFootDowns.Count() > nStepIndex );
  6256. Assert( bSuccess );
  6257. if ( !bSuccess )
  6258. MdlError( "Failed to detect footsteps in %s.\n", panim->name );
  6259. s_footdown_t FootDown = vecFootDowns[ nStepIndex ];
  6260. int nFootDownFrame = vecFootDowns[ nStepIndex ].nIndex;
  6261. int nFootDownDuration = vecFootDowns[ nStepIndex ].nLength;
  6262. //Msg( "Detected footstep (%s) on frame %i of %s. Step #(%i).\n", pRule->bonename, nFootDownFrame, panim->name, nStepIndex );
  6263. pRule->start = nFootDownFrame;
  6264. pRule->peak = nFootDownFrame + (int)(nFootDownDuration * 0.2f);
  6265. pRule->tail = nFootDownFrame + (int)(nFootDownDuration * 0.8f);
  6266. pRule->end = nFootDownFrame + (int)(nFootDownDuration * 1.0f);
  6267. WrapToFrameRange( pRule->start, panim );
  6268. WrapToFrameRange( pRule->peak, panim );
  6269. WrapToFrameRange( pRule->tail, panim );
  6270. WrapToFrameRange( pRule->end, panim );
  6271. //for ( int nFrame = 0; nFrame < panim->numframes; nFrame++ )
  6272. //{
  6273. // char szTemp[128] = "";
  6274. //
  6275. // for ( int cc=0; cc<vecPosAnim[nFrame] * 5; cc++ )
  6276. // {
  6277. // V_strcat_safe( szTemp, "*" );
  6278. // }
  6279. //
  6280. // if ( nFrame == pRule->start )
  6281. // V_strcat_safe( szTemp, "<-start--------" );
  6282. //
  6283. // if ( nFrame == pRule->peak )
  6284. // V_strcat_safe( szTemp, "<-peak---------" );
  6285. //
  6286. // if ( nFrame == pRule->tail )
  6287. // V_strcat_safe( szTemp, "<-tail---------" );
  6288. //
  6289. // if ( nFrame == pRule->end )
  6290. // V_strcat_safe( szTemp, "<-end----------" );
  6291. //
  6292. // Msg( "%s\n", szTemp );
  6293. //}
  6294. //Msg( "************************\n" );
  6295. }
  6296. if (pRule->start == 0 && pRule->peak == 0 && pRule->tail == 0 && pRule->end == 0)
  6297. {
  6298. pRule->tail = panim->numframes - 1;
  6299. pRule->end = panim->numframes - 1;
  6300. }
  6301. if (pRule->start != -1 && pRule->peak == -1 && pRule->tail == -1 && pRule->end != -1)
  6302. {
  6303. pRule->peak = (pRule->start + pRule->end) / 2;
  6304. pRule->tail = (pRule->start + pRule->end) / 2;
  6305. }
  6306. if (pRule->start != -1 && pRule->peak == -1 && pRule->tail != -1)
  6307. {
  6308. pRule->peak = (pRule->start + pRule->tail) / 2;
  6309. }
  6310. if (pRule->peak != -1 && pRule->tail == -1 && pRule->end != -1)
  6311. {
  6312. pRule->tail = (pRule->peak + pRule->end) / 2;
  6313. }
  6314. if (pRule->peak == -1)
  6315. {
  6316. pRule->start = 0;
  6317. pRule->peak = 0;
  6318. }
  6319. if (pRule->tail == -1)
  6320. {
  6321. pRule->tail = panim->numframes - 1;
  6322. pRule->end = panim->numframes - 1;
  6323. }
  6324. if (pRule->contact == -1)
  6325. {
  6326. pRule->contact = pRule->peak;
  6327. }
  6328. // huh, make up start and end numbers
  6329. if (pRule->start == -1)
  6330. {
  6331. s_ikrule_t *pPrev = FindPrevIKRule( panim, j );
  6332. if (pPrev->slot == pRule->slot)
  6333. {
  6334. if (pRule->peak < pPrev->tail)
  6335. {
  6336. pRule->start = pRule->peak + (pPrev->tail - pRule->peak) / 2;
  6337. }
  6338. else
  6339. {
  6340. pRule->start = pRule->peak + (pPrev->tail - pRule->peak + panim->numframes - 1) / 2;
  6341. }
  6342. pRule->start = (pRule->start + panim->numframes / 2) % (panim->numframes - 1);
  6343. pPrev->end = (pRule->start + panim->numframes - 1) % (panim->numframes - 1);
  6344. }
  6345. else
  6346. {
  6347. pRule->start = pPrev->tail;
  6348. pPrev->end = pRule->peak;
  6349. }
  6350. // printf("%s : %d (%d) : %d %d %d %d\n", panim->name, pRule->chain, panim->numframes - 1, pRule->start, pRule->peak, pRule->tail, pRule->end );
  6351. }
  6352. // huh, make up start and end numbers
  6353. if (pRule->end == -1)
  6354. {
  6355. s_ikrule_t *pNext = FindNextIKRule( panim, j );
  6356. if (pNext->slot == pRule->slot)
  6357. {
  6358. if (pNext->peak < pRule->tail)
  6359. {
  6360. pNext->start = pNext->peak + (pRule->tail - pNext->peak) / 2;
  6361. }
  6362. else
  6363. {
  6364. pNext->start = pNext->peak + (pRule->tail - pNext->peak + panim->numframes - 1) / 2;
  6365. }
  6366. pNext->start = (pNext->start + panim->numframes / 2) % (panim->numframes - 1);
  6367. pRule->end = (pNext->start + panim->numframes - 1) % (panim->numframes - 1);
  6368. }
  6369. else
  6370. {
  6371. pNext->start = pRule->tail;
  6372. pRule->end = pNext->peak;
  6373. }
  6374. // printf("%s : %d (%d) : %d %d %d %d\n", panim->name, pRule->chain, panim->numframes - 1, pRule->start, pRule->peak, pRule->tail, pRule->end );
  6375. }
  6376. // check for wrapping
  6377. if (pRule->peak < pRule->start)
  6378. {
  6379. pRule->peak += panim->numframes - 1;
  6380. }
  6381. if (pRule->tail < pRule->peak)
  6382. {
  6383. pRule->tail += panim->numframes - 1;
  6384. }
  6385. if (pRule->end < pRule->tail)
  6386. {
  6387. pRule->end += panim->numframes - 1;
  6388. }
  6389. if (pRule->contact < pRule->start)
  6390. {
  6391. pRule->contact += panim->numframes - 1;
  6392. }
  6393. /*
  6394. printf("%s : %d (%d) : %d %d %d %d : %s\n", panim->name, pRule->chain, panim->numframes - 1, pRule->start, pRule->peak, pRule->tail, pRule->end,
  6395. pRule->usesequence ? "usesequence" : pRule->usesource ? "source" : "" );
  6396. */
  6397. pRule->errorData.numerror = pRule->end - pRule->start + 1;
  6398. if (pRule->end >= panim->numframes)
  6399. pRule->errorData.numerror = pRule->errorData.numerror + 2;
  6400. pRule->errorData.pError = (s_streamdata_t *)calloc( pRule->errorData.numerror, sizeof( s_streamdata_t ));
  6401. int n = 0;
  6402. if (pRule->usesequence)
  6403. {
  6404. // FIXME: bah, this is horrendously hacky, add a damn back pointer
  6405. for (n = 0; n < g_sequence.Count(); n++)
  6406. {
  6407. if (g_sequence[n].panim[0][0] == panim)
  6408. break;
  6409. }
  6410. }
  6411. switch( pRule->type )
  6412. {
  6413. case IK_SELF:
  6414. {
  6415. matrix3x4_t boneToWorld[MAXSTUDIOBONES];
  6416. matrix3x4_t worldToBone;
  6417. matrix3x4_t local;
  6418. if (strlen(pRule->bonename) == 0)
  6419. {
  6420. pRule->bone = -1;
  6421. }
  6422. else
  6423. {
  6424. pRule->bone = findGlobalBone( pRule->bonename );
  6425. if (pRule->bone == -1)
  6426. {
  6427. MdlError("unknown bone '%s' in ikrule\n", pRule->bonename );
  6428. }
  6429. }
  6430. for (k = 0; k < pRule->errorData.numerror; k++)
  6431. {
  6432. if (pRule->usesequence)
  6433. {
  6434. CalcSeqTransforms( n, k + pRule->start, boneToWorld );
  6435. }
  6436. else if (pRule->usesource)
  6437. {
  6438. matrix3x4_t srcBoneToWorld[MAXSTUDIOSRCBONES];
  6439. BuildRawTransforms( panim->source, pAnimationName, k + pRule->start + panim->startframe - pSourceAnim->startframe, panim->scale, panim->adjust, panim->rotation, panim->flags, srcBoneToWorld );
  6440. TranslateAnimations( panim->source, srcBoneToWorld, boneToWorld );
  6441. }
  6442. else
  6443. {
  6444. CalcBoneTransforms( panim, k + pRule->start, boneToWorld );
  6445. }
  6446. if (pRule->bone != -1)
  6447. {
  6448. MatrixInvert( boneToWorld[pRule->bone], worldToBone );
  6449. ConcatTransforms( worldToBone, boneToWorld[g_ikchain[pRule->chain].link[2].bone], local );
  6450. }
  6451. else
  6452. {
  6453. MatrixCopy( boneToWorld[g_ikchain[pRule->chain].link[2].bone], local );
  6454. }
  6455. MatrixAngles( local, pRule->errorData.pError[k].q, pRule->errorData.pError[k].pos );
  6456. /*
  6457. QAngle ang;
  6458. QuaternionAngles( pRule->errorData.pError[k].q, ang );
  6459. printf("%d %.1f %.1f %.1f : %.1f %.1f %.1f\n",
  6460. k,
  6461. pRule->errorData.pError[k].pos.x, pRule->errorData.pError[k].pos.y, pRule->errorData.pError[k].pos.z,
  6462. ang.x, ang.y, ang.z );
  6463. */
  6464. }
  6465. }
  6466. break;
  6467. case IK_WORLD:
  6468. break;
  6469. case IK_ATTACHMENT:
  6470. {
  6471. matrix3x4_t boneToWorld[MAXSTUDIOBONES];
  6472. matrix3x4_t worldToBone;
  6473. matrix3x4_t local;
  6474. int bone = g_ikchain[pRule->chain].link[2].bone;
  6475. CalcBoneTransforms( panim, pRule->contact, boneToWorld );
  6476. // FIXME: add in motion
  6477. // pRule->pos = footfall;
  6478. // pRule->q = RadianEuler( 0, 0, 0 );
  6479. if (strlen(pRule->bonename) == 0)
  6480. {
  6481. if (pRule->bone != -1)
  6482. {
  6483. pRule->bone = bone;
  6484. }
  6485. }
  6486. else
  6487. {
  6488. pRule->bone = findGlobalBone( pRule->bonename );
  6489. if (pRule->bone == -1)
  6490. {
  6491. MdlError("unknown bone '%s' in ikrule\n", pRule->bonename );
  6492. }
  6493. }
  6494. if (pRule->bone != -1)
  6495. {
  6496. // FIXME: look for local bones...
  6497. CalcBoneTransforms( panim, pRule->contact, boneToWorld );
  6498. MatrixAngles( boneToWorld[pRule->bone], pRule->q, pRule->pos );
  6499. }
  6500. #if 0
  6501. printf("%d %.1f %.1f %.1f\n",
  6502. pRule->peak,
  6503. pRule->pos.x, pRule->pos.y, pRule->pos.z );
  6504. #endif
  6505. for (k = 0; k < pRule->errorData.numerror; k++)
  6506. {
  6507. int t = k + pRule->start;
  6508. if (pRule->usesequence)
  6509. {
  6510. CalcSeqTransforms( n, t, boneToWorld );
  6511. }
  6512. else if (pRule->usesource)
  6513. {
  6514. matrix3x4_t srcBoneToWorld[MAXSTUDIOSRCBONES];
  6515. BuildRawTransforms( panim->source, pAnimationName, t + panim->startframe - pSourceAnim->startframe, srcBoneToWorld );
  6516. TranslateAnimations( panim->source, srcBoneToWorld, boneToWorld );
  6517. }
  6518. else
  6519. {
  6520. CalcBoneTransforms( panim, t, boneToWorld );
  6521. }
  6522. Vector pos = pRule->pos + calcMovement( panim, t, pRule->contact );
  6523. // printf("%2d : %2d : %4.2f %6.1f %6.1f %6.1f\n", k, t, s, pos.x, pos.y, pos.z );
  6524. AngleMatrix( RadianEuler( pRule->q ), pos, local );
  6525. MatrixInvert( local, worldToBone );
  6526. // calc position error
  6527. ConcatTransforms( worldToBone, boneToWorld[bone], local );
  6528. MatrixAngles( local, pRule->errorData.pError[k].q, pRule->errorData.pError[k].pos );
  6529. #if 0
  6530. QAngle ang;
  6531. QuaternionAngles( pRule->errorData.pError[k].q, ang );
  6532. printf("%d %.1f %.1f %.1f : %.1f %.1f %.1f\n",
  6533. k + pRule->start,
  6534. pRule->errorData.pError[k].pos.x, pRule->errorData.pError[k].pos.y, pRule->errorData.pError[k].pos.z,
  6535. ang.x, ang.y, ang.z );
  6536. #endif
  6537. }
  6538. }
  6539. break;
  6540. case IK_GROUND:
  6541. {
  6542. matrix3x4_t boneToWorld[MAXSTUDIOBONES];
  6543. matrix3x4_t worldToBone;
  6544. matrix3x4_t local;
  6545. int bone = g_ikchain[pRule->chain].link[2].bone;
  6546. if (pRule->usesequence)
  6547. {
  6548. CalcSeqTransforms( n, pRule->contact, boneToWorld );
  6549. }
  6550. else if (pRule->usesource)
  6551. {
  6552. matrix3x4_t srcBoneToWorld[MAXSTUDIOSRCBONES];
  6553. BuildRawTransforms( panim->source, pAnimationName, pRule->contact + panim->startframe - pSourceAnim->startframe, panim->scale, panim->adjust, panim->rotation, panim->flags, srcBoneToWorld );
  6554. TranslateAnimations( panim->source, srcBoneToWorld, boneToWorld );
  6555. }
  6556. else
  6557. {
  6558. CalcBoneTransforms( panim, pRule->contact, boneToWorld );
  6559. }
  6560. // FIXME: add in motion
  6561. Vector footfall;
  6562. VectorTransform( g_ikchain[pRule->chain].center, boneToWorld[bone], footfall );
  6563. footfall.z = pRule->floor;
  6564. AngleMatrix( RadianEuler( 0, 0, 0 ), footfall, local );
  6565. MatrixInvert( local, worldToBone );
  6566. pRule->pos = footfall;
  6567. pRule->q = Quaternion( RadianEuler( 0, 0, 0 ) );
  6568. #if 0
  6569. printf("%d %.1f %.1f %.1f\n",
  6570. pRule->peak,
  6571. pRule->pos.x, pRule->pos.y, pRule->pos.z );
  6572. #endif
  6573. float s;
  6574. for (k = 0; k < pRule->errorData.numerror; k++)
  6575. {
  6576. int t = k + pRule->start;
  6577. /*
  6578. if (t > pRule->end)
  6579. {
  6580. t = t - (panim->numframes - 1);
  6581. }
  6582. */
  6583. if (pRule->usesequence)
  6584. {
  6585. CalcSeqTransforms( n, t, boneToWorld );
  6586. }
  6587. else if (pRule->usesource)
  6588. {
  6589. matrix3x4_t srcBoneToWorld[MAXSTUDIOSRCBONES];
  6590. BuildRawTransforms( panim->source, pAnimationName, pRule->contact + panim->startframe - pSourceAnim->startframe, panim->scale, panim->adjust, panim->rotation, panim->flags, srcBoneToWorld );
  6591. TranslateAnimations( panim->source, srcBoneToWorld, boneToWorld );
  6592. }
  6593. else
  6594. {
  6595. CalcBoneTransforms( panim, t, boneToWorld );
  6596. }
  6597. Vector pos = pRule->pos + calcMovement( panim, t, pRule->contact );
  6598. s = 0.0;
  6599. Vector cur;
  6600. VectorTransform( g_ikchain[pRule->chain].center, boneToWorld[bone], cur );
  6601. cur.z = pos.z;
  6602. if (t < pRule->start || t >= pRule->end)
  6603. {
  6604. // s = (float)(t - pRule->start) / (pRule->peak - pRule->start);
  6605. // pos = startPos * (1 - s) + pos * s;
  6606. pos = cur;
  6607. }
  6608. else if (t < pRule->peak)
  6609. {
  6610. s = (float)(pRule->peak - t) / (pRule->peak - pRule->start);
  6611. s = 3 * s * s - 2 * s * s * s;
  6612. pos = pos * (1 - s) + cur * s;
  6613. }
  6614. else if (t > pRule->tail)
  6615. {
  6616. s = (float)(t - pRule->tail) / (pRule->end - pRule->tail);
  6617. s = 3 * s * s - 2 * s * s * s;
  6618. pos = pos * (1 - s) + cur * s;
  6619. //pos = endPos - calcMovement( panim, t, pRule->tail );
  6620. }
  6621. //MatrixPosition( boneToWorld[bone], pos );
  6622. //pos.z = pRule->floor;
  6623. // printf("%2d : %2d : %4.2f %6.1f %6.1f %6.1f\n", k, t, s, pos.x, pos.y, pos.z );
  6624. AngleMatrix( RadianEuler( pRule->q ), pos, local );
  6625. MatrixInvert( local, worldToBone );
  6626. // calc position error
  6627. ConcatTransforms( worldToBone, boneToWorld[bone], local );
  6628. MatrixAngles( local, pRule->errorData.pError[k].q, pRule->errorData.pError[k].pos );
  6629. #if 0
  6630. QAngle ang;
  6631. QuaternionAngles( pRule->errorData.pError[k].q, ang );
  6632. printf("%d %.1f %.1f %.1f : %.1f %.1f %.1f\n",
  6633. k + pRule->start,
  6634. pRule->errorData.pError[k].pos.x, pRule->errorData.pError[k].pos.y, pRule->errorData.pError[k].pos.z,
  6635. ang.x, ang.y, ang.z );
  6636. #endif
  6637. }
  6638. }
  6639. break;
  6640. case IK_RELEASE:
  6641. case IK_UNLATCH:
  6642. break;
  6643. }
  6644. }
  6645. if ((panim->flags & STUDIO_DELTA) || panim->noAutoIK)
  6646. continue;
  6647. // auto release ik chains that are moved but not referenced and have no explicit rules
  6648. int count[16];
  6649. for (j = 0; j < g_numikchains; j++)
  6650. {
  6651. count[j] = 0;
  6652. }
  6653. for (j = 0; j < panim->numikrules; j++)
  6654. {
  6655. count[panim->ikrule[j].chain]++;
  6656. }
  6657. for (j = 0; j < g_numikchains; j++)
  6658. {
  6659. if (count[j] == 0 && panim->weight[g_ikchain[j].link[2].bone] > 0.0)
  6660. {
  6661. // printf("%s - %s\n", panim->name, g_ikchain[j].name );
  6662. k = panim->numikrules++;
  6663. panim->ikrule[k].chain = j;
  6664. panim->ikrule[k].slot = j;
  6665. panim->ikrule[k].type = IK_RELEASE;
  6666. panim->ikrule[k].start = 0;
  6667. panim->ikrule[k].peak = 0;
  6668. panim->ikrule[k].tail = panim->numframes - 1;
  6669. panim->ikrule[k].end = panim->numframes - 1;
  6670. }
  6671. }
  6672. }
  6673. // exit(0);
  6674. // realign IK across multiple animations
  6675. for (i = 0; i < g_sequence.Count(); i++)
  6676. {
  6677. for (j = 0; j < g_sequence[i].groupsize[0]; j++)
  6678. {
  6679. for (k = 0; k < g_sequence[i].groupsize[1]; k++)
  6680. {
  6681. g_sequence[i].numikrules = MAX( g_sequence[i].numikrules, g_sequence[i].panim[j][k]->numikrules );
  6682. }
  6683. }
  6684. // check for mismatched ik rules
  6685. s_animation_t *panim1 = g_sequence[i].panim[0][0];
  6686. for (j = 0; j < g_sequence[i].groupsize[0]; j++)
  6687. {
  6688. for (k = 0; k < g_sequence[i].groupsize[1]; k++)
  6689. {
  6690. s_animation_t *panim2 = g_sequence[i].panim[j][k];
  6691. if (panim1->numikrules != panim2->numikrules)
  6692. {
  6693. MdlWarning( "%s - mismatched number of IK rules: \"%s\"[%i] \"%s\"[%i]\n",
  6694. g_sequence[i].name, panim1->name, panim1->numikrules, panim2->name, panim2->numikrules );
  6695. s_animation_t *panim_from;
  6696. s_animation_t *panim_to;
  6697. if ( panim1->numikrules > panim2->numikrules )
  6698. {
  6699. panim_from = panim1;
  6700. panim_to = panim2;
  6701. }
  6702. else
  6703. {
  6704. panim_from = panim2;
  6705. panim_to = panim1;
  6706. }
  6707. panim_to->numikrules = panim_from->numikrules;
  6708. for (int n = 0; n < panim_from->numikrules; n++)
  6709. {
  6710. panim_to->ikrule[n].type = panim_from->ikrule[n].type;
  6711. panim_to->ikrule[n].chain = panim_from->ikrule[n].chain;
  6712. panim_to->ikrule[n].slot = panim_from->ikrule[n].slot;
  6713. }
  6714. }
  6715. for (int n = 0; n < panim1->numikrules; n++)
  6716. {
  6717. if ((panim1->ikrule[n].type != panim2->ikrule[n].type) ||
  6718. (panim1->ikrule[n].chain != panim2->ikrule[n].chain) ||
  6719. (panim1->ikrule[n].slot != panim2->ikrule[n].slot))
  6720. {
  6721. MdlError( "%s - mismatched IK rule %d: \n\"%s\" : %d %d %d\n\"%s\" : %d %d %d\n",
  6722. g_sequence[i].name, n,
  6723. panim1->name, panim1->ikrule[n].type, panim1->ikrule[n].chain, panim1->ikrule[n].slot,
  6724. panim2->name, panim2->ikrule[n].type, panim2->ikrule[n].chain, panim2->ikrule[n].slot );
  6725. }
  6726. }
  6727. }
  6728. }
  6729. // FIXME: this doesn't check alignment!!!
  6730. for (j = 0; j < g_sequence[i].groupsize[0]; j++)
  6731. {
  6732. for (k = 0; k < g_sequence[i].groupsize[1]; k++)
  6733. {
  6734. for (int n = 0; n < g_sequence[i].panim[j][k]->numikrules; n++)
  6735. {
  6736. g_sequence[i].panim[j][k]->ikrule[n].index = n;
  6737. }
  6738. }
  6739. }
  6740. }
  6741. }
  6742. //-----------------------------------------------------------------------------
  6743. // CompressAnimations
  6744. //-----------------------------------------------------------------------------
  6745. static void CompressAnimations( )
  6746. {
  6747. int i, j, k, n, m;
  6748. // !!!
  6749. //g_minSectionFrameLimit = 100000;
  6750. //g_animblocksize = 0;
  6751. // find scales for all bones
  6752. for (j = 0; j < g_numbones; j++)
  6753. {
  6754. // printf("%s : ", g_bonetable[j].name );
  6755. for (k = 0; k < 6; k++)
  6756. {
  6757. float minv, maxv, scale;
  6758. float total_minv, total_maxv;
  6759. if (k < 3)
  6760. {
  6761. minv = -128.0;
  6762. maxv = 128.0;
  6763. total_maxv = total_minv = g_bonetable[j].pos[k];
  6764. }
  6765. else
  6766. {
  6767. minv = -M_PI / 8.0;
  6768. maxv = M_PI / 8.0;
  6769. total_maxv = total_minv = g_bonetable[j].rot[k-3];
  6770. }
  6771. for (i = 0; i < g_numani; i++)
  6772. {
  6773. for (n = 0; n < g_panimation[i]->numframes; n++)
  6774. {
  6775. float v = 0.0f;
  6776. switch(k)
  6777. {
  6778. case 0:
  6779. case 1:
  6780. case 2:
  6781. if (g_panimation[i]->flags & STUDIO_DELTA)
  6782. {
  6783. v = g_panimation[i]->sanim[n][j].pos[k];
  6784. }
  6785. else
  6786. {
  6787. v = ( g_panimation[i]->sanim[n][j].pos[k] - g_bonetable[j].pos[k] );
  6788. if (g_panimation[i]->sanim[n][j].pos[k] < total_minv)
  6789. total_minv = g_panimation[i]->sanim[n][j].pos[k];
  6790. if (g_panimation[i]->sanim[n][j].pos[k] > total_maxv)
  6791. total_maxv = g_panimation[i]->sanim[n][j].pos[k];
  6792. }
  6793. break;
  6794. case 3:
  6795. case 4:
  6796. case 5:
  6797. if (g_panimation[i]->flags & STUDIO_DELTA)
  6798. {
  6799. v = g_panimation[i]->sanim[n][j].rot[k-3];
  6800. }
  6801. else
  6802. {
  6803. v = ( g_panimation[i]->sanim[n][j].rot[k-3] - g_bonetable[j].rot[k-3] );
  6804. }
  6805. while (v >= M_PI)
  6806. v -= M_PI * 2;
  6807. while (v < -M_PI)
  6808. v += M_PI * 2;
  6809. break;
  6810. }
  6811. if (v < minv)
  6812. minv = v;
  6813. if (v > maxv)
  6814. maxv = v;
  6815. }
  6816. }
  6817. if (minv < maxv)
  6818. {
  6819. if (-minv> maxv)
  6820. {
  6821. scale = minv / -32768.0;
  6822. }
  6823. else
  6824. {
  6825. scale = maxv / 32767;
  6826. }
  6827. }
  6828. else
  6829. {
  6830. scale = 1.0 / 32.0;
  6831. }
  6832. switch(k)
  6833. {
  6834. case 0:
  6835. case 1:
  6836. case 2:
  6837. g_bonetable[j].posscale[k] = scale;
  6838. g_bonetable[j].posrange[k] = total_maxv - total_minv;
  6839. break;
  6840. case 3:
  6841. case 4:
  6842. case 5:
  6843. // printf("(%.1f %.1f)", RAD2DEG(minv), RAD2DEG(maxv) );
  6844. // printf("(%.1f)", RAD2DEG(maxv-minv) );
  6845. g_bonetable[j].rotscale[k-3] = scale;
  6846. break;
  6847. }
  6848. // printf("%.0f ", 1.0 / scale );
  6849. }
  6850. // printf("\n" );
  6851. }
  6852. // reduce animations
  6853. for (i = 0; i < g_numani; i++)
  6854. {
  6855. s_animation_t *panim = g_panimation[i];
  6856. s_source_t *psource = panim->source;
  6857. if (g_bCheckLengths)
  6858. {
  6859. printf("%s\n", panim->name );
  6860. }
  6861. // setup animation interior sections
  6862. int iSectionFrames = panim->numframes;
  6863. if ( panim->numframes >= g_minSectionFrameLimit )
  6864. {
  6865. iSectionFrames = g_sectionFrames;
  6866. panim->sectionframes = g_sectionFrames;
  6867. panim->numsections = (int)(panim->numframes / panim->sectionframes) + 2;
  6868. }
  6869. else
  6870. {
  6871. panim->sectionframes = 0;
  6872. panim->numsections = 1;
  6873. }
  6874. for (int w = 0; w < panim->numsections; w++)
  6875. {
  6876. int iStartFrame = w * iSectionFrames;
  6877. int iEndFrame = (w + 1) * iSectionFrames;
  6878. iStartFrame = MIN( iStartFrame, panim->numframes - 1 );
  6879. iEndFrame = MIN( iEndFrame, panim->numframes - 1 );
  6880. // printf("%s : %d %d\n", panim->name, iStartFrame, iEndFrame );
  6881. for (j = 0; j < g_numbones; j++)
  6882. {
  6883. for (k = 0; k < 6; k++)
  6884. {
  6885. panim->anim[w][j].num[k] = 0;
  6886. panim->anim[w][j].data[k] = NULL;
  6887. }
  6888. // skip bones that are always procedural
  6889. if (g_bonetable[j].flags & BONE_ALWAYS_PROCEDURAL)
  6890. {
  6891. // panim->weight[j] = 0.0;
  6892. continue;
  6893. }
  6894. // skip bones that have no influence
  6895. if (panim->weight[j] < 0.001)
  6896. continue;
  6897. int checkmin[6], checkmax[6];
  6898. for (k = 0; k < 6; k++)
  6899. {
  6900. checkmin[k] = 32767;
  6901. checkmax[k] = -32768;
  6902. }
  6903. for (k = 0; k < 6; k++)
  6904. {
  6905. mstudioanimvalue_t *pcount, *pvalue;
  6906. float v;
  6907. short value[MAXSTUDIOANIMFRAMES];
  6908. mstudioanimvalue_t data[MAXSTUDIOANIMFRAMES];
  6909. // find deltas from default pose
  6910. for (n = 0; n <= iEndFrame - iStartFrame; n++)
  6911. {
  6912. s_bone_t *psrcdata = &panim->sanim[n+iStartFrame][j];
  6913. switch(k)
  6914. {
  6915. case 0: /* X Position */
  6916. case 1: /* Y Position */
  6917. case 2: /* Z Position */
  6918. if (panim->flags & STUDIO_DELTA)
  6919. {
  6920. value[n] = psrcdata->pos[k] / g_bonetable[j].posscale[k];
  6921. // pre-scale pos delta since format only has room for "overall" weight
  6922. float r = panim->posweight[j] / panim->weight[j];
  6923. value[n] *= r;
  6924. }
  6925. else
  6926. {
  6927. value[n] = ( psrcdata->pos[k] - g_bonetable[j].pos[k] ) / g_bonetable[j].posscale[k];
  6928. }
  6929. break;
  6930. case 3: /* X Rotation */
  6931. case 4: /* Y Rotation */
  6932. case 5: /* Z Rotation */
  6933. if (panim->flags & STUDIO_DELTA)
  6934. {
  6935. v = psrcdata->rot[k-3];
  6936. }
  6937. else
  6938. {
  6939. v = ( psrcdata->rot[k-3] - g_bonetable[j].rot[k-3] );
  6940. }
  6941. while (v >= M_PI)
  6942. v -= M_PI * 2;
  6943. while (v < -M_PI)
  6944. v += M_PI * 2;
  6945. value[n] = v / g_bonetable[j].rotscale[k-3];
  6946. break;
  6947. }
  6948. checkmin[k] = MIN( value[n], checkmin[k] );
  6949. checkmax[k] = MAX( value[n], checkmax[k] );
  6950. }
  6951. if (n == 0)
  6952. MdlError("no animation frames: \"%s\"\n", psource->filename );
  6953. // FIXME: this compression algorithm needs work
  6954. // initialize animation RLE block
  6955. memset( data, 0, sizeof( data ) );
  6956. pcount = data;
  6957. pvalue = pcount + 1;
  6958. pcount->num.valid = 1;
  6959. pcount->num.total = 1;
  6960. pvalue->value = value[0];
  6961. pvalue++;
  6962. // build a RLE of deltas from the default pose
  6963. for (m = 1; m < n; m++)
  6964. {
  6965. if (pcount->num.total == 255)
  6966. {
  6967. // chain too long, force a new entry
  6968. pcount = pvalue;
  6969. pvalue = pcount + 1;
  6970. pcount->num.valid++;
  6971. pvalue->value = value[m];
  6972. pvalue++;
  6973. }
  6974. // insert value if they're not equal,
  6975. // or if we're not on a run and the run is less than 3 units
  6976. else if ((value[m] != value[m-1])
  6977. || ((pcount->num.total == pcount->num.valid) && ((m < n - 1) && value[m] != value[m+1])))
  6978. {
  6979. if (pcount->num.total != pcount->num.valid)
  6980. {
  6981. //if (j == 0) printf("%d:%d ", pcount->num.valid, pcount->num.total );
  6982. pcount = pvalue;
  6983. pvalue = pcount + 1;
  6984. }
  6985. pcount->num.valid++;
  6986. pvalue->value = value[m];
  6987. pvalue++;
  6988. }
  6989. pcount->num.total++;
  6990. }
  6991. //if (j == 0) printf("%d:%d\n", pcount->num.valid, pcount->num.total );
  6992. panim->anim[w][j].num[k] = pvalue - data;
  6993. if (panim->anim[w][j].num[k] == 2 && value[0] == 0)
  6994. {
  6995. panim->anim[w][j].num[k] = 0;
  6996. }
  6997. else
  6998. {
  6999. panim->anim[w][j].data[k] = (mstudioanimvalue_t *)calloc( pvalue - data, sizeof( mstudioanimvalue_t ) );
  7000. memmove( panim->anim[w][j].data[k], data, (pvalue - data) * sizeof( mstudioanimvalue_t ) );
  7001. }
  7002. // printf("%d(%d) ", g_source[i]->panim[q]->numanim[j][k], n );
  7003. }
  7004. if (g_bCheckLengths)
  7005. {
  7006. char *tmp[6] = { "X", "Y", "Z", "XR", "YR", "ZR" };
  7007. n = 0;
  7008. float s = 0.0f;
  7009. for (k = 0; k < 6; k++)
  7010. {
  7011. if (panim->anim[w][j].num[k])
  7012. {
  7013. if (n == 0)
  7014. printf("%30s :", g_bonetable[j].name );
  7015. // printf("%2s (%8.3f: %8.3f %8.3f) ", tmp[k], g_bonetable[j].pos[k], checkmin[k], checkmax[k] );
  7016. if (k < 3)
  7017. s = g_bonetable[j].posscale[k];
  7018. else
  7019. s = g_bonetable[j].rotscale[k-3];
  7020. // printf("%2s %8.5f (%d %d) ", tmp[k], checkmax[k] - checkmin[k] );
  7021. printf("%2s %8.5f ", tmp[k], (checkmax[k] - checkmin[k]) * s );
  7022. n = 1;
  7023. }
  7024. }
  7025. if (n)
  7026. printf("\n");
  7027. }
  7028. }
  7029. }
  7030. if (panim->numsections == 1)
  7031. {
  7032. panim->sectionframes = 0;
  7033. }
  7034. }
  7035. }
  7036. //-----------------------------------------------------------------------------
  7037. // Compress a single animation stream
  7038. //-----------------------------------------------------------------------------
  7039. static void CompressSingle( s_animationstream_t *pStream )
  7040. {
  7041. int k, n, m;
  7042. if (pStream->numerror == 0)
  7043. return;
  7044. // printf("%s : ", g_bonetable[j].name );
  7045. for (k = 0; k < 6; k++)
  7046. {
  7047. float minv, maxv, scale;
  7048. RadianEuler ang;
  7049. if (k < 3)
  7050. {
  7051. minv = -128.0;
  7052. maxv = 128.0;
  7053. }
  7054. else
  7055. {
  7056. minv = -M_PI / 8.0;
  7057. maxv = M_PI / 8.0;
  7058. }
  7059. for (n = 0; n < pStream->numerror; n++)
  7060. {
  7061. float v = 0.0f;
  7062. switch(k)
  7063. {
  7064. case 0:
  7065. case 1:
  7066. case 2:
  7067. v = pStream->pError[n].pos[k];
  7068. break;
  7069. case 3:
  7070. case 4:
  7071. case 5:
  7072. QuaternionAngles( pStream->pError[n].q, ang );
  7073. v = ang[k-3];
  7074. while (v >= M_PI)
  7075. v -= M_PI * 2;
  7076. while (v < -M_PI)
  7077. v += M_PI * 2;
  7078. break;
  7079. }
  7080. if (v < minv)
  7081. minv = v;
  7082. if (v > maxv)
  7083. maxv = v;
  7084. }
  7085. // printf("%f %f\n", minv, maxv );
  7086. if (minv < maxv)
  7087. {
  7088. if (-minv> maxv)
  7089. {
  7090. scale = minv / -32768.0;
  7091. }
  7092. else
  7093. {
  7094. scale = maxv / 32767;
  7095. }
  7096. }
  7097. else
  7098. {
  7099. scale = 1.0 / 32.0;
  7100. }
  7101. pStream->scale[k] = scale;
  7102. mstudioanimvalue_t *pcount, *pvalue;
  7103. float v;
  7104. short value[MAXSTUDIOANIMFRAMES];
  7105. mstudioanimvalue_t data[MAXSTUDIOANIMFRAMES];
  7106. // find deltas from default pose
  7107. for (n = 0; n < pStream->numerror; n++)
  7108. {
  7109. switch(k)
  7110. {
  7111. case 0: /* X Position */
  7112. case 1: /* Y Position */
  7113. case 2: /* Z Position */
  7114. value[n] = pStream->pError[n].pos[k] / pStream->scale[k];
  7115. break;
  7116. case 3: /* X Rotation */
  7117. case 4: /* Y Rotation */
  7118. case 5: /* Z Rotation */
  7119. QuaternionAngles( pStream->pError[n].q, ang );
  7120. v = ang[k-3];
  7121. while (v >= M_PI)
  7122. v -= M_PI * 2;
  7123. while (v < -M_PI)
  7124. v += M_PI * 2;
  7125. value[n] = v / pStream->scale[k];
  7126. break;
  7127. }
  7128. }
  7129. // initialize animation RLE block
  7130. pStream->numanim[k] = 0;
  7131. memset( data, 0, sizeof( data ) );
  7132. pcount = data;
  7133. pvalue = pcount + 1;
  7134. pcount->num.valid = 1;
  7135. pcount->num.total = 1;
  7136. pvalue->value = value[0];
  7137. pvalue++;
  7138. // build a RLE of deltas from the default pose
  7139. for (m = 1; m < n; m++)
  7140. {
  7141. if (pcount->num.total == 255)
  7142. {
  7143. // chain too long, force a new entry
  7144. pcount = pvalue;
  7145. pvalue = pcount + 1;
  7146. pcount->num.valid++;
  7147. pvalue->value = value[m];
  7148. pvalue++;
  7149. }
  7150. // insert value if they're not equal,
  7151. // or if we're not on a run and the run is less than 3 units
  7152. else if ((value[m] != value[m-1])
  7153. || ((pcount->num.total == pcount->num.valid) && ((m < n - 1) && value[m] != value[m+1])))
  7154. {
  7155. if (pcount->num.total != pcount->num.valid)
  7156. {
  7157. //if (j == 0) printf("%d:%d ", pcount->num.valid, pcount->num.total );
  7158. pcount = pvalue;
  7159. pvalue = pcount + 1;
  7160. }
  7161. pcount->num.valid++;
  7162. pvalue->value = value[m];
  7163. pvalue++;
  7164. }
  7165. pcount->num.total++;
  7166. }
  7167. //if (j == 0) printf("%d:%d\n", pcount->num.valid, pcount->num.total );
  7168. pStream->numanim[k] = pvalue - data;
  7169. pStream->anim[k] = (mstudioanimvalue_t *)calloc( pvalue - data, sizeof( mstudioanimvalue_t ) );
  7170. memmove( pStream->anim[k], data, (pvalue - data) * sizeof( mstudioanimvalue_t ) );
  7171. // printf("%d (%d) : %d\n", pRule->numanim[k], n, pRule->errorData.numerror );
  7172. }
  7173. }
  7174. //-----------------------------------------------------------------------------
  7175. // Compress all the IK data
  7176. //-----------------------------------------------------------------------------
  7177. static void CompressIKErrors( )
  7178. {
  7179. int i, j;
  7180. // find scales for all bones
  7181. for (i = 0; i < g_numani; i++)
  7182. {
  7183. for (j = 0; j < g_panimation[i]->numikrules; j++)
  7184. {
  7185. s_ikrule_t *pRule = &g_panimation[i]->ikrule[j];
  7186. if (pRule->errorData.numerror == 0)
  7187. continue;
  7188. CompressSingle( &pRule->errorData );
  7189. }
  7190. }
  7191. }
  7192. //-----------------------------------------------------------------------------
  7193. // Compress all the Local Hierarchy data
  7194. //-----------------------------------------------------------------------------
  7195. static void CompressLocalHierarchy( )
  7196. {
  7197. int i, j;
  7198. // find scales for all bones
  7199. for (i = 0; i < g_numani; i++)
  7200. {
  7201. for (j = 0; j < g_panimation[i]->numlocalhierarchy; j++)
  7202. {
  7203. s_localhierarchy_t *pRule = &g_panimation[i]->localhierarchy[j];
  7204. if (pRule->localData.numerror == 0)
  7205. continue;
  7206. CompressSingle( &pRule->localData );
  7207. }
  7208. }
  7209. }
  7210. //-----------------------------------------------------------------------------
  7211. //
  7212. //-----------------------------------------------------------------------------
  7213. struct BonePriority_s
  7214. {
  7215. int m_nGlobalBoneId;
  7216. float m_nGlobalBoneWeight;
  7217. };
  7218. //-----------------------------------------------------------------------------
  7219. // Sort by bone weight
  7220. //-----------------------------------------------------------------------------
  7221. int compareBonePriority( const void *a, const void *b )
  7222. {
  7223. return
  7224. reinterpret_cast< const BonePriority_s * >( a )->m_nGlobalBoneWeight < reinterpret_cast< const BonePriority_s * >( b )->m_nGlobalBoneWeight ? -1 :
  7225. reinterpret_cast< const BonePriority_s * >( a )->m_nGlobalBoneWeight > reinterpret_cast< const BonePriority_s * >( b )->m_nGlobalBoneWeight ? 1 : 0;
  7226. };
  7227. //-----------------------------------------------------------------------------
  7228. // Dump A $definebone line, ensuring any parents are already dumped
  7229. //-----------------------------------------------------------------------------
  7230. void DumpDefineBone( int nBoneId, bool *pBoneDumpedList )
  7231. {
  7232. Assert( nBoneId < g_numbones );
  7233. if ( pBoneDumpedList[ nBoneId ] )
  7234. return;
  7235. const s_bonetable_t &bone = g_bonetable[ nBoneId ];
  7236. // Ensure the parent bone is dumped before the child
  7237. if ( bone.parent >= 0 )
  7238. {
  7239. DumpDefineBone( bone.parent, pBoneDumpedList );
  7240. }
  7241. printf( "$definebone " );
  7242. printf( "\"%s\" ", bone.name );
  7243. if ( bone.parent != -1 )
  7244. {
  7245. printf( "\"%s\" ", g_bonetable[ bone.parent ].name );
  7246. }
  7247. else
  7248. {
  7249. printf( "\"\" " );
  7250. }
  7251. Vector pos;
  7252. QAngle angles;
  7253. pos = bone.pos;
  7254. angles.Init( RAD2DEG( bone.rot.y ), RAD2DEG( bone.rot.z ), RAD2DEG( bone.rot.x ) );
  7255. printf( "%f %f %f %f %f %f", pos.x, pos.y, pos.z, angles.x, angles.y, angles.z );
  7256. MatrixAngles( bone.srcRealign, angles, pos );
  7257. printf( " %f %f %f %f %f %f", pos.x, pos.y, pos.z, angles.x, angles.y, angles.z );
  7258. printf( "\n" );
  7259. pBoneDumpedList[ nBoneId ] = true;
  7260. }
  7261. //-----------------------------------------------------------------------------
  7262. // Dump a $definebones .qci file with the bones in an optimal order
  7263. // i.e. Bones that are removed or replaced in LODs are later in the list
  7264. // bones that are used all of the time are at the top of the list
  7265. //-----------------------------------------------------------------------------
  7266. void DumpDefineBones()
  7267. {
  7268. BonePriority_s *pBonePriorityList = reinterpret_cast< BonePriority_s * >( stackalloc( g_numbones * sizeof( BonePriority_s ) ) );
  7269. for ( int i = 0; i < g_numbones; ++i )
  7270. {
  7271. BonePriority_s &bonePriority = pBonePriorityList[ i ];
  7272. bonePriority.m_nGlobalBoneId = i;
  7273. bonePriority.m_nGlobalBoneWeight = 0.0f;
  7274. }
  7275. for ( int i = 0; i < g_ScriptLODs.Count(); ++i )
  7276. {
  7277. const LodScriptData_t &scriptLOD = g_ScriptLODs[ i ];
  7278. for ( int j = 0; j < scriptLOD.boneReplacements.Count(); ++j )
  7279. {
  7280. // Ignore Shadow LOD
  7281. if ( scriptLOD.switchValue <= 0.0f )
  7282. continue;
  7283. const int nBoneId = findGlobalBone( scriptLOD.boneReplacements[ j ].GetSrcName() );
  7284. if ( nBoneId < 0 )
  7285. {
  7286. Warning( "Can't Find BoneReplacement Bone %s\n", scriptLOD.boneReplacements[ j ].GetSrcName() );
  7287. continue;
  7288. }
  7289. pBonePriorityList[ nBoneId ].m_nGlobalBoneWeight += scriptLOD.switchValue;
  7290. }
  7291. }
  7292. // bones used by hitboxes and attachments should always go first since they're used by the server
  7293. for ( int i = 0; i < g_numbones; ++i )
  7294. {
  7295. if ( g_bonetable[i].flags & (BONE_USED_BY_HITBOX | BONE_USED_BY_ATTACHMENT | BONE_USED_BY_BONE_MERGE ))
  7296. {
  7297. pBonePriorityList[ i ].m_nGlobalBoneWeight = -1.0f;
  7298. }
  7299. }
  7300. qsort( pBonePriorityList, g_numbones, sizeof( BonePriority_s ), compareBonePriority );
  7301. bool *pBoneDumpedList = reinterpret_cast< bool * >( stackalloc( g_numbones * sizeof( bool ) ) );
  7302. memset( pBoneDumpedList, 0, g_numbones * sizeof( bool ) );
  7303. for (int i = 0; i < g_numbones; i++)
  7304. {
  7305. const BonePriority_s &bonePriority = pBonePriorityList[ i ];
  7306. const int nBoneId = bonePriority.m_nGlobalBoneId;
  7307. if (g_bonetable[ nBoneId ].flags & BONE_ALWAYS_PROCEDURAL)
  7308. {
  7309. pBoneDumpedList[ nBoneId ] = true;
  7310. continue;
  7311. }
  7312. DumpDefineBone( nBoneId, pBoneDumpedList );
  7313. }
  7314. }
  7315. void ReLinkAttachments()
  7316. {
  7317. int i;
  7318. int j;
  7319. int k;
  7320. // relink per-model attachments, eyeballs
  7321. for (i = 0; i < g_nummodelsbeforeLOD; i++)
  7322. {
  7323. s_source_t *psource = g_model[i]->source;
  7324. for (j = 0; j < g_model[i]->numattachments; j++)
  7325. {
  7326. k = findGlobalBone( g_model[i]->attachment[j].bonename );
  7327. if (k == -1)
  7328. {
  7329. MdlError("unknown model attachment link '%s'\n", g_model[i]->attachment[j].bonename );
  7330. }
  7331. g_model[i]->attachment[j].bone = j;
  7332. }
  7333. for (j = 0; j < g_model[i]->numeyeballs; j++)
  7334. {
  7335. g_model[i]->eyeball[j].bone = psource->boneLocalToGlobal[g_model[i]->eyeball[j].bone];
  7336. }
  7337. }
  7338. }
  7339. void CheckEyeballSetup()
  7340. {
  7341. for (int i = 0; i < g_nummodelsbeforeLOD; i++)
  7342. {
  7343. for (int j = 0; j < g_model[i]->numeyeballs; j++)
  7344. {
  7345. s_eyeball_t *peyeball = &g_model[i]->eyeball[j];
  7346. if (peyeball->upperlidflexdesc == -1)
  7347. {
  7348. // MdlWarning( "eyeball %s missing upperlid data\n", peyeball->name );
  7349. int dummy = Add_Flexdesc( "dummy_eyelid" );
  7350. peyeball->upperlidflexdesc = dummy;
  7351. peyeball->upperflexdesc[0] = dummy;
  7352. peyeball->uppertarget[0] = -1;
  7353. peyeball->upperflexdesc[1] = dummy;
  7354. peyeball->uppertarget[1] = 0;
  7355. peyeball->upperflexdesc[2] = dummy;
  7356. peyeball->uppertarget[2] = 1;
  7357. }
  7358. if (peyeball->lowerlidflexdesc == -1)
  7359. {
  7360. // MdlWarning( "eyeball %s missing lower data\n", peyeball->name );
  7361. int dummy = Add_Flexdesc( "dummy_eyelid" );
  7362. peyeball->lowerlidflexdesc = dummy;
  7363. peyeball->lowerflexdesc[0] = dummy;
  7364. peyeball->lowertarget[0] = -1;
  7365. peyeball->lowerflexdesc[1] = dummy;
  7366. peyeball->lowertarget[1] = 0;
  7367. peyeball->lowerflexdesc[2] = dummy;
  7368. peyeball->lowertarget[2] = 1;
  7369. }
  7370. }
  7371. }
  7372. }
  7373. void SetupHitBoxes()
  7374. {
  7375. int i;
  7376. int j;
  7377. int k;
  7378. int n;
  7379. // set hitgroups
  7380. for (k = 0; k < g_numbones; k++)
  7381. {
  7382. g_bonetable[k].group = -9999;
  7383. }
  7384. for (j = 0; j < g_numhitgroups; j++)
  7385. {
  7386. k = findGlobalBone( g_hitgroup[j].name );
  7387. if (k != -1)
  7388. {
  7389. g_bonetable[k].group = g_hitgroup[j].group;
  7390. }
  7391. else
  7392. {
  7393. MdlError( "cannot find bone %s for hitgroup %d\n", g_hitgroup[j].name, g_hitgroup[j].group );
  7394. }
  7395. }
  7396. for (k = 0; k < g_numbones; k++)
  7397. {
  7398. if (g_bonetable[k].group == -9999)
  7399. {
  7400. if (g_bonetable[k].parent != -1)
  7401. g_bonetable[k].group = g_bonetable[g_bonetable[k].parent].group;
  7402. else
  7403. g_bonetable[k].group = 0;
  7404. }
  7405. }
  7406. if ( g_hitboxsets.Count() == 0 )
  7407. {
  7408. int index = g_hitboxsets.AddToTail();
  7409. s_hitboxset *set = &g_hitboxsets[ index ];
  7410. memset( set, 0, sizeof( *set) );
  7411. strcpy( set->hitboxsetname, "default" );
  7412. gflags |= STUDIOHDR_FLAGS_AUTOGENERATED_HITBOX;
  7413. // find intersection box volume for each bone
  7414. for (k = 0; k < g_numbones; k++)
  7415. {
  7416. for (j = 0; j < 3; j++)
  7417. {
  7418. if (g_bUseBoneInBBox)
  7419. {
  7420. g_bonetable[k].bmin[j] = 0.0;
  7421. g_bonetable[k].bmax[j] = 0.0;
  7422. }
  7423. else
  7424. {
  7425. g_bonetable[k].bmin[j] = 9999.0;
  7426. g_bonetable[k].bmax[j] = -9999.0;
  7427. }
  7428. }
  7429. }
  7430. // try all the connect vertices
  7431. for (i = 0; i < g_nummodelsbeforeLOD; i++)
  7432. {
  7433. s_loddata_t *pLodData = g_model[i]->m_pLodData;
  7434. if ( !pLodData )
  7435. continue;
  7436. Vector p;
  7437. for (j = 0; j < pLodData->numvertices; j++)
  7438. {
  7439. for (n = 0; n < pLodData->vertex[j].boneweight.numbones; n++)
  7440. {
  7441. k = pLodData->vertex[j].boneweight.bone[n];
  7442. VectorITransform( pLodData->vertex[j].position, g_bonetable[k].boneToPose, p );
  7443. if (p[0] < g_bonetable[k].bmin[0]) g_bonetable[k].bmin[0] = p[0];
  7444. if (p[1] < g_bonetable[k].bmin[1]) g_bonetable[k].bmin[1] = p[1];
  7445. if (p[2] < g_bonetable[k].bmin[2]) g_bonetable[k].bmin[2] = p[2];
  7446. if (p[0] > g_bonetable[k].bmax[0]) g_bonetable[k].bmax[0] = p[0];
  7447. if (p[1] > g_bonetable[k].bmax[1]) g_bonetable[k].bmax[1] = p[1];
  7448. if (p[2] > g_bonetable[k].bmax[2]) g_bonetable[k].bmax[2] = p[2];
  7449. }
  7450. }
  7451. }
  7452. // add in all your children as well
  7453. for (k = 0; k < g_numbones; k++)
  7454. {
  7455. if ((j = g_bonetable[k].parent) != -1)
  7456. {
  7457. if (g_bonetable[k].pos[0] < g_bonetable[j].bmin[0]) g_bonetable[j].bmin[0] = g_bonetable[k].pos[0];
  7458. if (g_bonetable[k].pos[1] < g_bonetable[j].bmin[1]) g_bonetable[j].bmin[1] = g_bonetable[k].pos[1];
  7459. if (g_bonetable[k].pos[2] < g_bonetable[j].bmin[2]) g_bonetable[j].bmin[2] = g_bonetable[k].pos[2];
  7460. if (g_bonetable[k].pos[0] > g_bonetable[j].bmax[0]) g_bonetable[j].bmax[0] = g_bonetable[k].pos[0];
  7461. if (g_bonetable[k].pos[1] > g_bonetable[j].bmax[1]) g_bonetable[j].bmax[1] = g_bonetable[k].pos[1];
  7462. if (g_bonetable[k].pos[2] > g_bonetable[j].bmax[2]) g_bonetable[j].bmax[2] = g_bonetable[k].pos[2];
  7463. }
  7464. }
  7465. for (k = 0; k < g_numbones; k++)
  7466. {
  7467. if (g_bonetable[k].bmin[0] < g_bonetable[k].bmax[0] - 1
  7468. && g_bonetable[k].bmin[1] < g_bonetable[k].bmax[1] - 1
  7469. && g_bonetable[k].bmin[2] < g_bonetable[k].bmax[2] - 1)
  7470. {
  7471. set->hitbox[set->numhitboxes].bone = k;
  7472. set->hitbox[set->numhitboxes].group = g_bonetable[k].group;
  7473. VectorCopy( g_bonetable[k].bmin, set->hitbox[set->numhitboxes].bmin );
  7474. VectorCopy( g_bonetable[k].bmax, set->hitbox[set->numhitboxes].bmax );
  7475. if (dump_hboxes)
  7476. {
  7477. printf("$hbox %d \"%s\" %.2f %.2f %.2f %.2f %.2f %.2f\n",
  7478. set->hitbox[set->numhitboxes].group,
  7479. g_bonetable[set->hitbox[set->numhitboxes].bone].name,
  7480. set->hitbox[set->numhitboxes].bmin[0], set->hitbox[set->numhitboxes].bmin[1], set->hitbox[set->numhitboxes].bmin[2],
  7481. set->hitbox[set->numhitboxes].bmax[0], set->hitbox[set->numhitboxes].bmax[1], set->hitbox[set->numhitboxes].bmax[2] );
  7482. }
  7483. set->numhitboxes++;
  7484. }
  7485. else
  7486. {
  7487. // don't leave the invalid bounds in the table - future code will use it to compute sequence bounds for attachment points
  7488. g_bonetable[k].bmin = vec3_origin;
  7489. g_bonetable[k].bmax = vec3_origin;
  7490. }
  7491. }
  7492. }
  7493. else
  7494. {
  7495. gflags &= ~STUDIOHDR_FLAGS_AUTOGENERATED_HITBOX;
  7496. for (int s = 0; s < g_hitboxsets.Count(); s++ )
  7497. {
  7498. s_hitboxset *set = &g_hitboxsets[ s ];
  7499. for (j = 0; j < set->numhitboxes; j++)
  7500. {
  7501. k = findGlobalBone( set->hitbox[j].name );
  7502. if (k != -1)
  7503. {
  7504. set->hitbox[j].bone = k;
  7505. #ifdef MDLCOMPILE
  7506. // This is temporary
  7507. // In mdlcompile, hitboxes come in defined in the space of the bone before remapping
  7508. // i.e. In the space the bone was built by the user
  7509. // In the near future, the hitboxes will be remapped before coming into studiomdl
  7510. if ( g_bonetable[ k ].bPreAligned )
  7511. {
  7512. const matrix3x4_t &mSrcRealign = g_bonetable[ k ].srcRealign;
  7513. Vector v = set->hitbox[j].bmin;
  7514. VectorIRotate( v, mSrcRealign, set->hitbox[ j ].bmin );
  7515. v = set->hitbox[j].bmax;
  7516. VectorIRotate( v, mSrcRealign, set->hitbox[ j ].bmax );
  7517. }
  7518. #endif // #ifdef MDLCOMPILE
  7519. }
  7520. else
  7521. {
  7522. MdlError( "cannot find bone %s for bbox\n", set->hitbox[j].name );
  7523. }
  7524. }
  7525. }
  7526. }
  7527. for (int s = 0; s < g_hitboxsets.Count(); s++ )
  7528. {
  7529. s_hitboxset *set = &g_hitboxsets[ s ];
  7530. // flag all bones used by hitboxes
  7531. for (j = 0; j < set->numhitboxes; j++)
  7532. {
  7533. k = set->hitbox[j].bone;
  7534. while (k != -1)
  7535. {
  7536. g_bonetable[k].flags |= BONE_USED_BY_HITBOX;
  7537. k = g_bonetable[k].parent;
  7538. }
  7539. }
  7540. }
  7541. }
  7542. void SetupFullBoneRenderBounds( CUtlVector<CBoneRenderBounds> &boneRenderBounds )
  7543. {
  7544. boneRenderBounds.SetSize( g_numbones );
  7545. // First, add the ones already calculated from vertices.
  7546. for ( int i=0; i < g_numbones; i++ )
  7547. {
  7548. CBoneRenderBounds *pOut = &boneRenderBounds[i];
  7549. pOut->m_Mins = g_bonetable[i].bmin;
  7550. pOut->m_Maxs = g_bonetable[i].bmax;
  7551. }
  7552. // Note: shared animation files will need to include the hitboxes or else their sequence
  7553. // boxes won't use this stuff.
  7554. // Now add hitboxes.
  7555. for ( int i=0; i < g_hitboxsets.Count(); i++ )
  7556. {
  7557. const s_hitboxset *pSet = &g_hitboxsets[i];
  7558. for ( int k=0; k < pSet->numhitboxes; k++ )
  7559. {
  7560. const s_bbox_t *pIn = &pSet->hitbox[k];
  7561. if ( pIn->bone >= 0 )
  7562. {
  7563. CBoneRenderBounds *pOut = &boneRenderBounds[pIn->bone];
  7564. VectorMin( pIn->bmin, pOut->m_Mins, pOut->m_Mins );
  7565. VectorMax( pIn->bmax, pOut->m_Maxs, pOut->m_Maxs );
  7566. }
  7567. }
  7568. }
  7569. }
  7570. void CalcSequenceBoundingBoxes()
  7571. {
  7572. int i;
  7573. int j;
  7574. int k;
  7575. int n;
  7576. int m;
  7577. CUtlVector<CBoneRenderBounds> boneRenderBounds;
  7578. SetupFullBoneRenderBounds( boneRenderBounds );
  7579. // find bounding box for each g_sequence
  7580. for (i = 0; i < g_numani; i++)
  7581. {
  7582. Vector bmin, bmax;
  7583. // find intersection box volume for each bone
  7584. for (j = 0; j < 3; j++)
  7585. {
  7586. bmin[j] = 9999.0;
  7587. bmax[j] = -9999.0;
  7588. }
  7589. for (j = 0; j < g_panimation[i]->numframes; j++)
  7590. {
  7591. matrix3x4_t bonetransform[MAXSTUDIOBONES]; // bone transformation matrix
  7592. matrix3x4_t posetransform[MAXSTUDIOBONES]; // bone transformation matrix
  7593. matrix3x4_t bonematrix; // local transformation matrix
  7594. Vector pos;
  7595. CalcBoneTransforms( g_panimation[i], j, bonetransform );
  7596. for (k = 0; k < g_numbones; k++)
  7597. {
  7598. MatrixInvert( g_bonetable[k].boneToPose, bonematrix );
  7599. ConcatTransforms (bonetransform[k], bonematrix, posetransform[k]);
  7600. }
  7601. // include hitboxes as well.
  7602. if ( !g_bboxonlyverts )
  7603. {
  7604. for (k = 0; k < g_numbones; k++)
  7605. {
  7606. Vector tmpMin, tmpMax;
  7607. TransformAABB( bonetransform[k], boneRenderBounds[k].m_Mins, boneRenderBounds[k].m_Maxs, tmpMin, tmpMax );
  7608. VectorMin( tmpMin, bmin, bmin );
  7609. VectorMax( tmpMax, bmax, bmax );
  7610. if ( g_verbose &&
  7611. (tmpMin.x < g_vecMinWorldspace.x ||
  7612. tmpMin.y < g_vecMinWorldspace.y ||
  7613. tmpMin.z < g_vecMinWorldspace.z ||
  7614. tmpMax.x > g_vecMaxWorldspace.x ||
  7615. tmpMax.y > g_vecMaxWorldspace.y ||
  7616. tmpMax.z > g_vecMaxWorldspace.z ) )
  7617. {
  7618. MdlWarning("%s : bone \"%s\" has bounding box out of range : %.0f %.0f %.0f : %.0f %.0f %.0f\n",
  7619. g_panimation[i]->name, g_bonetable[k].name,
  7620. tmpMin.x, tmpMin.y, tmpMin.z, tmpMax.z, tmpMax.y, tmpMax.z );
  7621. }
  7622. }
  7623. }
  7624. // include vertices
  7625. for (k = 0; k < g_nummodelsbeforeLOD; k++)
  7626. {
  7627. s_loddata_t *pLodData = g_model[k]->m_pLodData;
  7628. // skip blank empty model
  7629. if ( !pLodData )
  7630. continue;
  7631. for (n = 0; n < pLodData->numvertices; n++)
  7632. {
  7633. Vector tmp;
  7634. pos = Vector( 0, 0, 0 );
  7635. for (m = 0; m < pLodData->vertex[n].boneweight.numbones; m++)
  7636. {
  7637. VectorTransform( pLodData->vertex[n].position, posetransform[pLodData->vertex[n].boneweight.bone[m]], tmp ); // bug: should use all bones!
  7638. VectorMA( pos, pLodData->vertex[n].boneweight.weight[m], tmp, pos );
  7639. }
  7640. VectorMin( pos, bmin, bmin );
  7641. VectorMax( pos, bmax, bmax );
  7642. }
  7643. }
  7644. }
  7645. if (bmin.x < g_vecMinWorldspace.x || bmin.y < g_vecMinWorldspace.y || bmin.z < g_vecMinWorldspace.z || bmax.x > g_vecMaxWorldspace.x || bmax.y > g_vecMaxWorldspace.y || bmax.z > g_vecMaxWorldspace.z)
  7646. {
  7647. MdlWarning("%s : bounding box out of range : %.0f %.0f %.0f : %.0f %.0f %.0f\n",
  7648. g_panimation[i]->name,
  7649. bmin.x, bmin.y, bmin.z, bmax.z, bmax.y, bmax.z );
  7650. VectorMax( bmin, g_vecMinWorldspace, bmin );
  7651. VectorMin( bmax, g_vecMaxWorldspace, bmax );
  7652. }
  7653. VectorCopy( bmin, g_panimation[i]->bmin );
  7654. VectorCopy( bmax, g_panimation[i]->bmax );
  7655. /*
  7656. printf("%s : %.0f %.0f %.0f %.0f %.0f %.0f\n",
  7657. g_panimation[i]->name, bmin[0], bmax[0], bmin[1], bmax[1], bmin[2], bmax[2] );
  7658. */
  7659. // printf("%s %.2f\n", g_sequence[i].name, g_sequence[i].panim[0]->pos[9][0][0] / g_bonetable[9].pos[0] );
  7660. }
  7661. for (i = 0; i < g_sequence.Count(); i++)
  7662. {
  7663. Vector bmin, bmax;
  7664. // find intersection box volume for each bone
  7665. for (j = 0; j < 3; j++)
  7666. {
  7667. bmin[j] = 9999.0;
  7668. bmax[j] = -9999.0;
  7669. }
  7670. for (j = 0; j < g_sequence[i].groupsize[0]; j++)
  7671. {
  7672. for (k = 0; k < g_sequence[i].groupsize[1]; k++)
  7673. {
  7674. s_animation_t *panim = g_sequence[i].panim[j][k];
  7675. if (panim->bmin[0] < bmin[0]) bmin[0] = panim->bmin[0];
  7676. if (panim->bmin[1] < bmin[1]) bmin[1] = panim->bmin[1];
  7677. if (panim->bmin[2] < bmin[2]) bmin[2] = panim->bmin[2];
  7678. if (panim->bmax[0] > bmax[0]) bmax[0] = panim->bmax[0];
  7679. if (panim->bmax[1] > bmax[1]) bmax[1] = panim->bmax[1];
  7680. if (panim->bmax[2] > bmax[2]) bmax[2] = panim->bmax[2];
  7681. }
  7682. }
  7683. VectorCopy( bmin, g_sequence[i].bmin );
  7684. VectorCopy( bmax, g_sequence[i].bmax );
  7685. }
  7686. }
  7687. void SetIlluminationPosition()
  7688. {
  7689. // find center of domain
  7690. if (!illumpositionset)
  7691. {
  7692. // Only use the 0th sequence; that should be the idle sequence
  7693. VectorFill( illumposition, 0 );
  7694. if (g_sequence.Count() != 0)
  7695. {
  7696. VectorAdd( g_sequence[0].bmin, g_sequence[0].bmax, illumposition );
  7697. illumposition *= 0.5f;
  7698. }
  7699. illumpositionset = true;
  7700. }
  7701. }
  7702. void SimplifyModel()
  7703. {
  7704. if (g_sequence.Count() == 0 && g_numincludemodels == 0)
  7705. {
  7706. MdlError( "model has no sequences\n");
  7707. }
  7708. // have to load the lod sources before remapping bones so that the remap
  7709. // happens for all LODs.
  7710. LoadLODSources();
  7711. RemapBones();
  7712. LinkIKChains();
  7713. LinkIKLocks();
  7714. RealignBones();
  7715. ConvertBoneTreeCollapsesToReplaceBones();
  7716. // export bones
  7717. if (g_definebones)
  7718. {
  7719. DumpDefineBones();
  7720. exit( 0 );
  7721. }
  7722. // translate:
  7723. // replacebone "bone0" "bone1"
  7724. // replacebone "bone1" "bone2"
  7725. // replacebone "bone2" "bone3"
  7726. // to:
  7727. // replacebone "bone0" "bone3"
  7728. // replacebone "bone1" "bone3"
  7729. // replacebone "bone2" "bone3"
  7730. FixupReplacedBones();
  7731. RemapVerticesToGlobalBones();
  7732. if (g_bCenterBonesOnVerts)
  7733. {
  7734. CenterBonesOnVerts();
  7735. }
  7736. // remap lods to root, building aggregate final pools
  7737. // mark bones used by an lod
  7738. UnifyLODs();
  7739. if ( g_bPrintBones )
  7740. {
  7741. printf( "Hardware bone usage:\n" );
  7742. }
  7743. SpewBoneUsageStats();
  7744. MarkParentBoneLODs();
  7745. if ( g_bPrintBones )
  7746. {
  7747. printf( "CPU bone usage:\n" );
  7748. }
  7749. SpewBoneUsageStats();
  7750. RemapAnimations();
  7751. processAnimations();
  7752. limitBoneRotations();
  7753. limitIKChainLength();
  7754. RemapProceduralBones();
  7755. MakeTransitions();
  7756. RemapVertexAnimations();
  7757. RemapVertexAnimationsNewVersion();
  7758. FindAutolayers();
  7759. // link bonecontrollers
  7760. LinkBoneControllers();
  7761. // link screen aligned bones
  7762. TagScreenAlignedBones();
  7763. TagWorldAlignedBones();
  7764. // link attachments
  7765. LinkAttachments();
  7766. // link mouths
  7767. LinkMouths();
  7768. // procedural bone needs to propogate its bone usage up its chain
  7769. // ensures runtime sets up dependent bone hierarchy
  7770. MarkProceduralBoneChain();
  7771. LockBoneLengths();
  7772. ProcessIKRules();
  7773. CompressIKErrors( );
  7774. CompressLocalHierarchy( );
  7775. CalcPoseParameters();
  7776. ReLinkAttachments();
  7777. CheckEyeballSetup();
  7778. SetupHitBoxes();
  7779. CompressAnimations( );
  7780. CalcSequenceBoundingBoxes();
  7781. SetIlluminationPosition();
  7782. if ( g_bBuildPreview )
  7783. {
  7784. gflags |= STUDIOHDR_FLAGS_BUILT_IN_PREVIEW_MODE;
  7785. }
  7786. }