View.cpp 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Graphics/Camera.h"
  23. #include "../Graphics/DebugRenderer.h"
  24. #include "../IO/FileSystem.h"
  25. #include "../Graphics/Geometry.h"
  26. #include "../Graphics/Graphics.h"
  27. #include "../Graphics/GraphicsEvents.h"
  28. #include "../Graphics/GraphicsImpl.h"
  29. #include "../IO/Log.h"
  30. #include "../Graphics/Material.h"
  31. #include "../Graphics/OcclusionBuffer.h"
  32. #include "../Graphics/Octree.h"
  33. #include "../Graphics/Renderer.h"
  34. #include "../Graphics/RenderPath.h"
  35. #include "../Resource/ResourceCache.h"
  36. #include "../Core/Profiler.h"
  37. #include "../Scene/Scene.h"
  38. #include "../Graphics/ShaderVariation.h"
  39. #ifdef ATOMIC_3D
  40. #include "../Atomic3D/Skybox.h"
  41. #endif
  42. #include "../Graphics/Technique.h"
  43. #include "../Graphics/Texture2D.h"
  44. #include "../Graphics/Texture3D.h"
  45. #include "../Graphics/TextureCube.h"
  46. #include "../Graphics/VertexBuffer.h"
  47. #include "../Graphics/View.h"
  48. #include "../UI/UI.h"
  49. #include "../Core/WorkQueue.h"
  50. #include "../DebugNew.h"
  51. namespace Atomic
  52. {
  53. static const Vector3* directions[] =
  54. {
  55. &Vector3::RIGHT,
  56. &Vector3::LEFT,
  57. &Vector3::UP,
  58. &Vector3::DOWN,
  59. &Vector3::FORWARD,
  60. &Vector3::BACK
  61. };
  62. /// %Frustum octree query for shadowcasters.
  63. class ShadowCasterOctreeQuery : public FrustumOctreeQuery
  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. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask)
  70. {
  71. }
  72. /// Intersection test for drawables.
  73. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  74. {
  75. while (start != end)
  76. {
  77. Drawable* drawable = *start++;
  78. if (drawable->GetCastShadows() && (drawable->GetDrawableFlags() & drawableFlags_) &&
  79. (drawable->GetViewMask() & viewMask_))
  80. {
  81. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  82. result_.Push(drawable);
  83. }
  84. }
  85. }
  86. };
  87. /// %Frustum octree query for zones and occluders.
  88. class ZoneOccluderOctreeQuery : public FrustumOctreeQuery
  89. {
  90. public:
  91. /// Construct with frustum and query parameters.
  92. ZoneOccluderOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  93. unsigned viewMask = DEFAULT_VIEWMASK) :
  94. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask)
  95. {
  96. }
  97. /// Intersection test for drawables.
  98. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  99. {
  100. while (start != end)
  101. {
  102. Drawable* drawable = *start++;
  103. unsigned char flags = drawable->GetDrawableFlags();
  104. if ((flags == DRAWABLE_ZONE || (flags == DRAWABLE_GEOMETRY &&
  105. drawable->IsOccluder())) && (drawable->GetViewMask() & viewMask_))
  106. {
  107. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  108. result_.Push(drawable);
  109. }
  110. }
  111. }
  112. };
  113. /// %Frustum octree query with occlusion.
  114. class OccludedFrustumOctreeQuery : public FrustumOctreeQuery
  115. {
  116. public:
  117. /// Construct with frustum, occlusion buffer and query parameters.
  118. OccludedFrustumOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, OcclusionBuffer* buffer, unsigned char
  119. drawableFlags = DRAWABLE_ANY, unsigned viewMask = DEFAULT_VIEWMASK) :
  120. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask),
  121. buffer_(buffer)
  122. {
  123. }
  124. /// Intersection test for an octant.
  125. virtual Intersection TestOctant(const BoundingBox& box, bool inside)
  126. {
  127. if (inside)
  128. return buffer_->IsVisible(box) ? INSIDE : OUTSIDE;
  129. else
  130. {
  131. Intersection result = frustum_.IsInside(box);
  132. if (result != OUTSIDE && !buffer_->IsVisible(box))
  133. result = OUTSIDE;
  134. return result;
  135. }
  136. }
  137. /// Intersection test for drawables. Note: drawable occlusion is performed later in worker threads.
  138. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  139. {
  140. while (start != end)
  141. {
  142. Drawable* drawable = *start++;
  143. if ((drawable->GetDrawableFlags() & drawableFlags_) && (drawable->GetViewMask() & viewMask_))
  144. {
  145. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  146. result_.Push(drawable);
  147. }
  148. }
  149. }
  150. /// Occlusion buffer.
  151. OcclusionBuffer* buffer_;
  152. };
  153. void CheckVisibilityWork(const WorkItem* item, unsigned threadIndex)
  154. {
  155. View* view = reinterpret_cast<View*>(item->aux_);
  156. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  157. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  158. OcclusionBuffer* buffer = view->occlusionBuffer_;
  159. const Matrix3x4& viewMatrix = view->camera_->GetView();
  160. Vector3 viewZ = Vector3(viewMatrix.m20_, viewMatrix.m21_, viewMatrix.m22_);
  161. Vector3 absViewZ = viewZ.Abs();
  162. unsigned cameraViewMask = view->camera_->GetViewMask();
  163. bool cameraZoneOverride = view->cameraZoneOverride_;
  164. PerThreadSceneResult& result = view->sceneResults_[threadIndex];
  165. while (start != end)
  166. {
  167. Drawable* drawable = *start++;
  168. bool batchesUpdated = false;
  169. // If draw distance non-zero, update and check it
  170. float maxDistance = drawable->GetDrawDistance();
  171. if (maxDistance > 0.0f)
  172. {
  173. drawable->UpdateBatches(view->frame_);
  174. batchesUpdated = true;
  175. if (drawable->GetDistance() > maxDistance)
  176. continue;
  177. }
  178. if (!buffer || !drawable->IsOccludee() || buffer->IsVisible(drawable->GetWorldBoundingBox()))
  179. {
  180. if (!batchesUpdated)
  181. drawable->UpdateBatches(view->frame_);
  182. drawable->MarkInView(view->frame_);
  183. // For geometries, find zone, clear lights and calculate view space Z range
  184. if (drawable->GetDrawableFlags() & DRAWABLE_GEOMETRY)
  185. {
  186. Zone* drawableZone = drawable->GetZone();
  187. if (!cameraZoneOverride && (drawable->IsZoneDirty() || !drawableZone || (drawableZone->GetViewMask() &
  188. cameraViewMask) == 0))
  189. view->FindZone(drawable);
  190. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  191. Vector3 center = geomBox.Center();
  192. float viewCenterZ = viewZ.DotProduct(center) + viewMatrix.m23_;
  193. Vector3 edge = geomBox.Size() * 0.5f;
  194. float viewEdgeZ = absViewZ.DotProduct(edge);
  195. float minZ = viewCenterZ - viewEdgeZ;
  196. float maxZ = viewCenterZ + viewEdgeZ;
  197. drawable->SetMinMaxZ(viewCenterZ - viewEdgeZ, viewCenterZ + viewEdgeZ);
  198. drawable->ClearLights();
  199. // Expand the scene bounding box and Z range (skybox not included because of infinite size) and store the drawawble
  200. #ifdef ATOMIC_3D
  201. if (drawable->GetType() != Skybox::GetTypeStatic())
  202. #endif
  203. {
  204. result.minZ_ = Min(result.minZ_, minZ);
  205. result.maxZ_ = Max(result.maxZ_, maxZ);
  206. }
  207. result.geometries_.Push(drawable);
  208. }
  209. else if (drawable->GetDrawableFlags() & DRAWABLE_LIGHT)
  210. {
  211. Light* light = static_cast<Light*>(drawable);
  212. // Skip lights with zero brightness or black color
  213. if (!light->GetEffectiveColor().Equals(Color::BLACK))
  214. result.lights_.Push(light);
  215. }
  216. }
  217. }
  218. }
  219. void ProcessLightWork(const WorkItem* item, unsigned threadIndex)
  220. {
  221. View* view = reinterpret_cast<View*>(item->aux_);
  222. LightQueryResult* query = reinterpret_cast<LightQueryResult*>(item->start_);
  223. view->ProcessLight(*query, threadIndex);
  224. }
  225. void UpdateDrawableGeometriesWork(const WorkItem* item, unsigned threadIndex)
  226. {
  227. const FrameInfo& frame = *(reinterpret_cast<FrameInfo*>(item->aux_));
  228. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  229. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  230. while (start != end)
  231. {
  232. Drawable* drawable = *start++;
  233. // We may leave null pointer holes in the queue if a drawable is found out to require a main thread update
  234. if (drawable)
  235. drawable->UpdateGeometry(frame);
  236. }
  237. }
  238. void SortBatchQueueFrontToBackWork(const WorkItem* item, unsigned threadIndex)
  239. {
  240. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  241. queue->SortFrontToBack();
  242. }
  243. void SortBatchQueueBackToFrontWork(const WorkItem* item, unsigned threadIndex)
  244. {
  245. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  246. queue->SortBackToFront();
  247. }
  248. void SortLightQueueWork(const WorkItem* item, unsigned threadIndex)
  249. {
  250. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  251. start->litBaseBatches_.SortFrontToBack();
  252. start->litBatches_.SortFrontToBack();
  253. }
  254. void SortShadowQueueWork(const WorkItem* item, unsigned threadIndex)
  255. {
  256. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  257. for (unsigned i = 0; i < start->shadowSplits_.Size(); ++i)
  258. start->shadowSplits_[i].shadowBatches_.SortFrontToBack();
  259. }
  260. View::View(Context* context) :
  261. Object(context),
  262. graphics_(GetSubsystem<Graphics>()),
  263. renderer_(GetSubsystem<Renderer>()),
  264. scene_(0),
  265. octree_(0),
  266. camera_(0),
  267. cameraZone_(0),
  268. farClipZone_(0),
  269. renderTarget_(0),
  270. substituteRenderTarget_(0)
  271. {
  272. // Create octree query and scene results vector for each thread
  273. unsigned numThreads = GetSubsystem<WorkQueue>()->GetNumThreads() + 1; // Worker threads + main thread
  274. tempDrawables_.Resize(numThreads);
  275. sceneResults_.Resize(numThreads);
  276. frame_.camera_ = 0;
  277. }
  278. View::~View()
  279. {
  280. }
  281. bool View::Define(RenderSurface* renderTarget, Viewport* viewport)
  282. {
  283. renderPath_ = viewport->GetRenderPath();
  284. if (!renderPath_)
  285. return false;
  286. drawDebug_ = viewport->GetDrawDebug();
  287. hasScenePasses_ = false;
  288. lightVolumeCommand_ = 0;
  289. // Make sure that all necessary batch queues exist
  290. scenePasses_.Clear();
  291. noStencil_ = false;
  292. #ifdef ATOMIC_OPENGL
  293. #ifdef GL_ES_VERSION_2_0
  294. // On OpenGL ES we assume a stencil is not available or would not give a good performance, and disable light stencil
  295. // optimizations in any case
  296. noStencil_ = true;
  297. #else
  298. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  299. {
  300. const RenderPathCommand& command = renderPath_->commands_[i];
  301. if (!command.enabled_)
  302. continue;
  303. if (command.depthStencilName_.Length())
  304. {
  305. // Using a readable depth texture will disable light stencil optimizations on OpenGL, as for compatibility reasons
  306. // we are using a depth format without stencil channel
  307. noStencil_ = true;
  308. break;
  309. }
  310. }
  311. #endif
  312. #endif
  313. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  314. {
  315. const RenderPathCommand& command = renderPath_->commands_[i];
  316. if (!command.enabled_)
  317. continue;
  318. if (command.type_ == CMD_SCENEPASS)
  319. {
  320. hasScenePasses_ = true;
  321. ScenePassInfo info;
  322. info.pass_ = command.pass_;
  323. info.allowInstancing_ = command.sortMode_ != SORT_BACKTOFRONT;
  324. info.markToStencil_ = !noStencil_ && command.markToStencil_;
  325. info.vertexLights_ = command.vertexLights_;
  326. // Check scenepass metadata for defining custom passes which interact with lighting
  327. if (!command.metadata_.Empty())
  328. {
  329. if (command.metadata_ == "gbuffer")
  330. gBufferPassName_ = command.pass_;
  331. else if (command.metadata_ == "base" && command.pass_ != "base")
  332. {
  333. basePassName_ = command.pass_;
  334. litBasePassName_ = "lit" + command.pass_;
  335. }
  336. else if (command.metadata_ == "alpha" && command.pass_ != "alpha")
  337. {
  338. alphaPassName_ = command.pass_;
  339. litAlphaPassName_ = "lit" + command.pass_;
  340. }
  341. }
  342. HashMap<StringHash, BatchQueue>::Iterator j = batchQueues_.Find(command.pass_);
  343. if (j == batchQueues_.End())
  344. j = batchQueues_.Insert(Pair<StringHash, BatchQueue>(command.pass_, BatchQueue()));
  345. info.batchQueue_ = &j->second_;
  346. scenePasses_.Push(info);
  347. }
  348. // Allow a custom forward light pass
  349. else if (command.type_ == CMD_FORWARDLIGHTS && !command.pass_.Empty())
  350. lightPassName_ = command.pass_;
  351. }
  352. scene_ = viewport->GetScene();
  353. camera_ = viewport->GetCamera();
  354. octree_ = 0;
  355. // Get default zone first in case we do not have zones defined
  356. cameraZone_ = farClipZone_ = renderer_->GetDefaultZone();
  357. if (hasScenePasses_)
  358. {
  359. if (!scene_ || !camera_ || !camera_->IsEnabledEffective())
  360. return false;
  361. // If scene is loading scene content asynchronously, it is incomplete and should not be rendered
  362. if (scene_->IsAsyncLoading() && scene_->GetAsyncLoadMode() > LOAD_RESOURCES_ONLY)
  363. return false;
  364. octree_ = scene_->GetComponent<Octree>();
  365. if (!octree_)
  366. return false;
  367. // Do not accept view if camera projection is illegal
  368. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  369. if (!camera_->IsProjectionValid())
  370. return false;
  371. }
  372. cameraNode_ = camera_ ? camera_->GetNode() : (Node*)0;
  373. renderTarget_ = renderTarget;
  374. gBufferPassName_ = StringHash();
  375. basePassName_ = PASS_BASE;
  376. alphaPassName_ = PASS_ALPHA;
  377. lightPassName_ = PASS_LIGHT;
  378. litBasePassName_ = PASS_LITBASE;
  379. litAlphaPassName_ = PASS_LITALPHA;
  380. // Go through commands to check for deferred rendering and other flags
  381. deferred_ = false;
  382. deferredAmbient_ = false;
  383. useLitBase_ = false;
  384. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  385. {
  386. const RenderPathCommand& command = renderPath_->commands_[i];
  387. if (!command.enabled_)
  388. continue;
  389. // Check if ambient pass and G-buffer rendering happens at the same time
  390. if (command.type_ == CMD_SCENEPASS && command.outputNames_.Size() > 1)
  391. {
  392. if (CheckViewportWrite(command))
  393. deferredAmbient_ = true;
  394. }
  395. else if (command.type_ == CMD_LIGHTVOLUMES)
  396. {
  397. lightVolumeCommand_ = &command;
  398. deferred_ = true;
  399. }
  400. else if (command.type_ == CMD_FORWARDLIGHTS)
  401. useLitBase_ = command.useLitBase_;
  402. }
  403. // Validate the rect and calculate size. If zero rect, use whole rendertarget size
  404. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  405. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  406. const IntRect& rect = viewport->GetRect();
  407. if (rect != IntRect::ZERO)
  408. {
  409. viewRect_.left_ = Clamp(rect.left_, 0, rtWidth - 1);
  410. viewRect_.top_ = Clamp(rect.top_, 0, rtHeight - 1);
  411. viewRect_.right_ = Clamp(rect.right_, viewRect_.left_ + 1, rtWidth);
  412. viewRect_.bottom_ = Clamp(rect.bottom_, viewRect_.top_ + 1, rtHeight);
  413. }
  414. else
  415. viewRect_ = IntRect(0, 0, rtWidth, rtHeight);
  416. viewSize_ = viewRect_.Size();
  417. rtSize_ = IntVector2(rtWidth, rtHeight);
  418. // On OpenGL flip the viewport if rendering to a texture for consistent UV addressing with Direct3D9
  419. #ifdef ATOMIC_OPENGL
  420. if (renderTarget_)
  421. {
  422. viewRect_.bottom_ = rtHeight - viewRect_.top_;
  423. viewRect_.top_ = viewRect_.bottom_ - viewSize_.y_;
  424. }
  425. #endif
  426. drawShadows_ = renderer_->GetDrawShadows();
  427. materialQuality_ = renderer_->GetMaterialQuality();
  428. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  429. minInstances_ = renderer_->GetMinInstances();
  430. // Set possible quality overrides from the camera
  431. unsigned viewOverrideFlags = camera_ ? camera_->GetViewOverrideFlags() : VO_NONE;
  432. if (viewOverrideFlags & VO_LOW_MATERIAL_QUALITY)
  433. materialQuality_ = QUALITY_LOW;
  434. if (viewOverrideFlags & VO_DISABLE_SHADOWS)
  435. drawShadows_ = false;
  436. if (viewOverrideFlags & VO_DISABLE_OCCLUSION)
  437. maxOccluderTriangles_ = 0;
  438. // Occlusion buffer has constant width. If resulting height would be too large due to aspect ratio, disable occlusion
  439. if (viewSize_.y_ > viewSize_.x_ * 4)
  440. maxOccluderTriangles_ = 0;
  441. return true;
  442. }
  443. void View::Update(const FrameInfo& frame)
  444. {
  445. frame_.camera_ = camera_;
  446. frame_.timeStep_ = frame.timeStep_;
  447. frame_.frameNumber_ = frame.frameNumber_;
  448. frame_.viewSize_ = viewSize_;
  449. using namespace BeginViewUpdate;
  450. VariantMap& eventData = GetEventDataMap();
  451. eventData[P_VIEW] = this;
  452. eventData[P_SURFACE] = renderTarget_;
  453. eventData[P_TEXTURE] = (renderTarget_ ? renderTarget_->GetParentTexture() : 0);
  454. eventData[P_SCENE] = scene_;
  455. eventData[P_CAMERA] = camera_;
  456. renderer_->SendEvent(E_BEGINVIEWUPDATE, eventData);
  457. int maxSortedInstances = renderer_->GetMaxSortedInstances();
  458. // Clear buffers, geometry, light, occluder & batch list
  459. renderTargets_.Clear();
  460. geometries_.Clear();
  461. lights_.Clear();
  462. zones_.Clear();
  463. occluders_.Clear();
  464. vertexLightQueues_.Clear();
  465. for (HashMap<StringHash, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  466. i->second_.Clear(maxSortedInstances);
  467. if (hasScenePasses_ && (!camera_ || !octree_))
  468. {
  469. renderer_->SendEvent(E_ENDVIEWUPDATE, eventData);
  470. return;
  471. }
  472. // Set automatic aspect ratio if required
  473. if (camera_ && camera_->GetAutoAspectRatio())
  474. camera_->SetAspectRatioInternal((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  475. GetDrawables();
  476. GetBatches();
  477. renderer_->SendEvent(E_ENDVIEWUPDATE, eventData);
  478. }
  479. void View::Render()
  480. {
  481. if (hasScenePasses_ && (!octree_ || !camera_))
  482. return;
  483. // Actually update geometry data now
  484. UpdateGeometries();
  485. // Allocate screen buffers as necessary
  486. AllocateScreenBuffers();
  487. // Forget parameter sources from the previous view
  488. graphics_->ClearParameterSources();
  489. // If stream offset is supported, write all instance transforms to a single large buffer
  490. // Else we must lock the instance buffer for each batch group
  491. if (renderer_->GetDynamicInstancing() && graphics_->GetStreamOffsetSupport())
  492. PrepareInstancingBuffer();
  493. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  494. // again to ensure correct projection will be used
  495. if (camera_)
  496. {
  497. if (camera_->GetAutoAspectRatio())
  498. camera_->SetAspectRatioInternal((float)(viewSize_.x_) / (float)(viewSize_.y_));
  499. }
  500. // Bind the face selection and indirection cube maps for point light shadows
  501. #ifndef GL_ES_VERSION_2_0
  502. if (renderer_->GetDrawShadows())
  503. {
  504. graphics_->SetTexture(TU_FACESELECT, renderer_->GetFaceSelectCubeMap());
  505. graphics_->SetTexture(TU_INDIRECTION, renderer_->GetIndirectionCubeMap());
  506. }
  507. #endif
  508. if (renderTarget_)
  509. {
  510. // On OpenGL, flip the projection if rendering to a texture so that the texture can be addressed in the same way
  511. // as a render texture produced on Direct3D9
  512. #ifdef ATOMIC_OPENGL
  513. if (camera_)
  514. camera_->SetFlipVertical(true);
  515. #endif
  516. }
  517. // Render
  518. ExecuteRenderPathCommands();
  519. // After executing all commands, reset rendertarget & state for debug geometry rendering
  520. // Use the last rendertarget (before blitting) so that OpenGL deferred rendering can have benefit of proper depth buffer
  521. // values; after a blit to backbuffer the same depth buffer would not be available any longer
  522. graphics_->SetRenderTarget(0, currentRenderTarget_);
  523. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  524. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  525. graphics_->SetDepthStencil(GetDepthStencil(currentRenderTarget_));
  526. IntVector2 rtSizeNow = graphics_->GetRenderTargetDimensions();
  527. IntRect viewport = (currentRenderTarget_ == renderTarget_) ? viewRect_ : IntRect(0, 0, rtSizeNow.x_,
  528. rtSizeNow.y_);
  529. graphics_->SetViewport(viewport);
  530. graphics_->SetFillMode(FILL_SOLID);
  531. graphics_->SetClipPlane(false);
  532. graphics_->SetColorWrite(true);
  533. graphics_->SetDepthBias(0.0f, 0.0f);
  534. graphics_->SetScissorTest(false);
  535. graphics_->SetStencilTest(false);
  536. graphics_->ResetStreamFrequencies();
  537. // Draw the associated debug geometry now if enabled
  538. if (drawDebug_ && octree_ && camera_)
  539. {
  540. DebugRenderer* debug = octree_->GetComponent<DebugRenderer>();
  541. if (debug && debug->IsEnabledEffective())
  542. {
  543. debug->SetView(camera_);
  544. debug->Render();
  545. }
  546. }
  547. #ifdef ATOMIC_OPENGL
  548. if (camera_)
  549. camera_->SetFlipVertical(false);
  550. #endif
  551. // Run framebuffer blitting if necessary
  552. if (currentRenderTarget_ != renderTarget_)
  553. BlitFramebuffer(static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture()), renderTarget_, true);
  554. // "Forget" the scene, camera, octree and zone after rendering
  555. scene_ = 0;
  556. camera_ = 0;
  557. octree_ = 0;
  558. cameraZone_ = 0;
  559. farClipZone_ = 0;
  560. occlusionBuffer_ = 0;
  561. frame_.camera_ = 0;
  562. }
  563. Graphics* View::GetGraphics() const
  564. {
  565. return graphics_;
  566. }
  567. Renderer* View::GetRenderer() const
  568. {
  569. return renderer_;
  570. }
  571. void View::SetGlobalShaderParameters()
  572. {
  573. graphics_->SetShaderParameter(VSP_DELTATIME, frame_.timeStep_);
  574. graphics_->SetShaderParameter(PSP_DELTATIME, frame_.timeStep_);
  575. if (scene_)
  576. {
  577. float elapsedTime = scene_->GetElapsedTime();
  578. graphics_->SetShaderParameter(VSP_ELAPSEDTIME, elapsedTime);
  579. graphics_->SetShaderParameter(PSP_ELAPSEDTIME, elapsedTime);
  580. }
  581. }
  582. void View::SetCameraShaderParameters(Camera* camera, bool setProjection)
  583. {
  584. if (!camera)
  585. return;
  586. Matrix3x4 cameraEffectiveTransform = camera->GetEffectiveWorldTransform();
  587. graphics_->SetShaderParameter(VSP_CAMERAPOS, cameraEffectiveTransform.Translation());
  588. graphics_->SetShaderParameter(VSP_CAMERAROT, cameraEffectiveTransform.RotationMatrix());
  589. graphics_->SetShaderParameter(PSP_CAMERAPOS, cameraEffectiveTransform.Translation());
  590. float nearClip = camera->GetNearClip();
  591. float farClip = camera->GetFarClip();
  592. graphics_->SetShaderParameter(VSP_NEARCLIP, nearClip);
  593. graphics_->SetShaderParameter(VSP_FARCLIP, farClip);
  594. graphics_->SetShaderParameter(PSP_NEARCLIP, nearClip);
  595. graphics_->SetShaderParameter(PSP_FARCLIP, farClip);
  596. Vector4 depthMode = Vector4::ZERO;
  597. if (camera->IsOrthographic())
  598. {
  599. depthMode.x_ = 1.0f;
  600. #ifdef ATOMIC_OPENGL
  601. depthMode.z_ = 0.5f;
  602. depthMode.w_ = 0.5f;
  603. #else
  604. depthMode.z_ = 1.0f;
  605. #endif
  606. }
  607. else
  608. depthMode.w_ = 1.0f / camera->GetFarClip();
  609. graphics_->SetShaderParameter(VSP_DEPTHMODE, depthMode);
  610. Vector4 depthReconstruct(farClip / (farClip - nearClip), -nearClip / (farClip - nearClip), camera->IsOrthographic() ? 1.0f :
  611. 0.0f, camera->IsOrthographic() ? 0.0f : 1.0f);
  612. graphics_->SetShaderParameter(PSP_DEPTHRECONSTRUCT, depthReconstruct);
  613. Vector3 nearVector, farVector;
  614. camera->GetFrustumSize(nearVector, farVector);
  615. graphics_->SetShaderParameter(VSP_FRUSTUMSIZE, farVector);
  616. if (setProjection)
  617. {
  618. Matrix4 projection = camera->GetProjection();
  619. #ifdef ATOMIC_OPENGL
  620. // Add constant depth bias manually to the projection matrix due to glPolygonOffset() inconsistency
  621. float constantBias = 2.0f * graphics_->GetDepthConstantBias();
  622. projection.m22_ += projection.m32_ * constantBias;
  623. projection.m23_ += projection.m33_ * constantBias;
  624. #endif
  625. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * camera->GetView());
  626. }
  627. }
  628. void View::SetGBufferShaderParameters(const IntVector2& texSize, const IntRect& viewRect)
  629. {
  630. float texWidth = (float)texSize.x_;
  631. float texHeight = (float)texSize.y_;
  632. float widthRange = 0.5f * viewRect.Width() / texWidth;
  633. float heightRange = 0.5f * viewRect.Height() / texHeight;
  634. #ifdef ATOMIC_OPENGL
  635. Vector4 bufferUVOffset(((float)viewRect.left_) / texWidth + widthRange,
  636. 1.0f - (((float)viewRect.top_) / texHeight + heightRange), widthRange, heightRange);
  637. #else
  638. Vector4 bufferUVOffset((0.5f + (float)viewRect.left_) / texWidth + widthRange,
  639. (0.5f + (float)viewRect.top_) / texHeight + heightRange, widthRange, heightRange);
  640. #endif
  641. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  642. float invSizeX = 1.0f / texWidth;
  643. float invSizeY = 1.0f / texHeight;
  644. graphics_->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector4(invSizeX, invSizeY, 0.0f, 0.0f));
  645. }
  646. void View::GetDrawables()
  647. {
  648. if (!octree_ || !camera_)
  649. return;
  650. PROFILE(GetDrawables);
  651. WorkQueue* queue = GetSubsystem<WorkQueue>();
  652. PODVector<Drawable*>& tempDrawables = tempDrawables_[0];
  653. // Get zones and occluders first
  654. {
  655. ZoneOccluderOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_ZONE, camera_->GetViewMask());
  656. octree_->GetDrawables(query);
  657. }
  658. highestZonePriority_ = M_MIN_INT;
  659. int bestPriority = M_MIN_INT;
  660. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  661. for (PODVector<Drawable*>::ConstIterator i = tempDrawables.Begin(); i != tempDrawables.End(); ++i)
  662. {
  663. Drawable* drawable = *i;
  664. unsigned char flags = drawable->GetDrawableFlags();
  665. if (flags & DRAWABLE_ZONE)
  666. {
  667. Zone* zone = static_cast<Zone*>(drawable);
  668. zones_.Push(zone);
  669. int priority = zone->GetPriority();
  670. if (priority > highestZonePriority_)
  671. highestZonePriority_ = priority;
  672. if (priority > bestPriority && zone->IsInside(cameraPos))
  673. {
  674. cameraZone_ = zone;
  675. bestPriority = priority;
  676. }
  677. }
  678. else
  679. occluders_.Push(drawable);
  680. }
  681. // Determine the zone at far clip distance. If not found, or camera zone has override mode, use camera zone
  682. cameraZoneOverride_ = cameraZone_->GetOverride();
  683. if (!cameraZoneOverride_)
  684. {
  685. Vector3 farClipPos = cameraPos + cameraNode_->GetWorldDirection() * Vector3(0.0f, 0.0f, camera_->GetFarClip());
  686. bestPriority = M_MIN_INT;
  687. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  688. {
  689. int priority = (*i)->GetPriority();
  690. if (priority > bestPriority && (*i)->IsInside(farClipPos))
  691. {
  692. farClipZone_ = *i;
  693. bestPriority = priority;
  694. }
  695. }
  696. }
  697. if (farClipZone_ == renderer_->GetDefaultZone())
  698. farClipZone_ = cameraZone_;
  699. // If occlusion in use, get & render the occluders
  700. occlusionBuffer_ = 0;
  701. if (maxOccluderTriangles_ > 0)
  702. {
  703. UpdateOccluders(occluders_, camera_);
  704. if (occluders_.Size())
  705. {
  706. PROFILE(DrawOcclusion);
  707. occlusionBuffer_ = renderer_->GetOcclusionBuffer(camera_);
  708. DrawOccluders(occlusionBuffer_, occluders_);
  709. }
  710. }
  711. // Get lights and geometries. Coarse occlusion for octants is used at this point
  712. if (occlusionBuffer_)
  713. {
  714. OccludedFrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), occlusionBuffer_, DRAWABLE_GEOMETRY |
  715. DRAWABLE_LIGHT, camera_->GetViewMask());
  716. octree_->GetDrawables(query);
  717. }
  718. else
  719. {
  720. FrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY |
  721. DRAWABLE_LIGHT, camera_->GetViewMask());
  722. octree_->GetDrawables(query);
  723. }
  724. // Check drawable occlusion, find zones for moved drawables and collect geometries & lights in worker threads
  725. {
  726. for (unsigned i = 0; i < sceneResults_.Size(); ++i)
  727. {
  728. PerThreadSceneResult& result = sceneResults_[i];
  729. result.geometries_.Clear();
  730. result.lights_.Clear();
  731. result.minZ_ = M_INFINITY;
  732. result.maxZ_ = 0.0f;
  733. }
  734. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  735. int drawablesPerItem = tempDrawables.Size() / numWorkItems;
  736. PODVector<Drawable*>::Iterator start = tempDrawables.Begin();
  737. // Create a work item for each thread
  738. for (int i = 0; i < numWorkItems; ++i)
  739. {
  740. SharedPtr<WorkItem> item = queue->GetFreeItem();
  741. item->priority_ = M_MAX_UNSIGNED;
  742. item->workFunction_ = CheckVisibilityWork;
  743. item->aux_ = this;
  744. PODVector<Drawable*>::Iterator end = tempDrawables.End();
  745. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  746. end = start + drawablesPerItem;
  747. item->start_ = &(*start);
  748. item->end_ = &(*end);
  749. queue->AddWorkItem(item);
  750. start = end;
  751. }
  752. queue->Complete(M_MAX_UNSIGNED);
  753. }
  754. // Combine lights, geometries & scene Z range from the threads
  755. geometries_.Clear();
  756. lights_.Clear();
  757. minZ_ = M_INFINITY;
  758. maxZ_ = 0.0f;
  759. if (sceneResults_.Size() > 1)
  760. {
  761. for (unsigned i = 0; i < sceneResults_.Size(); ++i)
  762. {
  763. PerThreadSceneResult& result = sceneResults_[i];
  764. geometries_.Push(result.geometries_);
  765. lights_.Push(result.lights_);
  766. minZ_ = Min(minZ_, result.minZ_);
  767. maxZ_ = Max(maxZ_, result.maxZ_);
  768. }
  769. }
  770. else
  771. {
  772. // If just 1 thread, copy the results directly
  773. PerThreadSceneResult& result = sceneResults_[0];
  774. minZ_ = result.minZ_;
  775. maxZ_ = result.maxZ_;
  776. Swap(geometries_, result.geometries_);
  777. Swap(lights_, result.lights_);
  778. }
  779. if (minZ_ == M_INFINITY)
  780. minZ_ = 0.0f;
  781. // Sort the lights to brightest/closest first, and per-vertex lights first so that per-vertex base pass can be evaluated first
  782. for (unsigned i = 0; i < lights_.Size(); ++i)
  783. {
  784. Light* light = lights_[i];
  785. light->SetIntensitySortValue(camera_->GetDistance(light->GetNode()->GetWorldPosition()));
  786. light->SetLightQueue(0);
  787. }
  788. Sort(lights_.Begin(), lights_.End(), CompareLights);
  789. }
  790. void View::GetBatches()
  791. {
  792. if (!octree_ || !camera_)
  793. return;
  794. nonThreadedGeometries_.Clear();
  795. threadedGeometries_.Clear();
  796. WorkQueue* queue = GetSubsystem<WorkQueue>();
  797. PODVector<Light*> vertexLights;
  798. BatchQueue* alphaQueue = batchQueues_.Contains(alphaPassName_) ? &batchQueues_[alphaPassName_] : (BatchQueue*)0;
  799. // Process lit geometries and shadow casters for each light
  800. {
  801. PROFILE(ProcessLights);
  802. lightQueryResults_.Resize(lights_.Size());
  803. for (unsigned i = 0; i < lightQueryResults_.Size(); ++i)
  804. {
  805. SharedPtr<WorkItem> item = queue->GetFreeItem();
  806. item->priority_ = M_MAX_UNSIGNED;
  807. item->workFunction_ = ProcessLightWork;
  808. item->aux_ = this;
  809. LightQueryResult& query = lightQueryResults_[i];
  810. query.light_ = lights_[i];
  811. item->start_ = &query;
  812. queue->AddWorkItem(item);
  813. }
  814. // Ensure all lights have been processed before proceeding
  815. queue->Complete(M_MAX_UNSIGNED);
  816. }
  817. // Build light queues and lit batches
  818. {
  819. PROFILE(GetLightBatches);
  820. // Preallocate light queues: per-pixel lights which have lit geometries
  821. unsigned numLightQueues = 0;
  822. unsigned usedLightQueues = 0;
  823. for (Vector<LightQueryResult>::ConstIterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  824. {
  825. if (!i->light_->GetPerVertex() && i->litGeometries_.Size())
  826. ++numLightQueues;
  827. }
  828. lightQueues_.Resize(numLightQueues);
  829. maxLightsDrawables_.Clear();
  830. unsigned maxSortedInstances = renderer_->GetMaxSortedInstances();
  831. for (Vector<LightQueryResult>::Iterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  832. {
  833. LightQueryResult& query = *i;
  834. // If light has no affected geometries, no need to process further
  835. if (query.litGeometries_.Empty())
  836. continue;
  837. Light* light = query.light_;
  838. // Per-pixel light
  839. if (!light->GetPerVertex())
  840. {
  841. unsigned shadowSplits = query.numSplits_;
  842. // Initialize light queue and store it to the light so that it can be found later
  843. LightBatchQueue& lightQueue = lightQueues_[usedLightQueues++];
  844. light->SetLightQueue(&lightQueue);
  845. lightQueue.light_ = light;
  846. lightQueue.shadowMap_ = 0;
  847. lightQueue.litBaseBatches_.Clear(maxSortedInstances);
  848. lightQueue.litBatches_.Clear(maxSortedInstances);
  849. lightQueue.volumeBatches_.Clear();
  850. // Allocate shadow map now
  851. if (shadowSplits > 0)
  852. {
  853. lightQueue.shadowMap_ = renderer_->GetShadowMap(light, camera_, viewSize_.x_, viewSize_.y_);
  854. // If did not manage to get a shadow map, convert the light to unshadowed
  855. if (!lightQueue.shadowMap_)
  856. shadowSplits = 0;
  857. }
  858. // Setup shadow batch queues
  859. lightQueue.shadowSplits_.Resize(shadowSplits);
  860. for (unsigned j = 0; j < shadowSplits; ++j)
  861. {
  862. ShadowBatchQueue& shadowQueue = lightQueue.shadowSplits_[j];
  863. Camera* shadowCamera = query.shadowCameras_[j];
  864. shadowQueue.shadowCamera_ = shadowCamera;
  865. shadowQueue.nearSplit_ = query.shadowNearSplits_[j];
  866. shadowQueue.farSplit_ = query.shadowFarSplits_[j];
  867. shadowQueue.shadowBatches_.Clear(maxSortedInstances);
  868. // Setup the shadow split viewport and finalize shadow camera parameters
  869. shadowQueue.shadowViewport_ = GetShadowMapViewport(light, j, lightQueue.shadowMap_);
  870. FinalizeShadowCamera(shadowCamera, light, shadowQueue.shadowViewport_, query.shadowCasterBox_[j]);
  871. // Loop through shadow casters
  872. for (PODVector<Drawable*>::ConstIterator k = query.shadowCasters_.Begin() + query.shadowCasterBegin_[j];
  873. k < query.shadowCasters_.Begin() + query.shadowCasterEnd_[j]; ++k)
  874. {
  875. Drawable* drawable = *k;
  876. // If drawable is not in actual view frustum, mark it in view here and check its geometry update type
  877. if (!drawable->IsInView(frame_, true))
  878. {
  879. drawable->MarkInView(frame_.frameNumber_, 0);
  880. UpdateGeometryType type = drawable->GetUpdateGeometryType();
  881. if (type == UPDATE_MAIN_THREAD)
  882. nonThreadedGeometries_.Push(drawable);
  883. else if (type == UPDATE_WORKER_THREAD)
  884. threadedGeometries_.Push(drawable);
  885. }
  886. Zone* zone = GetZone(drawable);
  887. const Vector<SourceBatch>& batches = drawable->GetBatches();
  888. for (unsigned l = 0; l < batches.Size(); ++l)
  889. {
  890. const SourceBatch& srcBatch = batches[l];
  891. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  892. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  893. continue;
  894. Pass* pass = tech->GetSupportedPass(PASS_SHADOW);
  895. // Skip if material has no shadow pass
  896. if (!pass)
  897. continue;
  898. Batch destBatch(srcBatch);
  899. destBatch.pass_ = pass;
  900. destBatch.camera_ = shadowCamera;
  901. destBatch.zone_ = zone;
  902. destBatch.lightQueue_ = &lightQueue;
  903. AddBatchToQueue(shadowQueue.shadowBatches_, destBatch, tech);
  904. }
  905. }
  906. }
  907. // Process lit geometries
  908. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  909. {
  910. Drawable* drawable = *j;
  911. drawable->AddLight(light);
  912. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  913. if (!drawable->GetMaxLights())
  914. GetLitBatches(drawable, lightQueue, alphaQueue);
  915. else
  916. maxLightsDrawables_.Insert(drawable);
  917. }
  918. // In deferred modes, store the light volume batch now
  919. if (deferred_)
  920. {
  921. Batch volumeBatch;
  922. volumeBatch.geometry_ = renderer_->GetLightGeometry(light);
  923. volumeBatch.geometryType_ = GEOM_STATIC;
  924. volumeBatch.worldTransform_ = &light->GetVolumeTransform(camera_);
  925. volumeBatch.numWorldTransforms_ = 1;
  926. volumeBatch.camera_ = camera_;
  927. volumeBatch.lightQueue_ = &lightQueue;
  928. volumeBatch.distance_ = light->GetDistance();
  929. volumeBatch.material_ = 0;
  930. volumeBatch.pass_ = 0;
  931. volumeBatch.zone_ = 0;
  932. renderer_->SetLightVolumeBatchShaders(volumeBatch, lightVolumeCommand_->vertexShaderName_,
  933. lightVolumeCommand_->pixelShaderName_, lightVolumeCommand_->vertexShaderDefines_,
  934. lightVolumeCommand_->pixelShaderDefines_);
  935. lightQueue.volumeBatches_.Push(volumeBatch);
  936. }
  937. }
  938. // Per-vertex light
  939. else
  940. {
  941. // Add the vertex light to lit drawables. It will be processed later during base pass batch generation
  942. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  943. {
  944. Drawable* drawable = *j;
  945. drawable->AddVertexLight(light);
  946. }
  947. }
  948. }
  949. }
  950. // Process drawables with limited per-pixel light count
  951. if (maxLightsDrawables_.Size())
  952. {
  953. PROFILE(GetMaxLightsBatches);
  954. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  955. {
  956. Drawable* drawable = *i;
  957. drawable->LimitLights();
  958. const PODVector<Light*>& lights = drawable->GetLights();
  959. for (unsigned i = 0; i < lights.Size(); ++i)
  960. {
  961. Light* light = lights[i];
  962. // Find the correct light queue again
  963. LightBatchQueue* queue = light->GetLightQueue();
  964. if (queue)
  965. GetLitBatches(drawable, *queue, alphaQueue);
  966. }
  967. }
  968. }
  969. // Build base pass batches and find out the geometry update queue (threaded or nonthreaded) drawables should end up to
  970. {
  971. PROFILE(GetBaseBatches);
  972. for (PODVector<Drawable*>::ConstIterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  973. {
  974. Drawable* drawable = *i;
  975. UpdateGeometryType type = drawable->GetUpdateGeometryType();
  976. if (type == UPDATE_MAIN_THREAD)
  977. nonThreadedGeometries_.Push(drawable);
  978. else if (type == UPDATE_WORKER_THREAD)
  979. threadedGeometries_.Push(drawable);
  980. Zone* zone = GetZone(drawable);
  981. const Vector<SourceBatch>& batches = drawable->GetBatches();
  982. const PODVector<Light*>& drawableVertexLights = drawable->GetVertexLights();
  983. if (!drawableVertexLights.Empty())
  984. drawable->LimitVertexLights();
  985. for (unsigned j = 0; j < batches.Size(); ++j)
  986. {
  987. const SourceBatch& srcBatch = batches[j];
  988. // Check here if the material refers to a rendertarget texture with camera(s) attached
  989. // Only check this for backbuffer views (null rendertarget)
  990. if (srcBatch.material_ && srcBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_ && !renderTarget_)
  991. CheckMaterialForAuxView(srcBatch.material_);
  992. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  993. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  994. continue;
  995. Batch destBatch(srcBatch);
  996. destBatch.camera_ = camera_;
  997. destBatch.zone_ = zone;
  998. destBatch.isBase_ = true;
  999. destBatch.pass_ = 0;
  1000. destBatch.lightMask_ = GetLightMask(drawable);
  1001. // Check each of the scene passes
  1002. for (unsigned k = 0; k < scenePasses_.Size(); ++k)
  1003. {
  1004. ScenePassInfo& info = scenePasses_[k];
  1005. destBatch.pass_ = tech->GetSupportedPass(info.pass_);
  1006. if (!destBatch.pass_)
  1007. continue;
  1008. // Skip forward base pass if the corresponding litbase pass already exists
  1009. if (info.pass_ == basePassName_ && j < 32 && drawable->HasBasePass(j))
  1010. continue;
  1011. if (info.vertexLights_ && !drawableVertexLights.Empty())
  1012. {
  1013. // For a deferred opaque batch, check if the vertex lights include converted per-pixel lights, and remove
  1014. // them to prevent double-lighting
  1015. if (deferred_ && destBatch.pass_->GetBlendMode() == BLEND_REPLACE)
  1016. {
  1017. vertexLights.Clear();
  1018. for (unsigned i = 0; i < drawableVertexLights.Size(); ++i)
  1019. {
  1020. if (drawableVertexLights[i]->GetPerVertex())
  1021. vertexLights.Push(drawableVertexLights[i]);
  1022. }
  1023. }
  1024. else
  1025. vertexLights = drawableVertexLights;
  1026. if (!vertexLights.Empty())
  1027. {
  1028. // Find a vertex light queue. If not found, create new
  1029. unsigned long long hash = GetVertexLightQueueHash(vertexLights);
  1030. HashMap<unsigned long long, LightBatchQueue>::Iterator i = vertexLightQueues_.Find(hash);
  1031. if (i == vertexLightQueues_.End())
  1032. {
  1033. i = vertexLightQueues_.Insert(MakePair(hash, LightBatchQueue()));
  1034. i->second_.light_ = 0;
  1035. i->second_.shadowMap_ = 0;
  1036. i->second_.vertexLights_ = vertexLights;
  1037. }
  1038. destBatch.lightQueue_ = &(i->second_);
  1039. }
  1040. }
  1041. else
  1042. destBatch.lightQueue_ = 0;
  1043. bool allowInstancing = info.allowInstancing_;
  1044. if (allowInstancing && info.markToStencil_ && destBatch.lightMask_ != (zone->GetLightMask() & 0xff))
  1045. allowInstancing = false;
  1046. AddBatchToQueue(*info.batchQueue_, destBatch, tech, allowInstancing);
  1047. }
  1048. }
  1049. }
  1050. }
  1051. }
  1052. void View::UpdateGeometries()
  1053. {
  1054. PROFILE(SortAndUpdateGeometry);
  1055. WorkQueue* queue = GetSubsystem<WorkQueue>();
  1056. // Sort batches
  1057. {
  1058. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1059. {
  1060. const RenderPathCommand& command = renderPath_->commands_[i];
  1061. if (!IsNecessary(command))
  1062. continue;
  1063. if (command.type_ == CMD_SCENEPASS)
  1064. {
  1065. SharedPtr<WorkItem> item = queue->GetFreeItem();
  1066. item->priority_ = M_MAX_UNSIGNED;
  1067. item->workFunction_ = command.sortMode_ == SORT_FRONTTOBACK ? SortBatchQueueFrontToBackWork : SortBatchQueueBackToFrontWork;
  1068. item->start_ = &batchQueues_[command.pass_];
  1069. queue->AddWorkItem(item);
  1070. }
  1071. }
  1072. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1073. {
  1074. SharedPtr<WorkItem> lightItem = queue->GetFreeItem();
  1075. lightItem->priority_ = M_MAX_UNSIGNED;
  1076. lightItem->workFunction_ = SortLightQueueWork;
  1077. lightItem->start_ = &(*i);
  1078. queue->AddWorkItem(lightItem);
  1079. if (i->shadowSplits_.Size())
  1080. {
  1081. SharedPtr<WorkItem> shadowItem = queue->GetFreeItem();
  1082. shadowItem->priority_ = M_MAX_UNSIGNED;
  1083. shadowItem->workFunction_ = SortShadowQueueWork;
  1084. shadowItem->start_ = &(*i);
  1085. queue->AddWorkItem(shadowItem);
  1086. }
  1087. }
  1088. }
  1089. // Update geometries. Split into threaded and non-threaded updates.
  1090. {
  1091. if (threadedGeometries_.Size())
  1092. {
  1093. // In special cases (context loss, multi-view) a drawable may theoretically first have reported a threaded update, but will actually
  1094. // require a main thread update. Check these cases first and move as applicable. The threaded work routine will tolerate the null
  1095. // pointer holes that we leave to the threaded update queue.
  1096. for (PODVector<Drawable*>::Iterator i = threadedGeometries_.Begin(); i != threadedGeometries_.End(); ++i)
  1097. {
  1098. if ((*i)->GetUpdateGeometryType() == UPDATE_MAIN_THREAD)
  1099. {
  1100. nonThreadedGeometries_.Push(*i);
  1101. *i = 0;
  1102. }
  1103. }
  1104. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  1105. int drawablesPerItem = threadedGeometries_.Size() / numWorkItems;
  1106. PODVector<Drawable*>::Iterator start = threadedGeometries_.Begin();
  1107. for (int i = 0; i < numWorkItems; ++i)
  1108. {
  1109. PODVector<Drawable*>::Iterator end = threadedGeometries_.End();
  1110. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  1111. end = start + drawablesPerItem;
  1112. SharedPtr<WorkItem> item = queue->GetFreeItem();
  1113. item->priority_ = M_MAX_UNSIGNED;
  1114. item->workFunction_ = UpdateDrawableGeometriesWork;
  1115. item->aux_ = const_cast<FrameInfo*>(&frame_);
  1116. item->start_ = &(*start);
  1117. item->end_ = &(*end);
  1118. queue->AddWorkItem(item);
  1119. start = end;
  1120. }
  1121. }
  1122. // While the work queue is processed, update non-threaded geometries
  1123. for (PODVector<Drawable*>::ConstIterator i = nonThreadedGeometries_.Begin(); i != nonThreadedGeometries_.End(); ++i)
  1124. (*i)->UpdateGeometry(frame_);
  1125. }
  1126. // Finally ensure all threaded work has completed
  1127. queue->Complete(M_MAX_UNSIGNED);
  1128. }
  1129. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue, BatchQueue* alphaQueue)
  1130. {
  1131. Light* light = lightQueue.light_;
  1132. Zone* zone = GetZone(drawable);
  1133. const Vector<SourceBatch>& batches = drawable->GetBatches();
  1134. bool hasAmbientGradient = zone->GetAmbientGradient() && zone->GetAmbientStartColor() != zone->GetAmbientEndColor();
  1135. // Shadows on transparencies can only be rendered if shadow maps are not reused
  1136. bool allowTransparentShadows = !renderer_->GetReuseShadowMaps();
  1137. bool allowLitBase = useLitBase_ && !light->IsNegative() && light == drawable->GetFirstLight() &&
  1138. drawable->GetVertexLights().Empty() && !hasAmbientGradient;
  1139. for (unsigned i = 0; i < batches.Size(); ++i)
  1140. {
  1141. const SourceBatch& srcBatch = batches[i];
  1142. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  1143. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  1144. continue;
  1145. // Do not create pixel lit forward passes for materials that render into the G-buffer
  1146. if (gBufferPassName_.Value() && tech->HasPass(gBufferPassName_))
  1147. continue;
  1148. Batch destBatch(srcBatch);
  1149. bool isLitAlpha = false;
  1150. // Check for lit base pass. Because it uses the replace blend mode, it must be ensured to be the first light
  1151. // Also vertex lighting or ambient gradient require the non-lit base pass, so skip in those cases
  1152. if (i < 32 && allowLitBase)
  1153. {
  1154. destBatch.pass_ = tech->GetSupportedPass(litBasePassName_);
  1155. if (destBatch.pass_)
  1156. {
  1157. destBatch.isBase_ = true;
  1158. drawable->SetBasePass(i);
  1159. }
  1160. else
  1161. destBatch.pass_ = tech->GetSupportedPass(lightPassName_);
  1162. }
  1163. else
  1164. destBatch.pass_ = tech->GetSupportedPass(lightPassName_);
  1165. // If no lit pass, check for lit alpha
  1166. if (!destBatch.pass_)
  1167. {
  1168. destBatch.pass_ = tech->GetSupportedPass(litAlphaPassName_);
  1169. isLitAlpha = true;
  1170. }
  1171. // Skip if material does not receive light at all
  1172. if (!destBatch.pass_)
  1173. continue;
  1174. destBatch.camera_ = camera_;
  1175. destBatch.lightQueue_ = &lightQueue;
  1176. destBatch.zone_ = zone;
  1177. if (!isLitAlpha)
  1178. {
  1179. if (destBatch.isBase_)
  1180. AddBatchToQueue(lightQueue.litBaseBatches_, destBatch, tech);
  1181. else
  1182. AddBatchToQueue(lightQueue.litBatches_, destBatch, tech);
  1183. }
  1184. else if (alphaQueue)
  1185. {
  1186. // Transparent batches can not be instanced
  1187. AddBatchToQueue(*alphaQueue, destBatch, tech, false, allowTransparentShadows);
  1188. }
  1189. }
  1190. }
  1191. void View::ExecuteRenderPathCommands()
  1192. {
  1193. // If not reusing shadowmaps, render all of them first
  1194. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  1195. {
  1196. PROFILE(RenderShadowMaps);
  1197. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1198. {
  1199. if (i->shadowMap_)
  1200. RenderShadowMap(*i);
  1201. }
  1202. }
  1203. {
  1204. PROFILE(ExecuteRenderPath);
  1205. // Set for safety in case of empty renderpath
  1206. currentRenderTarget_ = substituteRenderTarget_ ? substituteRenderTarget_ : renderTarget_;
  1207. currentViewportTexture_ = 0;
  1208. bool viewportModified = false;
  1209. bool isPingponging = false;
  1210. unsigned lastCommandIndex = 0;
  1211. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1212. {
  1213. RenderPathCommand& command = renderPath_->commands_[i];
  1214. if (IsNecessary(command))
  1215. lastCommandIndex = i;
  1216. }
  1217. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1218. {
  1219. RenderPathCommand& command = renderPath_->commands_[i];
  1220. if (!IsNecessary(command))
  1221. continue;
  1222. bool viewportRead = CheckViewportRead(command);
  1223. bool viewportWrite = CheckViewportWrite(command);
  1224. bool beginPingpong = CheckPingpong(i);
  1225. // Has the viewport been modified and will be read as a texture by the current command?
  1226. if (viewportRead && viewportModified)
  1227. {
  1228. // Start pingponging without a blit if already rendering to the substitute render target
  1229. if (currentRenderTarget_ && currentRenderTarget_ == substituteRenderTarget_ && beginPingpong)
  1230. isPingponging = true;
  1231. // If not using pingponging, simply resolve/copy to the first viewport texture
  1232. if (!isPingponging)
  1233. {
  1234. if (!currentRenderTarget_)
  1235. {
  1236. graphics_->ResolveToTexture(viewportTextures_[0], viewRect_);
  1237. currentViewportTexture_ = viewportTextures_[0];
  1238. viewportModified = false;
  1239. }
  1240. else
  1241. {
  1242. if (viewportWrite)
  1243. {
  1244. BlitFramebuffer(static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture()),
  1245. viewportTextures_[0]->GetRenderSurface(), false);
  1246. currentViewportTexture_ = viewportTextures_[0];
  1247. viewportModified = false;
  1248. }
  1249. else
  1250. {
  1251. // If the current render target is already a texture, and we are not writing to it, can read that
  1252. // texture directly instead of blitting. However keep the viewport dirty flag in case a later command
  1253. // will do both read and write, and then we need to blit / resolve
  1254. currentViewportTexture_ = static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture());
  1255. }
  1256. }
  1257. }
  1258. else
  1259. {
  1260. // Swap the pingpong double buffer sides. Texture 0 will be read next
  1261. viewportTextures_[1] = viewportTextures_[0];
  1262. viewportTextures_[0] = static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture());
  1263. currentViewportTexture_ = viewportTextures_[0];
  1264. viewportModified = false;
  1265. }
  1266. }
  1267. if (beginPingpong)
  1268. isPingponging = true;
  1269. // Determine viewport write target
  1270. if (viewportWrite)
  1271. {
  1272. if (isPingponging)
  1273. {
  1274. currentRenderTarget_ = viewportTextures_[1]->GetRenderSurface();
  1275. // If the render path ends into a quad, it can be redirected to the final render target
  1276. // However, on OpenGL we can not reliably do this in case the final target is the backbuffer, and we want to
  1277. // render depth buffer sensitive debug geometry afterward (backbuffer and textures can not share depth)
  1278. #ifndef ATOMIC_OPENGL
  1279. if (i == lastCommandIndex && command.type_ == CMD_QUAD)
  1280. #else
  1281. if (i == lastCommandIndex && command.type_ == CMD_QUAD && renderTarget_)
  1282. #endif
  1283. currentRenderTarget_ = renderTarget_;
  1284. }
  1285. else
  1286. currentRenderTarget_ = substituteRenderTarget_ ? substituteRenderTarget_ : renderTarget_;
  1287. }
  1288. switch (command.type_)
  1289. {
  1290. case CMD_CLEAR:
  1291. {
  1292. PROFILE(ClearRenderTarget);
  1293. Color clearColor = command.clearColor_;
  1294. if (command.useFogColor_)
  1295. clearColor = farClipZone_->GetFogColor();
  1296. SetRenderTargets(command);
  1297. graphics_->Clear(command.clearFlags_, clearColor, command.clearDepth_, command.clearStencil_);
  1298. }
  1299. break;
  1300. case CMD_SCENEPASS:
  1301. if (!batchQueues_[command.pass_].IsEmpty())
  1302. {
  1303. PROFILE(RenderScenePass);
  1304. SetRenderTargets(command);
  1305. bool allowDepthWrite = SetTextures(command);
  1306. graphics_->SetDrawAntialiased(true);
  1307. graphics_->SetFillMode(camera_->GetFillMode());
  1308. graphics_->SetClipPlane(camera_->GetUseClipping(), camera_->GetClipPlane(), camera_->GetView(), camera_->GetProjection());
  1309. batchQueues_[command.pass_].Draw(this, command.markToStencil_, false, allowDepthWrite);
  1310. }
  1311. break;
  1312. case CMD_QUAD:
  1313. {
  1314. PROFILE(RenderQuad);
  1315. SetRenderTargets(command);
  1316. SetTextures(command);
  1317. RenderQuad(command);
  1318. }
  1319. break;
  1320. case CMD_FORWARDLIGHTS:
  1321. // Render shadow maps + opaque objects' additive lighting
  1322. if (!lightQueues_.Empty())
  1323. {
  1324. PROFILE(RenderLights);
  1325. SetRenderTargets(command);
  1326. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1327. {
  1328. // If reusing shadowmaps, render each of them before the lit batches
  1329. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1330. {
  1331. RenderShadowMap(*i);
  1332. SetRenderTargets(command);
  1333. }
  1334. bool allowDepthWrite = SetTextures(command);
  1335. graphics_->SetDrawAntialiased(true);
  1336. graphics_->SetFillMode(camera_->GetFillMode());
  1337. graphics_->SetClipPlane(camera_->GetUseClipping(), camera_->GetClipPlane(), camera_->GetView(), camera_->GetProjection());
  1338. // Draw base (replace blend) batches first
  1339. i->litBaseBatches_.Draw(this, false, false, allowDepthWrite);
  1340. // Then, if there are additive passes, optimize the light and draw them
  1341. if (!i->litBatches_.IsEmpty())
  1342. {
  1343. renderer_->OptimizeLightByScissor(i->light_, camera_);
  1344. if (!noStencil_)
  1345. renderer_->OptimizeLightByStencil(i->light_, camera_);
  1346. i->litBatches_.Draw(this, false, true, allowDepthWrite);
  1347. }
  1348. }
  1349. graphics_->SetScissorTest(false);
  1350. graphics_->SetStencilTest(false);
  1351. }
  1352. break;
  1353. case CMD_LIGHTVOLUMES:
  1354. // Render shadow maps + light volumes
  1355. if (!lightQueues_.Empty())
  1356. {
  1357. PROFILE(RenderLightVolumes);
  1358. SetRenderTargets(command);
  1359. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1360. {
  1361. // If reusing shadowmaps, render each of them before the lit batches
  1362. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1363. {
  1364. RenderShadowMap(*i);
  1365. SetRenderTargets(command);
  1366. }
  1367. SetTextures(command);
  1368. for (unsigned j = 0; j < i->volumeBatches_.Size(); ++j)
  1369. {
  1370. SetupLightVolumeBatch(i->volumeBatches_[j]);
  1371. i->volumeBatches_[j].Draw(this, false);
  1372. }
  1373. }
  1374. graphics_->SetScissorTest(false);
  1375. graphics_->SetStencilTest(false);
  1376. }
  1377. break;
  1378. case CMD_RENDERUI:
  1379. {
  1380. SetRenderTargets(command);
  1381. GetSubsystem<UI>()->Render(false);
  1382. }
  1383. break;
  1384. default:
  1385. break;
  1386. }
  1387. // If current command output to the viewport, mark it modified
  1388. if (viewportWrite)
  1389. viewportModified = true;
  1390. }
  1391. }
  1392. }
  1393. void View::SetRenderTargets(RenderPathCommand& command)
  1394. {
  1395. unsigned index = 0;
  1396. bool useColorWrite = true;
  1397. bool useCustomDepth = false;
  1398. while (index < command.outputNames_.Size())
  1399. {
  1400. if (!command.outputNames_[index].Compare("viewport", false))
  1401. graphics_->SetRenderTarget(index, currentRenderTarget_);
  1402. else
  1403. {
  1404. StringHash nameHash(command.outputNames_[index]);
  1405. if (renderTargets_.Contains(nameHash))
  1406. {
  1407. Texture2D* texture = renderTargets_[nameHash];
  1408. // Check for depth only rendering (by specifying a depth texture as the sole output)
  1409. if (!index && command.outputNames_.Size() == 1 && texture && (texture->GetFormat() ==
  1410. Graphics::GetReadableDepthFormat() || texture->GetFormat() == Graphics::GetDepthStencilFormat()))
  1411. {
  1412. useColorWrite = false;
  1413. useCustomDepth = true;
  1414. #ifndef ATOMIC_OPENGL
  1415. // On D3D actual depth-only rendering is illegal, we need a color rendertarget
  1416. if (!depthOnlyDummyTexture_)
  1417. {
  1418. depthOnlyDummyTexture_ = renderer_->GetScreenBuffer(texture->GetWidth(), texture->GetHeight(),
  1419. graphics_->GetDummyColorFormat(), false, false);
  1420. }
  1421. #endif
  1422. graphics_->SetRenderTarget(0, depthOnlyDummyTexture_);
  1423. graphics_->SetDepthStencil(texture);
  1424. }
  1425. else
  1426. graphics_->SetRenderTarget(index, texture);
  1427. }
  1428. else
  1429. graphics_->SetRenderTarget(0, (RenderSurface*)0);
  1430. }
  1431. ++index;
  1432. }
  1433. while (index < MAX_RENDERTARGETS)
  1434. {
  1435. graphics_->SetRenderTarget(index, (RenderSurface*)0);
  1436. ++index;
  1437. }
  1438. if (command.depthStencilName_.Length())
  1439. {
  1440. Texture2D* depthTexture = renderTargets_[StringHash(command.depthStencilName_)];
  1441. if (depthTexture)
  1442. {
  1443. useCustomDepth = true;
  1444. graphics_->SetDepthStencil(depthTexture);
  1445. }
  1446. }
  1447. // When rendering to the final destination rendertarget, use the actual viewport. Otherwise texture rendertargets will be
  1448. // viewport-sized, so they should use their full size as the viewport
  1449. IntVector2 rtSizeNow = graphics_->GetRenderTargetDimensions();
  1450. IntRect viewport = (graphics_->GetRenderTarget(0) == renderTarget_) ? viewRect_ : IntRect(0, 0, rtSizeNow.x_,
  1451. rtSizeNow.y_);
  1452. if (!useCustomDepth)
  1453. graphics_->SetDepthStencil(GetDepthStencil(graphics_->GetRenderTarget(0)));
  1454. graphics_->SetViewport(viewport);
  1455. graphics_->SetColorWrite(useColorWrite);
  1456. }
  1457. bool View::SetTextures(RenderPathCommand& command)
  1458. {
  1459. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1460. bool allowDepthWrite = true;
  1461. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1462. {
  1463. if (command.textureNames_[i].Empty())
  1464. continue;
  1465. // Bind the rendered output
  1466. if (!command.textureNames_[i].Compare("viewport", false))
  1467. {
  1468. graphics_->SetTexture(i, currentViewportTexture_);
  1469. continue;
  1470. }
  1471. // Bind a rendertarget
  1472. HashMap<StringHash, Texture2D*>::ConstIterator j = renderTargets_.Find(command.textureNames_[i]);
  1473. if (j != renderTargets_.End())
  1474. {
  1475. graphics_->SetTexture(i, j->second_);
  1476. // Check if the current depth stencil is being sampled
  1477. if (graphics_->GetDepthStencil() && j->second_ == graphics_->GetDepthStencil()->GetParentTexture())
  1478. allowDepthWrite = false;
  1479. continue;
  1480. }
  1481. // Bind a texture from the resource system
  1482. Texture* texture;
  1483. // Detect cube/3D textures by file extension: they are defined by an XML file
  1484. if (GetExtension(command.textureNames_[i]) == ".xml")
  1485. {
  1486. // Assume 3D textures are only bound to the volume map unit, otherwise it's a cube texture
  1487. if (i == TU_VOLUMEMAP)
  1488. texture = cache->GetResource<Texture3D>(command.textureNames_[i]);
  1489. else
  1490. texture = cache->GetResource<TextureCube>(command.textureNames_[i]);
  1491. }
  1492. else
  1493. texture = cache->GetResource<Texture2D>(command.textureNames_[i]);
  1494. if (texture)
  1495. graphics_->SetTexture(i, texture);
  1496. else
  1497. {
  1498. // If requesting a texture fails, clear the texture name to prevent redundant attempts
  1499. command.textureNames_[i] = String::EMPTY;
  1500. }
  1501. }
  1502. return allowDepthWrite;
  1503. }
  1504. void View::RenderQuad(RenderPathCommand& command)
  1505. {
  1506. if (command.vertexShaderName_.Empty() || command.pixelShaderName_.Empty())
  1507. return;
  1508. // If shader can not be found, clear it from the command to prevent redundant attempts
  1509. ShaderVariation* vs = graphics_->GetShader(VS, command.vertexShaderName_, command.vertexShaderDefines_);
  1510. if (!vs)
  1511. command.vertexShaderName_ = String::EMPTY;
  1512. ShaderVariation* ps = graphics_->GetShader(PS, command.pixelShaderName_, command.pixelShaderDefines_);
  1513. if (!ps)
  1514. command.pixelShaderName_ = String::EMPTY;
  1515. // Set shaders & shader parameters and textures
  1516. graphics_->SetShaders(vs, ps);
  1517. const HashMap<StringHash, Variant>& parameters = command.shaderParameters_;
  1518. for (HashMap<StringHash, Variant>::ConstIterator k = parameters.Begin(); k != parameters.End(); ++k)
  1519. graphics_->SetShaderParameter(k->first_, k->second_);
  1520. SetGlobalShaderParameters();
  1521. SetCameraShaderParameters(camera_, false);
  1522. // During renderpath commands the G-Buffer or viewport texture is assumed to always be viewport-sized
  1523. IntRect viewport = graphics_->GetViewport();
  1524. IntVector2 viewSize = IntVector2(viewport.Width(), viewport.Height());
  1525. SetGBufferShaderParameters(viewSize, IntRect(0, 0, viewSize.x_, viewSize.y_));
  1526. // Set per-rendertarget inverse size / offset shader parameters as necessary
  1527. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1528. {
  1529. const RenderTargetInfo& rtInfo = renderPath_->renderTargets_[i];
  1530. if (!rtInfo.enabled_)
  1531. continue;
  1532. StringHash nameHash(rtInfo.name_);
  1533. if (!renderTargets_.Contains(nameHash))
  1534. continue;
  1535. String invSizeName = rtInfo.name_ + "InvSize";
  1536. String offsetsName = rtInfo.name_ + "Offsets";
  1537. float width = (float)renderTargets_[nameHash]->GetWidth();
  1538. float height = (float)renderTargets_[nameHash]->GetHeight();
  1539. graphics_->SetShaderParameter(invSizeName, Vector2(1.0f / width, 1.0f / height));
  1540. #ifdef ATOMIC_OPENGL
  1541. graphics_->SetShaderParameter(offsetsName, Vector2::ZERO);
  1542. #else
  1543. graphics_->SetShaderParameter(offsetsName, Vector2(0.5f / width, 0.5f / height));
  1544. #endif
  1545. }
  1546. graphics_->SetBlendMode(BLEND_REPLACE);
  1547. graphics_->SetDepthTest(CMP_ALWAYS);
  1548. graphics_->SetDepthWrite(false);
  1549. graphics_->SetDrawAntialiased(false);
  1550. graphics_->SetFillMode(FILL_SOLID);
  1551. graphics_->SetClipPlane(false);
  1552. graphics_->SetScissorTest(false);
  1553. graphics_->SetStencilTest(false);
  1554. DrawFullscreenQuad(false);
  1555. }
  1556. bool View::IsNecessary(const RenderPathCommand& command)
  1557. {
  1558. return command.enabled_ && command.outputNames_.Size() && (command.type_ != CMD_SCENEPASS ||
  1559. !batchQueues_[command.pass_].IsEmpty());
  1560. }
  1561. bool View::CheckViewportRead(const RenderPathCommand& command)
  1562. {
  1563. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1564. {
  1565. if (!command.textureNames_[i].Empty() && !command.textureNames_[i].Compare("viewport", false))
  1566. return true;
  1567. }
  1568. return false;
  1569. }
  1570. bool View::CheckViewportWrite(const RenderPathCommand& command)
  1571. {
  1572. for (unsigned i = 0; i < command.outputNames_.Size(); ++i)
  1573. {
  1574. if (!command.outputNames_[i].Compare("viewport", false))
  1575. return true;
  1576. }
  1577. return false;
  1578. }
  1579. bool View::CheckPingpong(unsigned index)
  1580. {
  1581. // Current command must be a viewport-reading & writing quad to begin the pingpong chain
  1582. RenderPathCommand& current = renderPath_->commands_[index];
  1583. if (current.type_ != CMD_QUAD || !CheckViewportRead(current) || !CheckViewportWrite(current))
  1584. return false;
  1585. // If there are commands other than quads that target the viewport, we must keep rendering to the final target and resolving
  1586. // to a viewport texture when necessary instead of pingponging, as a scene pass is not guaranteed to fill the entire viewport
  1587. for (unsigned i = index + 1; i < renderPath_->commands_.Size(); ++i)
  1588. {
  1589. RenderPathCommand& command = renderPath_->commands_[i];
  1590. if (!IsNecessary(command))
  1591. continue;
  1592. if (CheckViewportWrite(command))
  1593. {
  1594. if (command.type_ != CMD_QUAD)
  1595. return false;
  1596. }
  1597. }
  1598. return true;
  1599. }
  1600. void View::AllocateScreenBuffers()
  1601. {
  1602. bool needSubstitute = false;
  1603. unsigned numViewportTextures = 0;
  1604. depthOnlyDummyTexture_ = 0;
  1605. #ifdef ATOMIC_OPENGL
  1606. // Due to FBO limitations, in OpenGL deferred modes need to render to texture first and then blit to the backbuffer
  1607. // Also, if rendering to a texture with full deferred rendering, it must be RGBA to comply with the rest of the buffers.
  1608. if ((deferred_ && !renderTarget_) || (deferredAmbient_ && renderTarget_ && renderTarget_->GetParentTexture()->GetFormat() !=
  1609. Graphics::GetRGBAFormat()))
  1610. needSubstitute = true;
  1611. // Also need substitute if rendering to backbuffer using a custom (readable) depth buffer
  1612. if (!renderTarget_ && !needSubstitute)
  1613. {
  1614. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1615. {
  1616. const RenderPathCommand& command = renderPath_->commands_[i];
  1617. if (!IsNecessary(command))
  1618. continue;
  1619. if (command.depthStencilName_.Length() && command.outputNames_.Size() && !command.outputNames_[0].Compare("viewport",
  1620. false))
  1621. {
  1622. needSubstitute = true;
  1623. break;
  1624. }
  1625. }
  1626. }
  1627. #endif
  1628. // If backbuffer is antialiased when using deferred rendering, need to reserve a buffer
  1629. if (deferred_ && !renderTarget_ && graphics_->GetMultiSample() > 1)
  1630. needSubstitute = true;
  1631. // If viewport is smaller than whole texture/backbuffer in deferred rendering, need to reserve a buffer, as the G-buffer
  1632. // textures will be sized equal to the viewport
  1633. if (viewSize_.x_ < rtSize_.x_ || viewSize_.y_ < rtSize_.y_)
  1634. {
  1635. if (deferred_)
  1636. needSubstitute = true;
  1637. else if (!needSubstitute)
  1638. {
  1639. // Check also if using MRT without deferred rendering and rendering to the viewport and another texture,
  1640. // or using custom depth
  1641. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1642. {
  1643. const RenderPathCommand& command = renderPath_->commands_[i];
  1644. if (!IsNecessary(command))
  1645. continue;
  1646. if (command.depthStencilName_.Length())
  1647. needSubstitute = true;
  1648. if (!needSubstitute && command.outputNames_.Size() > 1)
  1649. {
  1650. for (unsigned j = 0; j < command.outputNames_.Size(); ++j)
  1651. {
  1652. if (!command.outputNames_[j].Compare("viewport", false))
  1653. {
  1654. needSubstitute = true;
  1655. break;
  1656. }
  1657. }
  1658. }
  1659. if (needSubstitute)
  1660. break;
  1661. }
  1662. }
  1663. }
  1664. // Follow final rendertarget format, or use RGB to match the backbuffer format
  1665. unsigned format = renderTarget_ ? renderTarget_->GetParentTexture()->GetFormat() : Graphics::GetRGBFormat();
  1666. // If HDR rendering is enabled use RGBA16f and reserve a buffer
  1667. if (renderer_->GetHDRRendering())
  1668. {
  1669. format = Graphics::GetRGBAFloat16Format();
  1670. needSubstitute = true;
  1671. }
  1672. #ifdef ATOMIC_OPENGL
  1673. if (deferred_ && !renderer_->GetHDRRendering())
  1674. format = Graphics::GetRGBAFormat();
  1675. #endif
  1676. // Check for commands which read the viewport, or pingpong between viewport textures
  1677. bool hasViewportRead = false;
  1678. bool hasPingpong = false;
  1679. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1680. {
  1681. const RenderPathCommand& command = renderPath_->commands_[i];
  1682. if (!IsNecessary(command))
  1683. continue;
  1684. if (CheckViewportRead(command))
  1685. hasViewportRead = true;
  1686. if (!hasPingpong && CheckPingpong(i))
  1687. hasPingpong = true;
  1688. }
  1689. if (hasViewportRead)
  1690. {
  1691. ++numViewportTextures;
  1692. // If OpenGL ES, use substitute target to avoid resolve from the backbuffer, which may be slow. However if multisampling
  1693. // is specified, there is no choice
  1694. #ifdef GL_ES_VERSION_2_0
  1695. if (!renderTarget_ && graphics_->GetMultiSample() < 2)
  1696. needSubstitute = true;
  1697. #endif
  1698. // If we have viewport read and target is a cube map, must allocate a substitute target instead as BlitFramebuffer()
  1699. // does not support reading a cube map
  1700. if (renderTarget_ && renderTarget_->GetParentTexture()->GetType() == TextureCube::GetTypeStatic())
  1701. needSubstitute = true;
  1702. // If rendering to a texture, but the viewport is less than the whole texture, use a substitute to ensure
  1703. // postprocessing shaders will never read outside the viewport
  1704. if (renderTarget_ && (viewSize_.x_ < renderTarget_->GetWidth() || viewSize_.y_ < renderTarget_->GetHeight()))
  1705. needSubstitute = true;
  1706. if (hasPingpong && !needSubstitute)
  1707. ++numViewportTextures;
  1708. }
  1709. // Allocate screen buffers with filtering active in case the quad commands need that
  1710. // Follow the sRGB mode of the destination render target
  1711. bool sRGB = renderTarget_ ? renderTarget_->GetParentTexture()->GetSRGB() : graphics_->GetSRGB();
  1712. substituteRenderTarget_ = needSubstitute ? renderer_->GetScreenBuffer(viewSize_.x_, viewSize_.y_, format, true,
  1713. sRGB)->GetRenderSurface() : (RenderSurface*)0;
  1714. for (unsigned i = 0; i < MAX_VIEWPORT_TEXTURES; ++i)
  1715. {
  1716. viewportTextures_[i] = i < numViewportTextures ? renderer_->GetScreenBuffer(viewSize_.x_, viewSize_.y_, format, true, sRGB) :
  1717. (Texture2D*)0;
  1718. }
  1719. // If using a substitute render target and pingponging, the substitute can act as the second viewport texture
  1720. if (numViewportTextures == 1 && substituteRenderTarget_)
  1721. viewportTextures_[1] = static_cast<Texture2D*>(substituteRenderTarget_->GetParentTexture());
  1722. // Allocate extra render targets defined by the rendering path
  1723. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1724. {
  1725. const RenderTargetInfo& rtInfo = renderPath_->renderTargets_[i];
  1726. if (!rtInfo.enabled_)
  1727. continue;
  1728. float width = rtInfo.size_.x_;
  1729. float height = rtInfo.size_.y_;
  1730. if (rtInfo.sizeMode_ == SIZE_VIEWPORTDIVISOR)
  1731. {
  1732. width = (float)viewSize_.x_ / Max(width, M_EPSILON);
  1733. height = (float)viewSize_.y_ / Max(height, M_EPSILON);
  1734. }
  1735. else if (rtInfo.sizeMode_ == SIZE_VIEWPORTMULTIPLIER)
  1736. {
  1737. width = (float)viewSize_.x_ * width;
  1738. height = (float)viewSize_.y_ * height;
  1739. }
  1740. int intWidth = (int)(width + 0.5f);
  1741. int intHeight = (int)(height + 0.5f);
  1742. // If the rendertarget is persistent, key it with a hash derived from the RT name and the view's pointer
  1743. renderTargets_[rtInfo.name_] = renderer_->GetScreenBuffer(intWidth, intHeight, rtInfo.format_, rtInfo.filtered_,
  1744. rtInfo.sRGB_, rtInfo.persistent_ ? StringHash(rtInfo.name_).Value() + (unsigned)(size_t)this : 0);
  1745. }
  1746. }
  1747. void View::BlitFramebuffer(Texture2D* source, RenderSurface* destination, bool depthWrite)
  1748. {
  1749. if (!source)
  1750. return;
  1751. PROFILE(BlitFramebuffer);
  1752. // If blitting to the destination rendertarget, use the actual viewport. Intermediate textures on the other hand
  1753. // are always viewport-sized
  1754. IntVector2 srcSize(source->GetWidth(), source->GetHeight());
  1755. IntVector2 destSize = destination ? IntVector2(destination->GetWidth(), destination->GetHeight()) : IntVector2(
  1756. graphics_->GetWidth(), graphics_->GetHeight());
  1757. IntRect srcRect = (source->GetRenderSurface() == renderTarget_) ? viewRect_ : IntRect(0, 0, srcSize.x_, srcSize.y_);
  1758. IntRect destRect = (destination == renderTarget_) ? viewRect_ : IntRect(0, 0, destSize.x_, destSize.y_);
  1759. graphics_->SetBlendMode(BLEND_REPLACE);
  1760. graphics_->SetDepthTest(CMP_ALWAYS);
  1761. graphics_->SetDepthWrite(depthWrite);
  1762. graphics_->SetFillMode(FILL_SOLID);
  1763. graphics_->SetClipPlane(false);
  1764. graphics_->SetScissorTest(false);
  1765. graphics_->SetStencilTest(false);
  1766. graphics_->SetRenderTarget(0, destination);
  1767. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  1768. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  1769. graphics_->SetDepthStencil(GetDepthStencil(destination));
  1770. graphics_->SetViewport(destRect);
  1771. static const String shaderName("CopyFramebuffer");
  1772. graphics_->SetShaders(graphics_->GetShader(VS, shaderName), graphics_->GetShader(PS, shaderName));
  1773. SetGBufferShaderParameters(srcSize, srcRect);
  1774. graphics_->SetTexture(TU_DIFFUSE, source);
  1775. DrawFullscreenQuad(false);
  1776. }
  1777. void View::DrawFullscreenQuad(bool nearQuad)
  1778. {
  1779. Geometry* geometry = renderer_->GetQuadGeometry();
  1780. Matrix3x4 model = Matrix3x4::IDENTITY;
  1781. Matrix4 projection = Matrix4::IDENTITY;
  1782. #ifdef ATOMIC_OPENGL
  1783. if (camera_ && camera_->GetFlipVertical())
  1784. projection.m11_ = -1.0f;
  1785. model.m23_ = nearQuad ? -1.0f : 1.0f;
  1786. #else
  1787. model.m23_ = nearQuad ? 0.0f : 1.0f;
  1788. #endif
  1789. graphics_->SetCullMode(CULL_NONE);
  1790. graphics_->SetShaderParameter(VSP_MODEL, model);
  1791. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1792. graphics_->ClearTransformSources();
  1793. geometry->Draw(graphics_);
  1794. }
  1795. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  1796. {
  1797. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  1798. float halfViewSize = camera->GetHalfViewSize();
  1799. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  1800. for (PODVector<Drawable*>::Iterator i = occluders.Begin(); i != occluders.End();)
  1801. {
  1802. Drawable* occluder = *i;
  1803. bool erase = false;
  1804. if (!occluder->IsInView(frame_, true))
  1805. occluder->UpdateBatches(frame_);
  1806. // Check occluder's draw distance (in main camera view)
  1807. float maxDistance = occluder->GetDrawDistance();
  1808. if (maxDistance <= 0.0f || occluder->GetDistance() <= maxDistance)
  1809. {
  1810. // Check that occluder is big enough on the screen
  1811. const BoundingBox& box = occluder->GetWorldBoundingBox();
  1812. float diagonal = box.Size().Length();
  1813. float compare;
  1814. if (!camera->IsOrthographic())
  1815. compare = diagonal * halfViewSize / occluder->GetDistance();
  1816. else
  1817. compare = diagonal * invOrthoSize;
  1818. if (compare < occluderSizeThreshold_)
  1819. erase = true;
  1820. else
  1821. {
  1822. // Store amount of triangles divided by screen size as a sorting key
  1823. // (best occluders are big and have few triangles)
  1824. occluder->SetSortValue((float)occluder->GetNumOccluderTriangles() / compare);
  1825. }
  1826. }
  1827. else
  1828. erase = true;
  1829. if (erase)
  1830. i = occluders.Erase(i);
  1831. else
  1832. ++i;
  1833. }
  1834. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  1835. if (occluders.Size())
  1836. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  1837. }
  1838. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  1839. {
  1840. buffer->SetMaxTriangles(maxOccluderTriangles_);
  1841. buffer->Clear();
  1842. for (unsigned i = 0; i < occluders.Size(); ++i)
  1843. {
  1844. Drawable* occluder = occluders[i];
  1845. if (i > 0)
  1846. {
  1847. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  1848. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  1849. continue;
  1850. }
  1851. // Check for running out of triangles
  1852. if (!occluder->DrawOcclusion(buffer))
  1853. break;
  1854. }
  1855. buffer->BuildDepthHierarchy();
  1856. }
  1857. void View::ProcessLight(LightQueryResult& query, unsigned threadIndex)
  1858. {
  1859. Light* light = query.light_;
  1860. LightType type = light->GetLightType();
  1861. const Frustum& frustum = camera_->GetFrustum();
  1862. // Check if light should be shadowed
  1863. bool isShadowed = drawShadows_ && light->GetCastShadows() && !light->GetPerVertex() && light->GetShadowIntensity() < 1.0f;
  1864. // If shadow distance non-zero, check it
  1865. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  1866. isShadowed = false;
  1867. // OpenGL ES can not support point light shadows
  1868. #ifdef GL_ES_VERSION_2_0
  1869. if (isShadowed && type == LIGHT_POINT)
  1870. isShadowed = false;
  1871. #endif
  1872. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  1873. PODVector<Drawable*>& tempDrawables = tempDrawables_[threadIndex];
  1874. query.litGeometries_.Clear();
  1875. switch (type)
  1876. {
  1877. case LIGHT_DIRECTIONAL:
  1878. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1879. {
  1880. if (GetLightMask(geometries_[i]) & light->GetLightMask())
  1881. query.litGeometries_.Push(geometries_[i]);
  1882. }
  1883. break;
  1884. case LIGHT_SPOT:
  1885. {
  1886. FrustumOctreeQuery octreeQuery(tempDrawables, light->GetFrustum(), DRAWABLE_GEOMETRY,
  1887. camera_->GetViewMask());
  1888. octree_->GetDrawables(octreeQuery);
  1889. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1890. {
  1891. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1892. query.litGeometries_.Push(tempDrawables[i]);
  1893. }
  1894. }
  1895. break;
  1896. case LIGHT_POINT:
  1897. {
  1898. SphereOctreeQuery octreeQuery(tempDrawables, Sphere(light->GetNode()->GetWorldPosition(), light->GetRange()),
  1899. DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1900. octree_->GetDrawables(octreeQuery);
  1901. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1902. {
  1903. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1904. query.litGeometries_.Push(tempDrawables[i]);
  1905. }
  1906. }
  1907. break;
  1908. }
  1909. // If no lit geometries or not shadowed, no need to process shadow cameras
  1910. if (query.litGeometries_.Empty() || !isShadowed)
  1911. {
  1912. query.numSplits_ = 0;
  1913. return;
  1914. }
  1915. // Determine number of shadow cameras and setup their initial positions
  1916. SetupShadowCameras(query);
  1917. // Process each split for shadow casters
  1918. query.shadowCasters_.Clear();
  1919. for (unsigned i = 0; i < query.numSplits_; ++i)
  1920. {
  1921. Camera* shadowCamera = query.shadowCameras_[i];
  1922. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1923. query.shadowCasterBegin_[i] = query.shadowCasterEnd_[i] = query.shadowCasters_.Size();
  1924. // For point light check that the face is visible: if not, can skip the split
  1925. if (type == LIGHT_POINT && frustum.IsInsideFast(BoundingBox(shadowCameraFrustum)) == OUTSIDE)
  1926. continue;
  1927. // For directional light check that the split is inside the visible scene: if not, can skip the split
  1928. if (type == LIGHT_DIRECTIONAL)
  1929. {
  1930. if (minZ_ > query.shadowFarSplits_[i])
  1931. continue;
  1932. if (maxZ_ < query.shadowNearSplits_[i])
  1933. continue;
  1934. // Reuse lit geometry query for all except directional lights
  1935. ShadowCasterOctreeQuery query(tempDrawables, shadowCameraFrustum, DRAWABLE_GEOMETRY,
  1936. camera_->GetViewMask());
  1937. octree_->GetDrawables(query);
  1938. }
  1939. // Check which shadow casters actually contribute to the shadowing
  1940. ProcessShadowCasters(query, tempDrawables, i);
  1941. }
  1942. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  1943. // only cost has been the shadow camera setup & queries
  1944. if (query.shadowCasters_.Empty())
  1945. query.numSplits_ = 0;
  1946. }
  1947. void View::ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex)
  1948. {
  1949. Light* light = query.light_;
  1950. Camera* shadowCamera = query.shadowCameras_[splitIndex];
  1951. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1952. const Matrix3x4& lightView = shadowCamera->GetView();
  1953. const Matrix4& lightProj = shadowCamera->GetProjection();
  1954. LightType type = light->GetLightType();
  1955. query.shadowCasterBox_[splitIndex].defined_ = false;
  1956. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  1957. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  1958. // frustum, so that shadow casters do not get rendered into unnecessary splits
  1959. Frustum lightViewFrustum;
  1960. if (type != LIGHT_DIRECTIONAL)
  1961. lightViewFrustum = camera_->GetSplitFrustum(minZ_, maxZ_).Transformed(lightView);
  1962. else
  1963. lightViewFrustum = camera_->GetSplitFrustum(Max(minZ_, query.shadowNearSplits_[splitIndex]),
  1964. Min(maxZ_, query.shadowFarSplits_[splitIndex])).Transformed(lightView);
  1965. BoundingBox lightViewFrustumBox(lightViewFrustum);
  1966. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1967. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1968. return;
  1969. BoundingBox lightViewBox;
  1970. BoundingBox lightProjBox;
  1971. for (PODVector<Drawable*>::ConstIterator i = drawables.Begin(); i != drawables.End(); ++i)
  1972. {
  1973. Drawable* drawable = *i;
  1974. // In case this is a point or spot light query result reused for optimization, we may have non-shadowcasters included.
  1975. // Check for that first
  1976. if (!drawable->GetCastShadows())
  1977. continue;
  1978. // Check shadow mask
  1979. if (!(GetShadowMask(drawable) & light->GetLightMask()))
  1980. continue;
  1981. // For point light, check that this drawable is inside the split shadow camera frustum
  1982. if (type == LIGHT_POINT && shadowCameraFrustum.IsInsideFast(drawable->GetWorldBoundingBox()) == OUTSIDE)
  1983. continue;
  1984. // Check shadow distance
  1985. float maxShadowDistance = drawable->GetShadowDistance();
  1986. float drawDistance = drawable->GetDrawDistance();
  1987. bool batchesUpdated = drawable->IsInView(frame_, true);
  1988. if (drawDistance > 0.0f && (maxShadowDistance <= 0.0f || drawDistance < maxShadowDistance))
  1989. maxShadowDistance = drawDistance;
  1990. if (maxShadowDistance > 0.0f)
  1991. {
  1992. if (!batchesUpdated)
  1993. {
  1994. drawable->UpdateBatches(frame_);
  1995. batchesUpdated = true;
  1996. }
  1997. if (drawable->GetDistance() > maxShadowDistance)
  1998. continue;
  1999. }
  2000. // Note: as lights are processed threaded, it is possible a drawable's UpdateBatches() function is called several
  2001. // times. However, this should not cause problems as no scene modification happens at this point.
  2002. if (!batchesUpdated)
  2003. drawable->UpdateBatches(frame_);
  2004. // Project shadow caster bounding box to light view space for visibility check
  2005. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  2006. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  2007. {
  2008. // Merge to shadow caster bounding box and add to the list
  2009. if (type == LIGHT_DIRECTIONAL)
  2010. query.shadowCasterBox_[splitIndex].Merge(lightViewBox);
  2011. else
  2012. {
  2013. lightProjBox = lightViewBox.Projected(lightProj);
  2014. query.shadowCasterBox_[splitIndex].Merge(lightProjBox);
  2015. }
  2016. query.shadowCasters_.Push(drawable);
  2017. }
  2018. }
  2019. query.shadowCasterEnd_[splitIndex] = query.shadowCasters_.Size();
  2020. }
  2021. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  2022. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  2023. {
  2024. if (shadowCamera->IsOrthographic())
  2025. {
  2026. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  2027. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  2028. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  2029. }
  2030. else
  2031. {
  2032. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  2033. if (drawable->IsInView(frame_))
  2034. return true;
  2035. // For perspective lights, extrusion direction depends on the position of the shadow caster
  2036. Vector3 center = lightViewBox.Center();
  2037. Ray extrusionRay(center, center);
  2038. float extrusionDistance = shadowCamera->GetFarClip();
  2039. float originalDistance = Clamp(center.Length(), M_EPSILON, extrusionDistance);
  2040. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  2041. float sizeFactor = extrusionDistance / originalDistance;
  2042. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  2043. // than necessary, so the test will be conservative
  2044. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  2045. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  2046. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  2047. lightViewBox.Merge(extrudedBox);
  2048. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  2049. }
  2050. }
  2051. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  2052. {
  2053. unsigned width = shadowMap->GetWidth();
  2054. unsigned height = shadowMap->GetHeight();
  2055. switch (light->GetLightType())
  2056. {
  2057. case LIGHT_DIRECTIONAL:
  2058. {
  2059. int numSplits = light->GetNumShadowSplits();
  2060. if (numSplits == 1)
  2061. return IntRect(0, 0, width, height);
  2062. else if (numSplits == 2)
  2063. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  2064. else
  2065. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  2066. (splitIndex / 2 + 1) * height / 2);
  2067. }
  2068. case LIGHT_SPOT:
  2069. return IntRect(0, 0, width, height);
  2070. case LIGHT_POINT:
  2071. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  2072. (splitIndex / 2 + 1) * height / 3);
  2073. }
  2074. return IntRect();
  2075. }
  2076. void View::SetupShadowCameras(LightQueryResult& query)
  2077. {
  2078. Light* light = query.light_;
  2079. int splits = 0;
  2080. switch (light->GetLightType())
  2081. {
  2082. case LIGHT_DIRECTIONAL:
  2083. {
  2084. const CascadeParameters& cascade = light->GetShadowCascade();
  2085. float nearSplit = camera_->GetNearClip();
  2086. float farSplit;
  2087. int numSplits = light->GetNumShadowSplits();
  2088. while (splits < numSplits)
  2089. {
  2090. // If split is completely beyond camera far clip, we are done
  2091. if (nearSplit > camera_->GetFarClip())
  2092. break;
  2093. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  2094. if (farSplit <= nearSplit)
  2095. break;
  2096. // Setup the shadow camera for the split
  2097. Camera* shadowCamera = renderer_->GetShadowCamera();
  2098. query.shadowCameras_[splits] = shadowCamera;
  2099. query.shadowNearSplits_[splits] = nearSplit;
  2100. query.shadowFarSplits_[splits] = farSplit;
  2101. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit);
  2102. nearSplit = farSplit;
  2103. ++splits;
  2104. }
  2105. }
  2106. break;
  2107. case LIGHT_SPOT:
  2108. {
  2109. Camera* shadowCamera = renderer_->GetShadowCamera();
  2110. query.shadowCameras_[0] = shadowCamera;
  2111. Node* cameraNode = shadowCamera->GetNode();
  2112. Node* lightNode = light->GetNode();
  2113. cameraNode->SetTransform(lightNode->GetWorldPosition(), lightNode->GetWorldRotation());
  2114. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  2115. shadowCamera->SetFarClip(light->GetRange());
  2116. shadowCamera->SetFov(light->GetFov());
  2117. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  2118. splits = 1;
  2119. }
  2120. break;
  2121. case LIGHT_POINT:
  2122. {
  2123. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  2124. {
  2125. Camera* shadowCamera = renderer_->GetShadowCamera();
  2126. query.shadowCameras_[i] = shadowCamera;
  2127. Node* cameraNode = shadowCamera->GetNode();
  2128. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  2129. cameraNode->SetPosition(light->GetNode()->GetWorldPosition());
  2130. cameraNode->SetDirection(*directions[i]);
  2131. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  2132. shadowCamera->SetFarClip(light->GetRange());
  2133. shadowCamera->SetFov(90.0f);
  2134. shadowCamera->SetAspectRatio(1.0f);
  2135. }
  2136. splits = MAX_CUBEMAP_FACES;
  2137. }
  2138. break;
  2139. }
  2140. query.numSplits_ = splits;
  2141. }
  2142. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit)
  2143. {
  2144. Node* shadowCameraNode = shadowCamera->GetNode();
  2145. Node* lightNode = light->GetNode();
  2146. float extrusionDistance = camera_->GetFarClip();
  2147. const FocusParameters& parameters = light->GetShadowFocus();
  2148. // Calculate initial position & rotation
  2149. Vector3 pos = cameraNode_->GetWorldPosition() - extrusionDistance * lightNode->GetWorldDirection();
  2150. shadowCameraNode->SetTransform(pos, lightNode->GetWorldRotation());
  2151. // Calculate main camera shadowed frustum in light's view space
  2152. farSplit = Min(farSplit, camera_->GetFarClip());
  2153. // Use the scene Z bounds to limit frustum size if applicable
  2154. if (parameters.focus_)
  2155. {
  2156. nearSplit = Max(minZ_, nearSplit);
  2157. farSplit = Min(maxZ_, farSplit);
  2158. }
  2159. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  2160. Polyhedron frustumVolume;
  2161. frustumVolume.Define(splitFrustum);
  2162. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  2163. if (parameters.focus_)
  2164. {
  2165. BoundingBox litGeometriesBox;
  2166. for (unsigned i = 0; i < geometries_.Size(); ++i)
  2167. {
  2168. Drawable* drawable = geometries_[i];
  2169. #ifdef ATOMIC_3D
  2170. // Skip skyboxes as they have undefinedly large bounding box size
  2171. if (drawable->GetType() == Skybox::GetTypeStatic())
  2172. continue;
  2173. #endif
  2174. if (drawable->GetMinZ() <= farSplit && drawable->GetMaxZ() >= nearSplit &&
  2175. (GetLightMask(drawable) & light->GetLightMask()))
  2176. litGeometriesBox.Merge(drawable->GetWorldBoundingBox());
  2177. }
  2178. if (litGeometriesBox.defined_)
  2179. {
  2180. frustumVolume.Clip(litGeometriesBox);
  2181. // If volume became empty, restore it to avoid zero size
  2182. if (frustumVolume.Empty())
  2183. frustumVolume.Define(splitFrustum);
  2184. }
  2185. }
  2186. // Transform frustum volume to light space
  2187. const Matrix3x4& lightView = shadowCamera->GetView();
  2188. frustumVolume.Transform(lightView);
  2189. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  2190. BoundingBox shadowBox;
  2191. if (!parameters.nonUniform_)
  2192. shadowBox.Define(Sphere(frustumVolume));
  2193. else
  2194. shadowBox.Define(frustumVolume);
  2195. shadowCamera->SetOrthographic(true);
  2196. shadowCamera->SetAspectRatio(1.0f);
  2197. shadowCamera->SetNearClip(0.0f);
  2198. shadowCamera->SetFarClip(shadowBox.max_.z_);
  2199. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  2200. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  2201. }
  2202. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  2203. const BoundingBox& shadowCasterBox)
  2204. {
  2205. const FocusParameters& parameters = light->GetShadowFocus();
  2206. float shadowMapWidth = (float)(shadowViewport.Width());
  2207. LightType type = light->GetLightType();
  2208. if (type == LIGHT_DIRECTIONAL)
  2209. {
  2210. BoundingBox shadowBox;
  2211. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  2212. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  2213. shadowBox.min_.y_ = -shadowBox.max_.y_;
  2214. shadowBox.min_.x_ = -shadowBox.max_.x_;
  2215. // Requantize and snap to shadow map texels
  2216. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  2217. }
  2218. if (type == LIGHT_SPOT)
  2219. {
  2220. if (parameters.focus_)
  2221. {
  2222. float viewSizeX = Max(Abs(shadowCasterBox.min_.x_), Abs(shadowCasterBox.max_.x_));
  2223. float viewSizeY = Max(Abs(shadowCasterBox.min_.y_), Abs(shadowCasterBox.max_.y_));
  2224. float viewSize = Max(viewSizeX, viewSizeY);
  2225. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  2226. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  2227. float quantize = parameters.quantize_ * invOrthoSize;
  2228. float minView = parameters.minView_ * invOrthoSize;
  2229. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  2230. if (viewSize < 1.0f)
  2231. shadowCamera->SetZoom(1.0f / viewSize);
  2232. }
  2233. }
  2234. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  2235. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  2236. if (shadowCamera->GetZoom() >= 1.0f)
  2237. {
  2238. if (light->GetLightType() != LIGHT_POINT)
  2239. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  2240. else
  2241. {
  2242. #ifdef ATOMIC_OPENGL
  2243. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  2244. #else
  2245. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  2246. #endif
  2247. }
  2248. }
  2249. }
  2250. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  2251. const BoundingBox& viewBox)
  2252. {
  2253. Node* shadowCameraNode = shadowCamera->GetNode();
  2254. const FocusParameters& parameters = light->GetShadowFocus();
  2255. float shadowMapWidth = (float)(shadowViewport.Width());
  2256. float minX = viewBox.min_.x_;
  2257. float minY = viewBox.min_.y_;
  2258. float maxX = viewBox.max_.x_;
  2259. float maxY = viewBox.max_.y_;
  2260. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  2261. Vector2 viewSize(maxX - minX, maxY - minY);
  2262. // Quantize size to reduce swimming
  2263. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  2264. if (parameters.nonUniform_)
  2265. {
  2266. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  2267. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  2268. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  2269. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  2270. }
  2271. else if (parameters.focus_)
  2272. {
  2273. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  2274. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  2275. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  2276. viewSize.y_ = viewSize.x_;
  2277. }
  2278. shadowCamera->SetOrthoSize(viewSize);
  2279. // Center shadow camera to the view space bounding box
  2280. Quaternion rot(shadowCameraNode->GetWorldRotation());
  2281. Vector3 adjust(center.x_, center.y_, 0.0f);
  2282. shadowCameraNode->Translate(rot * adjust, TS_WORLD);
  2283. // If the shadow map viewport is known, snap to whole texels
  2284. if (shadowMapWidth > 0.0f)
  2285. {
  2286. Vector3 viewPos(rot.Inverse() * shadowCameraNode->GetWorldPosition());
  2287. // Take into account that shadow map border will not be used
  2288. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  2289. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  2290. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  2291. shadowCameraNode->Translate(rot * snap, TS_WORLD);
  2292. }
  2293. }
  2294. void View::FindZone(Drawable* drawable)
  2295. {
  2296. Vector3 center = drawable->GetWorldBoundingBox().Center();
  2297. int bestPriority = M_MIN_INT;
  2298. Zone* newZone = 0;
  2299. // If bounding box center is in view, the zone assignment is conclusive also for next frames. Otherwise it is temporary
  2300. // (possibly incorrect) and must be re-evaluated on the next frame
  2301. bool temporary = !camera_->GetFrustum().IsInside(center);
  2302. // First check if the current zone remains a conclusive result
  2303. Zone* lastZone = drawable->GetZone();
  2304. if (lastZone && (lastZone->GetViewMask() & camera_->GetViewMask()) && lastZone->GetPriority() >= highestZonePriority_ &&
  2305. (drawable->GetZoneMask() & lastZone->GetZoneMask()) && lastZone->IsInside(center))
  2306. newZone = lastZone;
  2307. else
  2308. {
  2309. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  2310. {
  2311. Zone* zone = *i;
  2312. int priority = zone->GetPriority();
  2313. if (priority > bestPriority && (drawable->GetZoneMask() & zone->GetZoneMask()) && zone->IsInside(center))
  2314. {
  2315. newZone = zone;
  2316. bestPriority = priority;
  2317. }
  2318. }
  2319. }
  2320. drawable->SetZone(newZone, temporary);
  2321. }
  2322. Technique* View::GetTechnique(Drawable* drawable, Material* material)
  2323. {
  2324. if (!material)
  2325. {
  2326. const Vector<TechniqueEntry>& techniques = renderer_->GetDefaultMaterial()->GetTechniques();
  2327. return techniques.Size() ? techniques[0].technique_ : (Technique*)0;
  2328. }
  2329. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  2330. // If only one technique, no choice
  2331. if (techniques.Size() == 1)
  2332. return techniques[0].technique_;
  2333. else
  2334. {
  2335. float lodDistance = drawable->GetLodDistance();
  2336. // Check for suitable technique. Techniques should be ordered like this:
  2337. // Most distant & highest quality
  2338. // Most distant & lowest quality
  2339. // Second most distant & highest quality
  2340. // ...
  2341. for (unsigned i = 0; i < techniques.Size(); ++i)
  2342. {
  2343. const TechniqueEntry& entry = techniques[i];
  2344. Technique* tech = entry.technique_;
  2345. if (!tech || (!tech->IsSupported()) || materialQuality_ < entry.qualityLevel_)
  2346. continue;
  2347. if (lodDistance >= entry.lodDistance_)
  2348. return tech;
  2349. }
  2350. // If no suitable technique found, fallback to the last
  2351. return techniques.Size() ? techniques.Back().technique_ : (Technique*)0;
  2352. }
  2353. }
  2354. void View::CheckMaterialForAuxView(Material* material)
  2355. {
  2356. const SharedPtr<Texture>* textures = material->GetTextures();
  2357. unsigned numTextures = material->GetNumUsedTextureUnits();
  2358. for (unsigned i = 0; i < numTextures; ++i)
  2359. {
  2360. Texture* texture = textures[i];
  2361. if (texture && texture->GetUsage() == TEXTURE_RENDERTARGET)
  2362. {
  2363. // Have to check cube & 2D textures separately
  2364. if (texture->GetType() == Texture2D::GetTypeStatic())
  2365. {
  2366. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  2367. RenderSurface* target = tex2D->GetRenderSurface();
  2368. if (target && target->GetUpdateMode() == SURFACE_UPDATEVISIBLE)
  2369. target->QueueUpdate();
  2370. }
  2371. else if (texture->GetType() == TextureCube::GetTypeStatic())
  2372. {
  2373. TextureCube* texCube = static_cast<TextureCube*>(texture);
  2374. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  2375. {
  2376. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  2377. if (target && target->GetUpdateMode() == SURFACE_UPDATEVISIBLE)
  2378. target->QueueUpdate();
  2379. }
  2380. }
  2381. }
  2382. }
  2383. // Flag as processed so we can early-out next time we come across this material on the same frame
  2384. material->MarkForAuxView(frame_.frameNumber_);
  2385. }
  2386. void View::AddBatchToQueue(BatchQueue& batchQueue, Batch& batch, Technique* tech, bool allowInstancing, bool allowShadows)
  2387. {
  2388. if (!batch.material_)
  2389. batch.material_ = renderer_->GetDefaultMaterial();
  2390. // Convert to instanced if possible
  2391. if (allowInstancing && batch.geometryType_ == GEOM_STATIC && batch.geometry_->GetIndexBuffer())
  2392. batch.geometryType_ = GEOM_INSTANCED;
  2393. if (batch.geometryType_ == GEOM_INSTANCED)
  2394. {
  2395. BatchGroupKey key(batch);
  2396. HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchQueue.batchGroups_.Find(key);
  2397. if (i == batchQueue.batchGroups_.End())
  2398. {
  2399. // Create a new group based on the batch
  2400. // In case the group remains below the instancing limit, do not enable instancing shaders yet
  2401. BatchGroup newGroup(batch);
  2402. newGroup.geometryType_ = GEOM_STATIC;
  2403. renderer_->SetBatchShaders(newGroup, tech, allowShadows);
  2404. newGroup.CalculateSortKey();
  2405. i = batchQueue.batchGroups_.Insert(MakePair(key, newGroup));
  2406. }
  2407. int oldSize = i->second_.instances_.Size();
  2408. i->second_.AddTransforms(batch);
  2409. // Convert to using instancing shaders when the instancing limit is reached
  2410. if (oldSize < minInstances_ && (int)i->second_.instances_.Size() >= minInstances_)
  2411. {
  2412. i->second_.geometryType_ = GEOM_INSTANCED;
  2413. renderer_->SetBatchShaders(i->second_, tech, allowShadows);
  2414. i->second_.CalculateSortKey();
  2415. }
  2416. }
  2417. else
  2418. {
  2419. renderer_->SetBatchShaders(batch, tech, allowShadows);
  2420. batch.CalculateSortKey();
  2421. // If batch is static with multiple world transforms and cannot instance, we must push copies of the batch individually
  2422. if (batch.geometryType_ == GEOM_STATIC && batch.numWorldTransforms_ > 1)
  2423. {
  2424. unsigned numTransforms = batch.numWorldTransforms_;
  2425. batch.numWorldTransforms_ = 1;
  2426. for (unsigned i = 0; i < numTransforms; ++i)
  2427. {
  2428. // Move the transform pointer to generate copies of the batch which only refer to 1 world transform
  2429. batchQueue.batches_.Push(batch);
  2430. ++batch.worldTransform_;
  2431. }
  2432. }
  2433. else
  2434. batchQueue.batches_.Push(batch);
  2435. }
  2436. }
  2437. void View::PrepareInstancingBuffer()
  2438. {
  2439. PROFILE(PrepareInstancingBuffer);
  2440. unsigned totalInstances = 0;
  2441. for (HashMap<StringHash, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  2442. totalInstances += i->second_.GetNumInstances();
  2443. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2444. {
  2445. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2446. totalInstances += i->shadowSplits_[j].shadowBatches_.GetNumInstances();
  2447. totalInstances += i->litBaseBatches_.GetNumInstances();
  2448. totalInstances += i->litBatches_.GetNumInstances();
  2449. }
  2450. // If fail to set buffer size, fall back to per-group locking
  2451. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  2452. {
  2453. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  2454. unsigned freeIndex = 0;
  2455. void* dest = instancingBuffer->Lock(0, totalInstances, true);
  2456. if (!dest)
  2457. return;
  2458. for (HashMap<StringHash, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  2459. i->second_.SetTransforms(dest, freeIndex);
  2460. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2461. {
  2462. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2463. i->shadowSplits_[j].shadowBatches_.SetTransforms(dest, freeIndex);
  2464. i->litBaseBatches_.SetTransforms(dest, freeIndex);
  2465. i->litBatches_.SetTransforms(dest, freeIndex);
  2466. }
  2467. instancingBuffer->Unlock();
  2468. }
  2469. }
  2470. void View::SetupLightVolumeBatch(Batch& batch)
  2471. {
  2472. Light* light = batch.lightQueue_->light_;
  2473. LightType type = light->GetLightType();
  2474. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  2475. float lightDist;
  2476. graphics_->SetBlendMode(light->IsNegative() ? BLEND_SUBTRACT : BLEND_ADD);
  2477. graphics_->SetDepthBias(0.0f, 0.0f);
  2478. graphics_->SetDepthWrite(false);
  2479. graphics_->SetFillMode(FILL_SOLID);
  2480. graphics_->SetClipPlane(false);
  2481. if (type != LIGHT_DIRECTIONAL)
  2482. {
  2483. if (type == LIGHT_POINT)
  2484. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  2485. else
  2486. lightDist = light->GetFrustum().Distance(cameraPos);
  2487. // Draw front faces if not inside light volume
  2488. if (lightDist < camera_->GetNearClip() * 2.0f)
  2489. {
  2490. renderer_->SetCullMode(CULL_CW, camera_);
  2491. graphics_->SetDepthTest(CMP_GREATER);
  2492. }
  2493. else
  2494. {
  2495. renderer_->SetCullMode(CULL_CCW, camera_);
  2496. graphics_->SetDepthTest(CMP_LESSEQUAL);
  2497. }
  2498. }
  2499. else
  2500. {
  2501. // In case the same camera is used for multiple views with differing aspect ratios (not recommended)
  2502. // refresh the directional light's model transform before rendering
  2503. light->GetVolumeTransform(camera_);
  2504. graphics_->SetCullMode(CULL_NONE);
  2505. graphics_->SetDepthTest(CMP_ALWAYS);
  2506. }
  2507. graphics_->SetScissorTest(false);
  2508. if (!noStencil_)
  2509. graphics_->SetStencilTest(true, CMP_NOTEQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 0, light->GetLightMask());
  2510. else
  2511. graphics_->SetStencilTest(false);
  2512. }
  2513. void View::RenderShadowMap(const LightBatchQueue& queue)
  2514. {
  2515. PROFILE(RenderShadowMap);
  2516. Texture2D* shadowMap = queue.shadowMap_;
  2517. graphics_->SetTexture(TU_SHADOWMAP, 0);
  2518. graphics_->SetColorWrite(false);
  2519. graphics_->SetDrawAntialiased(true);
  2520. graphics_->SetFillMode(FILL_SOLID);
  2521. graphics_->SetClipPlane(false);
  2522. graphics_->SetStencilTest(false);
  2523. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  2524. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  2525. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  2526. graphics_->SetDepthStencil(shadowMap);
  2527. graphics_->SetViewport(IntRect(0, 0, shadowMap->GetWidth(), shadowMap->GetHeight()));
  2528. graphics_->Clear(CLEAR_DEPTH);
  2529. // Set shadow depth bias
  2530. const BiasParameters& parameters = queue.light_->GetShadowBias();
  2531. // Render each of the splits
  2532. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  2533. {
  2534. float multiplier = 1.0f;
  2535. // For directional light cascade splits, adjust depth bias according to the far clip ratio of the splits
  2536. if (i > 0 && queue.light_->GetLightType() == LIGHT_DIRECTIONAL)
  2537. {
  2538. multiplier = Max(queue.shadowSplits_[i].shadowCamera_->GetFarClip() / queue.shadowSplits_[0].shadowCamera_->GetFarClip(), 1.0f);
  2539. multiplier = 1.0f + (multiplier - 1.0f) * queue.light_->GetShadowCascade().biasAutoAdjust_;
  2540. }
  2541. // Perform further modification of depth bias on OpenGL ES, as shadow calculations' precision is limited
  2542. float addition = 0.0f;
  2543. #ifdef GL_ES_VERSION_2_0
  2544. multiplier *= renderer_->GetMobileShadowBiasMul();
  2545. addition = renderer_->GetMobileShadowBiasAdd();
  2546. #endif
  2547. graphics_->SetDepthBias(multiplier * parameters.constantBias_ + addition, multiplier * parameters.slopeScaledBias_);
  2548. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  2549. if (!shadowQueue.shadowBatches_.IsEmpty())
  2550. {
  2551. graphics_->SetViewport(shadowQueue.shadowViewport_);
  2552. shadowQueue.shadowBatches_.Draw(this, false, false, true);
  2553. }
  2554. }
  2555. graphics_->SetColorWrite(true);
  2556. graphics_->SetDepthBias(0.0f, 0.0f);
  2557. }
  2558. RenderSurface* View::GetDepthStencil(RenderSurface* renderTarget)
  2559. {
  2560. // If using the backbuffer, return the backbuffer depth-stencil
  2561. if (!renderTarget)
  2562. return 0;
  2563. // Then check for linked depth-stencil
  2564. RenderSurface* depthStencil = renderTarget->GetLinkedDepthStencil();
  2565. // Finally get one from Renderer
  2566. if (!depthStencil)
  2567. depthStencil = renderer_->GetDepthStencil(renderTarget->GetWidth(), renderTarget->GetHeight());
  2568. return depthStencil;
  2569. }
  2570. }