View.cpp 90 KB

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