AnimatedModel.cpp 44 KB

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