Renderer2D.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. //
  2. // Copyright (c) 2008-2014 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 "Camera.h"
  24. #include "Context.h"
  25. #include "Drawable2D.h"
  26. #include "Geometry.h"
  27. #include "GraphicsEvents.h"
  28. #include "IndexBuffer.h"
  29. #include "Log.h"
  30. #include "Material.h"
  31. #include "Node.h"
  32. #include "Profiler.h"
  33. #include "Renderer2D.h"
  34. #include "Scene.h"
  35. #include "Sort.h"
  36. #include "VertexBuffer.h"
  37. #include "WorkQueue.h"
  38. #include "Texture2D.h"
  39. #include "Technique.h"
  40. #include "DebugNew.h"
  41. namespace Urho3D
  42. {
  43. extern const char* blendModeNames[];
  44. Renderer2D::Renderer2D(Context* context) :
  45. Drawable(context, DRAWABLE_RENDERER2D),
  46. indexBuffer_(new IndexBuffer(context_)),
  47. vertexBuffer_(new VertexBuffer(context_)),
  48. frustum_(0),
  49. indexCount_(0),
  50. vertexCount_(0)
  51. {
  52. SubscribeToEvent(E_BEGINVIEWUPDATE, HANDLER(Renderer2D, HandleBeginViewUpdate));
  53. }
  54. Renderer2D::~Renderer2D()
  55. {
  56. }
  57. void Renderer2D::RegisterObject(Context* context)
  58. {
  59. context->RegisterFactory<Renderer2D>();
  60. }
  61. void Renderer2D::UpdateBatches(const FrameInfo& frame)
  62. {
  63. unsigned count = batches_.Size();
  64. // Update non-thread critical parts of the source batches
  65. for (unsigned i = 0; i < count; ++i)
  66. {
  67. batches_[i].distance_ = 10.0f + (count - i) * 0.001f;
  68. batches_[i].worldTransform_ = &Matrix3x4::IDENTITY;
  69. }
  70. }
  71. void Renderer2D::UpdateGeometry(const FrameInfo& frame)
  72. {
  73. // Fill index buffer
  74. if (indexBuffer_->GetIndexCount() < indexCount_)
  75. {
  76. bool largeIndices = vertexCount_ > 0xffff;
  77. indexBuffer_->SetSize(indexCount_, largeIndices);
  78. void* buffer = indexBuffer_->Lock(0, indexCount_, true);
  79. if (buffer)
  80. {
  81. unsigned quadCount = indexCount_ / 6;
  82. if (largeIndices)
  83. {
  84. unsigned* dest = reinterpret_cast<unsigned*>(buffer);
  85. for (unsigned i = 0; i < quadCount; ++i)
  86. {
  87. unsigned base = i * 4;
  88. dest[0] = base;
  89. dest[1] = base + 1;
  90. dest[2] = base + 2;
  91. dest[3] = base;
  92. dest[4] = base + 2;
  93. dest[5] = base + 3;
  94. dest += 6;
  95. }
  96. }
  97. else
  98. {
  99. unsigned short* dest = reinterpret_cast<unsigned short*>(buffer);
  100. for (unsigned i = 0; i < quadCount; ++i)
  101. {
  102. unsigned base = i * 4;
  103. dest[0] = (unsigned short)(base);
  104. dest[1] = (unsigned short)(base + 1);
  105. dest[2] = (unsigned short)(base + 2);
  106. dest[3] = (unsigned short)(base);
  107. dest[4] = (unsigned short)(base + 2);
  108. dest[5] = (unsigned short)(base + 3);
  109. dest += 6;
  110. }
  111. }
  112. indexBuffer_->Unlock();
  113. }
  114. else
  115. {
  116. LOGERROR("Failed to lock index buffer");
  117. return;
  118. }
  119. }
  120. if (vertexBuffer_->GetVertexCount() < vertexCount_)
  121. vertexBuffer_->SetSize(vertexCount_, MASK_VERTEX2D);
  122. if (vertexCount_)
  123. {
  124. Vertex2D* dest = reinterpret_cast<Vertex2D*>(vertexBuffer_->Lock(0, vertexCount_, true));
  125. if (dest)
  126. {
  127. for (unsigned d = 0; d < drawables_.Size(); ++d)
  128. {
  129. if (!drawables_[d]->GetVisibility())
  130. continue;
  131. const Vector<Vertex2D>& vertices = drawables_[d]->GetVertices();
  132. for (unsigned i = 0; i < vertices.Size(); ++i)
  133. dest[i] = vertices[i];
  134. dest += vertices.Size();
  135. }
  136. vertexBuffer_->Unlock();
  137. }
  138. else
  139. LOGERROR("Failed to lock vertex buffer");
  140. }
  141. }
  142. UpdateGeometryType Renderer2D::GetUpdateGeometryType()
  143. {
  144. return UPDATE_MAIN_THREAD;
  145. }
  146. bool Renderer2D::CheckVisibility(Drawable2D* drawable) const
  147. {
  148. const BoundingBox& box = drawable->GetWorldBoundingBox();
  149. if (frustum_)
  150. return frustum_->IsInsideFast(box) != OUTSIDE;
  151. return frustumBoundingBox_.IsInsideFast(box) != OUTSIDE;
  152. }
  153. void Renderer2D::OnWorldBoundingBoxUpdate()
  154. {
  155. // Set a large dummy bounding box to ensure the renderer is rendered
  156. boundingBox_.Define(-M_LARGE_VALUE, M_LARGE_VALUE);
  157. worldBoundingBox_ = boundingBox_;
  158. }
  159. static void CheckDrawableVisibility(const WorkItem* item, unsigned threadIndex)
  160. {
  161. Renderer2D* renderer = reinterpret_cast<Renderer2D*>(item->aux_);
  162. Drawable2D** start = reinterpret_cast<Drawable2D**>(item->start_);
  163. Drawable2D** end = reinterpret_cast<Drawable2D**>(item->end_);
  164. while (start != end)
  165. {
  166. Drawable2D* drawable = *start++;
  167. if (renderer->CheckVisibility(drawable) && drawable->GetDefaultMaterial() && drawable->GetVertices().Size())
  168. drawable->SetVisibility(true);
  169. else
  170. drawable->SetVisibility(false);
  171. }
  172. }
  173. static inline bool CompareDrawable2Ds(Drawable2D* lhs, Drawable2D* rhs)
  174. {
  175. if (lhs->GetLayer() != rhs->GetLayer())
  176. return lhs->GetLayer() < rhs->GetLayer();
  177. if (lhs->GetOrderInLayer() != rhs->GetOrderInLayer())
  178. return lhs->GetOrderInLayer() < rhs->GetOrderInLayer();
  179. Material* lhsUsedMaterial = lhs->GetDefaultMaterial();
  180. Material* rhsUsedMaterial = rhs->GetDefaultMaterial();
  181. if (lhsUsedMaterial != rhsUsedMaterial)
  182. return lhsUsedMaterial->GetNameHash() < rhsUsedMaterial->GetNameHash();
  183. return lhs->GetID() < rhs->GetID();
  184. }
  185. void Renderer2D::HandleBeginViewUpdate(StringHash eventType, VariantMap& eventData)
  186. {
  187. using namespace BeginViewUpdate;
  188. Scene* scene = GetScene();
  189. // Check that we are updating the correct scene
  190. if (scene != eventData[P_SCENE].GetPtr())
  191. return;
  192. PROFILE(UpdateRenderer2D);
  193. drawables_.Clear();
  194. GetDrawables(drawables_, scene);
  195. // Set default material for Drawable2D.
  196. for (unsigned i = 0; i < drawables_.Size(); ++i)
  197. {
  198. Drawable2D* drawable = drawables_[i];
  199. if (!drawable->GetDefaultMaterial())
  200. drawable->SetDefaultMaterial(CreateMaterial(drawable->GetTexture(), drawable->GetBlendMode()));
  201. }
  202. Sort(drawables_.Begin(), drawables_.End(), CompareDrawable2Ds);
  203. Camera* camera = static_cast<Camera*>(eventData[P_CAMERA].GetPtr());
  204. frustum_ = &camera->GetFrustum();
  205. if (camera->IsOrthographic() && camera->GetNode()->GetWorldDirection() == Vector3::FORWARD)
  206. {
  207. // Define bounding box with min and max points
  208. frustumBoundingBox_.Define(frustum_->vertices_[2], frustum_->vertices_[4]);
  209. frustum_ = 0;
  210. }
  211. {
  212. PROFILE(CheckDrawableVisibility);
  213. WorkQueue* queue = GetSubsystem<WorkQueue>();
  214. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  215. int drawablesPerItem = drawables_.Size() / numWorkItems;
  216. PODVector<Drawable2D*>::Iterator start = drawables_.Begin();
  217. for (int i = 0; i < numWorkItems; ++i)
  218. {
  219. SharedPtr<WorkItem> item = queue->GetFreeItem();
  220. item->priority_ = M_MAX_UNSIGNED;
  221. item->workFunction_ = CheckDrawableVisibility;
  222. item->aux_ = this;
  223. PODVector<Drawable2D*>::Iterator end = drawables_.End();
  224. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  225. end = start + drawablesPerItem;
  226. item->start_ = &(*start);
  227. item->end_ = &(*end);
  228. queue->AddWorkItem(item);
  229. start = end;
  230. }
  231. queue->Complete(M_MAX_UNSIGNED);
  232. }
  233. vertexCount_ = 0;
  234. for (unsigned i = 0; i < drawables_.Size(); ++i)
  235. {
  236. if (drawables_[i]->GetVisibility())
  237. vertexCount_ += drawables_[i]->GetVertices().Size();
  238. }
  239. indexCount_ = vertexCount_ / 4 * 6;
  240. // Go through the drawables to form geometries & batches, but upload the actual vertex data later
  241. materials_.Clear();
  242. Material* material = 0;
  243. unsigned iStart = 0;
  244. unsigned iCount = 0;
  245. unsigned vStart = 0;
  246. unsigned vCount = 0;
  247. for (unsigned d = 0; d < drawables_.Size(); ++d)
  248. {
  249. if (!drawables_[d]->GetVisibility())
  250. continue;
  251. Material* usedMaterial = drawables_[d]->GetDefaultMaterial();
  252. const Vector<Vertex2D>& vertices = drawables_[d]->GetVertices();
  253. if (material != usedMaterial)
  254. {
  255. if (material)
  256. {
  257. AddBatch(material, iStart, iCount, vStart, vCount);
  258. iStart += iCount;
  259. iCount = 0;
  260. vStart += vCount;
  261. vCount = 0;
  262. }
  263. material = usedMaterial;
  264. }
  265. iCount += vertices.Size() / 4 * 6;
  266. vCount += vertices.Size();
  267. }
  268. if (material)
  269. AddBatch(material, iStart, iCount, vStart, vCount);
  270. // Now the amount of batches is known. Build the part of source batches that are sensitive to threading issues
  271. // (material & geometry pointers)
  272. unsigned count = materials_.Size();
  273. batches_.Resize(count);
  274. for (unsigned i = 0; i < count; ++i)
  275. {
  276. batches_[i].material_ = materials_[i];
  277. batches_[i].geometry_ = geometries_[i];
  278. }
  279. }
  280. void Renderer2D::GetDrawables(PODVector<Drawable2D*>& dest, Node* node)
  281. {
  282. if (!node)
  283. return;
  284. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  285. for (Vector<SharedPtr<Component> >::ConstIterator i = components.Begin(); i != components.End(); ++i)
  286. {
  287. Drawable2D* drawable = dynamic_cast<Drawable2D*>(i->Get());
  288. if (drawable)
  289. dest.Push(drawable);
  290. }
  291. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  292. for (Vector<SharedPtr<Node> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  293. GetDrawables(dest, i->Get());
  294. }
  295. void Renderer2D::AddBatch(Material* material, unsigned indexStart, unsigned indexCount, unsigned vertexStart, unsigned vertexCount)
  296. {
  297. if (!material || indexCount == 0 || vertexCount == 0)
  298. return;
  299. materials_.Push(SharedPtr<Material>(material));
  300. unsigned batchSize = materials_.Size();
  301. if (geometries_.Size() < batchSize)
  302. {
  303. SharedPtr<Geometry> geometry(new Geometry(context_));
  304. geometry->SetIndexBuffer(indexBuffer_);
  305. geometry->SetVertexBuffer(0, vertexBuffer_, MASK_VERTEX2D);
  306. geometries_.Push(geometry);
  307. }
  308. geometries_[batchSize - 1]->SetDrawRange(TRIANGLE_LIST, indexStart, indexCount, vertexStart, vertexCount, false);
  309. }
  310. Material* Renderer2D::GetMaterial(Texture2D* texture, BlendMode blendMode)
  311. {
  312. HashMap<Texture2D*, HashMap<int, SharedPtr<Material> > >::Iterator t = cachedMaterials_.Find(texture);
  313. if (t == cachedMaterials_.End())
  314. {
  315. SharedPtr<Material> material(CreateMaterial(texture, blendMode));
  316. cachedMaterials_[texture][blendMode] = material;
  317. return material;
  318. }
  319. HashMap<int, SharedPtr<Material> >& materials = t->second_;
  320. HashMap<int, SharedPtr<Material> >::Iterator b = materials.Find(blendMode);
  321. if (b != materials.End())
  322. return b->second_;
  323. SharedPtr<Material> material(CreateMaterial(texture, blendMode));
  324. materials[blendMode] = material;
  325. return material;
  326. }
  327. Material* Renderer2D::CreateMaterial(Texture2D* texture, BlendMode blendMode)
  328. {
  329. Material* material = new Material(context_);
  330. if (texture)
  331. material->SetName(texture->GetName() + "_" + blendModeNames[blendMode]);
  332. else
  333. material->SetName(blendModeNames[blendMode]);
  334. Technique* tech = new Technique(context_);
  335. Pass* pass = tech->CreatePass(PASS_ALPHA);
  336. pass->SetBlendMode(blendMode);
  337. pass->SetVertexShader("Basic");
  338. pass->SetVertexShaderDefines("DIFFMAP VERTEXCOLOR");
  339. pass->SetPixelShader("Basic");
  340. pass->SetPixelShaderDefines("DIFFMAP VERTEXCOLOR");
  341. pass->SetDepthWrite(false);
  342. material->SetTechnique(0, tech);
  343. material->SetCullMode(CULL_NONE);
  344. material->SetTexture(TU_DIFFUSE, texture);
  345. return material;
  346. }
  347. }