AnimatedModel.cpp 44 KB

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