AnimatedModel.cpp 37 KB

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