AnimatedModel.cpp 45 KB

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