StaticModelGroup.cpp 13 KB

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