StaticModelGroup.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. //
  2. // Copyright (c) 2008-2018 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 "../Graphics/Batch.h"
  25. #include "../Graphics/Camera.h"
  26. #include "../Graphics/Geometry.h"
  27. #include "../Graphics/Material.h"
  28. #include "../Graphics/OcclusionBuffer.h"
  29. #include "../Graphics/OctreeQuery.h"
  30. #include "../Graphics/StaticModelGroup.h"
  31. #include "../Graphics/VertexBuffer.h"
  32. #include "../Scene/Scene.h"
  33. #include "../DebugNew.h"
  34. namespace Urho3D
  35. {
  36. extern const char* GEOMETRY_CATEGORY;
  37. static const StringVector instanceNodesStructureElementNames =
  38. {
  39. "Instance Count",
  40. " NodeID"
  41. };
  42. StaticModelGroup::StaticModelGroup(Context* context) :
  43. StaticModel(context),
  44. nodesDirty_(false),
  45. nodeIDsDirty_(false)
  46. {
  47. // Initialize the default node IDs attribute
  48. UpdateNodeIDs();
  49. }
  50. StaticModelGroup::~StaticModelGroup() = default;
  51. void StaticModelGroup::RegisterObject(Context* context)
  52. {
  53. context->RegisterFactory<StaticModelGroup>(GEOMETRY_CATEGORY);
  54. URHO3D_COPY_BASE_ATTRIBUTES(StaticModel);
  55. URHO3D_ACCESSOR_ATTRIBUTE("Instance Nodes", GetNodeIDsAttr, SetNodeIDsAttr,
  56. VariantVector, Variant::emptyVariantVector, AM_DEFAULT | AM_NODEIDVECTOR)
  57. .SetMetadata(AttributeMetadata::P_VECTOR_STRUCT_ELEMENTS, instanceNodesStructureElementNames);
  58. }
  59. void StaticModelGroup::ApplyAttributes()
  60. {
  61. if (!nodesDirty_)
  62. return;
  63. // Remove all old instance nodes before searching for new
  64. for (unsigned i = 0; i < instanceNodes_.Size(); ++i)
  65. {
  66. Node* node = instanceNodes_[i];
  67. if (node)
  68. node->RemoveListener(this);
  69. }
  70. instanceNodes_.Clear();
  71. Scene* scene = GetScene();
  72. if (scene)
  73. {
  74. // The first index stores the number of IDs redundantly. This is for editing
  75. for (unsigned i = 1; i < nodeIDsAttr_.Size(); ++i)
  76. {
  77. Node* node = scene->GetNode(nodeIDsAttr_[i].GetUInt());
  78. if (node)
  79. {
  80. WeakPtr<Node> instanceWeak(node);
  81. node->AddListener(this);
  82. instanceNodes_.Push(instanceWeak);
  83. }
  84. }
  85. }
  86. worldTransforms_.Resize(instanceNodes_.Size());
  87. numWorldTransforms_ = 0; // Correct amount will be found during world bounding box update
  88. nodesDirty_ = false;
  89. OnMarkedDirty(GetNode());
  90. }
  91. void StaticModelGroup::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  92. {
  93. // If no bones or no bone-level testing, use the Drawable test
  94. RayQueryLevel level = query.level_;
  95. if (level < RAY_AABB)
  96. {
  97. Drawable::ProcessRayQuery(query, results);
  98. return;
  99. }
  100. // Check ray hit distance to AABB before proceeding with more accurate tests
  101. // GetWorldBoundingBox() updates the world transforms
  102. if (query.ray_.HitDistance(GetWorldBoundingBox()) >= query.maxDistance_)
  103. return;
  104. for (unsigned i = 0; i < numWorldTransforms_; ++i)
  105. {
  106. // Initial test using AABB
  107. float distance = query.ray_.HitDistance(boundingBox_.Transformed(worldTransforms_[i]));
  108. Vector3 normal = -query.ray_.direction_;
  109. // Then proceed to OBB and triangle-level tests if necessary
  110. if (level >= RAY_OBB && distance < query.maxDistance_)
  111. {
  112. Matrix3x4 inverse = worldTransforms_[i].Inverse();
  113. Ray localRay = query.ray_.Transformed(inverse);
  114. distance = localRay.HitDistance(boundingBox_);
  115. if (level == RAY_TRIANGLE && distance < query.maxDistance_)
  116. {
  117. distance = M_INFINITY;
  118. for (unsigned j = 0; j < batches_.Size(); ++j)
  119. {
  120. Geometry* geometry = batches_[j].geometry_;
  121. if (geometry)
  122. {
  123. Vector3 geometryNormal;
  124. float geometryDistance = geometry->GetHitDistance(localRay, &geometryNormal);
  125. if (geometryDistance < query.maxDistance_ && geometryDistance < distance)
  126. {
  127. distance = geometryDistance;
  128. normal = (worldTransforms_[i] * Vector4(geometryNormal, 0.0f)).Normalized();
  129. }
  130. }
  131. }
  132. }
  133. }
  134. if (distance < query.maxDistance_)
  135. {
  136. RayQueryResult result;
  137. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  138. result.normal_ = normal;
  139. result.distance_ = distance;
  140. result.drawable_ = this;
  141. result.node_ = node_;
  142. result.subObject_ = i;
  143. results.Push(result);
  144. }
  145. }
  146. }
  147. void StaticModelGroup::UpdateBatches(const FrameInfo& frame)
  148. {
  149. // Getting the world bounding box ensures the transforms are updated
  150. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  151. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  152. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  153. if (batches_.Size() > 1)
  154. {
  155. for (unsigned i = 0; i < batches_.Size(); ++i)
  156. {
  157. batches_[i].distance_ = frame.camera_->GetDistance(worldTransform * geometryData_[i].center_);
  158. batches_[i].worldTransform_ = numWorldTransforms_ ? &worldTransforms_[0] : &Matrix3x4::IDENTITY;
  159. batches_[i].numWorldTransforms_ = numWorldTransforms_;
  160. }
  161. }
  162. else if (batches_.Size() == 1)
  163. {
  164. batches_[0].distance_ = distance_;
  165. batches_[0].worldTransform_ = numWorldTransforms_ ? &worldTransforms_[0] : &Matrix3x4::IDENTITY;
  166. batches_[0].numWorldTransforms_ = numWorldTransforms_;
  167. }
  168. float scale = worldBoundingBox.Size().DotProduct(DOT_SCALE);
  169. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  170. if (newLodDistance != lodDistance_)
  171. {
  172. lodDistance_ = newLodDistance;
  173. CalculateLodLevels();
  174. }
  175. }
  176. unsigned StaticModelGroup::GetNumOccluderTriangles()
  177. {
  178. // Make sure instance transforms are up-to-date
  179. GetWorldBoundingBox();
  180. unsigned triangles = 0;
  181. for (unsigned i = 0; i < batches_.Size(); ++i)
  182. {
  183. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  184. if (!geometry)
  185. continue;
  186. // Check that the material is suitable for occlusion (default material always is)
  187. Material* mat = batches_[i].material_;
  188. if (mat && !mat->GetOcclusion())
  189. continue;
  190. triangles += numWorldTransforms_ * geometry->GetIndexCount() / 3;
  191. }
  192. return triangles;
  193. }
  194. bool StaticModelGroup::DrawOcclusion(OcclusionBuffer* buffer)
  195. {
  196. // Make sure instance transforms are up-to-date
  197. GetWorldBoundingBox();
  198. for (unsigned i = 0; i < numWorldTransforms_; ++i)
  199. {
  200. for (unsigned j = 0; j < batches_.Size(); ++j)
  201. {
  202. Geometry* geometry = GetLodGeometry(j, occlusionLodLevel_);
  203. if (!geometry)
  204. continue;
  205. // Check that the material is suitable for occlusion (default material always is) and set culling mode
  206. Material* material = batches_[j].material_;
  207. if (material)
  208. {
  209. if (!material->GetOcclusion())
  210. continue;
  211. buffer->SetCullMode(material->GetCullMode());
  212. }
  213. else
  214. buffer->SetCullMode(CULL_CCW);
  215. const unsigned char* vertexData;
  216. unsigned vertexSize;
  217. const unsigned char* indexData;
  218. unsigned indexSize;
  219. const PODVector<VertexElement>* elements;
  220. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elements);
  221. // Check for valid geometry data
  222. if (!vertexData || !indexData || !elements || VertexBuffer::GetElementOffset(*elements, TYPE_VECTOR3, SEM_POSITION) != 0)
  223. continue;
  224. unsigned indexStart = geometry->GetIndexStart();
  225. unsigned indexCount = geometry->GetIndexCount();
  226. // Draw and check for running out of triangles
  227. if (!buffer->AddTriangles(worldTransforms_[i], vertexData, vertexSize, indexData, indexSize, indexStart, indexCount))
  228. return false;
  229. }
  230. }
  231. return true;
  232. }
  233. void StaticModelGroup::AddInstanceNode(Node* node)
  234. {
  235. if (!node)
  236. return;
  237. WeakPtr<Node> instanceWeak(node);
  238. if (instanceNodes_.Contains(instanceWeak))
  239. return;
  240. // Add as a listener for the instance node, so that we know to dirty the transforms when the node moves or is enabled/disabled
  241. node->AddListener(this);
  242. instanceNodes_.Push(instanceWeak);
  243. UpdateNumTransforms();
  244. }
  245. void StaticModelGroup::RemoveInstanceNode(Node* node)
  246. {
  247. if (!node)
  248. return;
  249. WeakPtr<Node> instanceWeak(node);
  250. Vector<WeakPtr<Node> >::Iterator i = instanceNodes_.Find(instanceWeak);
  251. if (i == instanceNodes_.End())
  252. return;
  253. node->RemoveListener(this);
  254. instanceNodes_.Erase(i);
  255. UpdateNumTransforms();
  256. }
  257. void StaticModelGroup::RemoveAllInstanceNodes()
  258. {
  259. for (unsigned i = 0; i < instanceNodes_.Size(); ++i)
  260. {
  261. Node* node = instanceNodes_[i];
  262. if (node)
  263. node->RemoveListener(this);
  264. }
  265. instanceNodes_.Clear();
  266. UpdateNumTransforms();
  267. }
  268. Node* StaticModelGroup::GetInstanceNode(unsigned index) const
  269. {
  270. return index < instanceNodes_.Size() ? instanceNodes_[index] : nullptr;
  271. }
  272. void StaticModelGroup::SetNodeIDsAttr(const VariantVector& value)
  273. {
  274. // Just remember the node IDs. They need to go through the SceneResolver, and we actually find the nodes during
  275. // ApplyAttributes()
  276. if (value.Size())
  277. {
  278. nodeIDsAttr_.Clear();
  279. unsigned index = 0;
  280. unsigned numInstances = value[index++].GetUInt();
  281. // Prevent crash on entering negative value in the editor
  282. if (numInstances > M_MAX_INT)
  283. numInstances = 0;
  284. nodeIDsAttr_.Push(numInstances);
  285. while (numInstances--)
  286. {
  287. // If vector contains less IDs than should, fill the rest with zeroes
  288. if (index < value.Size())
  289. nodeIDsAttr_.Push(value[index++].GetUInt());
  290. else
  291. nodeIDsAttr_.Push(0);
  292. }
  293. }
  294. else
  295. {
  296. nodeIDsAttr_.Clear();
  297. nodeIDsAttr_.Push(0);
  298. }
  299. nodesDirty_ = true;
  300. nodeIDsDirty_ = false;
  301. }
  302. const VariantVector& StaticModelGroup::GetNodeIDsAttr() const
  303. {
  304. if (nodeIDsDirty_)
  305. UpdateNodeIDs();
  306. return nodeIDsAttr_;
  307. }
  308. void StaticModelGroup::OnNodeSetEnabled(Node* node)
  309. {
  310. Drawable::OnMarkedDirty(node);
  311. }
  312. void StaticModelGroup::OnWorldBoundingBoxUpdate()
  313. {
  314. // Update transforms and bounding box at the same time to have to go through the objects only once
  315. unsigned index = 0;
  316. BoundingBox worldBox;
  317. for (unsigned i = 0; i < instanceNodes_.Size(); ++i)
  318. {
  319. Node* node = instanceNodes_[i];
  320. if (!node || !node->IsEnabled())
  321. continue;
  322. const Matrix3x4& worldTransform = node->GetWorldTransform();
  323. worldTransforms_[index++] = worldTransform;
  324. worldBox.Merge(boundingBox_.Transformed(worldTransform));
  325. }
  326. worldBoundingBox_ = worldBox;
  327. // Store the amount of valid instances we found instead of resizing worldTransforms_. This is because this function may be
  328. // called from multiple worker threads simultaneously
  329. numWorldTransforms_ = index;
  330. }
  331. void StaticModelGroup::UpdateNumTransforms()
  332. {
  333. worldTransforms_.Resize(instanceNodes_.Size());
  334. numWorldTransforms_ = 0; // Correct amount will be during world bounding box update
  335. nodeIDsDirty_ = true;
  336. OnMarkedDirty(GetNode());
  337. MarkNetworkUpdate();
  338. }
  339. void StaticModelGroup::UpdateNodeIDs() const
  340. {
  341. unsigned numInstances = instanceNodes_.Size();
  342. nodeIDsAttr_.Clear();
  343. nodeIDsAttr_.Push(numInstances);
  344. for (unsigned i = 0; i < numInstances; ++i)
  345. {
  346. Node* node = instanceNodes_[i];
  347. nodeIDsAttr_.Push(node ? node->GetID() : 0);
  348. }
  349. nodeIDsDirty_ = false;
  350. }
  351. }