AnimatedModel.cpp 45 KB

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