CustomGeometry.cpp 16 KB

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