StaticModel.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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/AnimatedModel.h"
  26. #include "../Graphics/Batch.h"
  27. #include "../Graphics/Camera.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/FileSystem.h"
  34. #include "../IO/Log.h"
  35. #include "../Resource/ResourceCache.h"
  36. #include "../Resource/ResourceEvents.h"
  37. #include "../DebugNew.h"
  38. namespace Urho3D
  39. {
  40. extern const char* GEOMETRY_CATEGORY;
  41. StaticModel::StaticModel(Context* context) :
  42. Drawable(context, DRAWABLE_GEOMETRY),
  43. occlusionLodLevel_(M_MAX_UNSIGNED),
  44. materialsAttr_(Material::GetTypeStatic())
  45. {
  46. }
  47. StaticModel::~StaticModel() = default;
  48. void StaticModel::RegisterObject(Context* context)
  49. {
  50. context->RegisterFactory<StaticModel>(GEOMETRY_CATEGORY);
  51. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  52. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  53. URHO3D_ACCESSOR_ATTRIBUTE("Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()),
  54. AM_DEFAULT);
  55. URHO3D_ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
  56. URHO3D_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  57. URHO3D_ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
  58. URHO3D_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  59. URHO3D_ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  60. URHO3D_ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  61. URHO3D_COPY_BASE_ATTRIBUTES(Drawable);
  62. URHO3D_ATTRIBUTE("Occlusion LOD Level", int, occlusionLodLevel_, M_MAX_UNSIGNED, AM_DEFAULT);
  63. }
  64. void StaticModel::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  65. {
  66. RayQueryLevel level = query.level_;
  67. switch (level)
  68. {
  69. case RAY_AABB:
  70. Drawable::ProcessRayQuery(query, results);
  71. break;
  72. case RAY_OBB:
  73. case RAY_TRIANGLE:
  74. case RAY_TRIANGLE_UV:
  75. Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
  76. Ray localRay = query.ray_.Transformed(inverse);
  77. float distance = localRay.HitDistance(boundingBox_);
  78. Vector3 normal = -query.ray_.direction_;
  79. Vector2 geometryUV;
  80. unsigned hitBatch = M_MAX_UNSIGNED;
  81. if (level >= RAY_TRIANGLE && distance < query.maxDistance_)
  82. {
  83. distance = M_INFINITY;
  84. for (unsigned i = 0; i < batches_.Size(); ++i)
  85. {
  86. Geometry* geometry = batches_[i].geometry_;
  87. if (geometry)
  88. {
  89. Vector3 geometryNormal;
  90. float geometryDistance = level == RAY_TRIANGLE ? geometry->GetHitDistance(localRay, &geometryNormal) :
  91. geometry->GetHitDistance(localRay, &geometryNormal, &geometryUV);
  92. if (geometryDistance < query.maxDistance_ && geometryDistance < distance)
  93. {
  94. distance = geometryDistance;
  95. normal = (node_->GetWorldTransform() * Vector4(geometryNormal, 0.0f)).Normalized();
  96. hitBatch = i;
  97. }
  98. }
  99. }
  100. }
  101. if (distance < query.maxDistance_)
  102. {
  103. RayQueryResult result;
  104. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  105. result.normal_ = normal;
  106. result.textureUV_ = geometryUV;
  107. result.distance_ = distance;
  108. result.drawable_ = this;
  109. result.node_ = node_;
  110. result.subObject_ = hitBatch;
  111. results.Push(result);
  112. }
  113. break;
  114. }
  115. }
  116. void StaticModel::UpdateBatches(const FrameInfo& frame)
  117. {
  118. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  119. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  120. if (batches_.Size() == 1)
  121. batches_[0].distance_ = distance_;
  122. else
  123. {
  124. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  125. for (unsigned i = 0; i < batches_.Size(); ++i)
  126. batches_[i].distance_ = frame.camera_->GetDistance(worldTransform * geometryData_[i].center_);
  127. }
  128. float scale = worldBoundingBox.Size().DotProduct(DOT_SCALE);
  129. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  130. if (newLodDistance != lodDistance_)
  131. {
  132. lodDistance_ = newLodDistance;
  133. CalculateLodLevels();
  134. }
  135. }
  136. Geometry* StaticModel::GetLodGeometry(unsigned batchIndex, unsigned level)
  137. {
  138. if (batchIndex >= geometries_.Size())
  139. return nullptr;
  140. // If level is out of range, use visible geometry
  141. if (level < geometries_[batchIndex].Size())
  142. return geometries_[batchIndex][level];
  143. else
  144. return batches_[batchIndex].geometry_;
  145. }
  146. unsigned StaticModel::GetNumOccluderTriangles()
  147. {
  148. unsigned triangles = 0;
  149. for (unsigned i = 0; i < batches_.Size(); ++i)
  150. {
  151. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  152. if (!geometry)
  153. continue;
  154. // Check that the material is suitable for occlusion (default material always is)
  155. Material* mat = batches_[i].material_;
  156. if (mat && !mat->GetOcclusion())
  157. continue;
  158. triangles += geometry->GetIndexCount() / 3;
  159. }
  160. return triangles;
  161. }
  162. bool StaticModel::DrawOcclusion(OcclusionBuffer* buffer)
  163. {
  164. for (unsigned i = 0; i < batches_.Size(); ++i)
  165. {
  166. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  167. if (!geometry)
  168. continue;
  169. // Check that the material is suitable for occlusion (default material always is) and set culling mode
  170. Material* material = batches_[i].material_;
  171. if (material)
  172. {
  173. if (!material->GetOcclusion())
  174. continue;
  175. buffer->SetCullMode(material->GetCullMode());
  176. }
  177. else
  178. buffer->SetCullMode(CULL_CCW);
  179. const unsigned char* vertexData;
  180. unsigned vertexSize;
  181. const unsigned char* indexData;
  182. unsigned indexSize;
  183. const PODVector<VertexElement>* elements;
  184. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elements);
  185. // Check for valid geometry data
  186. if (!vertexData || !indexData || !elements || VertexBuffer::GetElementOffset(*elements, TYPE_VECTOR3, SEM_POSITION) != 0)
  187. continue;
  188. unsigned indexStart = geometry->GetIndexStart();
  189. unsigned indexCount = geometry->GetIndexCount();
  190. // Draw and check for running out of triangles
  191. if (!buffer->AddTriangles(node_->GetWorldTransform(), vertexData, vertexSize, indexData, indexSize, indexStart, indexCount))
  192. return false;
  193. }
  194. return true;
  195. }
  196. void StaticModel::SetModel(Model* model)
  197. {
  198. if (model == model_)
  199. return;
  200. if (!node_)
  201. {
  202. URHO3D_LOGERROR("Can not set model while model component is not attached to a scene node");
  203. return;
  204. }
  205. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  206. if (model_)
  207. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  208. model_ = model;
  209. if (model)
  210. {
  211. SubscribeToEvent(model, E_RELOADFINISHED, URHO3D_HANDLER(StaticModel, HandleModelReloadFinished));
  212. // Copy the subgeometry & LOD level structure
  213. SetNumGeometries(model->GetNumGeometries());
  214. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  215. const PODVector<Vector3>& geometryCenters = model->GetGeometryCenters();
  216. const Matrix3x4* worldTransform = node_ ? &node_->GetWorldTransform() : nullptr;
  217. for (unsigned i = 0; i < geometries.Size(); ++i)
  218. {
  219. batches_[i].worldTransform_ = worldTransform;
  220. geometries_[i] = geometries[i];
  221. geometryData_[i].center_ = geometryCenters[i];
  222. }
  223. SetBoundingBox(model->GetBoundingBox());
  224. ResetLodLevels();
  225. }
  226. else
  227. {
  228. SetNumGeometries(0);
  229. SetBoundingBox(BoundingBox());
  230. }
  231. MarkNetworkUpdate();
  232. }
  233. void StaticModel::SetMaterial(Material* material)
  234. {
  235. for (unsigned i = 0; i < batches_.Size(); ++i)
  236. batches_[i].material_ = material;
  237. MarkNetworkUpdate();
  238. }
  239. bool StaticModel::SetMaterial(unsigned index, Material* material)
  240. {
  241. if (index >= batches_.Size())
  242. {
  243. URHO3D_LOGERROR("Material index out of bounds");
  244. return false;
  245. }
  246. batches_[index].material_ = material;
  247. MarkNetworkUpdate();
  248. return true;
  249. }
  250. void StaticModel::SetOcclusionLodLevel(unsigned level)
  251. {
  252. occlusionLodLevel_ = level;
  253. MarkNetworkUpdate();
  254. }
  255. void StaticModel::ApplyMaterialList(const String& fileName)
  256. {
  257. String useFileName = fileName;
  258. if (useFileName.Trimmed().Empty() && model_)
  259. useFileName = ReplaceExtension(model_->GetName(), ".txt");
  260. auto* cache = GetSubsystem<ResourceCache>();
  261. SharedPtr<File> file = cache->GetFile(useFileName, false);
  262. if (!file)
  263. return;
  264. unsigned index = 0;
  265. while (!file->IsEof() && index < batches_.Size())
  266. {
  267. auto* material = cache->GetResource<Material>(file->ReadLine());
  268. if (material)
  269. SetMaterial(index, material);
  270. ++index;
  271. }
  272. }
  273. Material* StaticModel::GetMaterial(unsigned index) const
  274. {
  275. return index < batches_.Size() ? batches_[index].material_ : nullptr;
  276. }
  277. bool StaticModel::IsInside(const Vector3& point) const
  278. {
  279. if (!node_)
  280. return false;
  281. Vector3 localPosition = node_->GetWorldTransform().Inverse() * point;
  282. return IsInsideLocal(localPosition);
  283. }
  284. bool StaticModel::IsInsideLocal(const Vector3& point) const
  285. {
  286. // Early-out if point is not inside bounding box
  287. if (boundingBox_.IsInside(point) == OUTSIDE)
  288. return false;
  289. Ray localRay(point, Vector3(1.0f, -1.0f, 1.0f));
  290. for (unsigned i = 0; i < batches_.Size(); ++i)
  291. {
  292. Geometry* geometry = batches_[i].geometry_;
  293. if (geometry)
  294. {
  295. if (geometry->IsInside(localRay))
  296. return true;
  297. }
  298. }
  299. return false;
  300. }
  301. void StaticModel::SetBoundingBox(const BoundingBox& box)
  302. {
  303. boundingBox_ = box;
  304. OnMarkedDirty(node_);
  305. }
  306. void StaticModel::SetNumGeometries(unsigned num)
  307. {
  308. batches_.Resize(num);
  309. geometries_.Resize(num);
  310. geometryData_.Resize(num);
  311. ResetLodLevels();
  312. }
  313. void StaticModel::SetModelAttr(const ResourceRef& value)
  314. {
  315. auto* cache = GetSubsystem<ResourceCache>();
  316. SetModel(cache->GetResource<Model>(value.name_));
  317. }
  318. void StaticModel::SetMaterialsAttr(const ResourceRefList& value)
  319. {
  320. auto* cache = GetSubsystem<ResourceCache>();
  321. for (unsigned i = 0; i < value.names_.Size(); ++i)
  322. SetMaterial(i, cache->GetResource<Material>(value.names_[i]));
  323. }
  324. ResourceRef StaticModel::GetModelAttr() const
  325. {
  326. return GetResourceRef(model_, Model::GetTypeStatic());
  327. }
  328. const ResourceRefList& StaticModel::GetMaterialsAttr() const
  329. {
  330. materialsAttr_.names_.Resize(batches_.Size());
  331. for (unsigned i = 0; i < batches_.Size(); ++i)
  332. materialsAttr_.names_[i] = GetResourceName(GetMaterial(i));
  333. return materialsAttr_;
  334. }
  335. void StaticModel::OnWorldBoundingBoxUpdate()
  336. {
  337. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  338. }
  339. void StaticModel::ResetLodLevels()
  340. {
  341. // Ensure that each subgeometry has at least one LOD level, and reset the current LOD level
  342. for (unsigned i = 0; i < batches_.Size(); ++i)
  343. {
  344. if (!geometries_[i].Size())
  345. geometries_[i].Resize(1);
  346. batches_[i].geometry_ = geometries_[i][0];
  347. geometryData_[i].lodLevel_ = 0;
  348. }
  349. // Find out the real LOD levels on next geometry update
  350. lodDistance_ = M_INFINITY;
  351. }
  352. void StaticModel::CalculateLodLevels()
  353. {
  354. for (unsigned i = 0; i < batches_.Size(); ++i)
  355. {
  356. const Vector<SharedPtr<Geometry> >& batchGeometries = geometries_[i];
  357. // If only one LOD geometry, no reason to go through the LOD calculation
  358. if (batchGeometries.Size() <= 1)
  359. continue;
  360. unsigned j;
  361. for (j = 1; j < batchGeometries.Size(); ++j)
  362. {
  363. if (batchGeometries[j] && lodDistance_ <= batchGeometries[j]->GetLodDistance())
  364. break;
  365. }
  366. unsigned newLodLevel = j - 1;
  367. if (geometryData_[i].lodLevel_ != newLodLevel)
  368. {
  369. geometryData_[i].lodLevel_ = newLodLevel;
  370. batches_[i].geometry_ = batchGeometries[newLodLevel];
  371. }
  372. }
  373. }
  374. void StaticModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  375. {
  376. Model* currentModel = model_;
  377. model_.Reset(); // Set null to allow to be re-set
  378. SetModel(currentModel);
  379. }
  380. }