CustomGeometry.cpp 17 KB

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