AnimatedModel.cpp 47 KB

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