Renderer2D.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. //
  2. // Copyright (c) 2008-2016 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 "../Core/WorkQueue.h"
  26. #include "../Graphics/Camera.h"
  27. #include "../Graphics/Geometry.h"
  28. #include "../Graphics/GraphicsEvents.h"
  29. #include "../Graphics/IndexBuffer.h"
  30. #include "../Graphics/Material.h"
  31. #include "../Graphics/OctreeQuery.h"
  32. #include "../Graphics/Technique.h"
  33. #include "../Graphics/Texture2D.h"
  34. #include "../Graphics/VertexBuffer.h"
  35. #include "../Graphics/View.h"
  36. #include "../IO/Log.h"
  37. #include "../Scene/Node.h"
  38. #include "../Scene/Scene.h"
  39. #include "../Urho2D/Drawable2D.h"
  40. #include "../Urho2D/Renderer2D.h"
  41. #include "../DebugNew.h"
  42. namespace Urho3D
  43. {
  44. extern const char* blendModeNames[];
  45. static const unsigned MASK_VERTEX2D = MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1;
  46. ViewBatchInfo2D::ViewBatchInfo2D() :
  47. vertexBufferUpdateFrameNumber_(0),
  48. indexCount_(0),
  49. vertexCount_(0),
  50. batchUpdatedFrameNumber_(0),
  51. batchCount_(0)
  52. {
  53. }
  54. Renderer2D::Renderer2D(Context* context) :
  55. Drawable(context, DRAWABLE_GEOMETRY),
  56. material_(new Material(context)),
  57. indexBuffer_(new IndexBuffer(context_)),
  58. viewMask_(DEFAULT_VIEWMASK)
  59. {
  60. material_->SetName("Urho2D");
  61. Technique* tech = new Technique(context_);
  62. Pass* pass = tech->CreatePass("alpha");
  63. pass->SetVertexShader("Urho2D");
  64. pass->SetPixelShader("Urho2D");
  65. pass->SetDepthWrite(false);
  66. cachedTechniques_[BLEND_REPLACE] = tech;
  67. material_->SetTechnique(0, tech);
  68. material_->SetCullMode(CULL_NONE);
  69. frame_.frameNumber_ = 0;
  70. SubscribeToEvent(E_BEGINVIEWUPDATE, URHO3D_HANDLER(Renderer2D, HandleBeginViewUpdate));
  71. }
  72. Renderer2D::~Renderer2D()
  73. {
  74. }
  75. void Renderer2D::RegisterObject(Context* context)
  76. {
  77. context->RegisterFactory<Renderer2D>();
  78. }
  79. static inline bool CompareRayQueryResults(RayQueryResult& lr, RayQueryResult& rr)
  80. {
  81. Drawable2D* lhs = static_cast<Drawable2D*>(lr.drawable_);
  82. Drawable2D* rhs = static_cast<Drawable2D*>(rr.drawable_);
  83. if (lhs->GetLayer() != rhs->GetLayer())
  84. return lhs->GetLayer() > rhs->GetLayer();
  85. if (lhs->GetOrderInLayer() != rhs->GetOrderInLayer())
  86. return lhs->GetOrderInLayer() > rhs->GetOrderInLayer();
  87. return lhs->GetID() > rhs->GetID();
  88. }
  89. void Renderer2D::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  90. {
  91. unsigned resultSize = results.Size();
  92. for (unsigned i = 0; i < drawables_.Size(); ++i)
  93. {
  94. if (drawables_[i]->GetViewMask() & query.viewMask_)
  95. drawables_[i]->ProcessRayQuery(query, results);
  96. }
  97. if (results.Size() != resultSize)
  98. Sort(results.Begin() + resultSize, results.End(), CompareRayQueryResults);
  99. }
  100. void Renderer2D::UpdateBatches(const FrameInfo& frame)
  101. {
  102. unsigned count = batches_.Size();
  103. // Update non-thread critical parts of the source batches
  104. for (unsigned i = 0; i < count; ++i)
  105. {
  106. batches_[i].distance_ = 10.0f + (count - i) * 0.001f;
  107. batches_[i].worldTransform_ = &Matrix3x4::IDENTITY;
  108. }
  109. }
  110. void Renderer2D::UpdateGeometry(const FrameInfo& frame)
  111. {
  112. unsigned indexCount = 0;
  113. for (HashMap<Camera*, ViewBatchInfo2D>::ConstIterator i = viewBatchInfos_.Begin(); i != viewBatchInfos_.End(); ++i)
  114. {
  115. if (i->second_.batchUpdatedFrameNumber_ == frame_.frameNumber_)
  116. indexCount = Max(indexCount, i->second_.indexCount_);
  117. }
  118. // Fill index buffer
  119. if (indexBuffer_->GetIndexCount() < indexCount || indexBuffer_->IsDataLost())
  120. {
  121. bool largeIndices = (indexCount * 4 / 6) > 0xffff;
  122. indexBuffer_->SetSize(indexCount, largeIndices);
  123. void* buffer = indexBuffer_->Lock(0, indexCount, true);
  124. if (buffer)
  125. {
  126. unsigned quadCount = indexCount / 6;
  127. if (largeIndices)
  128. {
  129. unsigned* dest = reinterpret_cast<unsigned*>(buffer);
  130. for (unsigned i = 0; i < quadCount; ++i)
  131. {
  132. unsigned base = i * 4;
  133. dest[0] = base;
  134. dest[1] = base + 1;
  135. dest[2] = base + 2;
  136. dest[3] = base;
  137. dest[4] = base + 2;
  138. dest[5] = base + 3;
  139. dest += 6;
  140. }
  141. }
  142. else
  143. {
  144. unsigned short* dest = reinterpret_cast<unsigned short*>(buffer);
  145. for (unsigned i = 0; i < quadCount; ++i)
  146. {
  147. unsigned base = i * 4;
  148. dest[0] = (unsigned short)(base);
  149. dest[1] = (unsigned short)(base + 1);
  150. dest[2] = (unsigned short)(base + 2);
  151. dest[3] = (unsigned short)(base);
  152. dest[4] = (unsigned short)(base + 2);
  153. dest[5] = (unsigned short)(base + 3);
  154. dest += 6;
  155. }
  156. }
  157. indexBuffer_->Unlock();
  158. }
  159. else
  160. {
  161. URHO3D_LOGERROR("Failed to lock index buffer");
  162. return;
  163. }
  164. }
  165. Camera* camera = frame.camera_;
  166. ViewBatchInfo2D& viewBatchInfo = viewBatchInfos_[camera];
  167. if (viewBatchInfo.vertexBufferUpdateFrameNumber_ != frame_.frameNumber_)
  168. {
  169. unsigned vertexCount = viewBatchInfo.vertexCount_;
  170. VertexBuffer* vertexBuffer = viewBatchInfo.vertexBuffer_;
  171. if (vertexBuffer->GetVertexCount() < vertexCount)
  172. vertexBuffer->SetSize(vertexCount, MASK_VERTEX2D, true);
  173. if (vertexCount)
  174. {
  175. Vertex2D* dest = reinterpret_cast<Vertex2D*>(vertexBuffer->Lock(0, vertexCount, true));
  176. if (dest)
  177. {
  178. const PODVector<const SourceBatch2D*>& sourceBatches = viewBatchInfo.sourceBatches_;
  179. for (unsigned b = 0; b < sourceBatches.Size(); ++b)
  180. {
  181. const Vector<Vertex2D>& vertices = sourceBatches[b]->vertices_;
  182. for (unsigned i = 0; i < vertices.Size(); ++i)
  183. dest[i] = vertices[i];
  184. dest += vertices.Size();
  185. }
  186. vertexBuffer->Unlock();
  187. }
  188. else
  189. URHO3D_LOGERROR("Failed to lock vertex buffer");
  190. }
  191. viewBatchInfo.vertexBufferUpdateFrameNumber_ = frame_.frameNumber_;
  192. }
  193. }
  194. UpdateGeometryType Renderer2D::GetUpdateGeometryType()
  195. {
  196. return UPDATE_MAIN_THREAD;
  197. }
  198. void Renderer2D::AddDrawable(Drawable2D* drawable)
  199. {
  200. if (!drawable)
  201. return;
  202. drawables_.Push(drawable);
  203. }
  204. void Renderer2D::RemoveDrawable(Drawable2D* drawable)
  205. {
  206. if (!drawable)
  207. return;
  208. drawables_.Remove(drawable);
  209. }
  210. Material* Renderer2D::GetMaterial(Texture2D* texture, BlendMode blendMode)
  211. {
  212. if (!texture)
  213. return material_;
  214. HashMap<Texture2D*, HashMap<int, SharedPtr<Material> > >::Iterator t = cachedMaterials_.Find(texture);
  215. if (t == cachedMaterials_.End())
  216. {
  217. SharedPtr<Material> newMaterial = CreateMaterial(texture, blendMode);
  218. cachedMaterials_[texture][blendMode] = newMaterial;
  219. return newMaterial;
  220. }
  221. HashMap<int, SharedPtr<Material> >& materials = t->second_;
  222. HashMap<int, SharedPtr<Material> >::Iterator b = materials.Find(blendMode);
  223. if (b != materials.End())
  224. return b->second_;
  225. SharedPtr<Material> newMaterial = CreateMaterial(texture, blendMode);
  226. materials[blendMode] = newMaterial;
  227. return newMaterial;
  228. }
  229. bool Renderer2D::CheckVisibility(Drawable2D* drawable) const
  230. {
  231. if ((viewMask_ & drawable->GetViewMask()) == 0)
  232. return false;
  233. const BoundingBox& box = drawable->GetWorldBoundingBox();
  234. return frustum_.IsInsideFast(box) != OUTSIDE;
  235. }
  236. void Renderer2D::OnWorldBoundingBoxUpdate()
  237. {
  238. // Set a large dummy bounding box to ensure the renderer is rendered
  239. boundingBox_.Define(-M_LARGE_VALUE, M_LARGE_VALUE);
  240. worldBoundingBox_ = boundingBox_;
  241. }
  242. SharedPtr<Material> Renderer2D::CreateMaterial(Texture2D* texture, BlendMode blendMode)
  243. {
  244. SharedPtr<Material> newMaterial = material_->Clone();
  245. HashMap<int, SharedPtr<Technique> >::Iterator techIt = cachedTechniques_.Find((int)blendMode);
  246. if (techIt == cachedTechniques_.End())
  247. {
  248. SharedPtr<Technique> tech(new Technique(context_));
  249. Pass* pass = tech->CreatePass("alpha");
  250. pass->SetVertexShader("Urho2D");
  251. pass->SetPixelShader("Urho2D");
  252. pass->SetDepthWrite(false);
  253. pass->SetBlendMode(blendMode);
  254. techIt = cachedTechniques_.Insert(MakePair((int)blendMode, tech));
  255. }
  256. newMaterial->SetTechnique(0, techIt->second_.Get());
  257. newMaterial->SetName(texture->GetName() + "_" + blendModeNames[blendMode]);
  258. newMaterial->SetTexture(TU_DIFFUSE, texture);
  259. return newMaterial;
  260. }
  261. void CheckDrawableVisibility(const WorkItem* item, unsigned threadIndex)
  262. {
  263. Renderer2D* renderer = reinterpret_cast<Renderer2D*>(item->aux_);
  264. Drawable2D** start = reinterpret_cast<Drawable2D**>(item->start_);
  265. Drawable2D** end = reinterpret_cast<Drawable2D**>(item->end_);
  266. while (start != end)
  267. {
  268. Drawable2D* drawable = *start++;
  269. if (renderer->CheckVisibility(drawable))
  270. drawable->MarkInView(renderer->frame_);
  271. }
  272. }
  273. void Renderer2D::HandleBeginViewUpdate(StringHash eventType, VariantMap& eventData)
  274. {
  275. using namespace BeginViewUpdate;
  276. // Check that we are updating the correct scene
  277. if (GetScene() != eventData[P_SCENE].GetPtr())
  278. return;
  279. frame_ = static_cast<View*>(eventData[P_VIEW].GetPtr())->GetFrameInfo();
  280. URHO3D_PROFILE(UpdateRenderer2D);
  281. Camera* camera = static_cast<Camera*>(eventData[P_CAMERA].GetPtr());
  282. frustum_ = camera->GetFrustum();
  283. viewMask_ = camera->GetViewMask();
  284. // Check visibility
  285. {
  286. URHO3D_PROFILE(CheckDrawableVisibility);
  287. WorkQueue* queue = GetSubsystem<WorkQueue>();
  288. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  289. int drawablesPerItem = drawables_.Size() / numWorkItems;
  290. PODVector<Drawable2D*>::Iterator start = drawables_.Begin();
  291. for (int i = 0; i < numWorkItems; ++i)
  292. {
  293. SharedPtr<WorkItem> item = queue->GetFreeItem();
  294. item->priority_ = M_MAX_UNSIGNED;
  295. item->workFunction_ = CheckDrawableVisibility;
  296. item->aux_ = this;
  297. PODVector<Drawable2D*>::Iterator end = drawables_.End();
  298. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  299. end = start + drawablesPerItem;
  300. item->start_ = &(*start);
  301. item->end_ = &(*end);
  302. queue->AddWorkItem(item);
  303. start = end;
  304. }
  305. queue->Complete(M_MAX_UNSIGNED);
  306. }
  307. ViewBatchInfo2D& viewBatchInfo = viewBatchInfos_[camera];
  308. // Create vertex buffer
  309. if (!viewBatchInfo.vertexBuffer_)
  310. viewBatchInfo.vertexBuffer_ = new VertexBuffer(context_);
  311. UpdateViewBatchInfo(viewBatchInfo, camera);
  312. // Go through the drawables to form geometries & batches and calculate the total vertex / index count,
  313. // but upload the actual vertex data later. The idea is that the View class copies our batch vector to
  314. // its internal data structures, so we can reuse the batches for each view, provided that unique Geometry
  315. // objects are used for each view to specify the draw ranges
  316. batches_.Resize(viewBatchInfo.batchCount_);
  317. for (unsigned i = 0; i < viewBatchInfo.batchCount_; ++i)
  318. {
  319. batches_[i].distance_ = viewBatchInfo.distances_[i];
  320. batches_[i].material_ = viewBatchInfo.materials_[i];
  321. batches_[i].geometry_ = viewBatchInfo.geometries_[i];
  322. }
  323. }
  324. void Renderer2D::GetDrawables(PODVector<Drawable2D*>& dest, Node* node)
  325. {
  326. if (!node || !node->IsEnabled())
  327. return;
  328. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  329. for (Vector<SharedPtr<Component> >::ConstIterator i = components.Begin(); i != components.End(); ++i)
  330. {
  331. Drawable2D* drawable = dynamic_cast<Drawable2D*>(i->Get());
  332. if (drawable && drawable->IsEnabled())
  333. dest.Push(drawable);
  334. }
  335. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  336. for (Vector<SharedPtr<Node> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  337. GetDrawables(dest, i->Get());
  338. }
  339. static inline bool CompareSourceBatch2Ds(const SourceBatch2D* lhs, const SourceBatch2D* rhs)
  340. {
  341. if (lhs->distance_ != rhs->distance_)
  342. return lhs->distance_ > rhs->distance_;
  343. if (lhs->drawOrder_ != rhs->drawOrder_)
  344. return lhs->drawOrder_ < rhs->drawOrder_;
  345. if (lhs->material_ != rhs->material_)
  346. return lhs->material_->GetNameHash() < rhs->material_->GetNameHash();
  347. return lhs < rhs;
  348. }
  349. void Renderer2D::UpdateViewBatchInfo(ViewBatchInfo2D& viewBatchInfo, Camera* camera)
  350. {
  351. // Already update in same frame
  352. if (viewBatchInfo.batchUpdatedFrameNumber_ == frame_.frameNumber_)
  353. return;
  354. PODVector<const SourceBatch2D*>& sourceBatches = viewBatchInfo.sourceBatches_;
  355. sourceBatches.Clear();
  356. for (unsigned d = 0; d < drawables_.Size(); ++d)
  357. {
  358. if (!drawables_[d]->IsInView(camera))
  359. continue;
  360. const Vector<SourceBatch2D>& batches = drawables_[d]->GetSourceBatches();
  361. for (unsigned b = 0; b < batches.Size(); ++b)
  362. {
  363. if (batches[b].material_ && !batches[b].vertices_.Empty())
  364. sourceBatches.Push(&batches[b]);
  365. }
  366. }
  367. for (unsigned i = 0; i < sourceBatches.Size(); ++i)
  368. {
  369. const SourceBatch2D* sourceBatch = sourceBatches[i];
  370. Vector3 worldPos = sourceBatch->owner_->GetNode()->GetWorldPosition();
  371. sourceBatch->distance_ = camera->GetDistance(worldPos);
  372. }
  373. Sort(sourceBatches.Begin(), sourceBatches.End(), CompareSourceBatch2Ds);
  374. viewBatchInfo.batchCount_ = 0;
  375. Material* currMaterial = 0;
  376. unsigned iStart = 0;
  377. unsigned iCount = 0;
  378. unsigned vStart = 0;
  379. unsigned vCount = 0;
  380. float distance = M_INFINITY;
  381. for (unsigned b = 0; b < sourceBatches.Size(); ++b)
  382. {
  383. distance = Min(distance, sourceBatches[b]->distance_);
  384. Material* material = sourceBatches[b]->material_;
  385. const Vector<Vertex2D>& vertices = sourceBatches[b]->vertices_;
  386. // When new material encountered, finish the current batch and start new
  387. if (currMaterial != material)
  388. {
  389. if (currMaterial)
  390. {
  391. AddViewBatch(viewBatchInfo, currMaterial, iStart, iCount, vStart, vCount, distance);
  392. iStart += iCount;
  393. iCount = 0;
  394. vStart += vCount;
  395. vCount = 0;
  396. distance = M_INFINITY;
  397. }
  398. currMaterial = material;
  399. }
  400. iCount += vertices.Size() * 6 / 4;
  401. vCount += vertices.Size();
  402. }
  403. // Add the final batch if necessary
  404. if (currMaterial && vCount)
  405. AddViewBatch(viewBatchInfo, currMaterial, iStart, iCount, vStart, vCount,distance);
  406. viewBatchInfo.indexCount_ = iStart + iCount;
  407. viewBatchInfo.vertexCount_ = vStart + vCount;
  408. viewBatchInfo.batchUpdatedFrameNumber_ = frame_.frameNumber_;
  409. }
  410. void Renderer2D::AddViewBatch(ViewBatchInfo2D& viewBatchInfo, Material* material,
  411. unsigned indexStart, unsigned indexCount, unsigned vertexStart, unsigned vertexCount, float distance)
  412. {
  413. if (!material || indexCount == 0 || vertexCount == 0)
  414. return;
  415. if (viewBatchInfo.distances_.Size() <= viewBatchInfo.batchCount_)
  416. viewBatchInfo.distances_.Resize(viewBatchInfo.batchCount_ + 1);
  417. viewBatchInfo.distances_[viewBatchInfo.batchCount_] = distance;
  418. if (viewBatchInfo.materials_.Size() <= viewBatchInfo.batchCount_)
  419. viewBatchInfo.materials_.Resize(viewBatchInfo.batchCount_ + 1);
  420. viewBatchInfo.materials_[viewBatchInfo.batchCount_] = material;
  421. // Allocate new geometry if necessary
  422. if (viewBatchInfo.geometries_.Size() <= viewBatchInfo.batchCount_)
  423. {
  424. SharedPtr<Geometry> geometry(new Geometry(context_));
  425. geometry->SetIndexBuffer(indexBuffer_);
  426. geometry->SetVertexBuffer(0, viewBatchInfo.vertexBuffer_);
  427. viewBatchInfo.geometries_.Push(geometry);
  428. }
  429. Geometry* geometry = viewBatchInfo.geometries_[viewBatchInfo.batchCount_];
  430. geometry->SetDrawRange(TRIANGLE_LIST, indexStart, indexCount, vertexStart, vertexCount, false);
  431. viewBatchInfo.batchCount_++;
  432. }
  433. }