AnimatedModel.cpp 39 KB

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