View.cpp 94 KB

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