StaticModel.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. //
  2. // Copyright (c) 2008-2013 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 "AnimatedModel.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 "DebugNew.h"
  37. namespace Urho3D
  38. {
  39. extern const char* GEOMETRY_CATEGORY;
  40. StaticModel::StaticModel(Context* context) :
  41. Drawable(context, DRAWABLE_GEOMETRY),
  42. occlusionLodLevel_(M_MAX_UNSIGNED),
  43. materialsAttr_(Material::GetTypeStatic())
  44. {
  45. }
  46. StaticModel::~StaticModel()
  47. {
  48. }
  49. void StaticModel::RegisterObject(Context* context)
  50. {
  51. context->RegisterFactory<StaticModel>(GEOMETRY_CATEGORY);
  52. ACCESSOR_ATTRIBUTE(StaticModel, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  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 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, "Occlusion LOD Level", 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_NOSUBOBJECTS:
  70. case RAY_AABB:
  71. Drawable::ProcessRayQuery(query, results);
  72. break;
  73. case RAY_OBB:
  74. case RAY_TRIANGLE:
  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. if (level == RAY_TRIANGLE)
  81. {
  82. for (unsigned i = 0; i < batches_.Size(); ++i)
  83. {
  84. Geometry* geometry = batches_[i].geometry_;
  85. if (geometry)
  86. {
  87. distance = geometry->GetHitDistance(localRay);
  88. if (distance < query.maxDistance_)
  89. {
  90. RayQueryResult result;
  91. result.drawable_ = this;
  92. result.node_ = node_;
  93. result.distance_ = distance;
  94. result.subObject_ = M_MAX_UNSIGNED;
  95. results.Push(result);
  96. break;
  97. }
  98. }
  99. }
  100. }
  101. else
  102. {
  103. RayQueryResult result;
  104. result.drawable_ = this;
  105. result.node_ = node_;
  106. result.distance_ = distance;
  107. result.subObject_ = M_MAX_UNSIGNED;
  108. results.Push(result);
  109. }
  110. }
  111. break;
  112. }
  113. }
  114. void StaticModel::UpdateBatches(const FrameInfo& frame)
  115. {
  116. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  117. distance_ = frame.camera_->GetDistance(GetWorldBoundingBox().Center());
  118. if (batches_.Size() > 1)
  119. {
  120. for (unsigned i = 0; i < batches_.Size(); ++i)
  121. {
  122. batches_[i].distance_ = frame.camera_->GetDistance(worldTransform * geometryData_[i].center_);
  123. batches_[i].worldTransform_ = &worldTransform;
  124. }
  125. }
  126. else if (batches_.Size() == 1)
  127. {
  128. batches_[0].distance_ = distance_;
  129. batches_[0].worldTransform_ = &worldTransform;
  130. }
  131. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  132. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  133. if (newLodDistance != lodDistance_)
  134. {
  135. lodDistance_ = newLodDistance;
  136. CalculateLodLevels();
  137. }
  138. }
  139. Geometry* StaticModel::GetLodGeometry(unsigned batchIndex, unsigned level)
  140. {
  141. if (batchIndex >= geometries_.Size())
  142. return 0;
  143. // If level is out of range, use visible geometry
  144. if (level < geometries_[batchIndex].Size())
  145. return geometries_[batchIndex][level];
  146. else
  147. return batches_[batchIndex].geometry_;
  148. }
  149. unsigned StaticModel::GetNumOccluderTriangles()
  150. {
  151. unsigned triangles = 0;
  152. for (unsigned i = 0; i < batches_.Size(); ++i)
  153. {
  154. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  155. if (!geometry)
  156. continue;
  157. // Check that the material is suitable for occlusion (default material always is)
  158. Material* mat = batches_[i].material_;
  159. if (mat && !mat->GetOcclusion())
  160. continue;
  161. triangles += geometry->GetIndexCount() / 3;
  162. }
  163. return triangles;
  164. }
  165. bool StaticModel::DrawOcclusion(OcclusionBuffer* buffer)
  166. {
  167. for (unsigned i = 0; i < batches_.Size(); ++i)
  168. {
  169. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  170. if (!geometry)
  171. continue;
  172. // Check that the material is suitable for occlusion (default material always is) and set culling mode
  173. Material* material = batches_[i].material_;
  174. if (material)
  175. {
  176. if (!material->GetOcclusion())
  177. continue;
  178. buffer->SetCullMode(material->GetCullMode());
  179. }
  180. else
  181. buffer->SetCullMode(CULL_CCW);
  182. const unsigned char* vertexData;
  183. unsigned vertexSize;
  184. const unsigned char* indexData;
  185. unsigned indexSize;
  186. unsigned elementMask;
  187. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  188. // Check for valid geometry data
  189. if (!vertexData || !indexData)
  190. continue;
  191. unsigned indexStart = geometry->GetIndexStart();
  192. unsigned indexCount = geometry->GetIndexCount();
  193. // Draw and check for running out of triangles
  194. if (!buffer->Draw(node_->GetWorldTransform(), vertexData, vertexSize, indexData, indexSize, indexStart, indexCount))
  195. return false;
  196. }
  197. return true;
  198. }
  199. void StaticModel::SetModel(Model* model)
  200. {
  201. if (model == model_)
  202. return;
  203. // If script erroneously calls StaticModel::SetModel on an AnimatedModel, warn and redirect
  204. if (GetType() == AnimatedModel::GetTypeStatic())
  205. {
  206. LOGWARNING("StaticModel::SetModel() called on AnimatedModel. Redirecting to AnimatedModel::SetModel()");
  207. AnimatedModel* animatedModel = static_cast<AnimatedModel*>(this);
  208. animatedModel->SetModel(model);
  209. return;
  210. }
  211. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  212. if (model_)
  213. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  214. model_ = model;
  215. if (model)
  216. {
  217. SubscribeToEvent(model, E_RELOADFINISHED, HANDLER(StaticModel, HandleModelReloadFinished));
  218. // Copy the subgeometry & LOD level structure
  219. SetNumGeometries(model->GetNumGeometries());
  220. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  221. const PODVector<Vector3>& geometryCenters = model->GetGeometryCenters();
  222. for (unsigned i = 0; i < geometries.Size(); ++i)
  223. {
  224. geometries_[i] = geometries[i];
  225. geometryData_[i].center_ = geometryCenters[i];
  226. }
  227. SetBoundingBox(model->GetBoundingBox());
  228. ResetLodLevels();
  229. }
  230. else
  231. {
  232. SetNumGeometries(0);
  233. SetBoundingBox(BoundingBox());
  234. }
  235. MarkNetworkUpdate();
  236. }
  237. void StaticModel::SetMaterial(Material* material)
  238. {
  239. for (unsigned i = 0; i < batches_.Size(); ++i)
  240. batches_[i].material_ = material;
  241. MarkNetworkUpdate();
  242. }
  243. bool StaticModel::SetMaterial(unsigned index, Material* material)
  244. {
  245. if (index >= batches_.Size())
  246. {
  247. LOGERROR("Material index out of bounds");
  248. return false;
  249. }
  250. batches_[index].material_ = material;
  251. MarkNetworkUpdate();
  252. return true;
  253. }
  254. void StaticModel::SetOcclusionLodLevel(unsigned level)
  255. {
  256. occlusionLodLevel_ = level;
  257. MarkNetworkUpdate();
  258. }
  259. Material* StaticModel::GetMaterial(unsigned index) const
  260. {
  261. return index < batches_.Size() ? batches_[index].material_ : (Material*)0;
  262. }
  263. bool StaticModel::IsInside(const Vector3& point) const
  264. {
  265. if (!node_)
  266. return false;
  267. Vector3 localPosition = node_->GetWorldTransform().Inverse() * point;
  268. return IsInsideLocal(localPosition);
  269. }
  270. bool StaticModel::IsInsideLocal(const Vector3& point) const
  271. {
  272. // Early-out if point is not inside bounding box
  273. if (boundingBox_.IsInside(point) == OUTSIDE)
  274. return false;
  275. Ray localRay(point, Vector3(1.0f, -1.0f, 1.0f));
  276. for (unsigned i = 0; i < batches_.Size(); ++i)
  277. {
  278. Geometry* geometry = batches_[i].geometry_;
  279. if (geometry)
  280. {
  281. if (geometry->IsInside(localRay))
  282. return true;
  283. }
  284. }
  285. return false;
  286. }
  287. void StaticModel::SetBoundingBox(const BoundingBox& box)
  288. {
  289. boundingBox_ = box;
  290. OnMarkedDirty(node_);
  291. }
  292. void StaticModel::SetNumGeometries(unsigned num)
  293. {
  294. batches_.Resize(num);
  295. geometries_.Resize(num);
  296. geometryData_.Resize(num);
  297. ResetLodLevels();
  298. }
  299. void StaticModel::SetModelAttr(ResourceRef value)
  300. {
  301. ResourceCache* cache = GetSubsystem<ResourceCache>();
  302. SetModel(cache->GetResource<Model>(value.id_));
  303. }
  304. void StaticModel::SetMaterialsAttr(const ResourceRefList& value)
  305. {
  306. ResourceCache* cache = GetSubsystem<ResourceCache>();
  307. for (unsigned i = 0; i < value.ids_.Size(); ++i)
  308. SetMaterial(i, cache->GetResource<Material>(value.ids_[i]));
  309. }
  310. ResourceRef StaticModel::GetModelAttr() const
  311. {
  312. return GetResourceRef(model_, Model::GetTypeStatic());
  313. }
  314. const ResourceRefList& StaticModel::GetMaterialsAttr() const
  315. {
  316. materialsAttr_.ids_.Resize(batches_.Size());
  317. for (unsigned i = 0; i < batches_.Size(); ++i)
  318. materialsAttr_.ids_[i] = batches_[i].material_ ? batches_[i].material_->GetNameHash() : StringHash();
  319. return materialsAttr_;
  320. }
  321. void StaticModel::OnWorldBoundingBoxUpdate()
  322. {
  323. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  324. }
  325. void StaticModel::ResetLodLevels()
  326. {
  327. // Ensure that each subgeometry has at least one LOD level, and reset the current LOD level
  328. for (unsigned i = 0; i < batches_.Size(); ++i)
  329. {
  330. if (!geometries_[i].Size())
  331. geometries_[i].Resize(1);
  332. batches_[i].geometry_ = geometries_[i][0];
  333. geometryData_[i].lodLevel_ = 0;
  334. }
  335. // Find out the real LOD levels on next geometry update
  336. lodDistance_ = M_INFINITY;
  337. }
  338. void StaticModel::CalculateLodLevels()
  339. {
  340. for (unsigned i = 0; i < batches_.Size(); ++i)
  341. {
  342. const Vector<SharedPtr<Geometry> >& batchGeometries = geometries_[i];
  343. unsigned j;
  344. for (j = 1; j < batchGeometries.Size(); ++j)
  345. {
  346. if (batchGeometries[j] && lodDistance_ <= batchGeometries[j]->GetLodDistance())
  347. break;
  348. }
  349. unsigned newLodLevel = j - 1;
  350. if (geometryData_[i].lodLevel_ != newLodLevel)
  351. {
  352. geometryData_[i].lodLevel_ = newLodLevel;
  353. batches_[i].geometry_ = batchGeometries[newLodLevel];
  354. }
  355. }
  356. }
  357. void StaticModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  358. {
  359. Model* currentModel = model_;
  360. model_.Reset(); // Set null to allow to be re-set
  361. SetModel(currentModel);
  362. }
  363. }