AnimatedModel.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "AnimatedModel.h"
  25. #include "Animation.h"
  26. #include "AnimationState.h"
  27. #include "Camera.h"
  28. #include "DebugRenderer.h"
  29. #include "Geometry.h"
  30. #include "IndexBuffer.h"
  31. #include "Log.h"
  32. #include "Material.h"
  33. #include "Octree.h"
  34. #include "OctreeQuery.h"
  35. #include "Profiler.h"
  36. #include "Renderer.h"
  37. #include "ReplicationUtils.h"
  38. #include "ResourceCache.h"
  39. #include "Scene.h"
  40. #include "VertexBuffer.h"
  41. #include <algorithm>
  42. #include "DebugNew.h"
  43. static bool compareAnimationOrder(AnimationState* lhs, AnimationState* rhs)
  44. {
  45. return lhs->getPriority() < rhs->getPriority();
  46. }
  47. AnimatedModel::AnimatedModel(Octant* octant, const std::string& name) :
  48. StaticModel(NODE_ANIMATEDMODEL, octant, name),
  49. mAnimationLodFrameNumber(M_MAX_UNSIGNED),
  50. mAnimationLodBias(1.0f),
  51. mAnimationLodTimer(-1.0f),
  52. mAnimationLodDistance(0.0f),
  53. mInvisibleLodFactor(0.0f),
  54. mLocalAnimation(false),
  55. mAnimationDirty(true),
  56. mAnimationOrderDirty(true),
  57. mMorphsDirty(true)
  58. {
  59. }
  60. AnimatedModel::~AnimatedModel()
  61. {
  62. removeAllAnimationStates();
  63. }
  64. void AnimatedModel::save(Serializer& dest)
  65. {
  66. // Write GeometryNode properties
  67. GeometryNode::save(dest);
  68. // Write StaticModel properties
  69. dest.writeStringHash(getResourceHash(mModel));
  70. dest.writeVLE(mMaterials.size());
  71. for (unsigned i = 0; i < mMaterials.size(); ++i)
  72. dest.writeStringHash(getResourceHash(mMaterials[i]));
  73. // Write skeletal animation properties
  74. dest.writeFloat(mAnimationLodBias);
  75. dest.writeFloat(mInvisibleLodFactor);
  76. dest.writeBool(mLocalAnimation);
  77. // If this is the predicted component save, and local animation is enabled, do not store animation data
  78. bool localAnimation = (isProxy()) && (mLocalAnimation) && (checkPrediction());
  79. if (!localAnimation)
  80. {
  81. dest.writeVLE(mAnimationStates.size());
  82. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  83. {
  84. AnimationState* state = mAnimationStates[i];
  85. state->save(dest);
  86. }
  87. // Write morph properties
  88. dest.writeVLE(mMorphs.size());
  89. for (unsigned i = 0; i < mMorphs.size(); ++i)
  90. dest.writeFloat(mMorphs[i].mWeight);
  91. }
  92. else
  93. {
  94. dest.writeVLE(0);
  95. dest.writeVLE(0);
  96. }
  97. }
  98. void AnimatedModel::load(Deserializer& source, ResourceCache* cache)
  99. {
  100. // Read GeometryNode properties
  101. GeometryNode::load(source, cache);
  102. // Read StaticModel properties
  103. // Note: can not use StaticModel::load() because we need to set the skeleton
  104. setModel(cache->getResource<Model>(source.readStringHash()));
  105. unsigned numMaterials = source.readVLE();
  106. for (unsigned i = 0; i < numMaterials; ++i)
  107. setMaterial(i, cache->getResource<Material>(source.readStringHash()));
  108. // Read skeletal animation properties
  109. // If this is the predicted component load, and local animation is enabled, do not overwrite the animations
  110. mAnimationLodBias = source.readFloat();
  111. mInvisibleLodFactor = source.readFloat();
  112. mLocalAnimation = source.readBool();
  113. bool localAnimation = (isProxy()) && (mLocalAnimation) && (checkPrediction());
  114. std::set<StringHash> processed;
  115. unsigned numAnimationStates = source.readVLE();
  116. for (unsigned i = 0; i < numAnimationStates; ++i)
  117. {
  118. StringHash animation = source.readStringHash();
  119. AnimationState* newState = addAnimationState(cache->getResource<Animation>(animation));
  120. newState->load(source);
  121. processed.insert(animation);
  122. }
  123. if (!localAnimation)
  124. removeExtraAnimations(processed);
  125. // Read morph properties
  126. unsigned numMorphs = source.readVLE();
  127. for (unsigned i = 0; i < numMorphs; ++i)
  128. setMorphWeight(i, source.readFloat());
  129. }
  130. void AnimatedModel::saveXML(XMLElement& dest)
  131. {
  132. // Write GeometryNode properties
  133. GeometryNode::saveXML(dest);
  134. // Write StaticModel properties
  135. XMLElement modelElem = dest.createChildElement("model");
  136. modelElem.setString("name", getResourceName(mModel));
  137. for (unsigned i = 0; i < mMaterials.size(); ++i)
  138. {
  139. XMLElement materialElem = dest.createChildElement("material");
  140. materialElem.setInt("index", i);
  141. materialElem.setString("name", getResourceName(mMaterials[i]));
  142. }
  143. // Write skeletal animation properties
  144. XMLElement lodElem = dest.getChildElement("lod");
  145. lodElem.setFloat("animlodbias", mAnimationLodBias);
  146. lodElem.setFloat("invisiblelodfactor", mInvisibleLodFactor);
  147. lodElem.setBool("localanimation", mLocalAnimation);
  148. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  149. {
  150. XMLElement animationElem = dest.createChildElement("animation");
  151. mAnimationStates[i]->saveXML(animationElem);
  152. }
  153. // Write morph properties
  154. for (unsigned i = 0; i < mMorphs.size(); ++i)
  155. {
  156. XMLElement morphElem = dest.createChildElement("morph");
  157. morphElem.setInt("index", i);
  158. morphElem.setFloat("weight", mMorphs[i].mWeight);
  159. }
  160. }
  161. void AnimatedModel::loadXML(const XMLElement& source, ResourceCache* cache)
  162. {
  163. // Read GeometryNode properties
  164. GeometryNode::loadXML(source, cache);
  165. // Read StaticModel properties
  166. // Note: can not use StaticModel::loadXML() because we need to set the skeleton
  167. XMLElement modelElem = source.getChildElement("model");
  168. setModel(cache->getResource<Model>(modelElem.getString("name")));
  169. XMLElement materialElem = source.getChildElement("material");
  170. while (materialElem)
  171. {
  172. unsigned index = materialElem.getInt("index");
  173. setMaterial(index, cache->getResource<Material>(materialElem.getString("name")));
  174. materialElem = materialElem.getNextElement("material");
  175. }
  176. // Read skeletal animation properties
  177. XMLElement lodElem = source.getChildElement("lod");
  178. mAnimationLodBias = lodElem.getFloat("animlodbias");
  179. mInvisibleLodFactor = lodElem.getFloat("invisiblelodfactor");
  180. mLocalAnimation = lodElem.getBool("localanimation");
  181. removeAllAnimationStates();
  182. XMLElement animationElem = source.getChildElement("animation");
  183. while (animationElem)
  184. {
  185. AnimationState* newState = addAnimationState(cache->getResource<Animation>(animationElem.getString("name")));
  186. newState->loadXML(animationElem);
  187. animationElem = animationElem.getNextElement("animation");
  188. }
  189. // Read morph properties
  190. XMLElement morphElem = source.getChildElement("morph");
  191. while (morphElem)
  192. {
  193. unsigned index = morphElem.getInt("index");
  194. setMorphWeight(index, morphElem.getFloat("weight"));
  195. morphElem = morphElem.getNextElement("morph");
  196. }
  197. }
  198. bool AnimatedModel::writeNetUpdate(Serializer& dest, Serializer& destRevision, Deserializer& baseRevision, const NetUpdateInfo& info)
  199. {
  200. // Write GeometryNode properties and see if there were any changes
  201. bool prevBits = GeometryNode::writeNetUpdate(dest, destRevision, baseRevision, info);
  202. // Build bitmask of changed properties
  203. unsigned char bits = 0;
  204. // Model
  205. checkStringHash(getResourceHash(mModel), baseRevision, bits, 1);
  206. // Materials
  207. unsigned numBaseMaterials = baseRevision.getSize() ? baseRevision.readVLE() : 0;
  208. if (mMaterials.size() != numBaseMaterials)
  209. bits |= 2;
  210. for (unsigned i = 0; i < numBaseMaterials; ++i)
  211. {
  212. if (i < mMaterials.size())
  213. checkStringHash(getResourceHash(mMaterials[i]), baseRevision, bits, 2);
  214. else
  215. baseRevision.readStringHash();
  216. }
  217. // Animation LOD bias and invisible animation LOD distance factor
  218. checkFloat(mAnimationLodBias, 1.0f, baseRevision, bits, 4);
  219. checkFloat(mInvisibleLodFactor, 0.0f, baseRevision, bits, 4);
  220. // Animations
  221. unsigned numBaseAnimations = baseRevision.getSize() ? baseRevision.readVLE() : 0;
  222. if (mAnimationStates.size() != numBaseAnimations)
  223. bits |= 8;
  224. static std::vector<unsigned char> animBits;
  225. animBits.resize(mAnimationStates.size());
  226. // Assume that animations are new ie. require update of all fields
  227. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  228. animBits[i] = 1 | 2 | 4 | 8 | 16 | 32;
  229. for (unsigned i = 0; i < numBaseAnimations; ++i)
  230. {
  231. StringHash animation = baseRevision.readStringHash();
  232. StringHash startBone = baseRevision.readStringHash();
  233. bool looped = baseRevision.readBool();
  234. float weight = baseRevision.readFloat();
  235. float time = baseRevision.readFloat();
  236. int priority = baseRevision.readUByte();
  237. bool useNlerp = baseRevision.readBool();
  238. bool found = false;
  239. for (unsigned j = 0; j < mAnimationStates.size(); ++j)
  240. {
  241. AnimationState* state = mAnimationStates[j];
  242. if (state->getAnimation()->getNameHash() == animation)
  243. {
  244. // If animation exists in base state, update only the necessary properties
  245. found = true;
  246. animBits[j] = 0;
  247. if (startBone != state->getStartBone()->getNameHash())
  248. animBits[j] |= 1;
  249. if (looped != state->isLooped())
  250. animBits[j] |= 2;
  251. if (weight != state->getWeight())
  252. animBits[j] |= 4;
  253. if (time != state->getTime())
  254. animBits[j] |= 8;
  255. if (priority != state->getPriority())
  256. animBits[j] |= 16;
  257. if (useNlerp != state->getUseNlerp())
  258. animBits[j] |= 32;
  259. if (animBits[j])
  260. bits |= 8;
  261. break;
  262. }
  263. }
  264. // If not found, the number of animations has stayed same, but the animations are different
  265. if (!found)
  266. bits |= 8;
  267. }
  268. // Morphs
  269. unsigned numBaseMorphs = baseRevision.getSize() ? baseRevision.readVLE() : 0;
  270. if (mMorphs.size() != numBaseMorphs)
  271. bits |= 16;
  272. for (unsigned i = 0; i < numBaseMorphs; ++i)
  273. {
  274. if (i < mMorphs.size())
  275. checkUByte((unsigned char)(mMorphs[i].mWeight * 255.0f), baseRevision, bits, 16);
  276. else
  277. baseRevision.readUByte();
  278. }
  279. // Local animation flag
  280. checkBool(mLocalAnimation, false, baseRevision, bits, 32);
  281. // If local animation, do not send even if changed. It is slightly unoptimal to first check, then disable, but it ensures
  282. // that the base revision data stays the same (otherwise out of bounds reads might result when toggling local animation)
  283. if ((mLocalAnimation) && (checkPrediction(info.mConnection)))
  284. bits &= ~(8 | 16);
  285. // Update replication state fully, and network stream by delta
  286. dest.writeUByte(bits);
  287. writeStringHashDelta(getResourceHash(mModel), dest, destRevision, bits & 1);
  288. writeVLEDelta(mMaterials.size(), dest, destRevision, bits & 2);
  289. for (unsigned i = 0; i < mMaterials.size(); ++i)
  290. writeStringHashDelta(getResourceHash(mMaterials[i]), dest, destRevision, bits & 2);
  291. writeFloatDelta(mAnimationLodBias, dest, destRevision, bits & 4);
  292. writeFloatDelta(mInvisibleLodFactor, dest, destRevision, bits & 4);
  293. // Write all animations to the base replication state
  294. destRevision.writeVLE(mAnimationStates.size());
  295. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  296. {
  297. AnimationState* state = mAnimationStates[i];
  298. destRevision.writeStringHash(state->getAnimation()->getNameHash());
  299. destRevision.writeStringHash(state->getStartBone()->getNameHash());
  300. destRevision.writeBool(state->isLooped());
  301. destRevision.writeFloat(state->getWeight());
  302. destRevision.writeFloat(state->getTime());
  303. destRevision.writeUByte(state->getPriority());
  304. destRevision.writeBool(state->getUseNlerp());
  305. }
  306. // Then write delta of animations to the net stream
  307. if (bits & 8)
  308. {
  309. dest.writeVLE(mAnimationStates.size());
  310. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  311. {
  312. AnimationState* state = mAnimationStates[i];
  313. dest.writeStringHash(state->getAnimation()->getNameHash());
  314. dest.writeUByte(animBits[i]);
  315. if (animBits[i] & 1)
  316. dest.writeStringHash(state->getStartBone()->getNameHash());
  317. if (animBits[i] & 2)
  318. dest.writeBool(state->isLooped());
  319. if (animBits[i] & 4)
  320. dest.writeUByte((unsigned char)(state->getWeight() * 255.0f));
  321. if (animBits[i] & 8)
  322. dest.writeUShort((unsigned short)(state->getTime() * 65535.0f / state->getAnimation()->getLength()));
  323. if (animBits[i] & 16)
  324. dest.writeUByte(state->getPriority());
  325. if (animBits[i] & 32)
  326. dest.writeBool(state->getUseNlerp());
  327. }
  328. }
  329. writeVLEDelta(mMorphs.size(), dest, destRevision, bits & 16);
  330. for (unsigned i = 0; i < mMorphs.size(); ++i)
  331. writeUByteDelta((unsigned char)(mMorphs[i].mWeight * 255.0f), dest, destRevision, bits & 16);
  332. writeBoolDelta(mLocalAnimation, dest, destRevision, bits & 32);
  333. return prevBits || (bits != 0);
  334. }
  335. void AnimatedModel::readNetUpdate(Deserializer& source, ResourceCache* cache, const NetUpdateInfo& info)
  336. {
  337. // Read GeometryNode properties
  338. GeometryNode::readNetUpdate(source, cache, info);
  339. unsigned char bits = source.readUByte();
  340. if (bits & 1)
  341. setModel(cache->getResource<Model>(source.readStringHash()));
  342. if (bits & 2)
  343. {
  344. unsigned numMaterials = source.readVLE();
  345. for (unsigned i = 0; i < numMaterials; ++i)
  346. setMaterial(i, cache->getResource<Material>(source.readStringHash()));
  347. }
  348. if (bits & 4)
  349. {
  350. mAnimationLodBias = source.readFloat();
  351. mInvisibleLodFactor = source.readFloat();
  352. }
  353. if (bits & 8)
  354. {
  355. unsigned numAnimations = source.readVLE();
  356. std::set<StringHash> processed;
  357. for (unsigned i = 0; i < numAnimations; ++i)
  358. {
  359. StringHash animation = source.readStringHash();
  360. unsigned char animBits = source.readUByte();
  361. processed.insert(animation);
  362. // Find the animation state. If not found, create new
  363. AnimationState* state = getAnimationState(animation);
  364. bool newState = false;
  365. if (!state)
  366. {
  367. state = addAnimationState(cache->getResource<Animation>(animation));
  368. newState = true;
  369. }
  370. if (state)
  371. {
  372. if (animBits & 1)
  373. state->setStartBone(mSkeleton.getBone(source.readStringHash()));
  374. if (animBits & 2)
  375. state->setLooped(source.readBool());
  376. if (animBits & 4)
  377. state->setWeight(source.readUByte() / 255.0f);
  378. if (animBits & 8)
  379. state->setTime(source.readUShort() * state->getAnimation()->getLength() / 65535.0f);
  380. if (animBits & 16)
  381. state->setPriority(source.readUByte());
  382. if (animBits & 32)
  383. state->setUseNlerp(source.readBool());
  384. // If state is new, interpolate directly to the end
  385. if (newState)
  386. state->interpolate(true, mEntity->getScene()->getInterpolationLerpFactor());
  387. }
  388. else
  389. {
  390. // If state could not be added, just read the data to avoid desyncing the stream
  391. if (animBits & 1)
  392. source.readStringHash();
  393. if (animBits & 2)
  394. source.readBool();
  395. if (animBits & 4)
  396. source.readUByte();
  397. if (animBits & 8)
  398. source.readUShort();
  399. if (animBits & 16)
  400. source.readUByte();
  401. if (animBits & 32)
  402. source.readBool();
  403. }
  404. }
  405. removeExtraAnimations(processed);
  406. }
  407. if (bits & 16)
  408. {
  409. unsigned numMorphs = source.readVLE();
  410. for (unsigned i = 0; i < numMorphs; ++i)
  411. setMorphWeight(i, source.readUByte() / 255.0f);
  412. }
  413. readBoolDelta(mLocalAnimation, source, bits & 32);
  414. }
  415. void AnimatedModel::interpolate(bool snapToEnd)
  416. {
  417. Node::interpolate(snapToEnd);
  418. float t = mEntity->getScene()->getInterpolationLerpFactor();
  419. for (std::vector<AnimationState*>::iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  420. (*i)->interpolate(snapToEnd, t);
  421. }
  422. void AnimatedModel::getResourceRefs(std::vector<Resource*>& dest)
  423. {
  424. StaticModel::getResourceRefs(dest);
  425. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  426. dest.push_back(mAnimationStates[i]->getAnimation());
  427. }
  428. void AnimatedModel::processRayQuery(RayOctreeQuery& query, float initialDistance)
  429. {
  430. // If no bones or no bone-level testing, use the GeometryNode test
  431. if ((!mSkeleton.getNumBones()) || (query.mLevel < RAY_AABB))
  432. {
  433. GeometryNode::processRayQuery(query, initialDistance);
  434. return;
  435. }
  436. PROFILE(AnimatedModel_Raycast);
  437. const std::vector<SharedPtr<Bone> >& bones = mSkeleton.getBones();
  438. Sphere boneSphere;
  439. RayQueryLevel level = query.mLevel;
  440. for (unsigned i = 0; i < bones.size(); ++i)
  441. {
  442. Bone* bone = bones[i];
  443. unsigned collisionMask = bone->getCollisionMask();
  444. // Use hitbox if available
  445. if (collisionMask & BONECOLLISION_BOX)
  446. {
  447. // Do an initial crude test using the bone's AABB
  448. const Matrix4x3& transform = bone->getWorldTransform();
  449. const BoundingBox& box = bone->getBoundingBox();
  450. float distance = box.getTransformed(transform).getDistance(query.mRay);
  451. if (distance < query.mMaxDistance)
  452. {
  453. if (level == RAY_AABB)
  454. {
  455. RayQueryResult result;
  456. result.mNode = this;
  457. result.mDistance = distance;
  458. result.mSubObject = i;
  459. query.mResult.push_back(result);
  460. }
  461. else
  462. {
  463. // Follow with an OBB test if required
  464. Matrix4x3 inverse = transform.getInverse();
  465. Ray localRay(inverse * query.mRay.mOrigin, inverse * Vector4(query.mRay.mDirection, 0.0f));
  466. distance = box.getDistance(localRay);
  467. if (distance < query.mMaxDistance)
  468. {
  469. RayQueryResult result;
  470. result.mNode = this;
  471. result.mDistance = distance;
  472. result.mSubObject = i;
  473. query.mResult.push_back(result);
  474. }
  475. }
  476. }
  477. }
  478. else if (collisionMask & BONECOLLISION_SPHERE)
  479. {
  480. boneSphere.mCenter = bone->getWorldPosition();
  481. boneSphere.mRadius = bone->getRadius();
  482. float distance = boneSphere.getDistance(query.mRay);
  483. if (distance < query.mMaxDistance)
  484. {
  485. RayQueryResult result;
  486. result.mNode = this;
  487. result.mSubObject = i;
  488. result.mDistance = distance;
  489. query.mResult.push_back(result);
  490. }
  491. }
  492. }
  493. }
  494. void AnimatedModel::updateNode(const FrameInfo& frame)
  495. {
  496. // Update animation here
  497. if ((!mAnimationDirty) && (!mAnimationOrderDirty))
  498. return;
  499. // If node was invisible last frame, need to decide animation LOD distance here
  500. // If headless, retain the current animation distance (should be 0)
  501. if ((frame.mCamera) && (abs((int)frame.mFrameNumber - (int)mViewFrameNumber) > 1))
  502. {
  503. if (mInvisibleLodFactor == 0.0f)
  504. return;
  505. float distance = frame.mCamera->getDistance(getWorldPosition());
  506. // If distance is greater than draw distance, no need to update at all
  507. if ((mDrawDistance != 0.0f) && (distance > mDrawDistance))
  508. return;
  509. // Multiply the distance by a constant so that invisible nodes don't update that often
  510. static const Vector3 dotScale(1 / 3.0f, 1 / 3.0f, 1 / 3.0f);
  511. float scale = getWorldBoundingBox().getSize().dotProduct(dotScale);
  512. mAnimationLodDistance = frame.mCamera->getLodDistance(distance, scale, mLodBias) * mInvisibleLodFactor;
  513. }
  514. updateAnimation(frame);
  515. }
  516. void AnimatedModel::updateDistance(const FrameInfo& frame)
  517. {
  518. mDistance = frame.mCamera->getDistance(getWorldPosition());
  519. static const Vector3 dotScale(1 / 3.0f, 1 / 3.0f, 1 / 3.0f);
  520. float scale = getWorldBoundingBox().getSize().dotProduct(dotScale);
  521. float newLodDistance = frame.mCamera->getLodDistance(mDistance, scale, mLodBias);
  522. // If model is rendered from several views, use the minimum LOD distance for animation LOD
  523. if (frame.mFrameNumber != mAnimationLodFrameNumber)
  524. {
  525. mAnimationLodDistance = newLodDistance;
  526. mAnimationLodFrameNumber = frame.mFrameNumber;
  527. }
  528. else
  529. mAnimationLodDistance = min(mAnimationLodDistance, newLodDistance);
  530. if (newLodDistance != mLodDistance)
  531. {
  532. mLodDistance = newLodDistance;
  533. mLodLevelsDirty = true;
  534. }
  535. }
  536. void AnimatedModel::updateGeometry(const FrameInfo& frame, Renderer* renderer)
  537. {
  538. if (mLodLevelsDirty)
  539. calculateLodLevels();
  540. if ((mMorphsDirty) && (mMorphs.size()))
  541. updateMorphs();
  542. if ((mSkeleton.getNumBones()) && (mSkeleton.getRootBone()->isSkinningDirty()))
  543. updateSkinning();
  544. }
  545. bool AnimatedModel::getVertexShaderParameter(unsigned batchIndex, VSParameter parameter, const float** data, unsigned* count)
  546. {
  547. if ((parameter == VSP_MODELSKINMATRICES) && (mSkinMatrices.size()))
  548. {
  549. // Check if model has per-geometry bone mappings
  550. if ((mGeometrySkinMatrices.size()) && (mGeometrySkinMatrices[batchIndex].size()))
  551. {
  552. *count = mGeometrySkinMatrices[batchIndex].size() * 12;
  553. *data = mGeometrySkinMatrices[batchIndex][0].getData();
  554. }
  555. // If not, use the global skin matrices
  556. else
  557. {
  558. *count = mSkinMatrices.size() * 12;
  559. *data = mSkinMatrices[0].getData();
  560. }
  561. return true;
  562. }
  563. return false;
  564. }
  565. void AnimatedModel::drawDebugGeometry(DebugRenderer* debug)
  566. {
  567. debug->addBoundingBox(getWorldBoundingBox(), Color(0.0f, 1.0f, 0.0f), false);
  568. debug->addSkeleton(mSkeleton, Color(0.75f, 0.75f, 0.75f), false);
  569. }
  570. void AnimatedModel::setModel(Model* model)
  571. {
  572. if (model == mModel)
  573. return;
  574. PROFILE(AnimatedModel_SetModel);
  575. if (!model)
  576. return;
  577. mModel = model;
  578. // Copy the subgeometry & LOD level structure
  579. setNumGeometries(model->getNumGeometries());
  580. const std::vector<std::vector<SharedPtr<Geometry> > >& geometries = model->getGeometries();
  581. for (unsigned i = 0; i < geometries.size(); ++i)
  582. mGeometries[i] = geometries[i];
  583. // Copy geometry bone mappings
  584. const std::vector<std::vector<unsigned> >& geometryBoneMappings = model->getGeometryBoneMappings();
  585. mGeometryBoneMappings.clear();
  586. for (unsigned i = 0; i < geometryBoneMappings.size(); ++i)
  587. mGeometryBoneMappings.push_back(geometryBoneMappings[i]);
  588. // Copy morphs
  589. mMorphVertexBuffers.clear();
  590. mMorphs.clear();
  591. const std::vector<ModelMorph>& morphs = model->getMorphs();
  592. for (unsigned i = 0; i < morphs.size(); ++i)
  593. {
  594. ModelMorph newMorph;
  595. newMorph.mName = morphs[i].mName;
  596. newMorph.mNameHash = morphs[i].mNameHash;
  597. newMorph.mWeight = 0.0f;
  598. newMorph.mBuffers = morphs[i].mBuffers;
  599. mMorphs.push_back(newMorph);
  600. }
  601. // If model has morphs, must clone all geometries & vertex buffers that refer to morphable vertex data
  602. if (morphs.size())
  603. {
  604. cloneGeometries();
  605. markMorphsDirty();
  606. }
  607. // Copy bounding box & skeleton
  608. setBoundingBox(model->getBoundingBox());
  609. setSkeleton(model->getSkeleton());
  610. }
  611. AnimationState* AnimatedModel::addAnimationState(Animation* animation)
  612. {
  613. if (!animation)
  614. return 0;
  615. if (!mSkeleton.getNumBones())
  616. return 0;
  617. // Check for not adding twice
  618. AnimationState* existing = getAnimationState(animation);
  619. if (existing)
  620. return existing;
  621. AnimationState* newState = new AnimationState(this, animation);
  622. mAnimationStates.push_back(newState);
  623. markAnimationOrderDirty();
  624. return newState;
  625. }
  626. void AnimatedModel::removeAnimationState(Animation* animation)
  627. {
  628. if (animation)
  629. removeAnimationState(animation->getNameHash());
  630. }
  631. void AnimatedModel::removeAnimationState(const std::string& animationName)
  632. {
  633. removeAnimationState(StringHash(animationName));
  634. }
  635. void AnimatedModel::removeAnimationState(StringHash animationNameHash)
  636. {
  637. for (std::vector<AnimationState*>::iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  638. {
  639. AnimationState* state = *i;
  640. Animation* animation = state->getAnimation();
  641. // Check both the animation and the resource name
  642. if ((animation->getNameHash() == animationNameHash) || (animation->getAnimationNameHash() == animationNameHash))
  643. {
  644. // If animation is still interpolating, do not remove immediately, but set target weight to zero
  645. if ((isProxy()) && (state->isInterpolating()))
  646. state->setWeight(0.0f);
  647. else
  648. {
  649. delete state;
  650. mAnimationStates.erase(i);
  651. markAnimationDirty();
  652. }
  653. return;
  654. }
  655. }
  656. }
  657. void AnimatedModel::removeAnimationState(AnimationState* state)
  658. {
  659. for (std::vector<AnimationState*>::iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  660. {
  661. if (*i == state)
  662. {
  663. // If animation is still interpolating, do not remove immediately, but set target weight to zero
  664. if ((isProxy()) && (state->isInterpolating()))
  665. state->setWeight(0.0f);
  666. else
  667. {
  668. delete state;
  669. mAnimationStates.erase(i);
  670. markAnimationDirty();
  671. }
  672. return;
  673. }
  674. }
  675. }
  676. void AnimatedModel::removeAllAnimationStates()
  677. {
  678. for (std::vector<AnimationState*>::iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  679. delete *i;
  680. mAnimationStates.clear();
  681. markAnimationDirty();
  682. }
  683. void AnimatedModel::setAnimationLodBias(float bias)
  684. {
  685. mAnimationLodBias = max(bias, 0.0f);
  686. }
  687. void AnimatedModel::setInvisibleLodFactor(float factor)
  688. {
  689. if (factor < 0.0f)
  690. factor = 0.0f;
  691. else if ((factor != 0.0f) && (factor < 1.0f))
  692. factor = 1.0f;
  693. mInvisibleLodFactor = factor;
  694. }
  695. void AnimatedModel::setLocalAnimation(bool enable)
  696. {
  697. mLocalAnimation = enable;
  698. }
  699. void AnimatedModel::setMorphWeight(unsigned index, float weight)
  700. {
  701. if (index >= mMorphs.size())
  702. return;
  703. weight = clamp(weight, 0.0f, 1.0f);
  704. if (weight != mMorphs[index].mWeight)
  705. {
  706. mMorphs[index].mWeight = weight;
  707. markMorphsDirty();
  708. }
  709. }
  710. void AnimatedModel::setMorphWeight(const std::string& name, float weight)
  711. {
  712. weight = clamp(weight, 0.0f, 1.0f);
  713. for (std::vector<ModelMorph>::iterator i = mMorphs.begin(); i != mMorphs.end(); ++i)
  714. {
  715. if (i->mName == name)
  716. {
  717. if (weight != i->mWeight)
  718. {
  719. i->mWeight = weight;
  720. markMorphsDirty();
  721. }
  722. return;
  723. }
  724. }
  725. }
  726. void AnimatedModel::setMorphWeight(StringHash nameHash, float weight)
  727. {
  728. weight = clamp(weight, 0.0f, 1.0f);
  729. for (std::vector<ModelMorph>::iterator i = mMorphs.begin(); i != mMorphs.end(); ++i)
  730. {
  731. if (i->mNameHash == nameHash)
  732. {
  733. if (weight != i->mWeight)
  734. {
  735. i->mWeight = weight;
  736. markMorphsDirty();
  737. }
  738. return;
  739. }
  740. }
  741. }
  742. void AnimatedModel::resetMorphWeights()
  743. {
  744. for (std::vector<ModelMorph>::iterator i = mMorphs.begin(); i != mMorphs.end(); ++i)
  745. i->mWeight = 0.0f;
  746. markMorphsDirty();
  747. }
  748. void AnimatedModel::syncAnimation(AnimatedModel* srcNode)
  749. {
  750. if (!srcNode)
  751. return;
  752. // Make sure the animation proceeds at the same rate as in the source
  753. mAnimationLodBias = srcNode->mAnimationLodBias;
  754. mAnimationLodDistance = srcNode->mAnimationLodDistance;
  755. mAnimationLodFrameNumber = srcNode->mAnimationLodFrameNumber;
  756. const std::vector<AnimationState*>& srcStates = srcNode->getAnimationStates();
  757. std::set<Animation*> srcAnimations;
  758. for (unsigned i = 0; i < srcStates.size(); ++i)
  759. {
  760. AnimationState* src = srcStates[i];
  761. Animation* anim = src->getAnimation();
  762. srcAnimations.insert(anim);
  763. AnimationState* dest = getAnimationState(anim);
  764. if (!dest)
  765. dest = addAnimationState(anim);
  766. dest->sync(src);
  767. }
  768. // Check for extra states in destination and remove them
  769. if (mAnimationStates.size() > srcStates.size())
  770. {
  771. for (unsigned i = 0; i < mAnimationStates.size(); ++i)
  772. {
  773. AnimationState* state = mAnimationStates[i];
  774. if (srcAnimations.find(state->getAnimation()) == srcAnimations.end())
  775. removeAnimationState(state);
  776. }
  777. }
  778. }
  779. void AnimatedModel::syncMorphs(AnimatedModel* srcNode)
  780. {
  781. for (unsigned i = 0; i < mMorphs.size(); ++i)
  782. {
  783. float srcWeight = srcNode->getMorphWeight(mMorphs[i].mName);
  784. setMorphWeight(i, srcWeight);
  785. }
  786. }
  787. float AnimatedModel::getMorphWeight(unsigned index) const
  788. {
  789. if (index >= mMorphs.size())
  790. return 0.0f;
  791. return mMorphs[index].mWeight;
  792. }
  793. float AnimatedModel::getMorphWeight(const std::string& name) const
  794. {
  795. for (std::vector<ModelMorph>::const_iterator i = mMorphs.begin(); i != mMorphs.end(); ++i)
  796. {
  797. if (i->mName == name)
  798. return i->mWeight;
  799. }
  800. return 0.0f;
  801. }
  802. float AnimatedModel::getMorphWeight(StringHash nameHash) const
  803. {
  804. for (std::vector<ModelMorph>::const_iterator i = mMorphs.begin(); i != mMorphs.end(); ++i)
  805. {
  806. if (i->mNameHash == nameHash)
  807. return i->mWeight;
  808. }
  809. return 0.0f;
  810. }
  811. AnimationState* AnimatedModel::getAnimationState(Animation* animation) const
  812. {
  813. for (std::vector<AnimationState*>::const_iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  814. {
  815. if ((*i)->getAnimation() == animation)
  816. return *i;
  817. }
  818. return 0;
  819. }
  820. AnimationState* AnimatedModel::getAnimationState(const std::string& animationName) const
  821. {
  822. for (std::vector<AnimationState*>::const_iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  823. {
  824. Animation* animation = (*i)->getAnimation();
  825. // Check both the animation and the resource name
  826. if ((animation->getName() == animationName) || (animation->getAnimationName() == animationName))
  827. return *i;
  828. }
  829. return 0;
  830. }
  831. AnimationState* AnimatedModel::getAnimationState(StringHash animationNameHash) const
  832. {
  833. for (std::vector<AnimationState*>::const_iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  834. {
  835. Animation* animation = (*i)->getAnimation();
  836. // Check both the animation and the resource name
  837. if ((animation->getNameHash() == animationNameHash) || (animation->getAnimationNameHash() == animationNameHash))
  838. return *i;
  839. }
  840. return 0;
  841. }
  842. AnimationState* AnimatedModel::getAnimationState(unsigned index) const
  843. {
  844. if (index >= mAnimationStates.size())
  845. return 0;
  846. return mAnimationStates[index];
  847. }
  848. void AnimatedModel::setSkeleton(const Skeleton& skeleton)
  849. {
  850. PROFILE(AnimatedModel_SetSkeleton);
  851. removeAllAnimationStates();
  852. mSkeleton.define(skeleton.getBones());
  853. // Parent the root bone to the this node, so that objects can further be properly attached to bones
  854. Bone* rootBone = mSkeleton.getRootBone();
  855. if (rootBone)
  856. addChild(rootBone);
  857. // Reserve space for skinning matrices
  858. mSkinMatrices.resize(mSkeleton.getNumBones());
  859. refreshGeometryBoneMappings();
  860. }
  861. void AnimatedModel::onWorldBoundingBoxUpdate(BoundingBox& worldBoundingBox)
  862. {
  863. if (!mSkeleton.getNumBones())
  864. worldBoundingBox = mBoundingBox.getTransformed(getWorldTransform());
  865. else
  866. {
  867. // If has bones, update world bounding box based on them
  868. worldBoundingBox.mDefined = false;
  869. const std::vector<SharedPtr<Bone> >& bones = mSkeleton.getBones();
  870. for (std::vector<SharedPtr<Bone> >::const_iterator i = bones.begin(); i != bones.end(); ++i)
  871. {
  872. Bone* bone = *i;
  873. unsigned collisionMask = bone->getCollisionMask();
  874. // Use hitbox if available. If not, use only half of the sphere radius
  875. if (collisionMask & BONECOLLISION_BOX)
  876. worldBoundingBox.merge(bone->getBoundingBox().getTransformed(bone->getWorldTransform()));
  877. else if (collisionMask & BONECOLLISION_SPHERE)
  878. worldBoundingBox.merge(Sphere(bone->getWorldPosition(), bone->getRadius() * 0.5f));
  879. }
  880. }
  881. }
  882. void AnimatedModel::markAnimationDirty()
  883. {
  884. mAnimationDirty = true;
  885. // Mark for octree update, as animation is updated before octree reinsertion
  886. if (mOctant)
  887. mOctant->getRoot()->markNodeForUpdate(this);
  888. }
  889. void AnimatedModel::markAnimationOrderDirty()
  890. {
  891. mAnimationOrderDirty = true;
  892. // Mark for octree update, as animation is updated before octree reinsertion
  893. if (mOctant)
  894. mOctant->getRoot()->markNodeForUpdate(this);
  895. }
  896. void AnimatedModel::markMorphsDirty()
  897. {
  898. mMorphsDirty = true;
  899. }
  900. void AnimatedModel::cloneGeometries()
  901. {
  902. PROFILE(AnimatedModel_CloneGeometries);
  903. // Clone vertex buffers as necessary
  904. const std::vector<SharedPtr<VertexBuffer> >& originalVertexBuffers = mModel->getVertexBuffers();
  905. std::map<VertexBuffer*, SharedPtr<VertexBuffer> > clonedVertexBuffers;
  906. mMorphVertexBuffers.resize(originalVertexBuffers.size());
  907. for (unsigned i = 0; i < originalVertexBuffers.size(); ++i)
  908. {
  909. VertexBuffer* original = originalVertexBuffers[i];
  910. if (original->hasMorphRange())
  911. {
  912. SharedPtr<VertexBuffer> clone(new VertexBuffer(original->getRenderer()));
  913. clone->setSize(original->getVertexCount(), original->getElementMask());
  914. void* originalData = original->lock(0, original->getVertexCount(), LOCK_NORMAL);
  915. clone->setData(originalData);
  916. original->unlock();
  917. clone->setMorphRange(original->getMorphRangeStart(), original->getMorphRangeCount());
  918. clone->setMorphRangeResetData(original->getMorphRangeResetData());
  919. clonedVertexBuffers[original] = clone;
  920. mMorphVertexBuffers[i] = clone;
  921. }
  922. }
  923. // Geometries will always be cloned fully. They contain only references to buffer, so they are relatively light
  924. for (unsigned i = 0; i < mGeometries.size(); ++i)
  925. {
  926. for (unsigned j = 0; j < mGeometries[i].size(); ++j)
  927. {
  928. SharedPtr<Geometry> original = mGeometries[i][j];
  929. const std::vector<SharedPtr<VertexBuffer> >& originalBuffers = original->getVertexBuffers();
  930. SharedPtr<Geometry> clone(new Geometry());
  931. clone->setNumVertexBuffers(originalVertexBuffers.size());
  932. for (unsigned k = 0; k < originalVertexBuffers.size(); ++k)
  933. {
  934. VertexBuffer* originalBuffer = originalBuffers[k];
  935. if (clonedVertexBuffers.find(originalBuffer) != clonedVertexBuffers.end())
  936. clone->setVertexBuffer(k, clonedVertexBuffers[originalBuffer], original->getVertexElementMask(k));
  937. else
  938. clone->setVertexBuffer(k, originalBuffers[k], original->getVertexElementMask(k));
  939. }
  940. clone->setIndexBuffer(original->getIndexBuffer());
  941. clone->setDrawRange(original->getPrimitiveType(), original->getIndexStart(), original->getIndexCount());
  942. clone->setLodDistance(original->getLodDistance());
  943. mGeometries[i][j] = clone;
  944. }
  945. }
  946. }
  947. void AnimatedModel::refreshGeometryBoneMappings()
  948. {
  949. mGeometrySkinMatrices.clear();
  950. mGeometrySkinMatrixPtrs.clear();
  951. if (!mGeometryBoneMappings.size())
  952. return;
  953. // Check if all mappings are empty, then we do not need to use mapped skinning
  954. bool allEmpty = true;
  955. for (unsigned i = 0; i < mGeometryBoneMappings.size(); ++i)
  956. if (mGeometryBoneMappings[i].size())
  957. allEmpty = false;
  958. if (allEmpty)
  959. return;
  960. // Reserve space for per-geometry skinning matrices
  961. mGeometrySkinMatrices.resize(mGeometryBoneMappings.size());
  962. for (unsigned i = 0; i < mGeometryBoneMappings.size(); ++i)
  963. mGeometrySkinMatrices[i].resize(mGeometryBoneMappings[i].size());
  964. // Build original-to-skinindex matrix pointer mapping for fast copying
  965. // Note: at this point layout of mGeometrySkinMatrices cannot be modified or pointers become invalid
  966. mGeometrySkinMatrixPtrs.resize(mSkeleton.getNumBones());
  967. for (unsigned i = 0; i < mGeometryBoneMappings.size(); ++i)
  968. {
  969. for (unsigned j = 0; j < mGeometryBoneMappings[i].size(); ++j)
  970. mGeometrySkinMatrixPtrs[mGeometryBoneMappings[i][j]].push_back(&mGeometrySkinMatrices[i][j]);
  971. }
  972. }
  973. void AnimatedModel::updateAnimation(const FrameInfo& frame)
  974. {
  975. // If using animation LOD, accumulate time and see if it is time to update
  976. if ((mAnimationLodBias > 0.0f) && (mAnimationLodDistance > 0.0f))
  977. {
  978. // Check for first time update
  979. if (mAnimationLodTimer >= 0.0f)
  980. {
  981. mAnimationLodTimer += mAnimationLodBias * frame.mTimeStep * ANIMATION_LOD_BASESCALE;
  982. if (mAnimationLodTimer >= mAnimationLodDistance)
  983. mAnimationLodTimer = fmodf(mAnimationLodTimer, mAnimationLodDistance);
  984. else
  985. return;
  986. }
  987. else
  988. mAnimationLodTimer = 0.0f;
  989. }
  990. PROFILE(AnimatedModel_UpdateAnimation);
  991. // Make sure animations are in ascending priority order
  992. if (mAnimationOrderDirty)
  993. {
  994. std::sort(mAnimationStates.begin(), mAnimationStates.end(), compareAnimationOrder);
  995. mAnimationOrderDirty = false;
  996. }
  997. // Reset skeleton, then apply all animations
  998. mSkeleton.reset();
  999. for (std::vector<AnimationState*>::iterator i = mAnimationStates.begin(); i != mAnimationStates.end(); ++i)
  1000. (*i)->apply();
  1001. // Animation has changed the bounding box: mark node for octree reinsertion
  1002. VolumeNode::onMarkedDirty();
  1003. mAnimationDirty = false;
  1004. }
  1005. void AnimatedModel::updateSkinning()
  1006. {
  1007. PROFILE(AnimatedModel_UpdateSkinning);
  1008. // Note: the model's world transform will be baked in the skin matrices
  1009. const std::vector<SharedPtr<Bone > >& bones = mSkeleton.getBones();
  1010. // Skinning with global matrices only
  1011. if (!mGeometrySkinMatrices.size())
  1012. {
  1013. for (unsigned i = 0; i < bones.size(); ++i)
  1014. {
  1015. Bone* bone = bones[i];
  1016. if (bone->isSkinningDirty())
  1017. {
  1018. mSkinMatrices[i] = bone->getWorldTransform() * bone->getOffsetMatrix();
  1019. bone->clearSkinningDirty();
  1020. }
  1021. }
  1022. }
  1023. // Skinning with per-geometry matrices
  1024. else
  1025. {
  1026. for (unsigned i = 0; i < bones.size(); ++i)
  1027. {
  1028. Bone* bone = bones[i];
  1029. if (bone->isSkinningDirty())
  1030. {
  1031. mSkinMatrices[i] = bone->getWorldTransform() * bone->getOffsetMatrix();
  1032. // Copy the skin matrix to per-geometry matrices as needed
  1033. for (unsigned j = 0; j < mGeometrySkinMatrixPtrs[i].size(); ++j)
  1034. *mGeometrySkinMatrixPtrs[i][j] = mSkinMatrices[i];
  1035. bone->clearSkinningDirty();
  1036. }
  1037. }
  1038. }
  1039. }
  1040. void AnimatedModel::updateMorphs()
  1041. {
  1042. PROFILE(AnimatedModel_UpdateMorphs);
  1043. if (mMorphs.size())
  1044. {
  1045. try
  1046. {
  1047. // Reset the morph data range from all morphable vertex buffers, then apply morphs
  1048. for (unsigned i = 0; i < mMorphVertexBuffers.size(); ++i)
  1049. {
  1050. VertexBuffer* buffer = mMorphVertexBuffers[i];
  1051. if (buffer)
  1052. {
  1053. void* lockedMorphRange = buffer->lockMorphRange();
  1054. buffer->resetMorphRange(lockedMorphRange);
  1055. for (unsigned j = 0; j < mMorphs.size(); ++j)
  1056. {
  1057. if (mMorphs[j].mWeight > 0.0f)
  1058. {
  1059. std::map<unsigned, VertexBufferMorph>::iterator k = mMorphs[j].mBuffers.find(i);
  1060. if (k != mMorphs[j].mBuffers.end())
  1061. applyMorph(buffer, lockedMorphRange, k->second, mMorphs[j].mWeight);
  1062. }
  1063. }
  1064. buffer->unlock();
  1065. }
  1066. }
  1067. }
  1068. catch (...)
  1069. {
  1070. }
  1071. }
  1072. mMorphsDirty = false;
  1073. }
  1074. void AnimatedModel::applyMorph(VertexBuffer* buffer, void* lockedMorphRange, const VertexBufferMorph& morph, float weight)
  1075. {
  1076. unsigned elementMask = morph.mElementMask;
  1077. unsigned vertexCount = morph.mVertexCount;
  1078. unsigned normalOffset = buffer->getElementOffset(ELEMENT_NORMAL);
  1079. unsigned tangentOffset = buffer->getElementOffset(ELEMENT_TANGENT);
  1080. unsigned morphRangeStart = buffer->getMorphRangeStart();
  1081. unsigned vertexSize = buffer->getVertexSize();
  1082. unsigned char* srcData = morph.mMorphData;
  1083. unsigned char* destData = (unsigned char*)lockedMorphRange;
  1084. while (vertexCount--)
  1085. {
  1086. unsigned vertexIndex = *((unsigned*)srcData) - morphRangeStart;
  1087. srcData += sizeof(unsigned);
  1088. if (elementMask & MASK_POSITION)
  1089. {
  1090. float* dest = (float*)(destData + vertexIndex * vertexSize);
  1091. float* src = (float*)srcData;
  1092. dest[0] += src[0] * weight;
  1093. dest[1] += src[1] * weight;
  1094. dest[2] += src[2] * weight;
  1095. srcData += 3 * sizeof(float);
  1096. }
  1097. if (elementMask & MASK_NORMAL)
  1098. {
  1099. float* dest = (float*)(destData + vertexIndex * vertexSize + normalOffset);
  1100. float* src = (float*)srcData;
  1101. dest[0] += src[0] * weight;
  1102. dest[1] += src[1] * weight;
  1103. dest[2] += src[2] * weight;
  1104. srcData += 3 * sizeof(float);
  1105. }
  1106. if (elementMask & MASK_TANGENT)
  1107. {
  1108. float* dest = (float*)(destData + vertexIndex * vertexSize + tangentOffset);
  1109. float* src = (float*)srcData;
  1110. dest[0] += src[0] * weight;
  1111. dest[1] += src[1] * weight;
  1112. dest[2] += src[2] * weight;
  1113. srcData += 3 * sizeof(float);
  1114. }
  1115. }
  1116. }
  1117. void AnimatedModel::removeExtraAnimations(const std::set<StringHash>& animations)
  1118. {
  1119. bool removedAny = false;
  1120. for (std::vector<AnimationState*>::iterator i = mAnimationStates.begin(); i != mAnimationStates.end();)
  1121. {
  1122. AnimationState* state = *i;
  1123. if (animations.find(state->getAnimation()->getNameHash()) == animations.end())
  1124. {
  1125. // If animation is still interpolating, do not remove immediately, but set target weight to zero
  1126. if ((isProxy()) && (state->isInterpolating()))
  1127. {
  1128. state->setWeight(0.0f);
  1129. ++i;
  1130. }
  1131. else
  1132. {
  1133. delete state;
  1134. i = mAnimationStates.erase(i);
  1135. removedAny = true;
  1136. }
  1137. }
  1138. else
  1139. ++i;
  1140. }
  1141. if (removedAny)
  1142. markAnimationDirty();
  1143. }