Renderer2D.cpp 17 KB

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