AnimatedModel.cpp 49 KB

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