AnimatedModel.cpp 53 KB

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