AnimatedModel.cpp 37 KB

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