StaticModel.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. //
  2. // Copyright (c) 2008-2017 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 "../Graphics/VertexBuffer.h"
  33. #include "../IO/FileSystem.h"
  34. #include "../IO/Log.h"
  35. #include "../Resource/ResourceCache.h"
  36. #include "../Resource/ResourceEvents.h"
  37. #include "../DebugNew.h"
  38. namespace Atomic
  39. {
  40. extern const char* GEOMETRY_CATEGORY;
  41. StaticModel::StaticModel(Context* context) :
  42. Drawable(context, DRAWABLE_GEOMETRY),
  43. occlusionLodLevel_(M_MAX_UNSIGNED),
  44. materialsAttr_(Material::GetTypeStatic())
  45. {
  46. }
  47. StaticModel::~StaticModel()
  48. {
  49. }
  50. void StaticModel::RegisterObject(Context* context)
  51. {
  52. context->RegisterFactory<StaticModel>(GEOMETRY_CATEGORY);
  53. ATOMIC_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  54. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  55. ATOMIC_ACCESSOR_ATTRIBUTE("Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()),
  56. AM_DEFAULT);
  57. ATOMIC_ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
  58. ATOMIC_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  59. ATOMIC_ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
  60. ATOMIC_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  61. ATOMIC_ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  62. ATOMIC_ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  63. ATOMIC_COPY_BASE_ATTRIBUTES(Drawable);
  64. ATOMIC_ATTRIBUTE("Occlusion LOD Level", int, occlusionLodLevel_, M_MAX_UNSIGNED, AM_DEFAULT);
  65. // ATOMIC BEGIN
  66. ATOMIC_ACCESSOR_ATTRIBUTE("Geometry Enabled", GetGeometryEnabledAttr, SetGeometryEnabledAttr, VariantVector,
  67. Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
  68. // ATOMIC END
  69. }
  70. void StaticModel::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  71. {
  72. RayQueryLevel level = query.level_;
  73. switch (level)
  74. {
  75. case RAY_AABB:
  76. Drawable::ProcessRayQuery(query, results);
  77. break;
  78. case RAY_OBB:
  79. case RAY_TRIANGLE:
  80. case RAY_TRIANGLE_UV:
  81. Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
  82. Ray localRay = query.ray_.Transformed(inverse);
  83. float distance = localRay.HitDistance(boundingBox_);
  84. Vector3 normal = -query.ray_.direction_;
  85. Vector2 geometryUV;
  86. unsigned hitBatch = M_MAX_UNSIGNED;
  87. if (level >= RAY_TRIANGLE && distance < query.maxDistance_)
  88. {
  89. distance = M_INFINITY;
  90. for (unsigned i = 0; i < batches_.Size(); ++i)
  91. {
  92. Geometry* geometry = batches_[i].geometry_;
  93. if (geometry)
  94. {
  95. Vector3 geometryNormal;
  96. float geometryDistance = level == RAY_TRIANGLE ? geometry->GetHitDistance(localRay, &geometryNormal) :
  97. geometry->GetHitDistance(localRay, &geometryNormal, &geometryUV);
  98. if (geometryDistance < query.maxDistance_ && geometryDistance < distance)
  99. {
  100. distance = geometryDistance;
  101. normal = (node_->GetWorldTransform() * Vector4(geometryNormal, 0.0f)).Normalized();
  102. hitBatch = i;
  103. }
  104. }
  105. }
  106. }
  107. if (distance < query.maxDistance_)
  108. {
  109. RayQueryResult result;
  110. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  111. result.normal_ = normal;
  112. result.textureUV_ = geometryUV;
  113. result.distance_ = distance;
  114. result.drawable_ = this;
  115. result.node_ = node_;
  116. result.subObject_ = hitBatch;
  117. results.Push(result);
  118. }
  119. break;
  120. }
  121. }
  122. void StaticModel::UpdateBatches(const FrameInfo& frame)
  123. {
  124. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  125. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  126. if (batches_.Size() == 1)
  127. batches_[0].distance_ = distance_;
  128. else
  129. {
  130. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  131. for (unsigned i = 0; i < batches_.Size(); ++i)
  132. batches_[i].distance_ = frame.camera_->GetDistance(worldTransform * geometryData_[i].center_);
  133. }
  134. float scale = worldBoundingBox.Size().DotProduct(DOT_SCALE);
  135. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  136. if (newLodDistance != lodDistance_)
  137. {
  138. lodDistance_ = newLodDistance;
  139. CalculateLodLevels();
  140. }
  141. // ATOMIC BEGIN
  142. if (geometryDisabled_)
  143. UpdateBatchesHideGeometry();
  144. // ATOMIC END
  145. }
  146. Geometry* StaticModel::GetLodGeometry(unsigned batchIndex, unsigned level)
  147. {
  148. if (batchIndex >= geometries_.Size())
  149. return 0;
  150. // If level is out of range, use visible geometry
  151. if (level < geometries_[batchIndex].Size())
  152. return geometries_[batchIndex][level];
  153. else
  154. return batches_[batchIndex].geometry_;
  155. }
  156. unsigned StaticModel::GetNumOccluderTriangles()
  157. {
  158. unsigned triangles = 0;
  159. for (unsigned i = 0; i < batches_.Size(); ++i)
  160. {
  161. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  162. if (!geometry)
  163. continue;
  164. // Check that the material is suitable for occlusion (default material always is)
  165. Material* mat = batches_[i].material_;
  166. if (mat && !mat->GetOcclusion())
  167. continue;
  168. triangles += geometry->GetIndexCount() / 3;
  169. }
  170. return triangles;
  171. }
  172. bool StaticModel::DrawOcclusion(OcclusionBuffer* buffer)
  173. {
  174. for (unsigned i = 0; i < batches_.Size(); ++i)
  175. {
  176. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  177. if (!geometry)
  178. continue;
  179. // Check that the material is suitable for occlusion (default material always is) and set culling mode
  180. Material* material = batches_[i].material_;
  181. if (material)
  182. {
  183. if (!material->GetOcclusion())
  184. continue;
  185. buffer->SetCullMode(material->GetCullMode());
  186. }
  187. else
  188. buffer->SetCullMode(CULL_CCW);
  189. const unsigned char* vertexData;
  190. unsigned vertexSize;
  191. const unsigned char* indexData;
  192. unsigned indexSize;
  193. const PODVector<VertexElement>* elements;
  194. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elements);
  195. // Check for valid geometry data
  196. if (!vertexData || !indexData || !elements || VertexBuffer::GetElementOffset(*elements, TYPE_VECTOR3, SEM_POSITION) != 0)
  197. continue;
  198. unsigned indexStart = geometry->GetIndexStart();
  199. unsigned indexCount = geometry->GetIndexCount();
  200. // Draw and check for running out of triangles
  201. if (!buffer->AddTriangles(node_->GetWorldTransform(), vertexData, vertexSize, indexData, indexSize, indexStart, indexCount))
  202. return false;
  203. }
  204. return true;
  205. }
  206. void StaticModel::SetModel(Model* model)
  207. {
  208. if (model == model_)
  209. return;
  210. // ATOMIC BEGIN
  211. // If script erroneously calls StaticModel::SetModel on an AnimatedModel, warn and redirect
  212. if (GetType() == AnimatedModel::GetTypeStatic())
  213. {
  214. ATOMIC_LOGWARNING("StaticModel::SetModel() called on AnimatedModel. Redirecting to AnimatedModel::SetModel()");
  215. AnimatedModel* animatedModel = static_cast<AnimatedModel*>(this);
  216. animatedModel->SetModel(model);
  217. return;
  218. }
  219. // ATOMIC END
  220. if (!node_)
  221. {
  222. ATOMIC_LOGERROR("Can not set model while model component is not attached to a scene node");
  223. return;
  224. }
  225. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  226. if (model_)
  227. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  228. model_ = model;
  229. if (model)
  230. {
  231. SubscribeToEvent(model, E_RELOADFINISHED, ATOMIC_HANDLER(StaticModel, HandleModelReloadFinished));
  232. // Copy the subgeometry & LOD level structure
  233. SetNumGeometries(model->GetNumGeometries());
  234. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  235. const PODVector<Vector3>& geometryCenters = model->GetGeometryCenters();
  236. const Matrix3x4* worldTransform = node_ ? &node_->GetWorldTransform() : (const Matrix3x4*)0;
  237. for (unsigned i = 0; i < geometries.Size(); ++i)
  238. {
  239. batches_[i].worldTransform_ = worldTransform;
  240. geometries_[i] = geometries[i];
  241. geometryData_[i].center_ = geometryCenters[i];
  242. // ATOMIC BEGIN
  243. geometryData_[i].enabled_ = true;
  244. geometryData_[i].batchGeometry_ = 0;
  245. // ATOMIC END
  246. }
  247. SetBoundingBox(model->GetBoundingBox());
  248. ResetLodLevels();
  249. }
  250. else
  251. {
  252. SetNumGeometries(0);
  253. SetBoundingBox(BoundingBox());
  254. }
  255. MarkNetworkUpdate();
  256. }
  257. void StaticModel::SetMaterial(Material* material)
  258. {
  259. for (unsigned i = 0; i < batches_.Size(); ++i)
  260. batches_[i].material_ = material;
  261. MarkNetworkUpdate();
  262. }
  263. bool StaticModel::SetMaterial(unsigned index, Material* material)
  264. {
  265. if (index >= batches_.Size())
  266. {
  267. ATOMIC_LOGERROR("Material index out of bounds");
  268. return false;
  269. }
  270. batches_[index].material_ = material;
  271. MarkNetworkUpdate();
  272. return true;
  273. }
  274. void StaticModel::SetOcclusionLodLevel(unsigned level)
  275. {
  276. occlusionLodLevel_ = level;
  277. MarkNetworkUpdate();
  278. }
  279. void StaticModel::ApplyMaterialList(const String& fileName)
  280. {
  281. String useFileName = fileName;
  282. if (useFileName.Trimmed().Empty() && model_)
  283. useFileName = ReplaceExtension(model_->GetName(), ".txt");
  284. ResourceCache* cache = GetSubsystem<ResourceCache>();
  285. SharedPtr<File> file = cache->GetFile(useFileName, false);
  286. if (!file)
  287. return;
  288. unsigned index = 0;
  289. while (!file->IsEof() && index < batches_.Size())
  290. {
  291. Material* material = cache->GetResource<Material>(file->ReadLine());
  292. if (material)
  293. SetMaterial(index, material);
  294. ++index;
  295. }
  296. }
  297. Material* StaticModel::GetMaterial(unsigned index) const
  298. {
  299. return index < batches_.Size() ? batches_[index].material_ : (Material*)0;
  300. }
  301. bool StaticModel::IsInside(const Vector3& point) const
  302. {
  303. if (!node_)
  304. return false;
  305. Vector3 localPosition = node_->GetWorldTransform().Inverse() * point;
  306. return IsInsideLocal(localPosition);
  307. }
  308. bool StaticModel::IsInsideLocal(const Vector3& point) const
  309. {
  310. // Early-out if point is not inside bounding box
  311. if (boundingBox_.IsInside(point) == OUTSIDE)
  312. return false;
  313. Ray localRay(point, Vector3(1.0f, -1.0f, 1.0f));
  314. for (unsigned i = 0; i < batches_.Size(); ++i)
  315. {
  316. Geometry* geometry = batches_[i].geometry_;
  317. if (geometry)
  318. {
  319. if (geometry->IsInside(localRay))
  320. return true;
  321. }
  322. }
  323. return false;
  324. }
  325. void StaticModel::SetBoundingBox(const BoundingBox& box)
  326. {
  327. boundingBox_ = box;
  328. OnMarkedDirty(node_);
  329. }
  330. void StaticModel::SetNumGeometries(unsigned num)
  331. {
  332. batches_.Resize(num);
  333. geometries_.Resize(num);
  334. geometryData_.Resize(num);
  335. ResetLodLevels();
  336. }
  337. void StaticModel::SetModelAttr(const ResourceRef& value)
  338. {
  339. ResourceCache* cache = GetSubsystem<ResourceCache>();
  340. SetModel(cache->GetResource<Model>(value.name_));
  341. }
  342. void StaticModel::SetMaterialsAttr(const ResourceRefList& value)
  343. {
  344. ResourceCache* cache = GetSubsystem<ResourceCache>();
  345. for (unsigned i = 0; i < value.names_.Size(); ++i)
  346. SetMaterial(i, cache->GetResource<Material>(value.names_[i]));
  347. }
  348. ResourceRef StaticModel::GetModelAttr() const
  349. {
  350. return GetResourceRef(model_, Model::GetTypeStatic());
  351. }
  352. const ResourceRefList& StaticModel::GetMaterialsAttr() const
  353. {
  354. materialsAttr_.names_.Resize(batches_.Size());
  355. for (unsigned i = 0; i < batches_.Size(); ++i)
  356. materialsAttr_.names_[i] = GetResourceName(GetMaterial(i));
  357. return materialsAttr_;
  358. }
  359. void StaticModel::OnWorldBoundingBoxUpdate()
  360. {
  361. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  362. }
  363. void StaticModel::ResetLodLevels()
  364. {
  365. // Ensure that each subgeometry has at least one LOD level, and reset the current LOD level
  366. for (unsigned i = 0; i < batches_.Size(); ++i)
  367. {
  368. if (!geometries_[i].Size())
  369. geometries_[i].Resize(1);
  370. batches_[i].geometry_ = geometries_[i][0];
  371. geometryData_[i].lodLevel_ = 0;
  372. }
  373. // Find out the real LOD levels on next geometry update
  374. lodDistance_ = M_INFINITY;
  375. }
  376. void StaticModel::CalculateLodLevels()
  377. {
  378. for (unsigned i = 0; i < batches_.Size(); ++i)
  379. {
  380. const Vector<SharedPtr<Geometry> >& batchGeometries = geometries_[i];
  381. // If only one LOD geometry, no reason to go through the LOD calculation
  382. if (batchGeometries.Size() <= 1)
  383. continue;
  384. unsigned j;
  385. for (j = 1; j < batchGeometries.Size(); ++j)
  386. {
  387. if (batchGeometries[j] && lodDistance_ <= batchGeometries[j]->GetLodDistance())
  388. break;
  389. }
  390. unsigned newLodLevel = j - 1;
  391. if (geometryData_[i].lodLevel_ != newLodLevel)
  392. {
  393. geometryData_[i].lodLevel_ = newLodLevel;
  394. batches_[i].geometry_ = batchGeometries[newLodLevel];
  395. }
  396. }
  397. }
  398. void StaticModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  399. {
  400. Model* currentModel = model_;
  401. model_.Reset(); // Set null to allow to be re-set
  402. SetModel(currentModel);
  403. }
  404. // ATOMIC BEGIN
  405. bool StaticModel::GetGeometryVisible(const String& name)
  406. {
  407. if (!model_)
  408. return false;
  409. const Vector<String>& names = model_->GetGeometryNames();
  410. for (unsigned i = 0; i < names.Size(); i++)
  411. {
  412. if (name == names[i])
  413. return geometryData_[i].enabled_;
  414. }
  415. return false;
  416. }
  417. void StaticModel::ShowGeometry(const String& name)
  418. {
  419. if (!model_)
  420. return;
  421. const Vector<String>& names = model_->GetGeometryNames();
  422. for (unsigned i = 0; i < names.Size(); i++)
  423. {
  424. if (name == names[i])
  425. {
  426. if (geometryData_[i].batchGeometry_)
  427. batches_[i].geometry_ = geometryData_[i].batchGeometry_;
  428. geometryData_[i].batchGeometry_ = 0;
  429. geometryData_[i].enabled_ = true;
  430. }
  431. }
  432. geometryDisabled_ = false;
  433. for (unsigned i = 0; i < geometryData_.Size(); i++)
  434. {
  435. if (!geometryData_[i].enabled_)
  436. {
  437. geometryDisabled_ = true;
  438. break;
  439. }
  440. }
  441. }
  442. void StaticModel::HideGeometry(const String& name)
  443. {
  444. if (!model_)
  445. return;
  446. const Vector<String>& names = model_->GetGeometryNames();
  447. for (unsigned i = 0; i < names.Size(); i++)
  448. {
  449. if (name == names[i])
  450. {
  451. geometryDisabled_ = true;
  452. if (batches_[i].geometry_)
  453. geometryData_[i].batchGeometry_ = batches_[i].geometry_;
  454. geometryData_[i].enabled_ = false;
  455. }
  456. }
  457. }
  458. void StaticModel::SetGeometryEnabledAttr(const VariantVector& value)
  459. {
  460. if (!value.Size() || value.Size() != geometryData_.Size())
  461. {
  462. geometryDisabled_ = false;
  463. geometryEnabled_.Clear();
  464. return;
  465. }
  466. bool init = !geometryEnabled_.Size();
  467. geometryEnabled_ = value;
  468. for (unsigned i = 0; i < geometryData_.Size(); i++)
  469. {
  470. geometryData_[i].enabled_ = geometryEnabled_[i].GetBool();
  471. if (!geometryData_[i].enabled_)
  472. geometryDisabled_ = true;
  473. if (init)
  474. geometryData_[i].batchGeometry_ = 0;
  475. }
  476. }
  477. const VariantVector& StaticModel::GetGeometryEnabledAttr() const
  478. {
  479. geometryEnabled_.Resize(geometryData_.Size());
  480. geometryDisabled_ = false;
  481. for (unsigned i = 0; i < geometryData_.Size(); i++)
  482. {
  483. geometryEnabled_[i] = geometryData_[i].enabled_;
  484. if (!geometryData_[i].enabled_)
  485. geometryDisabled_ = true;
  486. }
  487. return geometryEnabled_;
  488. }
  489. void StaticModel::UpdateBatchesHideGeometry()
  490. {
  491. if (!geometryDisabled_ || !batches_.Size())
  492. return;
  493. for (unsigned i = 0; i < batches_.Size(); ++i)
  494. {
  495. SourceBatch* batch = &batches_[i];
  496. StaticModelGeometryData* data = &geometryData_[i];
  497. if (batch->geometry_)
  498. data->batchGeometry_ = batch->geometry_;
  499. if (data->enabled_ && !batch->geometry_)
  500. {
  501. batch->geometry_ = data->batchGeometry_;
  502. }
  503. else if (!data->enabled_ && batch->geometry_)
  504. {
  505. data->batchGeometry_ = batch->geometry_;
  506. batch->geometry_ = 0;
  507. }
  508. }
  509. }
  510. // ATOMIC END
  511. }