DecalSet.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  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 "Batch.h"
  26. #include "Camera.h"
  27. #include "Context.h"
  28. #include "DecalSet.h"
  29. #include "Geometry.h"
  30. #include "Graphics.h"
  31. #include "IndexBuffer.h"
  32. #include "Log.h"
  33. #include "MemoryBuffer.h"
  34. #include "Node.h"
  35. #include "Profiler.h"
  36. #include "ResourceCache.h"
  37. #include "Scene.h"
  38. #include "SceneEvents.h"
  39. #include "Tangent.h"
  40. #include "VectorBuffer.h"
  41. #include "VertexBuffer.h"
  42. #include "DebugNew.h"
  43. static const Vector3 DOT_SCALE(1 / 3.0f, 1 / 3.0f, 1 / 3.0f);
  44. static const unsigned MIN_VERTICES = 4;
  45. static const unsigned MIN_INDICES = 6;
  46. static const unsigned MAX_VERTICES = 65536;
  47. static const unsigned DEFAULT_MAX_VERTICES = 512;
  48. static const unsigned DEFAULT_MAX_INDICES = 1024;
  49. static const unsigned STATIC_ELEMENT_MASK = MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT;
  50. static const unsigned SKINNED_ELEMENT_MASK = MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT | MASK_BLENDWEIGHTS |
  51. MASK_BLENDINDICES;
  52. static DecalVertex ClipEdge(const DecalVertex& v0, const DecalVertex& v1, float d0, float d1, bool skinned)
  53. {
  54. DecalVertex ret;
  55. float t = d0 / (d0 - d1);
  56. ret.position_ = v0.position_ + t * (v1.position_ - v0.position_);
  57. ret.normal_ = v0.normal_ + t * (v1.normal_ - v0.normal_);
  58. if (skinned)
  59. {
  60. // Blend weights / indices can not be easily interpolated, choose the one that is nearer to the split plane
  61. const DecalVertex& src = Abs(d0) < Abs(d1) ? v0 : v1;
  62. for (unsigned i = 0; i < 4; ++i)
  63. {
  64. ret.blendWeights_[i] = src.blendWeights_[i];
  65. ret.blendIndices_[i] = src.blendIndices_[i];
  66. }
  67. }
  68. return ret;
  69. }
  70. static void ClipPolygon(PODVector<DecalVertex>& dest, const PODVector<DecalVertex>& src, const Plane& plane, bool skinned)
  71. {
  72. unsigned last;
  73. float lastDistance = 0.0f;
  74. dest.Clear();
  75. if (src.Empty())
  76. return;
  77. for (unsigned i = 0; i < src.Size(); ++i)
  78. {
  79. float distance = plane.Distance(src[i].position_);
  80. if (distance >= 0.0f)
  81. {
  82. if (lastDistance < 0.0f)
  83. dest.Push(ClipEdge(src[last], src[i], lastDistance, distance, skinned));
  84. dest.Push(src[i]);
  85. }
  86. else
  87. {
  88. if (lastDistance >= 0.0f && i != 0)
  89. dest.Push(ClipEdge(src[last], src[i], lastDistance, distance, skinned));
  90. }
  91. last = i;
  92. lastDistance = distance;
  93. }
  94. // Recheck the distances of the last and first vertices and add the final clipped vertex if applicable
  95. float distance = plane.Distance(src[0].position_);
  96. if ((lastDistance < 0.0f && distance >= 0.0f) || (lastDistance >= 0.0f && distance < 0.0f))
  97. dest.Push(ClipEdge(src[last], src[0], lastDistance, distance, skinned));
  98. }
  99. void Decal::AddVertex(const DecalVertex& vertex)
  100. {
  101. for (unsigned i = 0; i < vertices_.Size(); ++i)
  102. {
  103. if (vertex.position_.Equals(vertices_[i].position_) && vertex.normal_.Equals(vertices_[i].normal_))
  104. {
  105. indices_.Push(i);
  106. return;
  107. }
  108. }
  109. unsigned short newIndex = vertices_.Size();
  110. vertices_.Push(vertex);
  111. indices_.Push(newIndex);
  112. }
  113. void Decal::CalculateBoundingBox()
  114. {
  115. boundingBox_.Clear();
  116. for (unsigned i = 0; i < vertices_.Size(); ++i)
  117. boundingBox_.Merge(vertices_[i].position_);
  118. }
  119. OBJECTTYPESTATIC(DecalSet);
  120. DecalSet::DecalSet(Context* context) :
  121. Drawable(context),
  122. geometry_(new Geometry(context)),
  123. vertexBuffer_(new VertexBuffer(context_)),
  124. indexBuffer_(new IndexBuffer(context_)),
  125. numVertices_(0),
  126. numIndices_(0),
  127. maxVertices_(DEFAULT_MAX_VERTICES),
  128. maxIndices_(DEFAULT_MAX_INDICES),
  129. skinned_(false),
  130. bufferSizeDirty_(true),
  131. bufferDirty_(true),
  132. boundingBoxDirty_(true),
  133. skinningDirty_(false),
  134. assignBonesPending_(false)
  135. {
  136. drawableFlags_ = DRAWABLE_GEOMETRY;
  137. geometry_->SetIndexBuffer(indexBuffer_);
  138. batches_.Resize(1);
  139. batches_[0].geometry_ = geometry_;
  140. }
  141. DecalSet::~DecalSet()
  142. {
  143. }
  144. void DecalSet::RegisterObject(Context* context)
  145. {
  146. context->RegisterFactory<DecalSet>();
  147. ACCESSOR_ATTRIBUTE(DecalSet, VAR_RESOURCEREF, "Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()), AM_DEFAULT);
  148. ATTRIBUTE(DecalSet, VAR_BOOL, "Is Visible", visible_, true, AM_DEFAULT);
  149. ACCESSOR_ATTRIBUTE(DecalSet, VAR_BOOL, "Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  150. ACCESSOR_ATTRIBUTE(DecalSet, VAR_FLOAT, "Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  151. ACCESSOR_ATTRIBUTE(DecalSet, VAR_INT, "Max Vertices", GetMaxVertices, SetMaxVertices, unsigned, DEFAULT_MAX_VERTICES, AM_DEFAULT);
  152. ACCESSOR_ATTRIBUTE(DecalSet, VAR_INT, "Max Indices", GetMaxIndices, SetMaxIndices, unsigned, DEFAULT_MAX_INDICES, AM_DEFAULT);
  153. COPY_BASE_ATTRIBUTES(DecalSet, Drawable);
  154. ACCESSOR_ATTRIBUTE(DecalSet, VAR_VARIANTVECTOR, "Decals", GetDecalsAttr, SetDecalsAttr, VariantVector, VariantVector(), AM_FILE | AM_NOEDIT);
  155. }
  156. void DecalSet::ApplyAttributes()
  157. {
  158. if (assignBonesPending_)
  159. AssignBoneNodes();
  160. }
  161. void DecalSet::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  162. {
  163. // Do not return raycast hits
  164. }
  165. void DecalSet::UpdateBatches(const FrameInfo& frame)
  166. {
  167. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  168. distance_ = frame.camera_->GetDistance(GetWorldBoundingBox().Center());
  169. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  170. lodDistance_ = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  171. batches_[0].distance_ = distance_;
  172. batches_[0].worldTransform_ = &worldTransform;
  173. }
  174. void DecalSet::UpdateGeometry(const FrameInfo& frame)
  175. {
  176. if (bufferSizeDirty_)
  177. UpdateBufferSize();
  178. if (bufferDirty_ || vertexBuffer_->IsDataLost() || indexBuffer_->IsDataLost())
  179. UpdateBuffers();
  180. if (skinningDirty_)
  181. UpdateSkinning();
  182. }
  183. UpdateGeometryType DecalSet::GetUpdateGeometryType()
  184. {
  185. if (bufferDirty_ || bufferSizeDirty_ || vertexBuffer_->IsDataLost() || indexBuffer_->IsDataLost())
  186. return UPDATE_MAIN_THREAD;
  187. else if (skinningDirty_)
  188. return UPDATE_WORKER_THREAD;
  189. else
  190. return UPDATE_NONE;
  191. }
  192. void DecalSet::SetMaterial(Material* material)
  193. {
  194. batches_[0].material_ = material;
  195. MarkNetworkUpdate();
  196. }
  197. void DecalSet::SetMaxVertices(unsigned num)
  198. {
  199. // Never expand to 32 bit indices
  200. num = Clamp((int)num, MIN_VERTICES, MAX_VERTICES);
  201. if (num != maxVertices_)
  202. {
  203. bufferSizeDirty_ = true;
  204. maxVertices_ = num;
  205. while (decals_.Size() && numVertices_ > maxVertices_)
  206. RemoveDecals(1);
  207. MarkNetworkUpdate();
  208. }
  209. }
  210. void DecalSet::SetMaxIndices(unsigned num)
  211. {
  212. if (num < MIN_INDICES)
  213. num = MIN_INDICES;
  214. if (num != maxIndices_)
  215. {
  216. bufferSizeDirty_ = true;
  217. maxIndices_ = num;
  218. while (decals_.Size() && numIndices_ > maxIndices_)
  219. RemoveDecals(1);
  220. MarkNetworkUpdate();
  221. }
  222. }
  223. bool DecalSet::AddDecal(Drawable* target, const Vector3& worldPosition, const Quaternion& worldRotation, float size,
  224. float aspectRatio, float depth, const Vector2& topLeftUV, const Vector2& bottomRightUV, float timeToLive, float normalCutoff,
  225. float depthBias)
  226. {
  227. PROFILE(AddDecal);
  228. if (!node_)
  229. return false;
  230. if (!target || !target->GetNode())
  231. {
  232. LOGERROR("Null target drawable for decal");
  233. return false;
  234. }
  235. // Check for animated target and switch into skinned/static mode if necessary
  236. AnimatedModel* animatedModel = dynamic_cast<AnimatedModel*>(target);
  237. if ((animatedModel && !skinned_) || (!animatedModel && skinned_))
  238. {
  239. RemoveAllDecals();
  240. skinned_ = animatedModel != 0;
  241. bufferSizeDirty_ = true;
  242. }
  243. Matrix3x4 targetTransform = target->GetNode()->GetWorldTransform().Inverse();
  244. // For an animated model, adjust the decal position back to the bind pose
  245. // To do this, need to find the bone the decal is colliding with
  246. if (animatedModel)
  247. {
  248. Skeleton& skeleton = animatedModel->GetSkeleton();
  249. unsigned numBones = skeleton.GetNumBones();
  250. unsigned bestIndex = M_MAX_UNSIGNED;
  251. float bestDistance = M_INFINITY;
  252. for (unsigned i = 0; i < numBones; ++i)
  253. {
  254. Bone* bone = skeleton.GetBone(i);
  255. if (!bone->node_ || !bone->collisionMask_)
  256. continue;
  257. // Represent the decal as a sphere, try to find the closest match
  258. Sphere decalSphere(bone->node_->GetWorldTransform().Inverse() * (worldPosition + worldRotation * (0.5f * depth *
  259. Vector3::FORWARD)), size);
  260. float distance = (worldPosition - bone->node_->GetWorldPosition()).Length();
  261. if (bone->collisionMask_ & BONECOLLISION_BOX)
  262. {
  263. if (bone->boundingBox_.IsInside(decalSphere) != OUTSIDE && distance < bestDistance)
  264. {
  265. bestIndex = i;
  266. bestDistance = distance;
  267. }
  268. }
  269. else if (bone->collisionMask_ & BONECOLLISION_SPHERE)
  270. {
  271. Sphere boneSphere(Vector3::ZERO, bone->radius_);
  272. if (boneSphere.IsInside(decalSphere) != OUTSIDE && distance < bestDistance)
  273. {
  274. bestIndex = i;
  275. bestDistance = distance;
  276. }
  277. }
  278. }
  279. if (bestIndex < numBones)
  280. {
  281. Bone* bone = skeleton.GetBone(bestIndex);
  282. targetTransform = (bone->node_->GetWorldTransform() * bone->offsetMatrix_).Inverse();
  283. }
  284. }
  285. // Build the decal frustum
  286. Frustum decalFrustum;
  287. Matrix3x4 frustumTransform = targetTransform * Matrix3x4(worldPosition, worldRotation, 1.0f);
  288. decalFrustum.DefineOrtho(size, aspectRatio, 1.0, 0.0f, depth, frustumTransform);
  289. Vector3 biasVector = targetTransform * Vector4(worldRotation * (Vector3::BACK * depthBias), 0.0f);
  290. Vector3 decalNormal = (targetTransform * Vector4(worldRotation * Vector3::BACK, 0.0f)).Normalized();
  291. decals_.Resize(decals_.Size() + 1);
  292. Decal& newDecal = decals_.Back();
  293. newDecal.timeToLive_ = timeToLive;
  294. Vector<PODVector<DecalVertex> > faces;
  295. PODVector<DecalVertex> tempFace;
  296. unsigned numBatches = target->GetBatches().Size();
  297. for (unsigned i = 0; i < numBatches; ++i)
  298. GetFaces(faces, target, i, decalFrustum, decalNormal, normalCutoff);
  299. // Clip the acquired faces against all frustum planes
  300. for (unsigned i = 0; i < NUM_FRUSTUM_PLANES; ++i)
  301. {
  302. for (unsigned j = 0; j < faces.Size(); ++j)
  303. {
  304. PODVector<DecalVertex>& face = faces[j];
  305. if (face.Empty())
  306. continue;
  307. ClipPolygon(tempFace, face, decalFrustum.planes_[i], skinned_);
  308. face = tempFace;
  309. }
  310. }
  311. // Now triangulate the resulting faces into decal vertices
  312. for (unsigned i = 0; i < faces.Size(); ++i)
  313. {
  314. PODVector<DecalVertex>& face = faces[i];
  315. if (face.Size() < 3)
  316. continue;
  317. for (unsigned j = 2; j < face.Size(); ++j)
  318. {
  319. newDecal.AddVertex(face[0]);
  320. newDecal.AddVertex(face[j - 1]);
  321. newDecal.AddVertex(face[j]);
  322. }
  323. }
  324. // Check if resulted in no triangles
  325. if (newDecal.vertices_.Empty())
  326. {
  327. decals_.Pop();
  328. return true;
  329. }
  330. if (newDecal.vertices_.Size() > maxVertices_ || newDecal.indices_.Size() > maxIndices_)
  331. {
  332. LOGWARNING("Can not add decal, vertex count " + String(newDecal.vertices_.Size()) + " exceeds maximum " +
  333. String(maxVertices_));
  334. decals_.Pop();
  335. return false;
  336. }
  337. // Finally transform vertices to this node's local space
  338. Matrix3x4 decalTransform = node_->GetWorldTransform().Inverse() * target->GetNode()->GetWorldTransform();
  339. CalculateUVs(newDecal, frustumTransform.Inverse(), size, aspectRatio, depth, topLeftUV, bottomRightUV);
  340. TransformVertices(newDecal, skinned_ ? Matrix3x4::IDENTITY : decalTransform, biasVector);
  341. GenerateTangents(&newDecal.vertices_[0], sizeof(DecalVertex), &newDecal.indices_[0], sizeof(unsigned short), 0,
  342. newDecal.indices_.Size(), offsetof(DecalVertex, normal_), offsetof(DecalVertex, texCoord_), offsetof(DecalVertex,
  343. tangent_));
  344. newDecal.CalculateBoundingBox();
  345. numVertices_ += newDecal.vertices_.Size();
  346. numIndices_ += newDecal.indices_.Size();
  347. // Subscribe to scene post-update if defined a time-limited decal
  348. Scene* scene = GetScene();
  349. if (newDecal.timeToLive_ > 0.0f && scene && !HasSubscribedToEvent(scene, E_SCENEPOSTUPDATE))
  350. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(DecalSet, HandleScenePostUpdate));
  351. // Remove oldest decals if total vertices exceeded
  352. while (decals_.Size() && (numVertices_ > maxVertices_ || numIndices_ > maxIndices_))
  353. RemoveDecals(1);
  354. LOGDEBUG("Added decal with " + String(newDecal.vertices_.Size()) + " vertices");
  355. MarkDecalsDirty();
  356. return true;
  357. }
  358. void DecalSet::RemoveDecals(unsigned num)
  359. {
  360. while (decals_.Size() && num)
  361. {
  362. RemoveDecal(decals_.Begin());
  363. --num;
  364. }
  365. }
  366. void DecalSet::RemoveAllDecals()
  367. {
  368. if (!decals_.Empty())
  369. {
  370. decals_.Clear();
  371. numVertices_ = 0;
  372. numIndices_ = 0;
  373. MarkDecalsDirty();
  374. }
  375. // Remove all bones and skinning matrices and stop listening to the bone nodes
  376. for (Vector<Bone>::Iterator i = bones_.Begin(); i != bones_.End(); ++i)
  377. {
  378. if (i->node_)
  379. i->node_->RemoveListener(this);
  380. }
  381. bones_.Clear();
  382. skinMatrices_.Clear();
  383. UpdateBatch();
  384. }
  385. Material* DecalSet::GetMaterial() const
  386. {
  387. return batches_[0].material_;
  388. }
  389. void DecalSet::SetMaterialAttr(ResourceRef value)
  390. {
  391. ResourceCache* cache = GetSubsystem<ResourceCache>();
  392. SetMaterial(cache->GetResource<Material>(value.id_));
  393. }
  394. void DecalSet::SetDecalsAttr(VariantVector value)
  395. {
  396. unsigned index = 0;
  397. Scene* scene = GetScene();
  398. RemoveAllDecals();
  399. skinned_ = value[index++].GetBool();
  400. unsigned numDecals = value[index++].GetInt();
  401. while (numDecals--)
  402. {
  403. decals_.Resize(decals_.Size() + 1);
  404. Decal& newDecal = decals_.Back();
  405. newDecal.timer_ = value[index++].GetFloat();
  406. newDecal.timeToLive_ = value[index++].GetFloat();
  407. newDecal.vertices_.Resize(value[index++].GetInt());
  408. newDecal.indices_.Resize(value[index++].GetInt());
  409. MemoryBuffer geometry(value[index++].GetBuffer());
  410. for (PODVector<DecalVertex>::Iterator i = newDecal.vertices_.Begin(); i != newDecal.vertices_.End(); ++i)
  411. {
  412. i->position_ = geometry.ReadVector3();
  413. i->normal_ = geometry.ReadVector3();
  414. i->texCoord_ = geometry.ReadVector2();
  415. i->tangent_ = geometry.ReadVector4();
  416. if (skinned_)
  417. {
  418. for (unsigned j = 0; j < 4; ++j)
  419. i->blendWeights_[j] = geometry.ReadFloat();
  420. for (unsigned j = 0; j < 4; ++j)
  421. i->blendIndices_[j] = geometry.ReadUByte();
  422. }
  423. }
  424. for (PODVector<unsigned short>::Iterator i = newDecal.indices_.Begin(); i != newDecal.indices_.End(); ++i)
  425. *i = geometry.ReadUShort();
  426. newDecal.CalculateBoundingBox();
  427. numVertices_ += newDecal.vertices_.Size();
  428. numIndices_ += newDecal.indices_.Size();
  429. // Subscribe to scene post-update if defined a time-limited decal
  430. if (newDecal.timeToLive_ > 0.0f && scene && !HasSubscribedToEvent(scene, E_SCENEPOSTUPDATE))
  431. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(DecalSet, HandleScenePostUpdate));
  432. }
  433. if (skinned_)
  434. {
  435. unsigned numBones = value[index++].GetInt();
  436. skinMatrices_.Resize(numBones);
  437. while (numBones--)
  438. {
  439. bones_.Resize(bones_.Size() + 1);
  440. Bone& newBone = bones_.Back();
  441. newBone.name_ = value[index++].GetString();
  442. MemoryBuffer boneData(value[index++].GetBuffer());
  443. newBone.collisionMask_ = boneData.ReadUByte();
  444. if (newBone.collisionMask_ & BONECOLLISION_SPHERE)
  445. newBone.radius_ = boneData.ReadFloat();
  446. if (newBone.collisionMask_ & BONECOLLISION_BOX)
  447. newBone.boundingBox_ = boneData.ReadBoundingBox();
  448. Vector4* offsetMatrix = (Vector4*)newBone.offsetMatrix_.Data();
  449. offsetMatrix[0] = boneData.ReadVector4();
  450. offsetMatrix[1] = boneData.ReadVector4();
  451. offsetMatrix[2] = boneData.ReadVector4();
  452. }
  453. assignBonesPending_ = true;
  454. skinningDirty_ = true;
  455. }
  456. UpdateBatch();
  457. MarkDecalsDirty();
  458. bufferSizeDirty_ = true;
  459. }
  460. ResourceRef DecalSet::GetMaterialAttr() const
  461. {
  462. return GetResourceRef(batches_[0].material_, Material::GetTypeStatic());
  463. }
  464. VariantVector DecalSet::GetDecalsAttr() const
  465. {
  466. VariantVector ret;
  467. ret.Push(skinned_);
  468. ret.Push(decals_.Size());
  469. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  470. {
  471. ret.Push(i->timer_);
  472. ret.Push(i->timeToLive_);
  473. ret.Push(i->vertices_.Size());
  474. ret.Push(i->indices_.Size());
  475. VectorBuffer geometry;
  476. for (PODVector<DecalVertex>::ConstIterator j = i->vertices_.Begin(); j != i->vertices_.End(); ++j)
  477. {
  478. geometry.WriteVector3(j->position_);
  479. geometry.WriteVector3(j->normal_);
  480. geometry.WriteVector2(j->texCoord_);
  481. geometry.WriteVector4(j->tangent_);
  482. if (skinned_)
  483. {
  484. for (unsigned k = 0; k < 4; ++k)
  485. geometry.WriteFloat(j->blendWeights_[k]);
  486. for (unsigned k = 0; k < 4; ++k)
  487. geometry.WriteUByte(j->blendIndices_[k]);
  488. }
  489. }
  490. for (PODVector<unsigned short>::ConstIterator j = i->indices_.Begin(); j != i->indices_.End(); ++j)
  491. geometry.WriteUShort(*j);
  492. ret.Push(geometry.GetBuffer());
  493. }
  494. if (skinned_)
  495. {
  496. ret.Push(bones_.Size());
  497. for (Vector<Bone>::ConstIterator i = bones_.Begin(); i != bones_.End(); ++i)
  498. {
  499. ret.Push(i->name_);
  500. VectorBuffer boneData;
  501. boneData.WriteUByte(i->collisionMask_);
  502. if (i->collisionMask_ & BONECOLLISION_SPHERE)
  503. boneData.WriteFloat(i->radius_);
  504. if (i->collisionMask_ & BONECOLLISION_BOX)
  505. boneData.WriteBoundingBox(i->boundingBox_);
  506. const Vector4* offsetMatrix = (const Vector4*)i->offsetMatrix_.Data();
  507. boneData.WriteVector4(offsetMatrix[0]);
  508. boneData.WriteVector4(offsetMatrix[1]);
  509. boneData.WriteVector4(offsetMatrix[2]);
  510. ret.Push(boneData.GetBuffer());
  511. }
  512. }
  513. return ret;
  514. }
  515. void DecalSet::OnMarkedDirty(Node* node)
  516. {
  517. Drawable::OnMarkedDirty(node);
  518. if (skinned_)
  519. {
  520. // If the scene node or any of the bone nodes move, mark skinning dirty
  521. skinningDirty_ = true;
  522. }
  523. }
  524. void DecalSet::OnWorldBoundingBoxUpdate()
  525. {
  526. if (!skinned_)
  527. {
  528. if (boundingBoxDirty_)
  529. CalculateBoundingBox();
  530. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  531. }
  532. else
  533. {
  534. // When using skinning, update world bounding box based on the bones
  535. worldBoundingBox_.defined_ = false;
  536. for (Vector<Bone>::ConstIterator i = bones_.Begin(); i != bones_.End(); ++i)
  537. {
  538. Node* boneNode = i->node_;
  539. if (!boneNode)
  540. continue;
  541. // Use hitbox if available. If not, use only half of the sphere radius
  542. if (i->collisionMask_ & BONECOLLISION_BOX)
  543. worldBoundingBox_.Merge(i->boundingBox_.Transformed(boneNode->GetWorldTransform()));
  544. else if (i->collisionMask_ & BONECOLLISION_SPHERE)
  545. worldBoundingBox_.Merge(Sphere(boneNode->GetWorldPosition(), i->radius_ * 0.5f));
  546. }
  547. }
  548. }
  549. void DecalSet::GetFaces(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, const Frustum& frustum,
  550. const Vector3& decalNormal, float normalCutoff)
  551. {
  552. Geometry* geometry;
  553. // Special handling for static/animated models, as they may use LOD: use the fixed software LOD level for decals
  554. StaticModel* staticModel = dynamic_cast<StaticModel*>(target);
  555. if (staticModel)
  556. geometry = staticModel->GetSoftwareGeometry(batchIndex);
  557. else
  558. geometry = target->GetBatches()[batchIndex].geometry_;
  559. if (!geometry)
  560. return;
  561. const unsigned char* positionData = 0;
  562. const unsigned char* normalData = 0;
  563. const unsigned char* skinningData = 0;
  564. const unsigned char* indexData = 0;
  565. unsigned positionStride;
  566. unsigned normalStride;
  567. unsigned skinningStride;
  568. unsigned indexStride;
  569. IndexBuffer* ib = geometry->GetIndexBuffer();
  570. if (ib)
  571. {
  572. indexData = ib->GetShadowData();
  573. indexStride = ib->GetIndexSize();
  574. }
  575. // For morphed models positions, normals and skinning may be in different buffers
  576. for (unsigned i = 0; i < geometry->GetNumVertexBuffers(); ++i)
  577. {
  578. VertexBuffer* vb = geometry->GetVertexBuffer(i);
  579. if (!vb)
  580. continue;
  581. unsigned elementMask = geometry->GetVertexElementMask(i);
  582. unsigned char* data = vb->GetShadowData();
  583. if ((elementMask & MASK_POSITION) && data)
  584. {
  585. positionData = data;
  586. positionStride = vb->GetVertexSize();
  587. }
  588. if ((elementMask & MASK_NORMAL) && data)
  589. {
  590. normalData = data + vb->GetElementOffset(ELEMENT_NORMAL);
  591. normalStride = vb->GetVertexSize();
  592. }
  593. if ((elementMask & MASK_BLENDWEIGHTS) && data)
  594. {
  595. skinningData = data + vb->GetElementOffset(ELEMENT_BLENDWEIGHTS);
  596. skinningStride = vb->GetVertexSize();
  597. }
  598. }
  599. // Positions and indices are needed
  600. if (!positionData || !indexData)
  601. {
  602. LOGWARNING("Can not add decal, object does not have CPU-side geometry data");
  603. return;
  604. }
  605. unsigned indexStart = geometry->GetIndexStart();
  606. unsigned indexCount = geometry->GetIndexCount();
  607. // 16-bit indices
  608. if (indexStride == sizeof(unsigned short))
  609. {
  610. const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
  611. const unsigned short* indicesEnd = indices + indexCount;
  612. while (indices < indicesEnd)
  613. {
  614. GetFace(faces, target, batchIndex, indices[0], indices[1], indices[2], positionData, normalData, skinningData,
  615. positionStride, normalStride, skinningStride, frustum, decalNormal, normalCutoff);
  616. indices += 3;
  617. }
  618. }
  619. else
  620. // 32-bit indices
  621. {
  622. const unsigned* indices = ((const unsigned*)indexData) + indexStart;
  623. const unsigned* indicesEnd = indices + indexCount;
  624. while (indices < indicesEnd)
  625. {
  626. GetFace(faces, target, batchIndex, indices[0], indices[1], indices[2], positionData, normalData, skinningData,
  627. positionStride, normalStride, skinningStride, frustum, decalNormal, normalCutoff);
  628. indices += 3;
  629. }
  630. }
  631. }
  632. void DecalSet::GetFace(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, unsigned i0, unsigned i1,
  633. unsigned i2, const unsigned char* positionData, const unsigned char* normalData, const unsigned char* skinningData,
  634. unsigned positionStride, unsigned normalStride, unsigned skinningStride, const Frustum& frustum, const Vector3& decalNormal,
  635. float normalCutoff)
  636. {
  637. bool hasNormals = normalData != 0;
  638. bool hasSkinning = skinned_ && skinningData != 0;
  639. const Vector3& v0 = *((const Vector3*)(&positionData[i0 * positionStride]));
  640. const Vector3& v1 = *((const Vector3*)(&positionData[i1 * positionStride]));
  641. const Vector3& v2 = *((const Vector3*)(&positionData[i2 * positionStride]));
  642. const Vector3& n0 = hasNormals ? *((const Vector3*)(&normalData[i0 * normalStride])) : Vector3::ZERO;
  643. const Vector3& n1 = hasNormals ? *((const Vector3*)(&normalData[i1 * normalStride])) : Vector3::ZERO;
  644. const Vector3& n2 = hasNormals ? *((const Vector3*)(&normalData[i2 * normalStride])) : Vector3::ZERO;
  645. const unsigned char* s0 = hasSkinning ? &skinningData[i0 * skinningStride] : (const unsigned char*)0;
  646. const unsigned char* s1 = hasSkinning ? &skinningData[i1 * skinningStride] : (const unsigned char*)0;
  647. const unsigned char* s2 = hasSkinning ? &skinningData[i2 * skinningStride] : (const unsigned char*)0;
  648. // Check if face is too much away from the decal normal
  649. if (hasNormals && decalNormal.DotProduct((n0 + n1 + n2) / 3.0f) < normalCutoff)
  650. return;
  651. // Check if face is culled completely by any of the planes
  652. for (unsigned i = PLANE_FAR; i < NUM_FRUSTUM_PLANES; --i)
  653. {
  654. const Plane& plane = frustum.planes_[i];
  655. if (plane.Distance(v0) < 0.0f && plane.Distance(v1) < 0.0f && plane.Distance(v2) < 0.0f)
  656. return;
  657. }
  658. faces.Resize(faces.Size() + 1);
  659. PODVector<DecalVertex>& face = faces.Back();
  660. if (!hasSkinning)
  661. {
  662. face.Push(DecalVertex(v0, n0));
  663. face.Push(DecalVertex(v1, n1));
  664. face.Push(DecalVertex(v2, n2));
  665. }
  666. else
  667. {
  668. const float* bw0 = (const float*)s0;
  669. const float* bw1 = (const float*)s1;
  670. const float* bw2 = (const float*)s2;
  671. const unsigned char* bi0 = s0 + sizeof(float) * 4;
  672. const unsigned char* bi1 = s1 + sizeof(float) * 4;
  673. const unsigned char* bi2 = s2 + sizeof(float) * 4;
  674. unsigned char nbi0[4];
  675. unsigned char nbi1[4];
  676. unsigned char nbi2[4];
  677. // Make sure all bones are found and that there is room in the skinning matrices
  678. if (!GetBones(target, batchIndex, bw0, bi0, nbi0) || !GetBones(target, batchIndex, bw1, bi1, nbi1) ||
  679. !GetBones(target, batchIndex, bw2, bi2, nbi2))
  680. return;
  681. face.Push(DecalVertex(v0, n0, bw0, nbi0));
  682. face.Push(DecalVertex(v1, n1, bw1, nbi1));
  683. face.Push(DecalVertex(v2, n2, bw2, nbi2));
  684. }
  685. }
  686. bool DecalSet::GetBones(Drawable* target, unsigned batchIndex, const float* blendWeights, const unsigned char* blendIndices,
  687. unsigned char* newBlendIndices)
  688. {
  689. AnimatedModel* animatedModel = dynamic_cast<AnimatedModel*>(target);
  690. if (!animatedModel)
  691. return false;
  692. // Check whether target is using global or per-geometry skinning
  693. const Vector<PODVector<Matrix3x4> >& geometrySkinMatrices = animatedModel->GetGeometrySkinMatrices();
  694. const Vector<PODVector<unsigned> >& geometryBoneMappings = animatedModel->GetGeometryBoneMappings();
  695. for (unsigned i = 0; i < 4; ++i)
  696. {
  697. if (blendWeights[i] > 0.0f)
  698. {
  699. Bone* bone = 0;
  700. if (geometrySkinMatrices.Empty())
  701. bone = animatedModel->GetSkeleton().GetBone(blendIndices[i]);
  702. else if (blendIndices[i] < geometryBoneMappings[batchIndex].Size())
  703. bone = animatedModel->GetSkeleton().GetBone(geometryBoneMappings[batchIndex][blendIndices[i]]);
  704. if (!bone)
  705. {
  706. LOGWARNING("Out of range bone index for skinned decal");
  707. return false;
  708. }
  709. bool found = false;
  710. unsigned index;
  711. for (index = 0; index < bones_.Size(); ++index)
  712. {
  713. if (bones_[index].node_ == bone->node_)
  714. {
  715. // Check also that the offset matrix matches, in case we for example have a separate attachment AnimatedModel
  716. // with a different bind pose
  717. const float* offsetA = bones_[index].offsetMatrix_.Data();
  718. const float* offsetB = bone->offsetMatrix_.Data();
  719. unsigned j;
  720. for (j = 0; j < 12; ++j)
  721. {
  722. if (!Equals(offsetA[j], offsetB[j]))
  723. break;
  724. }
  725. if (j == 12)
  726. {
  727. found = true;
  728. break;
  729. }
  730. }
  731. }
  732. if (!found)
  733. {
  734. if (bones_.Size() >= MAX_SKIN_MATRICES)
  735. {
  736. LOGWARNING("Maximum skinned decal bone count reached");
  737. return false;
  738. }
  739. else
  740. {
  741. // Copy the bone from the model to the decal
  742. index = bones_.Size();
  743. bones_.Resize(bones_.Size() + 1);
  744. bones_[index] = *bone;
  745. skinMatrices_.Resize(skinMatrices_.Size() + 1);
  746. skinningDirty_ = true;
  747. // Start listening to bone transform changes to update skinning, update amount of shader data in the batch
  748. bone->node_->AddListener(this);
  749. UpdateBatch();
  750. }
  751. }
  752. newBlendIndices[i] = index;
  753. }
  754. else
  755. newBlendIndices[i] = 0;
  756. }
  757. return true;
  758. }
  759. void DecalSet::CalculateUVs(Decal& decal, const Matrix3x4& view, float size, float aspectRatio, float depth,
  760. const Vector2& topLeftUV, const Vector2& bottomRightUV)
  761. {
  762. Matrix4 projection(Matrix4::ZERO);
  763. float h = (1.0f / (size * 0.5f));
  764. float w = h / aspectRatio;
  765. float q = 1.0f / depth;
  766. float r = 0.0f;
  767. projection.m00_ = w;
  768. projection.m11_ = h;
  769. projection.m22_ = q;
  770. projection.m23_ = r;
  771. projection.m33_ = 1.0f;
  772. Matrix4 viewProj = projection * view;
  773. for (PODVector<DecalVertex>::Iterator i = decal.vertices_.Begin(); i != decal.vertices_.End(); ++i)
  774. {
  775. Vector3 projected = viewProj * i->position_;
  776. i->texCoord_ = Vector2(
  777. Lerp(topLeftUV.x_, bottomRightUV.x_, projected.x_ * 0.5f + 0.5f),
  778. Lerp(bottomRightUV.y_, topLeftUV.y_, projected.y_ * 0.5f + 0.5f)
  779. );
  780. }
  781. }
  782. void DecalSet::TransformVertices(Decal& decal, const Matrix3x4& transform, const Vector3& biasVector)
  783. {
  784. for (PODVector<DecalVertex>::Iterator i = decal.vertices_.Begin(); i != decal.vertices_.End(); ++i)
  785. {
  786. i->position_ = transform * (i->position_ + biasVector);
  787. i->normal_ = (transform * i->normal_).Normalized();
  788. }
  789. }
  790. List<Decal>::Iterator DecalSet::RemoveDecal(List<Decal>::Iterator i)
  791. {
  792. numVertices_ -= i->vertices_.Size();
  793. numIndices_ -= i->indices_.Size();
  794. MarkDecalsDirty();
  795. return decals_.Erase(i);
  796. }
  797. void DecalSet::MarkDecalsDirty()
  798. {
  799. if (!boundingBoxDirty_)
  800. {
  801. boundingBoxDirty_ = true;
  802. OnMarkedDirty(node_);
  803. }
  804. bufferDirty_ = true;
  805. }
  806. void DecalSet::CalculateBoundingBox()
  807. {
  808. boundingBox_.Clear();
  809. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  810. boundingBox_.Merge(i->boundingBox_);
  811. boundingBoxDirty_ = false;
  812. }
  813. void DecalSet::UpdateBufferSize()
  814. {
  815. vertexBuffer_->SetSize(maxVertices_, skinned_ ? SKINNED_ELEMENT_MASK : STATIC_ELEMENT_MASK);
  816. indexBuffer_->SetSize(maxIndices_, false);
  817. geometry_->SetVertexBuffer(0, vertexBuffer_);
  818. bufferDirty_ = true;
  819. bufferSizeDirty_ = false;
  820. }
  821. void DecalSet::UpdateBuffers()
  822. {
  823. geometry_->SetDrawRange(TRIANGLE_LIST, 0, numIndices_, 0, numVertices_);
  824. float* vertices = (float*)vertexBuffer_->Lock(0, numVertices_);
  825. unsigned short* indices = (unsigned short*)indexBuffer_->Lock(0, numIndices_);
  826. unsigned short indexStart = 0;
  827. if (vertices && indices)
  828. {
  829. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  830. {
  831. for (unsigned j = 0; j < i->vertices_.Size(); ++j)
  832. {
  833. const DecalVertex& vertex = i->vertices_[j];
  834. *vertices++ = vertex.position_.x_;
  835. *vertices++ = vertex.position_.y_;
  836. *vertices++ = vertex.position_.z_;
  837. *vertices++ = vertex.normal_.x_;
  838. *vertices++ = vertex.normal_.y_;
  839. *vertices++ = vertex.normal_.z_;
  840. *vertices++ = vertex.texCoord_.x_;
  841. *vertices++ = vertex.texCoord_.y_;
  842. *vertices++ = vertex.tangent_.x_;
  843. *vertices++ = vertex.tangent_.y_;
  844. *vertices++ = vertex.tangent_.z_;
  845. *vertices++ = vertex.tangent_.w_;
  846. if (skinned_)
  847. {
  848. *vertices++ = vertex.blendWeights_[0];
  849. *vertices++ = vertex.blendWeights_[1];
  850. *vertices++ = vertex.blendWeights_[2];
  851. *vertices++ = vertex.blendWeights_[3];
  852. *vertices++ = *((float*)vertex.blendIndices_);
  853. }
  854. }
  855. for (unsigned j = 0; j < i->indices_.Size(); ++j)
  856. *indices++ = i->indices_[j] + indexStart;
  857. indexStart += i->vertices_.Size();
  858. }
  859. }
  860. vertexBuffer_->Unlock();
  861. vertexBuffer_->ClearDataLost();
  862. indexBuffer_->Unlock();
  863. indexBuffer_->ClearDataLost();
  864. bufferDirty_ = false;
  865. }
  866. void DecalSet::UpdateSkinning()
  867. {
  868. // Use model's world transform in case a bone is missing
  869. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  870. for (unsigned i = 0; i < bones_.Size(); ++i)
  871. {
  872. const Bone& bone = bones_[i];
  873. if (bone.node_)
  874. skinMatrices_[i] = bone.node_->GetWorldTransform() * bone.offsetMatrix_;
  875. else
  876. skinMatrices_[i] = worldTransform;
  877. }
  878. skinningDirty_ = false;
  879. }
  880. void DecalSet::UpdateBatch()
  881. {
  882. if (skinMatrices_.Size())
  883. {
  884. batches_[0].geometryType_ = GEOM_SKINNED;
  885. batches_[0].shaderData_ = skinMatrices_[0].Data();
  886. batches_[0].shaderDataSize_ = skinMatrices_.Size() * 12;
  887. }
  888. else
  889. {
  890. batches_[0].geometryType_ = GEOM_STATIC;
  891. batches_[0].shaderData_ = 0;
  892. batches_[0].shaderDataSize_ = 0;
  893. }
  894. }
  895. void DecalSet::AssignBoneNodes()
  896. {
  897. assignBonesPending_ = false;
  898. if (!node_)
  899. return;
  900. // Find the bone nodes from the node hierarchy and add listeners
  901. for (Vector<Bone>::Iterator i = bones_.Begin(); i != bones_.End(); ++i)
  902. {
  903. Node* boneNode = node_->GetChild(i->name_, true);
  904. if (boneNode)
  905. boneNode->AddListener(this);
  906. i->node_ = boneNode;
  907. }
  908. }
  909. void DecalSet::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  910. {
  911. using namespace ScenePostUpdate;
  912. float timeStep = eventData[P_TIMESTEP].GetFloat();
  913. for (List<Decal>::Iterator i = decals_.Begin(); i != decals_.End();)
  914. {
  915. i->timer_ += timeStep;
  916. // Remove the decal if time to live expired
  917. if (i->timeToLive_ > 0.0f && i->timer_ > i->timeToLive_)
  918. i = RemoveDecal(i);
  919. else
  920. ++i;
  921. }
  922. }