PageRenderTime 134ms CodeModel.GetById 15ms app.highlight 107ms RepoModel.GetById 1ms app.codeStats 1ms

/indra/llcharacter/llkeyframemotion.cpp

https://bitbucket.org/lindenlab/viewer-beta/
C++ | 2046 lines | 1475 code | 274 blank | 297 comment | 258 complexity | bcac424223eba63d80fae115706dd945 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1/** 
   2 * @file llkeyframemotion.cpp
   3 * @brief Implementation of LLKeyframeMotion class.
   4 *
   5 * $LicenseInfo:firstyear=2001&license=viewerlgpl$
   6 * Second Life Viewer Source Code
   7 * Copyright (C) 2010, Linden Research, Inc.
   8 * 
   9 * This library is free software; you can redistribute it and/or
  10 * modify it under the terms of the GNU Lesser General Public
  11 * License as published by the Free Software Foundation;
  12 * version 2.1 of the License only.
  13 * 
  14 * This library is distributed in the hope that it will be useful,
  15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  17 * Lesser General Public License for more details.
  18 * 
  19 * You should have received a copy of the GNU Lesser General Public
  20 * License along with this library; if not, write to the Free Software
  21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
  22 * 
  23 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
  24 * $/LicenseInfo$
  25 */
  26
  27//-----------------------------------------------------------------------------
  28// Header Files
  29//-----------------------------------------------------------------------------
  30#include "linden_common.h"
  31
  32#include "llmath.h"
  33#include "llanimationstates.h"
  34#include "llassetstorage.h"
  35#include "lldatapacker.h"
  36#include "llcharacter.h"
  37#include "llcriticaldamp.h"
  38#include "lldir.h"
  39#include "llendianswizzle.h"
  40#include "llkeyframemotion.h"
  41#include "llquantize.h"
  42#include "llvfile.h"
  43#include "m3math.h"
  44#include "message.h"
  45
  46//-----------------------------------------------------------------------------
  47// Static Definitions
  48//-----------------------------------------------------------------------------
  49LLVFS*				LLKeyframeMotion::sVFS = NULL;
  50LLKeyframeDataCache::keyframe_data_map_t	LLKeyframeDataCache::sKeyframeDataMap;
  51
  52//-----------------------------------------------------------------------------
  53// Globals
  54//-----------------------------------------------------------------------------
  55static F32 JOINT_LENGTH_K = 0.7f;
  56static S32 MAX_ITERATIONS = 20;
  57static S32 MIN_ITERATIONS = 1;
  58static S32 MIN_ITERATION_COUNT = 2;
  59static F32 MAX_PIXEL_AREA_CONSTRAINTS = 80000.f;
  60static F32 MIN_PIXEL_AREA_CONSTRAINTS = 1000.f;
  61static F32 MIN_ACCELERATION_SQUARED = 0.0005f * 0.0005f;
  62
  63static F32 MAX_CONSTRAINTS = 10;
  64
  65//-----------------------------------------------------------------------------
  66// JointMotionList
  67//-----------------------------------------------------------------------------
  68LLKeyframeMotion::JointMotionList::JointMotionList()
  69	: mDuration(0.f),
  70	  mLoop(FALSE),
  71	  mLoopInPoint(0.f),
  72	  mLoopOutPoint(0.f),
  73	  mEaseInDuration(0.f),
  74	  mEaseOutDuration(0.f),
  75	  mBasePriority(LLJoint::LOW_PRIORITY),
  76	  mHandPose(LLHandMotion::HAND_POSE_SPREAD),
  77	  mMaxPriority(LLJoint::LOW_PRIORITY)
  78{
  79}
  80
  81LLKeyframeMotion::JointMotionList::~JointMotionList()
  82{
  83	for_each(mConstraints.begin(), mConstraints.end(), DeletePointer());
  84	for_each(mJointMotionArray.begin(), mJointMotionArray.end(), DeletePointer());
  85}
  86
  87U32 LLKeyframeMotion::JointMotionList::dumpDiagInfo()
  88{
  89	S32	total_size = sizeof(JointMotionList);
  90
  91	for (U32 i = 0; i < getNumJointMotions(); i++)
  92	{
  93		LLKeyframeMotion::JointMotion* joint_motion_p = mJointMotionArray[i];
  94
  95		llinfos << "\tJoint " << joint_motion_p->mJointName << llendl;
  96		if (joint_motion_p->mUsage & LLJointState::SCALE)
  97		{
  98			llinfos << "\t" << joint_motion_p->mScaleCurve.mNumKeys << " scale keys at " 
  99			<< joint_motion_p->mScaleCurve.mNumKeys * sizeof(ScaleKey) << " bytes" << llendl;
 100
 101			total_size += joint_motion_p->mScaleCurve.mNumKeys * sizeof(ScaleKey);
 102		}
 103		if (joint_motion_p->mUsage & LLJointState::ROT)
 104		{
 105			llinfos << "\t" << joint_motion_p->mRotationCurve.mNumKeys << " rotation keys at " 
 106			<< joint_motion_p->mRotationCurve.mNumKeys * sizeof(RotationKey) << " bytes" << llendl;
 107
 108			total_size += joint_motion_p->mRotationCurve.mNumKeys * sizeof(RotationKey);
 109		}
 110		if (joint_motion_p->mUsage & LLJointState::POS)
 111		{
 112			llinfos << "\t" << joint_motion_p->mPositionCurve.mNumKeys << " position keys at " 
 113			<< joint_motion_p->mPositionCurve.mNumKeys * sizeof(PositionKey) << " bytes" << llendl;
 114
 115			total_size += joint_motion_p->mPositionCurve.mNumKeys * sizeof(PositionKey);
 116		}
 117	}
 118	llinfos << "Size: " << total_size << " bytes" << llendl;
 119
 120	return total_size;
 121}
 122
 123//-----------------------------------------------------------------------------
 124//-----------------------------------------------------------------------------
 125// ****Curve classes
 126//-----------------------------------------------------------------------------
 127//-----------------------------------------------------------------------------
 128
 129
 130//-----------------------------------------------------------------------------
 131// ScaleCurve::ScaleCurve()
 132//-----------------------------------------------------------------------------
 133LLKeyframeMotion::ScaleCurve::ScaleCurve()
 134{
 135	mInterpolationType = LLKeyframeMotion::IT_LINEAR;
 136	mNumKeys = 0;
 137}
 138
 139//-----------------------------------------------------------------------------
 140// ScaleCurve::~ScaleCurve()
 141//-----------------------------------------------------------------------------
 142LLKeyframeMotion::ScaleCurve::~ScaleCurve() 
 143{
 144	mKeys.clear();
 145	mNumKeys = 0;
 146}
 147
 148//-----------------------------------------------------------------------------
 149// getValue()
 150//-----------------------------------------------------------------------------
 151LLVector3 LLKeyframeMotion::ScaleCurve::getValue(F32 time, F32 duration)
 152{
 153	LLVector3 value;
 154
 155	if (mKeys.empty())
 156	{
 157		value.clearVec();
 158		return value;
 159	}
 160	
 161	key_map_t::iterator right = mKeys.lower_bound(time);
 162	if (right == mKeys.end())
 163	{
 164		// Past last key
 165		--right;
 166		value = right->second.mScale;
 167	}
 168	else if (right == mKeys.begin() || right->first == time)
 169	{
 170		// Before first key or exactly on a key
 171		value = right->second.mScale;
 172	}
 173	else
 174	{
 175		// Between two keys
 176		key_map_t::iterator left = right; --left;
 177		F32 index_before = left->first;
 178		F32 index_after = right->first;
 179		ScaleKey& scale_before = left->second;
 180		ScaleKey& scale_after = right->second;
 181		if (right == mKeys.end())
 182		{
 183			scale_after = mLoopInKey;
 184			index_after = duration;
 185		}
 186
 187		F32 u = (time - index_before) / (index_after - index_before);
 188		value = interp(u, scale_before, scale_after);
 189	}
 190	return value;
 191}
 192
 193//-----------------------------------------------------------------------------
 194// interp()
 195//-----------------------------------------------------------------------------
 196LLVector3 LLKeyframeMotion::ScaleCurve::interp(F32 u, ScaleKey& before, ScaleKey& after)
 197{
 198	switch (mInterpolationType)
 199	{
 200	case IT_STEP:
 201		return before.mScale;
 202
 203	default:
 204	case IT_LINEAR:
 205	case IT_SPLINE:
 206		return lerp(before.mScale, after.mScale, u);
 207	}
 208}
 209
 210//-----------------------------------------------------------------------------
 211// RotationCurve::RotationCurve()
 212//-----------------------------------------------------------------------------
 213LLKeyframeMotion::RotationCurve::RotationCurve()
 214{
 215	mInterpolationType = LLKeyframeMotion::IT_LINEAR;
 216	mNumKeys = 0;
 217}
 218
 219//-----------------------------------------------------------------------------
 220// RotationCurve::~RotationCurve()
 221//-----------------------------------------------------------------------------
 222LLKeyframeMotion::RotationCurve::~RotationCurve()
 223{
 224	mKeys.clear();
 225	mNumKeys = 0;
 226}
 227
 228//-----------------------------------------------------------------------------
 229// RotationCurve::getValue()
 230//-----------------------------------------------------------------------------
 231LLQuaternion LLKeyframeMotion::RotationCurve::getValue(F32 time, F32 duration)
 232{
 233	LLQuaternion value;
 234
 235	if (mKeys.empty())
 236	{
 237		value = LLQuaternion::DEFAULT;
 238		return value;
 239	}
 240	
 241	key_map_t::iterator right = mKeys.lower_bound(time);
 242	if (right == mKeys.end())
 243	{
 244		// Past last key
 245		--right;
 246		value = right->second.mRotation;
 247	}
 248	else if (right == mKeys.begin() || right->first == time)
 249	{
 250		// Before first key or exactly on a key
 251		value = right->second.mRotation;
 252	}
 253	else
 254	{
 255		// Between two keys
 256		key_map_t::iterator left = right; --left;
 257		F32 index_before = left->first;
 258		F32 index_after = right->first;
 259		RotationKey& rot_before = left->second;
 260		RotationKey& rot_after = right->second;
 261		if (right == mKeys.end())
 262		{
 263			rot_after = mLoopInKey;
 264			index_after = duration;
 265		}
 266
 267		F32 u = (time - index_before) / (index_after - index_before);
 268		value = interp(u, rot_before, rot_after);
 269	}
 270	return value;
 271}
 272
 273//-----------------------------------------------------------------------------
 274// interp()
 275//-----------------------------------------------------------------------------
 276LLQuaternion LLKeyframeMotion::RotationCurve::interp(F32 u, RotationKey& before, RotationKey& after)
 277{
 278	switch (mInterpolationType)
 279	{
 280	case IT_STEP:
 281		return before.mRotation;
 282
 283	default:
 284	case IT_LINEAR:
 285	case IT_SPLINE:
 286		return nlerp(u, before.mRotation, after.mRotation);
 287	}
 288}
 289
 290
 291//-----------------------------------------------------------------------------
 292// PositionCurve::PositionCurve()
 293//-----------------------------------------------------------------------------
 294LLKeyframeMotion::PositionCurve::PositionCurve()
 295{
 296	mInterpolationType = LLKeyframeMotion::IT_LINEAR;
 297	mNumKeys = 0;
 298}
 299
 300//-----------------------------------------------------------------------------
 301// PositionCurve::~PositionCurve()
 302//-----------------------------------------------------------------------------
 303LLKeyframeMotion::PositionCurve::~PositionCurve()
 304{
 305	mKeys.clear();
 306	mNumKeys = 0;
 307}
 308
 309//-----------------------------------------------------------------------------
 310// PositionCurve::getValue()
 311//-----------------------------------------------------------------------------
 312LLVector3 LLKeyframeMotion::PositionCurve::getValue(F32 time, F32 duration)
 313{
 314	LLVector3 value;
 315
 316	if (mKeys.empty())
 317	{
 318		value.clearVec();
 319		return value;
 320	}
 321	
 322	key_map_t::iterator right = mKeys.lower_bound(time);
 323	if (right == mKeys.end())
 324	{
 325		// Past last key
 326		--right;
 327		value = right->second.mPosition;
 328	}
 329	else if (right == mKeys.begin() || right->first == time)
 330	{
 331		// Before first key or exactly on a key
 332		value = right->second.mPosition;
 333	}
 334	else
 335	{
 336		// Between two keys
 337		key_map_t::iterator left = right; --left;
 338		F32 index_before = left->first;
 339		F32 index_after = right->first;
 340		PositionKey& pos_before = left->second;
 341		PositionKey& pos_after = right->second;
 342		if (right == mKeys.end())
 343		{
 344			pos_after = mLoopInKey;
 345			index_after = duration;
 346		}
 347
 348		F32 u = (time - index_before) / (index_after - index_before);
 349		value = interp(u, pos_before, pos_after);
 350	}
 351
 352	llassert(value.isFinite());
 353	
 354	return value;
 355}
 356
 357//-----------------------------------------------------------------------------
 358// interp()
 359//-----------------------------------------------------------------------------
 360LLVector3 LLKeyframeMotion::PositionCurve::interp(F32 u, PositionKey& before, PositionKey& after)
 361{
 362	switch (mInterpolationType)
 363	{
 364	case IT_STEP:
 365		return before.mPosition;
 366	default:
 367	case IT_LINEAR:
 368	case IT_SPLINE:
 369		return lerp(before.mPosition, after.mPosition, u);
 370	}
 371}
 372
 373
 374//-----------------------------------------------------------------------------
 375//-----------------------------------------------------------------------------
 376// JointMotion class
 377//-----------------------------------------------------------------------------
 378//-----------------------------------------------------------------------------
 379
 380//-----------------------------------------------------------------------------
 381// JointMotion::update()
 382//-----------------------------------------------------------------------------
 383void LLKeyframeMotion::JointMotion::update(LLJointState* joint_state, F32 time, F32 duration)
 384{
 385	// this value being 0 is the cause of https://jira.lindenlab.com/browse/SL-22678 but I haven't 
 386	// managed to get a stack to see how it got here. Testing for 0 here will stop the crash.
 387	if ( joint_state == NULL )
 388	{
 389		return;
 390	}
 391
 392	U32 usage = joint_state->getUsage();
 393
 394	//-------------------------------------------------------------------------
 395	// update scale component of joint state
 396	//-------------------------------------------------------------------------
 397	if ((usage & LLJointState::SCALE) && mScaleCurve.mNumKeys)
 398	{
 399		joint_state->setScale( mScaleCurve.getValue( time, duration ) );
 400	}
 401
 402	//-------------------------------------------------------------------------
 403	// update rotation component of joint state
 404	//-------------------------------------------------------------------------
 405	if ((usage & LLJointState::ROT) && mRotationCurve.mNumKeys)
 406	{
 407		joint_state->setRotation( mRotationCurve.getValue( time, duration ) );
 408	}
 409
 410	//-------------------------------------------------------------------------
 411	// update position component of joint state
 412	//-------------------------------------------------------------------------
 413	if ((usage & LLJointState::POS) && mPositionCurve.mNumKeys)
 414	{
 415		joint_state->setPosition( mPositionCurve.getValue( time, duration ) );
 416	}
 417}
 418
 419
 420//-----------------------------------------------------------------------------
 421//-----------------------------------------------------------------------------
 422// LLKeyframeMotion class
 423//-----------------------------------------------------------------------------
 424//-----------------------------------------------------------------------------
 425
 426//-----------------------------------------------------------------------------
 427// LLKeyframeMotion()
 428// Class Constructor
 429//-----------------------------------------------------------------------------
 430LLKeyframeMotion::LLKeyframeMotion(const LLUUID &id) 
 431	: LLMotion(id),
 432		mJointMotionList(NULL),
 433		mPelvisp(NULL),
 434		mLastSkeletonSerialNum(0),
 435		mLastUpdateTime(0.f),
 436		mLastLoopedTime(0.f),
 437		mAssetStatus(ASSET_UNDEFINED)
 438{
 439
 440}
 441
 442
 443//-----------------------------------------------------------------------------
 444// ~LLKeyframeMotion()
 445// Class Destructor
 446//-----------------------------------------------------------------------------
 447LLKeyframeMotion::~LLKeyframeMotion()
 448{
 449	for_each(mConstraints.begin(), mConstraints.end(), DeletePointer());
 450}
 451
 452//-----------------------------------------------------------------------------
 453// create()
 454//-----------------------------------------------------------------------------
 455LLMotion *LLKeyframeMotion::create(const LLUUID &id)
 456{
 457	return new LLKeyframeMotion(id);
 458}
 459
 460//-----------------------------------------------------------------------------
 461// getJointState()
 462//-----------------------------------------------------------------------------
 463LLPointer<LLJointState>& LLKeyframeMotion::getJointState(U32 index)
 464{
 465	llassert_always (index < mJointStates.size());
 466	return mJointStates[index];
 467}
 468
 469//-----------------------------------------------------------------------------
 470// getJoint()
 471//-----------------------------------------------------------------------------
 472LLJoint* LLKeyframeMotion::getJoint(U32 index)
 473{
 474	llassert_always (index < mJointStates.size());
 475	LLJoint* joint = mJointStates[index]->getJoint();
 476	
 477	//Commented out 06-28-11 by Aura.
 478	//llassert_always (joint);
 479	return joint;
 480}
 481
 482//-----------------------------------------------------------------------------
 483// LLKeyframeMotion::onInitialize(LLCharacter *character)
 484//-----------------------------------------------------------------------------
 485LLMotion::LLMotionInitStatus LLKeyframeMotion::onInitialize(LLCharacter *character)
 486{
 487	mCharacter = character;
 488	
 489	LLUUID* character_id;
 490
 491	// asset already loaded?
 492	switch(mAssetStatus)
 493	{
 494	case ASSET_NEEDS_FETCH:
 495		// request asset
 496		mAssetStatus = ASSET_FETCHED;
 497
 498		character_id = new LLUUID(mCharacter->getID());
 499		gAssetStorage->getAssetData(mID,
 500						LLAssetType::AT_ANIMATION,
 501						onLoadComplete,
 502						(void *)character_id,
 503						FALSE);
 504
 505		return STATUS_HOLD;
 506	case ASSET_FETCHED:
 507		return STATUS_HOLD;
 508	case ASSET_FETCH_FAILED:
 509		return STATUS_FAILURE;
 510	case ASSET_LOADED:
 511		return STATUS_SUCCESS;
 512	default:
 513		// we don't know what state the asset is in yet, so keep going
 514		// check keyframe cache first then static vfs then asset request
 515		break;
 516	}
 517
 518	LLKeyframeMotion::JointMotionList* joint_motion_list = LLKeyframeDataCache::getKeyframeData(getID());
 519
 520	if(joint_motion_list)
 521	{
 522		// motion already existed in cache, so grab it
 523		mJointMotionList = joint_motion_list;
 524
 525		mJointStates.reserve(mJointMotionList->getNumJointMotions());
 526		
 527		// don't forget to allocate joint states
 528		// set up joint states to point to character joints
 529		for(U32 i = 0; i < mJointMotionList->getNumJointMotions(); i++)
 530		{
 531			JointMotion* joint_motion = mJointMotionList->getJointMotion(i);
 532			if (LLJoint *joint = mCharacter->getJoint(joint_motion->mJointName))
 533			{
 534				LLPointer<LLJointState> joint_state = new LLJointState;
 535				mJointStates.push_back(joint_state);
 536				joint_state->setJoint(joint);
 537				joint_state->setUsage(joint_motion->mUsage);
 538				joint_state->setPriority(joint_motion->mPriority);
 539			}
 540			else
 541			{
 542				// add dummy joint state with no associated joint
 543				mJointStates.push_back(new LLJointState);
 544			}
 545		}
 546		mAssetStatus = ASSET_LOADED;
 547		setupPose();
 548		return STATUS_SUCCESS;
 549	}
 550
 551	//-------------------------------------------------------------------------
 552	// Load named file by concatenating the character prefix with the motion name.
 553	// Load data into a buffer to be parsed.
 554	//-------------------------------------------------------------------------
 555	U8 *anim_data;
 556	S32 anim_file_size;
 557
 558	if (!sVFS)
 559	{
 560		llerrs << "Must call LLKeyframeMotion::setVFS() first before loading a keyframe file!" << llendl;
 561	}
 562
 563	BOOL success = FALSE;
 564	LLVFile* anim_file = new LLVFile(sVFS, mID, LLAssetType::AT_ANIMATION);
 565	if (!anim_file || !anim_file->getSize())
 566	{
 567		delete anim_file;
 568		anim_file = NULL;
 569		
 570		// request asset over network on next call to load
 571		mAssetStatus = ASSET_NEEDS_FETCH;
 572
 573		return STATUS_HOLD;
 574	}
 575	else
 576	{
 577		anim_file_size = anim_file->getSize();
 578		anim_data = new U8[anim_file_size];
 579		success = anim_file->read(anim_data, anim_file_size);	/*Flawfinder: ignore*/
 580		delete anim_file;
 581		anim_file = NULL;
 582	}
 583
 584	if (!success)
 585	{
 586		llwarns << "Can't open animation file " << mID << llendl;
 587		mAssetStatus = ASSET_FETCH_FAILED;
 588		return STATUS_FAILURE;
 589	}
 590
 591	lldebugs << "Loading keyframe data for: " << getName() << ":" << getID() << " (" << anim_file_size << " bytes)" << llendl;
 592
 593	LLDataPackerBinaryBuffer dp(anim_data, anim_file_size);
 594
 595	if (!deserialize(dp))
 596	{
 597		llwarns << "Failed to decode asset for animation " << getName() << ":" << getID() << llendl;
 598		mAssetStatus = ASSET_FETCH_FAILED;
 599		return STATUS_FAILURE;
 600	}
 601
 602	delete []anim_data;
 603
 604	mAssetStatus = ASSET_LOADED;
 605	return STATUS_SUCCESS;
 606}
 607
 608//-----------------------------------------------------------------------------
 609// setupPose()
 610//-----------------------------------------------------------------------------
 611BOOL LLKeyframeMotion::setupPose()
 612{
 613	// add all valid joint states to the pose
 614	for (U32 jm=0; jm<mJointMotionList->getNumJointMotions(); jm++)
 615	{
 616		LLPointer<LLJointState> joint_state = getJointState(jm);
 617		if ( joint_state->getJoint() )
 618		{
 619			addJointState( joint_state );
 620		}
 621	}
 622
 623	// initialize joint constraints
 624	for (JointMotionList::constraint_list_t::iterator iter = mJointMotionList->mConstraints.begin();
 625		 iter != mJointMotionList->mConstraints.end(); ++iter)
 626	{
 627		JointConstraintSharedData* shared_constraintp = *iter;
 628		JointConstraint* constraintp = new JointConstraint(shared_constraintp);
 629		initializeConstraint(constraintp);
 630		mConstraints.push_front(constraintp);
 631	}
 632
 633	if (mJointMotionList->mConstraints.size())
 634	{
 635		mPelvisp = mCharacter->getJoint("mPelvis");
 636		if (!mPelvisp)
 637		{
 638			return FALSE;
 639		}
 640	}
 641
 642	// setup loop keys
 643	setLoopIn(mJointMotionList->mLoopInPoint);
 644	setLoopOut(mJointMotionList->mLoopOutPoint);
 645
 646	return TRUE;
 647}
 648
 649//-----------------------------------------------------------------------------
 650// LLKeyframeMotion::onActivate()
 651//-----------------------------------------------------------------------------
 652BOOL LLKeyframeMotion::onActivate()
 653{
 654	// If the keyframe anim has an associated emote, trigger it. 
 655	if( mJointMotionList->mEmoteName.length() > 0 )
 656	{
 657		LLUUID emote_anim_id = gAnimLibrary.stringToAnimState(mJointMotionList->mEmoteName);
 658		// don't start emote if already active to avoid recursion
 659		if (!mCharacter->isMotionActive(emote_anim_id))
 660		{
 661			mCharacter->startMotion( emote_anim_id );
 662		}
 663	}
 664
 665	mLastLoopedTime = 0.f;
 666
 667	return TRUE;
 668}
 669
 670//-----------------------------------------------------------------------------
 671// LLKeyframeMotion::onUpdate()
 672//-----------------------------------------------------------------------------
 673BOOL LLKeyframeMotion::onUpdate(F32 time, U8* joint_mask)
 674{
 675	llassert(time >= 0.f);
 676
 677	if (mJointMotionList->mLoop)
 678	{
 679		if (mJointMotionList->mDuration == 0.0f)
 680		{
 681			time = 0.f;
 682			mLastLoopedTime = 0.0f;
 683		}
 684		else if (mStopped)
 685		{
 686			mLastLoopedTime = llmin(mJointMotionList->mDuration, mLastLoopedTime + time - mLastUpdateTime);
 687		}
 688		else if (time > mJointMotionList->mLoopOutPoint)
 689		{
 690			if ((mJointMotionList->mLoopOutPoint - mJointMotionList->mLoopInPoint) == 0.f)
 691			{
 692				mLastLoopedTime = mJointMotionList->mLoopOutPoint;
 693			}
 694			else
 695			{
 696				mLastLoopedTime = mJointMotionList->mLoopInPoint + 
 697					fmod(time - mJointMotionList->mLoopOutPoint, 
 698					mJointMotionList->mLoopOutPoint - mJointMotionList->mLoopInPoint);
 699			}
 700		}
 701		else
 702		{
 703			mLastLoopedTime = time;
 704		}
 705	}
 706	else
 707	{
 708		mLastLoopedTime = time;
 709	}
 710
 711	applyKeyframes(mLastLoopedTime);
 712
 713	applyConstraints(mLastLoopedTime, joint_mask);
 714
 715	mLastUpdateTime = time;
 716
 717	return mLastLoopedTime <= mJointMotionList->mDuration;
 718}
 719
 720//-----------------------------------------------------------------------------
 721// applyKeyframes()
 722//-----------------------------------------------------------------------------
 723void LLKeyframeMotion::applyKeyframes(F32 time)
 724{
 725	llassert_always (mJointMotionList->getNumJointMotions() <= mJointStates.size());
 726	for (U32 i=0; i<mJointMotionList->getNumJointMotions(); i++)
 727	{
 728		mJointMotionList->getJointMotion(i)->update(mJointStates[i],
 729													  time, 
 730													  mJointMotionList->mDuration );
 731	}
 732
 733	LLJoint::JointPriority* pose_priority = (LLJoint::JointPriority* )mCharacter->getAnimationData("Hand Pose Priority");
 734	if (pose_priority)
 735	{
 736		if (mJointMotionList->mMaxPriority >= *pose_priority)
 737		{
 738			mCharacter->setAnimationData("Hand Pose", &mJointMotionList->mHandPose);
 739			mCharacter->setAnimationData("Hand Pose Priority", &mJointMotionList->mMaxPriority);
 740		}
 741	}
 742	else
 743	{
 744		mCharacter->setAnimationData("Hand Pose", &mJointMotionList->mHandPose);
 745		mCharacter->setAnimationData("Hand Pose Priority", &mJointMotionList->mMaxPriority);
 746	}
 747}
 748
 749//-----------------------------------------------------------------------------
 750// applyConstraints()
 751//-----------------------------------------------------------------------------
 752void LLKeyframeMotion::applyConstraints(F32 time, U8* joint_mask)
 753{
 754	//TODO: investigate replacing spring simulation with critically damped motion
 755
 756	// re-init constraints if skeleton has changed
 757	if (mCharacter->getSkeletonSerialNum() != mLastSkeletonSerialNum)
 758	{
 759		mLastSkeletonSerialNum = mCharacter->getSkeletonSerialNum();
 760		for (constraint_list_t::iterator iter = mConstraints.begin();
 761			 iter != mConstraints.end(); ++iter)
 762		{
 763			JointConstraint* constraintp = *iter;
 764			initializeConstraint(constraintp);
 765		}
 766	}
 767
 768	// apply constraints
 769	for (constraint_list_t::iterator iter = mConstraints.begin();
 770		 iter != mConstraints.end(); ++iter)
 771	{
 772		JointConstraint* constraintp = *iter;
 773		applyConstraint(constraintp, time, joint_mask);
 774	}
 775}
 776
 777//-----------------------------------------------------------------------------
 778// LLKeyframeMotion::onDeactivate()
 779//-----------------------------------------------------------------------------
 780void LLKeyframeMotion::onDeactivate()
 781{
 782	for (constraint_list_t::iterator iter = mConstraints.begin();
 783		 iter != mConstraints.end(); ++iter)
 784	{
 785		JointConstraint* constraintp = *iter;
 786		deactivateConstraint(constraintp);
 787	}
 788}
 789
 790//-----------------------------------------------------------------------------
 791// setStopTime()
 792//-----------------------------------------------------------------------------
 793// time is in seconds since character creation
 794void LLKeyframeMotion::setStopTime(F32 time)
 795{
 796	LLMotion::setStopTime(time);
 797
 798	if (mJointMotionList->mLoop && mJointMotionList->mLoopOutPoint != mJointMotionList->mDuration)
 799	{
 800		F32 start_loop_time = mActivationTimestamp + mJointMotionList->mLoopInPoint;
 801		F32 loop_fraction_time;
 802		if (mJointMotionList->mLoopOutPoint == mJointMotionList->mLoopInPoint)
 803		{
 804			loop_fraction_time = 0.f;
 805		}
 806		else
 807		{
 808			loop_fraction_time = fmod(time - start_loop_time, 
 809				mJointMotionList->mLoopOutPoint - mJointMotionList->mLoopInPoint);
 810		}
 811		mStopTimestamp = llmax(time, 
 812			(time - loop_fraction_time) + (mJointMotionList->mDuration - mJointMotionList->mLoopInPoint) - getEaseOutDuration());
 813	}
 814}
 815
 816//-----------------------------------------------------------------------------
 817// initializeConstraint()
 818//-----------------------------------------------------------------------------
 819void LLKeyframeMotion::initializeConstraint(JointConstraint* constraint)
 820{
 821	JointConstraintSharedData *shared_data = constraint->mSharedData;
 822
 823	S32 joint_num;
 824	LLVector3 source_pos = mCharacter->getVolumePos(shared_data->mSourceConstraintVolume, shared_data->mSourceConstraintOffset);
 825	LLJoint* cur_joint = getJoint(shared_data->mJointStateIndices[0]);
 826	if ( !cur_joint )
 827	{
 828		return;
 829	}
 830	
 831	F32 source_pos_offset = dist_vec(source_pos, cur_joint->getWorldPosition());
 832
 833	constraint->mTotalLength = constraint->mJointLengths[0] = dist_vec(cur_joint->getParent()->getWorldPosition(), source_pos);
 834	
 835	// grab joint lengths
 836	for (joint_num = 1; joint_num < shared_data->mChainLength; joint_num++)
 837	{
 838		cur_joint = getJointState(shared_data->mJointStateIndices[joint_num])->getJoint();
 839		if (!cur_joint)
 840		{
 841			return;
 842		}
 843		constraint->mJointLengths[joint_num] = dist_vec(cur_joint->getWorldPosition(), cur_joint->getParent()->getWorldPosition());
 844		constraint->mTotalLength += constraint->mJointLengths[joint_num];
 845	}
 846
 847	// store fraction of total chain length so we know how to shear the entire chain towards the goal position
 848	for (joint_num = 1; joint_num < shared_data->mChainLength; joint_num++)
 849	{
 850		constraint->mJointLengthFractions[joint_num] = constraint->mJointLengths[joint_num] / constraint->mTotalLength;
 851	}
 852
 853	// add last step in chain, from final joint to constraint position
 854	constraint->mTotalLength += source_pos_offset;
 855
 856	constraint->mSourceVolume = mCharacter->findCollisionVolume(shared_data->mSourceConstraintVolume);
 857	constraint->mTargetVolume = mCharacter->findCollisionVolume(shared_data->mTargetConstraintVolume);
 858}
 859
 860//-----------------------------------------------------------------------------
 861// activateConstraint()
 862//-----------------------------------------------------------------------------
 863void LLKeyframeMotion::activateConstraint(JointConstraint* constraint)
 864{
 865	JointConstraintSharedData *shared_data = constraint->mSharedData;
 866	constraint->mActive = TRUE;
 867	S32 joint_num;
 868
 869	// grab ground position if we need to
 870	if (shared_data->mConstraintTargetType == CONSTRAINT_TARGET_TYPE_GROUND)
 871	{
 872		LLVector3 source_pos = mCharacter->getVolumePos(shared_data->mSourceConstraintVolume, shared_data->mSourceConstraintOffset);
 873		LLVector3 ground_pos_agent;
 874		mCharacter->getGround(source_pos, ground_pos_agent, constraint->mGroundNorm);
 875		constraint->mGroundPos = mCharacter->getPosGlobalFromAgent(ground_pos_agent + shared_data->mTargetConstraintOffset);
 876	}
 877
 878	for (joint_num = 1; joint_num < shared_data->mChainLength; joint_num++)
 879	{
 880		LLJoint* cur_joint = getJoint(shared_data->mJointStateIndices[joint_num]);
 881		if ( !cur_joint )
 882		{
 883			return;
 884		}
 885		constraint->mPositions[joint_num] = (cur_joint->getWorldPosition() - mPelvisp->getWorldPosition()) * ~mPelvisp->getWorldRotation();
 886	}
 887
 888	constraint->mWeight = 1.f;
 889}
 890
 891//-----------------------------------------------------------------------------
 892// deactivateConstraint()
 893//-----------------------------------------------------------------------------
 894void LLKeyframeMotion::deactivateConstraint(JointConstraint *constraintp)
 895{
 896	if (constraintp->mSourceVolume)
 897	{
 898		constraintp->mSourceVolume->mUpdateXform = FALSE;
 899	}
 900
 901	if (!constraintp->mSharedData->mConstraintTargetType == CONSTRAINT_TARGET_TYPE_GROUND)
 902	{
 903		if (constraintp->mTargetVolume)
 904		{
 905			constraintp->mTargetVolume->mUpdateXform = FALSE;
 906		}
 907	}
 908	constraintp->mActive = FALSE;
 909}
 910
 911//-----------------------------------------------------------------------------
 912// applyConstraint()
 913//-----------------------------------------------------------------------------
 914void LLKeyframeMotion::applyConstraint(JointConstraint* constraint, F32 time, U8* joint_mask)
 915{
 916	JointConstraintSharedData *shared_data = constraint->mSharedData;
 917	if (!shared_data) return;
 918
 919	LLVector3		positions[MAX_CHAIN_LENGTH];
 920	const F32*		joint_lengths = constraint->mJointLengths;
 921	LLVector3		velocities[MAX_CHAIN_LENGTH - 1];
 922	LLQuaternion	old_rots[MAX_CHAIN_LENGTH];
 923	S32				joint_num;
 924
 925	if (time < shared_data->mEaseInStartTime)
 926	{
 927		return;
 928	}
 929
 930	if (time > shared_data->mEaseOutStopTime)
 931	{
 932		if (constraint->mActive)
 933		{
 934			deactivateConstraint(constraint);
 935		}
 936		return;
 937	}
 938
 939	if (!constraint->mActive || time < shared_data->mEaseInStopTime)
 940	{
 941		activateConstraint(constraint);
 942	}
 943
 944	LLJoint* root_joint = getJoint(shared_data->mJointStateIndices[shared_data->mChainLength]);
 945	if (! root_joint) 
 946	{
 947		return;
 948	}
 949	
 950	LLVector3 root_pos = root_joint->getWorldPosition();
 951//	LLQuaternion root_rot = 
 952	root_joint->getParent()->getWorldRotation();
 953//	LLQuaternion inv_root_rot = ~root_rot;
 954
 955//	LLVector3 current_source_pos = mCharacter->getVolumePos(shared_data->mSourceConstraintVolume, shared_data->mSourceConstraintOffset);
 956
 957	//apply underlying keyframe animation to get nominal "kinematic" joint positions
 958	for (joint_num = 0; joint_num <= shared_data->mChainLength; joint_num++)
 959	{
 960		LLJoint* cur_joint = getJoint(shared_data->mJointStateIndices[joint_num]);
 961		if (!cur_joint)
 962		{
 963			return;
 964		}
 965		
 966		if (joint_mask[cur_joint->getJointNum()] >= (0xff >> (7 - getPriority())))
 967		{
 968			// skip constraint
 969			return;
 970		}
 971		old_rots[joint_num] = cur_joint->getRotation();
 972		cur_joint->setRotation(getJointState(shared_data->mJointStateIndices[joint_num])->getRotation());
 973	}
 974
 975
 976	LLVector3 keyframe_source_pos = mCharacter->getVolumePos(shared_data->mSourceConstraintVolume, shared_data->mSourceConstraintOffset);
 977	LLVector3 target_pos;
 978
 979	switch(shared_data->mConstraintTargetType)
 980	{
 981	case CONSTRAINT_TARGET_TYPE_GROUND:
 982		target_pos = mCharacter->getPosAgentFromGlobal(constraint->mGroundPos);
 983//		llinfos << "Target Pos " << constraint->mGroundPos << " on " << mCharacter->findCollisionVolume(shared_data->mSourceConstraintVolume)->getName() << llendl;
 984		break;
 985	case CONSTRAINT_TARGET_TYPE_BODY:
 986		target_pos = mCharacter->getVolumePos(shared_data->mTargetConstraintVolume, shared_data->mTargetConstraintOffset);
 987		break;
 988	default:
 989		break;
 990	}
 991	
 992	LLVector3 norm;
 993	LLJoint *source_jointp = NULL;
 994	LLJoint *target_jointp = NULL;
 995
 996	if (shared_data->mConstraintType == CONSTRAINT_TYPE_PLANE)
 997	{
 998		switch(shared_data->mConstraintTargetType)
 999		{
1000		case CONSTRAINT_TARGET_TYPE_GROUND:
1001			norm = constraint->mGroundNorm;
1002			break;
1003		case CONSTRAINT_TARGET_TYPE_BODY:
1004			target_jointp = mCharacter->findCollisionVolume(shared_data->mTargetConstraintVolume);
1005			if (target_jointp)
1006			{
1007				// *FIX: do proper normal calculation for stretched
1008				// spheres (inverse transpose)
1009				norm = target_pos - target_jointp->getWorldPosition();
1010			}
1011
1012			if (norm.isExactlyZero())
1013			{
1014				source_jointp = mCharacter->findCollisionVolume(shared_data->mSourceConstraintVolume);
1015				norm = -1.f * shared_data->mSourceConstraintOffset;
1016				if (source_jointp)	
1017				{
1018					norm = norm * source_jointp->getWorldRotation();
1019				}
1020			}
1021			norm.normVec();
1022			break;
1023		default:
1024			norm.clearVec();
1025			break;
1026		}
1027		
1028		target_pos = keyframe_source_pos + (norm * ((target_pos - keyframe_source_pos) * norm));
1029	}
1030
1031	if (constraint->mSharedData->mChainLength != 0 &&
1032		dist_vec_squared(root_pos, target_pos) * 0.95f > constraint->mTotalLength * constraint->mTotalLength)
1033	{
1034		constraint->mWeight = lerp(constraint->mWeight, 0.f, LLCriticalDamp::getInterpolant(0.1f));
1035	}
1036	else
1037	{
1038		constraint->mWeight = lerp(constraint->mWeight, 1.f, LLCriticalDamp::getInterpolant(0.3f));
1039	}
1040
1041	F32 weight = constraint->mWeight * ((shared_data->mEaseOutStopTime == 0.f) ? 1.f : 
1042		llmin(clamp_rescale(time, shared_data->mEaseInStartTime, shared_data->mEaseInStopTime, 0.f, 1.f), 
1043		clamp_rescale(time, shared_data->mEaseOutStartTime, shared_data->mEaseOutStopTime, 1.f, 0.f)));
1044
1045	LLVector3 source_to_target = target_pos - keyframe_source_pos;
1046	
1047	S32 max_iteration_count = llround(clamp_rescale(
1048										  mCharacter->getPixelArea(),
1049										  MAX_PIXEL_AREA_CONSTRAINTS,
1050										  MIN_PIXEL_AREA_CONSTRAINTS,
1051										  (F32)MAX_ITERATIONS,
1052										  (F32)MIN_ITERATIONS));
1053
1054	if (shared_data->mChainLength)
1055	{
1056		LLJoint* end_joint = getJoint(shared_data->mJointStateIndices[0]);
1057		
1058		if (!end_joint)
1059		{
1060			return;
1061		}
1062		
1063		LLQuaternion end_rot = end_joint->getWorldRotation();
1064
1065		// slam start and end of chain to the proper positions (rest of chain stays put)
1066		positions[0] = lerp(keyframe_source_pos, target_pos, weight);
1067		positions[shared_data->mChainLength] = root_pos;
1068
1069		// grab keyframe-specified positions of joints	
1070		for (joint_num = 1; joint_num < shared_data->mChainLength; joint_num++)
1071		{
1072			LLJoint* cur_joint = getJoint(shared_data->mJointStateIndices[joint_num]);
1073			
1074			if (!cur_joint)
1075			{
1076				return;
1077			}
1078			
1079			LLVector3 kinematic_position = cur_joint->getWorldPosition() + 
1080				(source_to_target * constraint->mJointLengthFractions[joint_num]);
1081
1082			// convert intermediate joint positions to world coordinates
1083			positions[joint_num] = ( constraint->mPositions[joint_num] * mPelvisp->getWorldRotation()) + mPelvisp->getWorldPosition();
1084			F32 time_constant = 1.f / clamp_rescale(constraint->mFixupDistanceRMS, 0.f, 0.5f, 0.2f, 8.f);
1085//			llinfos << "Interpolant " << LLCriticalDamp::getInterpolant(time_constant, FALSE) << " and fixup distance " << constraint->mFixupDistanceRMS << " on " << mCharacter->findCollisionVolume(shared_data->mSourceConstraintVolume)->getName() << llendl;
1086			positions[joint_num] = lerp(positions[joint_num], kinematic_position, 
1087				LLCriticalDamp::getInterpolant(time_constant, FALSE));
1088		}
1089
1090		S32 iteration_count;
1091		for (iteration_count = 0; iteration_count < max_iteration_count; iteration_count++)
1092		{
1093			S32 num_joints_finished = 0;
1094			for (joint_num = 1; joint_num < shared_data->mChainLength; joint_num++)
1095			{
1096				// constraint to child
1097				LLVector3 acceleration = (positions[joint_num - 1] - positions[joint_num]) * 
1098					(dist_vec(positions[joint_num], positions[joint_num - 1]) - joint_lengths[joint_num - 1]) * JOINT_LENGTH_K;
1099				// constraint to parent
1100				acceleration  += (positions[joint_num + 1] - positions[joint_num]) * 
1101					(dist_vec(positions[joint_num + 1], positions[joint_num]) - joint_lengths[joint_num]) * JOINT_LENGTH_K;
1102
1103				if (acceleration.magVecSquared() < MIN_ACCELERATION_SQUARED)
1104				{
1105					num_joints_finished++;
1106				}
1107
1108				velocities[joint_num - 1] = velocities[joint_num - 1] * 0.7f;
1109				positions[joint_num] += velocities[joint_num - 1] + (acceleration * 0.5f);
1110				velocities[joint_num - 1] += acceleration;
1111			}
1112
1113			if ((iteration_count >= MIN_ITERATION_COUNT) && 
1114				(num_joints_finished == shared_data->mChainLength - 1))
1115			{
1116//				llinfos << iteration_count << " iterations on " << 
1117//					mCharacter->findCollisionVolume(shared_data->mSourceConstraintVolume)->getName() << llendl;
1118				break;
1119			}
1120		}
1121
1122		for (joint_num = shared_data->mChainLength; joint_num > 0; joint_num--)
1123		{
1124			LLJoint* cur_joint = getJoint(shared_data->mJointStateIndices[joint_num]);
1125			
1126			if (!cur_joint)
1127			{
1128				return;
1129			}
1130			LLJoint* child_joint = getJoint(shared_data->mJointStateIndices[joint_num - 1]);
1131			if (!child_joint)
1132			{
1133				return;
1134			}
1135			
1136			LLQuaternion parent_rot = cur_joint->getParent()->getWorldRotation();
1137
1138			LLQuaternion cur_rot = cur_joint->getWorldRotation();
1139			LLQuaternion fixup_rot;
1140			
1141			LLVector3 target_at = positions[joint_num - 1] - positions[joint_num];
1142			LLVector3 current_at;
1143
1144			// at bottom of chain, use point on collision volume, not joint position
1145			if (joint_num == 1)
1146			{
1147				current_at = mCharacter->getVolumePos(shared_data->mSourceConstraintVolume, shared_data->mSourceConstraintOffset) -
1148					cur_joint->getWorldPosition();
1149			}
1150			else
1151			{
1152				current_at = child_joint->getPosition() * cur_rot;
1153			}
1154			fixup_rot.shortestArc(current_at, target_at);
1155
1156			LLQuaternion target_rot = cur_rot * fixup_rot;
1157			target_rot = target_rot * ~parent_rot;
1158
1159			if (weight != 1.f)
1160			{
1161				LLQuaternion cur_rot = getJointState(shared_data->mJointStateIndices[joint_num])->getRotation();
1162				target_rot = nlerp(weight, cur_rot, target_rot);
1163			}
1164
1165			getJointState(shared_data->mJointStateIndices[joint_num])->setRotation(target_rot);
1166			cur_joint->setRotation(target_rot);
1167		}
1168
1169		LLQuaternion end_local_rot = end_rot * ~end_joint->getParent()->getWorldRotation();
1170
1171		if (weight == 1.f)
1172		{
1173			getJointState(shared_data->mJointStateIndices[0])->setRotation(end_local_rot);
1174		}
1175		else
1176		{
1177			LLQuaternion cur_rot = getJointState(shared_data->mJointStateIndices[0])->getRotation();
1178			getJointState(shared_data->mJointStateIndices[0])->setRotation(nlerp(weight, cur_rot, end_local_rot));
1179		}
1180
1181		// save simulated positions in pelvis-space and calculate total fixup distance
1182		constraint->mFixupDistanceRMS = 0.f;
1183		F32 delta_time = llmax(0.02f, llabs(time - mLastUpdateTime));
1184		for (joint_num = 1; joint_num < shared_data->mChainLength; joint_num++)
1185		{
1186			LLVector3 new_pos = (positions[joint_num] - mPelvisp->getWorldPosition()) * ~mPelvisp->getWorldRotation();
1187			constraint->mFixupDistanceRMS += dist_vec_squared(new_pos, constraint->mPositions[joint_num]) / delta_time;
1188			constraint->mPositions[joint_num] = new_pos;
1189		}
1190		constraint->mFixupDistanceRMS *= 1.f / (constraint->mTotalLength * (F32)(shared_data->mChainLength - 1));
1191		constraint->mFixupDistanceRMS = (F32) sqrt(constraint->mFixupDistanceRMS);
1192
1193		//reset old joint rots
1194		for (joint_num = 0; joint_num <= shared_data->mChainLength; joint_num++)
1195		{
1196			LLJoint* cur_joint = getJoint(shared_data->mJointStateIndices[joint_num]);
1197			if (!cur_joint)
1198			{
1199				return;
1200			}
1201
1202			cur_joint->setRotation(old_rots[joint_num]);
1203		}
1204	}
1205	// simple positional constraint (pelvis only)
1206	else if (getJointState(shared_data->mJointStateIndices[0])->getUsage() & LLJointState::POS)
1207	{
1208		LLVector3 delta = source_to_target * weight;
1209		LLPointer<LLJointState> current_joint_state = getJointState(shared_data->mJointStateIndices[0]);
1210		LLQuaternion parent_rot = current_joint_state->getJoint()->getParent()->getWorldRotation();
1211		delta = delta * ~parent_rot;
1212		current_joint_state->setPosition(current_joint_state->getJoint()->getPosition() + delta);
1213	}
1214}
1215
1216//-----------------------------------------------------------------------------
1217// deserialize()
1218//-----------------------------------------------------------------------------
1219BOOL LLKeyframeMotion::deserialize(LLDataPacker& dp)
1220{
1221	BOOL old_version = FALSE;
1222	mJointMotionList = new LLKeyframeMotion::JointMotionList;
1223
1224	//-------------------------------------------------------------------------
1225	// get base priority
1226	//-------------------------------------------------------------------------
1227	S32 temp_priority;
1228	U16 version;
1229	U16 sub_version;
1230
1231	if (!dp.unpackU16(version, "version"))
1232	{
1233		llwarns << "can't read version number" << llendl;
1234		return FALSE;
1235	}
1236
1237	if (!dp.unpackU16(sub_version, "sub_version"))
1238	{
1239		llwarns << "can't read sub version number" << llendl;
1240		return FALSE;
1241	}
1242
1243	if (version == 0 && sub_version == 1)
1244	{
1245		old_version = TRUE;
1246	}
1247	else if (version != KEYFRAME_MOTION_VERSION || sub_version != KEYFRAME_MOTION_SUBVERSION)
1248	{
1249#if LL_RELEASE
1250		llwarns << "Bad animation version " << version << "." << sub_version << llendl;
1251		return FALSE;
1252#else
1253		llerrs << "Bad animation version " << version << "." << sub_version << llendl;
1254#endif
1255	}
1256
1257	if (!dp.unpackS32(temp_priority, "base_priority"))
1258	{
1259		llwarns << "can't read animation base_priority" << llendl;
1260		return FALSE;
1261	}
1262	mJointMotionList->mBasePriority = (LLJoint::JointPriority) temp_priority;
1263
1264	if (mJointMotionList->mBasePriority >= LLJoint::ADDITIVE_PRIORITY)
1265	{
1266		mJointMotionList->mBasePriority = (LLJoint::JointPriority)((int)LLJoint::ADDITIVE_PRIORITY-1);
1267		mJointMotionList->mMaxPriority = mJointMotionList->mBasePriority;
1268	}
1269	else if (mJointMotionList->mBasePriority < LLJoint::USE_MOTION_PRIORITY)
1270	{
1271		llwarns << "bad animation base_priority " << mJointMotionList->mBasePriority << llendl;
1272		return FALSE;
1273	}
1274
1275	//-------------------------------------------------------------------------
1276	// get duration
1277	//-------------------------------------------------------------------------
1278	if (!dp.unpackF32(mJointMotionList->mDuration, "duration"))
1279	{
1280		llwarns << "can't read duration" << llendl;
1281		return FALSE;
1282	}
1283	
1284	if (mJointMotionList->mDuration > MAX_ANIM_DURATION ||
1285	    !llfinite(mJointMotionList->mDuration))
1286	{
1287		llwarns << "invalid animation duration" << llendl;
1288		return FALSE;
1289	}
1290
1291	//-------------------------------------------------------------------------
1292	// get emote (optional)
1293	//-------------------------------------------------------------------------
1294	if (!dp.unpackString(mJointMotionList->mEmoteName, "emote_name"))
1295	{
1296		llwarns << "can't read optional_emote_animation" << llendl;
1297		return FALSE;
1298	}
1299
1300	if(mJointMotionList->mEmoteName==mID.asString())
1301	{
1302		llwarns << "Malformed animation mEmoteName==mID" << llendl;
1303		return FALSE;
1304	}
1305
1306	//-------------------------------------------------------------------------
1307	// get loop
1308	//-------------------------------------------------------------------------
1309	if (!dp.unpackF32(mJointMotionList->mLoopInPoint, "loop_in_point") ||
1310	    !llfinite(mJointMotionList->mLoopInPoint))
1311	{
1312		llwarns << "can't read loop point" << llendl;
1313		return FALSE;
1314	}
1315
1316	if (!dp.unpackF32(mJointMotionList->mLoopOutPoint, "loop_out_point") ||
1317	    !llfinite(mJointMotionList->mLoopOutPoint))
1318	{
1319		llwarns << "can't read loop point" << llendl;
1320		return FALSE;
1321	}
1322
1323	if (!dp.unpackS32(mJointMotionList->mLoop, "loop"))
1324	{
1325		llwarns << "can't read loop" << llendl;
1326		return FALSE;
1327	}
1328
1329	//-------------------------------------------------------------------------
1330	// get easeIn and easeOut
1331	//-------------------------------------------------------------------------
1332	if (!dp.unpackF32(mJointMotionList->mEaseInDuration, "ease_in_duration") ||
1333	    !llfinite(mJointMotionList->mEaseInDuration))
1334	{
1335		llwarns << "can't read easeIn" << llendl;
1336		return FALSE;
1337	}
1338
1339	if (!dp.unpackF32(mJointMotionList->mEaseOutDuration, "ease_out_duration") ||
1340	    !llfinite(mJointMotionList->mEaseOutDuration))
1341	{
1342		llwarns << "can't read easeOut" << llendl;
1343		return FALSE;
1344	}
1345
1346	//-------------------------------------------------------------------------
1347	// get hand pose
1348	//-------------------------------------------------------------------------
1349	U32 word;
1350	if (!dp.unpackU32(word, "hand_pose"))
1351	{
1352		llwarns << "can't read hand pose" << llendl;
1353		return FALSE;
1354	}
1355	
1356	if(word > LLHandMotion::NUM_HAND_POSES)
1357	{
1358		llwarns << "invalid LLHandMotion::eHandPose index: " << word << llendl;
1359		return FALSE;
1360	}
1361	
1362	mJointMotionList->mHandPose = (LLHandMotion::eHandPose)word;
1363
1364	//-------------------------------------------------------------------------
1365	// get number of joint motions
1366	//-------------------------------------------------------------------------
1367	U32 num_motions = 0;
1368	if (!dp.unpackU32(num_motions, "num_joints"))
1369	{
1370		llwarns << "can't read number of joints" << llendl;
1371		return FALSE;
1372	}
1373
1374	if (num_motions == 0)
1375	{
1376		llwarns << "no joints in animation" << llendl;
1377		return FALSE;
1378	}
1379	else if (num_motions > LL_CHARACTER_MAX_JOINTS)
1380	{
1381		llwarns << "too many joints in animation" << llendl;
1382		return FALSE;
1383	}
1384
1385	mJointMotionList->mJointMotionArray.clear();
1386	mJointMotionList->mJointMotionArray.reserve(num_motions);
1387	mJointStates.clear();
1388	mJointStates.reserve(num_motions);
1389
1390	//-------------------------------------------------------------------------
1391	// initialize joint motions
1392	//-------------------------------------------------------------------------
1393
1394	for(U32 i=0; i<num_motions; ++i)
1395	{
1396		JointMotion* joint_motion = new JointMotion;		
1397		mJointMotionList->mJointMotionArray.push_back(joint_motion);
1398		
1399		std::string joint_name;
1400		if (!dp.unpackString(joint_name, "joint_name"))
1401		{
1402			llwarns << "can't read joint name" << llendl;
1403			return FALSE;
1404		}
1405
1406		if (joint_name == "mScreen" || joint_name == "mRoot")
1407		{
1408			llwarns << "attempted to animate special " << joint_name << " joint" << llendl;
1409			return FALSE;
1410		}
1411				
1412		//---------------------------------------------------------------------
1413		// find the corresponding joint
1414		//---------------------------------------------------------------------
1415		LLJoint *joint = mCharacter->getJoint( joint_name );
1416		if (joint)
1417		{
1418//			llinfos << "  joint: " << joint_name << llendl;
1419		}
1420		else
1421		{
1422			llwarns << "joint not found: " << joint_name << llendl;
1423			//return FALSE;
1424		}
1425
1426		joint_motion->mJointName = joint_name;
1427		
1428		LLPointer<LLJointState> joint_state = new LLJointState;
1429		mJointStates.push_back(joint_state);
1430		joint_state->setJoint( joint ); // note: can accept NULL
1431		joint_state->setUsage( 0 );
1432
1433		//---------------------------------------------------------------------
1434		// get joint priority
1435		//---------------------------------------------------------------------
1436		S32 joint_priority;
1437		if (!dp.unpackS32(joint_priority, "joint_priority"))
1438		{
1439			llwarns << "can't read joint priority." << llendl;
1440			return FALSE;
1441		}
1442
1443		if (joint_priority < LLJoint::USE_MOTION_PRIORITY)
1444		{
1445			llwarns << "joint priority unknown - too low." << llendl;
1446			return FALSE;
1447		}
1448		
1449		joint_motion->mPriority = (LLJoint::JointPriority)joint_priority;
1450		if (joint_priority != LLJoint::USE_MOTION_PRIORITY &&
1451		    joint_priority > mJointMotionList->mMaxPriority)
1452		{
1453			mJointMotionList->mMaxPriority = (LLJoint::JointPriority)joint_priority;
1454		}
1455
1456		joint_state->setPriority((LLJoint::JointPriority)joint_priority);
1457
1458		//---------------------------------------------------------------------
1459		// scan rotation curve header
1460		//---------------------------------------------------------------------
1461		if (!dp.unpackS32(joint_motion->mRotationCurve.mNumKeys, "num_rot_keys") || joint_motion->mRotationCurve.mNumKeys < 0)
1462		{
1463			llwarns << "can't read number of rotation keys" << llendl;
1464			return FALSE;
1465		}
1466
1467		joint_motion->mRotationCurve.mInterpolationType = IT_LINEAR;
1468		if (joint_motion->mRotationCurve.mNumKeys != 0)
1469		{
1470			joint_state->setUsage(joint_state->getUsage() | LLJointState::ROT );
1471		}
1472
1473		//---------------------------------------------------------------------
1474		// scan rotation curve keys
1475		//---------------------------------------------------------------------
1476		RotationCurve *rCurve = &joint_motion->mRotationCurve;
1477
1478		for (S32 k = 0; k < joint_motion->mRotationCurve.mNumKeys; k++)
1479		{
1480			F32 time;
1481			U16 time_short;
1482
1483			if (old_version)
1484			{
1485				if (!dp.unpackF32(time, "time") ||
1486				    !llfinite(time))
1487				{
1488					llwarns << "can't read rotation key (" << k << ")" << llendl;
1489					return FALSE;
1490				}
1491
1492			}
1493			else
1494			{
1495				if (!dp.unpackU16(time_short, "time"))
1496				{
1497					llwarns << "can't read rotation key (" << k << ")" << llendl;
1498					return FALSE;
1499				}
1500
1501				time = U16_to_F32(time_short, 0.f, mJointMotionList->mDuration);
1502				
1503				if (time < 0 || time > mJointMotionList->mDuration)
1504				{
1505					llwarns << "invalid frame time" << llendl;
1506					return FALSE;
1507				}
1508			}
1509			
1510			RotationKey rot_key;
1511			rot_key.mTime = time;
1512			LLVector3 rot_angles;
1513			U16 x, y, z;
1514
1515			BOOL success = TRUE;
1516
1517			if (old_version)
1518			{
1519				success = dp.unpackVector3(rot_angles, "rot_angles") && rot_angles.isFinite();
1520
1521				LLQuaternion::Order ro = StringToOrder("ZYX");
1522				rot_key.mRotation = mayaQ(rot_angles.mV[VX], rot_angles.mV[VY], rot_angles.mV[VZ], ro);
1523			}
1524			else
1525			{
1526				success &= dp.unpackU16(x, "rot_angle_x");
1527				success &= dp.unpackU16(y, "rot_angle_y");
1528				success &= dp.unpackU16(z, "rot_angle_z");
1529
1530				LLVector3 rot_vec;
1531				rot_vec.mV[VX] = U16_to_F32(x, -1.f, 1.f);
1532				rot_vec.mV[VY] = U16_to_F32(y, -1.f, 1.f);
1533				rot_vec.mV[VZ] = U16_to_F32(z, -1.f, 1.f);
1534				rot_key.mRotation.unpackFromVector3(rot_vec);
1535			}
1536
1537			if( !(rot_key.mRotation.isFinite()) )
1538			{
1539				llwarns << "non-finite angle in rotation key" << llendl;
1540				success = FALSE;
1541			}
1542			
1543			if (!success)
1544			{
1545				llwarns << "can't read rotation key (" << k << ")" << llendl;
1546				return FALSE;
1547			}
1548
1549			rCurve->mKeys[time] = rot_key;
1550		}
1551
1552		//---------------------------------------------------------------------
1553		// scan position curve header
1554		//---------------------------------------------------------------------
1555		if (!dp.unpackS32(joint_motion->mPositionCurve.mNumKeys, "num_pos_keys") || joint_motion->mPositionCurve.mNumKeys < 0)
1556		{
1557			llwarns << "can't read number of position keys" << llendl;
1558			return FALSE;
1559		}
1560
1561		joint_motion->mPositionCurve.mInterpolationType = IT_LINEAR;
1562		if (joint_motion->mPositionCurve.mNumKeys != 0)
1563		{
1564			joint_state->setUsage(joint_state->getUsage() | LLJointState::POS );
1565		}
1566
1567		//---------------------------------------------------------------------
1568		// scan position curve keys
1569		//---------------------------------------------------------------------
1570		PositionCurve *pCurve = &joint_motion->mPositionCurve;
1571		BOOL is_pelvis = joint_motion->mJointName == "mPelvis";
1572		for (S32 k = 0; k < joint_motion->mPositionCurve.mNumKeys; k++)
1573		{
1574			U16 time_short;
1575			PositionKey pos_key;
1576
1577			if (old_version)
1578			{
1579				if (!dp.unpackF32(pos_key

Large files files are truncated, but you can click here to view the full file