StaticModelGroup.cpp 12 KB

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