AnimatedModel.cpp 40 KB

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