View.cpp 100 KB

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