2
0

View.cpp 108 KB

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