AnimatedModel.cpp 45 KB

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