AnimatedModel.cpp 47 KB

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