Renderer2D.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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 "Technique.h"
  37. #include "Texture2D.h"
  38. #include "VertexBuffer.h"
  39. #include "WorkQueue.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_ || indexBuffer_->IsDataLost())
  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->GetMaterial() && 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->GetMaterial();
  180. Material* rhsUsedMaterial = rhs->GetMaterial();
  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. // Check and set default material
  196. for (unsigned i = 0; i < drawables_.Size(); ++i)
  197. {
  198. Drawable2D* drawable = drawables_[i];
  199. if (!drawable->GetMaterial())
  200. drawable->SetMaterial(GetMaterial(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. // Check visibility
  212. {
  213. PROFILE(CheckDrawableVisibility);
  214. WorkQueue* queue = GetSubsystem<WorkQueue>();
  215. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  216. int drawablesPerItem = drawables_.Size() / numWorkItems;
  217. PODVector<Drawable2D*>::Iterator start = drawables_.Begin();
  218. for (int i = 0; i < numWorkItems; ++i)
  219. {
  220. SharedPtr<WorkItem> item = queue->GetFreeItem();
  221. item->priority_ = M_MAX_UNSIGNED;
  222. item->workFunction_ = CheckDrawableVisibility;
  223. item->aux_ = this;
  224. PODVector<Drawable2D*>::Iterator end = drawables_.End();
  225. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  226. end = start + drawablesPerItem;
  227. item->start_ = &(*start);
  228. item->end_ = &(*end);
  229. queue->AddWorkItem(item);
  230. start = end;
  231. }
  232. queue->Complete(M_MAX_UNSIGNED);
  233. }
  234. vertexCount_ = 0;
  235. for (unsigned i = 0; i < drawables_.Size(); ++i)
  236. {
  237. if (drawables_[i]->GetVisibility())
  238. vertexCount_ += drawables_[i]->GetVertices().Size();
  239. }
  240. indexCount_ = vertexCount_ / 4 * 6;
  241. // Go through the drawables to form geometries & batches, but upload the actual vertex data later
  242. materials_.Clear();
  243. Material* material = 0;
  244. unsigned iStart = 0;
  245. unsigned iCount = 0;
  246. unsigned vStart = 0;
  247. unsigned vCount = 0;
  248. for (unsigned d = 0; d < drawables_.Size(); ++d)
  249. {
  250. if (!drawables_[d]->GetVisibility())
  251. continue;
  252. Material* usedMaterial = drawables_[d]->GetMaterial();
  253. const Vector<Vertex2D>& vertices = drawables_[d]->GetVertices();
  254. if (material != usedMaterial)
  255. {
  256. if (material)
  257. {
  258. AddBatch(material, iStart, iCount, vStart, vCount);
  259. iStart += iCount;
  260. iCount = 0;
  261. vStart += vCount;
  262. vCount = 0;
  263. }
  264. material = usedMaterial;
  265. }
  266. iCount += vertices.Size() / 4 * 6;
  267. vCount += vertices.Size();
  268. }
  269. if (material)
  270. AddBatch(material, iStart, iCount, vStart, vCount);
  271. // Now the amount of batches is known. Build the part of source batches that are sensitive to threading issues
  272. // (material & geometry pointers)
  273. unsigned count = materials_.Size();
  274. batches_.Resize(count);
  275. for (unsigned i = 0; i < count; ++i)
  276. {
  277. batches_[i].material_ = materials_[i];
  278. batches_[i].geometry_ = geometries_[i];
  279. }
  280. }
  281. void Renderer2D::GetDrawables(PODVector<Drawable2D*>& dest, Node* node)
  282. {
  283. if (!node || !node->IsEnabled())
  284. return;
  285. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  286. for (Vector<SharedPtr<Component> >::ConstIterator i = components.Begin(); i != components.End(); ++i)
  287. {
  288. Drawable2D* drawable = dynamic_cast<Drawable2D*>(i->Get());
  289. if (drawable && drawable->IsEnabled())
  290. dest.Push(drawable);
  291. }
  292. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  293. for (Vector<SharedPtr<Node> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  294. GetDrawables(dest, i->Get());
  295. }
  296. Material* Renderer2D::GetMaterial(Texture2D* texture, BlendMode blendMode)
  297. {
  298. HashMap<Texture2D*, HashMap<int, SharedPtr<Material> > >::Iterator t = cachedMaterials_.Find(texture);
  299. if (t == cachedMaterials_.End())
  300. {
  301. SharedPtr<Material> material(CreateMaterial(texture, blendMode));
  302. cachedMaterials_[texture][blendMode] = material;
  303. return material;
  304. }
  305. HashMap<int, SharedPtr<Material> >& materials = t->second_;
  306. HashMap<int, SharedPtr<Material> >::Iterator b = materials.Find(blendMode);
  307. if (b != materials.End())
  308. return b->second_;
  309. SharedPtr<Material> material(CreateMaterial(texture, blendMode));
  310. materials[blendMode] = material;
  311. return material;
  312. }
  313. Material* Renderer2D::CreateMaterial(Texture2D* texture, BlendMode blendMode)
  314. {
  315. Material* material = new Material(context_);
  316. if (texture)
  317. material->SetName(texture->GetName() + "_" + blendModeNames[blendMode]);
  318. else
  319. material->SetName(blendModeNames[blendMode]);
  320. Technique* tech = new Technique(context_);
  321. Pass* pass = tech->CreatePass(PASS_ALPHA);
  322. pass->SetBlendMode(blendMode);
  323. pass->SetVertexShader("Basic");
  324. pass->SetVertexShaderDefines("DIFFMAP VERTEXCOLOR");
  325. pass->SetPixelShader("Basic");
  326. pass->SetPixelShaderDefines("DIFFMAP VERTEXCOLOR");
  327. pass->SetDepthWrite(false);
  328. material->SetTechnique(0, tech);
  329. material->SetCullMode(CULL_NONE);
  330. material->SetTexture(TU_DIFFUSE, texture);
  331. return material;
  332. }
  333. void Renderer2D::AddBatch(Material* material, unsigned indexStart, unsigned indexCount, unsigned vertexStart, unsigned vertexCount)
  334. {
  335. if (!material || indexCount == 0 || vertexCount == 0)
  336. return;
  337. materials_.Push(SharedPtr<Material>(material));
  338. unsigned batchSize = materials_.Size();
  339. if (geometries_.Size() < batchSize)
  340. {
  341. SharedPtr<Geometry> geometry(new Geometry(context_));
  342. geometry->SetIndexBuffer(indexBuffer_);
  343. geometry->SetVertexBuffer(0, vertexBuffer_, MASK_VERTEX2D);
  344. geometries_.Push(geometry);
  345. }
  346. geometries_[batchSize - 1]->SetDrawRange(TRIANGLE_LIST, indexStart, indexCount, vertexStart, vertexCount, false);
  347. }
  348. }