AnimatedModel.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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 "Batch.h"
  28. #include "Camera.h"
  29. #include "Context.h"
  30. #include "DebugRenderer.h"
  31. #include "DrawableEvents.h"
  32. #include "Geometry.h"
  33. #include "Graphics.h"
  34. #include "IndexBuffer.h"
  35. #include "Log.h"
  36. #include "Material.h"
  37. #include "MemoryBuffer.h"
  38. #include "Octree.h"
  39. #include "Profiler.h"
  40. #include "ResourceCache.h"
  41. #include "ResourceEvents.h"
  42. #include "Scene.h"
  43. #include "Sort.h"
  44. #include "VertexBuffer.h"
  45. #include "DebugNew.h"
  46. static const Vector3 DOT_SCALE(1 / 3.0f, 1 / 3.0f, 1 / 3.0f);
  47. static bool CompareAnimationOrder(const SharedPtr<AnimationState>& lhs, const SharedPtr<AnimationState>& rhs)
  48. {
  49. return lhs->GetLayer() < rhs->GetLayer();
  50. }
  51. OBJECTTYPESTATIC(AnimatedModel);
  52. AnimatedModel::AnimatedModel(Context* context) :
  53. StaticModel(context),
  54. animationLodFrameNumber_(0),
  55. animationLodBias_(1.0f),
  56. animationLodTimer_(-1.0f),
  57. animationLodDistance_(0.0f),
  58. invisibleLodFactor_(0.0f),
  59. animationDirty_(false),
  60. animationOrderDirty_(false),
  61. morphsDirty_(true),
  62. skinningDirty_(true),
  63. isMaster_(true),
  64. assignBonesPending_(false)
  65. {
  66. }
  67. AnimatedModel::~AnimatedModel()
  68. {
  69. }
  70. void AnimatedModel::RegisterObject(Context* context)
  71. {
  72. context->RegisterFactory<AnimatedModel>();
  73. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_RESOURCEREF, "Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  74. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_RESOURCEREFLIST, "Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()), AM_DEFAULT);
  75. ATTRIBUTE(AnimatedModel, VAR_BOOL, "Is Visible", visible_, true, AM_DEFAULT);
  76. ATTRIBUTE(AnimatedModel, VAR_BOOL, "Is Occluder", occluder_, false, AM_DEFAULT);
  77. ATTRIBUTE(AnimatedModel, VAR_BOOL, "Can Be Occluded", occludee_, true, AM_DEFAULT);
  78. ATTRIBUTE(AnimatedModel, VAR_BOOL, "Cast Shadows", castShadows_, false, AM_DEFAULT);
  79. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_FLOAT, "Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  80. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_FLOAT, "Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  81. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_FLOAT, "LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  82. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_FLOAT, "Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
  83. COPY_BASE_ATTRIBUTES(AnimatedModel, Drawable);
  84. ATTRIBUTE(AnimatedModel, VAR_INT, "Ray/Occl. LOD Level", softwareLodLevel_, M_MAX_UNSIGNED, AM_DEFAULT);
  85. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_VARIANTVECTOR, "Bone Animation Enabled", GetBonesEnabledAttr, SetBonesEnabledAttr, VariantVector, VariantVector(), AM_FILE | AM_NOEDIT);
  86. ACCESSOR_ATTRIBUTE(AnimatedModel, VAR_VARIANTVECTOR, "Animation States", GetAnimationStatesAttr, SetAnimationStatesAttr, VariantVector, VariantVector(), AM_FILE | AM_NOEDIT);
  87. }
  88. void AnimatedModel::ApplyAttributes()
  89. {
  90. if (assignBonesPending_)
  91. {
  92. AssignBoneNodes();
  93. assignBonesPending_ = false;
  94. }
  95. }
  96. void AnimatedModel::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  97. {
  98. // If no bones or no bone-level testing, use the Drawable test
  99. if (query.level_ < RAY_AABB || !skeleton_.GetRootBone() || !skeleton_.GetRootBone()->node_)
  100. {
  101. Drawable::ProcessRayQuery(query, results);
  102. return;
  103. }
  104. // Check ray hit distance to AABB before proceeding with bone-level tests
  105. if (query.ray_.HitDistance(GetWorldBoundingBox()) > query.maxDistance_)
  106. return;
  107. const Vector<Bone>& bones = skeleton_.GetBones();
  108. Sphere boneSphere;
  109. RayQueryLevel level = query.level_;
  110. for (unsigned i = 0; i < bones.Size(); ++i)
  111. {
  112. const Bone& bone = bones[i];
  113. if (!bone.node_)
  114. continue;
  115. // Use hitbox if available
  116. if (bone.collisionMask_ & BONECOLLISION_BOX)
  117. {
  118. // Do an initial crude test using the bone's AABB
  119. const BoundingBox& box = bone.boundingBox_;
  120. const Matrix3x4& transform = bone.node_->GetWorldTransform();
  121. float distance = query.ray_.HitDistance(box.Transformed(transform));
  122. if (distance <= query.maxDistance_)
  123. {
  124. if (level == RAY_AABB)
  125. {
  126. RayQueryResult result;
  127. result.drawable_ = this;
  128. result.node_ = GetNode();
  129. result.distance_ = distance;
  130. result.subObject_ = i;
  131. results.Push(result);
  132. }
  133. else
  134. {
  135. // Follow with an OBB test if required
  136. Matrix3x4 inverse = transform.Inverse();
  137. Ray localRay(inverse * query.ray_.origin_, inverse * Vector4(query.ray_.direction_, 0.0f));
  138. distance = localRay.HitDistance(box);
  139. if (distance <= query.maxDistance_)
  140. {
  141. RayQueryResult result;
  142. result.drawable_ = this;
  143. result.node_ = GetNode();
  144. result.distance_ = distance;
  145. result.subObject_ = i;
  146. results.Push(result);
  147. }
  148. }
  149. }
  150. }
  151. else if (bone.collisionMask_ & BONECOLLISION_SPHERE)
  152. {
  153. boneSphere.center_ = bone.node_->GetWorldPosition();
  154. boneSphere.radius_ = bone.radius_;
  155. float distance = query.ray_.HitDistance(boneSphere);
  156. if (distance <= query.maxDistance_)
  157. {
  158. RayQueryResult result;
  159. result.drawable_ = this;
  160. result.node_ = GetNode();
  161. result.subObject_ = i;
  162. result.distance_ = distance;
  163. results.Push(result);
  164. }
  165. }
  166. }
  167. }
  168. void AnimatedModel::Update(const FrameInfo& frame)
  169. {
  170. // Update animation here
  171. if (!animationDirty_ && !animationOrderDirty_)
  172. return;
  173. // If node was invisible last frame, need to decide animation LOD distance here
  174. // If headless, retain the current animation distance (should be 0)
  175. if (frame.camera_ && abs((int)frame.frameNumber_ - (int)viewFrameNumber_) > 1)
  176. {
  177. if (invisibleLodFactor_ == 0.0f)
  178. return;
  179. float distance = frame.camera_->GetDistance(GetWorldPosition());
  180. // If distance is greater than draw distance, no need to update at all
  181. if (drawDistance_ > 0.0f && distance > drawDistance_)
  182. return;
  183. // Multiply the distance by a constant so that invisible nodes don't update that often
  184. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  185. animationLodDistance_ = frame.camera_->GetLodDistance(distance, scale, lodBias_) * invisibleLodFactor_;
  186. }
  187. UpdateAnimation(frame);
  188. }
  189. void AnimatedModel::UpdateDistance(const FrameInfo& frame)
  190. {
  191. const Matrix3x4& worldTransform = GetWorldTransform();
  192. distance_ = frame.camera_->GetDistance(worldTransform.Translation());
  193. // Note: per-geometry distances do not take skinning into account
  194. for (unsigned i = 0; i < geometryCenters_.Size(); ++i)
  195. geometryDistances_[i] = frame.camera_->GetDistance(worldTransform * geometryCenters_[i]);
  196. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  197. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  198. // If model is rendered from several views, use the minimum LOD distance for animation LOD
  199. if (frame.frameNumber_ != animationLodFrameNumber_)
  200. {
  201. animationLodDistance_ = newLodDistance;
  202. animationLodFrameNumber_ = frame.frameNumber_;
  203. }
  204. else
  205. animationLodDistance_ = Min(animationLodDistance_, newLodDistance);
  206. if (newLodDistance != lodDistance_)
  207. {
  208. lodDistance_ = newLodDistance;
  209. CalculateLodLevels();
  210. }
  211. }
  212. void AnimatedModel::UpdateGeometry(const FrameInfo& frame)
  213. {
  214. if (morphsDirty_)
  215. UpdateMorphs();
  216. if (skinningDirty_)
  217. UpdateSkinning();
  218. }
  219. UpdateGeometryType AnimatedModel::GetUpdateGeometryType()
  220. {
  221. if (morphsDirty_)
  222. return UPDATE_MAIN_THREAD;
  223. else if (skinningDirty_)
  224. return UPDATE_WORKER_THREAD;
  225. else
  226. return UPDATE_NONE;
  227. }
  228. void AnimatedModel::GetBatch(Batch& batch, const FrameInfo& frame, unsigned batchIndex)
  229. {
  230. batch.distance_ = geometryDistances_[batchIndex];
  231. batch.geometry_ = geometries_[batchIndex][lodLevels_[batchIndex]];
  232. batch.geometryType_ = GEOM_SKINNED;
  233. batch.worldTransform_ = &GetWorldTransform();
  234. batch.material_ = materials_[batchIndex];
  235. if (skinMatrices_.Size())
  236. {
  237. // Check if model has per-geometry bone mappings
  238. if (geometrySkinMatrices_.Size() && geometrySkinMatrices_[batchIndex].Size())
  239. {
  240. batch.shaderData_ = geometrySkinMatrices_[batchIndex][0].GetData();
  241. batch.shaderDataSize_ = geometrySkinMatrices_[batchIndex].Size() * 12;
  242. }
  243. // If not, use the global skin matrices
  244. else
  245. {
  246. batch.shaderData_ = skinMatrices_[0].GetData();
  247. batch.shaderDataSize_ = skinMatrices_.Size() * 12;
  248. }
  249. }
  250. }
  251. void AnimatedModel::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  252. {
  253. debug->AddBoundingBox(GetWorldBoundingBox(), Color(0.0f, 1.0f, 0.0f), depthTest);
  254. debug->AddSkeleton(skeleton_, Color(0.75f, 0.75f, 0.75f), depthTest);
  255. }
  256. void AnimatedModel::SetModel(Model* model, bool createBones)
  257. {
  258. if (!model || model == model_)
  259. return;
  260. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  261. if (model_)
  262. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  263. if (model)
  264. SubscribeToEvent(model, E_RELOADFINISHED, HANDLER(AnimatedModel, HandleModelReloadFinished));
  265. model_ = model;
  266. // Copy the subgeometry & LOD level structure
  267. SetNumGeometries(model->GetNumGeometries());
  268. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  269. for (unsigned i = 0; i < geometries.Size(); ++i)
  270. geometries_[i] = geometries[i];
  271. geometryCenters_ = model->GetGeometryCenters();
  272. geometryDistances_.Resize(geometryCenters_.Size());
  273. // Copy geometry bone mappings
  274. const Vector<PODVector<unsigned> >& geometryBoneMappings = model->GetGeometryBoneMappings();
  275. geometryBoneMappings_.Clear();
  276. for (unsigned i = 0; i < geometryBoneMappings.Size(); ++i)
  277. geometryBoneMappings_.Push(geometryBoneMappings[i]);
  278. // Copy morphs
  279. morphVertexBuffers_.Clear();
  280. morphs_.Clear();
  281. const Vector<ModelMorph>& morphs = model->GetMorphs();
  282. for (unsigned i = 0; i < morphs.Size(); ++i)
  283. {
  284. ModelMorph newMorph;
  285. newMorph.name_ = morphs[i].name_;
  286. newMorph.nameHash_ = morphs[i].nameHash_;
  287. newMorph.weight_ = 0.0f;
  288. newMorph.buffers_ = morphs[i].buffers_;
  289. morphs_.Push(newMorph);
  290. }
  291. // If model has morphs, must clone all geometries & vertex buffers that refer to morphable vertex data
  292. if (morphs.Size())
  293. {
  294. CloneGeometries();
  295. MarkMorphsDirty();
  296. }
  297. // Copy bounding box & skeleton
  298. SetBoundingBox(model->GetBoundingBox());
  299. SetSkeleton(model->GetSkeleton(), createBones);
  300. }
  301. AnimationState* AnimatedModel::AddAnimationState(Animation* animation)
  302. {
  303. if (!isMaster_)
  304. {
  305. LOGERROR("Can not add animation state to non-master model");
  306. return 0;
  307. }
  308. if (!animation || !skeleton_.GetNumBones())
  309. return 0;
  310. // Check for not adding twice
  311. AnimationState* existing = GetAnimationState(animation);
  312. if (existing)
  313. return existing;
  314. SharedPtr<AnimationState> newState(new AnimationState(this, animation));
  315. animationStates_.Push(newState);
  316. MarkAnimationOrderDirty();
  317. return newState;
  318. }
  319. void AnimatedModel::RemoveAnimationState(Animation* animation)
  320. {
  321. if (animation)
  322. RemoveAnimationState(animation->GetNameHash());
  323. }
  324. void AnimatedModel::RemoveAnimationState(const String& animationName)
  325. {
  326. RemoveAnimationState(StringHash(animationName));
  327. }
  328. void AnimatedModel::RemoveAnimationState(StringHash animationNameHash)
  329. {
  330. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  331. {
  332. AnimationState* state = *i;
  333. Animation* animation = state->GetAnimation();
  334. // Check both the animation and the resource name
  335. if (animation->GetNameHash() == animationNameHash || animation->GetAnimationNameHash() == animationNameHash)
  336. {
  337. animationStates_.Erase(i);
  338. MarkAnimationDirty();
  339. }
  340. }
  341. }
  342. void AnimatedModel::RemoveAnimationState(AnimationState* state)
  343. {
  344. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  345. {
  346. if (*i == state)
  347. {
  348. animationStates_.Erase(i);
  349. MarkAnimationDirty();
  350. return;
  351. }
  352. }
  353. }
  354. void AnimatedModel::RemoveAllAnimationStates()
  355. {
  356. animationStates_.Clear();
  357. MarkAnimationDirty();
  358. }
  359. void AnimatedModel::SetAnimationLodBias(float bias)
  360. {
  361. animationLodBias_ = Max(bias, 0.0f);
  362. }
  363. void AnimatedModel::SetInvisibleLodFactor(float factor)
  364. {
  365. if (factor < 0.0f)
  366. factor = 0.0f;
  367. else if (factor != 0.0f && factor < 1.0f)
  368. factor = 1.0f;
  369. invisibleLodFactor_ = factor;
  370. }
  371. void AnimatedModel::SetMorphWeight(unsigned index, float weight)
  372. {
  373. if (index >= morphs_.Size())
  374. return;
  375. weight = Clamp(weight, 0.0f, 1.0f);
  376. if (weight != morphs_[index].weight_)
  377. {
  378. morphs_[index].weight_ = weight;
  379. MarkMorphsDirty();
  380. // For a master model, set the same morph weight on non-master models
  381. if (isMaster_)
  382. {
  383. PODVector<AnimatedModel*> models;
  384. GetComponents<AnimatedModel>(models);
  385. // Indexing might not be the same, so use the name hash instead
  386. for (unsigned i = 1; i < models.Size(); ++i)
  387. models[i]->SetMorphWeight(morphs_[index].nameHash_, weight);
  388. }
  389. }
  390. }
  391. void AnimatedModel::SetMorphWeight(const String& name, float weight)
  392. {
  393. for (unsigned i = 0; i < morphs_.Size(); ++i)
  394. {
  395. if (morphs_[i].name_ == name)
  396. {
  397. SetMorphWeight(i, weight);
  398. return;
  399. }
  400. }
  401. }
  402. void AnimatedModel::SetMorphWeight(StringHash nameHash, float weight)
  403. {
  404. for (unsigned i = 0; i < morphs_.Size(); ++i)
  405. {
  406. if (morphs_[i].nameHash_ == nameHash)
  407. {
  408. SetMorphWeight(i, weight);
  409. return;
  410. }
  411. }
  412. }
  413. void AnimatedModel::ResetMorphWeights()
  414. {
  415. for (Vector<ModelMorph>::Iterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  416. i->weight_ = 0.0f;
  417. MarkMorphsDirty();
  418. // For a master model, reset weights on non-master models
  419. if (isMaster_)
  420. {
  421. PODVector<AnimatedModel*> models;
  422. GetComponents<AnimatedModel>(models);
  423. // Indexing might not be the same, so use the name hash instead
  424. for (unsigned i = 1; i < models.Size(); ++i)
  425. models[i]->ResetMorphWeights();
  426. }
  427. }
  428. float AnimatedModel::GetMorphWeight(unsigned index) const
  429. {
  430. return index < morphs_.Size() ? morphs_[index].weight_ : 0.0f;
  431. }
  432. float AnimatedModel::GetMorphWeight(const String& name) const
  433. {
  434. for (Vector<ModelMorph>::ConstIterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  435. {
  436. if (i->name_ == name)
  437. return i->weight_;
  438. }
  439. return 0.0f;
  440. }
  441. float AnimatedModel::GetMorphWeight(StringHash nameHash) const
  442. {
  443. for (Vector<ModelMorph>::ConstIterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  444. {
  445. if (i->nameHash_ == nameHash)
  446. return i->weight_;
  447. }
  448. return 0.0f;
  449. }
  450. AnimationState* AnimatedModel::GetAnimationState(Animation* animation) const
  451. {
  452. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  453. {
  454. if ((*i)->GetAnimation() == animation)
  455. return *i;
  456. }
  457. return 0;
  458. }
  459. AnimationState* AnimatedModel::GetAnimationState(const String& animationName) const
  460. {
  461. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  462. {
  463. Animation* animation = (*i)->GetAnimation();
  464. // Check both the animation and the resource name
  465. if (animation->GetName() == animationName || animation->GetAnimationName() == animationName)
  466. return *i;
  467. }
  468. return 0;
  469. }
  470. AnimationState* AnimatedModel::GetAnimationState(StringHash animationNameHash) const
  471. {
  472. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  473. {
  474. Animation* animation = (*i)->GetAnimation();
  475. // Check both the animation and the resource name
  476. if (animation->GetNameHash() == animationNameHash || animation->GetAnimationNameHash() == animationNameHash)
  477. return *i;
  478. }
  479. return 0;
  480. }
  481. AnimationState* AnimatedModel::GetAnimationState(unsigned index) const
  482. {
  483. return index < animationStates_.Size() ? animationStates_[index].Get() : 0;
  484. }
  485. void AnimatedModel::SetSkeleton(const Skeleton& skeleton, bool createBones)
  486. {
  487. if (!node_ && createBones)
  488. {
  489. LOGWARNING("AnimatedModel not attached to a scene node, can not create bone nodes");
  490. return;
  491. }
  492. if (isMaster_)
  493. {
  494. // Check if bone structure has stayed compatible (reloading the model.) In that case retain the old bones and animations
  495. if (skeleton_.GetNumBones() == skeleton.GetNumBones())
  496. {
  497. Vector<Bone>& destBones = skeleton_.GetModifiableBones();
  498. const Vector<Bone>& srcBones = skeleton.GetBones();
  499. bool compatible = true;
  500. for (unsigned i = 0; i < destBones.Size(); ++i)
  501. {
  502. if (destBones[i].node_ && destBones[i].name_ == srcBones[i].name_ && destBones[i].parentIndex_ ==
  503. srcBones[i].parentIndex_)
  504. {
  505. // If compatible, just copy the values and retain the old node and animated status
  506. Node* boneNode = destBones[i].node_;
  507. bool animated = destBones[i].animated_;
  508. destBones[i] = srcBones[i];
  509. destBones[i].node_ = boneNode;
  510. destBones[i].animated_ = animated;
  511. }
  512. else
  513. {
  514. compatible = false;
  515. break;
  516. }
  517. }
  518. if (compatible)
  519. return;
  520. }
  521. RemoveAllAnimationStates();
  522. // Detach the rootbone of the previous model if any
  523. if (createBones)
  524. {
  525. Bone* rootBone = skeleton_.GetRootBone();
  526. if (rootBone)
  527. node_->RemoveChild(rootBone->node_);
  528. }
  529. skeleton_.Define(skeleton);
  530. // Remove collision information from dummy bones that do not affect skinning, to prevent them from being merged
  531. // to the bounding box
  532. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  533. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  534. {
  535. if (i->collisionMask_ & BONECOLLISION_BOX && i->boundingBox_.Size().Length() < M_EPSILON)
  536. i->collisionMask_ &= ~BONECOLLISION_BOX;
  537. if (i->collisionMask_ & BONECOLLISION_SPHERE && i->radius_ < M_EPSILON)
  538. i->collisionMask_ &= ~BONECOLLISION_SPHERE;
  539. }
  540. // Create scene nodes for the bones
  541. if (createBones)
  542. {
  543. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  544. {
  545. // Create bones as local, as they are never to be directly synchronized over the network
  546. Node* boneNode = node_->CreateChild(i->name_, LOCAL);
  547. boneNode->AddListener(this);
  548. boneNode->SetTransform(i->initialPosition_, i->initialRotation_, i->initialScale_);
  549. i->node_ = boneNode;
  550. }
  551. for (unsigned i = 0; i < bones.Size(); ++i)
  552. {
  553. unsigned parentIndex = bones[i].parentIndex_;
  554. if (parentIndex != i && parentIndex < bones.Size())
  555. bones[parentIndex].node_->AddChild(bones[i].node_);
  556. }
  557. }
  558. MarkAnimationDirty();
  559. using namespace BoneHierarchyCreated;
  560. VariantMap eventData;
  561. eventData[P_NODE] = (void*)node_;
  562. SendEvent(E_BONEHIERARCHYCREATED, eventData);
  563. }
  564. else
  565. {
  566. // For non-master models: use the bone nodes of the master model
  567. skeleton_.Define(skeleton);
  568. if (createBones)
  569. {
  570. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  571. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  572. {
  573. Node* boneNode = node_->GetChild(i->name_, true);
  574. if (boneNode)
  575. boneNode->AddListener(this);
  576. i->node_ = boneNode;
  577. }
  578. }
  579. }
  580. // Reserve space for skinning matrices
  581. skinMatrices_.Resize(skeleton_.GetNumBones());
  582. RefreshGeometryBoneMappings();
  583. assignBonesPending_ = !createBones;
  584. }
  585. void AnimatedModel::SetModelAttr(ResourceRef value)
  586. {
  587. ResourceCache* cache = GetSubsystem<ResourceCache>();
  588. // When loading a scene, set model without creating the bone nodes (will be assigned later during post-load)
  589. SetModel(cache->GetResource<Model>(value.id_), !IsLoading());
  590. }
  591. void AnimatedModel::SetBonesEnabledAttr(VariantVector value)
  592. {
  593. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  594. for (unsigned i = 0; i < bones.Size() && i < value.Size(); ++i)
  595. bones[i].animated_ = value[i].GetBool();
  596. }
  597. void AnimatedModel::SetAnimationStatesAttr(VariantVector value)
  598. {
  599. ResourceCache* cache = GetSubsystem<ResourceCache>();
  600. RemoveAllAnimationStates();
  601. unsigned index = 0;
  602. while (index < value.Size())
  603. {
  604. const ResourceRef& animRef = value[index++].GetResourceRef();
  605. AnimationState* state = AddAnimationState(cache->GetResource<Animation>(animRef.id_));
  606. if (state)
  607. {
  608. state->SetStartBone(skeleton_.GetBone(value[index++].GetStringHash()));
  609. state->SetLooped(value[index++].GetBool());
  610. state->SetWeight(value[index++].GetFloat());
  611. state->SetTime(value[index++].GetFloat());
  612. state->SetLayer(value[index++].GetInt());
  613. state->SetUseNlerp(value[index++].GetBool());
  614. }
  615. else
  616. index += 6;
  617. }
  618. }
  619. ResourceRef AnimatedModel::GetModelAttr() const
  620. {
  621. return GetResourceRef(model_, Model::GetTypeStatic());
  622. }
  623. VariantVector AnimatedModel::GetBonesEnabledAttr() const
  624. {
  625. VariantVector ret;
  626. const Vector<Bone>& bones = skeleton_.GetBones();
  627. for (Vector<Bone>::ConstIterator i = bones.Begin(); i != bones.End(); ++i)
  628. ret.Push(i->animated_);
  629. return ret;
  630. }
  631. VariantVector AnimatedModel::GetAnimationStatesAttr() const
  632. {
  633. VariantVector ret;
  634. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  635. {
  636. AnimationState* state = *i;
  637. Bone* startBone = state->GetStartBone();
  638. ret.Push(ResourceRef(Animation::GetTypeStatic(), state->GetAnimation()->GetNameHash()));
  639. ret.Push(startBone ? startBone->nameHash_ : StringHash());
  640. ret.Push(state->IsLooped());
  641. ret.Push(state->GetWeight());
  642. ret.Push(state->GetTime());
  643. ret.Push((int)state->GetLayer());
  644. ret.Push(state->GetUseNlerp());
  645. }
  646. return ret;
  647. }
  648. void AnimatedModel::OnNodeSet(Node* node)
  649. {
  650. Drawable::OnNodeSet(node);
  651. // If this AnimatedModel is the first in the node, it is the master which controls animation & morphs
  652. isMaster_ = GetComponent<AnimatedModel>() == this;
  653. }
  654. void AnimatedModel::OnMarkedDirty(Node* node)
  655. {
  656. Drawable::OnMarkedDirty(node);
  657. // If the scene node or any of the bone nodes move, mark skinning dirty
  658. skinningDirty_ = true;
  659. }
  660. void AnimatedModel::OnWorldBoundingBoxUpdate()
  661. {
  662. if (!skeleton_.GetNumBones())
  663. worldBoundingBox_ = boundingBox_.Transformed(GetWorldTransform());
  664. else
  665. {
  666. // If has bones, update world bounding box based on them
  667. worldBoundingBox_.defined_ = false;
  668. const Vector<Bone>& bones = skeleton_.GetBones();
  669. for (Vector<Bone>::ConstIterator i = bones.Begin(); i != bones.End(); ++i)
  670. {
  671. Node* boneNode = i->node_;
  672. if (!boneNode)
  673. continue;
  674. // Use hitbox if available. If not, use only half of the sphere radius
  675. if (i->collisionMask_ & BONECOLLISION_BOX)
  676. worldBoundingBox_.Merge(i->boundingBox_.Transformed(boneNode->GetWorldTransform()));
  677. else if (i->collisionMask_ & BONECOLLISION_SPHERE)
  678. worldBoundingBox_.Merge(Sphere(boneNode->GetWorldPosition(), i->radius_ * 0.5f));
  679. }
  680. }
  681. }
  682. void AnimatedModel::AssignBoneNodes()
  683. {
  684. if (!node_)
  685. return;
  686. // Find the bone nodes from the node hierarchy and add listeners
  687. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  688. bool boneFound = false;
  689. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  690. {
  691. Node* boneNode = node_->GetChild(i->name_, true);
  692. if (boneNode)
  693. {
  694. boneFound = true;
  695. boneNode->AddListener(this);
  696. }
  697. i->node_ = boneNode;
  698. }
  699. // If no bones found, this may be a prefab where the bone information was left out.
  700. // In that case reassign the skeleton now if possible
  701. if (!boneFound && model_)
  702. SetSkeleton(model_->GetSkeleton(), true);
  703. // Re-assign the same start bone to animations to get the proper bone node this time
  704. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  705. {
  706. AnimationState* state = *i;
  707. state->SetStartBone(state->GetStartBone());
  708. }
  709. MarkAnimationDirty();
  710. }
  711. void AnimatedModel::MarkAnimationDirty()
  712. {
  713. if (isMaster_)
  714. {
  715. animationDirty_ = true;
  716. // Mark for pre-octree reinsertion update (threaded)
  717. MarkForUpdate();
  718. }
  719. }
  720. void AnimatedModel::MarkAnimationOrderDirty()
  721. {
  722. if (isMaster_)
  723. {
  724. animationOrderDirty_ = true;
  725. // Mark for pre-octree reinsertion update (threaded)
  726. MarkForUpdate();
  727. }
  728. }
  729. void AnimatedModel::MarkMorphsDirty()
  730. {
  731. morphsDirty_ = true;
  732. }
  733. void AnimatedModel::CloneGeometries()
  734. {
  735. // Clone vertex buffers as necessary
  736. const Vector<SharedPtr<VertexBuffer> >& originalVertexBuffers = model_->GetVertexBuffers();
  737. Map<VertexBuffer*, SharedPtr<VertexBuffer> > clonedVertexBuffers;
  738. morphVertexBuffers_.Resize(originalVertexBuffers.Size());
  739. for (unsigned i = 0; i < originalVertexBuffers.Size(); ++i)
  740. {
  741. VertexBuffer* original = originalVertexBuffers[i];
  742. if (original->HasMorphRange())
  743. {
  744. SharedPtr<VertexBuffer> clone(new VertexBuffer(context_));
  745. clone->SetSize(original->GetVertexCount(), original->GetElementMask(), true);
  746. void* originalData = original->Lock(0, original->GetVertexCount(), LOCK_READONLY);
  747. if (originalData)
  748. {
  749. clone->SetData(originalData);
  750. original->Unlock();
  751. }
  752. clone->SetMorphRange(original->GetMorphRangeStart(), original->GetMorphRangeCount());
  753. clone->SetMorphRangeResetData(original->GetMorphRangeResetData());
  754. clonedVertexBuffers[original] = clone;
  755. morphVertexBuffers_[i] = clone;
  756. }
  757. }
  758. // Geometries will always be cloned fully. They contain only references to buffer, so they are relatively light
  759. for (unsigned i = 0; i < geometries_.Size(); ++i)
  760. {
  761. for (unsigned j = 0; j < geometries_[i].Size(); ++j)
  762. {
  763. SharedPtr<Geometry> original = geometries_[i][j];
  764. const Vector<SharedPtr<VertexBuffer> >& originalBuffers = original->GetVertexBuffers();
  765. SharedPtr<Geometry> clone(new Geometry(context_));
  766. clone->SetNumVertexBuffers(originalBuffers.Size());
  767. for (unsigned k = 0; k < originalBuffers.Size(); ++k)
  768. {
  769. VertexBuffer* originalBuffer = originalBuffers[k];
  770. if (clonedVertexBuffers.Contains(originalBuffer))
  771. clone->SetVertexBuffer(k, clonedVertexBuffers[originalBuffer], original->GetVertexElementMask(k));
  772. else
  773. clone->SetVertexBuffer(k, originalBuffers[k], original->GetVertexElementMask(k));
  774. }
  775. clone->SetIndexBuffer(original->GetIndexBuffer());
  776. clone->SetDrawRange(original->GetPrimitiveType(), original->GetIndexStart(), original->GetIndexCount());
  777. clone->SetLodDistance(original->GetLodDistance());
  778. clone->SetRawData(original->GetRawVertexData(), original->GetRawIndexData());
  779. geometries_[i][j] = clone;
  780. }
  781. }
  782. }
  783. void AnimatedModel::RefreshGeometryBoneMappings()
  784. {
  785. geometrySkinMatrices_.Clear();
  786. geometrySkinMatrixPtrs_.Clear();
  787. if (!geometryBoneMappings_.Size())
  788. return;
  789. // Check if all mappings are empty, then we do not need to use mapped skinning
  790. bool allEmpty = true;
  791. for (unsigned i = 0; i < geometryBoneMappings_.Size(); ++i)
  792. if (geometryBoneMappings_[i].Size())
  793. allEmpty = false;
  794. if (allEmpty)
  795. return;
  796. // Reserve space for per-geometry skinning matrices
  797. geometrySkinMatrices_.Resize(geometryBoneMappings_.Size());
  798. for (unsigned i = 0; i < geometryBoneMappings_.Size(); ++i)
  799. geometrySkinMatrices_[i].Resize(geometryBoneMappings_[i].Size());
  800. // Build original-to-skinindex matrix pointer mapping for fast copying
  801. // Note: at this point layout of geometrySkinMatrices_ cannot be modified or pointers become invalid
  802. geometrySkinMatrixPtrs_.Resize(skeleton_.GetNumBones());
  803. for (unsigned i = 0; i < geometryBoneMappings_.Size(); ++i)
  804. {
  805. for (unsigned j = 0; j < geometryBoneMappings_[i].Size(); ++j)
  806. geometrySkinMatrixPtrs_[geometryBoneMappings_[i][j]].Push(&geometrySkinMatrices_[i][j]);
  807. }
  808. }
  809. void AnimatedModel::UpdateAnimation(const FrameInfo& frame)
  810. {
  811. // If using animation LOD, accumulate time and see if it is time to update
  812. if (animationLodBias_ > 0.0f && animationLodDistance_ > 0.0f)
  813. {
  814. // Check for first time update
  815. if (animationLodTimer_ >= 0.0f)
  816. {
  817. animationLodTimer_ += animationLodBias_ * frame.timeStep_ * frame.viewSize_.y_ * ANIMATION_LOD_BASESCALE;
  818. if (animationLodTimer_ >= animationLodDistance_)
  819. animationLodTimer_ = fmodf(animationLodTimer_, animationLodDistance_);
  820. else
  821. return;
  822. }
  823. else
  824. animationLodTimer_ = 0.0f;
  825. }
  826. // Make sure animations are in ascending priority order
  827. if (animationOrderDirty_)
  828. {
  829. Sort(animationStates_.Begin(), animationStates_.End(), CompareAnimationOrder);
  830. animationOrderDirty_ = false;
  831. }
  832. // Reset skeleton, then apply all animations
  833. skeleton_.Reset();
  834. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  835. (*i)->Apply();
  836. // Animation has changed the bounding box: mark node for octree reinsertion
  837. Drawable::OnMarkedDirty(node_);
  838. // For optimization, recalculate world bounding box already here (during the threaded update)
  839. GetWorldBoundingBox();
  840. animationDirty_ = false;
  841. }
  842. void AnimatedModel::UpdateSkinning()
  843. {
  844. // Note: the model's world transform will be baked in the skin matrices
  845. const Vector<Bone>& bones = skeleton_.GetBones();
  846. // Use model's world transform in case a bone is missing
  847. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  848. // Skinning with global matrices only
  849. if (!geometrySkinMatrices_.Size())
  850. {
  851. for (unsigned i = 0; i < bones.Size(); ++i)
  852. {
  853. const Bone& bone = bones[i];
  854. if (bone.node_)
  855. skinMatrices_[i] = bone.node_->GetWorldTransform() * bone.offsetMatrix_;
  856. else
  857. skinMatrices_[i] = worldTransform;
  858. }
  859. }
  860. // Skinning with per-geometry matrices
  861. else
  862. {
  863. for (unsigned i = 0; i < bones.Size(); ++i)
  864. {
  865. const Bone& bone = bones[i];
  866. if (bone.node_)
  867. skinMatrices_[i] = bone.node_->GetWorldTransform() * bone.offsetMatrix_;
  868. else
  869. skinMatrices_[i] = worldTransform;
  870. // Copy the skin matrix to per-geometry matrices as needed
  871. for (unsigned j = 0; j < geometrySkinMatrixPtrs_[i].Size(); ++j)
  872. *geometrySkinMatrixPtrs_[i][j] = skinMatrices_[i];
  873. }
  874. }
  875. skinningDirty_ = false;
  876. }
  877. void AnimatedModel::UpdateMorphs()
  878. {
  879. if (morphs_.Size())
  880. {
  881. // Reset the morph data range from all morphable vertex buffers, then apply morphs
  882. for (unsigned i = 0; i < morphVertexBuffers_.Size(); ++i)
  883. {
  884. VertexBuffer* buffer = morphVertexBuffers_[i];
  885. if (buffer)
  886. {
  887. void* lockedMorphRange = buffer->LockMorphRange();
  888. if (!lockedMorphRange)
  889. continue;
  890. buffer->ResetMorphRange(lockedMorphRange);
  891. for (unsigned j = 0; j < morphs_.Size(); ++j)
  892. {
  893. if (morphs_[j].weight_ > 0.0f)
  894. {
  895. Map<unsigned, VertexBufferMorph>::Iterator k = morphs_[j].buffers_.Find(i);
  896. if (k != morphs_[j].buffers_.End())
  897. ApplyMorph(buffer, lockedMorphRange, k->second_, morphs_[j].weight_);
  898. }
  899. }
  900. buffer->Unlock();
  901. }
  902. }
  903. }
  904. morphsDirty_ = false;
  905. }
  906. void AnimatedModel::ApplyMorph(VertexBuffer* buffer, void* lockedMorphRange, const VertexBufferMorph& morph, float weight)
  907. {
  908. unsigned elementMask = morph.elementMask_;
  909. unsigned vertexCount = morph.vertexCount_;
  910. unsigned normalOffset = buffer->GetElementOffset(ELEMENT_NORMAL);
  911. unsigned tangentOffset = buffer->GetElementOffset(ELEMENT_TANGENT);
  912. unsigned morphRangeStart = buffer->GetMorphRangeStart();
  913. unsigned vertexSize = buffer->GetVertexSize();
  914. unsigned char* srcData = morph.morphData_;
  915. unsigned char* destData = (unsigned char*)lockedMorphRange;
  916. while (vertexCount--)
  917. {
  918. unsigned vertexIndex = *((unsigned*)srcData) - morphRangeStart;
  919. srcData += sizeof(unsigned);
  920. if (elementMask & MASK_POSITION)
  921. {
  922. float* dest = (float*)(destData + vertexIndex * vertexSize);
  923. float* src = (float*)srcData;
  924. dest[0] += src[0] * weight;
  925. dest[1] += src[1] * weight;
  926. dest[2] += src[2] * weight;
  927. srcData += 3 * sizeof(float);
  928. }
  929. if (elementMask & MASK_NORMAL)
  930. {
  931. float* dest = (float*)(destData + vertexIndex * vertexSize + normalOffset);
  932. float* src = (float*)srcData;
  933. dest[0] += src[0] * weight;
  934. dest[1] += src[1] * weight;
  935. dest[2] += src[2] * weight;
  936. srcData += 3 * sizeof(float);
  937. }
  938. if (elementMask & MASK_TANGENT)
  939. {
  940. float* dest = (float*)(destData + vertexIndex * vertexSize + tangentOffset);
  941. float* src = (float*)srcData;
  942. dest[0] += src[0] * weight;
  943. dest[1] += src[1] * weight;
  944. dest[2] += src[2] * weight;
  945. srcData += 3 * sizeof(float);
  946. }
  947. }
  948. }
  949. void AnimatedModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  950. {
  951. Model* currentModel = model_;
  952. model_ = 0; // Set null to allow to be re-set
  953. SetModel(currentModel);
  954. }