AnimatedModel.cpp 35 KB

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