View.cpp 100 KB

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