AnimatedModel.cpp 52 KB

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