View.cpp 99 KB

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