View.cpp 98 KB

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