DecalSet.cpp 37 KB

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