View.cpp 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "DebugRenderer.h"
  26. #include "Geometry.h"
  27. #include "Graphics.h"
  28. #include "GraphicsImpl.h"
  29. #include "Log.h"
  30. #include "Material.h"
  31. #include "OcclusionBuffer.h"
  32. #include "Octree.h"
  33. #include "Renderer.h"
  34. #include "ResourceCache.h"
  35. #include "PostProcess.h"
  36. #include "Profiler.h"
  37. #include "Scene.h"
  38. #include "ShaderVariation.h"
  39. #include "Skybox.h"
  40. #include "Sort.h"
  41. #include "Technique.h"
  42. #include "Texture2D.h"
  43. #include "TextureCube.h"
  44. #include "VertexBuffer.h"
  45. #include "View.h"
  46. #include "WorkQueue.h"
  47. #include "Zone.h"
  48. #include "DebugNew.h"
  49. namespace Urho3D
  50. {
  51. static const Vector3 directions[] =
  52. {
  53. Vector3(1.0f, 0.0f, 0.0f),
  54. Vector3(-1.0f, 0.0f, 0.0f),
  55. Vector3(0.0f, 1.0f, 0.0f),
  56. Vector3(0.0f, -1.0f, 0.0f),
  57. Vector3(0.0f, 0.0f, 1.0f),
  58. Vector3(0.0f, 0.0f, -1.0f)
  59. };
  60. static const int CHECK_DRAWABLES_PER_WORK_ITEM = 64;
  61. static const float LIGHT_INTENSITY_THRESHOLD = 0.001f;
  62. /// %Frustum octree query for shadowcasters.
  63. class ShadowCasterOctreeQuery : public OctreeQuery
  64. {
  65. public:
  66. /// Construct with frustum and query parameters.
  67. ShadowCasterOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  68. unsigned viewMask = DEFAULT_VIEWMASK) :
  69. OctreeQuery(result, drawableFlags, viewMask),
  70. frustum_(frustum)
  71. {
  72. }
  73. /// Intersection test for an octant.
  74. virtual Intersection TestOctant(const BoundingBox& box, bool inside)
  75. {
  76. if (inside)
  77. return INSIDE;
  78. else
  79. return frustum_.IsInside(box);
  80. }
  81. /// Intersection test for drawables.
  82. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  83. {
  84. while (start != end)
  85. {
  86. Drawable* drawable = *start;
  87. if ((drawable->GetDrawableFlags() & drawableFlags_) && drawable->GetCastShadows() && drawable->IsVisible() &&
  88. (drawable->GetViewMask() & viewMask_))
  89. {
  90. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  91. result_.Push(drawable);
  92. }
  93. ++start;
  94. }
  95. }
  96. /// Frustum.
  97. Frustum frustum_;
  98. };
  99. /// %Frustum octree query for zones and occluders.
  100. class ZoneOccluderOctreeQuery : public OctreeQuery
  101. {
  102. public:
  103. /// Construct with frustum and query parameters.
  104. ZoneOccluderOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  105. unsigned viewMask = DEFAULT_VIEWMASK) :
  106. OctreeQuery(result, drawableFlags, viewMask),
  107. frustum_(frustum)
  108. {
  109. }
  110. /// Intersection test for an octant.
  111. virtual Intersection TestOctant(const BoundingBox& box, bool inside)
  112. {
  113. if (inside)
  114. return INSIDE;
  115. else
  116. return frustum_.IsInside(box);
  117. }
  118. /// Intersection test for drawables.
  119. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  120. {
  121. while (start != end)
  122. {
  123. Drawable* drawable = *start;
  124. unsigned char flags = drawable->GetDrawableFlags();
  125. if ((flags == DRAWABLE_ZONE || (flags == DRAWABLE_GEOMETRY && drawable->IsOccluder())) && drawable->IsVisible() &&
  126. (drawable->GetViewMask() & viewMask_))
  127. {
  128. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  129. result_.Push(drawable);
  130. }
  131. ++start;
  132. }
  133. }
  134. /// Frustum.
  135. Frustum frustum_;
  136. };
  137. /// %Frustum octree query with occlusion.
  138. class OccludedFrustumOctreeQuery : public OctreeQuery
  139. {
  140. public:
  141. /// Construct with frustum, occlusion buffer and query parameters.
  142. OccludedFrustumOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, OcclusionBuffer* buffer, unsigned char
  143. drawableFlags = DRAWABLE_ANY, unsigned viewMask = DEFAULT_VIEWMASK) :
  144. OctreeQuery(result, drawableFlags, viewMask),
  145. frustum_(frustum),
  146. buffer_(buffer)
  147. {
  148. }
  149. /// Intersection test for an octant.
  150. virtual Intersection TestOctant(const BoundingBox& box, bool inside)
  151. {
  152. if (inside)
  153. return buffer_->IsVisible(box) ? INSIDE : OUTSIDE;
  154. else
  155. {
  156. Intersection result = frustum_.IsInside(box);
  157. if (result != OUTSIDE && !buffer_->IsVisible(box))
  158. result = OUTSIDE;
  159. return result;
  160. }
  161. }
  162. /// Intersection test for drawables. Note: drawable occlusion is performed later in worker threads.
  163. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  164. {
  165. while (start != end)
  166. {
  167. Drawable* drawable = *start;
  168. if ((drawable->GetDrawableFlags() & drawableFlags_) && drawable->IsVisible() &&
  169. (drawable->GetViewMask() & viewMask_))
  170. {
  171. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  172. result_.Push(drawable);
  173. }
  174. ++start;
  175. }
  176. }
  177. /// Frustum.
  178. Frustum frustum_;
  179. /// Occlusion buffer.
  180. OcclusionBuffer* buffer_;
  181. };
  182. void CheckVisibilityWork(const WorkItem* item, unsigned threadIndex)
  183. {
  184. View* view = reinterpret_cast<View*>(item->aux_);
  185. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  186. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  187. OcclusionBuffer* buffer = view->occlusionBuffer_;
  188. const Matrix3x4& viewMatrix = view->camera_->GetInverseWorldTransform();
  189. while (start != end)
  190. {
  191. Drawable* drawable = *start++;
  192. drawable->UpdateBatches(view->frame_);
  193. // If draw distance non-zero, check it
  194. float maxDistance = drawable->GetDrawDistance();
  195. if ((maxDistance <= 0.0f || drawable->GetDistance() <= maxDistance) && (!buffer || !drawable->IsOccludee() ||
  196. buffer->IsVisible(drawable->GetWorldBoundingBox())))
  197. {
  198. drawable->MarkInView(view->frame_);
  199. // For geometries, clear lights and calculate view space Z range
  200. if (drawable->GetDrawableFlags() & DRAWABLE_GEOMETRY)
  201. {
  202. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  203. Vector3 center = geomBox.Center();
  204. float viewCenterZ = viewMatrix.m20_ * center.x_ + viewMatrix.m21_ * center.y_ + viewMatrix.m22_ * center.z_ +
  205. viewMatrix.m23_;
  206. Vector3 edge = geomBox.Size() * 0.5f;
  207. float viewEdgeZ = Abs(viewMatrix.m20_) * edge.x_ + Abs(viewMatrix.m21_) * edge.y_ + Abs(viewMatrix.m22_) *
  208. edge.z_;
  209. drawable->SetMinMaxZ(viewCenterZ - viewEdgeZ, viewCenterZ + viewEdgeZ);
  210. drawable->ClearLights();
  211. }
  212. }
  213. }
  214. }
  215. void ProcessLightWork(const WorkItem* item, unsigned threadIndex)
  216. {
  217. View* view = reinterpret_cast<View*>(item->aux_);
  218. LightQueryResult* query = reinterpret_cast<LightQueryResult*>(item->start_);
  219. view->ProcessLight(*query, threadIndex);
  220. }
  221. void UpdateDrawableGeometriesWork(const WorkItem* item, unsigned threadIndex)
  222. {
  223. const FrameInfo& frame = *(reinterpret_cast<FrameInfo*>(item->aux_));
  224. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  225. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  226. while (start != end)
  227. {
  228. Drawable* drawable = *start;
  229. drawable->UpdateGeometry(frame);
  230. ++start;
  231. }
  232. }
  233. void SortBatchQueueFrontToBackWork(const WorkItem* item, unsigned threadIndex)
  234. {
  235. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  236. queue->SortFrontToBack();
  237. }
  238. void SortBatchQueueBackToFrontWork(const WorkItem* item, unsigned threadIndex)
  239. {
  240. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  241. queue->SortBackToFront();
  242. }
  243. void SortLightQueueWork(const WorkItem* item, unsigned threadIndex)
  244. {
  245. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  246. start->litBatches_.SortFrontToBack();
  247. }
  248. void SortShadowQueueWork(const WorkItem* item, unsigned threadIndex)
  249. {
  250. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  251. for (unsigned i = 0; i < start->shadowSplits_.Size(); ++i)
  252. start->shadowSplits_[i].shadowBatches_.SortFrontToBack();
  253. }
  254. OBJECTTYPESTATIC(View);
  255. View::View(Context* context) :
  256. Object(context),
  257. graphics_(GetSubsystem<Graphics>()),
  258. renderer_(GetSubsystem<Renderer>()),
  259. octree_(0),
  260. camera_(0),
  261. cameraZone_(0),
  262. farClipZone_(0),
  263. renderTarget_(0)
  264. {
  265. frame_.camera_ = 0;
  266. // Create octree query vector for each thread
  267. tempDrawables_.Resize(GetSubsystem<WorkQueue>()->GetNumThreads() + 1);
  268. }
  269. View::~View()
  270. {
  271. }
  272. bool View::Define(RenderSurface* renderTarget, Viewport* viewport)
  273. {
  274. Scene* scene = viewport->GetScene();
  275. Camera* camera = viewport->GetCamera();
  276. if (!scene || !camera || !camera->GetNode())
  277. return false;
  278. // If scene is loading asynchronously, it is incomplete and should not be rendered
  279. if (scene->IsAsyncLoading())
  280. return false;
  281. Octree* octree = scene->GetComponent<Octree>();
  282. if (!octree)
  283. return false;
  284. renderMode_ = renderer_->GetRenderMode();
  285. octree_ = octree;
  286. camera_ = camera;
  287. cameraNode_ = camera->GetNode();
  288. renderTarget_ = renderTarget;
  289. // Get active post-processing effects on the viewport
  290. const Vector<SharedPtr<PostProcess> >& postProcesses = viewport->GetPostProcesses();
  291. postProcesses_.Clear();
  292. for (Vector<SharedPtr<PostProcess> >::ConstIterator i = postProcesses.Begin(); i != postProcesses.End(); ++i)
  293. {
  294. PostProcess* effect = i->Get();
  295. if (effect && effect->IsActive())
  296. postProcesses_.Push(*i);
  297. }
  298. // Validate the rect and calculate size. If zero rect, use whole rendertarget size
  299. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  300. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  301. const IntRect& rect = viewport->GetRect();
  302. if (rect != IntRect::ZERO)
  303. {
  304. viewRect_.left_ = Clamp(rect.left_, 0, rtWidth - 1);
  305. viewRect_.top_ = Clamp(rect.top_, 0, rtHeight - 1);
  306. viewRect_.right_ = Clamp(rect.right_, viewRect_.left_ + 1, rtWidth);
  307. viewRect_.bottom_ = Clamp(rect.bottom_, viewRect_.top_ + 1, rtHeight);
  308. }
  309. else
  310. viewRect_ = IntRect(0, 0, rtWidth, rtHeight);
  311. viewSize_ = viewRect_.Size();
  312. rtSize_ = IntVector2(rtWidth, rtHeight);
  313. // On OpenGL flip the viewport if rendering to a texture for consistent UV addressing with Direct3D9
  314. #ifdef USE_OPENGL
  315. if (renderTarget_)
  316. {
  317. viewRect_.bottom_ = rtSize_.y_ - viewRect_.top_;
  318. viewRect_.top_ = viewRect_.bottom_ - viewSize_.y_;
  319. }
  320. #endif
  321. drawShadows_ = renderer_->GetDrawShadows();
  322. materialQuality_ = renderer_->GetMaterialQuality();
  323. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  324. // Set possible quality overrides from the camera
  325. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  326. if (viewOverrideFlags & VO_LOW_MATERIAL_QUALITY)
  327. materialQuality_ = QUALITY_LOW;
  328. if (viewOverrideFlags & VO_DISABLE_SHADOWS)
  329. drawShadows_ = false;
  330. if (viewOverrideFlags & VO_DISABLE_OCCLUSION)
  331. maxOccluderTriangles_ = 0;
  332. return true;
  333. }
  334. void View::Update(const FrameInfo& frame)
  335. {
  336. if (!camera_ || !octree_)
  337. return;
  338. frame_.camera_ = camera_;
  339. frame_.timeStep_ = frame.timeStep_;
  340. frame_.frameNumber_ = frame.frameNumber_;
  341. frame_.viewSize_ = viewSize_;
  342. int maxSortedInstances = renderer_->GetMaxSortedInstances();
  343. // Clear screen buffers, geometry, light, occluder & batch lists
  344. screenBuffers_.Clear();
  345. geometries_.Clear();
  346. shadowGeometries_.Clear();
  347. lights_.Clear();
  348. zones_.Clear();
  349. occluders_.Clear();
  350. baseQueue_.Clear(maxSortedInstances);
  351. preAlphaQueue_.Clear(maxSortedInstances);
  352. gbufferQueue_.Clear(maxSortedInstances);
  353. alphaQueue_.Clear(maxSortedInstances);
  354. postAlphaQueue_.Clear(maxSortedInstances);
  355. vertexLightQueues_.Clear();
  356. // Do not update if camera projection is illegal
  357. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  358. if (!camera_->IsProjectionValid())
  359. return;
  360. // Set automatic aspect ratio if required
  361. if (camera_->GetAutoAspectRatio())
  362. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  363. GetDrawables();
  364. GetBatches();
  365. UpdateGeometries();
  366. }
  367. void View::Render()
  368. {
  369. if (!octree_ || !camera_)
  370. return;
  371. // Allocate screen buffers for post-processing and blitting as necessary
  372. AllocateScreenBuffers();
  373. // Forget parameter sources from the previous view
  374. graphics_->ClearParameterSources();
  375. // If stream offset is supported, write all instance transforms to a single large buffer
  376. // Else we must lock the instance buffer for each batch group
  377. if (renderer_->GetDynamicInstancing() && graphics_->GetStreamOffsetSupport())
  378. PrepareInstancingBuffer();
  379. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  380. // again to ensure correct projection will be used
  381. if (camera_->GetAutoAspectRatio())
  382. camera_->SetAspectRatio((float)(viewSize_.x_) / (float)(viewSize_.y_));
  383. graphics_->SetColorWrite(true);
  384. // Bind the face selection and indirection cube maps for point light shadows
  385. if (renderer_->GetDrawShadows())
  386. {
  387. graphics_->SetTexture(TU_FACESELECT, renderer_->GetFaceSelectCubeMap());
  388. graphics_->SetTexture(TU_INDIRECTION, renderer_->GetIndirectionCubeMap());
  389. }
  390. // Set "view texture" to prevent destination texture sampling in case we do not render to the destination directly
  391. // ie. when using deferred rendering and/or doing post-processing
  392. if (renderTarget_)
  393. graphics_->SetViewTexture(renderTarget_->GetParentTexture());
  394. // On OpenGL, flip the projection if rendering to a texture so that the texture can be addressed in the same way
  395. // as a render texture produced on Direct3D9
  396. #ifdef USE_OPENGL
  397. if (renderTarget_)
  398. camera_->SetFlipVertical(true);
  399. #endif
  400. // Render
  401. if (renderMode_ == RENDER_FORWARD)
  402. RenderBatchesForward();
  403. else
  404. RenderBatchesDeferred();
  405. #ifdef USE_OPENGL
  406. camera_->SetFlipVertical(false);
  407. #endif
  408. graphics_->SetDepthBias(0.0f, 0.0f);
  409. graphics_->SetScissorTest(false);
  410. graphics_->SetStencilTest(false);
  411. graphics_->SetViewTexture(0);
  412. graphics_->ResetStreamFrequencies();
  413. // Run post-processes or framebuffer blitting now
  414. if (screenBuffers_.Size())
  415. {
  416. if (postProcesses_.Size())
  417. RunPostProcesses();
  418. else
  419. BlitFramebuffer();
  420. }
  421. // If this is a main view, draw the associated debug geometry now
  422. if (!renderTarget_)
  423. {
  424. DebugRenderer* debug = octree_->GetComponent<DebugRenderer>();
  425. if (debug)
  426. {
  427. debug->SetView(camera_);
  428. debug->Render();
  429. }
  430. }
  431. // "Forget" the camera, octree and zone after rendering
  432. camera_ = 0;
  433. octree_ = 0;
  434. cameraZone_ = 0;
  435. farClipZone_ = 0;
  436. occlusionBuffer_ = 0;
  437. frame_.camera_ = 0;
  438. }
  439. void View::GetDrawables()
  440. {
  441. PROFILE(GetDrawables);
  442. WorkQueue* queue = GetSubsystem<WorkQueue>();
  443. PODVector<Drawable*>& tempDrawables = tempDrawables_[0];
  444. // Get zones and occluders first
  445. {
  446. ZoneOccluderOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_ZONE);
  447. octree_->GetDrawables(query);
  448. }
  449. highestZonePriority_ = M_MIN_INT;
  450. int bestPriority = M_MIN_INT;
  451. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  452. // Get default zone first in case we do not have zones defined
  453. Zone* defaultZone = renderer_->GetDefaultZone();
  454. cameraZone_ = farClipZone_ = defaultZone;
  455. for (PODVector<Drawable*>::ConstIterator i = tempDrawables.Begin(); i != tempDrawables.End(); ++i)
  456. {
  457. Drawable* drawable = *i;
  458. unsigned char flags = drawable->GetDrawableFlags();
  459. if (flags & DRAWABLE_ZONE)
  460. {
  461. Zone* zone = static_cast<Zone*>(drawable);
  462. zones_.Push(zone);
  463. int priority = zone->GetPriority();
  464. if (priority > highestZonePriority_)
  465. highestZonePriority_ = priority;
  466. if (zone->IsInside(cameraPos) && priority > bestPriority)
  467. {
  468. cameraZone_ = zone;
  469. bestPriority = priority;
  470. }
  471. }
  472. else
  473. occluders_.Push(drawable);
  474. }
  475. // Determine the zone at far clip distance. If not found, or camera zone has override mode, use camera zone
  476. cameraZoneOverride_ = cameraZone_->GetOverride();
  477. if (!cameraZoneOverride_)
  478. {
  479. Vector3 farClipPos = cameraPos + cameraNode_->GetWorldDirection() * Vector3(0.0f, 0.0f, camera_->GetFarClip());
  480. bestPriority = M_MIN_INT;
  481. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  482. {
  483. int priority = (*i)->GetPriority();
  484. if ((*i)->IsInside(farClipPos) && priority > bestPriority)
  485. {
  486. farClipZone_ = *i;
  487. bestPriority = priority;
  488. }
  489. }
  490. }
  491. if (farClipZone_ == defaultZone)
  492. farClipZone_ = cameraZone_;
  493. // If occlusion in use, get & render the occluders
  494. occlusionBuffer_ = 0;
  495. if (maxOccluderTriangles_ > 0)
  496. {
  497. UpdateOccluders(occluders_, camera_);
  498. if (occluders_.Size())
  499. {
  500. PROFILE(DrawOcclusion);
  501. occlusionBuffer_ = renderer_->GetOcclusionBuffer(camera_);
  502. DrawOccluders(occlusionBuffer_, occluders_);
  503. }
  504. }
  505. // Get lights and geometries. Coarse occlusion for octants is used at this point
  506. if (occlusionBuffer_)
  507. {
  508. OccludedFrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), occlusionBuffer_, DRAWABLE_GEOMETRY |
  509. DRAWABLE_LIGHT);
  510. octree_->GetDrawables(query);
  511. }
  512. else
  513. {
  514. FrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  515. octree_->GetDrawables(query);
  516. }
  517. // Check drawable occlusion and find zones for moved drawables in worker threads
  518. {
  519. WorkItem item;
  520. item.workFunction_ = CheckVisibilityWork;
  521. item.aux_ = this;
  522. PODVector<Drawable*>::Iterator start = tempDrawables.Begin();
  523. while (start != tempDrawables.End())
  524. {
  525. PODVector<Drawable*>::Iterator end = tempDrawables.End();
  526. if (end - start > CHECK_DRAWABLES_PER_WORK_ITEM)
  527. end = start + CHECK_DRAWABLES_PER_WORK_ITEM;
  528. item.start_ = &(*start);
  529. item.end_ = &(*end);
  530. queue->AddWorkItem(item);
  531. start = end;
  532. }
  533. queue->Complete();
  534. }
  535. // Sort into geometries & lights, and build visible scene bounding boxes in world and view space
  536. sceneBox_.min_ = sceneBox_.max_ = Vector3::ZERO;
  537. sceneBox_.defined_ = false;
  538. minZ_ = M_INFINITY;
  539. maxZ_ = 0.0f;
  540. const Matrix3x4& view = camera_->GetInverseWorldTransform();
  541. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  542. {
  543. Drawable* drawable = tempDrawables[i];
  544. if (!drawable->IsInView(frame_))
  545. continue;
  546. if (drawable->GetDrawableFlags() & DRAWABLE_GEOMETRY)
  547. {
  548. // Find zone for the drawable if necessary
  549. if (!drawable->GetZone() && !cameraZoneOverride_)
  550. FindZone(drawable);
  551. // Expand the scene bounding box and Z range (skybox not included because of infinite size) and store the drawawble
  552. if (drawable->GetType() != Skybox::GetTypeStatic())
  553. {
  554. sceneBox_.Merge(drawable->GetWorldBoundingBox());
  555. minZ_ = Min(minZ_, drawable->GetMinZ());
  556. maxZ_ = Max(maxZ_, drawable->GetMaxZ());
  557. }
  558. geometries_.Push(drawable);
  559. }
  560. else
  561. {
  562. Light* light = static_cast<Light*>(drawable);
  563. // Skip lights which are so dim that they can not contribute to a rendertarget
  564. if (light->GetColor().Intensity() > LIGHT_INTENSITY_THRESHOLD)
  565. lights_.Push(light);
  566. }
  567. }
  568. if (minZ_ == M_INFINITY)
  569. minZ_ = 0.0f;
  570. // Sort the lights to brightest/closest first
  571. for (unsigned i = 0; i < lights_.Size(); ++i)
  572. {
  573. Light* light = lights_[i];
  574. light->SetIntensitySortValue(camera_->GetDistance(light->GetNode()->GetWorldPosition()));
  575. light->SetLightQueue(0);
  576. }
  577. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  578. }
  579. void View::GetBatches()
  580. {
  581. WorkQueue* queue = GetSubsystem<WorkQueue>();
  582. PODVector<Light*> vertexLights;
  583. // Process lit geometries and shadow casters for each light
  584. {
  585. PROFILE(ProcessLights);
  586. lightQueryResults_.Resize(lights_.Size());
  587. WorkItem item;
  588. item.workFunction_ = ProcessLightWork;
  589. item.aux_ = this;
  590. for (unsigned i = 0; i < lightQueryResults_.Size(); ++i)
  591. {
  592. LightQueryResult& query = lightQueryResults_[i];
  593. query.light_ = lights_[i];
  594. item.start_ = &query;
  595. queue->AddWorkItem(item);
  596. }
  597. // Ensure all lights have been processed before proceeding
  598. queue->Complete();
  599. }
  600. // Build light queues and lit batches
  601. {
  602. PROFILE(GetLightBatches);
  603. // Preallocate light queues: per-pixel lights which have lit geometries
  604. unsigned numLightQueues = 0;
  605. unsigned usedLightQueues = 0;
  606. for (Vector<LightQueryResult>::ConstIterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  607. {
  608. if (!i->light_->GetPerVertex() && i->litGeometries_.Size())
  609. ++numLightQueues;
  610. }
  611. lightQueues_.Resize(numLightQueues);
  612. maxLightsDrawables_.Clear();
  613. unsigned maxSortedInstances = renderer_->GetMaxSortedInstances();
  614. for (Vector<LightQueryResult>::Iterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  615. {
  616. LightQueryResult& query = *i;
  617. // If light has no affected geometries, no need to process further
  618. if (query.litGeometries_.Empty())
  619. continue;
  620. Light* light = query.light_;
  621. // Per-pixel light
  622. if (!light->GetPerVertex())
  623. {
  624. unsigned shadowSplits = query.numSplits_;
  625. // Initialize light queue and store it to the light so that it can be found later
  626. LightBatchQueue& lightQueue = lightQueues_[usedLightQueues++];
  627. light->SetLightQueue(&lightQueue);
  628. lightQueue.light_ = light;
  629. lightQueue.shadowMap_ = 0;
  630. lightQueue.litBatches_.Clear(maxSortedInstances);
  631. lightQueue.volumeBatches_.Clear();
  632. // Allocate shadow map now
  633. if (shadowSplits > 0)
  634. {
  635. lightQueue.shadowMap_ = renderer_->GetShadowMap(light, camera_, viewSize_.x_, viewSize_.y_);
  636. // If did not manage to get a shadow map, convert the light to unshadowed
  637. if (!lightQueue.shadowMap_)
  638. shadowSplits = 0;
  639. }
  640. // Setup shadow batch queues
  641. lightQueue.shadowSplits_.Resize(shadowSplits);
  642. for (unsigned j = 0; j < shadowSplits; ++j)
  643. {
  644. ShadowBatchQueue& shadowQueue = lightQueue.shadowSplits_[j];
  645. Camera* shadowCamera = query.shadowCameras_[j];
  646. shadowQueue.shadowCamera_ = shadowCamera;
  647. shadowQueue.nearSplit_ = query.shadowNearSplits_[j];
  648. shadowQueue.farSplit_ = query.shadowFarSplits_[j];
  649. shadowQueue.shadowBatches_.Clear(maxSortedInstances);
  650. // Setup the shadow split viewport and finalize shadow camera parameters
  651. shadowQueue.shadowViewport_ = GetShadowMapViewport(light, j, lightQueue.shadowMap_);
  652. FinalizeShadowCamera(shadowCamera, light, shadowQueue.shadowViewport_, query.shadowCasterBox_[j]);
  653. // Loop through shadow casters
  654. for (PODVector<Drawable*>::ConstIterator k = query.shadowCasters_.Begin() + query.shadowCasterBegin_[j];
  655. k < query.shadowCasters_.Begin() + query.shadowCasterEnd_[j]; ++k)
  656. {
  657. Drawable* drawable = *k;
  658. if (!drawable->IsInView(frame_, false))
  659. {
  660. drawable->MarkInView(frame_, false);
  661. shadowGeometries_.Push(drawable);
  662. }
  663. Zone* zone = GetZone(drawable);
  664. const Vector<SourceBatch>& batches = drawable->GetBatches();
  665. for (unsigned l = 0; l < batches.Size(); ++l)
  666. {
  667. const SourceBatch& srcBatch = batches[l];
  668. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  669. if (!srcBatch.geometry_ || !tech)
  670. continue;
  671. Pass* pass = tech->GetPass(PASS_SHADOW);
  672. // Skip if material has no shadow pass
  673. if (!pass)
  674. continue;
  675. Batch destBatch(srcBatch);
  676. destBatch.pass_ = pass;
  677. destBatch.camera_ = shadowCamera;
  678. destBatch.zone_ = zone;
  679. destBatch.lightQueue_ = &lightQueue;
  680. AddBatchToQueue(shadowQueue.shadowBatches_, destBatch, tech);
  681. }
  682. }
  683. }
  684. // Process lit geometries
  685. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  686. {
  687. Drawable* drawable = *j;
  688. drawable->AddLight(light);
  689. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  690. if (!drawable->GetMaxLights())
  691. GetLitBatches(drawable, lightQueue);
  692. else
  693. maxLightsDrawables_.Insert(drawable);
  694. }
  695. // In deferred modes, store the light volume batch now
  696. if (renderMode_ != RENDER_FORWARD)
  697. {
  698. Batch volumeBatch;
  699. volumeBatch.geometry_ = renderer_->GetLightGeometry(light);
  700. volumeBatch.worldTransform_ = &light->GetVolumeTransform(camera_);
  701. volumeBatch.overrideView_ = light->GetLightType() == LIGHT_DIRECTIONAL;
  702. volumeBatch.camera_ = camera_;
  703. volumeBatch.lightQueue_ = &lightQueue;
  704. volumeBatch.distance_ = light->GetDistance();
  705. volumeBatch.material_ = 0;
  706. volumeBatch.pass_ = 0;
  707. volumeBatch.zone_ = 0;
  708. renderer_->SetLightVolumeBatchShaders(volumeBatch);
  709. lightQueue.volumeBatches_.Push(volumeBatch);
  710. }
  711. }
  712. // Per-vertex light
  713. else
  714. {
  715. // Add the vertex light to lit drawables. It will be processed later during base pass batch generation
  716. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  717. {
  718. Drawable* drawable = *j;
  719. drawable->AddVertexLight(light);
  720. }
  721. }
  722. }
  723. }
  724. // Process drawables with limited per-pixel light count
  725. if (maxLightsDrawables_.Size())
  726. {
  727. PROFILE(GetMaxLightsBatches);
  728. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  729. {
  730. Drawable* drawable = *i;
  731. drawable->LimitLights();
  732. const PODVector<Light*>& lights = drawable->GetLights();
  733. for (unsigned i = 0; i < lights.Size(); ++i)
  734. {
  735. Light* light = lights[i];
  736. // Find the correct light queue again
  737. LightBatchQueue* queue = light->GetLightQueue();
  738. if (queue)
  739. GetLitBatches(drawable, *queue);
  740. }
  741. }
  742. }
  743. // Build base pass batches
  744. {
  745. PROFILE(GetBaseBatches);
  746. hasZeroLightMask_ = false;
  747. for (PODVector<Drawable*>::ConstIterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  748. {
  749. Drawable* drawable = *i;
  750. Zone* zone = GetZone(drawable);
  751. const Vector<SourceBatch>& batches = drawable->GetBatches();
  752. const PODVector<Light*>& drawableVertexLights = drawable->GetVertexLights();
  753. if (!drawableVertexLights.Empty())
  754. drawable->LimitVertexLights();
  755. for (unsigned j = 0; j < batches.Size(); ++j)
  756. {
  757. const SourceBatch& srcBatch = batches[j];
  758. // Check here if the material refers to a rendertarget texture with camera(s) attached
  759. // Only check this for the main view (null rendertarget)
  760. if (srcBatch.material_ && srcBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_ && !renderTarget_)
  761. CheckMaterialForAuxView(srcBatch.material_);
  762. // If already has a lit base pass, skip (forward rendering only)
  763. if (j < 32 && drawable->HasBasePass(j))
  764. continue;
  765. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  766. if (!srcBatch.geometry_ || !tech)
  767. continue;
  768. Batch destBatch(srcBatch);
  769. destBatch.camera_ = camera_;
  770. destBatch.zone_ = zone;
  771. destBatch.isBase_ = true;
  772. destBatch.pass_ = 0;
  773. destBatch.lightMask_ = GetLightMask(drawable);
  774. // In deferred modes check for G-buffer and material passes first
  775. if (renderMode_ == RENDER_PREPASS)
  776. {
  777. destBatch.pass_ = tech->GetPass(PASS_PREPASS);
  778. if (destBatch.pass_)
  779. {
  780. // If the opaque object has a zero lightmask, have to skip light buffer optimization
  781. if (!hasZeroLightMask_ && (!(GetLightMask(drawable) & 0xff)))
  782. hasZeroLightMask_ = true;
  783. // Allow G-buffer pass instancing only if lightmask matches zone lightmask
  784. AddBatchToQueue(gbufferQueue_, destBatch, tech, destBatch.lightMask_ == (zone->GetLightMask() & 0xff));
  785. destBatch.pass_ = tech->GetPass(PASS_MATERIAL);
  786. }
  787. }
  788. if (renderMode_ == RENDER_DEFERRED)
  789. destBatch.pass_ = tech->GetPass(PASS_DEFERRED);
  790. // Next check for forward unlit base pass
  791. if (!destBatch.pass_)
  792. destBatch.pass_ = tech->GetPass(PASS_BASE);
  793. if (destBatch.pass_)
  794. {
  795. // Check for vertex lights (both forward unlit, light pre-pass material pass, and deferred G-buffer)
  796. if (!drawableVertexLights.Empty())
  797. {
  798. // For a deferred opaque batch, check if the vertex lights include converted per-pixel lights, and remove
  799. // them to prevent double-lighting
  800. if (renderMode_ != RENDER_FORWARD && destBatch.pass_->GetBlendMode() == BLEND_REPLACE)
  801. {
  802. vertexLights.Clear();
  803. for (unsigned i = 0; i < drawableVertexLights.Size(); ++i)
  804. {
  805. if (drawableVertexLights[i]->GetPerVertex())
  806. vertexLights.Push(drawableVertexLights[i]);
  807. }
  808. }
  809. else
  810. vertexLights = drawableVertexLights;
  811. if (!vertexLights.Empty())
  812. {
  813. // Find a vertex light queue. If not found, create new
  814. unsigned long long hash = GetVertexLightQueueHash(vertexLights);
  815. HashMap<unsigned long long, LightBatchQueue>::Iterator i = vertexLightQueues_.Find(hash);
  816. if (i == vertexLightQueues_.End())
  817. {
  818. i = vertexLightQueues_.Insert(MakePair(hash, LightBatchQueue()));
  819. i->second_.light_ = 0;
  820. i->second_.shadowMap_ = 0;
  821. i->second_.vertexLights_ = vertexLights;
  822. }
  823. destBatch.lightQueue_ = &(i->second_);
  824. }
  825. }
  826. // Check whether batch is opaque or transparent
  827. if (destBatch.pass_->GetBlendMode() == BLEND_REPLACE)
  828. {
  829. if (destBatch.pass_->GetType() != PASS_DEFERRED)
  830. AddBatchToQueue(baseQueue_, destBatch, tech);
  831. else
  832. {
  833. // Allow G-buffer pass instancing only if lightmask matches zone lightmask
  834. AddBatchToQueue(gbufferQueue_, destBatch, tech, destBatch.lightMask_ == (destBatch.zone_->GetLightMask() & 0xff));
  835. }
  836. }
  837. else
  838. {
  839. // Transparent batches can not be instanced
  840. AddBatchToQueue(alphaQueue_, destBatch, tech, false);
  841. }
  842. continue;
  843. }
  844. // If no pass found so far, finally check for pre-alpha / post-alpha custom passes
  845. destBatch.pass_ = tech->GetPass(PASS_PREALPHA);
  846. if (destBatch.pass_)
  847. {
  848. AddBatchToQueue(preAlphaQueue_, destBatch, tech);
  849. continue;
  850. }
  851. destBatch.pass_ = tech->GetPass(PASS_POSTALPHA);
  852. if (destBatch.pass_)
  853. {
  854. // Post-alpha pass is treated similarly as alpha, and is not instanced
  855. AddBatchToQueue(postAlphaQueue_, destBatch, tech, false);
  856. continue;
  857. }
  858. }
  859. }
  860. }
  861. }
  862. void View::UpdateGeometries()
  863. {
  864. PROFILE(SortAndUpdateGeometry);
  865. WorkQueue* queue = GetSubsystem<WorkQueue>();
  866. // Sort batches
  867. {
  868. WorkItem item;
  869. item.workFunction_ = SortBatchQueueFrontToBackWork;
  870. item.start_ = &baseQueue_;
  871. queue->AddWorkItem(item);
  872. item.start_ = &preAlphaQueue_;
  873. queue->AddWorkItem(item);
  874. if (renderMode_ != RENDER_FORWARD)
  875. {
  876. item.start_ = &gbufferQueue_;
  877. queue->AddWorkItem(item);
  878. }
  879. item.workFunction_ = SortBatchQueueBackToFrontWork;
  880. item.start_ = &alphaQueue_;
  881. queue->AddWorkItem(item);
  882. item.start_ = &postAlphaQueue_;
  883. queue->AddWorkItem(item);
  884. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  885. {
  886. item.workFunction_ = SortLightQueueWork;
  887. item.start_ = &(*i);
  888. queue->AddWorkItem(item);
  889. if (i->shadowSplits_.Size())
  890. {
  891. item.workFunction_ = SortShadowQueueWork;
  892. queue->AddWorkItem(item);
  893. }
  894. }
  895. }
  896. // Update geometries. Split into threaded and non-threaded updates.
  897. {
  898. nonThreadedGeometries_.Clear();
  899. threadedGeometries_.Clear();
  900. for (PODVector<Drawable*>::Iterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  901. {
  902. UpdateGeometryType type = (*i)->GetUpdateGeometryType();
  903. if (type == UPDATE_MAIN_THREAD)
  904. nonThreadedGeometries_.Push(*i);
  905. else if (type == UPDATE_WORKER_THREAD)
  906. threadedGeometries_.Push(*i);
  907. }
  908. for (PODVector<Drawable*>::Iterator i = shadowGeometries_.Begin(); i != shadowGeometries_.End(); ++i)
  909. {
  910. UpdateGeometryType type = (*i)->GetUpdateGeometryType();
  911. if (type == UPDATE_MAIN_THREAD)
  912. nonThreadedGeometries_.Push(*i);
  913. else if (type == UPDATE_WORKER_THREAD)
  914. threadedGeometries_.Push(*i);
  915. }
  916. if (threadedGeometries_.Size())
  917. {
  918. WorkItem item;
  919. item.workFunction_ = UpdateDrawableGeometriesWork;
  920. item.aux_ = const_cast<FrameInfo*>(&frame_);
  921. PODVector<Drawable*>::Iterator start = threadedGeometries_.Begin();
  922. while (start != threadedGeometries_.End())
  923. {
  924. PODVector<Drawable*>::Iterator end = threadedGeometries_.End();
  925. if (end - start > DRAWABLES_PER_WORK_ITEM)
  926. end = start + DRAWABLES_PER_WORK_ITEM;
  927. item.start_ = &(*start);
  928. item.end_ = &(*end);
  929. queue->AddWorkItem(item);
  930. start = end;
  931. }
  932. }
  933. // While the work queue is processed, update non-threaded geometries
  934. for (PODVector<Drawable*>::ConstIterator i = nonThreadedGeometries_.Begin(); i != nonThreadedGeometries_.End(); ++i)
  935. (*i)->UpdateGeometry(frame_);
  936. }
  937. // Finally ensure all threaded work has completed
  938. queue->Complete();
  939. }
  940. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue)
  941. {
  942. Light* light = lightQueue.light_;
  943. Zone* zone = GetZone(drawable);
  944. const Vector<SourceBatch>& batches = drawable->GetBatches();
  945. bool hasAmbientGradient = zone->GetAmbientGradient() && zone->GetAmbientStartColor() != zone->GetAmbientEndColor();
  946. // Shadows on transparencies can only be rendered if shadow maps are not reused
  947. bool allowTransparentShadows = !renderer_->GetReuseShadowMaps();
  948. bool allowLitBase = light == drawable->GetFirstLight() && drawable->GetVertexLights().Empty() && !hasAmbientGradient;
  949. for (unsigned i = 0; i < batches.Size(); ++i)
  950. {
  951. const SourceBatch& srcBatch = batches[i];
  952. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  953. if (!srcBatch.geometry_ || !tech)
  954. continue;
  955. // Do not create pixel lit forward passes for materials that render into the G-buffer
  956. if ((renderMode_ == RENDER_PREPASS && tech->HasPass(PASS_PREPASS)) || (renderMode_ == RENDER_DEFERRED &&
  957. tech->HasPass(PASS_DEFERRED)))
  958. continue;
  959. Batch destBatch(srcBatch);
  960. // Check for lit base pass. Because it uses the replace blend mode, it must be ensured to be the first light
  961. // Also vertex lighting or ambient gradient require the non-lit base pass, so skip in those cases
  962. if (i < 32 && allowLitBase)
  963. {
  964. destBatch.pass_ = tech->GetPass(PASS_LITBASE);
  965. if (destBatch.pass_)
  966. {
  967. destBatch.isBase_ = true;
  968. drawable->SetBasePass(i);
  969. }
  970. else
  971. destBatch.pass_ = tech->GetPass(PASS_LIGHT);
  972. }
  973. else
  974. destBatch.pass_ = tech->GetPass(PASS_LIGHT);
  975. // Skip if material does not receive light at all
  976. if (!destBatch.pass_)
  977. continue;
  978. destBatch.camera_ = camera_;
  979. destBatch.lightQueue_ = &lightQueue;
  980. destBatch.zone_ = zone;
  981. // Check from the ambient pass whether the object is opaque or transparent
  982. Pass* ambientPass = tech->GetPass(PASS_BASE);
  983. if (!ambientPass || ambientPass->GetBlendMode() == BLEND_REPLACE)
  984. AddBatchToQueue(lightQueue.litBatches_, destBatch, tech);
  985. else
  986. {
  987. // Transparent batches can not be instanced
  988. AddBatchToQueue(alphaQueue_, destBatch, tech, false, allowTransparentShadows);
  989. }
  990. }
  991. }
  992. void View::RenderBatchesForward()
  993. {
  994. // If using hardware multisampling with post-processing, render to the backbuffer first and then resolve
  995. bool resolve = screenBuffers_.Size() && !renderTarget_ && graphics_->GetMultiSample() > 1;
  996. RenderSurface* renderTarget = (screenBuffers_.Size() && !resolve) ? screenBuffers_[0]->GetRenderSurface() : renderTarget_;
  997. RenderSurface* depthStencil = GetDepthStencil(renderTarget);
  998. // If not reusing shadowmaps, render all of them first
  999. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  1000. {
  1001. PROFILE(RenderShadowMaps);
  1002. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1003. {
  1004. if (i->shadowMap_)
  1005. RenderShadowMap(*i);
  1006. }
  1007. }
  1008. graphics_->SetRenderTarget(0, renderTarget);
  1009. graphics_->SetDepthStencil(depthStencil);
  1010. graphics_->SetViewport(viewRect_);
  1011. #ifndef GL_ES_VERSION_2_0
  1012. graphics_->Clear(CLEAR_DEPTH | CLEAR_STENCIL);
  1013. #else
  1014. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH, farClipZone_->GetFogColor());
  1015. #endif
  1016. graphics_->SetFillMode(camera_->GetFillMode());
  1017. // Render opaque object unlit base pass
  1018. if (!baseQueue_.IsEmpty())
  1019. {
  1020. PROFILE(RenderBase);
  1021. baseQueue_.Draw(graphics_, renderer_);
  1022. }
  1023. // Render shadow maps + opaque objects' additive lighting
  1024. if (!lightQueues_.Empty())
  1025. {
  1026. PROFILE(RenderLights);
  1027. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1028. {
  1029. // If reusing shadowmaps, render each of them before the lit batches
  1030. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1031. {
  1032. RenderShadowMap(*i);
  1033. graphics_->SetRenderTarget(0, renderTarget);
  1034. graphics_->SetDepthStencil(depthStencil);
  1035. graphics_->SetViewport(viewRect_);
  1036. graphics_->SetFillMode(camera_->GetFillMode());
  1037. }
  1038. i->litBatches_.Draw(i->light_, graphics_, renderer_);
  1039. }
  1040. }
  1041. graphics_->SetScissorTest(false);
  1042. graphics_->SetStencilTest(false);
  1043. #ifndef GL_ES_VERSION_2_0
  1044. // At this point clear the parts of viewport not occupied by opaque geometry with fog color.
  1045. // On OpenGL ES an ordinary color clear has been performed beforehand instead
  1046. graphics_->SetBlendMode(BLEND_REPLACE);
  1047. graphics_->SetColorWrite(true);
  1048. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1049. graphics_->SetDepthWrite(false);
  1050. graphics_->SetFillMode(FILL_SOLID);
  1051. graphics_->SetScissorTest(false);
  1052. graphics_->SetStencilTest(false);
  1053. graphics_->SetShaders(renderer_->GetVertexShader("Basic"), renderer_->GetPixelShader("Basic"));
  1054. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, farClipZone_->GetFogColor());
  1055. graphics_->ClearParameterSource(SP_MATERIAL);
  1056. DrawFullscreenQuad(camera_, false);
  1057. #endif
  1058. graphics_->SetFillMode(camera_->GetFillMode());
  1059. // Render pre-alpha custom pass
  1060. if (!preAlphaQueue_.IsEmpty())
  1061. {
  1062. PROFILE(RenderPreAlpha);
  1063. preAlphaQueue_.Draw(graphics_, renderer_);
  1064. }
  1065. // Render transparent objects (both base passes & additive lighting)
  1066. if (!alphaQueue_.IsEmpty())
  1067. {
  1068. PROFILE(RenderAlpha);
  1069. alphaQueue_.Draw(graphics_, renderer_, true);
  1070. }
  1071. // Render post-alpha custom pass
  1072. if (!postAlphaQueue_.IsEmpty())
  1073. {
  1074. PROFILE(RenderPostAlpha);
  1075. postAlphaQueue_.Draw(graphics_, renderer_);
  1076. }
  1077. graphics_->SetFillMode(FILL_SOLID);
  1078. // Resolve multisampled backbuffer now if necessary
  1079. if (resolve)
  1080. graphics_->ResolveToTexture(screenBuffers_[0], viewRect_);
  1081. }
  1082. void View::RenderBatchesDeferred()
  1083. {
  1084. // If not reusing shadowmaps, render all of them first
  1085. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  1086. {
  1087. PROFILE(RenderShadowMaps);
  1088. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1089. {
  1090. if (i->shadowMap_)
  1091. RenderShadowMap(*i);
  1092. }
  1093. }
  1094. bool hwDepth = graphics_->GetHardwareDepthSupport();
  1095. // In light prepass mode the albedo buffer is used for light accumulation instead
  1096. Texture2D* albedoBuffer = renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, Graphics::GetRGBAFormat());
  1097. Texture2D* normalBuffer = renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, Graphics::GetRGBAFormat());
  1098. Texture2D* depthBuffer = renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, hwDepth ? Graphics::GetDepthStencilFormat() :
  1099. Graphics::GetLinearDepthFormat());
  1100. RenderSurface* renderTarget = screenBuffers_.Size() ? screenBuffers_[0]->GetRenderSurface() : renderTarget_;
  1101. RenderSurface* depthStencil = hwDepth ? depthBuffer->GetRenderSurface() : renderer_->GetDepthStencil(rtSize_.x_, rtSize_.y_);
  1102. if (renderMode_ == RENDER_PREPASS)
  1103. {
  1104. graphics_->SetRenderTarget(0, normalBuffer);
  1105. if (!hwDepth)
  1106. graphics_->SetRenderTarget(1, depthBuffer);
  1107. }
  1108. else
  1109. {
  1110. graphics_->SetRenderTarget(0, renderTarget);
  1111. graphics_->SetRenderTarget(1, albedoBuffer);
  1112. graphics_->SetRenderTarget(2, normalBuffer);
  1113. if (!hwDepth)
  1114. graphics_->SetRenderTarget(3, depthBuffer);
  1115. }
  1116. graphics_->SetDepthStencil(depthStencil);
  1117. graphics_->SetViewport(viewRect_);
  1118. graphics_->Clear(CLEAR_DEPTH | CLEAR_STENCIL);
  1119. graphics_->SetFillMode(camera_->GetFillMode());
  1120. // Render G-buffer batches
  1121. if (!gbufferQueue_.IsEmpty())
  1122. {
  1123. PROFILE(RenderGBuffer);
  1124. gbufferQueue_.Draw(graphics_, renderer_, false, true);
  1125. }
  1126. graphics_->SetFillMode(FILL_SOLID);
  1127. // Clear the light accumulation buffer (light pre-pass only.) However, skip the clear if the first light is a directional
  1128. // light with full mask
  1129. RenderSurface* lightRenderTarget = renderMode_ == RENDER_PREPASS ? albedoBuffer->GetRenderSurface() : renderTarget;
  1130. if (renderMode_ == RENDER_PREPASS)
  1131. {
  1132. bool optimizeLightBuffer = !hasZeroLightMask_ && !lightQueues_.Empty() && lightQueues_.Front().light_->GetLightType() ==
  1133. LIGHT_DIRECTIONAL && (lightQueues_.Front().light_->GetLightMask() & 0xff) == 0xff;
  1134. graphics_->SetRenderTarget(0, lightRenderTarget);
  1135. graphics_->ResetRenderTarget(1);
  1136. graphics_->SetDepthStencil(depthStencil);
  1137. graphics_->SetViewport(viewRect_);
  1138. if (!optimizeLightBuffer)
  1139. graphics_->Clear(CLEAR_COLOR);
  1140. }
  1141. else
  1142. {
  1143. graphics_->ResetRenderTarget(1);
  1144. graphics_->ResetRenderTarget(2);
  1145. graphics_->ResetRenderTarget(3);
  1146. }
  1147. // Render shadow maps + light volumes
  1148. if (!lightQueues_.Empty())
  1149. {
  1150. PROFILE(RenderLights);
  1151. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1152. {
  1153. // If reusing shadowmaps, render each of them before the lit batches
  1154. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1155. {
  1156. RenderShadowMap(*i);
  1157. graphics_->SetRenderTarget(0, lightRenderTarget);
  1158. graphics_->SetDepthStencil(depthStencil);
  1159. graphics_->SetViewport(viewRect_);
  1160. }
  1161. if (renderMode_ == RENDER_DEFERRED)
  1162. graphics_->SetTexture(TU_ALBEDOBUFFER, albedoBuffer);
  1163. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  1164. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  1165. for (unsigned j = 0; j < i->volumeBatches_.Size(); ++j)
  1166. {
  1167. SetupLightVolumeBatch(i->volumeBatches_[j]);
  1168. i->volumeBatches_[j].Draw(graphics_, renderer_);
  1169. }
  1170. }
  1171. }
  1172. graphics_->SetTexture(TU_ALBEDOBUFFER, 0);
  1173. graphics_->SetTexture(TU_NORMALBUFFER, 0);
  1174. graphics_->SetTexture(TU_DEPTHBUFFER, 0);
  1175. if (renderMode_ == RENDER_PREPASS)
  1176. {
  1177. graphics_->SetRenderTarget(0, renderTarget);
  1178. graphics_->SetDepthStencil(depthStencil);
  1179. graphics_->SetViewport(viewRect_);
  1180. }
  1181. // At this point clear the parts of viewport not occupied by opaque geometry with fog color
  1182. graphics_->SetBlendMode(BLEND_REPLACE);
  1183. graphics_->SetColorWrite(true);
  1184. graphics_->SetDepthTest(CMP_ALWAYS);
  1185. graphics_->SetDepthWrite(false);
  1186. graphics_->SetScissorTest(false);
  1187. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 0);
  1188. graphics_->SetShaders(renderer_->GetVertexShader("Basic"), renderer_->GetPixelShader("Basic"));
  1189. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, farClipZone_->GetFogColor());
  1190. graphics_->ClearParameterSource(SP_MATERIAL);
  1191. DrawFullscreenQuad(camera_, false);
  1192. graphics_->SetFillMode(camera_->GetFillMode());
  1193. // Render opaque objects with deferred lighting result (light pre-pass only)
  1194. if (!baseQueue_.IsEmpty())
  1195. {
  1196. PROFILE(RenderBase);
  1197. graphics_->SetTexture(TU_LIGHTBUFFER, renderMode_ == RENDER_PREPASS ? albedoBuffer : 0);
  1198. baseQueue_.Draw(graphics_, renderer_);
  1199. graphics_->SetTexture(TU_LIGHTBUFFER, 0);
  1200. }
  1201. // Render pre-alpha custom pass
  1202. if (!preAlphaQueue_.IsEmpty())
  1203. {
  1204. PROFILE(RenderPreAlpha);
  1205. preAlphaQueue_.Draw(graphics_, renderer_);
  1206. }
  1207. // Render transparent objects (both base passes & additive lighting)
  1208. if (!alphaQueue_.IsEmpty())
  1209. {
  1210. PROFILE(RenderAlpha);
  1211. alphaQueue_.Draw(graphics_, renderer_, true);
  1212. }
  1213. // Render post-alpha custom pass
  1214. if (!postAlphaQueue_.IsEmpty())
  1215. {
  1216. PROFILE(RenderPostAlpha);
  1217. postAlphaQueue_.Draw(graphics_, renderer_);
  1218. }
  1219. graphics_->SetFillMode(FILL_SOLID);
  1220. }
  1221. void View::AllocateScreenBuffers()
  1222. {
  1223. unsigned neededBuffers = 0;
  1224. #ifdef USE_OPENGL
  1225. // Due to FBO limitations, in OpenGL deferred modes need to render to texture first and then blit to the backbuffer
  1226. // Also, if rendering to a texture with deferred rendering, it must be RGBA to comply with the rest of the buffers.
  1227. if (renderMode_ != RENDER_FORWARD && (!renderTarget_ || (renderMode_ == RENDER_DEFERRED &&
  1228. renderTarget_->GetParentTexture()->GetFormat() != Graphics::GetRGBAFormat())))
  1229. neededBuffers = 1;
  1230. #endif
  1231. unsigned postProcessPasses = 0;
  1232. for (unsigned i = 0; i < postProcesses_.Size(); ++i)
  1233. postProcessPasses += postProcesses_[i]->GetNumPasses();
  1234. // If more than one post-process pass, need 2 buffers for ping-pong rendering
  1235. if (postProcessPasses)
  1236. neededBuffers = Min((int)postProcessPasses, 2);
  1237. unsigned format = Graphics::GetRGBFormat();
  1238. #ifdef USE_OPENGL
  1239. if (renderMode_ == RENDER_DEFERRED)
  1240. format = Graphics::GetRGBAFormat();
  1241. #endif
  1242. // Allocate screen buffers with filtering active in case the post-processing effects need that
  1243. for (unsigned i = 0; i < neededBuffers; ++i)
  1244. screenBuffers_.Push(renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, format, true));
  1245. }
  1246. void View::BlitFramebuffer()
  1247. {
  1248. // Blit the final image to destination rendertarget
  1249. /// \todo Depth is reset to far plane, so geometry drawn after the view can not be depth tested
  1250. graphics_->SetBlendMode(BLEND_REPLACE);
  1251. graphics_->SetDepthTest(CMP_ALWAYS);
  1252. graphics_->SetDepthWrite(true);
  1253. graphics_->SetScissorTest(false);
  1254. graphics_->SetStencilTest(false);
  1255. graphics_->SetRenderTarget(0, renderTarget_);
  1256. graphics_->SetDepthStencil(GetDepthStencil(renderTarget_));
  1257. graphics_->SetViewport(viewRect_);
  1258. String shaderName = "CopyFramebuffer";
  1259. graphics_->SetShaders(renderer_->GetVertexShader(shaderName), renderer_->GetPixelShader(shaderName));
  1260. float rtWidth = (float)rtSize_.x_;
  1261. float rtHeight = (float)rtSize_.y_;
  1262. float widthRange = 0.5f * viewSize_.x_ / rtWidth;
  1263. float heightRange = 0.5f * viewSize_.y_ / rtHeight;
  1264. #ifdef USE_OPENGL
  1265. Vector4 bufferUVOffset(((float)viewRect_.left_) / rtWidth + widthRange,
  1266. 1.0f - (((float)viewRect_.top_) / rtHeight + heightRange), widthRange, heightRange);
  1267. #else
  1268. Vector4 bufferUVOffset((0.5f + (float)viewRect_.left_) / rtWidth + widthRange,
  1269. (0.5f + (float)viewRect_.top_) / rtHeight + heightRange, widthRange, heightRange);
  1270. #endif
  1271. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  1272. graphics_->SetTexture(TU_DIFFUSE, screenBuffers_[0]);
  1273. DrawFullscreenQuad(camera_, false);
  1274. }
  1275. void View::RunPostProcesses()
  1276. {
  1277. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1278. // Ping-pong buffer indices for read and write
  1279. unsigned readRtIndex = 0;
  1280. unsigned writeRtIndex = screenBuffers_.Size() - 1;
  1281. graphics_->SetBlendMode(BLEND_REPLACE);
  1282. graphics_->SetDepthTest(CMP_ALWAYS);
  1283. graphics_->SetScissorTest(false);
  1284. graphics_->SetStencilTest(false);
  1285. for (unsigned i = 0; i < postProcesses_.Size(); ++i)
  1286. {
  1287. PostProcess* effect = postProcesses_[i];
  1288. // For each effect, rendertargets can be re-used. Allocate them now
  1289. renderer_->SaveScreenBufferAllocations();
  1290. const HashMap<StringHash, PostProcessRenderTarget>& renderTargetInfos = effect->GetRenderTargets();
  1291. HashMap<StringHash, Texture2D*> renderTargets;
  1292. for (HashMap<StringHash, PostProcessRenderTarget>::ConstIterator j = renderTargetInfos.Begin(); j !=
  1293. renderTargetInfos.End(); ++j)
  1294. {
  1295. unsigned width = j->second_.size_.x_;
  1296. unsigned height = j->second_.size_.y_;
  1297. if (j->second_.sizeDivisor_)
  1298. {
  1299. width = viewSize_.x_ / width;
  1300. height = viewSize_.y_ / height;
  1301. }
  1302. renderTargets[j->first_] = renderer_->GetScreenBuffer(width, height, j->second_.format_, j->second_.filtered_);
  1303. }
  1304. // Run each effect pass
  1305. for (unsigned j = 0; j < effect->GetNumPasses(); ++j)
  1306. {
  1307. PostProcessPass* pass = effect->GetPass(j);
  1308. bool lastPass = (i == postProcesses_.Size() - 1) && (j == effect->GetNumPasses() - 1);
  1309. bool swapBuffers = false;
  1310. // Write depth on the last pass only
  1311. graphics_->SetDepthWrite(lastPass);
  1312. // Set output rendertarget
  1313. RenderSurface* rt = 0;
  1314. String output = pass->GetOutput().ToLower();
  1315. if (output == "viewport")
  1316. {
  1317. if (!lastPass)
  1318. {
  1319. rt = screenBuffers_[writeRtIndex]->GetRenderSurface();
  1320. swapBuffers = true;
  1321. }
  1322. else
  1323. rt = renderTarget_;
  1324. graphics_->SetRenderTarget(0, rt);
  1325. graphics_->SetDepthStencil(GetDepthStencil(rt));
  1326. graphics_->SetViewport(viewRect_);
  1327. }
  1328. else
  1329. {
  1330. HashMap<StringHash, Texture2D*>::ConstIterator k = renderTargets.Find(StringHash(output));
  1331. if (k != renderTargets.End())
  1332. rt = k->second_->GetRenderSurface();
  1333. else
  1334. continue; // Skip pass if rendertarget can not be found
  1335. graphics_->SetRenderTarget(0, rt);
  1336. graphics_->SetDepthStencil(GetDepthStencil(rt));
  1337. graphics_->SetViewport(IntRect(0, 0, rt->GetWidth(), rt->GetHeight()));
  1338. }
  1339. // Set shaders, shader parameters and textures
  1340. graphics_->SetShaders(renderer_->GetVertexShader(pass->GetVertexShader()),
  1341. renderer_->GetPixelShader(pass->GetPixelShader()));
  1342. const HashMap<StringHash, Vector4>& globalParameters = effect->GetShaderParameters();
  1343. for (HashMap<StringHash, Vector4>::ConstIterator k = globalParameters.Begin(); k != globalParameters.End(); ++k)
  1344. graphics_->SetShaderParameter(k->first_, k->second_);
  1345. const HashMap<StringHash, Vector4>& parameters = pass->GetShaderParameters();
  1346. for (HashMap<StringHash, Vector4>::ConstIterator k = parameters.Begin(); k != parameters.End(); ++k)
  1347. graphics_->SetShaderParameter(k->first_, k->second_);
  1348. float rtWidth = (float)rtSize_.x_;
  1349. float rtHeight = (float)rtSize_.y_;
  1350. float widthRange = 0.5f * viewSize_.x_ / rtWidth;
  1351. float heightRange = 0.5f * viewSize_.y_ / rtHeight;
  1352. #ifdef USE_OPENGL
  1353. Vector4 bufferUVOffset(((float)viewRect_.left_) / rtWidth + widthRange,
  1354. 1.0f - (((float)viewRect_.top_) / rtHeight + heightRange), widthRange, heightRange);
  1355. #else
  1356. Vector4 bufferUVOffset((0.5f + (float)viewRect_.left_) / rtWidth + widthRange,
  1357. (0.5f + (float)viewRect_.top_) / rtHeight + heightRange, widthRange, heightRange);
  1358. #endif
  1359. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  1360. graphics_->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector4(1.0f / rtWidth, 1.0f / rtHeight, 0.0f, 0.0f));
  1361. // Set per-rendertarget inverse size / offset shader parameters as necessary
  1362. for (HashMap<StringHash, PostProcessRenderTarget>::ConstIterator k = renderTargetInfos.Begin(); k !=
  1363. renderTargetInfos.End(); ++k)
  1364. {
  1365. String invSizeName = k->second_.name_ + "InvSize";
  1366. String offsetsName = k->second_.name_ + "Offsets";
  1367. float width = (float)renderTargets[k->first_]->GetWidth();
  1368. float height = (float)renderTargets[k->first_]->GetHeight();
  1369. graphics_->SetShaderParameter(StringHash(invSizeName), Vector4(1.0f / width, 1.0f / height, 0.0f, 0.0f));
  1370. #ifdef USE_OPENGL
  1371. graphics_->SetShaderParameter(StringHash(offsetsName), Vector4::ZERO);
  1372. #else
  1373. graphics_->SetShaderParameter(StringHash(offsetsName), Vector4(0.5f / width, 0.5f / height, 0.0f, 0.0f));
  1374. #endif
  1375. }
  1376. const String* textureNames = pass->GetTextures();
  1377. for (unsigned k = 0; k < MAX_MATERIAL_TEXTURE_UNITS; ++k)
  1378. {
  1379. if (!textureNames[k].Empty())
  1380. {
  1381. // Texture may either refer to a rendertarget or to a texture resource
  1382. if (!textureNames[k].Compare("viewport", false))
  1383. graphics_->SetTexture(k, screenBuffers_[readRtIndex]);
  1384. else
  1385. {
  1386. HashMap<StringHash, Texture2D*>::ConstIterator l = renderTargets.Find(StringHash(textureNames[k]));
  1387. if (l != renderTargets.End())
  1388. graphics_->SetTexture(k, l->second_);
  1389. else
  1390. {
  1391. // If requesting a texture fails, clear the texture name to prevent redundant attempts
  1392. Texture2D* texture = cache->GetResource<Texture2D>(textureNames[k]);
  1393. if (texture)
  1394. graphics_->SetTexture(k, texture);
  1395. else
  1396. pass->SetTexture((TextureUnit)k, String());
  1397. }
  1398. }
  1399. }
  1400. }
  1401. DrawFullscreenQuad(camera_, false);
  1402. // Swap the ping-pong buffer sides now if necessary
  1403. if (swapBuffers)
  1404. Swap(readRtIndex, writeRtIndex);
  1405. }
  1406. // Forget the rendertargets allocated during this effect
  1407. renderer_->RestoreScreenBufferAllocations();
  1408. }
  1409. }
  1410. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  1411. {
  1412. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  1413. float halfViewSize = camera->GetHalfViewSize();
  1414. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  1415. Vector3 cameraPos = camera->GetNode()->GetWorldPosition();
  1416. for (PODVector<Drawable*>::Iterator i = occluders.Begin(); i != occluders.End();)
  1417. {
  1418. Drawable* occluder = *i;
  1419. bool erase = false;
  1420. if (!occluder->IsInView(frame_, false))
  1421. occluder->UpdateBatches(frame_);
  1422. // Check occluder's draw distance (in main camera view)
  1423. float maxDistance = occluder->GetDrawDistance();
  1424. if (maxDistance <= 0.0f || occluder->GetDistance() <= maxDistance)
  1425. {
  1426. // Check that occluder is big enough on the screen
  1427. const BoundingBox& box = occluder->GetWorldBoundingBox();
  1428. float diagonal = box.Size().Length();
  1429. float compare;
  1430. if (!camera->IsOrthographic())
  1431. compare = diagonal * halfViewSize / occluder->GetDistance();
  1432. else
  1433. compare = diagonal * invOrthoSize;
  1434. if (compare < occluderSizeThreshold_)
  1435. erase = true;
  1436. else
  1437. {
  1438. // Store amount of triangles divided by screen size as a sorting key
  1439. // (best occluders are big and have few triangles)
  1440. occluder->SetSortValue((float)occluder->GetNumOccluderTriangles() / compare);
  1441. }
  1442. }
  1443. else
  1444. erase = true;
  1445. if (erase)
  1446. i = occluders.Erase(i);
  1447. else
  1448. ++i;
  1449. }
  1450. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  1451. if (occluders.Size())
  1452. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  1453. }
  1454. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  1455. {
  1456. buffer->SetMaxTriangles(maxOccluderTriangles_);
  1457. buffer->Clear();
  1458. for (unsigned i = 0; i < occluders.Size(); ++i)
  1459. {
  1460. Drawable* occluder = occluders[i];
  1461. if (i > 0)
  1462. {
  1463. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  1464. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  1465. continue;
  1466. }
  1467. // Check for running out of triangles
  1468. if (!occluder->DrawOcclusion(buffer))
  1469. break;
  1470. }
  1471. buffer->BuildDepthHierarchy();
  1472. }
  1473. void View::ProcessLight(LightQueryResult& query, unsigned threadIndex)
  1474. {
  1475. Light* light = query.light_;
  1476. LightType type = light->GetLightType();
  1477. const Frustum& frustum = camera_->GetFrustum();
  1478. // Check if light should be shadowed
  1479. bool isShadowed = drawShadows_ && light->GetCastShadows() && !light->GetPerVertex() && light->GetShadowIntensity() < 1.0f;
  1480. // If shadow distance non-zero, check it
  1481. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  1482. isShadowed = false;
  1483. // OpenGL ES can not support point light shadows
  1484. #ifdef GL_ES_VERSION_2_0
  1485. if (isShadowed && type == LIGHT_POINT)
  1486. isShadowed = false;
  1487. #endif
  1488. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  1489. PODVector<Drawable*>& tempDrawables = tempDrawables_[threadIndex];
  1490. query.litGeometries_.Clear();
  1491. switch (type)
  1492. {
  1493. case LIGHT_DIRECTIONAL:
  1494. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1495. {
  1496. if (GetLightMask(geometries_[i]) & light->GetLightMask())
  1497. query.litGeometries_.Push(geometries_[i]);
  1498. }
  1499. break;
  1500. case LIGHT_SPOT:
  1501. {
  1502. FrustumOctreeQuery octreeQuery(tempDrawables, light->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1503. octree_->GetDrawables(octreeQuery);
  1504. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1505. {
  1506. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1507. query.litGeometries_.Push(tempDrawables[i]);
  1508. }
  1509. }
  1510. break;
  1511. case LIGHT_POINT:
  1512. {
  1513. SphereOctreeQuery octreeQuery(tempDrawables, Sphere(light->GetNode()->GetWorldPosition(), light->GetRange()),
  1514. DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1515. octree_->GetDrawables(octreeQuery);
  1516. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1517. {
  1518. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1519. query.litGeometries_.Push(tempDrawables[i]);
  1520. }
  1521. }
  1522. break;
  1523. }
  1524. // If no lit geometries or not shadowed, no need to process shadow cameras
  1525. if (query.litGeometries_.Empty() || !isShadowed)
  1526. {
  1527. query.numSplits_ = 0;
  1528. return;
  1529. }
  1530. // Determine number of shadow cameras and setup their initial positions
  1531. SetupShadowCameras(query);
  1532. // Process each split for shadow casters
  1533. query.shadowCasters_.Clear();
  1534. for (unsigned i = 0; i < query.numSplits_; ++i)
  1535. {
  1536. Camera* shadowCamera = query.shadowCameras_[i];
  1537. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1538. query.shadowCasterBegin_[i] = query.shadowCasterEnd_[i] = query.shadowCasters_.Size();
  1539. // For point light check that the face is visible: if not, can skip the split
  1540. if (type == LIGHT_POINT && frustum.IsInsideFast(BoundingBox(shadowCameraFrustum)) == OUTSIDE)
  1541. continue;
  1542. // For directional light check that the split is inside the visible scene: if not, can skip the split
  1543. if (type == LIGHT_DIRECTIONAL)
  1544. {
  1545. if (minZ_ > query.shadowFarSplits_[i])
  1546. continue;
  1547. if (maxZ_ < query.shadowNearSplits_[i])
  1548. continue;
  1549. }
  1550. // Reuse lit geometry query for all except directional lights
  1551. if (type == LIGHT_DIRECTIONAL)
  1552. {
  1553. ShadowCasterOctreeQuery query(tempDrawables, shadowCameraFrustum, DRAWABLE_GEOMETRY,
  1554. camera_->GetViewMask());
  1555. octree_->GetDrawables(query);
  1556. }
  1557. // Check which shadow casters actually contribute to the shadowing
  1558. ProcessShadowCasters(query, tempDrawables, i);
  1559. }
  1560. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  1561. // only cost has been the shadow camera setup & queries
  1562. if (query.shadowCasters_.Empty())
  1563. query.numSplits_ = 0;
  1564. }
  1565. void View::ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex)
  1566. {
  1567. Light* light = query.light_;
  1568. Camera* shadowCamera = query.shadowCameras_[splitIndex];
  1569. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1570. const Matrix3x4& lightView = shadowCamera->GetInverseWorldTransform();
  1571. const Matrix4& lightProj = shadowCamera->GetProjection();
  1572. LightType type = light->GetLightType();
  1573. query.shadowCasterBox_[splitIndex].defined_ = false;
  1574. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  1575. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  1576. // frustum, so that shadow casters do not get rendered into unnecessary splits
  1577. Frustum lightViewFrustum;
  1578. if (type != LIGHT_DIRECTIONAL)
  1579. lightViewFrustum = camera_->GetSplitFrustum(minZ_, maxZ_).Transformed(lightView);
  1580. else
  1581. lightViewFrustum = camera_->GetSplitFrustum(Max(minZ_, query.shadowNearSplits_[splitIndex]),
  1582. Min(maxZ_, query.shadowFarSplits_[splitIndex])).Transformed(lightView);
  1583. BoundingBox lightViewFrustumBox(lightViewFrustum);
  1584. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1585. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1586. return;
  1587. BoundingBox lightViewBox;
  1588. BoundingBox lightProjBox;
  1589. for (PODVector<Drawable*>::ConstIterator i = drawables.Begin(); i != drawables.End(); ++i)
  1590. {
  1591. Drawable* drawable = *i;
  1592. // In case this is a point or spot light query result reused for optimization, we may have non-shadowcasters included.
  1593. // Check for that first
  1594. if (!drawable->GetCastShadows())
  1595. continue;
  1596. // For point light, check that this drawable is inside the split shadow camera frustum
  1597. if (type == LIGHT_POINT && shadowCameraFrustum.IsInsideFast(drawable->GetWorldBoundingBox()) == OUTSIDE)
  1598. continue;
  1599. // Note: as lights are processed threaded, it is possible a drawable's UpdateBatches() function is called several
  1600. // times. However, this should not cause problems as no scene modification happens at this point.
  1601. if (!drawable->IsInView(frame_, false))
  1602. drawable->UpdateBatches(frame_);
  1603. // Check shadow distance
  1604. float maxShadowDistance = drawable->GetShadowDistance();
  1605. if (maxShadowDistance > 0.0f && drawable->GetDistance() > maxShadowDistance)
  1606. continue;
  1607. // Check shadow mask
  1608. if (!(GetShadowMask(drawable) & light->GetLightMask()))
  1609. continue;
  1610. // Project shadow caster bounding box to light view space for visibility check
  1611. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1612. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1613. {
  1614. // Merge to shadow caster bounding box and add to the list
  1615. if (type == LIGHT_DIRECTIONAL)
  1616. query.shadowCasterBox_[splitIndex].Merge(lightViewBox);
  1617. else
  1618. {
  1619. lightProjBox = lightViewBox.Projected(lightProj);
  1620. query.shadowCasterBox_[splitIndex].Merge(lightProjBox);
  1621. }
  1622. query.shadowCasters_.Push(drawable);
  1623. }
  1624. }
  1625. query.shadowCasterEnd_[splitIndex] = query.shadowCasters_.Size();
  1626. }
  1627. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  1628. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  1629. {
  1630. if (shadowCamera->IsOrthographic())
  1631. {
  1632. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  1633. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  1634. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1635. }
  1636. else
  1637. {
  1638. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  1639. if (drawable->IsInView(frame_))
  1640. return true;
  1641. // For perspective lights, extrusion direction depends on the position of the shadow caster
  1642. Vector3 center = lightViewBox.Center();
  1643. Ray extrusionRay(center, center.Normalized());
  1644. float extrusionDistance = shadowCamera->GetFarClip();
  1645. float originalDistance = Clamp(center.Length(), M_EPSILON, extrusionDistance);
  1646. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  1647. float sizeFactor = extrusionDistance / originalDistance;
  1648. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  1649. // than necessary, so the test will be conservative
  1650. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  1651. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  1652. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  1653. lightViewBox.Merge(extrudedBox);
  1654. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1655. }
  1656. }
  1657. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  1658. {
  1659. unsigned width = shadowMap->GetWidth();
  1660. unsigned height = shadowMap->GetHeight();
  1661. int maxCascades = renderer_->GetMaxShadowCascades();
  1662. switch (light->GetLightType())
  1663. {
  1664. case LIGHT_DIRECTIONAL:
  1665. if (maxCascades == 1)
  1666. return IntRect(0, 0, width, height);
  1667. else if (maxCascades == 2)
  1668. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  1669. else
  1670. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  1671. (splitIndex / 2 + 1) * height / 2);
  1672. case LIGHT_SPOT:
  1673. return IntRect(0, 0, width, height);
  1674. case LIGHT_POINT:
  1675. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  1676. (splitIndex / 2 + 1) * height / 3);
  1677. }
  1678. return IntRect();
  1679. }
  1680. void View::SetupShadowCameras(LightQueryResult& query)
  1681. {
  1682. Light* light = query.light_;
  1683. LightType type = light->GetLightType();
  1684. int splits = 0;
  1685. if (type == LIGHT_DIRECTIONAL)
  1686. {
  1687. const CascadeParameters& cascade = light->GetShadowCascade();
  1688. float nearSplit = camera_->GetNearClip();
  1689. float farSplit;
  1690. while (splits < renderer_->GetMaxShadowCascades())
  1691. {
  1692. // If split is completely beyond camera far clip, we are done
  1693. if (nearSplit > camera_->GetFarClip())
  1694. break;
  1695. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  1696. if (farSplit <= nearSplit)
  1697. break;
  1698. // Setup the shadow camera for the split
  1699. Camera* shadowCamera = renderer_->GetShadowCamera();
  1700. query.shadowCameras_[splits] = shadowCamera;
  1701. query.shadowNearSplits_[splits] = nearSplit;
  1702. query.shadowFarSplits_[splits] = farSplit;
  1703. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit);
  1704. nearSplit = farSplit;
  1705. ++splits;
  1706. }
  1707. }
  1708. if (type == LIGHT_SPOT)
  1709. {
  1710. Camera* shadowCamera = renderer_->GetShadowCamera();
  1711. query.shadowCameras_[0] = shadowCamera;
  1712. Node* cameraNode = shadowCamera->GetNode();
  1713. Node* lightNode = light->GetNode();
  1714. cameraNode->SetTransform(lightNode->GetWorldPosition(), lightNode->GetWorldRotation());
  1715. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1716. shadowCamera->SetFarClip(light->GetRange());
  1717. shadowCamera->SetFov(light->GetFov());
  1718. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1719. splits = 1;
  1720. }
  1721. if (type == LIGHT_POINT)
  1722. {
  1723. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1724. {
  1725. Camera* shadowCamera = renderer_->GetShadowCamera();
  1726. query.shadowCameras_[i] = shadowCamera;
  1727. Node* cameraNode = shadowCamera->GetNode();
  1728. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1729. cameraNode->SetPosition(light->GetNode()->GetWorldPosition());
  1730. cameraNode->SetDirection(directions[i]);
  1731. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1732. shadowCamera->SetFarClip(light->GetRange());
  1733. shadowCamera->SetFov(90.0f);
  1734. shadowCamera->SetAspectRatio(1.0f);
  1735. }
  1736. splits = MAX_CUBEMAP_FACES;
  1737. }
  1738. query.numSplits_ = splits;
  1739. }
  1740. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit)
  1741. {
  1742. Node* shadowCameraNode = shadowCamera->GetNode();
  1743. Node* lightNode = light->GetNode();
  1744. float extrusionDistance = camera_->GetFarClip();
  1745. const FocusParameters& parameters = light->GetShadowFocus();
  1746. // Calculate initial position & rotation
  1747. Vector3 lightWorldDirection = lightNode->GetWorldRotation() * Vector3::FORWARD;
  1748. Vector3 pos = cameraNode_->GetWorldPosition() - extrusionDistance * lightWorldDirection;
  1749. shadowCameraNode->SetTransform(pos, lightNode->GetWorldRotation());
  1750. // Calculate main camera shadowed frustum in light's view space
  1751. farSplit = Min(farSplit, camera_->GetFarClip());
  1752. // Use the scene Z bounds to limit frustum size if applicable
  1753. if (parameters.focus_)
  1754. {
  1755. nearSplit = Max(minZ_, nearSplit);
  1756. farSplit = Min(maxZ_, farSplit);
  1757. }
  1758. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  1759. Polyhedron frustumVolume;
  1760. frustumVolume.Define(splitFrustum);
  1761. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  1762. if (parameters.focus_)
  1763. {
  1764. BoundingBox litGeometriesBox;
  1765. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1766. {
  1767. Drawable* drawable = geometries_[i];
  1768. // Skip skyboxes as they have undefinedly large bounding box size
  1769. if (drawable->GetType() == Skybox::GetTypeStatic())
  1770. continue;
  1771. if (drawable->GetMinZ() <= farSplit && drawable->GetMaxZ() >= nearSplit &&
  1772. (GetLightMask(drawable) & light->GetLightMask()))
  1773. litGeometriesBox.Merge(drawable->GetWorldBoundingBox());
  1774. }
  1775. if (litGeometriesBox.defined_)
  1776. {
  1777. frustumVolume.Clip(litGeometriesBox);
  1778. // If volume became empty, restore it to avoid zero size
  1779. if (frustumVolume.Empty())
  1780. frustumVolume.Define(splitFrustum);
  1781. }
  1782. }
  1783. // Transform frustum volume to light space
  1784. const Matrix3x4& lightView = shadowCamera->GetInverseWorldTransform();
  1785. frustumVolume.Transform(lightView);
  1786. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  1787. BoundingBox shadowBox;
  1788. if (!parameters.nonUniform_)
  1789. shadowBox.Define(Sphere(frustumVolume));
  1790. else
  1791. shadowBox.Define(frustumVolume);
  1792. shadowCamera->SetOrthographic(true);
  1793. shadowCamera->SetAspectRatio(1.0f);
  1794. shadowCamera->SetNearClip(0.0f);
  1795. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1796. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  1797. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  1798. }
  1799. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1800. const BoundingBox& shadowCasterBox)
  1801. {
  1802. const FocusParameters& parameters = light->GetShadowFocus();
  1803. float shadowMapWidth = (float)(shadowViewport.Width());
  1804. LightType type = light->GetLightType();
  1805. if (type == LIGHT_DIRECTIONAL)
  1806. {
  1807. BoundingBox shadowBox;
  1808. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1809. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  1810. shadowBox.min_.y_ = -shadowBox.max_.y_;
  1811. shadowBox.min_.x_ = -shadowBox.max_.x_;
  1812. // Requantize and snap to shadow map texels
  1813. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  1814. }
  1815. if (type == LIGHT_SPOT)
  1816. {
  1817. if (parameters.focus_)
  1818. {
  1819. float viewSizeX = Max(Abs(shadowCasterBox.min_.x_), Abs(shadowCasterBox.max_.x_));
  1820. float viewSizeY = Max(Abs(shadowCasterBox.min_.y_), Abs(shadowCasterBox.max_.y_));
  1821. float viewSize = Max(viewSizeX, viewSizeY);
  1822. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  1823. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  1824. float quantize = parameters.quantize_ * invOrthoSize;
  1825. float minView = parameters.minView_ * invOrthoSize;
  1826. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  1827. if (viewSize < 1.0f)
  1828. shadowCamera->SetZoom(1.0f / viewSize);
  1829. }
  1830. }
  1831. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  1832. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  1833. if (shadowCamera->GetZoom() >= 1.0f)
  1834. {
  1835. if (light->GetLightType() != LIGHT_POINT)
  1836. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  1837. else
  1838. {
  1839. #ifdef USE_OPENGL
  1840. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  1841. #else
  1842. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  1843. #endif
  1844. }
  1845. }
  1846. }
  1847. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1848. const BoundingBox& viewBox)
  1849. {
  1850. Node* shadowCameraNode = shadowCamera->GetNode();
  1851. const FocusParameters& parameters = light->GetShadowFocus();
  1852. float shadowMapWidth = (float)(shadowViewport.Width());
  1853. float minX = viewBox.min_.x_;
  1854. float minY = viewBox.min_.y_;
  1855. float maxX = viewBox.max_.x_;
  1856. float maxY = viewBox.max_.y_;
  1857. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  1858. Vector2 viewSize(maxX - minX, maxY - minY);
  1859. // Quantize size to reduce swimming
  1860. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  1861. if (parameters.nonUniform_)
  1862. {
  1863. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1864. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  1865. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1866. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  1867. }
  1868. else if (parameters.focus_)
  1869. {
  1870. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  1871. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1872. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1873. viewSize.y_ = viewSize.x_;
  1874. }
  1875. shadowCamera->SetOrthoSize(viewSize);
  1876. // Center shadow camera to the view space bounding box
  1877. Vector3 pos(shadowCameraNode->GetWorldPosition());
  1878. Quaternion rot(shadowCameraNode->GetWorldRotation());
  1879. Vector3 adjust(center.x_, center.y_, 0.0f);
  1880. shadowCameraNode->Translate(rot * adjust);
  1881. // If the shadow map viewport is known, snap to whole texels
  1882. if (shadowMapWidth > 0.0f)
  1883. {
  1884. Vector3 viewPos(rot.Inverse() * shadowCameraNode->GetWorldPosition());
  1885. // Take into account that shadow map border will not be used
  1886. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  1887. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  1888. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  1889. shadowCameraNode->Translate(rot * snap);
  1890. }
  1891. }
  1892. void View::FindZone(Drawable* drawable)
  1893. {
  1894. Vector3 center = drawable->GetWorldBoundingBox().Center();
  1895. int bestPriority = M_MIN_INT;
  1896. Zone* newZone = 0;
  1897. // If bounding box center is in view, the zone assignment is conclusive also for next frames. Otherwise it is temporary
  1898. // (possibly incorrect) and must be re-evaluated on the next frame
  1899. bool temporary = !camera_->GetFrustum().IsInside(center);
  1900. // First check if the last zone remains a conclusive result
  1901. Zone* lastZone = drawable->GetLastZone();
  1902. if (lastZone && lastZone->IsInside(center) && (drawable->GetZoneMask() & lastZone->GetZoneMask()) &&
  1903. lastZone->GetPriority() >= highestZonePriority_)
  1904. newZone = lastZone;
  1905. else
  1906. {
  1907. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  1908. {
  1909. Zone* zone = *i;
  1910. int priority = zone->GetPriority();
  1911. if (zone->IsInside(center) && (drawable->GetZoneMask() & zone->GetZoneMask()) && priority > bestPriority)
  1912. {
  1913. newZone = zone;
  1914. bestPriority = priority;
  1915. }
  1916. }
  1917. }
  1918. drawable->SetZone(newZone, temporary);
  1919. }
  1920. Zone* View::GetZone(Drawable* drawable)
  1921. {
  1922. if (cameraZoneOverride_)
  1923. return cameraZone_;
  1924. Zone* drawableZone = drawable->GetZone();
  1925. return drawableZone ? drawableZone : cameraZone_;
  1926. }
  1927. unsigned View::GetLightMask(Drawable* drawable)
  1928. {
  1929. return drawable->GetLightMask() & GetZone(drawable)->GetLightMask();
  1930. }
  1931. unsigned View::GetShadowMask(Drawable* drawable)
  1932. {
  1933. return drawable->GetShadowMask() & GetZone(drawable)->GetShadowMask();
  1934. }
  1935. unsigned long long View::GetVertexLightQueueHash(const PODVector<Light*>& vertexLights)
  1936. {
  1937. unsigned long long hash = 0;
  1938. for (PODVector<Light*>::ConstIterator i = vertexLights.Begin(); i != vertexLights.End(); ++i)
  1939. hash += (unsigned long long)(*i);
  1940. return hash;
  1941. }
  1942. Technique* View::GetTechnique(Drawable* drawable, Material* material)
  1943. {
  1944. if (!material)
  1945. {
  1946. const Vector<TechniqueEntry>& techniques = renderer_->GetDefaultMaterial()->GetTechniques();
  1947. return techniques.Size() ? techniques[0].technique_ : (Technique*)0;
  1948. }
  1949. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  1950. // If only one technique, no choice
  1951. if (techniques.Size() == 1)
  1952. return techniques[0].technique_;
  1953. else
  1954. {
  1955. float lodDistance = drawable->GetLodDistance();
  1956. // Check for suitable technique. Techniques should be ordered like this:
  1957. // Most distant & highest quality
  1958. // Most distant & lowest quality
  1959. // Second most distant & highest quality
  1960. // ...
  1961. for (unsigned i = 0; i < techniques.Size(); ++i)
  1962. {
  1963. const TechniqueEntry& entry = techniques[i];
  1964. Technique* tech = entry.technique_;
  1965. if (!tech || (tech->IsSM3() && !graphics_->GetSM3Support()) || materialQuality_ < entry.qualityLevel_)
  1966. continue;
  1967. if (lodDistance >= entry.lodDistance_)
  1968. return tech;
  1969. }
  1970. // If no suitable technique found, fallback to the last
  1971. return techniques.Size() ? techniques.Back().technique_ : (Technique*)0;
  1972. }
  1973. }
  1974. void View::CheckMaterialForAuxView(Material* material)
  1975. {
  1976. const SharedPtr<Texture>* textures = material->GetTextures();
  1977. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  1978. {
  1979. // Have to check cube & 2D textures separately
  1980. Texture* texture = textures[i];
  1981. if (texture)
  1982. {
  1983. if (texture->GetType() == Texture2D::GetTypeStatic())
  1984. {
  1985. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1986. RenderSurface* target = tex2D->GetRenderSurface();
  1987. if (target)
  1988. {
  1989. Viewport* viewport = target->GetViewport();
  1990. if (viewport->GetScene() && viewport->GetCamera())
  1991. renderer_->AddView(target, viewport);
  1992. }
  1993. }
  1994. else if (texture->GetType() == TextureCube::GetTypeStatic())
  1995. {
  1996. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1997. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1998. {
  1999. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  2000. if (target)
  2001. {
  2002. Viewport* viewport = target->GetViewport();
  2003. if (viewport->GetScene() && viewport->GetCamera())
  2004. renderer_->AddView(target, viewport);
  2005. }
  2006. }
  2007. }
  2008. }
  2009. }
  2010. // Set frame number so that we can early-out next time we come across this material on the same frame
  2011. material->MarkForAuxView(frame_.frameNumber_);
  2012. }
  2013. void View::AddBatchToQueue(BatchQueue& batchQueue, Batch& batch, Technique* tech, bool allowInstancing, bool allowShadows)
  2014. {
  2015. if (!batch.material_)
  2016. batch.material_ = renderer_->GetDefaultMaterial();
  2017. // Convert to instanced if possible
  2018. if (allowInstancing && batch.geometryType_ == GEOM_STATIC && batch.geometry_->GetIndexBuffer() && !batch.shaderData_ &&
  2019. !batch.overrideView_)
  2020. batch.geometryType_ = GEOM_INSTANCED;
  2021. if (batch.geometryType_ == GEOM_INSTANCED)
  2022. {
  2023. HashMap<BatchGroupKey, BatchGroup>* groups = batch.isBase_ ? &batchQueue.baseBatchGroups_ : &batchQueue.batchGroups_;
  2024. BatchGroupKey key(batch);
  2025. HashMap<BatchGroupKey, BatchGroup>::Iterator i = groups->Find(key);
  2026. if (i == groups->End())
  2027. {
  2028. // Create a new group based on the batch
  2029. renderer_->SetBatchShaders(batch, tech, allowShadows);
  2030. BatchGroup newGroup(batch);
  2031. newGroup.CalculateSortKey();
  2032. newGroup.instances_.Push(InstanceData(batch.worldTransform_, batch.distance_));
  2033. groups->Insert(MakePair(key, newGroup));
  2034. }
  2035. else
  2036. i->second_.instances_.Push(InstanceData(batch.worldTransform_, batch.distance_));
  2037. }
  2038. else
  2039. {
  2040. renderer_->SetBatchShaders(batch, tech, allowShadows);
  2041. batch.CalculateSortKey();
  2042. batchQueue.batches_.Push(batch);
  2043. }
  2044. }
  2045. void View::PrepareInstancingBuffer()
  2046. {
  2047. PROFILE(PrepareInstancingBuffer);
  2048. unsigned totalInstances = 0;
  2049. totalInstances += baseQueue_.GetNumInstances(renderer_);
  2050. totalInstances += preAlphaQueue_.GetNumInstances(renderer_);
  2051. if (renderMode_ != RENDER_FORWARD)
  2052. totalInstances += gbufferQueue_.GetNumInstances(renderer_);
  2053. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2054. {
  2055. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2056. totalInstances += i->shadowSplits_[j].shadowBatches_.GetNumInstances(renderer_);
  2057. totalInstances += i->litBatches_.GetNumInstances(renderer_);
  2058. }
  2059. // If fail to set buffer size, fall back to per-group locking
  2060. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  2061. {
  2062. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  2063. unsigned freeIndex = 0;
  2064. void* dest = instancingBuffer->Lock(0, totalInstances, true);
  2065. if (!dest)
  2066. return;
  2067. baseQueue_.SetTransforms(renderer_, dest, freeIndex);
  2068. preAlphaQueue_.SetTransforms(renderer_, dest, freeIndex);
  2069. if (renderMode_ != RENDER_FORWARD)
  2070. gbufferQueue_.SetTransforms(renderer_, dest, freeIndex);
  2071. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2072. {
  2073. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2074. i->shadowSplits_[j].shadowBatches_.SetTransforms(renderer_, dest, freeIndex);
  2075. i->litBatches_.SetTransforms(renderer_, dest, freeIndex);
  2076. }
  2077. instancingBuffer->Unlock();
  2078. }
  2079. }
  2080. void View::SetupLightVolumeBatch(Batch& batch)
  2081. {
  2082. Light* light = batch.lightQueue_->light_;
  2083. LightType type = light->GetLightType();
  2084. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  2085. float lightDist;
  2086. // Use replace blend mode for the first pre-pass light volume, and additive for the rest
  2087. graphics_->SetBlendMode(renderMode_ == RENDER_PREPASS && light == lightQueues_.Front().light_ ? BLEND_REPLACE : BLEND_ADD);
  2088. graphics_->SetDepthBias(0.0f, 0.0f);
  2089. graphics_->SetDepthWrite(false);
  2090. if (type != LIGHT_DIRECTIONAL)
  2091. {
  2092. if (type == LIGHT_POINT)
  2093. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  2094. else
  2095. lightDist = light->GetFrustum().Distance(cameraPos);
  2096. // Draw front faces if not inside light volume
  2097. if (lightDist < camera_->GetNearClip() * 2.0f)
  2098. {
  2099. renderer_->SetCullMode(CULL_CW, camera_);
  2100. graphics_->SetDepthTest(CMP_GREATER);
  2101. }
  2102. else
  2103. {
  2104. renderer_->SetCullMode(CULL_CCW, camera_);
  2105. graphics_->SetDepthTest(CMP_LESSEQUAL);
  2106. }
  2107. }
  2108. else
  2109. {
  2110. // In case the same camera is used for multiple views with differing aspect ratios (not recommended)
  2111. // refresh the directional light's model transform before rendering
  2112. light->GetVolumeTransform(camera_);
  2113. graphics_->SetCullMode(CULL_NONE);
  2114. graphics_->SetDepthTest(CMP_ALWAYS);
  2115. }
  2116. graphics_->SetScissorTest(false);
  2117. graphics_->SetStencilTest(true, CMP_NOTEQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 0, light->GetLightMask());
  2118. }
  2119. void View::DrawFullscreenQuad(Camera* camera, bool nearQuad)
  2120. {
  2121. Light* quadDirLight = renderer_->GetQuadDirLight();
  2122. Matrix3x4 model(quadDirLight->GetDirLightTransform(camera, nearQuad));
  2123. graphics_->SetCullMode(CULL_NONE);
  2124. graphics_->SetShaderParameter(VSP_MODEL, model);
  2125. graphics_->SetShaderParameter(VSP_VIEWPROJ, camera->GetProjection());
  2126. graphics_->ClearTransformSources();
  2127. renderer_->GetLightGeometry(quadDirLight)->Draw(graphics_);
  2128. }
  2129. void View::RenderShadowMap(const LightBatchQueue& queue)
  2130. {
  2131. PROFILE(RenderShadowMap);
  2132. Texture2D* shadowMap = queue.shadowMap_;
  2133. graphics_->SetTexture(TU_SHADOWMAP, 0);
  2134. graphics_->SetColorWrite(false);
  2135. graphics_->SetFillMode(FILL_SOLID);
  2136. graphics_->SetStencilTest(false);
  2137. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  2138. graphics_->SetDepthStencil(shadowMap);
  2139. graphics_->SetViewport(IntRect(0, 0, shadowMap->GetWidth(), shadowMap->GetHeight()));
  2140. graphics_->Clear(CLEAR_DEPTH);
  2141. // Set shadow depth bias
  2142. BiasParameters parameters = queue.light_->GetShadowBias();
  2143. // Adjust the light's constant depth bias according to global shadow map resolution
  2144. /// \todo Should remove this adjustment and find a more flexible solution
  2145. unsigned shadowMapSize = renderer_->GetShadowMapSize();
  2146. if (shadowMapSize <= 512)
  2147. parameters.constantBias_ *= 2.0f;
  2148. else if (shadowMapSize >= 2048)
  2149. parameters.constantBias_ *= 0.5f;
  2150. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  2151. // Render each of the splits
  2152. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  2153. {
  2154. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  2155. if (!shadowQueue.shadowBatches_.IsEmpty())
  2156. {
  2157. graphics_->SetViewport(shadowQueue.shadowViewport_);
  2158. shadowQueue.shadowBatches_.Draw(graphics_, renderer_);
  2159. }
  2160. }
  2161. graphics_->SetColorWrite(true);
  2162. graphics_->SetDepthBias(0.0f, 0.0f);
  2163. }
  2164. RenderSurface* View::GetDepthStencil(RenderSurface* renderTarget)
  2165. {
  2166. // If using the backbuffer, return the backbuffer depth-stencil
  2167. if (!renderTarget)
  2168. return 0;
  2169. // Then check for linked depth-stencil
  2170. RenderSurface* depthStencil = renderTarget->GetLinkedDepthStencil();
  2171. // Finally get one from Renderer
  2172. if (!depthStencil)
  2173. depthStencil = renderer_->GetDepthStencil(renderTarget->GetWidth(), renderTarget->GetHeight());
  2174. return depthStencil;
  2175. }
  2176. }