AnimatedModel.cpp 43 KB

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