AnimatedModel.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Atomic3D/AnimatedModel.h"
  26. #include "../Atomic3D/Animation.h"
  27. #include "../Atomic3D/AnimationState.h"
  28. #include "../Graphics/Batch.h"
  29. #include "../Graphics/Camera.h"
  30. #include "../Graphics/DebugRenderer.h"
  31. #include "../Graphics/DrawableEvents.h"
  32. #include "../Graphics/Geometry.h"
  33. #include "../Graphics/Graphics.h"
  34. #include "../Graphics/IndexBuffer.h"
  35. #include "../Graphics/Material.h"
  36. #include "../Graphics/Octree.h"
  37. #include "../Graphics/VertexBuffer.h"
  38. #include "../IO/Log.h"
  39. #include "../Resource/ResourceCache.h"
  40. #include "../Resource/ResourceEvents.h"
  41. #include "../Scene/Scene.h"
  42. #include "../DebugNew.h"
  43. namespace Atomic
  44. {
  45. extern const char* GEOMETRY_CATEGORY;
  46. static bool CompareAnimationOrder(const SharedPtr<AnimationState>& lhs, const SharedPtr<AnimationState>& rhs)
  47. {
  48. return lhs->GetLayer() < rhs->GetLayer();
  49. }
  50. static const unsigned MAX_ANIMATION_STATES = 256;
  51. bool AnimatedModel::boneCreationEnabled_ = true;
  52. AnimatedModel::AnimatedModel(Context* context) :
  53. StaticModel(context),
  54. animationLodFrameNumber_(0),
  55. morphElementMask_(0),
  56. animationLodBias_(1.0f),
  57. animationLodTimer_(-1.0f),
  58. animationLodDistance_(0.0f),
  59. updateInvisible_(false),
  60. animationDirty_(false),
  61. animationOrderDirty_(false),
  62. morphsDirty_(false),
  63. skinningDirty_(true),
  64. boneBoundingBoxDirty_(true),
  65. isMaster_(true),
  66. loading_(false),
  67. assignBonesPending_(false)
  68. {
  69. }
  70. AnimatedModel::~AnimatedModel()
  71. {
  72. // When being destroyed, remove the bone hierarchy if appropriate (last AnimatedModel in the node)
  73. Bone* rootBone = skeleton_.GetRootBone();
  74. if (rootBone && rootBone->node_)
  75. {
  76. Node* parent = rootBone->node_->GetParent();
  77. if (parent && !parent->GetComponent<AnimatedModel>())
  78. RemoveRootBone();
  79. }
  80. }
  81. void AnimatedModel::RegisterObject(Context* context)
  82. {
  83. context->RegisterFactory<AnimatedModel>(GEOMETRY_CATEGORY);
  84. ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  85. MIXED_ACCESSOR_ATTRIBUTE("Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  86. ACCESSOR_ATTRIBUTE("Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()),
  87. AM_DEFAULT);
  88. ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
  89. ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  90. ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
  91. ACCESSOR_ATTRIBUTE("Update When Invisible", GetUpdateInvisible, SetUpdateInvisible, bool, false, AM_DEFAULT);
  92. ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  93. ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  94. ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  95. ACCESSOR_ATTRIBUTE("Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
  96. COPY_BASE_ATTRIBUTES(Drawable);
  97. MIXED_ACCESSOR_ATTRIBUTE("Bone Animation Enabled", GetBonesEnabledAttr, SetBonesEnabledAttr, VariantVector,
  98. Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
  99. MIXED_ACCESSOR_ATTRIBUTE("Animation States", GetAnimationStatesAttr, SetAnimationStatesAttr, VariantVector,
  100. Variant::emptyVariantVector, AM_FILE);
  101. ACCESSOR_ATTRIBUTE("Morphs", GetMorphsAttr, SetMorphsAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  102. AM_DEFAULT | AM_NOEDIT);
  103. }
  104. bool AnimatedModel::Load(Deserializer& source, bool setInstanceDefault)
  105. {
  106. loading_ = true;
  107. bool success = Component::Load(source, setInstanceDefault);
  108. loading_ = false;
  109. return success;
  110. }
  111. bool AnimatedModel::LoadXML(const XMLElement& source, bool setInstanceDefault)
  112. {
  113. loading_ = true;
  114. bool success = Component::LoadXML(source, setInstanceDefault);
  115. loading_ = false;
  116. return success;
  117. }
  118. void AnimatedModel::ApplyAttributes()
  119. {
  120. if (assignBonesPending_)
  121. AssignBoneNodes();
  122. }
  123. void AnimatedModel::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  124. {
  125. // If no bones or no bone-level testing, use the StaticModel test
  126. RayQueryLevel level = query.level_;
  127. if (level < RAY_TRIANGLE || !skeleton_.GetNumBones() || !boneCreationEnabled_)
  128. {
  129. StaticModel::ProcessRayQuery(query, results);
  130. return;
  131. }
  132. // Check ray hit distance to AABB before proceeding with bone-level tests
  133. if (query.ray_.HitDistance(GetWorldBoundingBox()) >= query.maxDistance_)
  134. return;
  135. const Vector<Bone>& bones = skeleton_.GetBones();
  136. Sphere boneSphere;
  137. for (unsigned i = 0; i < bones.Size(); ++i)
  138. {
  139. const Bone& bone = bones[i];
  140. if (!bone.node_)
  141. continue;
  142. float distance;
  143. // Use hitbox if available
  144. if (bone.collisionMask_ & BONECOLLISION_BOX)
  145. {
  146. // Do an initial crude test using the bone's AABB
  147. const BoundingBox& box = bone.boundingBox_;
  148. const Matrix3x4& transform = bone.node_->GetWorldTransform();
  149. distance = query.ray_.HitDistance(box.Transformed(transform));
  150. if (distance >= query.maxDistance_)
  151. continue;
  152. if (level != RAY_AABB)
  153. {
  154. // Follow with an OBB test if required
  155. Matrix3x4 inverse = transform.Inverse();
  156. Ray localRay = query.ray_.Transformed(inverse);
  157. distance = localRay.HitDistance(box);
  158. if (distance >= query.maxDistance_)
  159. continue;
  160. }
  161. }
  162. else if (bone.collisionMask_ & BONECOLLISION_SPHERE)
  163. {
  164. boneSphere.center_ = bone.node_->GetWorldPosition();
  165. boneSphere.radius_ = bone.radius_;
  166. distance = query.ray_.HitDistance(boneSphere);
  167. if (distance >= query.maxDistance_)
  168. continue;
  169. }
  170. else
  171. continue;
  172. // If the code reaches here then we have a hit
  173. RayQueryResult result;
  174. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  175. result.normal_ = -query.ray_.direction_;
  176. result.distance_ = distance;
  177. result.drawable_ = this;
  178. result.node_ = node_;
  179. result.subObject_ = i;
  180. results.Push(result);
  181. }
  182. }
  183. void AnimatedModel::Update(const FrameInfo& frame)
  184. {
  185. // If node was invisible last frame, need to decide animation LOD distance here
  186. // If headless, retain the current animation distance (should be 0)
  187. if (frame.camera_ && abs((int)frame.frameNumber_ - (int)viewFrameNumber_) > 1)
  188. {
  189. // First check for no update at all when invisible
  190. if (!updateInvisible_)
  191. return;
  192. float distance = frame.camera_->GetDistance(node_->GetWorldPosition());
  193. // If distance is greater than draw distance, no need to update at all
  194. if (drawDistance_ > 0.0f && distance > drawDistance_)
  195. return;
  196. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  197. animationLodDistance_ = frame.camera_->GetLodDistance(distance, scale, lodBias_);
  198. }
  199. if (animationDirty_ || animationOrderDirty_)
  200. UpdateAnimation(frame);
  201. else if (boneBoundingBoxDirty_)
  202. UpdateBoneBoundingBox();
  203. }
  204. void AnimatedModel::UpdateBatches(const FrameInfo& frame)
  205. {
  206. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  207. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  208. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  209. // Note: per-geometry distances do not take skinning into account. Especially in case of a ragdoll they may be
  210. // much off base if the node's own transform is not updated
  211. if (batches_.Size() == 1)
  212. batches_[0].distance_ = distance_;
  213. else
  214. {
  215. for (unsigned i = 0; i < batches_.Size(); ++i)
  216. batches_[i].distance_ = frame.camera_->GetDistance(worldTransform * geometryData_[i].center_);
  217. }
  218. // Use a transformed version of the model's bounding box instead of world bounding box for LOD scale
  219. // determination so that animation does not change the scale
  220. BoundingBox transformedBoundingBox = boundingBox_.Transformed(worldTransform);
  221. float scale = transformedBoundingBox.Size().DotProduct(DOT_SCALE);
  222. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  223. // If model is rendered from several views, use the minimum LOD distance for animation LOD
  224. if (frame.frameNumber_ != animationLodFrameNumber_)
  225. {
  226. animationLodDistance_ = newLodDistance;
  227. animationLodFrameNumber_ = frame.frameNumber_;
  228. }
  229. else
  230. animationLodDistance_ = Min(animationLodDistance_, newLodDistance);
  231. if (newLodDistance != lodDistance_)
  232. {
  233. lodDistance_ = newLodDistance;
  234. CalculateLodLevels();
  235. }
  236. }
  237. void AnimatedModel::UpdateGeometry(const FrameInfo& frame)
  238. {
  239. if (morphsDirty_)
  240. UpdateMorphs();
  241. if (skinningDirty_)
  242. UpdateSkinning();
  243. }
  244. UpdateGeometryType AnimatedModel::GetUpdateGeometryType()
  245. {
  246. if (morphsDirty_)
  247. return UPDATE_MAIN_THREAD;
  248. else if (skinningDirty_)
  249. return UPDATE_WORKER_THREAD;
  250. else
  251. return UPDATE_NONE;
  252. }
  253. void AnimatedModel::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  254. {
  255. if (debug && IsEnabledEffective())
  256. {
  257. debug->AddBoundingBox(GetWorldBoundingBox(), Color::GREEN, depthTest);
  258. debug->AddSkeleton(skeleton_, Color(0.75f, 0.75f, 0.75f), depthTest);
  259. }
  260. }
  261. void AnimatedModel::SetModel(Model* model, bool createBones)
  262. {
  263. if (model == model_)
  264. return;
  265. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  266. if (model_)
  267. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  268. model_ = model;
  269. if (model)
  270. {
  271. SubscribeToEvent(model, E_RELOADFINISHED, HANDLER(AnimatedModel, HandleModelReloadFinished));
  272. // Copy the subgeometry & LOD level structure
  273. SetNumGeometries(model->GetNumGeometries());
  274. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  275. const PODVector<Vector3>& geometryCenters = model->GetGeometryCenters();
  276. for (unsigned i = 0; i < geometries.Size(); ++i)
  277. {
  278. geometries_[i] = geometries[i];
  279. geometryData_[i].center_ = geometryCenters[i];
  280. }
  281. // Copy geometry bone mappings
  282. const Vector<PODVector<unsigned> >& geometryBoneMappings = model->GetGeometryBoneMappings();
  283. geometryBoneMappings_.Clear();
  284. geometryBoneMappings_.Reserve(geometryBoneMappings.Size());
  285. for (unsigned i = 0; i < geometryBoneMappings.Size(); ++i)
  286. geometryBoneMappings_.Push(geometryBoneMappings[i]);
  287. // Copy morphs. Note: morph vertex buffers will be created later on-demand
  288. morphVertexBuffers_.Clear();
  289. morphs_.Clear();
  290. const Vector<ModelMorph>& morphs = model->GetMorphs();
  291. morphs_.Reserve(morphs.Size());
  292. morphElementMask_ = 0;
  293. for (unsigned i = 0; i < morphs.Size(); ++i)
  294. {
  295. ModelMorph newMorph;
  296. newMorph.name_ = morphs[i].name_;
  297. newMorph.nameHash_ = morphs[i].nameHash_;
  298. newMorph.weight_ = 0.0f;
  299. newMorph.buffers_ = morphs[i].buffers_;
  300. for (HashMap<unsigned, VertexBufferMorph>::ConstIterator j = morphs[i].buffers_.Begin();
  301. j != morphs[i].buffers_.End(); ++j)
  302. morphElementMask_ |= j->second_.elementMask_;
  303. morphs_.Push(newMorph);
  304. }
  305. // Copy bounding box & skeleton
  306. SetBoundingBox(model->GetBoundingBox());
  307. // Initial bone bounding box is just the one stored in the model
  308. boneBoundingBox_ = boundingBox_;
  309. boneBoundingBoxDirty_ = true;
  310. SetSkeleton(model->GetSkeleton(), createBones);
  311. ResetLodLevels();
  312. // Enable skinning in batches
  313. for (unsigned i = 0; i < batches_.Size(); ++i)
  314. {
  315. if (skinMatrices_.Size())
  316. {
  317. batches_[i].geometryType_ = GEOM_SKINNED;
  318. // Check if model has per-geometry bone mappings
  319. if (geometrySkinMatrices_.Size() && geometrySkinMatrices_[i].Size())
  320. {
  321. batches_[i].worldTransform_ = &geometrySkinMatrices_[i][0];
  322. batches_[i].numWorldTransforms_ = geometrySkinMatrices_[i].Size();
  323. }
  324. // If not, use the global skin matrices
  325. else
  326. {
  327. batches_[i].worldTransform_ = &skinMatrices_[0];
  328. batches_[i].numWorldTransforms_ = skinMatrices_.Size();
  329. }
  330. }
  331. else
  332. {
  333. batches_[i].geometryType_ = GEOM_STATIC;
  334. batches_[i].worldTransform_ = &node_->GetWorldTransform();
  335. batches_[i].numWorldTransforms_ = 1;
  336. }
  337. }
  338. }
  339. else
  340. {
  341. RemoveRootBone(); // Remove existing root bone if any
  342. SetNumGeometries(0);
  343. geometryBoneMappings_.Clear();
  344. morphVertexBuffers_.Clear();
  345. morphs_.Clear();
  346. morphElementMask_ = 0;
  347. SetBoundingBox(BoundingBox());
  348. SetSkeleton(Skeleton(), false);
  349. }
  350. MarkNetworkUpdate();
  351. }
  352. AnimationState* AnimatedModel::AddAnimationState(Animation* animation)
  353. {
  354. if (!isMaster_)
  355. {
  356. LOGERROR("Can not add animation state to non-master model");
  357. return 0;
  358. }
  359. if (!animation || !skeleton_.GetNumBones())
  360. return 0;
  361. // Check for not adding twice
  362. AnimationState* existing = GetAnimationState(animation);
  363. if (existing)
  364. return existing;
  365. SharedPtr<AnimationState> newState(new AnimationState(this, animation));
  366. animationStates_.Push(newState);
  367. MarkAnimationOrderDirty();
  368. return newState;
  369. }
  370. void AnimatedModel::RemoveAnimationState(Animation* animation)
  371. {
  372. if (animation)
  373. RemoveAnimationState(animation->GetNameHash());
  374. else
  375. {
  376. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  377. {
  378. AnimationState* state = *i;
  379. if (!state->GetAnimation())
  380. {
  381. animationStates_.Erase(i);
  382. MarkAnimationDirty();
  383. return;
  384. }
  385. }
  386. }
  387. }
  388. void AnimatedModel::RemoveAnimationState(const String& animationName)
  389. {
  390. RemoveAnimationState(StringHash(animationName));
  391. }
  392. void AnimatedModel::RemoveAnimationState(StringHash animationNameHash)
  393. {
  394. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  395. {
  396. AnimationState* state = *i;
  397. Animation* animation = state->GetAnimation();
  398. if (animation)
  399. {
  400. // Check both the animation and the resource name
  401. if (animation->GetNameHash() == animationNameHash || animation->GetAnimationNameHash() == animationNameHash)
  402. {
  403. animationStates_.Erase(i);
  404. MarkAnimationDirty();
  405. return;
  406. }
  407. }
  408. }
  409. }
  410. void AnimatedModel::RemoveAnimationState(AnimationState* state)
  411. {
  412. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  413. {
  414. if (*i == state)
  415. {
  416. animationStates_.Erase(i);
  417. MarkAnimationDirty();
  418. return;
  419. }
  420. }
  421. }
  422. void AnimatedModel::RemoveAnimationState(unsigned index)
  423. {
  424. if (index < animationStates_.Size())
  425. {
  426. animationStates_.Erase(index);
  427. MarkAnimationDirty();
  428. }
  429. }
  430. void AnimatedModel::RemoveAllAnimationStates()
  431. {
  432. if (animationStates_.Size())
  433. {
  434. animationStates_.Clear();
  435. MarkAnimationDirty();
  436. }
  437. }
  438. void AnimatedModel::SetAnimationLodBias(float bias)
  439. {
  440. animationLodBias_ = Max(bias, 0.0f);
  441. MarkNetworkUpdate();
  442. }
  443. void AnimatedModel::SetUpdateInvisible(bool enable)
  444. {
  445. updateInvisible_ = enable;
  446. MarkNetworkUpdate();
  447. }
  448. void AnimatedModel::SetMorphWeight(unsigned index, float weight)
  449. {
  450. if (index >= morphs_.Size())
  451. return;
  452. // If morph vertex buffers have not been created yet, create now
  453. if (weight > 0.0f && morphVertexBuffers_.Empty())
  454. CloneGeometries();
  455. weight = Clamp(weight, 0.0f, 1.0f);
  456. if (weight != morphs_[index].weight_)
  457. {
  458. morphs_[index].weight_ = weight;
  459. // For a master model, set the same morph weight on non-master models
  460. if (isMaster_)
  461. {
  462. PODVector<AnimatedModel*> models;
  463. GetComponents<AnimatedModel>(models);
  464. // Indexing might not be the same, so use the name hash instead
  465. for (unsigned i = 1; i < models.Size(); ++i)
  466. {
  467. if (!models[i]->isMaster_)
  468. models[i]->SetMorphWeight(morphs_[index].nameHash_, weight);
  469. }
  470. }
  471. MarkMorphsDirty();
  472. MarkNetworkUpdate();
  473. }
  474. }
  475. void AnimatedModel::SetMorphWeight(const String& name, float weight)
  476. {
  477. for (unsigned i = 0; i < morphs_.Size(); ++i)
  478. {
  479. if (morphs_[i].name_ == name)
  480. {
  481. SetMorphWeight(i, weight);
  482. return;
  483. }
  484. }
  485. }
  486. void AnimatedModel::SetMorphWeight(StringHash nameHash, float weight)
  487. {
  488. for (unsigned i = 0; i < morphs_.Size(); ++i)
  489. {
  490. if (morphs_[i].nameHash_ == nameHash)
  491. {
  492. SetMorphWeight(i, weight);
  493. return;
  494. }
  495. }
  496. }
  497. void AnimatedModel::ResetMorphWeights()
  498. {
  499. for (Vector<ModelMorph>::Iterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  500. i->weight_ = 0.0f;
  501. // For a master model, reset weights on non-master models
  502. if (isMaster_)
  503. {
  504. PODVector<AnimatedModel*> models;
  505. GetComponents<AnimatedModel>(models);
  506. for (unsigned i = 1; i < models.Size(); ++i)
  507. {
  508. if (!models[i]->isMaster_)
  509. models[i]->ResetMorphWeights();
  510. }
  511. }
  512. MarkMorphsDirty();
  513. MarkNetworkUpdate();
  514. }
  515. float AnimatedModel::GetMorphWeight(unsigned index) const
  516. {
  517. return index < morphs_.Size() ? morphs_[index].weight_ : 0.0f;
  518. }
  519. float AnimatedModel::GetMorphWeight(const String& name) const
  520. {
  521. for (Vector<ModelMorph>::ConstIterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  522. {
  523. if (i->name_ == name)
  524. return i->weight_;
  525. }
  526. return 0.0f;
  527. }
  528. float AnimatedModel::GetMorphWeight(StringHash nameHash) const
  529. {
  530. for (Vector<ModelMorph>::ConstIterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  531. {
  532. if (i->nameHash_ == nameHash)
  533. return i->weight_;
  534. }
  535. return 0.0f;
  536. }
  537. AnimationState* AnimatedModel::GetAnimationState(Animation* animation) const
  538. {
  539. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  540. {
  541. if ((*i)->GetAnimation() == animation)
  542. return *i;
  543. }
  544. return 0;
  545. }
  546. AnimationState* AnimatedModel::GetAnimationState(const String& animationName) const
  547. {
  548. return GetAnimationState(StringHash(animationName));
  549. }
  550. AnimationState* AnimatedModel::GetAnimationState(StringHash animationNameHash) const
  551. {
  552. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  553. {
  554. Animation* animation = (*i)->GetAnimation();
  555. if (animation)
  556. {
  557. // Check both the animation and the resource name
  558. if (animation->GetNameHash() == animationNameHash || animation->GetAnimationNameHash() == animationNameHash)
  559. return *i;
  560. }
  561. }
  562. return 0;
  563. }
  564. AnimationState* AnimatedModel::GetAnimationState(unsigned index) const
  565. {
  566. return index < animationStates_.Size() ? animationStates_[index].Get() : 0;
  567. }
  568. void AnimatedModel::SetSkeleton(const Skeleton& skeleton, bool createBones)
  569. {
  570. if (!node_ && createBones)
  571. {
  572. LOGERROR("AnimatedModel not attached to a scene node, can not create bone nodes");
  573. return;
  574. }
  575. if (createBones && !boneCreationEnabled_)
  576. createBones = false;
  577. if (isMaster_)
  578. {
  579. // Check if bone structure has stayed compatible (reloading the model.) In that case retain the old bones and animations
  580. if (skeleton_.GetNumBones() == skeleton.GetNumBones())
  581. {
  582. Vector<Bone>& destBones = skeleton_.GetModifiableBones();
  583. const Vector<Bone>& srcBones = skeleton.GetBones();
  584. bool compatible = true;
  585. for (unsigned i = 0; i < destBones.Size(); ++i)
  586. {
  587. if (destBones[i].node_ && destBones[i].name_ == srcBones[i].name_ && destBones[i].parentIndex_ ==
  588. srcBones[i].parentIndex_)
  589. {
  590. // If compatible, just copy the values and retain the old node and animated status
  591. Node* boneNode = destBones[i].node_;
  592. bool animated = destBones[i].animated_;
  593. destBones[i] = srcBones[i];
  594. destBones[i].node_ = boneNode;
  595. destBones[i].animated_ = animated;
  596. }
  597. else
  598. {
  599. compatible = false;
  600. break;
  601. }
  602. }
  603. if (compatible)
  604. return;
  605. }
  606. RemoveAllAnimationStates();
  607. // Detach the rootbone of the previous model if any
  608. if (createBones)
  609. RemoveRootBone();
  610. skeleton_.Define(skeleton);
  611. // Remove collision information from dummy bones that do not affect skinning, to prevent them from being merged
  612. // to the bounding box
  613. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  614. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  615. {
  616. if (i->collisionMask_ & BONECOLLISION_BOX && i->boundingBox_.Size().Length() < M_EPSILON)
  617. i->collisionMask_ &= ~BONECOLLISION_BOX;
  618. if (i->collisionMask_ & BONECOLLISION_SPHERE && i->radius_ < M_EPSILON)
  619. i->collisionMask_ &= ~BONECOLLISION_SPHERE;
  620. }
  621. // Create scene nodes for the bones
  622. if (createBones)
  623. {
  624. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  625. {
  626. // Create bones as local, as they are never to be directly synchronized over the network
  627. Node* boneNode = node_->CreateChild(i->name_, LOCAL);
  628. boneNode->AddListener(this);
  629. boneNode->SetTransform(i->initialPosition_, i->initialRotation_, i->initialScale_);
  630. i->node_ = boneNode;
  631. }
  632. for (unsigned i = 0; i < bones.Size(); ++i)
  633. {
  634. unsigned parentIndex = bones[i].parentIndex_;
  635. if (parentIndex != i && parentIndex < bones.Size())
  636. bones[parentIndex].node_->AddChild(bones[i].node_);
  637. }
  638. }
  639. using namespace BoneHierarchyCreated;
  640. VariantMap& eventData = GetEventDataMap();
  641. eventData[P_NODE] = node_;
  642. node_->SendEvent(E_BONEHIERARCHYCREATED, eventData);
  643. }
  644. else
  645. {
  646. // For non-master models: use the bone nodes of the master model
  647. skeleton_.Define(skeleton);
  648. if (createBones)
  649. {
  650. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  651. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  652. {
  653. Node* boneNode = node_->GetChild(i->name_, true);
  654. if (boneNode)
  655. boneNode->AddListener(this);
  656. i->node_ = boneNode;
  657. }
  658. }
  659. }
  660. // Reserve space for skinning matrices
  661. skinMatrices_.Resize(skeleton_.GetNumBones());
  662. SetGeometryBoneMappings();
  663. assignBonesPending_ = !createBones;
  664. }
  665. void AnimatedModel::SetModelAttr(const ResourceRef& value)
  666. {
  667. ResourceCache* cache = GetSubsystem<ResourceCache>();
  668. // When loading a scene, set model without creating the bone nodes (will be assigned later during post-load)
  669. SetModel(cache->GetResource<Model>(value.name_), !loading_);
  670. }
  671. void AnimatedModel::SetBonesEnabledAttr(const VariantVector& value)
  672. {
  673. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  674. for (unsigned i = 0; i < bones.Size() && i < value.Size(); ++i)
  675. bones[i].animated_ = value[i].GetBool();
  676. }
  677. void AnimatedModel::SetAnimationStatesAttr(const VariantVector& value)
  678. {
  679. ResourceCache* cache = GetSubsystem<ResourceCache>();
  680. RemoveAllAnimationStates();
  681. unsigned index = 0;
  682. unsigned numStates = index < value.Size() ? value[index++].GetUInt() : 0;
  683. // Prevent negative or overly large value being assigned from the editor
  684. if (numStates > M_MAX_INT)
  685. numStates = 0;
  686. if (numStates > MAX_ANIMATION_STATES)
  687. numStates = MAX_ANIMATION_STATES;
  688. animationStates_.Reserve(numStates);
  689. while (numStates--)
  690. {
  691. if (index + 5 < value.Size())
  692. {
  693. // Note: null animation is allowed here for editing
  694. const ResourceRef& animRef = value[index++].GetResourceRef();
  695. SharedPtr<AnimationState> newState(new AnimationState(this, cache->GetResource<Animation>(animRef.name_)));
  696. animationStates_.Push(newState);
  697. newState->SetStartBone(skeleton_.GetBone(value[index++].GetString()));
  698. newState->SetLooped(value[index++].GetBool());
  699. newState->SetWeight(value[index++].GetFloat());
  700. newState->SetTime(value[index++].GetFloat());
  701. newState->SetLayer((unsigned char)value[index++].GetInt());
  702. }
  703. else
  704. {
  705. // If not enough data, just add an empty animation state
  706. SharedPtr<AnimationState> newState(new AnimationState(this, 0));
  707. animationStates_.Push(newState);
  708. }
  709. }
  710. if (animationStates_.Size())
  711. {
  712. MarkAnimationDirty();
  713. MarkAnimationOrderDirty();
  714. }
  715. }
  716. void AnimatedModel::SetMorphsAttr(const PODVector<unsigned char>& value)
  717. {
  718. for (unsigned index = 0; index < value.Size(); ++index)
  719. SetMorphWeight(index, (float)value[index] / 255.0f);
  720. }
  721. ResourceRef AnimatedModel::GetModelAttr() const
  722. {
  723. return GetResourceRef(model_, Model::GetTypeStatic());
  724. }
  725. VariantVector AnimatedModel::GetBonesEnabledAttr() const
  726. {
  727. VariantVector ret;
  728. const Vector<Bone>& bones = skeleton_.GetBones();
  729. ret.Reserve(bones.Size());
  730. for (Vector<Bone>::ConstIterator i = bones.Begin(); i != bones.End(); ++i)
  731. ret.Push(i->animated_);
  732. return ret;
  733. }
  734. VariantVector AnimatedModel::GetAnimationStatesAttr() const
  735. {
  736. VariantVector ret;
  737. ret.Reserve(animationStates_.Size() * 6 + 1);
  738. ret.Push(animationStates_.Size());
  739. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  740. {
  741. AnimationState* state = *i;
  742. Animation* animation = state->GetAnimation();
  743. Bone* startBone = state->GetStartBone();
  744. ret.Push(GetResourceRef(animation, Animation::GetTypeStatic()));
  745. ret.Push(startBone ? startBone->name_ : String::EMPTY);
  746. ret.Push(state->IsLooped());
  747. ret.Push(state->GetWeight());
  748. ret.Push(state->GetTime());
  749. ret.Push((int)state->GetLayer());
  750. }
  751. return ret;
  752. }
  753. const PODVector<unsigned char>& AnimatedModel::GetMorphsAttr() const
  754. {
  755. attrBuffer_.Clear();
  756. for (Vector<ModelMorph>::ConstIterator i = morphs_.Begin(); i != morphs_.End(); ++i)
  757. attrBuffer_.WriteUByte((unsigned char)(i->weight_ * 255.0f));
  758. return attrBuffer_.GetBuffer();
  759. }
  760. void AnimatedModel::OnNodeSet(Node* node)
  761. {
  762. Drawable::OnNodeSet(node);
  763. if (node)
  764. {
  765. // If this AnimatedModel is the first in the node, it is the master which controls animation & morphs
  766. isMaster_ = GetComponent<AnimatedModel>() == this;
  767. }
  768. }
  769. void AnimatedModel::OnMarkedDirty(Node* node)
  770. {
  771. Drawable::OnMarkedDirty(node);
  772. // If the scene node or any of the bone nodes move, mark skinning and the bone bounding box dirty
  773. if (skeleton_.GetNumBones())
  774. {
  775. skinningDirty_ = true;
  776. boneBoundingBoxDirty_ = true;
  777. }
  778. }
  779. void AnimatedModel::OnWorldBoundingBoxUpdate()
  780. {
  781. if (isMaster_)
  782. {
  783. // Note: do not update bone bounding box here, instead do it in either of the threaded updates
  784. worldBoundingBox_ = boneBoundingBox_.Transformed(node_->GetWorldTransform());
  785. }
  786. else
  787. {
  788. // Non-master animated models get the bounding box from the master
  789. /// \todo If it's a skinned attachment that does not cover the whole body, it will have unnecessarily large bounds
  790. AnimatedModel* master = node_->GetComponent<AnimatedModel>();
  791. // Check if we've become the new master model in case the original was deleted
  792. if (master == this)
  793. isMaster_ = true;
  794. if (master)
  795. worldBoundingBox_ = master->GetWorldBoundingBox();
  796. }
  797. }
  798. void AnimatedModel::AssignBoneNodes()
  799. {
  800. assignBonesPending_ = false;
  801. if (!node_ || !boneCreationEnabled_)
  802. return;
  803. // Find the bone nodes from the node hierarchy and add listeners
  804. Vector<Bone>& bones = skeleton_.GetModifiableBones();
  805. bool boneFound = false;
  806. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  807. {
  808. Node* boneNode = node_->GetChild(i->name_, true);
  809. if (boneNode)
  810. {
  811. boneFound = true;
  812. boneNode->AddListener(this);
  813. }
  814. i->node_ = boneNode;
  815. }
  816. // If no bones found, this may be a prefab where the bone information was left out.
  817. // In that case reassign the skeleton now if possible
  818. if (!boneFound && model_)
  819. {
  820. // ATOMIC: instead of calling SetSkeleton which does significant initialization
  821. // create the bone nodes here (which also avoids a bone init issue)
  822. // SetSkeleton(model_->GetSkeleton(), true);
  823. for (Vector<Bone>::Iterator i = bones.Begin(); i != bones.End(); ++i)
  824. {
  825. // Create bones as local, as they are never to be directly synchronized over the network
  826. Node* boneNode = node_->CreateChild(i->name_, LOCAL);
  827. boneNode->AddListener(this);
  828. boneNode->SetTransform(i->initialPosition_, i->initialRotation_, i->initialScale_);
  829. i->node_ = boneNode;
  830. }
  831. for (unsigned i = 0; i < bones.Size(); ++i)
  832. {
  833. unsigned parentIndex = bones[i].parentIndex_;
  834. if (parentIndex != i && parentIndex < bones.Size())
  835. bones[parentIndex].node_->AddChild(bones[i].node_);
  836. }
  837. }
  838. // Re-assign the same start bone to animations to get the proper bone node this time
  839. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  840. {
  841. AnimationState* state = *i;
  842. state->SetStartBone(state->GetStartBone());
  843. }
  844. }
  845. void AnimatedModel::RemoveRootBone()
  846. {
  847. Bone* rootBone = skeleton_.GetRootBone();
  848. if (rootBone && rootBone->node_)
  849. rootBone->node_->Remove();
  850. }
  851. void AnimatedModel::MarkAnimationDirty()
  852. {
  853. if (isMaster_)
  854. {
  855. animationDirty_ = true;
  856. MarkForUpdate();
  857. }
  858. }
  859. void AnimatedModel::MarkAnimationOrderDirty()
  860. {
  861. if (isMaster_)
  862. {
  863. animationOrderDirty_ = true;
  864. MarkForUpdate();
  865. }
  866. }
  867. void AnimatedModel::MarkMorphsDirty()
  868. {
  869. morphsDirty_ = true;
  870. }
  871. void AnimatedModel::CloneGeometries()
  872. {
  873. const Vector<SharedPtr<VertexBuffer> >& originalVertexBuffers = model_->GetVertexBuffers();
  874. HashMap<VertexBuffer*, SharedPtr<VertexBuffer> > clonedVertexBuffers;
  875. morphVertexBuffers_.Resize(originalVertexBuffers.Size());
  876. for (unsigned i = 0; i < originalVertexBuffers.Size(); ++i)
  877. {
  878. VertexBuffer* original = originalVertexBuffers[i];
  879. if (model_->GetMorphRangeCount(i))
  880. {
  881. SharedPtr<VertexBuffer> clone(new VertexBuffer(context_));
  882. clone->SetShadowed(true);
  883. clone->SetSize(original->GetVertexCount(), morphElementMask_ & original->GetElementMask(), true);
  884. void* dest = clone->Lock(0, original->GetVertexCount());
  885. if (dest)
  886. {
  887. CopyMorphVertices(dest, original->GetShadowData(), original->GetVertexCount(), clone, original);
  888. clone->Unlock();
  889. }
  890. clonedVertexBuffers[original] = clone;
  891. morphVertexBuffers_[i] = clone;
  892. }
  893. else
  894. morphVertexBuffers_[i].Reset();
  895. }
  896. // Geometries will always be cloned fully. They contain only references to buffer, so they are relatively light
  897. for (unsigned i = 0; i < geometries_.Size(); ++i)
  898. {
  899. for (unsigned j = 0; j < geometries_[i].Size(); ++j)
  900. {
  901. SharedPtr<Geometry> original = geometries_[i][j];
  902. SharedPtr<Geometry> clone(new Geometry(context_));
  903. // Add an additional vertex stream into the clone, which supplies only the morphable vertex data, while the static
  904. // data comes from the original vertex buffer(s)
  905. const Vector<SharedPtr<VertexBuffer> >& originalBuffers = original->GetVertexBuffers();
  906. unsigned totalBuf = originalBuffers.Size();
  907. for (unsigned k = 0; k < originalBuffers.Size(); ++k)
  908. {
  909. VertexBuffer* originalBuffer = originalBuffers[k];
  910. if (clonedVertexBuffers.Contains(originalBuffer))
  911. ++totalBuf;
  912. }
  913. clone->SetNumVertexBuffers(totalBuf);
  914. unsigned l = 0;
  915. for (unsigned k = 0; k < originalBuffers.Size(); ++k)
  916. {
  917. VertexBuffer* originalBuffer = originalBuffers[k];
  918. unsigned originalMask = original->GetVertexElementMask(k);
  919. if (clonedVertexBuffers.Contains(originalBuffer))
  920. {
  921. VertexBuffer* clonedBuffer = clonedVertexBuffers[originalBuffer];
  922. clone->SetVertexBuffer(l++, originalBuffer, originalMask & ~clonedBuffer->GetElementMask());
  923. clone->SetVertexBuffer(l++, clonedBuffer, originalMask & clonedBuffer->GetElementMask());
  924. }
  925. else
  926. clone->SetVertexBuffer(l++, originalBuffer, originalMask);
  927. }
  928. clone->SetIndexBuffer(original->GetIndexBuffer());
  929. clone->SetDrawRange(original->GetPrimitiveType(), original->GetIndexStart(), original->GetIndexCount());
  930. clone->SetLodDistance(original->GetLodDistance());
  931. geometries_[i][j] = clone;
  932. }
  933. }
  934. // Make sure the rendering batches use the new cloned geometries
  935. ResetLodLevels();
  936. MarkMorphsDirty();
  937. }
  938. void AnimatedModel::CopyMorphVertices(void* destVertexData, void* srcVertexData, unsigned vertexCount, VertexBuffer* destBuffer,
  939. VertexBuffer* srcBuffer)
  940. {
  941. unsigned mask = destBuffer->GetElementMask() & srcBuffer->GetElementMask();
  942. unsigned normalOffset = srcBuffer->GetElementOffset(ELEMENT_NORMAL);
  943. unsigned tangentOffset = srcBuffer->GetElementOffset(ELEMENT_TANGENT);
  944. unsigned vertexSize = srcBuffer->GetVertexSize();
  945. float* dest = (float*)destVertexData;
  946. unsigned char* src = (unsigned char*)srcVertexData;
  947. while (vertexCount--)
  948. {
  949. if (mask & MASK_POSITION)
  950. {
  951. float* posSrc = (float*)src;
  952. dest[0] = posSrc[0];
  953. dest[1] = posSrc[1];
  954. dest[2] = posSrc[2];
  955. dest += 3;
  956. }
  957. if (mask & MASK_NORMAL)
  958. {
  959. float* normalSrc = (float*)(src + normalOffset);
  960. dest[0] = normalSrc[0];
  961. dest[1] = normalSrc[1];
  962. dest[2] = normalSrc[2];
  963. dest += 3;
  964. }
  965. if (mask & MASK_TANGENT)
  966. {
  967. float* tangentSrc = (float*)(src + tangentOffset);
  968. dest[0] = tangentSrc[0];
  969. dest[1] = tangentSrc[1];
  970. dest[2] = tangentSrc[2];
  971. dest[3] = tangentSrc[3];
  972. dest += 4;
  973. }
  974. src += vertexSize;
  975. }
  976. }
  977. void AnimatedModel::SetGeometryBoneMappings()
  978. {
  979. geometrySkinMatrices_.Clear();
  980. geometrySkinMatrixPtrs_.Clear();
  981. if (!geometryBoneMappings_.Size())
  982. return;
  983. // Check if all mappings are empty, then we do not need to use mapped skinning
  984. bool allEmpty = true;
  985. for (unsigned i = 0; i < geometryBoneMappings_.Size(); ++i)
  986. if (geometryBoneMappings_[i].Size())
  987. allEmpty = false;
  988. if (allEmpty)
  989. return;
  990. // Reserve space for per-geometry skinning matrices
  991. geometrySkinMatrices_.Resize(geometryBoneMappings_.Size());
  992. for (unsigned i = 0; i < geometryBoneMappings_.Size(); ++i)
  993. geometrySkinMatrices_[i].Resize(geometryBoneMappings_[i].Size());
  994. // Build original-to-skinindex matrix pointer mapping for fast copying
  995. // Note: at this point layout of geometrySkinMatrices_ cannot be modified or pointers become invalid
  996. geometrySkinMatrixPtrs_.Resize(skeleton_.GetNumBones());
  997. for (unsigned i = 0; i < geometryBoneMappings_.Size(); ++i)
  998. {
  999. for (unsigned j = 0; j < geometryBoneMappings_[i].Size(); ++j)
  1000. geometrySkinMatrixPtrs_[geometryBoneMappings_[i][j]].Push(&geometrySkinMatrices_[i][j]);
  1001. }
  1002. }
  1003. void AnimatedModel::UpdateAnimation(const FrameInfo& frame)
  1004. {
  1005. // If using animation LOD, accumulate time and see if it is time to update
  1006. if (animationLodBias_ > 0.0f && animationLodDistance_ > 0.0f)
  1007. {
  1008. // Check for first time update
  1009. if (animationLodTimer_ >= 0.0f)
  1010. {
  1011. animationLodTimer_ += animationLodBias_ * frame.timeStep_ * ANIMATION_LOD_BASESCALE;
  1012. if (animationLodTimer_ >= animationLodDistance_)
  1013. animationLodTimer_ = fmodf(animationLodTimer_, animationLodDistance_);
  1014. else
  1015. return;
  1016. }
  1017. else
  1018. animationLodTimer_ = 0.0f;
  1019. }
  1020. // Make sure animations are in ascending priority order
  1021. if (animationOrderDirty_)
  1022. {
  1023. Sort(animationStates_.Begin(), animationStates_.End(), CompareAnimationOrder);
  1024. animationOrderDirty_ = false;
  1025. }
  1026. // Reset skeleton, apply all animations, calculate bones' bounding box. Make sure this is only done for the master model
  1027. // (first AnimatedModel in a node)
  1028. if (isMaster_)
  1029. {
  1030. skeleton_.ResetSilent();
  1031. for (Vector<SharedPtr<AnimationState> >::Iterator i = animationStates_.Begin(); i != animationStates_.End(); ++i)
  1032. (*i)->Apply();
  1033. // Skeleton reset and animations apply the node transforms "silently" to avoid repeated marking dirty. Mark dirty now
  1034. node_->MarkDirty();
  1035. // Calculate new bone bounding box
  1036. UpdateBoneBoundingBox();
  1037. }
  1038. animationDirty_ = false;
  1039. }
  1040. void AnimatedModel::UpdateBoneBoundingBox()
  1041. {
  1042. if (skeleton_.GetNumBones())
  1043. {
  1044. // The bone bounding box is in local space, so need the node's inverse transform
  1045. boneBoundingBox_.defined_ = false;
  1046. Matrix3x4 inverseNodeTransform = node_->GetWorldTransform().Inverse();
  1047. const Vector<Bone>& bones = skeleton_.GetBones();
  1048. for (Vector<Bone>::ConstIterator i = bones.Begin(); i != bones.End(); ++i)
  1049. {
  1050. Node* boneNode = i->node_;
  1051. if (!boneNode)
  1052. continue;
  1053. // Use hitbox if available. If not, use only half of the sphere radius
  1054. /// \todo The sphere radius should be multiplied with bone scale
  1055. if (i->collisionMask_ & BONECOLLISION_BOX)
  1056. boneBoundingBox_.Merge(i->boundingBox_.Transformed(inverseNodeTransform * boneNode->GetWorldTransform()));
  1057. else if (i->collisionMask_ & BONECOLLISION_SPHERE)
  1058. boneBoundingBox_.Merge(Sphere(inverseNodeTransform * boneNode->GetWorldPosition(), i->radius_ * 0.5f));
  1059. }
  1060. }
  1061. boneBoundingBoxDirty_ = false;
  1062. worldBoundingBoxDirty_ = true;
  1063. }
  1064. void AnimatedModel::UpdateSkinning()
  1065. {
  1066. // Note: the model's world transform will be baked in the skin matrices
  1067. const Vector<Bone>& bones = skeleton_.GetBones();
  1068. // Use model's world transform in case a bone is missing
  1069. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  1070. // Skinning with global matrices only
  1071. if (!geometrySkinMatrices_.Size())
  1072. {
  1073. for (unsigned i = 0; i < bones.Size(); ++i)
  1074. {
  1075. const Bone& bone = bones[i];
  1076. if (bone.node_)
  1077. skinMatrices_[i] = bone.node_->GetWorldTransform() * bone.offsetMatrix_;
  1078. else
  1079. skinMatrices_[i] = worldTransform;
  1080. }
  1081. }
  1082. // Skinning with per-geometry matrices
  1083. else
  1084. {
  1085. for (unsigned i = 0; i < bones.Size(); ++i)
  1086. {
  1087. const Bone& bone = bones[i];
  1088. if (bone.node_)
  1089. skinMatrices_[i] = bone.node_->GetWorldTransform() * bone.offsetMatrix_;
  1090. else
  1091. skinMatrices_[i] = worldTransform;
  1092. // Copy the skin matrix to per-geometry matrices as needed
  1093. for (unsigned j = 0; j < geometrySkinMatrixPtrs_[i].Size(); ++j)
  1094. *geometrySkinMatrixPtrs_[i][j] = skinMatrices_[i];
  1095. }
  1096. }
  1097. skinningDirty_ = false;
  1098. }
  1099. void AnimatedModel::UpdateMorphs()
  1100. {
  1101. Graphics* graphics = GetSubsystem<Graphics>();
  1102. if (!graphics)
  1103. return;
  1104. if (morphs_.Size())
  1105. {
  1106. // Reset the morph data range from all morphable vertex buffers, then apply morphs
  1107. for (unsigned i = 0; i < morphVertexBuffers_.Size(); ++i)
  1108. {
  1109. VertexBuffer* buffer = morphVertexBuffers_[i];
  1110. if (buffer)
  1111. {
  1112. VertexBuffer* originalBuffer = model_->GetVertexBuffers()[i];
  1113. unsigned morphStart = model_->GetMorphRangeStart(i);
  1114. unsigned morphCount = model_->GetMorphRangeCount(i);
  1115. void* dest = buffer->Lock(morphStart, morphCount);
  1116. if (dest)
  1117. {
  1118. // Reset morph range by copying data from the original vertex buffer
  1119. CopyMorphVertices(dest, originalBuffer->GetShadowData() + morphStart * originalBuffer->GetVertexSize(),
  1120. morphCount, buffer, originalBuffer);
  1121. for (unsigned j = 0; j < morphs_.Size(); ++j)
  1122. {
  1123. if (morphs_[j].weight_ > 0.0f)
  1124. {
  1125. HashMap<unsigned, VertexBufferMorph>::Iterator k = morphs_[j].buffers_.Find(i);
  1126. if (k != morphs_[j].buffers_.End())
  1127. ApplyMorph(buffer, dest, morphStart, k->second_, morphs_[j].weight_);
  1128. }
  1129. }
  1130. buffer->Unlock();
  1131. }
  1132. }
  1133. }
  1134. }
  1135. morphsDirty_ = false;
  1136. }
  1137. void AnimatedModel::ApplyMorph(VertexBuffer* buffer, void* destVertexData, unsigned morphRangeStart, const VertexBufferMorph& morph,
  1138. float weight)
  1139. {
  1140. unsigned elementMask = morph.elementMask_ & buffer->GetElementMask();
  1141. unsigned vertexCount = morph.vertexCount_;
  1142. unsigned normalOffset = buffer->GetElementOffset(ELEMENT_NORMAL);
  1143. unsigned tangentOffset = buffer->GetElementOffset(ELEMENT_TANGENT);
  1144. unsigned vertexSize = buffer->GetVertexSize();
  1145. unsigned char* srcData = morph.morphData_;
  1146. unsigned char* destData = (unsigned char*)destVertexData;
  1147. while (vertexCount--)
  1148. {
  1149. unsigned vertexIndex = *((unsigned*)srcData) - morphRangeStart;
  1150. srcData += sizeof(unsigned);
  1151. if (elementMask & MASK_POSITION)
  1152. {
  1153. float* dest = (float*)(destData + vertexIndex * vertexSize);
  1154. float* src = (float*)srcData;
  1155. dest[0] += src[0] * weight;
  1156. dest[1] += src[1] * weight;
  1157. dest[2] += src[2] * weight;
  1158. srcData += 3 * sizeof(float);
  1159. }
  1160. if (elementMask & MASK_NORMAL)
  1161. {
  1162. float* dest = (float*)(destData + vertexIndex * vertexSize + normalOffset);
  1163. float* src = (float*)srcData;
  1164. dest[0] += src[0] * weight;
  1165. dest[1] += src[1] * weight;
  1166. dest[2] += src[2] * weight;
  1167. srcData += 3 * sizeof(float);
  1168. }
  1169. if (elementMask & MASK_TANGENT)
  1170. {
  1171. float* dest = (float*)(destData + vertexIndex * vertexSize + tangentOffset);
  1172. float* src = (float*)srcData;
  1173. dest[0] += src[0] * weight;
  1174. dest[1] += src[1] * weight;
  1175. dest[2] += src[2] * weight;
  1176. srcData += 3 * sizeof(float);
  1177. }
  1178. }
  1179. }
  1180. void AnimatedModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  1181. {
  1182. Model* currentModel = model_;
  1183. model_.Reset(); // Set null to allow to be re-set
  1184. SetModel(currentModel);
  1185. }
  1186. void AnimatedModel::SetBoneCreationEnabled(bool enabled)
  1187. {
  1188. boneCreationEnabled_ = enabled;
  1189. }
  1190. }