AnimatedModel.cpp 44 KB

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