DecalSet.cpp 38 KB

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