AnimatedModel.cpp 43 KB

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