StaticModel.cpp 13 KB

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