StaticModel.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Batch.h"
  25. #include "Camera.h"
  26. #include "Context.h"
  27. #include "Geometry.h"
  28. #include "Log.h"
  29. #include "Material.h"
  30. #include "Model.h"
  31. #include "OcclusionBuffer.h"
  32. #include "OctreeQuery.h"
  33. #include "Profiler.h"
  34. #include "ResourceCache.h"
  35. #include "ResourceEvents.h"
  36. #include "StaticModel.h"
  37. #include "XMLElement.h"
  38. #include "DebugNew.h"
  39. namespace Urho3D
  40. {
  41. OBJECTTYPESTATIC(StaticModel);
  42. StaticModel::StaticModel(Context* context) :
  43. Drawable(context),
  44. occlusionLodLevel_(M_MAX_UNSIGNED)
  45. {
  46. drawableFlags_ = DRAWABLE_GEOMETRY;
  47. materialsAttr_.type_ = Material::GetTypeStatic();
  48. }
  49. StaticModel::~StaticModel()
  50. {
  51. }
  52. void StaticModel::RegisterObject(Context* context)
  53. {
  54. context->RegisterFactory<StaticModel>();
  55. ACCESSOR_ATTRIBUTE(StaticModel, VAR_RESOURCEREF, "Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  56. REF_ACCESSOR_ATTRIBUTE(StaticModel, VAR_RESOURCEREFLIST, "Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()), AM_DEFAULT);
  57. ATTRIBUTE(StaticModel, VAR_BOOL, "Is Visible", visible_, true, AM_DEFAULT);
  58. ATTRIBUTE(StaticModel, VAR_BOOL, "Is Occluder", occluder_, false, AM_DEFAULT);
  59. ACCESSOR_ATTRIBUTE(StaticModel, VAR_BOOL, "Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  60. ATTRIBUTE(StaticModel, VAR_BOOL, "Cast Shadows", castShadows_, false, AM_DEFAULT);
  61. ACCESSOR_ATTRIBUTE(StaticModel, VAR_FLOAT, "Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  62. ACCESSOR_ATTRIBUTE(StaticModel, VAR_FLOAT, "Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  63. ACCESSOR_ATTRIBUTE(StaticModel, VAR_FLOAT, "LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  64. COPY_BASE_ATTRIBUTES(StaticModel, Drawable);
  65. ATTRIBUTE(StaticModel, VAR_INT, "Occlusion LOD Level", occlusionLodLevel_, M_MAX_UNSIGNED, AM_DEFAULT);
  66. }
  67. void StaticModel::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  68. {
  69. RayQueryLevel level = query.level_;
  70. switch (level)
  71. {
  72. case RAY_AABB_NOSUBOBJECTS:
  73. case RAY_AABB:
  74. Drawable::ProcessRayQuery(query, results);
  75. break;
  76. case RAY_OBB:
  77. {
  78. Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
  79. Ray localRay(inverse * query.ray_.origin_, inverse * Vector4(query.ray_.direction_, 0.0f));
  80. float distance = localRay.HitDistance(boundingBox_);
  81. if (distance <= query.maxDistance_)
  82. {
  83. RayQueryResult result;
  84. result.drawable_ = this;
  85. result.node_ = GetNode();
  86. result.distance_ = distance;
  87. result.subObject_ = M_MAX_UNSIGNED;
  88. results.Push(result);
  89. }
  90. }
  91. break;
  92. case RAY_TRIANGLE:
  93. {
  94. // Do a pretest using the OBB
  95. Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
  96. Ray localRay(inverse * query.ray_.origin_, inverse * Vector4(query.ray_.direction_, 0.0f));
  97. float distance = localRay.HitDistance(boundingBox_);
  98. if (distance <= query.maxDistance_)
  99. {
  100. // Then the actual test using triangle geometry
  101. for (unsigned i = 0; i < batches_.Size(); ++i)
  102. {
  103. Geometry* geometry = batches_[i].geometry_;
  104. if (geometry)
  105. {
  106. distance = geometry->GetHitDistance(localRay);
  107. if (distance <= query.maxDistance_)
  108. {
  109. RayQueryResult result;
  110. result.drawable_ = this;
  111. result.node_ = GetNode();
  112. result.distance_ = distance;
  113. result.subObject_ = M_MAX_UNSIGNED;
  114. results.Push(result);
  115. break;
  116. }
  117. }
  118. }
  119. }
  120. }
  121. break;
  122. }
  123. }
  124. void StaticModel::UpdateBatches(const FrameInfo& frame)
  125. {
  126. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  127. distance_ = frame.camera_->GetDistance(GetWorldBoundingBox().Center());
  128. if (batches_.Size() > 1)
  129. {
  130. for (unsigned i = 0; i < batches_.Size(); ++i)
  131. {
  132. batches_[i].distance_ = frame.camera_->GetDistance(worldTransform * geometryData_[i].center_);
  133. batches_[i].worldTransform_ = &worldTransform;
  134. }
  135. }
  136. else if (batches_.Size() == 1)
  137. {
  138. batches_[0].distance_ = distance_;
  139. batches_[0].worldTransform_ = &worldTransform;
  140. }
  141. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  142. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  143. if (newLodDistance != lodDistance_)
  144. {
  145. lodDistance_ = newLodDistance;
  146. CalculateLodLevels();
  147. }
  148. }
  149. Geometry* StaticModel::GetLodGeometry(unsigned batchIndex, unsigned level)
  150. {
  151. if (batchIndex >= geometries_.Size())
  152. return 0;
  153. // If level is out of range, use visible geometry
  154. if (level < geometries_[batchIndex].Size())
  155. return geometries_[batchIndex][level];
  156. else
  157. return batches_[batchIndex].geometry_;
  158. }
  159. unsigned StaticModel::GetNumOccluderTriangles()
  160. {
  161. unsigned triangles = 0;
  162. for (unsigned i = 0; i < batches_.Size(); ++i)
  163. {
  164. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  165. if (!geometry)
  166. continue;
  167. // Check that the material is suitable for occlusion (default material always is)
  168. Material* mat = batches_[i].material_;
  169. if (mat && !mat->GetOcclusion())
  170. continue;
  171. triangles += geometry->GetIndexCount() / 3;
  172. }
  173. return triangles;
  174. }
  175. bool StaticModel::DrawOcclusion(OcclusionBuffer* buffer)
  176. {
  177. bool success = true;
  178. for (unsigned i = 0; i < batches_.Size(); ++i)
  179. {
  180. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  181. if (!geometry)
  182. continue;
  183. // Check that the material is suitable for occlusion (default material always is) and set culling mode
  184. Material* material = batches_[i].material_;
  185. if (material)
  186. {
  187. if (!material->GetOcclusion())
  188. continue;
  189. buffer->SetCullMode(material->GetCullMode());
  190. }
  191. else
  192. buffer->SetCullMode(CULL_CCW);
  193. const unsigned char* vertexData;
  194. unsigned vertexSize;
  195. const unsigned char* indexData;
  196. unsigned indexSize;
  197. unsigned elementMask;
  198. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  199. // Check for valid geometry data
  200. if (!vertexData || !indexData)
  201. continue;
  202. unsigned indexStart = geometry->GetIndexStart();
  203. unsigned indexCount = geometry->GetIndexCount();
  204. // Draw and check for running out of triangles
  205. success = buffer->Draw(node_->GetWorldTransform(), vertexData, vertexSize, indexData, indexSize, indexStart, indexCount);
  206. if (!success)
  207. break;
  208. }
  209. return success;
  210. }
  211. void StaticModel::SetModel(Model* model)
  212. {
  213. if (!model || model == model_)
  214. return;
  215. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  216. if (model_)
  217. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  218. if (model)
  219. SubscribeToEvent(model, E_RELOADFINISHED, HANDLER(StaticModel, HandleModelReloadFinished));
  220. model_ = model;
  221. // Copy the subgeometry & LOD level structure
  222. SetNumGeometries(model->GetNumGeometries());
  223. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  224. const PODVector<Vector3>& geometryCenters = model->GetGeometryCenters();
  225. for (unsigned i = 0; i < geometries.Size(); ++i)
  226. {
  227. geometries_[i] = geometries[i];
  228. geometryData_[i].center_ = geometryCenters[i];
  229. }
  230. SetBoundingBox(model->GetBoundingBox());
  231. ResetLodLevels();
  232. MarkNetworkUpdate();
  233. }
  234. void StaticModel::SetMaterial(Material* material)
  235. {
  236. for (unsigned i = 0; i < batches_.Size(); ++i)
  237. batches_[i].material_ = material;
  238. MarkNetworkUpdate();
  239. }
  240. bool StaticModel::SetMaterial(unsigned index, Material* material)
  241. {
  242. if (index >= batches_.Size())
  243. {
  244. LOGERROR("Material index out of bounds");
  245. return false;
  246. }
  247. batches_[index].material_ = material;
  248. MarkNetworkUpdate();
  249. return true;
  250. }
  251. void StaticModel::SetOcclusionLodLevel(unsigned level)
  252. {
  253. occlusionLodLevel_ = level;
  254. MarkNetworkUpdate();
  255. }
  256. Material* StaticModel::GetMaterial(unsigned index) const
  257. {
  258. return index < batches_.Size() ? batches_[index].material_ : (Material*)0;
  259. }
  260. void StaticModel::SetBoundingBox(const BoundingBox& box)
  261. {
  262. boundingBox_ = box;
  263. OnMarkedDirty(node_);
  264. }
  265. void StaticModel::SetNumGeometries(unsigned num)
  266. {
  267. batches_.Resize(num);
  268. geometries_.Resize(num);
  269. geometryData_.Resize(num);
  270. ResetLodLevels();
  271. }
  272. void StaticModel::SetModelAttr(ResourceRef value)
  273. {
  274. ResourceCache* cache = GetSubsystem<ResourceCache>();
  275. SetModel(cache->GetResource<Model>(value.id_));
  276. }
  277. void StaticModel::SetMaterialsAttr(const ResourceRefList& value)
  278. {
  279. ResourceCache* cache = GetSubsystem<ResourceCache>();
  280. for (unsigned i = 0; i < value.ids_.Size(); ++i)
  281. SetMaterial(i, cache->GetResource<Material>(value.ids_[i]));
  282. }
  283. ResourceRef StaticModel::GetModelAttr() const
  284. {
  285. return GetResourceRef(model_, Model::GetTypeStatic());
  286. }
  287. const ResourceRefList& StaticModel::GetMaterialsAttr() const
  288. {
  289. materialsAttr_.ids_.Resize(batches_.Size());
  290. for (unsigned i = 0; i < batches_.Size(); ++i)
  291. materialsAttr_.ids_[i] = batches_[i].material_ ? batches_[i].material_->GetNameHash() : StringHash();
  292. return materialsAttr_;
  293. }
  294. void StaticModel::OnWorldBoundingBoxUpdate()
  295. {
  296. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  297. }
  298. void StaticModel::ResetLodLevels()
  299. {
  300. // Ensure that each subgeometry has at least one LOD level, and reset the current LOD level
  301. for (unsigned i = 0; i < batches_.Size(); ++i)
  302. {
  303. if (!geometries_[i].Size())
  304. geometries_[i].Resize(1);
  305. batches_[i].geometry_ = geometries_[i][0];
  306. geometryData_[i].lodLevel_ = 0;
  307. }
  308. // Find out the real LOD levels on next geometry update
  309. lodDistance_ = M_INFINITY;
  310. }
  311. void StaticModel::CalculateLodLevels()
  312. {
  313. for (unsigned i = 0; i < batches_.Size(); ++i)
  314. {
  315. const Vector<SharedPtr<Geometry> >& batchGeometries = geometries_[i];
  316. unsigned j;
  317. for (j = 1; j < batchGeometries.Size(); ++j)
  318. {
  319. if (batchGeometries[j] && lodDistance_ <= batchGeometries[j]->GetLodDistance())
  320. break;
  321. }
  322. unsigned newLodLevel = j - 1;
  323. if (geometryData_[i].lodLevel_ != newLodLevel)
  324. {
  325. geometryData_[i].lodLevel_ = newLodLevel;
  326. batches_[i].geometry_ = batchGeometries[newLodLevel];
  327. }
  328. }
  329. }
  330. void StaticModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  331. {
  332. Model* currentModel = model_;
  333. model_ = 0; // Set null to allow to be re-set
  334. SetModel(currentModel);
  335. }
  336. }