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 "Model.h"
  30. #include "OcclusionBuffer.h"
  31. #include "OctreeQuery.h"
  32. #include "Profiler.h"
  33. #include "ResourceCache.h"
  34. #include "ResourceEvents.h"
  35. #include "StaticModel.h"
  36. #include "XMLElement.h"
  37. #include "DebugNew.h"
  38. static const Vector3 DOT_SCALE(1 / 3.0f, 1 / 3.0f, 1 / 3.0f);
  39. OBJECTTYPESTATIC(StaticModel);
  40. StaticModel::StaticModel(Context* context) :
  41. Drawable(context),
  42. softwareLodLevel_(M_MAX_UNSIGNED)
  43. {
  44. drawableFlags_ = DRAWABLE_GEOMETRY;
  45. materialsAttr_.type_ = Material::GetTypeStatic();
  46. }
  47. StaticModel::~StaticModel()
  48. {
  49. }
  50. void StaticModel::RegisterObject(Context* context)
  51. {
  52. context->RegisterFactory<StaticModel>();
  53. ACCESSOR_ATTRIBUTE(StaticModel, VAR_RESOURCEREF, "Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  54. REF_ACCESSOR_ATTRIBUTE(StaticModel, VAR_RESOURCEREFLIST, "Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()), AM_DEFAULT);
  55. ATTRIBUTE(StaticModel, VAR_BOOL, "Is Visible", visible_, true, AM_DEFAULT);
  56. ATTRIBUTE(StaticModel, VAR_BOOL, "Is Occluder", occluder_, false, AM_DEFAULT);
  57. ACCESSOR_ATTRIBUTE(StaticModel, VAR_BOOL, "Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  58. ATTRIBUTE(StaticModel, VAR_BOOL, "Cast Shadows", castShadows_, false, AM_DEFAULT);
  59. ACCESSOR_ATTRIBUTE(StaticModel, VAR_FLOAT, "Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  60. ACCESSOR_ATTRIBUTE(StaticModel, VAR_FLOAT, "Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  61. ACCESSOR_ATTRIBUTE(StaticModel, VAR_FLOAT, "LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  62. COPY_BASE_ATTRIBUTES(StaticModel, Drawable);
  63. ATTRIBUTE(StaticModel, VAR_INT, "Ray/Occl. LOD Level", softwareLodLevel_, M_MAX_UNSIGNED, AM_DEFAULT);
  64. }
  65. void StaticModel::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  66. {
  67. RayQueryLevel level = query.level_;
  68. switch (level)
  69. {
  70. case RAY_AABB_NOSUBOBJECTS:
  71. case RAY_AABB:
  72. Drawable::ProcessRayQuery(query, results);
  73. break;
  74. case RAY_OBB:
  75. {
  76. Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
  77. Ray localRay(inverse * query.ray_.origin_, inverse * Vector4(query.ray_.direction_, 0.0f));
  78. float distance = localRay.HitDistance(boundingBox_);
  79. if (distance <= query.maxDistance_)
  80. {
  81. RayQueryResult result;
  82. result.drawable_ = this;
  83. result.node_ = GetNode();
  84. result.distance_ = distance;
  85. result.subObject_ = M_MAX_UNSIGNED;
  86. results.Push(result);
  87. }
  88. }
  89. break;
  90. case RAY_TRIANGLE:
  91. {
  92. // Do a pretest using the OBB
  93. Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
  94. Ray localRay(inverse * query.ray_.origin_, inverse * Vector4(query.ray_.direction_, 0.0f));
  95. float distance = localRay.HitDistance(boundingBox_);
  96. if (distance <= query.maxDistance_)
  97. {
  98. // Then the actual test using triangle geometry
  99. for (unsigned i = 0; i < geometries_.Size(); ++i)
  100. {
  101. Geometry* geometry = GetSoftwareGeometry(i);
  102. if (geometry)
  103. {
  104. distance = geometry->GetDistance(localRay);
  105. if (distance <= query.maxDistance_)
  106. {
  107. RayQueryResult result;
  108. result.drawable_ = this;
  109. result.node_ = GetNode();
  110. result.distance_ = distance;
  111. result.subObject_ = M_MAX_UNSIGNED;
  112. results.Push(result);
  113. break;
  114. }
  115. }
  116. }
  117. }
  118. }
  119. break;
  120. }
  121. }
  122. void StaticModel::UpdateBatches(const FrameInfo& frame)
  123. {
  124. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  125. distance_ = frame.camera_->GetDistance(GetWorldBoundingBox().Center());
  126. if (batches_.Size() > 1)
  127. {
  128. for (unsigned i = 0; i < batches_.Size(); ++i)
  129. {
  130. batches_[i].distance_ = frame.camera_->GetDistance(worldTransform * geometryData_[i].center_);
  131. batches_[i].worldTransform_ = &worldTransform;
  132. }
  133. }
  134. else if (batches_.Size() == 1)
  135. {
  136. batches_[0].distance_ = distance_;
  137. batches_[0].worldTransform_ = &worldTransform;
  138. }
  139. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  140. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  141. if (newLodDistance != lodDistance_)
  142. {
  143. lodDistance_ = newLodDistance;
  144. CalculateLodLevels();
  145. }
  146. }
  147. unsigned StaticModel::GetNumOccluderTriangles()
  148. {
  149. unsigned triangles = 0;
  150. for (unsigned i = 0; i < batches_.Size(); ++i)
  151. {
  152. Geometry* geometry = GetSoftwareGeometry(i);
  153. if (!geometry)
  154. continue;
  155. // Check that the material is suitable for occlusion (default material always is)
  156. Material* mat = batches_[i].material_;
  157. if (mat && !mat->GetOcclusion())
  158. continue;
  159. triangles += geometry->GetIndexCount() / 3;
  160. }
  161. return triangles;
  162. }
  163. bool StaticModel::DrawOcclusion(OcclusionBuffer* buffer)
  164. {
  165. bool success = true;
  166. for (unsigned i = 0; i < batches_.Size(); ++i)
  167. {
  168. Geometry* geometry = GetSoftwareGeometry(i);
  169. if (!geometry)
  170. continue;
  171. // Check that the material is suitable for occlusion (default material always is) and set culling mode
  172. Material* material = batches_[i].material_;
  173. if (material)
  174. {
  175. if (!material->GetOcclusion())
  176. continue;
  177. buffer->SetCullMode(material->GetCullMode());
  178. }
  179. else
  180. buffer->SetCullMode(CULL_CCW);
  181. const unsigned char* vertexData;
  182. unsigned vertexSize;
  183. const unsigned char* indexData;
  184. unsigned indexSize;
  185. unsigned elementMask;
  186. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  187. // Check for valid geometry data
  188. if (!vertexData || !indexData)
  189. continue;
  190. unsigned indexStart = geometry->GetIndexStart();
  191. unsigned indexCount = geometry->GetIndexCount();
  192. // Draw and check for running out of triangles
  193. if (!buffer->Draw(node_->GetWorldTransform(), vertexData, vertexSize, indexData, indexSize, indexStart, indexCount))
  194. success = false;
  195. if (!success)
  196. break;
  197. }
  198. return success;
  199. }
  200. void StaticModel::SetModel(Model* model)
  201. {
  202. if (!model || model == model_)
  203. return;
  204. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  205. if (model_)
  206. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  207. if (model)
  208. SubscribeToEvent(model, E_RELOADFINISHED, HANDLER(StaticModel, HandleModelReloadFinished));
  209. model_ = model;
  210. // Copy the subgeometry & LOD level structure
  211. SetNumGeometries(model->GetNumGeometries());
  212. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  213. const PODVector<Vector3>& geometryCenters = model->GetGeometryCenters();
  214. for (unsigned i = 0; i < geometries.Size(); ++i)
  215. {
  216. geometries_[i] = geometries[i];
  217. geometryData_[i].center_ = geometryCenters[i];
  218. }
  219. SetBoundingBox(model->GetBoundingBox());
  220. ResetLodLevels();
  221. MarkNetworkUpdate();
  222. }
  223. void StaticModel::SetMaterial(Material* material)
  224. {
  225. for (unsigned i = 0; i < batches_.Size(); ++i)
  226. batches_[i].material_ = material;
  227. MarkNetworkUpdate();
  228. }
  229. bool StaticModel::SetMaterial(unsigned index, Material* material)
  230. {
  231. if (index >= batches_.Size())
  232. {
  233. LOGERROR("Material index out of bounds");
  234. return false;
  235. }
  236. batches_[index].material_ = material;
  237. MarkNetworkUpdate();
  238. return true;
  239. }
  240. void StaticModel::SetSoftwareLodLevel(unsigned level)
  241. {
  242. softwareLodLevel_ = level;
  243. MarkNetworkUpdate();
  244. }
  245. Material* StaticModel::GetMaterial(unsigned index) const
  246. {
  247. return index < batches_.Size() ? batches_[index].material_ : (Material*)0;
  248. }
  249. Geometry* StaticModel::GetSoftwareGeometry(unsigned index) const
  250. {
  251. if (index >= geometries_.Size())
  252. return 0;
  253. unsigned lodLevel;
  254. // Check whether to use same LOD as visible, or a specific LOD
  255. if (softwareLodLevel_ == M_MAX_UNSIGNED)
  256. lodLevel = geometryData_[index].lodLevel_;
  257. else
  258. lodLevel = Clamp(softwareLodLevel_, 0, geometries_[index].Size());
  259. return geometries_[index][lodLevel];
  260. }
  261. void StaticModel::SetBoundingBox(const BoundingBox& box)
  262. {
  263. boundingBox_ = box;
  264. OnMarkedDirty(node_);
  265. }
  266. void StaticModel::SetNumGeometries(unsigned num)
  267. {
  268. batches_.Resize(num);
  269. geometries_.Resize(num);
  270. geometryData_.Resize(num);
  271. ResetLodLevels();
  272. }
  273. void StaticModel::SetModelAttr(ResourceRef value)
  274. {
  275. ResourceCache* cache = GetSubsystem<ResourceCache>();
  276. SetModel(cache->GetResource<Model>(value.id_));
  277. }
  278. void StaticModel::SetMaterialsAttr(const ResourceRefList& value)
  279. {
  280. ResourceCache* cache = GetSubsystem<ResourceCache>();
  281. for (unsigned i = 0; i < value.ids_.Size(); ++i)
  282. SetMaterial(i, cache->GetResource<Material>(value.ids_[i]));
  283. }
  284. ResourceRef StaticModel::GetModelAttr() const
  285. {
  286. return GetResourceRef(model_, Model::GetTypeStatic());
  287. }
  288. const ResourceRefList& StaticModel::GetMaterialsAttr() const
  289. {
  290. materialsAttr_.ids_.Resize(batches_.Size());
  291. for (unsigned i = 0; i < batches_.Size(); ++i)
  292. materialsAttr_.ids_[i] = batches_[i].material_ ? batches_[i].material_->GetNameHash() : StringHash();
  293. return materialsAttr_;
  294. }
  295. void StaticModel::OnWorldBoundingBoxUpdate()
  296. {
  297. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  298. }
  299. void StaticModel::ResetLodLevels()
  300. {
  301. // Ensure that each subgeometry has at least one LOD level, and reset the current LOD level
  302. for (unsigned i = 0; i < batches_.Size(); ++i)
  303. {
  304. if (!geometries_[i].Size())
  305. geometries_[i].Resize(1);
  306. batches_[i].geometry_ = geometries_[i][0];
  307. geometryData_[i].lodLevel_ = 0;
  308. }
  309. // Find out the real LOD levels on next geometry update
  310. lodDistance_ = M_INFINITY;
  311. }
  312. void StaticModel::CalculateLodLevels()
  313. {
  314. for (unsigned i = 0; i < batches_.Size(); ++i)
  315. {
  316. const Vector<SharedPtr<Geometry> >& batchGeometries = geometries_[i];
  317. unsigned j;
  318. for (j = 1; j < batchGeometries.Size(); ++j)
  319. {
  320. if (batchGeometries[j] && lodDistance_ <= batchGeometries[j]->GetLodDistance())
  321. break;
  322. }
  323. unsigned newLodLevel = j - 1;
  324. if (geometryData_[i].lodLevel_ != newLodLevel)
  325. {
  326. geometryData_[i].lodLevel_ = newLodLevel;
  327. batches_[i].geometry_ = batchGeometries[newLodLevel];
  328. }
  329. }
  330. }
  331. void StaticModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  332. {
  333. Model* currentModel = model_;
  334. model_ = 0; // Set null to allow to be re-set
  335. SetModel(currentModel);
  336. }