DecalSet.cpp 38 KB

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