2
0

DecalSet.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "AnimatedModel.h"
  24. #include "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. 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, 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>();
  161. ACCESSOR_ATTRIBUTE(DecalSet, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  162. ACCESSOR_ATTRIBUTE(DecalSet, VAR_RESOURCEREF, "Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()), AM_DEFAULT);
  163. ACCESSOR_ATTRIBUTE(DecalSet, VAR_INT, "Max Vertices", GetMaxVertices, SetMaxVertices, unsigned, DEFAULT_MAX_VERTICES, AM_DEFAULT);
  164. ACCESSOR_ATTRIBUTE(DecalSet, VAR_INT, "Max Indices", GetMaxIndices, SetMaxIndices, unsigned, DEFAULT_MAX_INDICES, 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, Variant::emptyVariantVector, 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. // Do not add decals in headless mode
  243. if (!node_ || !GetSubsystem<Graphics>())
  244. return false;
  245. if (!target || !target->GetNode())
  246. {
  247. LOGERROR("Null target drawable for decal");
  248. return false;
  249. }
  250. // Check for animated target and switch into skinned/static mode if necessary
  251. AnimatedModel* animatedModel = dynamic_cast<AnimatedModel*>(target);
  252. if ((animatedModel && !skinned_) || (!animatedModel && skinned_))
  253. {
  254. RemoveAllDecals();
  255. skinned_ = animatedModel != 0;
  256. bufferSizeDirty_ = true;
  257. }
  258. // Center the decal frustum on the world position
  259. Vector3 adjustedWorldPosition = worldPosition - 0.5f * depth * (worldRotation * Vector3::FORWARD);
  260. Matrix3x4 targetTransform = target->GetNode()->GetWorldTransform().Inverse();
  261. // For an animated model, adjust the decal position back to the bind pose
  262. // To do this, need to find the bone the decal is colliding with
  263. if (animatedModel)
  264. {
  265. Skeleton& skeleton = animatedModel->GetSkeleton();
  266. unsigned numBones = skeleton.GetNumBones();
  267. Bone* bestBone = 0;
  268. float bestSize = 0.0f;
  269. for (unsigned i = 0; i < numBones; ++i)
  270. {
  271. Bone* bone = skeleton.GetBone(i);
  272. if (!bone->node_ || !bone->collisionMask_)
  273. continue;
  274. // Represent the decal as a sphere, try to find the biggest colliding bone
  275. Sphere decalSphere(bone->node_->GetWorldTransform().Inverse() * worldPosition, 0.5f * size /
  276. bone->node_->GetWorldScale().Length());
  277. if (bone->collisionMask_ & BONECOLLISION_BOX)
  278. {
  279. float size = bone->boundingBox_.HalfSize().Length();
  280. if (bone->boundingBox_.IsInside(decalSphere) && size > bestSize)
  281. {
  282. bestBone = bone;
  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) && size > bestSize)
  291. {
  292. bestBone = bone;
  293. bestSize = size;
  294. }
  295. }
  296. }
  297. if (bestBone)
  298. targetTransform = (bestBone->node_->GetWorldTransform() * bestBone->offsetMatrix_).Inverse();
  299. }
  300. // Build the decal frustum
  301. Frustum decalFrustum;
  302. Matrix3x4 frustumTransform = targetTransform * Matrix3x4(adjustedWorldPosition, worldRotation, 1.0f);
  303. decalFrustum.DefineOrtho(size, aspectRatio, 1.0, 0.0f, depth, frustumTransform);
  304. Vector3 decalNormal = (targetTransform * Vector4(worldRotation * Vector3::BACK, 0.0f)).Normalized();
  305. decals_.Resize(decals_.Size() + 1);
  306. Decal& newDecal = decals_.Back();
  307. newDecal.timeToLive_ = timeToLive;
  308. Vector<PODVector<DecalVertex> > faces;
  309. PODVector<DecalVertex> tempFace;
  310. unsigned numBatches = target->GetBatches().Size();
  311. // Use either a specified subgeometry in the target, or all
  312. if (subGeometry < numBatches)
  313. GetFaces(faces, target, subGeometry, decalFrustum, decalNormal, normalCutoff);
  314. else
  315. {
  316. for (unsigned i = 0; i < numBatches; ++i)
  317. GetFaces(faces, target, i, decalFrustum, decalNormal, normalCutoff);
  318. }
  319. // Clip the acquired faces against all frustum planes
  320. for (unsigned i = 0; i < NUM_FRUSTUM_PLANES; ++i)
  321. {
  322. for (unsigned j = 0; j < faces.Size(); ++j)
  323. {
  324. PODVector<DecalVertex>& face = faces[j];
  325. if (face.Empty())
  326. continue;
  327. ClipPolygon(tempFace, face, decalFrustum.planes_[i], skinned_);
  328. face = tempFace;
  329. }
  330. }
  331. // Now triangulate the resulting faces into decal vertices
  332. for (unsigned i = 0; i < faces.Size(); ++i)
  333. {
  334. PODVector<DecalVertex>& face = faces[i];
  335. if (face.Size() < 3)
  336. continue;
  337. for (unsigned j = 2; j < face.Size(); ++j)
  338. {
  339. newDecal.AddVertex(face[0]);
  340. newDecal.AddVertex(face[j - 1]);
  341. newDecal.AddVertex(face[j]);
  342. }
  343. }
  344. // Check if resulted in no triangles
  345. if (newDecal.vertices_.Empty())
  346. {
  347. decals_.Pop();
  348. return true;
  349. }
  350. if (newDecal.vertices_.Size() > maxVertices_)
  351. {
  352. LOGWARNING("Can not add decal, vertex count " + String(newDecal.vertices_.Size()) + " exceeds maximum " +
  353. String(maxVertices_));
  354. decals_.Pop();
  355. return false;
  356. }
  357. if (newDecal.indices_.Size() > maxIndices_)
  358. {
  359. LOGWARNING("Can not add decal, index count " + String(newDecal.indices_.Size()) + " exceeds maximum " +
  360. String(maxIndices_));
  361. decals_.Pop();
  362. return false;
  363. }
  364. // Calculate UVs
  365. Matrix4 projection(Matrix4::ZERO);
  366. projection.m11_ = (1.0f / (size * 0.5f));
  367. projection.m00_ = projection.m11_ / aspectRatio;
  368. projection.m22_ = 1.0f / depth;
  369. projection.m33_ = 1.0f;
  370. CalculateUVs(newDecal, frustumTransform.Inverse(), projection, topLeftUV, bottomRightUV);
  371. // Transform vertices to this node's local space and generate tangents
  372. Matrix3x4 decalTransform = node_->GetWorldTransform().Inverse() * target->GetNode()->GetWorldTransform();
  373. TransformVertices(newDecal, skinned_ ? Matrix3x4::IDENTITY : decalTransform);
  374. GenerateTangents(&newDecal.vertices_[0], sizeof(DecalVertex), &newDecal.indices_[0], sizeof(unsigned short), 0,
  375. newDecal.indices_.Size(), offsetof(DecalVertex, normal_), offsetof(DecalVertex, texCoord_), offsetof(DecalVertex,
  376. tangent_));
  377. newDecal.CalculateBoundingBox();
  378. numVertices_ += newDecal.vertices_.Size();
  379. numIndices_ += newDecal.indices_.Size();
  380. // Subscribe to scene post-update if defined a time-limited decal
  381. Scene* scene = GetScene();
  382. if (!subscribed_ && newDecal.timeToLive_ > 0.0f && scene)
  383. {
  384. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(DecalSet, HandleScenePostUpdate));
  385. subscribed_ = true;
  386. }
  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 (num-- && decals_.Size())
  397. RemoveDecal(decals_.Begin());
  398. }
  399. void DecalSet::RemoveAllDecals()
  400. {
  401. if (!decals_.Empty())
  402. {
  403. decals_.Clear();
  404. numVertices_ = 0;
  405. numIndices_ = 0;
  406. MarkDecalsDirty();
  407. }
  408. // Remove all bones and skinning matrices and stop listening to the bone nodes
  409. for (Vector<Bone>::Iterator i = bones_.Begin(); i != bones_.End(); ++i)
  410. {
  411. if (i->node_)
  412. i->node_->RemoveListener(this);
  413. }
  414. bones_.Clear();
  415. skinMatrices_.Clear();
  416. UpdateBatch();
  417. }
  418. Material* DecalSet::GetMaterial() const
  419. {
  420. return batches_[0].material_;
  421. }
  422. void DecalSet::SetMaterialAttr(ResourceRef value)
  423. {
  424. ResourceCache* cache = GetSubsystem<ResourceCache>();
  425. SetMaterial(cache->GetResource<Material>(value.id_));
  426. }
  427. void DecalSet::SetDecalsAttr(VariantVector value)
  428. {
  429. unsigned index = 0;
  430. Scene* scene = GetScene();
  431. RemoveAllDecals();
  432. skinned_ = value[index++].GetBool();
  433. unsigned numDecals = value[index++].GetInt();
  434. bool hasTimeLimitedDecal = false;
  435. while (numDecals--)
  436. {
  437. decals_.Resize(decals_.Size() + 1);
  438. Decal& newDecal = decals_.Back();
  439. newDecal.timer_ = value[index++].GetFloat();
  440. newDecal.timeToLive_ = value[index++].GetFloat();
  441. newDecal.vertices_.Resize(value[index++].GetInt());
  442. newDecal.indices_.Resize(value[index++].GetInt());
  443. MemoryBuffer geometry(value[index++].GetBuffer());
  444. for (PODVector<DecalVertex>::Iterator i = newDecal.vertices_.Begin(); i != newDecal.vertices_.End(); ++i)
  445. {
  446. i->position_ = geometry.ReadVector3();
  447. i->normal_ = geometry.ReadVector3();
  448. i->texCoord_ = geometry.ReadVector2();
  449. i->tangent_ = geometry.ReadVector4();
  450. if (skinned_)
  451. {
  452. for (unsigned j = 0; j < 4; ++j)
  453. i->blendWeights_[j] = geometry.ReadFloat();
  454. for (unsigned j = 0; j < 4; ++j)
  455. i->blendIndices_[j] = geometry.ReadUByte();
  456. }
  457. }
  458. for (PODVector<unsigned short>::Iterator i = newDecal.indices_.Begin(); i != newDecal.indices_.End(); ++i)
  459. *i = geometry.ReadUShort();
  460. newDecal.CalculateBoundingBox();
  461. numVertices_ += newDecal.vertices_.Size();
  462. numIndices_ += newDecal.indices_.Size();
  463. if (!hasTimeLimitedDecal && newDecal.timeToLive_ > 0.0f)
  464. hasTimeLimitedDecal = true;
  465. }
  466. // Subscribe to scene post-update if defined a time-limited decal
  467. if (!subscribed_ && hasTimeLimitedDecal && scene)
  468. {
  469. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(DecalSet, HandleScenePostUpdate));
  470. subscribed_ = true;
  471. }
  472. if (skinned_)
  473. {
  474. unsigned numBones = value[index++].GetInt();
  475. skinMatrices_.Resize(numBones);
  476. bones_.Resize(numBones);
  477. for (unsigned i = 0; i < numBones; ++i)
  478. {
  479. Bone& newBone = bones_[i];
  480. newBone.name_ = value[index++].GetString();
  481. MemoryBuffer boneData(value[index++].GetBuffer());
  482. newBone.collisionMask_ = boneData.ReadUByte();
  483. if (newBone.collisionMask_ & BONECOLLISION_SPHERE)
  484. newBone.radius_ = boneData.ReadFloat();
  485. if (newBone.collisionMask_ & BONECOLLISION_BOX)
  486. newBone.boundingBox_ = boneData.ReadBoundingBox();
  487. boneData.Read(&newBone.offsetMatrix_.m00_, sizeof(Matrix3x4));
  488. }
  489. assignBonesPending_ = true;
  490. skinningDirty_ = true;
  491. }
  492. UpdateBatch();
  493. MarkDecalsDirty();
  494. bufferSizeDirty_ = true;
  495. }
  496. ResourceRef DecalSet::GetMaterialAttr() const
  497. {
  498. return GetResourceRef(batches_[0].material_, Material::GetTypeStatic());
  499. }
  500. VariantVector DecalSet::GetDecalsAttr() const
  501. {
  502. VariantVector ret;
  503. ret.Push(skinned_);
  504. ret.Push(decals_.Size());
  505. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  506. {
  507. ret.Push(i->timer_);
  508. ret.Push(i->timeToLive_);
  509. ret.Push(i->vertices_.Size());
  510. ret.Push(i->indices_.Size());
  511. VectorBuffer geometry;
  512. for (PODVector<DecalVertex>::ConstIterator j = i->vertices_.Begin(); j != i->vertices_.End(); ++j)
  513. {
  514. geometry.WriteVector3(j->position_);
  515. geometry.WriteVector3(j->normal_);
  516. geometry.WriteVector2(j->texCoord_);
  517. geometry.WriteVector4(j->tangent_);
  518. if (skinned_)
  519. {
  520. for (unsigned k = 0; k < 4; ++k)
  521. geometry.WriteFloat(j->blendWeights_[k]);
  522. for (unsigned k = 0; k < 4; ++k)
  523. geometry.WriteUByte(j->blendIndices_[k]);
  524. }
  525. }
  526. for (PODVector<unsigned short>::ConstIterator j = i->indices_.Begin(); j != i->indices_.End(); ++j)
  527. geometry.WriteUShort(*j);
  528. ret.Push(geometry.GetBuffer());
  529. }
  530. if (skinned_)
  531. {
  532. ret.Push(bones_.Size());
  533. for (Vector<Bone>::ConstIterator i = bones_.Begin(); i != bones_.End(); ++i)
  534. {
  535. ret.Push(i->name_);
  536. VectorBuffer boneData;
  537. boneData.WriteUByte(i->collisionMask_);
  538. if (i->collisionMask_ & BONECOLLISION_SPHERE)
  539. boneData.WriteFloat(i->radius_);
  540. if (i->collisionMask_ & BONECOLLISION_BOX)
  541. boneData.WriteBoundingBox(i->boundingBox_);
  542. boneData.Write(i->offsetMatrix_.Data(), sizeof(Matrix3x4));
  543. ret.Push(boneData.GetBuffer());
  544. }
  545. }
  546. return ret;
  547. }
  548. void DecalSet::OnMarkedDirty(Node* node)
  549. {
  550. Drawable::OnMarkedDirty(node);
  551. if (skinned_)
  552. {
  553. // If the scene node or any of the bone nodes move, mark skinning dirty
  554. skinningDirty_ = true;
  555. }
  556. }
  557. void DecalSet::OnWorldBoundingBoxUpdate()
  558. {
  559. if (!skinned_)
  560. {
  561. if (boundingBoxDirty_)
  562. CalculateBoundingBox();
  563. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  564. }
  565. else
  566. {
  567. // When using skinning, update world bounding box based on the bones
  568. worldBoundingBox_.defined_ = false;
  569. for (Vector<Bone>::ConstIterator i = bones_.Begin(); i != bones_.End(); ++i)
  570. {
  571. Node* boneNode = i->node_;
  572. if (!boneNode)
  573. continue;
  574. // Use hitbox if available. If not, use only half of the sphere radius
  575. if (i->collisionMask_ & BONECOLLISION_BOX)
  576. worldBoundingBox_.Merge(i->boundingBox_.Transformed(boneNode->GetWorldTransform()));
  577. else if (i->collisionMask_ & BONECOLLISION_SPHERE)
  578. worldBoundingBox_.Merge(Sphere(boneNode->GetWorldPosition(), i->radius_ * 0.5f));
  579. }
  580. }
  581. }
  582. void DecalSet::GetFaces(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, const Frustum& frustum,
  583. const Vector3& decalNormal, float normalCutoff)
  584. {
  585. // Try to use the most accurate LOD level if possible
  586. Geometry* geometry = target->GetLodGeometry(batchIndex, 0);
  587. if (!geometry || geometry->GetPrimitiveType() != TRIANGLE_LIST)
  588. return;
  589. const unsigned char* positionData = 0;
  590. const unsigned char* normalData = 0;
  591. const unsigned char* skinningData = 0;
  592. const unsigned char* indexData = 0;
  593. unsigned positionStride = 0;
  594. unsigned normalStride = 0;
  595. unsigned skinningStride = 0;
  596. unsigned indexStride = 0;
  597. IndexBuffer* ib = geometry->GetIndexBuffer();
  598. if (ib)
  599. {
  600. indexData = ib->GetShadowData();
  601. indexStride = ib->GetIndexSize();
  602. }
  603. // For morphed models positions, normals and skinning may be in different buffers
  604. for (unsigned i = 0; i < geometry->GetNumVertexBuffers(); ++i)
  605. {
  606. VertexBuffer* vb = geometry->GetVertexBuffer(i);
  607. if (!vb)
  608. continue;
  609. unsigned elementMask = geometry->GetVertexElementMask(i);
  610. unsigned char* data = vb->GetShadowData();
  611. if (!data)
  612. continue;
  613. if (elementMask & MASK_POSITION)
  614. {
  615. positionData = data;
  616. positionStride = vb->GetVertexSize();
  617. }
  618. if (elementMask & MASK_NORMAL)
  619. {
  620. normalData = data + vb->GetElementOffset(ELEMENT_NORMAL);
  621. normalStride = vb->GetVertexSize();
  622. }
  623. if (elementMask & MASK_BLENDWEIGHTS)
  624. {
  625. skinningData = data + vb->GetElementOffset(ELEMENT_BLENDWEIGHTS);
  626. skinningStride = vb->GetVertexSize();
  627. }
  628. }
  629. // Positions and indices are needed
  630. if (!positionData)
  631. {
  632. // As a fallback, try to get the geometry's raw vertex/index data
  633. unsigned elementMask;
  634. geometry->GetRawData(positionData, positionStride, indexData, indexStride, elementMask);
  635. if (!positionData)
  636. {
  637. LOGWARNING("Can not add decal, target drawable has no CPU-side geometry data");
  638. return;
  639. }
  640. }
  641. if (indexData)
  642. {
  643. unsigned indexStart = geometry->GetIndexStart();
  644. unsigned indexCount = geometry->GetIndexCount();
  645. // 16-bit indices
  646. if (indexStride == sizeof(unsigned short))
  647. {
  648. const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
  649. const unsigned short* indicesEnd = indices + indexCount;
  650. while (indices < indicesEnd)
  651. {
  652. GetFace(faces, target, batchIndex, indices[0], indices[1], indices[2], positionData, normalData, skinningData,
  653. positionStride, normalStride, skinningStride, frustum, decalNormal, normalCutoff);
  654. indices += 3;
  655. }
  656. }
  657. else
  658. // 32-bit indices
  659. {
  660. const unsigned* indices = ((const unsigned*)indexData) + indexStart;
  661. const unsigned* indicesEnd = indices + indexCount;
  662. while (indices < indicesEnd)
  663. {
  664. GetFace(faces, target, batchIndex, indices[0], indices[1], indices[2], positionData, normalData, skinningData,
  665. positionStride, normalStride, skinningStride, frustum, decalNormal, normalCutoff);
  666. indices += 3;
  667. }
  668. }
  669. }
  670. else
  671. {
  672. // Non-indexed geometry
  673. unsigned indices = geometry->GetVertexStart();
  674. unsigned indicesEnd = indices + geometry->GetVertexCount();
  675. while (indices + 2 < indicesEnd)
  676. {
  677. GetFace(faces, target, batchIndex, indices, indices + 1, indices + 2, positionData, normalData, skinningData,
  678. positionStride, normalStride, skinningStride, frustum, decalNormal, normalCutoff);
  679. indices += 3;
  680. }
  681. }
  682. }
  683. void DecalSet::GetFace(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, unsigned i0, unsigned i1,
  684. unsigned i2, const unsigned char* positionData, const unsigned char* normalData, const unsigned char* skinningData,
  685. unsigned positionStride, unsigned normalStride, unsigned skinningStride, const Frustum& frustum, const Vector3& decalNormal,
  686. float normalCutoff)
  687. {
  688. bool hasNormals = normalData != 0;
  689. bool hasSkinning = skinned_ && skinningData != 0;
  690. const Vector3& v0 = *((const Vector3*)(&positionData[i0 * positionStride]));
  691. const Vector3& v1 = *((const Vector3*)(&positionData[i1 * positionStride]));
  692. const Vector3& v2 = *((const Vector3*)(&positionData[i2 * positionStride]));
  693. // Calculate unsmoothed face normals if no normal data
  694. Vector3 faceNormal = Vector3::ZERO;
  695. if (!hasNormals)
  696. {
  697. Vector3 dist1 = v1 - v0;
  698. Vector3 dist2 = v2 - v0;
  699. faceNormal = (dist1.CrossProduct(dist2)).Normalized();
  700. }
  701. const Vector3& n0 = hasNormals ? *((const Vector3*)(&normalData[i0 * normalStride])) : faceNormal;
  702. const Vector3& n1 = hasNormals ? *((const Vector3*)(&normalData[i1 * normalStride])) : faceNormal;
  703. const Vector3& n2 = hasNormals ? *((const Vector3*)(&normalData[i2 * normalStride])) : faceNormal;
  704. const unsigned char* s0 = hasSkinning ? &skinningData[i0 * skinningStride] : (const unsigned char*)0;
  705. const unsigned char* s1 = hasSkinning ? &skinningData[i1 * skinningStride] : (const unsigned char*)0;
  706. const unsigned char* s2 = hasSkinning ? &skinningData[i2 * skinningStride] : (const unsigned char*)0;
  707. // Check if face is too much away from the decal normal
  708. if (decalNormal.DotProduct((n0 + n1 + n2) / 3.0f) < normalCutoff)
  709. return;
  710. // Check if face is culled completely by any of the planes
  711. for (unsigned i = PLANE_FAR; i < NUM_FRUSTUM_PLANES; --i)
  712. {
  713. const Plane& plane = frustum.planes_[i];
  714. if (plane.Distance(v0) < 0.0f && plane.Distance(v1) < 0.0f && plane.Distance(v2) < 0.0f)
  715. return;
  716. }
  717. faces.Resize(faces.Size() + 1);
  718. PODVector<DecalVertex>& face = faces.Back();
  719. if (!hasSkinning)
  720. {
  721. face.Reserve(3);
  722. face.Push(DecalVertex(v0, n0));
  723. face.Push(DecalVertex(v1, n1));
  724. face.Push(DecalVertex(v2, n2));
  725. }
  726. else
  727. {
  728. const float* bw0 = (const float*)s0;
  729. const float* bw1 = (const float*)s1;
  730. const float* bw2 = (const float*)s2;
  731. const unsigned char* bi0 = s0 + sizeof(float) * 4;
  732. const unsigned char* bi1 = s1 + sizeof(float) * 4;
  733. const unsigned char* bi2 = s2 + sizeof(float) * 4;
  734. unsigned char nbi0[4];
  735. unsigned char nbi1[4];
  736. unsigned char nbi2[4];
  737. // Make sure all bones are found and that there is room in the skinning matrices
  738. if (!GetBones(target, batchIndex, bw0, bi0, nbi0) || !GetBones(target, batchIndex, bw1, bi1, nbi1) ||
  739. !GetBones(target, batchIndex, bw2, bi2, nbi2))
  740. return;
  741. face.Reserve(3);
  742. face.Push(DecalVertex(v0, n0, bw0, nbi0));
  743. face.Push(DecalVertex(v1, n1, bw1, nbi1));
  744. face.Push(DecalVertex(v2, n2, bw2, nbi2));
  745. }
  746. }
  747. bool DecalSet::GetBones(Drawable* target, unsigned batchIndex, const float* blendWeights, const unsigned char* blendIndices,
  748. unsigned char* newBlendIndices)
  749. {
  750. AnimatedModel* animatedModel = dynamic_cast<AnimatedModel*>(target);
  751. if (!animatedModel)
  752. return false;
  753. // Check whether target is using global or per-geometry skinning
  754. const Vector<PODVector<Matrix3x4> >& geometrySkinMatrices = animatedModel->GetGeometrySkinMatrices();
  755. const Vector<PODVector<unsigned> >& geometryBoneMappings = animatedModel->GetGeometryBoneMappings();
  756. for (unsigned i = 0; i < 4; ++i)
  757. {
  758. if (blendWeights[i] > 0.0f)
  759. {
  760. Bone* bone = 0;
  761. if (geometrySkinMatrices.Empty())
  762. bone = animatedModel->GetSkeleton().GetBone(blendIndices[i]);
  763. else if (blendIndices[i] < geometryBoneMappings[batchIndex].Size())
  764. bone = animatedModel->GetSkeleton().GetBone(geometryBoneMappings[batchIndex][blendIndices[i]]);
  765. if (!bone)
  766. {
  767. LOGWARNING("Out of range bone index for skinned decal");
  768. return false;
  769. }
  770. bool found = false;
  771. unsigned index;
  772. for (index = 0; index < bones_.Size(); ++index)
  773. {
  774. if (bones_[index].node_ == bone->node_)
  775. {
  776. // Check also that the offset matrix matches, in case we for example have a separate attachment AnimatedModel
  777. // with a different bind pose
  778. const float* offsetA = bones_[index].offsetMatrix_.Data();
  779. const float* offsetB = bone->offsetMatrix_.Data();
  780. unsigned j;
  781. for (j = 0; j < 12; ++j)
  782. {
  783. if (!Equals(offsetA[j], offsetB[j]))
  784. break;
  785. }
  786. if (j == 12)
  787. {
  788. found = true;
  789. break;
  790. }
  791. }
  792. }
  793. if (!found)
  794. {
  795. if (bones_.Size() >= MAX_SKIN_MATRICES)
  796. {
  797. LOGWARNING("Maximum skinned decal bone count reached");
  798. return false;
  799. }
  800. else
  801. {
  802. // Copy the bone from the model to the decal
  803. index = bones_.Size();
  804. bones_.Resize(bones_.Size() + 1);
  805. bones_[index] = *bone;
  806. skinMatrices_.Resize(skinMatrices_.Size() + 1);
  807. skinningDirty_ = true;
  808. // Start listening to bone transform changes to update skinning, update amount of shader data in the batch
  809. bone->node_->AddListener(this);
  810. UpdateBatch();
  811. }
  812. }
  813. newBlendIndices[i] = index;
  814. }
  815. else
  816. newBlendIndices[i] = 0;
  817. }
  818. return true;
  819. }
  820. void DecalSet::CalculateUVs(Decal& decal, const Matrix3x4& view, const Matrix4& projection, const Vector2& topLeftUV,
  821. const Vector2& bottomRightUV)
  822. {
  823. Matrix4 viewProj = projection * view;
  824. for (PODVector<DecalVertex>::Iterator i = decal.vertices_.Begin(); i != decal.vertices_.End(); ++i)
  825. {
  826. Vector3 projected = viewProj * i->position_;
  827. i->texCoord_ = Vector2(
  828. Lerp(topLeftUV.x_, bottomRightUV.x_, projected.x_ * 0.5f + 0.5f),
  829. Lerp(bottomRightUV.y_, topLeftUV.y_, projected.y_ * 0.5f + 0.5f)
  830. );
  831. }
  832. }
  833. void DecalSet::TransformVertices(Decal& decal, const Matrix3x4& transform)
  834. {
  835. for (PODVector<DecalVertex>::Iterator i = decal.vertices_.Begin(); i != decal.vertices_.End(); ++i)
  836. {
  837. i->position_ = transform * i->position_;
  838. i->normal_ = (transform * i->normal_).Normalized();
  839. }
  840. }
  841. List<Decal>::Iterator DecalSet::RemoveDecal(List<Decal>::Iterator i)
  842. {
  843. numVertices_ -= i->vertices_.Size();
  844. numIndices_ -= i->indices_.Size();
  845. MarkDecalsDirty();
  846. return decals_.Erase(i);
  847. }
  848. void DecalSet::MarkDecalsDirty()
  849. {
  850. if (!boundingBoxDirty_)
  851. {
  852. boundingBoxDirty_ = true;
  853. OnMarkedDirty(node_);
  854. }
  855. bufferDirty_ = true;
  856. }
  857. void DecalSet::CalculateBoundingBox()
  858. {
  859. boundingBox_.Clear();
  860. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  861. boundingBox_.Merge(i->boundingBox_);
  862. boundingBoxDirty_ = false;
  863. }
  864. void DecalSet::UpdateBufferSize()
  865. {
  866. vertexBuffer_->SetSize(maxVertices_, skinned_ ? SKINNED_ELEMENT_MASK : STATIC_ELEMENT_MASK);
  867. indexBuffer_->SetSize(maxIndices_, false);
  868. geometry_->SetVertexBuffer(0, vertexBuffer_);
  869. bufferDirty_ = true;
  870. bufferSizeDirty_ = false;
  871. }
  872. void DecalSet::UpdateBuffers()
  873. {
  874. geometry_->SetDrawRange(TRIANGLE_LIST, 0, numIndices_, 0, numVertices_);
  875. float* vertices = (float*)vertexBuffer_->Lock(0, numVertices_);
  876. unsigned short* indices = (unsigned short*)indexBuffer_->Lock(0, numIndices_);
  877. unsigned short indexStart = 0;
  878. if (vertices && indices)
  879. {
  880. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  881. {
  882. for (unsigned j = 0; j < i->vertices_.Size(); ++j)
  883. {
  884. const DecalVertex& vertex = i->vertices_[j];
  885. *vertices++ = vertex.position_.x_;
  886. *vertices++ = vertex.position_.y_;
  887. *vertices++ = vertex.position_.z_;
  888. *vertices++ = vertex.normal_.x_;
  889. *vertices++ = vertex.normal_.y_;
  890. *vertices++ = vertex.normal_.z_;
  891. *vertices++ = vertex.texCoord_.x_;
  892. *vertices++ = vertex.texCoord_.y_;
  893. *vertices++ = vertex.tangent_.x_;
  894. *vertices++ = vertex.tangent_.y_;
  895. *vertices++ = vertex.tangent_.z_;
  896. *vertices++ = vertex.tangent_.w_;
  897. if (skinned_)
  898. {
  899. *vertices++ = vertex.blendWeights_[0];
  900. *vertices++ = vertex.blendWeights_[1];
  901. *vertices++ = vertex.blendWeights_[2];
  902. *vertices++ = vertex.blendWeights_[3];
  903. *vertices++ = *((float*)vertex.blendIndices_);
  904. }
  905. }
  906. for (unsigned j = 0; j < i->indices_.Size(); ++j)
  907. *indices++ = i->indices_[j] + indexStart;
  908. indexStart += i->vertices_.Size();
  909. }
  910. }
  911. vertexBuffer_->Unlock();
  912. vertexBuffer_->ClearDataLost();
  913. indexBuffer_->Unlock();
  914. indexBuffer_->ClearDataLost();
  915. bufferDirty_ = false;
  916. }
  917. void DecalSet::UpdateSkinning()
  918. {
  919. // Use model's world transform in case a bone is missing
  920. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  921. for (unsigned i = 0; i < bones_.Size(); ++i)
  922. {
  923. const Bone& bone = bones_[i];
  924. if (bone.node_)
  925. skinMatrices_[i] = bone.node_->GetWorldTransform() * bone.offsetMatrix_;
  926. else
  927. skinMatrices_[i] = worldTransform;
  928. }
  929. skinningDirty_ = false;
  930. }
  931. void DecalSet::UpdateBatch()
  932. {
  933. if (skinMatrices_.Size())
  934. {
  935. batches_[0].geometryType_ = GEOM_SKINNED;
  936. batches_[0].shaderData_ = skinMatrices_[0].Data();
  937. batches_[0].shaderDataSize_ = skinMatrices_.Size() * 12;
  938. }
  939. else
  940. {
  941. batches_[0].geometryType_ = GEOM_STATIC;
  942. batches_[0].shaderData_ = 0;
  943. batches_[0].shaderDataSize_ = 0;
  944. }
  945. }
  946. void DecalSet::AssignBoneNodes()
  947. {
  948. assignBonesPending_ = false;
  949. if (!node_)
  950. return;
  951. // Find the bone nodes from the node hierarchy and add listeners
  952. for (Vector<Bone>::Iterator i = bones_.Begin(); i != bones_.End(); ++i)
  953. {
  954. Node* boneNode = node_->GetChild(i->name_, true);
  955. if (boneNode)
  956. boneNode->AddListener(this);
  957. i->node_ = boneNode;
  958. }
  959. }
  960. void DecalSet::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  961. {
  962. using namespace ScenePostUpdate;
  963. float timeStep = eventData[P_TIMESTEP].GetFloat();
  964. for (List<Decal>::Iterator i = decals_.Begin(); i != decals_.End();)
  965. {
  966. i->timer_ += timeStep;
  967. // Remove the decal if time to live expired
  968. if (i->timeToLive_ > 0.0f && i->timer_ > i->timeToLive_)
  969. i = RemoveDecal(i);
  970. else
  971. ++i;
  972. }
  973. }
  974. }