Renderer2D.cpp 18 KB

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