CustomGeometry.cpp 16 KB

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