AnimatedModel.cpp 35 KB

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