AnimatedModel.cpp 37 KB

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