AnimatedModel.cpp 44 KB

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