Renderer2D.cpp 17 KB

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