View.cpp 101 KB

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