CustomGeometry.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. //
  2. // Copyright (c) 2008-2022 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 "../Graphics/Batch.h"
  26. #include "../Graphics/Camera.h"
  27. #include "../Graphics/CustomGeometry.h"
  28. #include "../Graphics/Geometry.h"
  29. #include "../Graphics/Material.h"
  30. #include "../Graphics/OcclusionBuffer.h"
  31. #include "../Graphics/OctreeQuery.h"
  32. #include "../Graphics/VertexBuffer.h"
  33. #include "../IO/Log.h"
  34. #include "../IO/MemoryBuffer.h"
  35. #include "../Resource/ResourceCache.h"
  36. #include "../Scene/Node.h"
  37. #include "../DebugNew.h"
  38. namespace Urho3D
  39. {
  40. extern const char* GEOMETRY_CATEGORY;
  41. CustomGeometry::CustomGeometry(Context* context)
  42. : Drawable(context, DRAWABLE_GEOMETRY)
  43. , vertexBuffer_(new VertexBuffer(context))
  44. , elementMask_(MASK_POSITION)
  45. , geometryIndex_(0)
  46. , materialsAttr_(Material::GetTypeStatic())
  47. , dynamic_(false)
  48. {
  49. vertexBuffer_->SetShadowed(true);
  50. SetNumGeometries(1);
  51. }
  52. CustomGeometry::~CustomGeometry() = default;
  53. void CustomGeometry::RegisterObject(Context* context)
  54. {
  55. context->RegisterFactory<CustomGeometry>(GEOMETRY_CATEGORY);
  56. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  57. URHO3D_ATTRIBUTE("Dynamic Vertex Buffer", bool, dynamic_, false, AM_DEFAULT);
  58. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Geometry Data", GetGeometryDataAttr, SetGeometryDataAttr, PODVector<unsigned char>,
  59. Variant::emptyBuffer, AM_FILE | AM_NOEDIT);
  60. URHO3D_ACCESSOR_ATTRIBUTE("Materials", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList,
  61. ResourceRefList(Material::GetTypeStatic()), AM_DEFAULT);
  62. URHO3D_ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
  63. URHO3D_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  64. URHO3D_ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
  65. URHO3D_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  66. URHO3D_ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  67. URHO3D_ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  68. URHO3D_COPY_BASE_ATTRIBUTES(Drawable);
  69. }
  70. void CustomGeometry::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  71. {
  72. RayQueryLevel level = query.level_;
  73. switch (level)
  74. {
  75. case RAY_AABB:
  76. Drawable::ProcessRayQuery(query, results);
  77. break;
  78. case RAY_OBB:
  79. case RAY_TRIANGLE:
  80. {
  81. Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
  82. Ray localRay = query.ray_.Transformed(inverse);
  83. float distance = localRay.HitDistance(boundingBox_);
  84. Vector3 normal = -query.ray_.direction_;
  85. if (level == RAY_TRIANGLE && distance < query.maxDistance_)
  86. {
  87. distance = M_INFINITY;
  88. for (unsigned i = 0; i < batches_.Size(); ++i)
  89. {
  90. Geometry* geometry = batches_[i].geometry_;
  91. if (geometry)
  92. {
  93. Vector3 geometryNormal;
  94. float geometryDistance = geometry->GetHitDistance(localRay, &geometryNormal);
  95. if (geometryDistance < query.maxDistance_ && geometryDistance < distance)
  96. {
  97. distance = geometryDistance;
  98. normal = (node_->GetWorldTransform() * Vector4(geometryNormal, 0.0f)).Normalized();
  99. }
  100. }
  101. }
  102. }
  103. if (distance < query.maxDistance_)
  104. {
  105. RayQueryResult result;
  106. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  107. result.normal_ = normal;
  108. result.distance_ = distance;
  109. result.drawable_ = this;
  110. result.node_ = node_;
  111. result.subObject_ = M_MAX_UNSIGNED;
  112. results.Push(result);
  113. }
  114. }
  115. break;
  116. case RAY_TRIANGLE_UV:
  117. URHO3D_LOGWARNING("RAY_TRIANGLE_UV query level is not supported for CustomGeometry component");
  118. break;
  119. }
  120. }
  121. Geometry* CustomGeometry::GetLodGeometry(unsigned batchIndex, unsigned level)
  122. {
  123. return batchIndex < geometries_.Size() ? geometries_[batchIndex] : nullptr;
  124. }
  125. unsigned CustomGeometry::GetNumOccluderTriangles()
  126. {
  127. unsigned triangles = 0;
  128. for (unsigned i = 0; i < batches_.Size(); ++i)
  129. {
  130. Geometry* geometry = GetLodGeometry(i, 0);
  131. if (!geometry)
  132. continue;
  133. // Check that the material is suitable for occlusion (default material always is)
  134. Material* mat = batches_[i].material_;
  135. if (mat && !mat->GetOcclusion())
  136. continue;
  137. triangles += geometry->GetVertexCount() / 3;
  138. }
  139. return triangles;
  140. }
  141. bool CustomGeometry::DrawOcclusion(OcclusionBuffer* buffer)
  142. {
  143. bool success = true;
  144. for (unsigned i = 0; i < batches_.Size(); ++i)
  145. {
  146. Geometry* geometry = GetLodGeometry(i, 0);
  147. if (!geometry)
  148. continue;
  149. // Check that the material is suitable for occlusion (default material always is) and set culling mode
  150. Material* material = batches_[i].material_;
  151. if (material)
  152. {
  153. if (!material->GetOcclusion())
  154. continue;
  155. buffer->SetCullMode(material->GetCullMode());
  156. }
  157. else
  158. buffer->SetCullMode(CULL_CCW);
  159. const unsigned char* vertexData;
  160. unsigned vertexSize;
  161. const unsigned char* indexData;
  162. unsigned indexSize;
  163. const PODVector<VertexElement>* elements;
  164. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elements);
  165. // Check for valid geometry data
  166. if (!vertexData || !elements || VertexBuffer::GetElementOffset(*elements, TYPE_VECTOR3, SEM_POSITION) != 0)
  167. continue;
  168. // Draw and check for running out of triangles
  169. success = buffer->AddTriangles(node_->GetWorldTransform(), vertexData, vertexSize, geometry->GetVertexStart(),
  170. geometry->GetVertexCount());
  171. if (!success)
  172. break;
  173. }
  174. return success;
  175. }
  176. void CustomGeometry::Clear()
  177. {
  178. elementMask_ = MASK_POSITION;
  179. batches_.Clear();
  180. geometries_.Clear();
  181. primitiveTypes_.Clear();
  182. vertices_.Clear();
  183. }
  184. void CustomGeometry::SetNumGeometries(unsigned num)
  185. {
  186. batches_.Resize(num);
  187. geometries_.Resize(num);
  188. primitiveTypes_.Resize(num);
  189. vertices_.Resize(num);
  190. for (unsigned i = 0; i < geometries_.Size(); ++i)
  191. {
  192. if (!geometries_[i])
  193. geometries_[i] = new Geometry(context_);
  194. batches_[i].geometry_ = geometries_[i];
  195. }
  196. }
  197. void CustomGeometry::SetDynamic(bool enable)
  198. {
  199. dynamic_ = enable;
  200. MarkNetworkUpdate();
  201. }
  202. void CustomGeometry::BeginGeometry(unsigned index, PrimitiveType type)
  203. {
  204. if (index > geometries_.Size())
  205. {
  206. URHO3D_LOGERROR("Geometry index out of bounds");
  207. return;
  208. }
  209. geometryIndex_ = index;
  210. primitiveTypes_[index] = type;
  211. vertices_[index].Clear();
  212. // If beginning the first geometry, reset the element mask
  213. if (!index)
  214. elementMask_ = MASK_POSITION;
  215. }
  216. void CustomGeometry::DefineVertex(const Vector3& position)
  217. {
  218. if (vertices_.Size() < geometryIndex_)
  219. return;
  220. vertices_[geometryIndex_].Resize(vertices_[geometryIndex_].Size() + 1);
  221. vertices_[geometryIndex_].Back().position_ = position;
  222. }
  223. void CustomGeometry::DefineNormal(const Vector3& normal)
  224. {
  225. if (vertices_.Size() < geometryIndex_ || vertices_[geometryIndex_].Empty())
  226. return;
  227. vertices_[geometryIndex_].Back().normal_ = normal;
  228. elementMask_ |= MASK_NORMAL;
  229. }
  230. void CustomGeometry::DefineColor(const Color& color)
  231. {
  232. if (vertices_.Size() < geometryIndex_ || vertices_[geometryIndex_].Empty())
  233. return;
  234. vertices_[geometryIndex_].Back().color_ = color.ToUInt();
  235. elementMask_ |= MASK_COLOR;
  236. }
  237. void CustomGeometry::DefineTexCoord(const Vector2& texCoord)
  238. {
  239. if (vertices_.Size() < geometryIndex_ || vertices_[geometryIndex_].Empty())
  240. return;
  241. vertices_[geometryIndex_].Back().texCoord_ = texCoord;
  242. elementMask_ |= MASK_TEXCOORD1;
  243. }
  244. void CustomGeometry::DefineTangent(const Vector4& tangent)
  245. {
  246. if (vertices_.Size() < geometryIndex_ || vertices_[geometryIndex_].Empty())
  247. return;
  248. vertices_[geometryIndex_].Back().tangent_ = tangent;
  249. elementMask_ |= MASK_TANGENT;
  250. }
  251. void CustomGeometry::DefineGeometry(unsigned index, PrimitiveType type, unsigned numVertices, bool hasNormals,
  252. bool hasColors, bool hasTexCoords, bool hasTangents)
  253. {
  254. if (index > geometries_.Size())
  255. {
  256. URHO3D_LOGERROR("Geometry index out of bounds");
  257. return;
  258. }
  259. geometryIndex_ = index;
  260. primitiveTypes_[index] = type;
  261. vertices_[index].Resize(numVertices);
  262. // If defining the first geometry, reset the element mask
  263. if (!index)
  264. elementMask_ = MASK_POSITION;
  265. if (hasNormals)
  266. elementMask_ |= MASK_NORMAL;
  267. if (hasColors)
  268. elementMask_ |= MASK_COLOR;
  269. if (hasTexCoords)
  270. elementMask_ |= MASK_TEXCOORD1;
  271. if (hasTangents)
  272. elementMask_ |= MASK_TANGENT;
  273. }
  274. void CustomGeometry::Commit()
  275. {
  276. URHO3D_PROFILE(CommitCustomGeometry);
  277. unsigned totalVertices = 0;
  278. boundingBox_.Clear();
  279. for (unsigned i = 0; i < vertices_.Size(); ++i)
  280. {
  281. totalVertices += vertices_[i].Size();
  282. for (unsigned j = 0; j < vertices_[i].Size(); ++j)
  283. boundingBox_.Merge(vertices_[i][j].position_);
  284. }
  285. // Make sure world-space bounding box will be updated
  286. OnMarkedDirty(node_);
  287. // Resize (recreate) the vertex buffer only if necessary
  288. if (vertexBuffer_->GetVertexCount() != totalVertices || vertexBuffer_->GetElementMask() != elementMask_ ||
  289. vertexBuffer_->IsDynamic() != dynamic_)
  290. vertexBuffer_->SetSize(totalVertices, elementMask_, dynamic_);
  291. if (totalVertices)
  292. {
  293. auto* dest = (unsigned char*)vertexBuffer_->Lock(0, totalVertices, true);
  294. if (dest)
  295. {
  296. unsigned vertexStart = 0;
  297. for (unsigned i = 0; i < vertices_.Size(); ++i)
  298. {
  299. unsigned vertexCount = 0;
  300. for (unsigned j = 0; j < vertices_[i].Size(); ++j)
  301. {
  302. *((Vector3*)dest) = vertices_[i][j].position_;
  303. dest += sizeof(Vector3);
  304. if (elementMask_ & MASK_NORMAL)
  305. {
  306. *((Vector3*)dest) = vertices_[i][j].normal_;
  307. dest += sizeof(Vector3);
  308. }
  309. if (elementMask_ & MASK_COLOR)
  310. {
  311. *((unsigned*)dest) = vertices_[i][j].color_;
  312. dest += sizeof(unsigned);
  313. }
  314. if (elementMask_ & MASK_TEXCOORD1)
  315. {
  316. *((Vector2*)dest) = vertices_[i][j].texCoord_;
  317. dest += sizeof(Vector2);
  318. }
  319. if (elementMask_ & MASK_TANGENT)
  320. {
  321. *((Vector4*)dest) = vertices_[i][j].tangent_;
  322. dest += sizeof(Vector4);
  323. }
  324. ++vertexCount;
  325. }
  326. geometries_[i]->SetVertexBuffer(0, vertexBuffer_);
  327. geometries_[i]->SetDrawRange(primitiveTypes_[i], 0, 0, vertexStart, vertexCount);
  328. vertexStart += vertexCount;
  329. }
  330. vertexBuffer_->Unlock();
  331. }
  332. else
  333. URHO3D_LOGERROR("Failed to lock custom geometry vertex buffer");
  334. }
  335. else
  336. {
  337. for (unsigned i = 0; i < geometries_.Size(); ++i)
  338. {
  339. geometries_[i]->SetVertexBuffer(0, vertexBuffer_);
  340. geometries_[i]->SetDrawRange(primitiveTypes_[i], 0, 0, 0, 0);
  341. }
  342. }
  343. vertexBuffer_->ClearDataLost();
  344. }
  345. void CustomGeometry::SetMaterial(Material* material)
  346. {
  347. for (unsigned i = 0; i < batches_.Size(); ++i)
  348. batches_[i].material_ = material;
  349. MarkNetworkUpdate();
  350. }
  351. bool CustomGeometry::SetMaterial(unsigned index, Material* material)
  352. {
  353. if (index >= batches_.Size())
  354. {
  355. URHO3D_LOGERROR("Material index out of bounds");
  356. return false;
  357. }
  358. batches_[index].material_ = material;
  359. MarkNetworkUpdate();
  360. return true;
  361. }
  362. unsigned CustomGeometry::GetNumVertices(unsigned index) const
  363. {
  364. return index < vertices_.Size() ? vertices_[index].Size() : 0;
  365. }
  366. Material* CustomGeometry::GetMaterial(unsigned index) const
  367. {
  368. return index < batches_.Size() ? batches_[index].material_ : nullptr;
  369. }
  370. CustomGeometryVertex* CustomGeometry::GetVertex(unsigned geometryIndex, unsigned vertexNum)
  371. {
  372. return (geometryIndex < vertices_.Size() && vertexNum < vertices_[geometryIndex].Size())
  373. ? &vertices_[geometryIndex][vertexNum]
  374. : nullptr;
  375. }
  376. void CustomGeometry::SetGeometryDataAttr(const PODVector<unsigned char>& value)
  377. {
  378. if (value.Empty())
  379. return;
  380. MemoryBuffer buffer(value);
  381. SetNumGeometries(buffer.ReadVLE());
  382. elementMask_ = VertexMaskFlags(buffer.ReadUInt());
  383. for (unsigned i = 0; i < geometries_.Size(); ++i)
  384. {
  385. unsigned numVertices = buffer.ReadVLE();
  386. vertices_[i].Resize(numVertices);
  387. primitiveTypes_[i] = (PrimitiveType)buffer.ReadUByte();
  388. for (unsigned j = 0; j < numVertices; ++j)
  389. {
  390. if (elementMask_ & MASK_POSITION)
  391. vertices_[i][j].position_ = buffer.ReadVector3();
  392. if (elementMask_ & MASK_NORMAL)
  393. vertices_[i][j].normal_ = buffer.ReadVector3();
  394. if (elementMask_ & MASK_COLOR)
  395. vertices_[i][j].color_ = buffer.ReadUInt();
  396. if (elementMask_ & MASK_TEXCOORD1)
  397. vertices_[i][j].texCoord_ = buffer.ReadVector2();
  398. if (elementMask_ & MASK_TANGENT)
  399. vertices_[i][j].tangent_ = buffer.ReadVector4();
  400. }
  401. }
  402. Commit();
  403. }
  404. void CustomGeometry::SetMaterialsAttr(const ResourceRefList& value)
  405. {
  406. auto* cache = GetSubsystem<ResourceCache>();
  407. for (unsigned i = 0; i < value.names_.Size(); ++i)
  408. SetMaterial(i, cache->GetResource<Material>(value.names_[i]));
  409. }
  410. PODVector<unsigned char> CustomGeometry::GetGeometryDataAttr() const
  411. {
  412. VectorBuffer ret;
  413. ret.WriteVLE(geometries_.Size());
  414. ret.WriteUInt(elementMask_);
  415. for (unsigned i = 0; i < geometries_.Size(); ++i)
  416. {
  417. unsigned numVertices = vertices_[i].Size();
  418. ret.WriteVLE(numVertices);
  419. ret.WriteUByte(primitiveTypes_[i]);
  420. for (unsigned j = 0; j < numVertices; ++j)
  421. {
  422. if (elementMask_ & MASK_POSITION)
  423. ret.WriteVector3(vertices_[i][j].position_);
  424. if (elementMask_ & MASK_NORMAL)
  425. ret.WriteVector3(vertices_[i][j].normal_);
  426. if (elementMask_ & MASK_COLOR)
  427. ret.WriteUInt(vertices_[i][j].color_);
  428. if (elementMask_ & MASK_TEXCOORD1)
  429. ret.WriteVector2(vertices_[i][j].texCoord_);
  430. if (elementMask_ & MASK_TANGENT)
  431. ret.WriteVector4(vertices_[i][j].tangent_);
  432. }
  433. }
  434. return ret.GetBuffer();
  435. }
  436. const ResourceRefList& CustomGeometry::GetMaterialsAttr() const
  437. {
  438. materialsAttr_.names_.Resize(batches_.Size());
  439. for (unsigned i = 0; i < batches_.Size(); ++i)
  440. materialsAttr_.names_[i] = GetResourceName(batches_[i].material_);
  441. return materialsAttr_;
  442. }
  443. void CustomGeometry::OnWorldBoundingBoxUpdate()
  444. {
  445. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  446. }
  447. } // namespace Urho3D