StaticModel.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. //
  2. // Copyright (c) 2008-2015 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 "../IO/FileSystem.h"
  33. #include "../IO/Log.h"
  34. #include "../Resource/ResourceCache.h"
  35. #include "../Resource/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("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  53. MIXED_ACCESSOR_ATTRIBUTE("Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  54. ACCESSOR_ATTRIBUTE("Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()),
  55. AM_DEFAULT);
  56. ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
  57. ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  58. ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
  59. ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  60. ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  61. ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  62. COPY_BASE_ATTRIBUTES(Drawable);
  63. ATTRIBUTE("Occlusion LOD Level", int, occlusionLodLevel_, 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:
  71. Drawable::ProcessRayQuery(query, results);
  72. break;
  73. case RAY_OBB:
  74. case RAY_TRIANGLE:
  75. case RAY_TRIANGLE_UV:
  76. Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
  77. Ray localRay = query.ray_.Transformed(inverse);
  78. float distance = localRay.HitDistance(boundingBox_);
  79. Vector3 normal = -query.ray_.direction_;
  80. Vector2 geometryUV;
  81. unsigned hitBatch = M_MAX_UNSIGNED;
  82. if (level >= RAY_TRIANGLE && distance < query.maxDistance_)
  83. {
  84. distance = M_INFINITY;
  85. for (unsigned i = 0; i < batches_.Size(); ++i)
  86. {
  87. Geometry* geometry = batches_[i].geometry_;
  88. if (geometry)
  89. {
  90. Vector3 geometryNormal;
  91. float geometryDistance = level == RAY_TRIANGLE ? geometry->GetHitDistance(localRay, &geometryNormal) :
  92. geometry->GetHitDistance(localRay, &geometryNormal, &geometryUV);
  93. if (geometryDistance < query.maxDistance_ && geometryDistance < distance)
  94. {
  95. distance = geometryDistance;
  96. normal = (node_->GetWorldTransform() * Vector4(geometryNormal, 0.0f)).Normalized();
  97. hitBatch = i;
  98. }
  99. }
  100. }
  101. }
  102. if (distance < query.maxDistance_)
  103. {
  104. RayQueryResult result;
  105. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  106. result.normal_ = normal;
  107. result.textureUV_ = geometryUV;
  108. result.distance_ = distance;
  109. result.drawable_ = this;
  110. result.node_ = node_;
  111. result.subObject_ = hitBatch;
  112. results.Push(result);
  113. }
  114. break;
  115. }
  116. }
  117. void StaticModel::UpdateBatches(const FrameInfo& frame)
  118. {
  119. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  120. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  121. if (batches_.Size() == 1)
  122. batches_[0].distance_ = distance_;
  123. else
  124. {
  125. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  126. for (unsigned i = 0; i < batches_.Size(); ++i)
  127. batches_[i].distance_ = frame.camera_->GetDistance(worldTransform * geometryData_[i].center_);
  128. }
  129. float scale = worldBoundingBox.Size().DotProduct(DOT_SCALE);
  130. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  131. if (newLodDistance != lodDistance_)
  132. {
  133. lodDistance_ = newLodDistance;
  134. CalculateLodLevels();
  135. }
  136. }
  137. Geometry* StaticModel::GetLodGeometry(unsigned batchIndex, unsigned level)
  138. {
  139. if (batchIndex >= geometries_.Size())
  140. return 0;
  141. // If level is out of range, use visible geometry
  142. if (level < geometries_[batchIndex].Size())
  143. return geometries_[batchIndex][level];
  144. else
  145. return batches_[batchIndex].geometry_;
  146. }
  147. unsigned StaticModel::GetNumOccluderTriangles()
  148. {
  149. unsigned triangles = 0;
  150. for (unsigned i = 0; i < batches_.Size(); ++i)
  151. {
  152. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  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. for (unsigned i = 0; i < batches_.Size(); ++i)
  166. {
  167. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  168. if (!geometry)
  169. continue;
  170. // Check that the material is suitable for occlusion (default material always is) and set culling mode
  171. Material* material = batches_[i].material_;
  172. if (material)
  173. {
  174. if (!material->GetOcclusion())
  175. continue;
  176. buffer->SetCullMode(material->GetCullMode());
  177. }
  178. else
  179. buffer->SetCullMode(CULL_CCW);
  180. const unsigned char* vertexData;
  181. unsigned vertexSize;
  182. const unsigned char* indexData;
  183. unsigned indexSize;
  184. unsigned elementMask;
  185. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  186. // Check for valid geometry data
  187. if (!vertexData || !indexData)
  188. continue;
  189. unsigned indexStart = geometry->GetIndexStart();
  190. unsigned indexCount = geometry->GetIndexCount();
  191. // Draw and check for running out of triangles
  192. if (!buffer->Draw(node_->GetWorldTransform(), vertexData, vertexSize, indexData, indexSize, indexStart, indexCount))
  193. return false;
  194. }
  195. return true;
  196. }
  197. void StaticModel::SetModel(Model* model)
  198. {
  199. if (model == model_)
  200. return;
  201. // If script erroneously calls StaticModel::SetModel on an AnimatedModel, warn and redirect
  202. if (GetType() == AnimatedModel::GetTypeStatic())
  203. {
  204. LOGWARNING("StaticModel::SetModel() called on AnimatedModel. Redirecting to AnimatedModel::SetModel()");
  205. AnimatedModel* animatedModel = static_cast<AnimatedModel*>(this);
  206. animatedModel->SetModel(model);
  207. return;
  208. }
  209. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  210. if (model_)
  211. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  212. model_ = model;
  213. if (model)
  214. {
  215. SubscribeToEvent(model, E_RELOADFINISHED, URHO3D_HANDLER(StaticModel, HandleModelReloadFinished));
  216. // Copy the subgeometry & LOD level structure
  217. SetNumGeometries(model->GetNumGeometries());
  218. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  219. const PODVector<Vector3>& geometryCenters = model->GetGeometryCenters();
  220. const Matrix3x4* worldTransform = node_ ? &node_->GetWorldTransform() : (const Matrix3x4*)0;
  221. for (unsigned i = 0; i < geometries.Size(); ++i)
  222. {
  223. batches_[i].worldTransform_ = worldTransform;
  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. void StaticModel::ApplyMaterialList(const String& fileName)
  260. {
  261. String useFileName = fileName;
  262. if (useFileName.Trimmed().Empty() && model_)
  263. useFileName = ReplaceExtension(model_->GetName(), ".txt");
  264. ResourceCache* cache = GetSubsystem<ResourceCache>();
  265. SharedPtr<File> file = cache->GetFile(useFileName, false);
  266. if (!file)
  267. return;
  268. unsigned index = 0;
  269. while (!file->IsEof() && index < batches_.Size())
  270. {
  271. Material* material = cache->GetResource<Material>(file->ReadLine());
  272. if (material)
  273. SetMaterial(index, material);
  274. ++index;
  275. }
  276. }
  277. Material* StaticModel::GetMaterial(unsigned index) const
  278. {
  279. return index < batches_.Size() ? batches_[index].material_ : (Material*)0;
  280. }
  281. bool StaticModel::IsInside(const Vector3& point) const
  282. {
  283. if (!node_)
  284. return false;
  285. Vector3 localPosition = node_->GetWorldTransform().Inverse() * point;
  286. return IsInsideLocal(localPosition);
  287. }
  288. bool StaticModel::IsInsideLocal(const Vector3& point) const
  289. {
  290. // Early-out if point is not inside bounding box
  291. if (boundingBox_.IsInside(point) == OUTSIDE)
  292. return false;
  293. Ray localRay(point, Vector3(1.0f, -1.0f, 1.0f));
  294. for (unsigned i = 0; i < batches_.Size(); ++i)
  295. {
  296. Geometry* geometry = batches_[i].geometry_;
  297. if (geometry)
  298. {
  299. if (geometry->IsInside(localRay))
  300. return true;
  301. }
  302. }
  303. return false;
  304. }
  305. void StaticModel::SetBoundingBox(const BoundingBox& box)
  306. {
  307. boundingBox_ = box;
  308. OnMarkedDirty(node_);
  309. }
  310. void StaticModel::SetNumGeometries(unsigned num)
  311. {
  312. batches_.Resize(num);
  313. geometries_.Resize(num);
  314. geometryData_.Resize(num);
  315. ResetLodLevels();
  316. }
  317. void StaticModel::SetModelAttr(const ResourceRef& value)
  318. {
  319. ResourceCache* cache = GetSubsystem<ResourceCache>();
  320. SetModel(cache->GetResource<Model>(value.name_));
  321. }
  322. void StaticModel::SetMaterialsAttr(const ResourceRefList& value)
  323. {
  324. ResourceCache* cache = GetSubsystem<ResourceCache>();
  325. for (unsigned i = 0; i < value.names_.Size(); ++i)
  326. SetMaterial(i, cache->GetResource<Material>(value.names_[i]));
  327. }
  328. ResourceRef StaticModel::GetModelAttr() const
  329. {
  330. return GetResourceRef(model_, Model::GetTypeStatic());
  331. }
  332. const ResourceRefList& StaticModel::GetMaterialsAttr() const
  333. {
  334. materialsAttr_.names_.Resize(batches_.Size());
  335. for (unsigned i = 0; i < batches_.Size(); ++i)
  336. materialsAttr_.names_[i] = GetResourceName(batches_[i].material_);
  337. return materialsAttr_;
  338. }
  339. void StaticModel::OnWorldBoundingBoxUpdate()
  340. {
  341. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  342. }
  343. void StaticModel::ResetLodLevels()
  344. {
  345. // Ensure that each subgeometry has at least one LOD level, and reset the current LOD level
  346. for (unsigned i = 0; i < batches_.Size(); ++i)
  347. {
  348. if (!geometries_[i].Size())
  349. geometries_[i].Resize(1);
  350. batches_[i].geometry_ = geometries_[i][0];
  351. geometryData_[i].lodLevel_ = 0;
  352. }
  353. // Find out the real LOD levels on next geometry update
  354. lodDistance_ = M_INFINITY;
  355. }
  356. void StaticModel::CalculateLodLevels()
  357. {
  358. for (unsigned i = 0; i < batches_.Size(); ++i)
  359. {
  360. const Vector<SharedPtr<Geometry> >& batchGeometries = geometries_[i];
  361. // If only one LOD geometry, no reason to go through the LOD calculation
  362. if (batchGeometries.Size() <= 1)
  363. continue;
  364. unsigned j;
  365. for (j = 1; j < batchGeometries.Size(); ++j)
  366. {
  367. if (batchGeometries[j] && lodDistance_ <= batchGeometries[j]->GetLodDistance())
  368. break;
  369. }
  370. unsigned newLodLevel = j - 1;
  371. if (geometryData_[i].lodLevel_ != newLodLevel)
  372. {
  373. geometryData_[i].lodLevel_ = newLodLevel;
  374. batches_[i].geometry_ = batchGeometries[newLodLevel];
  375. }
  376. }
  377. }
  378. void StaticModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  379. {
  380. Model* currentModel = model_;
  381. model_.Reset(); // Set null to allow to be re-set
  382. SetModel(currentModel);
  383. }
  384. }