View.cpp 90 KB

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