AnimatedModel.cpp 49 KB

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