AnimatedModel.cpp 52 KB

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