DecalSet.cpp 38 KB

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