DecalSet.cpp 38 KB

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