DecalSet.cpp 39 KB

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