View.cpp 111 KB

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