AnimatedModel.cpp 46 KB

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