View.cpp 102 KB

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