DecalSet.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/AnimatedModel.h"
  26. #include "../Graphics/Batch.h"
  27. #include "../Graphics/Camera.h"
  28. #include "../Graphics/DecalSet.h"
  29. #include "../Graphics/Geometry.h"
  30. #include "../Graphics/Graphics.h"
  31. #include "../Graphics/IndexBuffer.h"
  32. #include "../Graphics/Material.h"
  33. #include "../Graphics/Tangent.h"
  34. #include "../Graphics/VertexBuffer.h"
  35. #include "../IO/Log.h"
  36. #include "../IO/MemoryBuffer.h"
  37. #include "../Resource/ResourceCache.h"
  38. #include "../Scene/Scene.h"
  39. #include "../Scene/SceneEvents.h"
  40. #include "../DebugNew.h"
  41. #ifdef _MSC_VER
  42. #pragma warning(disable:6293)
  43. #endif
  44. namespace Atomic
  45. {
  46. extern const char* GEOMETRY_CATEGORY;
  47. static const unsigned MIN_VERTICES = 4;
  48. static const unsigned MIN_INDICES = 6;
  49. static const unsigned MAX_VERTICES = 65536;
  50. static const unsigned DEFAULT_MAX_VERTICES = 512;
  51. static const unsigned DEFAULT_MAX_INDICES = 1024;
  52. static const unsigned STATIC_ELEMENT_MASK = MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT;
  53. static const unsigned SKINNED_ELEMENT_MASK = MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT | MASK_BLENDWEIGHTS |
  54. MASK_BLENDINDICES;
  55. static DecalVertex ClipEdge(const DecalVertex& v0, const DecalVertex& v1, float d0, float d1, bool skinned)
  56. {
  57. DecalVertex ret;
  58. float t = d0 / (d0 - d1);
  59. ret.position_ = v0.position_ + t * (v1.position_ - v0.position_);
  60. ret.normal_ = v0.normal_ + t * (v1.normal_ - v0.normal_);
  61. if (skinned)
  62. {
  63. if (*((unsigned*)v0.blendIndices_) != *((unsigned*)v1.blendIndices_))
  64. {
  65. // Blend weights and indices: if indices are different, choose the vertex nearer to the split plane
  66. const DecalVertex& src = Abs(d0) < Abs(d1) ? v0 : v1;
  67. for (unsigned i = 0; i < 4; ++i)
  68. {
  69. ret.blendWeights_[i] = src.blendWeights_[i];
  70. ret.blendIndices_[i] = src.blendIndices_[i];
  71. }
  72. }
  73. else
  74. {
  75. // If indices are same, can interpolate the weights
  76. for (unsigned i = 0; i < 4; ++i)
  77. {
  78. ret.blendWeights_[i] = v0.blendWeights_[i] + t * (v1.blendWeights_[i] - v0.blendWeights_[i]);
  79. ret.blendIndices_[i] = v0.blendIndices_[i];
  80. }
  81. }
  82. }
  83. return ret;
  84. }
  85. static void ClipPolygon(PODVector<DecalVertex>& dest, const PODVector<DecalVertex>& src, const Plane& plane, bool skinned)
  86. {
  87. unsigned last = 0;
  88. float lastDistance = 0.0f;
  89. dest.Clear();
  90. if (src.Empty())
  91. return;
  92. for (unsigned i = 0; i < src.Size(); ++i)
  93. {
  94. float distance = plane.Distance(src[i].position_);
  95. if (distance >= 0.0f)
  96. {
  97. if (lastDistance < 0.0f)
  98. dest.Push(ClipEdge(src[last], src[i], lastDistance, distance, skinned));
  99. dest.Push(src[i]);
  100. }
  101. else
  102. {
  103. if (lastDistance >= 0.0f && i != 0)
  104. dest.Push(ClipEdge(src[last], src[i], lastDistance, distance, skinned));
  105. }
  106. last = i;
  107. lastDistance = distance;
  108. }
  109. // Recheck the distances of the last and first vertices and add the final clipped vertex if applicable
  110. float distance = plane.Distance(src[0].position_);
  111. if ((lastDistance < 0.0f && distance >= 0.0f) || (lastDistance >= 0.0f && distance < 0.0f))
  112. dest.Push(ClipEdge(src[last], src[0], lastDistance, distance, skinned));
  113. }
  114. void Decal::AddVertex(const DecalVertex& vertex)
  115. {
  116. for (unsigned i = 0; i < vertices_.Size(); ++i)
  117. {
  118. if (vertex.position_.Equals(vertices_[i].position_) && vertex.normal_.Equals(vertices_[i].normal_))
  119. {
  120. indices_.Push((unsigned short)i);
  121. return;
  122. }
  123. }
  124. unsigned short newIndex = (unsigned short)vertices_.Size();
  125. vertices_.Push(vertex);
  126. indices_.Push(newIndex);
  127. }
  128. void Decal::CalculateBoundingBox()
  129. {
  130. boundingBox_.Clear();
  131. for (unsigned i = 0; i < vertices_.Size(); ++i)
  132. boundingBox_.Merge(vertices_[i].position_);
  133. }
  134. DecalSet::DecalSet(Context* context) :
  135. Drawable(context, DRAWABLE_GEOMETRY),
  136. geometry_(new Geometry(context)),
  137. vertexBuffer_(new VertexBuffer(context_)),
  138. indexBuffer_(new IndexBuffer(context_)),
  139. numVertices_(0),
  140. numIndices_(0),
  141. maxVertices_(DEFAULT_MAX_VERTICES),
  142. maxIndices_(DEFAULT_MAX_INDICES),
  143. optimizeBufferSize_(false),
  144. skinned_(false),
  145. bufferDirty_(true),
  146. boundingBoxDirty_(true),
  147. skinningDirty_(false),
  148. assignBonesPending_(false),
  149. subscribed_(false)
  150. {
  151. geometry_->SetIndexBuffer(indexBuffer_);
  152. batches_.Resize(1);
  153. batches_[0].geometry_ = geometry_;
  154. batches_[0].geometryType_ = GEOM_STATIC_NOINSTANCING;
  155. }
  156. DecalSet::~DecalSet()
  157. {
  158. }
  159. void DecalSet::RegisterObject(Context* context)
  160. {
  161. context->RegisterFactory<DecalSet>(GEOMETRY_CATEGORY);
  162. ATOMIC_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  163. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()),
  164. AM_DEFAULT);
  165. ATOMIC_ACCESSOR_ATTRIBUTE("Max Vertices", GetMaxVertices, SetMaxVertices, unsigned, DEFAULT_MAX_VERTICES, AM_DEFAULT);
  166. ATOMIC_ACCESSOR_ATTRIBUTE("Max Indices", GetMaxIndices, SetMaxIndices, unsigned, DEFAULT_MAX_INDICES, AM_DEFAULT);
  167. ATOMIC_ACCESSOR_ATTRIBUTE("Optimize Buffer Size", GetOptimizeBufferSize, SetOptimizeBufferSize, bool, false, AM_DEFAULT);
  168. ATOMIC_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  169. ATOMIC_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  170. ATOMIC_COPY_BASE_ATTRIBUTES(Drawable);
  171. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Decals", GetDecalsAttr, SetDecalsAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  172. AM_FILE | AM_NOEDIT);
  173. }
  174. void DecalSet::ApplyAttributes()
  175. {
  176. if (assignBonesPending_)
  177. AssignBoneNodes();
  178. }
  179. void DecalSet::OnSetEnabled()
  180. {
  181. Drawable::OnSetEnabled();
  182. UpdateEventSubscription(true);
  183. }
  184. void DecalSet::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  185. {
  186. // Do not return raycast hits
  187. }
  188. void DecalSet::UpdateBatches(const FrameInfo& frame)
  189. {
  190. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  191. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  192. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  193. float scale = worldBoundingBox.Size().DotProduct(DOT_SCALE);
  194. lodDistance_ = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  195. batches_[0].distance_ = distance_;
  196. if (!skinned_)
  197. batches_[0].worldTransform_ = &worldTransform;
  198. }
  199. void DecalSet::UpdateGeometry(const FrameInfo& frame)
  200. {
  201. if (bufferDirty_ || vertexBuffer_->IsDataLost() || indexBuffer_->IsDataLost())
  202. UpdateBuffers();
  203. if (skinningDirty_)
  204. UpdateSkinning();
  205. }
  206. UpdateGeometryType DecalSet::GetUpdateGeometryType()
  207. {
  208. if (bufferDirty_ || vertexBuffer_->IsDataLost() || indexBuffer_->IsDataLost())
  209. return UPDATE_MAIN_THREAD;
  210. else if (skinningDirty_)
  211. return UPDATE_WORKER_THREAD;
  212. else
  213. return UPDATE_NONE;
  214. }
  215. void DecalSet::SetMaterial(Material* material)
  216. {
  217. batches_[0].material_ = material;
  218. MarkNetworkUpdate();
  219. }
  220. void DecalSet::SetMaxVertices(unsigned num)
  221. {
  222. // Never expand to 32 bit indices
  223. num = (unsigned)Clamp(num, MIN_VERTICES, MAX_VERTICES);
  224. if (num != maxVertices_)
  225. {
  226. if (!optimizeBufferSize_)
  227. bufferDirty_ = true;
  228. maxVertices_ = num;
  229. while (decals_.Size() && numVertices_ > maxVertices_)
  230. RemoveDecals(1);
  231. MarkNetworkUpdate();
  232. }
  233. }
  234. void DecalSet::SetMaxIndices(unsigned num)
  235. {
  236. if (num < MIN_INDICES)
  237. num = MIN_INDICES;
  238. if (num != maxIndices_)
  239. {
  240. if (!optimizeBufferSize_)
  241. bufferDirty_ = true;
  242. maxIndices_ = num;
  243. while (decals_.Size() && numIndices_ > maxIndices_)
  244. RemoveDecals(1);
  245. MarkNetworkUpdate();
  246. }
  247. }
  248. void DecalSet::SetOptimizeBufferSize(bool enable)
  249. {
  250. if (enable != optimizeBufferSize_)
  251. {
  252. optimizeBufferSize_ = enable;
  253. bufferDirty_ = true;
  254. MarkNetworkUpdate();
  255. }
  256. }
  257. bool DecalSet::AddDecal(Drawable* target, const Vector3& worldPosition, const Quaternion& worldRotation, float size,
  258. float aspectRatio, float depth, const Vector2& topLeftUV, const Vector2& bottomRightUV, float timeToLive, float normalCutoff,
  259. unsigned subGeometry)
  260. {
  261. ATOMIC_PROFILE(AddDecal);
  262. // Do not add decals in headless mode
  263. if (!node_ || !GetSubsystem<Graphics>())
  264. return false;
  265. if (!target || !target->GetNode())
  266. {
  267. ATOMIC_LOGERROR("Null target drawable for decal");
  268. return false;
  269. }
  270. // Check for animated target and switch into skinned/static mode if necessary
  271. AnimatedModel* animatedModel = dynamic_cast<AnimatedModel*>(target);
  272. if ((animatedModel && !skinned_) || (!animatedModel && skinned_))
  273. {
  274. RemoveAllDecals();
  275. skinned_ = animatedModel != 0;
  276. bufferDirty_ = true;
  277. }
  278. // Center the decal frustum on the world position
  279. Vector3 adjustedWorldPosition = worldPosition - 0.5f * depth * (worldRotation * Vector3::FORWARD);
  280. /// \todo target transform is not right if adding a decal to StaticModelGroup
  281. Matrix3x4 targetTransform = target->GetNode()->GetWorldTransform().Inverse();
  282. // For an animated model, adjust the decal position back to the bind pose
  283. // To do this, need to find the bone the decal is colliding with
  284. if (animatedModel)
  285. {
  286. Skeleton& skeleton = animatedModel->GetSkeleton();
  287. unsigned numBones = skeleton.GetNumBones();
  288. Bone* bestBone = 0;
  289. float bestSize = 0.0f;
  290. for (unsigned i = 0; i < numBones; ++i)
  291. {
  292. Bone* bone = skeleton.GetBone(i);
  293. if (!bone->node_ || !bone->collisionMask_)
  294. continue;
  295. // Represent the decal as a sphere, try to find the biggest colliding bone
  296. Sphere decalSphere
  297. (bone->node_->GetWorldTransform().Inverse() * worldPosition, 0.5f * size / bone->node_->GetWorldScale().Length());
  298. if (bone->collisionMask_ & BONECOLLISION_BOX)
  299. {
  300. float size = bone->boundingBox_.HalfSize().Length();
  301. if (bone->boundingBox_.IsInside(decalSphere) && size > bestSize)
  302. {
  303. bestBone = bone;
  304. bestSize = size;
  305. }
  306. }
  307. else if (bone->collisionMask_ & BONECOLLISION_SPHERE)
  308. {
  309. Sphere boneSphere(Vector3::ZERO, bone->radius_);
  310. float size = bone->radius_;
  311. if (boneSphere.IsInside(decalSphere) && size > bestSize)
  312. {
  313. bestBone = bone;
  314. bestSize = size;
  315. }
  316. }
  317. }
  318. if (bestBone)
  319. targetTransform = (bestBone->node_->GetWorldTransform() * bestBone->offsetMatrix_).Inverse();
  320. }
  321. // Build the decal frustum
  322. Frustum decalFrustum;
  323. Matrix3x4 frustumTransform = targetTransform * Matrix3x4(adjustedWorldPosition, worldRotation, 1.0f);
  324. decalFrustum.DefineOrtho(size, aspectRatio, 1.0, 0.0f, depth, frustumTransform);
  325. Vector3 decalNormal = (targetTransform * Vector4(worldRotation * Vector3::BACK, 0.0f)).Normalized();
  326. decals_.Resize(decals_.Size() + 1);
  327. Decal& newDecal = decals_.Back();
  328. newDecal.timeToLive_ = timeToLive;
  329. Vector<PODVector<DecalVertex> > faces;
  330. PODVector<DecalVertex> tempFace;
  331. unsigned numBatches = target->GetBatches().Size();
  332. // Use either a specified subgeometry in the target, or all
  333. if (subGeometry < numBatches)
  334. GetFaces(faces, target, subGeometry, decalFrustum, decalNormal, normalCutoff);
  335. else
  336. {
  337. for (unsigned i = 0; i < numBatches; ++i)
  338. GetFaces(faces, target, i, decalFrustum, decalNormal, normalCutoff);
  339. }
  340. // Clip the acquired faces against all frustum planes
  341. for (unsigned i = 0; i < NUM_FRUSTUM_PLANES; ++i)
  342. {
  343. for (unsigned j = 0; j < faces.Size(); ++j)
  344. {
  345. PODVector<DecalVertex>& face = faces[j];
  346. if (face.Empty())
  347. continue;
  348. ClipPolygon(tempFace, face, decalFrustum.planes_[i], skinned_);
  349. face = tempFace;
  350. }
  351. }
  352. // Now triangulate the resulting faces into decal vertices
  353. for (unsigned i = 0; i < faces.Size(); ++i)
  354. {
  355. PODVector<DecalVertex>& face = faces[i];
  356. if (face.Size() < 3)
  357. continue;
  358. for (unsigned j = 2; j < face.Size(); ++j)
  359. {
  360. newDecal.AddVertex(face[0]);
  361. newDecal.AddVertex(face[j - 1]);
  362. newDecal.AddVertex(face[j]);
  363. }
  364. }
  365. // Check if resulted in no triangles
  366. if (newDecal.vertices_.Empty())
  367. {
  368. decals_.Pop();
  369. return true;
  370. }
  371. if (newDecal.vertices_.Size() > maxVertices_)
  372. {
  373. ATOMIC_LOGWARNING("Can not add decal, vertex count " + String(newDecal.vertices_.Size()) + " exceeds maximum " +
  374. String(maxVertices_));
  375. decals_.Pop();
  376. return false;
  377. }
  378. if (newDecal.indices_.Size() > maxIndices_)
  379. {
  380. ATOMIC_LOGWARNING("Can not add decal, index count " + String(newDecal.indices_.Size()) + " exceeds maximum " +
  381. String(maxIndices_));
  382. decals_.Pop();
  383. return false;
  384. }
  385. // Calculate UVs
  386. Matrix4 projection(Matrix4::ZERO);
  387. projection.m11_ = (1.0f / (size * 0.5f));
  388. projection.m00_ = projection.m11_ / aspectRatio;
  389. projection.m22_ = 1.0f / depth;
  390. projection.m33_ = 1.0f;
  391. CalculateUVs(newDecal, frustumTransform.Inverse(), projection, topLeftUV, bottomRightUV);
  392. // Transform vertices to this node's local space and generate tangents
  393. Matrix3x4 decalTransform = node_->GetWorldTransform().Inverse() * target->GetNode()->GetWorldTransform();
  394. TransformVertices(newDecal, skinned_ ? Matrix3x4::IDENTITY : decalTransform);
  395. GenerateTangents(&newDecal.vertices_[0], sizeof(DecalVertex), &newDecal.indices_[0], sizeof(unsigned short), 0,
  396. newDecal.indices_.Size(), offsetof(DecalVertex, normal_), offsetof(DecalVertex, texCoord_), offsetof(DecalVertex,
  397. tangent_));
  398. newDecal.CalculateBoundingBox();
  399. numVertices_ += newDecal.vertices_.Size();
  400. numIndices_ += newDecal.indices_.Size();
  401. // Remove oldest decals if total vertices exceeded
  402. while (decals_.Size() && (numVertices_ > maxVertices_ || numIndices_ > maxIndices_))
  403. RemoveDecals(1);
  404. ATOMIC_LOGDEBUG("Added decal with " + String(newDecal.vertices_.Size()) + " vertices");
  405. // If new decal is time limited, subscribe to scene post-update
  406. if (newDecal.timeToLive_ > 0.0f && !subscribed_)
  407. UpdateEventSubscription(false);
  408. MarkDecalsDirty();
  409. return true;
  410. }
  411. void DecalSet::RemoveDecals(unsigned num)
  412. {
  413. while (num-- && decals_.Size())
  414. RemoveDecal(decals_.Begin());
  415. }
  416. void DecalSet::RemoveAllDecals()
  417. {
  418. if (!decals_.Empty())
  419. {
  420. decals_.Clear();
  421. numVertices_ = 0;
  422. numIndices_ = 0;
  423. MarkDecalsDirty();
  424. }
  425. // Remove all bones and skinning matrices and stop listening to the bone nodes
  426. for (Vector<Bone>::Iterator i = bones_.Begin(); i != bones_.End(); ++i)
  427. {
  428. if (i->node_)
  429. i->node_->RemoveListener(this);
  430. }
  431. bones_.Clear();
  432. skinMatrices_.Clear();
  433. UpdateBatch();
  434. }
  435. Material* DecalSet::GetMaterial() const
  436. {
  437. return batches_[0].material_;
  438. }
  439. void DecalSet::SetMaterialAttr(const ResourceRef& value)
  440. {
  441. ResourceCache* cache = GetSubsystem<ResourceCache>();
  442. SetMaterial(cache->GetResource<Material>(value.name_));
  443. }
  444. void DecalSet::SetDecalsAttr(const PODVector<unsigned char>& value)
  445. {
  446. RemoveAllDecals();
  447. if (value.Empty())
  448. return;
  449. MemoryBuffer buffer(value);
  450. skinned_ = buffer.ReadBool();
  451. unsigned numDecals = buffer.ReadVLE();
  452. while (numDecals--)
  453. {
  454. decals_.Resize(decals_.Size() + 1);
  455. Decal& newDecal = decals_.Back();
  456. newDecal.timer_ = buffer.ReadFloat();
  457. newDecal.timeToLive_ = buffer.ReadFloat();
  458. newDecal.vertices_.Resize(buffer.ReadVLE());
  459. newDecal.indices_.Resize(buffer.ReadVLE());
  460. for (PODVector<DecalVertex>::Iterator i = newDecal.vertices_.Begin(); i != newDecal.vertices_.End(); ++i)
  461. {
  462. i->position_ = buffer.ReadVector3();
  463. i->normal_ = buffer.ReadVector3();
  464. i->texCoord_ = buffer.ReadVector2();
  465. i->tangent_ = buffer.ReadVector4();
  466. if (skinned_)
  467. {
  468. for (unsigned j = 0; j < 4; ++j)
  469. i->blendWeights_[j] = buffer.ReadFloat();
  470. for (unsigned j = 0; j < 4; ++j)
  471. i->blendIndices_[j] = buffer.ReadUByte();
  472. }
  473. }
  474. for (PODVector<unsigned short>::Iterator i = newDecal.indices_.Begin(); i != newDecal.indices_.End(); ++i)
  475. *i = buffer.ReadUShort();
  476. newDecal.CalculateBoundingBox();
  477. numVertices_ += newDecal.vertices_.Size();
  478. numIndices_ += newDecal.indices_.Size();
  479. }
  480. if (skinned_)
  481. {
  482. unsigned numBones = buffer.ReadVLE();
  483. skinMatrices_.Resize(numBones);
  484. bones_.Resize(numBones);
  485. for (unsigned i = 0; i < numBones; ++i)
  486. {
  487. Bone& newBone = bones_[i];
  488. newBone.name_ = buffer.ReadString();
  489. newBone.collisionMask_ = buffer.ReadUByte();
  490. if (newBone.collisionMask_ & BONECOLLISION_SPHERE)
  491. newBone.radius_ = buffer.ReadFloat();
  492. if (newBone.collisionMask_ & BONECOLLISION_BOX)
  493. newBone.boundingBox_ = buffer.ReadBoundingBox();
  494. buffer.Read(&newBone.offsetMatrix_.m00_, sizeof(Matrix3x4));
  495. }
  496. assignBonesPending_ = true;
  497. skinningDirty_ = true;
  498. }
  499. UpdateEventSubscription(true);
  500. UpdateBatch();
  501. MarkDecalsDirty();
  502. }
  503. ResourceRef DecalSet::GetMaterialAttr() const
  504. {
  505. return GetResourceRef(batches_[0].material_, Material::GetTypeStatic());
  506. }
  507. PODVector<unsigned char> DecalSet::GetDecalsAttr() const
  508. {
  509. VectorBuffer ret;
  510. ret.WriteBool(skinned_);
  511. ret.WriteVLE(decals_.Size());
  512. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  513. {
  514. ret.WriteFloat(i->timer_);
  515. ret.WriteFloat(i->timeToLive_);
  516. ret.WriteVLE(i->vertices_.Size());
  517. ret.WriteVLE(i->indices_.Size());
  518. for (PODVector<DecalVertex>::ConstIterator j = i->vertices_.Begin(); j != i->vertices_.End(); ++j)
  519. {
  520. ret.WriteVector3(j->position_);
  521. ret.WriteVector3(j->normal_);
  522. ret.WriteVector2(j->texCoord_);
  523. ret.WriteVector4(j->tangent_);
  524. if (skinned_)
  525. {
  526. for (unsigned k = 0; k < 4; ++k)
  527. ret.WriteFloat(j->blendWeights_[k]);
  528. for (unsigned k = 0; k < 4; ++k)
  529. ret.WriteUByte(j->blendIndices_[k]);
  530. }
  531. }
  532. for (PODVector<unsigned short>::ConstIterator j = i->indices_.Begin(); j != i->indices_.End(); ++j)
  533. ret.WriteUShort(*j);
  534. }
  535. if (skinned_)
  536. {
  537. ret.WriteVLE(bones_.Size());
  538. for (Vector<Bone>::ConstIterator i = bones_.Begin(); i != bones_.End(); ++i)
  539. {
  540. ret.WriteString(i->name_);
  541. ret.WriteUByte(i->collisionMask_);
  542. if (i->collisionMask_ & BONECOLLISION_SPHERE)
  543. ret.WriteFloat(i->radius_);
  544. if (i->collisionMask_ & BONECOLLISION_BOX)
  545. ret.WriteBoundingBox(i->boundingBox_);
  546. ret.Write(i->offsetMatrix_.Data(), sizeof(Matrix3x4));
  547. }
  548. }
  549. return ret.GetBuffer();
  550. }
  551. void DecalSet::OnMarkedDirty(Node* node)
  552. {
  553. Drawable::OnMarkedDirty(node);
  554. if (skinned_)
  555. {
  556. // If the scene node or any of the bone nodes move, mark skinning dirty
  557. skinningDirty_ = true;
  558. }
  559. }
  560. void DecalSet::OnWorldBoundingBoxUpdate()
  561. {
  562. if (!skinned_)
  563. {
  564. if (boundingBoxDirty_)
  565. CalculateBoundingBox();
  566. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  567. }
  568. else
  569. {
  570. // When using skinning, update world bounding box based on the bones
  571. BoundingBox worldBox;
  572. for (Vector<Bone>::ConstIterator i = bones_.Begin(); i != bones_.End(); ++i)
  573. {
  574. Node* boneNode = i->node_;
  575. if (!boneNode)
  576. continue;
  577. // Use hitbox if available. If not, use only half of the sphere radius
  578. /// \todo The sphere radius should be multiplied with bone scale
  579. if (i->collisionMask_ & BONECOLLISION_BOX)
  580. worldBox.Merge(i->boundingBox_.Transformed(boneNode->GetWorldTransform()));
  581. else if (i->collisionMask_ & BONECOLLISION_SPHERE)
  582. worldBox.Merge(Sphere(boneNode->GetWorldPosition(), i->radius_ * 0.5f));
  583. }
  584. worldBoundingBox_ = worldBox;
  585. }
  586. }
  587. void DecalSet::GetFaces(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, const Frustum& frustum,
  588. const Vector3& decalNormal, float normalCutoff)
  589. {
  590. // Try to use the most accurate LOD level if possible
  591. Geometry* geometry = target->GetLodGeometry(batchIndex, 0);
  592. if (!geometry || geometry->GetPrimitiveType() != TRIANGLE_LIST)
  593. return;
  594. const unsigned char* positionData = 0;
  595. const unsigned char* normalData = 0;
  596. const unsigned char* skinningData = 0;
  597. const unsigned char* indexData = 0;
  598. unsigned positionStride = 0;
  599. unsigned normalStride = 0;
  600. unsigned skinningStride = 0;
  601. unsigned indexStride = 0;
  602. IndexBuffer* ib = geometry->GetIndexBuffer();
  603. if (ib)
  604. {
  605. indexData = ib->GetShadowData();
  606. indexStride = ib->GetIndexSize();
  607. }
  608. // For morphed models positions, normals and skinning may be in different buffers
  609. for (unsigned i = 0; i < geometry->GetNumVertexBuffers(); ++i)
  610. {
  611. VertexBuffer* vb = geometry->GetVertexBuffer(i);
  612. if (!vb)
  613. continue;
  614. unsigned elementMask = vb->GetElementMask();
  615. unsigned char* data = vb->GetShadowData();
  616. if (!data)
  617. continue;
  618. if (elementMask & MASK_POSITION)
  619. {
  620. positionData = data;
  621. positionStride = vb->GetVertexSize();
  622. }
  623. if (elementMask & MASK_NORMAL)
  624. {
  625. normalData = data + vb->GetElementOffset(SEM_NORMAL);
  626. normalStride = vb->GetVertexSize();
  627. }
  628. if (elementMask & MASK_BLENDWEIGHTS)
  629. {
  630. skinningData = data + vb->GetElementOffset(SEM_BLENDWEIGHTS);
  631. skinningStride = vb->GetVertexSize();
  632. }
  633. }
  634. // Positions and indices are needed
  635. if (!positionData)
  636. {
  637. // As a fallback, try to get the geometry's raw vertex/index data
  638. const PODVector<VertexElement>* elements;
  639. geometry->GetRawData(positionData, positionStride, indexData, indexStride, elements);
  640. if (!positionData)
  641. {
  642. ATOMIC_LOGWARNING("Can not add decal, target drawable has no CPU-side geometry data");
  643. return;
  644. }
  645. }
  646. if (indexData)
  647. {
  648. unsigned indexStart = geometry->GetIndexStart();
  649. unsigned indexCount = geometry->GetIndexCount();
  650. // 16-bit indices
  651. if (indexStride == sizeof(unsigned short))
  652. {
  653. const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
  654. const unsigned short* indicesEnd = indices + indexCount;
  655. while (indices < indicesEnd)
  656. {
  657. GetFace(faces, target, batchIndex, indices[0], indices[1], indices[2], positionData, normalData, skinningData,
  658. positionStride, normalStride, skinningStride, frustum, decalNormal, normalCutoff);
  659. indices += 3;
  660. }
  661. }
  662. else
  663. // 32-bit indices
  664. {
  665. const unsigned* indices = ((const unsigned*)indexData) + indexStart;
  666. const unsigned* indicesEnd = indices + indexCount;
  667. while (indices < indicesEnd)
  668. {
  669. GetFace(faces, target, batchIndex, indices[0], indices[1], indices[2], positionData, normalData, skinningData,
  670. positionStride, normalStride, skinningStride, frustum, decalNormal, normalCutoff);
  671. indices += 3;
  672. }
  673. }
  674. }
  675. else
  676. {
  677. // Non-indexed geometry
  678. unsigned indices = geometry->GetVertexStart();
  679. unsigned indicesEnd = indices + geometry->GetVertexCount();
  680. while (indices + 2 < indicesEnd)
  681. {
  682. GetFace(faces, target, batchIndex, indices, indices + 1, indices + 2, positionData, normalData, skinningData,
  683. positionStride, normalStride, skinningStride, frustum, decalNormal, normalCutoff);
  684. indices += 3;
  685. }
  686. }
  687. }
  688. void DecalSet::GetFace(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, unsigned i0, unsigned i1,
  689. unsigned i2, const unsigned char* positionData, const unsigned char* normalData, const unsigned char* skinningData,
  690. unsigned positionStride, unsigned normalStride, unsigned skinningStride, const Frustum& frustum, const Vector3& decalNormal,
  691. float normalCutoff)
  692. {
  693. bool hasNormals = normalData != 0;
  694. bool hasSkinning = skinned_ && skinningData != 0;
  695. const Vector3& v0 = *((const Vector3*)(&positionData[i0 * positionStride]));
  696. const Vector3& v1 = *((const Vector3*)(&positionData[i1 * positionStride]));
  697. const Vector3& v2 = *((const Vector3*)(&positionData[i2 * positionStride]));
  698. // Calculate unsmoothed face normals if no normal data
  699. Vector3 faceNormal = Vector3::ZERO;
  700. if (!hasNormals)
  701. {
  702. Vector3 dist1 = v1 - v0;
  703. Vector3 dist2 = v2 - v0;
  704. faceNormal = (dist1.CrossProduct(dist2)).Normalized();
  705. }
  706. const Vector3& n0 = hasNormals ? *((const Vector3*)(&normalData[i0 * normalStride])) : faceNormal;
  707. const Vector3& n1 = hasNormals ? *((const Vector3*)(&normalData[i1 * normalStride])) : faceNormal;
  708. const Vector3& n2 = hasNormals ? *((const Vector3*)(&normalData[i2 * normalStride])) : faceNormal;
  709. const unsigned char* s0 = hasSkinning ? &skinningData[i0 * skinningStride] : (const unsigned char*)0;
  710. const unsigned char* s1 = hasSkinning ? &skinningData[i1 * skinningStride] : (const unsigned char*)0;
  711. const unsigned char* s2 = hasSkinning ? &skinningData[i2 * skinningStride] : (const unsigned char*)0;
  712. // Check if face is too much away from the decal normal
  713. if (decalNormal.DotProduct((n0 + n1 + n2) / 3.0f) < normalCutoff)
  714. return;
  715. // Check if face is culled completely by any of the planes
  716. for (unsigned i = PLANE_FAR; i < NUM_FRUSTUM_PLANES; --i)
  717. {
  718. const Plane& plane = frustum.planes_[i];
  719. if (plane.Distance(v0) < 0.0f && plane.Distance(v1) < 0.0f && plane.Distance(v2) < 0.0f)
  720. return;
  721. }
  722. faces.Resize(faces.Size() + 1);
  723. PODVector<DecalVertex>& face = faces.Back();
  724. if (!hasSkinning)
  725. {
  726. face.Reserve(3);
  727. face.Push(DecalVertex(v0, n0));
  728. face.Push(DecalVertex(v1, n1));
  729. face.Push(DecalVertex(v2, n2));
  730. }
  731. else
  732. {
  733. const float* bw0 = (const float*)s0;
  734. const float* bw1 = (const float*)s1;
  735. const float* bw2 = (const float*)s2;
  736. const unsigned char* bi0 = s0 + sizeof(float) * 4;
  737. const unsigned char* bi1 = s1 + sizeof(float) * 4;
  738. const unsigned char* bi2 = s2 + sizeof(float) * 4;
  739. unsigned char nbi0[4];
  740. unsigned char nbi1[4];
  741. unsigned char nbi2[4];
  742. // Make sure all bones are found and that there is room in the skinning matrices
  743. if (!GetBones(target, batchIndex, bw0, bi0, nbi0) || !GetBones(target, batchIndex, bw1, bi1, nbi1) ||
  744. !GetBones(target, batchIndex, bw2, bi2, nbi2))
  745. return;
  746. face.Reserve(3);
  747. face.Push(DecalVertex(v0, n0, bw0, nbi0));
  748. face.Push(DecalVertex(v1, n1, bw1, nbi1));
  749. face.Push(DecalVertex(v2, n2, bw2, nbi2));
  750. }
  751. }
  752. bool DecalSet::GetBones(Drawable* target, unsigned batchIndex, const float* blendWeights, const unsigned char* blendIndices,
  753. unsigned char* newBlendIndices)
  754. {
  755. AnimatedModel* animatedModel = dynamic_cast<AnimatedModel*>(target);
  756. if (!animatedModel)
  757. return false;
  758. // Check whether target is using global or per-geometry skinning
  759. const Vector<PODVector<Matrix3x4> >& geometrySkinMatrices = animatedModel->GetGeometrySkinMatrices();
  760. const Vector<PODVector<unsigned> >& geometryBoneMappings = animatedModel->GetGeometryBoneMappings();
  761. for (unsigned i = 0; i < 4; ++i)
  762. {
  763. if (blendWeights[i] > 0.0f)
  764. {
  765. Bone* bone = 0;
  766. if (geometrySkinMatrices.Empty())
  767. bone = animatedModel->GetSkeleton().GetBone(blendIndices[i]);
  768. else if (blendIndices[i] < geometryBoneMappings[batchIndex].Size())
  769. bone = animatedModel->GetSkeleton().GetBone(geometryBoneMappings[batchIndex][blendIndices[i]]);
  770. if (!bone)
  771. {
  772. ATOMIC_LOGWARNING("Out of range bone index for skinned decal");
  773. return false;
  774. }
  775. bool found = false;
  776. unsigned index;
  777. for (index = 0; index < bones_.Size(); ++index)
  778. {
  779. if (bones_[index].node_ == bone->node_)
  780. {
  781. // Check also that the offset matrix matches, in case we for example have a separate attachment AnimatedModel
  782. // with a different bind pose
  783. if (bones_[index].offsetMatrix_.Equals(bone->offsetMatrix_))
  784. {
  785. found = true;
  786. break;
  787. }
  788. }
  789. }
  790. if (!found)
  791. {
  792. if (bones_.Size() >= Graphics::GetMaxBones())
  793. {
  794. ATOMIC_LOGWARNING("Maximum skinned decal bone count reached");
  795. return false;
  796. }
  797. else
  798. {
  799. // Copy the bone from the model to the decal
  800. index = bones_.Size();
  801. bones_.Resize(bones_.Size() + 1);
  802. bones_[index] = *bone;
  803. skinMatrices_.Resize(skinMatrices_.Size() + 1);
  804. skinningDirty_ = true;
  805. // Start listening to bone transform changes to update skinning
  806. bone->node_->AddListener(this);
  807. }
  808. }
  809. newBlendIndices[i] = (unsigned char)index;
  810. }
  811. else
  812. newBlendIndices[i] = 0;
  813. }
  814. // Update amount of shader data in the decal batch
  815. UpdateBatch();
  816. return true;
  817. }
  818. void DecalSet::CalculateUVs(Decal& decal, const Matrix3x4& view, const Matrix4& projection, const Vector2& topLeftUV,
  819. const Vector2& bottomRightUV)
  820. {
  821. Matrix4 viewProj = projection * view;
  822. for (PODVector<DecalVertex>::Iterator i = decal.vertices_.Begin(); i != decal.vertices_.End(); ++i)
  823. {
  824. Vector3 projected = viewProj * i->position_;
  825. i->texCoord_ = Vector2(
  826. Lerp(topLeftUV.x_, bottomRightUV.x_, projected.x_ * 0.5f + 0.5f),
  827. Lerp(bottomRightUV.y_, topLeftUV.y_, projected.y_ * 0.5f + 0.5f)
  828. );
  829. }
  830. }
  831. void DecalSet::TransformVertices(Decal& decal, const Matrix3x4& transform)
  832. {
  833. for (PODVector<DecalVertex>::Iterator i = decal.vertices_.Begin(); i != decal.vertices_.End(); ++i)
  834. {
  835. i->position_ = transform * i->position_;
  836. i->normal_ = (transform * Vector4(i->normal_, 0.0f)).Normalized();
  837. }
  838. }
  839. List<Decal>::Iterator DecalSet::RemoveDecal(List<Decal>::Iterator i)
  840. {
  841. numVertices_ -= i->vertices_.Size();
  842. numIndices_ -= i->indices_.Size();
  843. MarkDecalsDirty();
  844. return decals_.Erase(i);
  845. }
  846. void DecalSet::MarkDecalsDirty()
  847. {
  848. if (!boundingBoxDirty_)
  849. {
  850. boundingBoxDirty_ = true;
  851. OnMarkedDirty(node_);
  852. }
  853. bufferDirty_ = true;
  854. }
  855. void DecalSet::CalculateBoundingBox()
  856. {
  857. boundingBox_.Clear();
  858. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  859. boundingBox_.Merge(i->boundingBox_);
  860. boundingBoxDirty_ = false;
  861. }
  862. void DecalSet::UpdateBuffers()
  863. {
  864. unsigned newElementMask = skinned_ ? SKINNED_ELEMENT_MASK : STATIC_ELEMENT_MASK;
  865. unsigned newVBSize = optimizeBufferSize_ ? numVertices_ : maxVertices_;
  866. unsigned newIBSize = optimizeBufferSize_ ? numIndices_ : maxIndices_;
  867. if (vertexBuffer_->GetElementMask() != newElementMask || vertexBuffer_->GetVertexCount() != newVBSize)
  868. vertexBuffer_->SetSize(newVBSize, newElementMask);
  869. if (indexBuffer_->GetIndexCount() != newIBSize)
  870. indexBuffer_->SetSize(newIBSize, false);
  871. geometry_->SetVertexBuffer(0, vertexBuffer_);
  872. geometry_->SetDrawRange(TRIANGLE_LIST, 0, numIndices_, 0, numVertices_);
  873. float* vertices = numVertices_ ? (float*)vertexBuffer_->Lock(0, numVertices_) : (float*)0;
  874. unsigned short* indices = numIndices_ ? (unsigned short*)indexBuffer_->Lock(0, numIndices_) : (unsigned short*)0;
  875. if (vertices && indices)
  876. {
  877. unsigned short indexStart = 0;
  878. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  879. {
  880. for (unsigned j = 0; j < i->vertices_.Size(); ++j)
  881. {
  882. const DecalVertex& vertex = i->vertices_[j];
  883. *vertices++ = vertex.position_.x_;
  884. *vertices++ = vertex.position_.y_;
  885. *vertices++ = vertex.position_.z_;
  886. *vertices++ = vertex.normal_.x_;
  887. *vertices++ = vertex.normal_.y_;
  888. *vertices++ = vertex.normal_.z_;
  889. *vertices++ = vertex.texCoord_.x_;
  890. *vertices++ = vertex.texCoord_.y_;
  891. *vertices++ = vertex.tangent_.x_;
  892. *vertices++ = vertex.tangent_.y_;
  893. *vertices++ = vertex.tangent_.z_;
  894. *vertices++ = vertex.tangent_.w_;
  895. if (skinned_)
  896. {
  897. *vertices++ = vertex.blendWeights_[0];
  898. *vertices++ = vertex.blendWeights_[1];
  899. *vertices++ = vertex.blendWeights_[2];
  900. *vertices++ = vertex.blendWeights_[3];
  901. *vertices++ = *((float*)vertex.blendIndices_);
  902. }
  903. }
  904. for (unsigned j = 0; j < i->indices_.Size(); ++j)
  905. *indices++ = i->indices_[j] + indexStart;
  906. indexStart += i->vertices_.Size();
  907. }
  908. }
  909. vertexBuffer_->Unlock();
  910. vertexBuffer_->ClearDataLost();
  911. indexBuffer_->Unlock();
  912. indexBuffer_->ClearDataLost();
  913. bufferDirty_ = false;
  914. }
  915. void DecalSet::UpdateSkinning()
  916. {
  917. // Use model's world transform in case a bone is missing
  918. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  919. for (unsigned i = 0; i < bones_.Size(); ++i)
  920. {
  921. const Bone& bone = bones_[i];
  922. if (bone.node_)
  923. skinMatrices_[i] = bone.node_->GetWorldTransform() * bone.offsetMatrix_;
  924. else
  925. skinMatrices_[i] = worldTransform;
  926. }
  927. skinningDirty_ = false;
  928. }
  929. void DecalSet::UpdateBatch()
  930. {
  931. if (skinMatrices_.Size())
  932. {
  933. batches_[0].geometryType_ = GEOM_SKINNED;
  934. batches_[0].worldTransform_ = &skinMatrices_[0];
  935. batches_[0].numWorldTransforms_ = skinMatrices_.Size();
  936. }
  937. else
  938. {
  939. batches_[0].geometryType_ = GEOM_STATIC;
  940. batches_[0].worldTransform_ = &node_->GetWorldTransform();
  941. batches_[0].numWorldTransforms_ = 1;
  942. }
  943. }
  944. void DecalSet::AssignBoneNodes()
  945. {
  946. assignBonesPending_ = false;
  947. if (!node_)
  948. return;
  949. // Find the bone nodes from the node hierarchy and add listeners
  950. for (Vector<Bone>::Iterator i = bones_.Begin(); i != bones_.End(); ++i)
  951. {
  952. Node* boneNode = node_->GetChild(i->name_, true);
  953. if (boneNode)
  954. boneNode->AddListener(this);
  955. i->node_ = boneNode;
  956. }
  957. }
  958. void DecalSet::UpdateEventSubscription(bool checkAllDecals)
  959. {
  960. Scene* scene = GetScene();
  961. if (!scene)
  962. return;
  963. bool enabled = IsEnabledEffective();
  964. if (enabled && checkAllDecals)
  965. {
  966. bool hasTimeLimitedDecals = false;
  967. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  968. {
  969. if (i->timeToLive_ > 0.0f)
  970. {
  971. hasTimeLimitedDecals = true;
  972. break;
  973. }
  974. }
  975. // If no time limited decals, no need to subscribe to scene update
  976. enabled = hasTimeLimitedDecals;
  977. }
  978. if (enabled && !subscribed_)
  979. {
  980. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, ATOMIC_HANDLER(DecalSet, HandleScenePostUpdate));
  981. subscribed_ = true;
  982. }
  983. else if (!enabled && subscribed_)
  984. {
  985. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  986. subscribed_ = false;
  987. }
  988. }
  989. void DecalSet::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  990. {
  991. using namespace ScenePostUpdate;
  992. float timeStep = eventData[P_TIMESTEP].GetFloat();
  993. for (List<Decal>::Iterator i = decals_.Begin(); i != decals_.End();)
  994. {
  995. i->timer_ += timeStep;
  996. // Remove the decal if time to live expired
  997. if (i->timeToLive_ > 0.0f && i->timer_ > i->timeToLive_)
  998. i = RemoveDecal(i);
  999. else
  1000. ++i;
  1001. }
  1002. }
  1003. }