DecalSet.cpp 38 KB

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