View.cpp 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "DebugRenderer.h"
  26. #include "Geometry.h"
  27. #include "Graphics.h"
  28. #include "Light.h"
  29. #include "Log.h"
  30. #include "Material.h"
  31. #include "OcclusionBuffer.h"
  32. #include "Octree.h"
  33. #include "OctreeQuery.h"
  34. #include "Renderer.h"
  35. #include "Profiler.h"
  36. #include "Scene.h"
  37. #include "ShaderVariation.h"
  38. #include "Technique.h"
  39. #include "Texture2D.h"
  40. #include "TextureCube.h"
  41. #include "Time.h"
  42. #include "VertexBuffer.h"
  43. #include "View.h"
  44. #include "Zone.h"
  45. #include "DebugNew.h"
  46. static const String aaVariation[] = {
  47. "",
  48. "Ortho"
  49. };
  50. static const Vector3 directions[] =
  51. {
  52. Vector3::RIGHT,
  53. Vector3::LEFT,
  54. Vector3::UP,
  55. Vector3::DOWN,
  56. Vector3::FORWARD,
  57. Vector3::BACK,
  58. };
  59. OBJECTTYPESTATIC(View);
  60. View::View(Context* context) :
  61. Object(context),
  62. graphics_(GetSubsystem<Graphics>()),
  63. renderer_(GetSubsystem<Renderer>()),
  64. octree_(0),
  65. camera_(0),
  66. zone_(0),
  67. renderTarget_(0),
  68. depthStencil_(0),
  69. jitterCounter_(0)
  70. {
  71. frame_.camera_ = 0;
  72. }
  73. View::~View()
  74. {
  75. }
  76. bool View::Define(RenderSurface* renderTarget, const Viewport& viewport)
  77. {
  78. if ((!viewport.scene_) || (!viewport.camera_))
  79. return false;
  80. // If scene is loading asynchronously, it is incomplete and should not be rendered
  81. if (viewport.scene_->IsAsyncLoading())
  82. return false;
  83. Octree* octree = viewport.scene_->GetComponent<Octree>();
  84. if (!octree)
  85. return false;
  86. mode_ = graphics_->GetRenderMode();
  87. // In deferred mode, check for the render texture being too large
  88. if ((mode_ != RENDER_FORWARD) && (renderTarget))
  89. {
  90. if ((renderTarget->GetWidth() > graphics_->GetWidth()) || (renderTarget->GetHeight() > graphics_->GetHeight()))
  91. {
  92. // Display message only once per rendertarget, do not spam each frame
  93. if (gBufferErrorDisplayed_.Find(renderTarget) == gBufferErrorDisplayed_.End())
  94. {
  95. gBufferErrorDisplayed_.Insert(renderTarget);
  96. LOGERROR("Render texture is larger than the G-buffer, can not render");
  97. }
  98. return false;
  99. }
  100. }
  101. octree_ = octree;
  102. camera_ = viewport.camera_;
  103. renderTarget_ = renderTarget;
  104. if (!renderTarget)
  105. depthStencil_ = 0;
  106. else
  107. depthStencil_ = renderTarget->GetLinkedDepthBuffer();
  108. zone_ = renderer_->GetDefaultZone();
  109. // Validate the rect and calculate size. If zero rect, use whole render target size
  110. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  111. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  112. if (viewport.rect_ != IntRect::ZERO)
  113. {
  114. screenRect_.left_ = Clamp(viewport.rect_.left_, 0, rtWidth - 1);
  115. screenRect_.top_ = Clamp(viewport.rect_.top_, 0, rtHeight - 1);
  116. screenRect_.right_ = Clamp(viewport.rect_.right_, screenRect_.left_ + 1, rtWidth);
  117. screenRect_.bottom_ = Clamp(viewport.rect_.bottom_, screenRect_.top_ + 1, rtHeight);
  118. }
  119. else
  120. screenRect_ = IntRect(0, 0, rtWidth, rtHeight);
  121. width_ = screenRect_.right_ - screenRect_.left_;
  122. height_ = screenRect_.bottom_ - screenRect_.top_;
  123. // Set possible quality overrides from the camera
  124. drawShadows_ = renderer_->GetDrawShadows();
  125. materialQuality_ = renderer_->GetMaterialQuality();
  126. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  127. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  128. if (viewOverrideFlags & VOF_LOW_MATERIAL_QUALITY)
  129. materialQuality_ = QUALITY_LOW;
  130. if (viewOverrideFlags & VOF_DISABLE_SHADOWS)
  131. drawShadows_ = false;
  132. if (viewOverrideFlags & VOF_DISABLE_OCCLUSION)
  133. maxOccluderTriangles_ = 0;
  134. return true;
  135. }
  136. void View::Update(const FrameInfo& frame)
  137. {
  138. if ((!camera_) || (!octree_))
  139. return;
  140. frame_.camera_ = camera_;
  141. frame_.timeStep_ = frame.timeStep_;
  142. frame_.frameNumber_ = frame.frameNumber_;
  143. frame_.viewSize_ = IntVector2(width_, height_);
  144. // Clear old light scissor cache, geometry, light, occluder & batch lists
  145. lightScissorCache_.Clear();
  146. geometries_.Clear();
  147. geometryDepthBounds_.Clear();
  148. lights_.Clear();
  149. occluders_.Clear();
  150. shadowOccluders_.Clear();
  151. gBufferQueue_.Clear();
  152. baseQueue_.Clear();
  153. extraQueue_.Clear();
  154. transparentQueue_.Clear();
  155. noShadowLightQueue_.Clear();
  156. lightQueues_.Clear();
  157. // Set automatic aspect ratio if required
  158. if (camera_->GetAutoAspectRatio())
  159. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  160. // Reset projection jitter if was used last frame
  161. camera_->SetProjectionOffset(Vector2::ZERO);
  162. // Reset shadow map use count; they can be reused between views as each is rendered completely at a time
  163. renderer_->ResetShadowMapUseCount();
  164. GetDrawables();
  165. GetBatches();
  166. }
  167. void View::Render()
  168. {
  169. if ((!octree_) || (!camera_))
  170. return;
  171. // If stream offset is supported, write all instance transforms to a single large buffer
  172. // Else we must lock the instance buffer for each batch group
  173. if ((renderer_->GetDynamicInstancing()) && (graphics_->GetStreamOffsetSupport()))
  174. PrepareInstancingBuffer();
  175. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  176. // again to ensure correct projection will be used
  177. if (camera_->GetAutoAspectRatio())
  178. camera_->SetAspectRatio((float)(screenRect_.right_ - screenRect_.left_) / (float)(screenRect_.bottom_ - screenRect_.top_));
  179. // Set the "view texture" to ensure the rendertarget will not be bound as a texture during rendering
  180. if (renderTarget_)
  181. graphics_->SetViewTexture(renderTarget_->GetParentTexture());
  182. else
  183. graphics_->SetViewTexture(0);
  184. graphics_->SetFillMode(FILL_SOLID);
  185. // Calculate view-global shader parameters
  186. CalculateShaderParameters();
  187. // If not reusing shadowmaps, render all of them first
  188. if (!renderer_->reuseShadowMaps_)
  189. {
  190. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  191. {
  192. LightBatchQueue& queue = lightQueues_[i];
  193. if (queue.light_->GetShadowMap())
  194. RenderShadowMap(queue);
  195. }
  196. }
  197. if (mode_ == RENDER_FORWARD)
  198. RenderBatchesForward();
  199. else
  200. RenderBatchesDeferred();
  201. graphics_->SetViewTexture(0);
  202. // If this is a main view, draw the associated debug geometry now
  203. if (!renderTarget_)
  204. {
  205. Scene* scene = static_cast<Scene*>(octree_->GetNode());
  206. if (scene)
  207. {
  208. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  209. if (debug)
  210. {
  211. debug->SetView(camera_);
  212. debug->Render();
  213. }
  214. }
  215. }
  216. // "Forget" the camera, octree and zone after rendering
  217. camera_ = 0;
  218. octree_ = 0;
  219. zone_ = 0;
  220. frame_.camera_ = 0;
  221. }
  222. void View::GetDrawables()
  223. {
  224. PROFILE(GetDrawables);
  225. Vector3 cameraPos = camera_->GetWorldPosition();
  226. // Get zones & find the zone camera is in
  227. PODVector<Zone*> zones;
  228. PointOctreeQuery query(reinterpret_cast<PODVector<Drawable*>& >(zones), cameraPos, DRAWABLE_ZONE);
  229. octree_->GetDrawables(query);
  230. int highestZonePriority = M_MIN_INT;
  231. for (unsigned i = 0; i < zones.Size(); ++i)
  232. {
  233. Zone* zone = zones[i];
  234. if ((zone->IsInside(cameraPos)) && (zone->GetPriority() > highestZonePriority))
  235. {
  236. zone_ = zone;
  237. highestZonePriority = zone->GetPriority();
  238. }
  239. }
  240. // If occlusion in use, get & render the occluders, then build the depth buffer hierarchy
  241. bool useOcclusion = false;
  242. OcclusionBuffer* buffer = 0;
  243. if (maxOccluderTriangles_ > 0)
  244. {
  245. FrustumOctreeQuery query(occluders_, camera_->GetFrustum(), DRAWABLE_GEOMETRY, true, false);
  246. octree_->GetDrawables(query);
  247. UpdateOccluders(occluders_, camera_);
  248. if (occluders_.Size())
  249. {
  250. buffer = renderer_->GetOrCreateOcclusionBuffer(camera_, maxOccluderTriangles_);
  251. DrawOccluders(buffer, occluders_);
  252. buffer->BuildDepthHierarchy();
  253. useOcclusion = true;
  254. }
  255. }
  256. if (!useOcclusion)
  257. {
  258. // Get geometries & lights without occlusion
  259. FrustumOctreeQuery query(tempDrawables_, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  260. octree_->GetDrawables(query);
  261. }
  262. else
  263. {
  264. // Get geometries & lights using occlusion
  265. OccludedFrustumOctreeQuery query(tempDrawables_, camera_->GetFrustum(), buffer, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  266. octree_->GetDrawables(query);
  267. }
  268. // Sort into geometries & lights, and build visible scene bounding boxes in world and view space
  269. sceneBox_.min_ = sceneBox_.max_ = Vector3::ZERO;
  270. sceneBox_.defined_ = false;
  271. sceneViewBox_.min_ = sceneViewBox_.max_ = Vector3::ZERO;
  272. sceneViewBox_.defined_ = false;
  273. Matrix3x4 view(camera_->GetInverseWorldTransform());
  274. unsigned cameraViewMask = camera_->GetViewMask();
  275. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  276. {
  277. Drawable* drawable = tempDrawables_[i];
  278. // Check view mask
  279. if (!(cameraViewMask & drawable->GetViewMask()))
  280. continue;
  281. drawable->UpdateDistance(frame_);
  282. // If draw distance non-zero, check it
  283. float maxDistance = drawable->GetDrawDistance();
  284. if ((maxDistance > 0.0f) && (drawable->GetDistance() > maxDistance))
  285. continue;
  286. unsigned flags = drawable->GetDrawableFlags();
  287. if (flags & DRAWABLE_GEOMETRY)
  288. {
  289. drawable->ClearBasePass();
  290. drawable->MarkInView(frame_);
  291. drawable->UpdateGeometry(frame_);
  292. // Expand the scene bounding boxes
  293. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  294. BoundingBox geoview_Box = geomBox.Transformed(view);
  295. sceneBox_.Merge(geomBox);
  296. sceneViewBox_.Merge(geoview_Box);
  297. // Store depth info to speed up split directional light queries
  298. GeometryDepthBounds bounds;
  299. bounds.min_ = geoview_Box.min_.z_;
  300. bounds.max_ = geoview_Box.max_.z_;
  301. geometryDepthBounds_.Push(bounds);
  302. geometries_.Push(drawable);
  303. }
  304. else if (flags & DRAWABLE_LIGHT)
  305. {
  306. Light* light = static_cast<Light*>(drawable);
  307. // Skip if light is culled by the zone
  308. if (!(light->GetViewMask() & zone_->GetViewMask()))
  309. continue;
  310. light->MarkInView(frame_);
  311. lights_.Push(light);
  312. }
  313. }
  314. // Sort the lights to brightest/closest first
  315. for (unsigned i = 0; i < lights_.Size(); ++i)
  316. lights_[i]->SetIntensitySortValue(cameraPos);
  317. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  318. }
  319. void View::GetBatches()
  320. {
  321. HashSet<LitTransparencyCheck> litTransparencies;
  322. HashSet<Drawable*> maxLightsDrawables;
  323. Map<Light*, unsigned> lightQueueIndex;
  324. PassType gBufferPass = PASS_DEFERRED;
  325. PassType additionalPass = PASS_EXTRA;
  326. if (mode_ == RENDER_PREPASS)
  327. {
  328. gBufferPass = PASS_PREPASS;
  329. additionalPass = PASS_MATERIAL;
  330. }
  331. // Go through lights
  332. {
  333. PROFILE_MULTIPLE(GetLightBatches, lights_.Size());
  334. unsigned lightQueueCount = 0;
  335. for (unsigned i = 0; i < lights_.Size(); ++i)
  336. {
  337. Light* light = lights_[i];
  338. unsigned splits = ProcessLight(light);
  339. if (!splits)
  340. continue;
  341. // Prepare lit object + shadow caster queues for each split
  342. if (lightQueues_.Size() < lightQueueCount + splits)
  343. lightQueues_.Resize(lightQueueCount + splits);
  344. unsigned prevLightQueueCount = lightQueueCount;
  345. for (unsigned j = 0; j < splits; ++j)
  346. {
  347. Light* SplitLight = splitLights_[j];
  348. LightBatchQueue& lightQueue = lightQueues_[lightQueueCount];
  349. lightQueue.light_ = SplitLight;
  350. lightQueue.shadowBatches_.Clear();
  351. lightQueue.litBatches_.Clear();
  352. lightQueue.volumeBatches_.Clear();
  353. lightQueue.lastSplit_ = false;
  354. // Loop through shadow casters
  355. Camera* shadowCamera = SplitLight->GetShadowCamera();
  356. for (unsigned k = 0; k < shadowCasters_[j].Size(); ++k)
  357. {
  358. Drawable* drawable = shadowCasters_[j][k];
  359. unsigned numBatches = drawable->GetNumBatches();
  360. for (unsigned l = 0; l < numBatches; ++l)
  361. {
  362. Batch shadowBatch;
  363. drawable->GetBatch(frame_, l, shadowBatch);
  364. Technique* tech = GetTechnique(drawable, shadowBatch.material_);
  365. if ((!shadowBatch.geometry_) || (!tech))
  366. continue;
  367. Pass* pass = tech->GetPass(PASS_SHADOW);
  368. // Skip if material has no shadow pass
  369. if (!pass)
  370. continue;
  371. // Fill the rest of the batch
  372. shadowBatch.camera_ = shadowCamera;
  373. shadowBatch.distance_ = shadowCamera->GetDistance(drawable->GetWorldPosition());
  374. shadowBatch.light_ = SplitLight;
  375. shadowBatch.hasPriority_ = (!pass->GetAlphaTest()) && (!pass->GetAlphaMask());
  376. renderer_->SetBatchShaders(shadowBatch, tech, pass);
  377. lightQueue.shadowBatches_.AddBatch(shadowBatch);
  378. }
  379. }
  380. // Loop through lit geometries
  381. if (litGeometries_[j].Size())
  382. {
  383. bool storeLightQueue = true;
  384. for (unsigned k = 0; k < litGeometries_[j].Size(); ++k)
  385. {
  386. Drawable* drawable = litGeometries_[j][k];
  387. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  388. if (!drawable->GetMaxLights())
  389. GetLitBatches(drawable, light, SplitLight, &lightQueue, litTransparencies, gBufferPass);
  390. else
  391. {
  392. drawable->AddLight(SplitLight);
  393. maxLightsDrawables.Insert(drawable);
  394. }
  395. }
  396. // Store the light queue, and light volume batch in deferred mode
  397. if (mode_ != RENDER_FORWARD)
  398. {
  399. Batch volumeBatch;
  400. volumeBatch.geometry_ = renderer_->GetLightGeometry(SplitLight);
  401. volumeBatch.worldTransform_ = &SplitLight->GetVolumeTransform(*camera_);
  402. volumeBatch.overrideView_ = SplitLight->GetLightType() == LIGHT_DIRECTIONAL;
  403. volumeBatch.camera_ = camera_;
  404. volumeBatch.light_ = SplitLight;
  405. volumeBatch.distance_ = SplitLight->GetDistance();
  406. renderer_->SetLightVolumeShaders(volumeBatch);
  407. // If light is a split point light, it must be treated as shadowed in any case for correct stencil clearing
  408. if ((SplitLight->GetShadowMap()) || (SplitLight->GetLightType() == LIGHT_SPLITPOINT))
  409. lightQueue.volumeBatches_.Push(volumeBatch);
  410. else
  411. {
  412. storeLightQueue = false;
  413. noShadowLightQueue_.AddBatch(volumeBatch, true);
  414. }
  415. }
  416. if (storeLightQueue)
  417. {
  418. lightQueueIndex[SplitLight] = lightQueueCount;
  419. ++lightQueueCount;
  420. }
  421. }
  422. }
  423. // Mark the last split
  424. if (lightQueueCount != prevLightQueueCount)
  425. lightQueues_[lightQueueCount - 1].lastSplit_ = true;
  426. }
  427. // Resize the light queue vector now that final size is known
  428. lightQueues_.Resize(lightQueueCount);
  429. }
  430. // Process drawables with limited light count
  431. if (maxLightsDrawables.Size())
  432. {
  433. PROFILE(GetMaxLightsBatches);
  434. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables.Begin(); i != maxLightsDrawables.End(); ++i)
  435. {
  436. Drawable* drawable = *i;
  437. drawable->LimitLights();
  438. const PODVector<Light*>& lights = drawable->GetLights();
  439. for (unsigned i = 0; i < lights.Size(); ++i)
  440. {
  441. Light* SplitLight = lights[i];
  442. Light* light = SplitLight->GetOriginalLight();
  443. if (!light)
  444. light = SplitLight;
  445. // Find the correct light queue again
  446. LightBatchQueue* queue = 0;
  447. Map<Light*, unsigned>::Iterator j = lightQueueIndex.Find(SplitLight);
  448. if (j != lightQueueIndex.End())
  449. queue = &lightQueues_[j->second_];
  450. GetLitBatches(drawable, light, SplitLight, queue, litTransparencies, gBufferPass);
  451. }
  452. }
  453. }
  454. // Go through geometries for base pass batches
  455. {
  456. PROFILE(GetBaseBatches);
  457. for (unsigned i = 0; i < geometries_.Size(); ++i)
  458. {
  459. Drawable* drawable = geometries_[i];
  460. unsigned numBatches = drawable->GetNumBatches();
  461. for (unsigned j = 0; j < numBatches; ++j)
  462. {
  463. Batch baseBatch;
  464. drawable->GetBatch(frame_, j, baseBatch);
  465. Technique* tech = GetTechnique(drawable, baseBatch.material_);
  466. if ((!baseBatch.geometry_) || (!tech))
  467. continue;
  468. // Check here if the material technique refers to a render target texture with camera(s) attached
  469. // Only check this for the main view (null rendertarget)
  470. if ((!renderTarget_) && (baseBatch.material_) && (baseBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_))
  471. CheckMaterialForAuxView(baseBatch.material_);
  472. // If object already has a lit base pass, can skip the unlit base pass
  473. if (drawable->HasBasePass(j))
  474. continue;
  475. // Fill the rest of the batch
  476. baseBatch.camera_ = camera_;
  477. baseBatch.distance_ = drawable->GetDistance();
  478. Pass* pass = 0;
  479. // In deferred mode, check for a G-buffer batch first
  480. if (mode_ != RENDER_FORWARD)
  481. {
  482. pass = tech->GetPass(gBufferPass);
  483. if (pass)
  484. {
  485. renderer_->SetBatchShaders(baseBatch, tech, pass);
  486. baseBatch.hasPriority_ = (!pass->GetAlphaTest()) && (!pass->GetAlphaMask());
  487. gBufferQueue_.AddBatch(baseBatch);
  488. // Check also for an additional pass. In light prepass mode this actually renders the visible geometry
  489. pass = tech->GetPass(additionalPass);
  490. if (pass)
  491. {
  492. renderer_->SetBatchShaders(baseBatch, tech, pass);
  493. baseQueue_.AddBatch(baseBatch);
  494. }
  495. continue;
  496. }
  497. }
  498. // Then check for forward rendering base pass
  499. pass = tech->GetPass(PASS_BASE);
  500. if (pass)
  501. {
  502. renderer_->SetBatchShaders(baseBatch, tech, pass);
  503. if (pass->GetBlendMode() == BLEND_REPLACE)
  504. {
  505. baseBatch.hasPriority_ = (!pass->GetAlphaTest()) && (!pass->GetAlphaMask());
  506. baseQueue_.AddBatch(baseBatch);
  507. }
  508. else
  509. {
  510. baseBatch.hasPriority_ = true;
  511. transparentQueue_.AddBatch(baseBatch, true);
  512. }
  513. continue;
  514. }
  515. else
  516. {
  517. // If no base pass, finally check for extra / custom pass
  518. pass = tech->GetPass(PASS_EXTRA);
  519. if (pass)
  520. {
  521. baseBatch.hasPriority_ = false;
  522. renderer_->SetBatchShaders(baseBatch, tech, pass);
  523. extraQueue_.AddBatch(baseBatch);
  524. }
  525. }
  526. }
  527. }
  528. }
  529. // All batches have been collected. Sort them now
  530. SortBatches();
  531. }
  532. void View::GetLitBatches(Drawable* drawable, Light* light, Light* SplitLight, LightBatchQueue* lightQueue,
  533. HashSet<LitTransparencyCheck>& litTransparencies, PassType gBufferPass)
  534. {
  535. bool splitPointLight = SplitLight->GetLightType() == LIGHT_SPLITPOINT;
  536. // Whether to allow shadows for transparencies, or for forward lit objects in deferred mode
  537. bool allowShadows = (!renderer_->reuseShadowMaps_) && (!splitPointLight);
  538. unsigned numBatches = drawable->GetNumBatches();
  539. for (unsigned i = 0; i < numBatches; ++i)
  540. {
  541. Batch litBatch;
  542. drawable->GetBatch(frame_, i, litBatch);
  543. Technique* tech = GetTechnique(drawable, litBatch.material_);
  544. if ((!litBatch.geometry_) || (!tech))
  545. continue;
  546. // If material uses opaque G-buffer rendering, skip
  547. if ((mode_ != RENDER_FORWARD) && (tech->HasPass(gBufferPass)))
  548. continue;
  549. Pass* pass = 0;
  550. bool priority = false;
  551. // For directional light, check for lit base pass
  552. if (SplitLight->GetLightType() == LIGHT_DIRECTIONAL)
  553. {
  554. if (!drawable->HasBasePass(i))
  555. {
  556. pass = tech->GetPass(PASS_LITBASE);
  557. if (pass)
  558. {
  559. priority = true;
  560. drawable->SetBasePass(i);
  561. }
  562. }
  563. }
  564. // If no first light pass, get ordinary light pass
  565. if (!pass)
  566. pass = tech->GetPass(PASS_LIGHT);
  567. // Skip if material does not receive light at all
  568. if (!pass)
  569. continue;
  570. // Fill the rest of the batch
  571. litBatch.camera_ = camera_;
  572. litBatch.distance_ = drawable->GetDistance();
  573. litBatch.light_ = SplitLight;
  574. litBatch.hasPriority_ = priority;
  575. // Check from the ambient pass whether the object is opaque
  576. Pass* ambientPass = tech->GetPass(PASS_BASE);
  577. if ((!ambientPass) || (ambientPass->GetBlendMode() == BLEND_REPLACE))
  578. {
  579. if (mode_ == RENDER_FORWARD)
  580. {
  581. if (lightQueue)
  582. {
  583. renderer_->SetBatchShaders(litBatch, tech, pass);
  584. lightQueue->litBatches_.AddBatch(litBatch);
  585. }
  586. }
  587. else
  588. {
  589. renderer_->SetBatchShaders(litBatch, tech, pass, allowShadows);
  590. baseQueue_.AddBatch(litBatch);
  591. }
  592. }
  593. else
  594. {
  595. if (splitPointLight)
  596. {
  597. // Check if already lit
  598. LitTransparencyCheck check(light, drawable, i);
  599. if (litTransparencies.Find(check) != litTransparencies.End())
  600. continue;
  601. // Use the original light instead of the split one, to choose correct scissor
  602. litBatch.light_ = light;
  603. litTransparencies.Insert(check);
  604. }
  605. renderer_->SetBatchShaders(litBatch, tech, pass, allowShadows);
  606. transparentQueue_.AddBatch(litBatch, true);
  607. }
  608. }
  609. }
  610. void View::RenderBatchesForward()
  611. {
  612. {
  613. // Render opaque objects' base passes
  614. PROFILE(RenderBasePass);
  615. graphics_->ClearLastParameterSources();
  616. graphics_->SetColorWrite(true);
  617. graphics_->SetStencilTest(false);
  618. graphics_->SetRenderTarget(0, renderTarget_);
  619. graphics_->SetDepthStencil(depthStencil_);
  620. graphics_->SetViewport(screenRect_);
  621. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, zone_->GetFogColor());
  622. RenderBatchQueue(baseQueue_);
  623. }
  624. {
  625. // Render shadow maps + opaque objects' shadowed additive lighting
  626. PROFILE(RenderLights);
  627. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  628. {
  629. LightBatchQueue& queue = lightQueues_[i];
  630. // If reusing shadowmaps, render each of them before the lit batches
  631. if ((renderer_->reuseShadowMaps_) && (queue.light_->GetShadowMap()))
  632. RenderShadowMap(queue);
  633. graphics_->ClearLastParameterSources();
  634. graphics_->SetRenderTarget(0, renderTarget_);
  635. graphics_->SetDepthStencil(depthStencil_);
  636. graphics_->SetViewport(screenRect_);
  637. RenderForwardLightBatchQueue(queue.litBatches_, queue.light_);
  638. // Clear the stencil buffer after the last split
  639. if (queue.lastSplit_)
  640. {
  641. LightType type = queue.light_->GetLightType();
  642. if ((type == LIGHT_SPLITPOINT) || (type == LIGHT_DIRECTIONAL))
  643. DrawSplitLightToStencil(*camera_, queue.light_, true);
  644. }
  645. }
  646. }
  647. {
  648. // Render extra / custom passes
  649. PROFILE(RenderExtraPass);
  650. graphics_->ClearLastParameterSources();
  651. graphics_->SetRenderTarget(0, renderTarget_);
  652. graphics_->SetDepthStencil(depthStencil_);
  653. graphics_->SetViewport(screenRect_);
  654. RenderBatchQueue(extraQueue_);
  655. }
  656. {
  657. // Render transparent objects last (both base passes & additive lighting)
  658. PROFILE(RenderTransparent);
  659. RenderBatchQueue(transparentQueue_, true);
  660. }
  661. }
  662. void View::RenderBatchesDeferred()
  663. {
  664. bool deferred = mode_ != RENDER_PREPASS;
  665. Texture2D* diffBuffer = graphics_->GetDiffBuffer();
  666. Texture2D* normalBuffer = graphics_->GetNormalBuffer();
  667. Texture2D* depthBuffer = graphics_->GetDepthBuffer();
  668. // Check for temporal antialiasing in deferred mode. Only use it on the main view (null rendertarget)
  669. bool temporalAA = (!renderTarget_) && (graphics_->GetMultiSample() > 0);
  670. if (temporalAA)
  671. {
  672. ++jitterCounter_;
  673. if (jitterCounter_ > 3)
  674. jitterCounter_ = 2;
  675. Vector2 jitter(-0.25f, -0.25f);
  676. if (jitterCounter_ & 1)
  677. jitter = -jitter;
  678. jitter.x_ /= width_;
  679. jitter.y_ /= height_;
  680. camera_->SetProjectionOffset(jitter);
  681. }
  682. RenderSurface* finalRenderTarget = temporalAA ? graphics_->GetScreenBuffer(jitterCounter_ & 1)->GetRenderSurface() : renderTarget_;
  683. // In OpenGL, we will use two depth stencils: one for the G-buffer, and one for light accumulation
  684. #ifdef USE_OPENGL
  685. RenderSurface* lightDepthStencil = deferred ? depthStencil_ : depthBuffer->GetRenderSurface();
  686. RenderSurface* finalDepthStencil = depthStencil_;
  687. // Exception: if temporal AA is used, the G-buffer depth stencil can be used for the whole time,
  688. // as the backbuffer is only copied to in the very end
  689. if (temporalAA)
  690. lightDepthStencil = finalDepthStencil = depthBuffer->GetRenderSurface();
  691. #else
  692. // In Direct3D9 the system depth stencil will be used for the whole time
  693. RenderSurface* lightDepthStencil = 0;
  694. RenderSurface* finalDepthStencil = 0;
  695. #endif
  696. // Calculate shader parameters needed only in deferred rendering
  697. Vector3 nearVector, farVector;
  698. camera_->GetFrustumSize(nearVector, farVector);
  699. Vector4 viewportParams(farVector.x_, farVector.y_, farVector.z_, 0.0f);
  700. float gBufferWidth = (float)diffBuffer->GetWidth();
  701. float gBufferHeight = (float)diffBuffer->GetHeight();
  702. float widthRange = 0.5f * width_ / gBufferWidth;
  703. float heightRange = 0.5f * height_ / gBufferHeight;
  704. #ifdef USE_OPENGL
  705. Vector4 bufferUVOffset(((float)screenRect_.left_) / gBufferWidth + widthRange,
  706. ((float)screenRect_.top_) / gBufferHeight + heightRange, widthRange, heightRange);
  707. // Hardware depth is non-linear in perspective views, so calculate the depth reconstruction parameters
  708. float farClip = camera_->GetFarClip();
  709. float nearClip = camera_->GetNearClip();
  710. Vector4 depthReconstruct = Vector4::ZERO;
  711. depthReconstruct.x_ = farClip / (farClip - nearClip);
  712. depthReconstruct.y_ = -nearClip / (farClip - nearClip);
  713. shaderParameters_[PSP_DEPTHRECONSTRUCT] = depthReconstruct;
  714. #else
  715. Vector4 bufferUVOffset((0.5f + (float)screenRect_.left_) / gBufferWidth + widthRange,
  716. (0.5f + (float)screenRect_.top_) / gBufferHeight + heightRange, widthRange, heightRange);
  717. #endif
  718. Vector4 viewportSize((float)screenRect_.left_ / gBufferWidth, (float)screenRect_.top_ / gBufferHeight,
  719. (float)screenRect_.right_ / gBufferWidth, (float)screenRect_.bottom_ / gBufferHeight);
  720. shaderParameters_[VSP_FRUSTUMSIZE] = viewportParams;
  721. shaderParameters_[VSP_GBUFFEROFFSETS] = bufferUVOffset;
  722. shaderParameters_[PSP_GBUFFEROFFSETS] = bufferUVOffset;
  723. shaderParameters_[PSP_GBUFFERVIEWPORT] = viewportSize;
  724. {
  725. // Clear and render the G-buffer
  726. PROFILE(RenderGBuffer);
  727. graphics_->ClearLastParameterSources();
  728. graphics_->SetColorWrite(true);
  729. graphics_->SetScissorTest(false);
  730. graphics_->SetStencilTest(false);
  731. #ifdef USE_OPENGL
  732. // On OpenGL, clear the diffuse and depth buffers normally
  733. if (deferred)
  734. {
  735. graphics_->SetRenderTarget(0, diffBuffer);
  736. graphics_->SetDepthStencil(depthBuffer);
  737. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL);
  738. graphics_->SetRenderTarget(1, normalBuffer);
  739. }
  740. else
  741. {
  742. graphics_->SetRenderTarget(0, (RenderSurface*)0);
  743. graphics_->SetDepthStencil(depthBuffer);
  744. graphics_->Clear(CLEAR_DEPTH | CLEAR_STENCIL);
  745. graphics_->SetRenderTarget(0, normalBuffer);
  746. }
  747. #else
  748. // On Direct3D9, clear only depth and stencil at first (fillrate optimization)
  749. if (deferred)
  750. {
  751. graphics_->SetRenderTarget(0, diffBuffer);
  752. graphics_->SetRenderTarget(1, normalBuffer);
  753. graphics_->SetRenderTarget(2, depthBuffer);
  754. }
  755. else
  756. {
  757. graphics_->SetRenderTarget(0, normalBuffer);
  758. graphics_->SetRenderTarget(1, depthBuffer);
  759. }
  760. graphics_->SetDepthStencil(lightDepthStencil);
  761. graphics_->SetViewport(screenRect_);
  762. graphics_->Clear(CLEAR_DEPTH | CLEAR_STENCIL);
  763. #endif
  764. RenderBatchQueue(gBufferQueue_);
  765. graphics_->SetAlphaTest(false);
  766. graphics_->SetBlendMode(BLEND_REPLACE);
  767. #ifndef USE_OPENGL
  768. // On Direct3D9, clear now the parts of G-Buffer that were not rendered into
  769. graphics_->SetDepthTest(CMP_LESSEQUAL);
  770. graphics_->SetDepthWrite(false);
  771. if (deferred)
  772. {
  773. graphics_->ResetRenderTarget(2);
  774. graphics_->SetRenderTarget(1, depthBuffer);
  775. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("Deferred/GBufferFill"),
  776. renderer_->GetPixelShader("Deferred/GBufferFill"), false, shaderParameters_);
  777. }
  778. else
  779. {
  780. graphics_->ResetRenderTarget(1);
  781. graphics_->SetRenderTarget(0, depthBuffer);
  782. graphics_->SetViewport(screenRect_);
  783. // The stencil shader writes color 1.0, which equals far depth
  784. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("Stencil"),
  785. renderer_->GetPixelShader("Stencil"), false, shaderParameters_);
  786. }
  787. #endif
  788. }
  789. if (deferred)
  790. {
  791. // Render ambient color & fog. On OpenGL the depth buffer will be copied now if necessary
  792. graphics_->ClearLastParameterSources();
  793. graphics_->SetDepthTest(CMP_ALWAYS);
  794. graphics_->SetRenderTarget(0, finalRenderTarget);
  795. graphics_->ResetRenderTarget(1);
  796. #ifdef USE_OPENGL
  797. bool copyDepth = lightDepthStencil != depthBuffer->GetRenderSurface();
  798. graphics_->SetDepthWrite(copyDepth);
  799. #else
  800. graphics_->ResetRenderTarget(2);
  801. #endif
  802. graphics_->SetDepthStencil(lightDepthStencil);
  803. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  804. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  805. graphics_->SetViewport(screenRect_);
  806. String pixelShaderName = "Deferred/Ambient";
  807. #ifdef USE_OPENGL
  808. if (camera_->IsOrthographic())
  809. pixelShaderName += "Ortho";
  810. #endif
  811. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("Deferred/Ambient"),
  812. renderer_->GetPixelShader(pixelShaderName), false, shaderParameters_);
  813. }
  814. else
  815. {
  816. // Light prepass: reset the light accumulation buffer with black color
  817. // On OpenGL we still use the GBuffer's depth buffer at this point, so depth is not copied yet
  818. graphics_->SetRenderTarget(0, diffBuffer);
  819. #ifndef USE_OPENGL
  820. graphics_->ResetRenderTarget(1);
  821. #endif
  822. graphics_->SetDepthStencil(lightDepthStencil);
  823. graphics_->SetViewport(screenRect_);
  824. graphics_->Clear(CLEAR_COLOR);
  825. }
  826. {
  827. // Render lights
  828. PROFILE(RenderLights);
  829. // Shadowed lights
  830. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  831. {
  832. LightBatchQueue& queue = lightQueues_[i];
  833. // If reusing shadowmaps, render each of them before the lit batches
  834. if ((renderer_->reuseShadowMaps_) && (queue.light_->GetShadowMap()))
  835. RenderShadowMap(queue);
  836. // Light volume batches are not sorted as there should be only one of them
  837. if (queue.volumeBatches_.Size())
  838. {
  839. graphics_->ClearLastParameterSources();
  840. if (deferred)
  841. {
  842. graphics_->SetRenderTarget(0, finalRenderTarget);
  843. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  844. }
  845. else
  846. graphics_->SetRenderTarget(0, diffBuffer);
  847. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  848. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  849. graphics_->SetDepthStencil(lightDepthStencil);
  850. graphics_->SetViewport(screenRect_);
  851. for (unsigned j = 0; j < queue.volumeBatches_.Size(); ++j)
  852. {
  853. renderer_->SetupLightBatch(queue.volumeBatches_[j]);
  854. queue.volumeBatches_[j].Draw(graphics_, shaderParameters_);
  855. }
  856. // If was the last split of a split point light, clear the stencil by rendering the point light again
  857. if ((queue.lastSplit_) && (queue.light_->GetLightType() == LIGHT_SPLITPOINT))
  858. DrawSplitLightToStencil(*camera_, queue.light_, true);
  859. }
  860. }
  861. // Non-shadowed lights
  862. if (noShadowLightQueue_.sortedBatches_.Size())
  863. {
  864. graphics_->ClearLastParameterSources();
  865. if (deferred)
  866. {
  867. graphics_->SetRenderTarget(0, finalRenderTarget);
  868. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  869. }
  870. else
  871. graphics_->SetRenderTarget(0, diffBuffer);
  872. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  873. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  874. graphics_->SetDepthStencil(lightDepthStencil);
  875. graphics_->SetViewport(screenRect_);
  876. for (unsigned i = 0; i < noShadowLightQueue_.sortedBatches_.Size(); ++i)
  877. {
  878. renderer_->SetupLightBatch(*noShadowLightQueue_.sortedBatches_[i]);
  879. noShadowLightQueue_.sortedBatches_[i]->Draw(graphics_, shaderParameters_);
  880. }
  881. }
  882. }
  883. {
  884. // Render base passes
  885. PROFILE(RenderBasePass);
  886. graphics_->ClearLastParameterSources();
  887. graphics_->SetStencilTest(false);
  888. graphics_->SetRenderTarget(0, finalRenderTarget);
  889. graphics_->SetDepthStencil(finalDepthStencil);
  890. graphics_->SetViewport(screenRect_);
  891. graphics_->SetTexture(TU_DIFFBUFFER, 0);
  892. graphics_->SetTexture(TU_NORMALBUFFER, 0);
  893. graphics_->SetTexture(TU_DEPTHBUFFER, 0);
  894. if (!deferred)
  895. {
  896. #ifdef USE_OPENGL
  897. // In OpenGL light prepass mode, copy depth now
  898. if (finalDepthStencil != depthBuffer->GetRenderSurface())
  899. {
  900. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  901. graphics_->SetAlphaTest(false);
  902. graphics_->SetBlendMode(BLEND_REPLACE);
  903. graphics_->SetDepthTest(CMP_ALWAYS);
  904. graphics_->SetDepthWrite(true);
  905. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("Prepass/CopyDepth"),
  906. renderer_->GetPixelShader("Prepass/CopyDepth"), false, shaderParameters_);
  907. }
  908. else
  909. graphics_->Clear(CLEAR_COLOR, zone_->GetFogColor());
  910. #else
  911. graphics_->Clear(CLEAR_COLOR, zone_->GetFogColor());
  912. #endif
  913. }
  914. // Remember to bind the light buffer in prepass mode
  915. RenderBatchQueue(baseQueue_, true, !deferred);
  916. }
  917. {
  918. // Render extra / custom passes
  919. PROFILE(RenderExtraPass);
  920. RenderBatchQueue(extraQueue_);
  921. }
  922. {
  923. // Render transparent objects last (both ambient & additive lighting)
  924. PROFILE(RenderTransparent);
  925. RenderBatchQueue(transparentQueue_, true);
  926. }
  927. // Render temporal antialiasing now if enabled
  928. if (temporalAA)
  929. {
  930. PROFILE(RenderTemporalAA);
  931. // Disable averaging if it is the first frame rendered in this view
  932. float thisFrameWeight = jitterCounter_ < 2 ? 1.0f : 0.5f;
  933. Vector4 depthMode = Vector4::ZERO;
  934. if (camera_->IsOrthographic())
  935. depthMode.z_ = 1.0f;
  936. else
  937. depthMode.w_ = 1.0f / camera_->GetFarClip();
  938. unsigned index = camera_->IsOrthographic() ? 1 : 0;
  939. String shaderName = "TemporalAA_" + aaVariation[index];
  940. graphics_->SetAlphaTest(false);
  941. graphics_->SetBlendMode(BLEND_REPLACE);
  942. graphics_->SetDepthTest(CMP_ALWAYS);
  943. graphics_->SetDepthWrite(false);
  944. graphics_->SetScissorTest(false);
  945. graphics_->SetStencilTest(false);
  946. graphics_->SetRenderTarget(0, renderTarget_);
  947. graphics_->SetDepthStencil(depthStencil_);
  948. graphics_->SetViewport(screenRect_);
  949. // Pre-select the right shaders so that we can set shader parameters that can not go into the parameter map
  950. // (matrices)
  951. graphics_->SetShaders(renderer_->GetVertexShader(shaderName), renderer_->GetPixelShader(shaderName));
  952. graphics_->SetShaderParameter(VSP_CAMERAROT, camera_->GetWorldTransform().RotationMatrix());
  953. graphics_->SetShaderParameter(VSP_DEPTHMODE, depthMode);
  954. graphics_->SetShaderParameter(PSP_CAMERAPOS, camera_->GetWorldPosition());
  955. graphics_->SetShaderParameter(PSP_ANTIALIASWEIGHTS, Vector4(thisFrameWeight, 1.0f - thisFrameWeight, 0.0f, 0.0f));
  956. graphics_->SetShaderParameter(PSP_SAMPLEOFFSETS, Vector4(1.0f / gBufferWidth, 1.0f / gBufferHeight, 0.0f, 0.0f));
  957. graphics_->SetShaderParameter(PSP_VIEWPROJ, camera_->GetProjection(false) * lastCameraView_);
  958. graphics_->SetTexture(TU_DIFFBUFFER, graphics_->GetScreenBuffer(jitterCounter_ & 1));
  959. graphics_->SetTexture(TU_NORMALBUFFER, graphics_->GetScreenBuffer((jitterCounter_ + 1) & 1));
  960. graphics_->SetTexture(TU_DEPTHBUFFER, graphics_->GetDepthBuffer());
  961. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader(shaderName),
  962. renderer_->GetPixelShader(shaderName), false, shaderParameters_);
  963. // Store view transform for next frame
  964. lastCameraView_ = camera_->GetInverseWorldTransform();
  965. }
  966. }
  967. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  968. {
  969. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  970. float halfViewSize = camera->GetHalfViewSize();
  971. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  972. Vector3 cameraPos = camera->GetWorldPosition();
  973. unsigned cameraViewMask = camera->GetViewMask();
  974. for (unsigned i = 0; i < occluders.Size(); ++i)
  975. {
  976. Drawable* occluder = occluders[i];
  977. occluder->UpdateDistance(frame_);
  978. bool erase = false;
  979. // Check view mask
  980. if (!(cameraViewMask & occluder->GetViewMask()))
  981. erase = true;
  982. // Check occluder's draw distance (in main camera view)
  983. float maxDistance = occluder->GetDrawDistance();
  984. if ((maxDistance > 0.0f) && (occluder->GetDistance() > maxDistance))
  985. erase = true;
  986. // Check that occluder is big enough on the screen
  987. const BoundingBox& box = occluder->GetWorldBoundingBox();
  988. float diagonal = (box.max_ - box.min_).LengthFast();
  989. float compare;
  990. if (!camera->IsOrthographic())
  991. compare = diagonal * halfViewSize / occluder->GetDistance();
  992. else
  993. compare = diagonal * invOrthoSize;
  994. if (compare < occluderSizeThreshold_)
  995. erase = true;
  996. if (!erase)
  997. {
  998. unsigned totalTriangles = 0;
  999. unsigned batches = occluder->GetNumBatches();
  1000. Batch tempBatch;
  1001. for (unsigned j = 0; j < batches; ++j)
  1002. {
  1003. occluder->GetBatch(frame_, j, tempBatch);
  1004. if (tempBatch.geometry_)
  1005. totalTriangles += tempBatch.geometry_->GetIndexCount() / 3;
  1006. }
  1007. // Store amount of triangles divided by screen size as a sorting key
  1008. // (best occluders are big and have few triangles)
  1009. occluder->SetSortValue((float)totalTriangles / compare);
  1010. }
  1011. else
  1012. {
  1013. occluders.Erase(occluders.Begin() + i);
  1014. --i;
  1015. }
  1016. }
  1017. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  1018. if (occluders.Size())
  1019. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  1020. }
  1021. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  1022. {
  1023. for (unsigned i = 0; i < occluders.Size(); ++i)
  1024. {
  1025. Drawable* occluder = occluders[i];
  1026. if (i > 0)
  1027. {
  1028. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  1029. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  1030. continue;
  1031. }
  1032. occluder->UpdateGeometry(frame_);
  1033. // Check for running out of triangles
  1034. if (!occluder->DrawOcclusion(buffer))
  1035. return;
  1036. }
  1037. }
  1038. unsigned View::ProcessLight(Light* light)
  1039. {
  1040. unsigned numLitGeometries = 0;
  1041. unsigned numShadowCasters = 0;
  1042. unsigned numSplits;
  1043. // Check if light should be shadowed
  1044. bool isShadowed = (drawShadows_) && (light->GetCastShadows());
  1045. // If shadow distance non-zero, check it
  1046. if ((isShadowed) && (light->GetShadowDistance() > 0.0f) && (light->GetDistance() > light->GetShadowDistance()))
  1047. isShadowed = false;
  1048. // If light has no ramp textures defined, set defaults
  1049. if ((light->GetLightType() != LIGHT_DIRECTIONAL) && (!light->GetRampTexture()))
  1050. light->SetRampTexture(renderer_->GetDefaultLightRamp());
  1051. if ((light->GetLightType() == LIGHT_SPOT) && (!light->GetShapeTexture()))
  1052. light->SetShapeTexture(renderer_->GetDefaultLightSpot());
  1053. // Split the light if necessary
  1054. if (isShadowed)
  1055. numSplits = SplitLight(light);
  1056. else
  1057. {
  1058. // No splitting, use the original light
  1059. splitLights_[0] = light;
  1060. numSplits = 1;
  1061. }
  1062. // For a shadowed directional light, get occluders once using the whole (non-split) light frustum
  1063. bool useOcclusion = false;
  1064. OcclusionBuffer* buffer = 0;
  1065. if ((maxOccluderTriangles_ > 0) && (isShadowed) && (light->GetLightType() == LIGHT_DIRECTIONAL))
  1066. {
  1067. // This shadow camera is never used for actually querying shadow casters, just occluders
  1068. Camera* shadowCamera = renderer_->CreateShadowCamera();
  1069. light->SetShadowCamera(shadowCamera);
  1070. SetupShadowCamera(light, true);
  1071. // Get occluders, which must be shadow-casting themselves
  1072. FrustumOctreeQuery query(shadowOccluders_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY, true, true);
  1073. octree_->GetDrawables(query);
  1074. UpdateOccluders(shadowOccluders_, shadowCamera);
  1075. if (shadowOccluders_.Size())
  1076. {
  1077. // Shadow viewport is rectangular and consumes more CPU fillrate, so halve size
  1078. buffer = renderer_->GetOrCreateOcclusionBuffer(shadowCamera, maxOccluderTriangles_, true);
  1079. DrawOccluders(buffer, shadowOccluders_);
  1080. buffer->BuildDepthHierarchy();
  1081. useOcclusion = true;
  1082. }
  1083. }
  1084. // Process each split for shadow camera update, lit geometries, and shadow casters
  1085. for (unsigned i = 0; i < numSplits; ++i)
  1086. {
  1087. litGeometries_[i].Clear();
  1088. shadowCasters_[i].Clear();
  1089. }
  1090. for (unsigned i = 0; i < numSplits; ++i)
  1091. {
  1092. Light* split = splitLights_[i];
  1093. LightType type = split->GetLightType();
  1094. bool isSplitShadowed = (isShadowed) && (split->GetCastShadows());
  1095. Camera* shadowCamera = 0;
  1096. // If shadow casting, choose the shadow map & update shadow camera
  1097. if (isSplitShadowed)
  1098. {
  1099. shadowCamera = renderer_->CreateShadowCamera();
  1100. split->SetShadowMap(renderer_->GetShadowMap(splitLights_[i]->GetShadowResolution()));
  1101. // Check if managed to get a shadow map. Otherwise must convert to non-shadowed
  1102. if (split->GetShadowMap())
  1103. {
  1104. split->SetShadowCamera(shadowCamera);
  1105. SetupShadowCamera(split);
  1106. }
  1107. else
  1108. {
  1109. isSplitShadowed = false;
  1110. split->SetShadowCamera(0);
  1111. }
  1112. }
  1113. else
  1114. {
  1115. split->SetShadowCamera(0);
  1116. split->SetShadowMap(0);
  1117. }
  1118. BoundingBox geometryBox;
  1119. BoundingBox shadowCasterBox;
  1120. switch (type)
  1121. {
  1122. case LIGHT_DIRECTIONAL:
  1123. // Loop through visible geometries and check if they belong to this split
  1124. {
  1125. float nearSplit = split->GetNearSplit() - split->GetNearFadeRange();
  1126. float farSplit = split->GetFarSplit();
  1127. // If split extends to the whole visible frustum, no depth check necessary
  1128. bool optimize = (nearSplit <= camera_->GetNearClip()) && (farSplit >= camera_->GetFarClip());
  1129. // If whole visible scene is outside the split, can reject trivially
  1130. if ((sceneViewBox_.min_.z_ > farSplit) || (sceneViewBox_.max_.z_ < nearSplit))
  1131. {
  1132. split->SetShadowMap(0);
  1133. continue;
  1134. }
  1135. bool generateBoxes = (isSplitShadowed) && (split->GetShadowFocus().focus_);
  1136. Matrix3x4 lightView;
  1137. if (shadowCamera)
  1138. lightView = shadowCamera->GetInverseWorldTransform();
  1139. if (!optimize)
  1140. {
  1141. for (unsigned j = 0; j < geometries_.Size(); ++j)
  1142. {
  1143. Drawable* drawable = geometries_[j];
  1144. const GeometryDepthBounds& bounds = geometryDepthBounds_[j];
  1145. // Check bounds and light mask
  1146. if ((bounds.min_ <= farSplit) && (bounds.max_ >= nearSplit) && (drawable->GetLightMask() &
  1147. split->GetLightMask()))
  1148. {
  1149. litGeometries_[i].Push(drawable);
  1150. if (generateBoxes)
  1151. geometryBox.Merge(drawable->GetWorldBoundingBox().Transformed(lightView));
  1152. }
  1153. }
  1154. }
  1155. else
  1156. {
  1157. for (unsigned j = 0; j < geometries_.Size(); ++j)
  1158. {
  1159. Drawable* drawable = geometries_[j];
  1160. // Need to check light mask only
  1161. if (drawable->GetLightMask() & split->GetLightMask())
  1162. {
  1163. litGeometries_[i].Push(drawable);
  1164. if (generateBoxes)
  1165. geometryBox.Merge(drawable->GetWorldBoundingBox().Transformed(lightView));
  1166. }
  1167. }
  1168. }
  1169. }
  1170. // Then get shadow casters by shadow camera frustum query. Use occlusion because of potentially many geometries
  1171. if ((isSplitShadowed) && (litGeometries_[i].Size()))
  1172. {
  1173. Camera* shadowCamera = split->GetShadowCamera();
  1174. if (!useOcclusion)
  1175. {
  1176. // Get potential shadow casters without occlusion
  1177. FrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY);
  1178. octree_->GetDrawables(query);
  1179. }
  1180. else
  1181. {
  1182. // Get potential shadow casters with occlusion
  1183. OccludedFrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), buffer,
  1184. DRAWABLE_GEOMETRY);
  1185. octree_->GetDrawables(query);
  1186. }
  1187. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, false, isSplitShadowed);
  1188. }
  1189. break;
  1190. case LIGHT_POINT:
  1191. {
  1192. SphereOctreeQuery query(tempDrawables_, Sphere(split->GetWorldPosition(), split->GetRange()), DRAWABLE_GEOMETRY);
  1193. octree_->GetDrawables(query);
  1194. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, true, false);
  1195. }
  1196. break;
  1197. case LIGHT_SPOT:
  1198. case LIGHT_SPLITPOINT:
  1199. {
  1200. FrustumOctreeQuery query(tempDrawables_, splitLights_[i]->GetFrustum(), DRAWABLE_GEOMETRY);
  1201. octree_->GetDrawables(query);
  1202. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, true, isSplitShadowed);
  1203. }
  1204. break;
  1205. }
  1206. // Optimization: if a particular split has no shadow casters, render as unshadowed
  1207. if (!shadowCasters_[i].Size())
  1208. split->SetShadowMap(0);
  1209. // Focus shadow camera as applicable
  1210. if (split->GetShadowMap())
  1211. {
  1212. if (split->GetShadowFocus().focus_)
  1213. FocusShadowCamera(split, geometryBox, shadowCasterBox);
  1214. // Set a zoom factor to ensure that we do not render to the shadow map border
  1215. // (clamp addressing is necessary because border mode /w hardware shadow maps is not supported by all GPUs)
  1216. Camera* shadowCamera = split->GetShadowCamera();
  1217. Texture2D* shadowMap = split->GetShadowMap();
  1218. if (shadowCamera->GetZoom() >= 1.0f)
  1219. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((float)(shadowMap->GetWidth() - 2) / (float)shadowMap->GetWidth()));
  1220. }
  1221. // Update count of total lit geometries & shadow casters
  1222. numLitGeometries += litGeometries_[i].Size();
  1223. numShadowCasters += shadowCasters_[i].Size();
  1224. }
  1225. // If no lit geometries at all, no need to process further
  1226. if (!numLitGeometries)
  1227. numSplits = 0;
  1228. // If no shadow casters at all, concatenate lit geometries into one & return the original light
  1229. else if (!numShadowCasters)
  1230. {
  1231. if (numSplits > 1)
  1232. {
  1233. // Make sure there are no duplicates
  1234. HashSet<Drawable*> allLitGeometries;
  1235. for (unsigned i = 0; i < numSplits; ++i)
  1236. {
  1237. for (Vector<Drawable*>::Iterator j = litGeometries_[i].Begin(); j != litGeometries_[i].End(); ++j)
  1238. allLitGeometries.Insert(*j);
  1239. }
  1240. litGeometries_[0].Resize(allLitGeometries.Size());
  1241. unsigned index = 0;
  1242. for (HashSet<Drawable*>::Iterator i = allLitGeometries.Begin(); i != allLitGeometries.End(); ++i)
  1243. litGeometries_[0][index++] = *i;
  1244. }
  1245. splitLights_[0] = light;
  1246. splitLights_[0]->SetShadowMap(0);
  1247. numSplits = 1;
  1248. }
  1249. return numSplits;
  1250. }
  1251. void View::ProcessLightQuery(unsigned splitIndex, const PODVector<Drawable*>& result, BoundingBox& geometryBox,
  1252. BoundingBox& shadowCasterBox, bool getLitGeometries, bool GetShadowCasters)
  1253. {
  1254. Light* light = splitLights_[splitIndex];
  1255. Matrix3x4 lightView;
  1256. Matrix4 lightProj;
  1257. Frustum lightViewFrustum;
  1258. BoundingBox lightViewFrustumBox;
  1259. bool mergeBoxes = (light->GetLightType() != LIGHT_SPLITPOINT) && (light->GetShadowMap()) && (light->GetShadowFocus().focus_);
  1260. bool projectBoxes = false;
  1261. Camera* shadowCamera = light->GetShadowCamera();
  1262. if (shadowCamera)
  1263. {
  1264. bool projectBoxes = !shadowCamera->IsOrthographic();
  1265. lightView = shadowCamera->GetInverseWorldTransform();
  1266. lightProj = shadowCamera->GetProjection();
  1267. // Transform scene frustum into shadow camera's view space for shadow caster visibility check
  1268. // For point & spot lights, we can use the whole scene frustum. For directional lights, use the
  1269. // intersection of the scene frustum and the split frustum, so that shadow casters do not get
  1270. // rendered into unnecessary splits
  1271. if (light->GetLightType() != LIGHT_DIRECTIONAL)
  1272. lightViewFrustum = camera_->GetSplitFrustum(sceneViewBox_.min_.z_, sceneViewBox_.max_.z_).Transformed(lightView);
  1273. else
  1274. lightViewFrustum = camera_->GetSplitFrustum(Max(sceneViewBox_.min_.z_, light->GetNearSplit() - light->GetNearFadeRange()),
  1275. Min(sceneViewBox_.max_.z_, light->GetFarSplit())).Transformed(lightView);
  1276. lightViewFrustumBox.Define(lightViewFrustum);
  1277. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1278. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1279. GetShadowCasters = false;
  1280. }
  1281. else
  1282. GetShadowCasters = false;
  1283. BoundingBox lightViewBox;
  1284. BoundingBox lightProjBox;
  1285. for (unsigned i = 0; i < result.Size(); ++i)
  1286. {
  1287. Drawable* drawable = static_cast<Drawable*>(result[i]);
  1288. drawable->UpdateDistance(frame_);
  1289. bool boxGenerated = false;
  1290. // If draw distance non-zero, check it
  1291. float maxDistance = drawable->GetDrawDistance();
  1292. if ((maxDistance > 0.0f) && (drawable->GetDistance() > maxDistance))
  1293. continue;
  1294. // Check light mask
  1295. if (!(drawable->GetLightMask() & light->GetLightMask()))
  1296. continue;
  1297. // Get lit geometry only if inside main camera frustum this frame
  1298. if ((getLitGeometries) && (drawable->IsInView(frame_)))
  1299. {
  1300. if (mergeBoxes)
  1301. {
  1302. // Transform bounding box into light view space, and to projection space if needed
  1303. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1304. if (!projectBoxes)
  1305. geometryBox.Merge(lightViewBox);
  1306. else
  1307. {
  1308. lightProjBox = lightViewBox.Projected(lightProj);
  1309. geometryBox.Merge(lightProjBox);
  1310. }
  1311. boxGenerated = true;
  1312. }
  1313. litGeometries_[splitIndex].Push(drawable);
  1314. }
  1315. // Shadow caster need not be inside main camera frustum: in that case try to detect whether
  1316. // the shadow projection intersects the view
  1317. if ((GetShadowCasters) && (drawable->GetCastShadows()))
  1318. {
  1319. // If shadow distance non-zero, check it
  1320. float maxShadowDistance = drawable->GetShadowDistance();
  1321. if ((maxShadowDistance > 0.0f) && (drawable->GetDistance() > maxShadowDistance))
  1322. continue;
  1323. if (!boxGenerated)
  1324. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1325. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1326. {
  1327. if (mergeBoxes)
  1328. {
  1329. if (!projectBoxes)
  1330. shadowCasterBox.Merge(lightViewBox);
  1331. else
  1332. {
  1333. if (!boxGenerated)
  1334. lightProjBox = lightViewBox.Projected(lightProj);
  1335. shadowCasterBox.Merge(lightProjBox);
  1336. }
  1337. }
  1338. // Update geometry now if not updated yet
  1339. if (!drawable->IsInView(frame_))
  1340. {
  1341. drawable->MarkInShadowView(frame_);
  1342. drawable->UpdateGeometry(frame_);
  1343. }
  1344. shadowCasters_[splitIndex].Push(drawable);
  1345. }
  1346. }
  1347. }
  1348. }
  1349. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  1350. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  1351. {
  1352. // If shadow caster is also an occluder, must let it be visible, because it has potentially already culled
  1353. // away other shadow casters (could also check the actual shadow occluder vector, but that would be slower)
  1354. if (drawable->IsOccluder())
  1355. return true;
  1356. if (shadowCamera->IsOrthographic())
  1357. {
  1358. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  1359. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  1360. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1361. }
  1362. else
  1363. {
  1364. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  1365. if (drawable->IsInView(frame_))
  1366. return true;
  1367. // For perspective lights, extrusion direction depends on the position of the shadow caster
  1368. Vector3 center = lightViewBox.Center();
  1369. Ray extrusionRay(center, center.Normalized());
  1370. float extrusionDistance = shadowCamera->GetFarClip();
  1371. float originalDistance = Clamp(center.LengthFast(), M_EPSILON, extrusionDistance);
  1372. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  1373. float sizeFactor = extrusionDistance / originalDistance;
  1374. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  1375. // than necessary, so the test will be conservative
  1376. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  1377. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  1378. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  1379. lightViewBox.Merge(extrudedBox);
  1380. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1381. }
  1382. }
  1383. void View::SetupShadowCamera(Light* light, bool shadowOcclusion)
  1384. {
  1385. Camera* shadowCamera = light->GetShadowCamera();
  1386. Node* cameraNode = shadowCamera->GetNode();
  1387. const FocusParameters& parameters = light->GetShadowFocus();
  1388. // Reset zoom
  1389. shadowCamera->SetZoom(1.0f);
  1390. switch(light->GetLightType())
  1391. {
  1392. case LIGHT_DIRECTIONAL:
  1393. {
  1394. float extrusionDistance = camera_->GetFarClip();
  1395. // Calculate initial position & rotation
  1396. Vector3 lightWorldDirection = light->GetWorldRotation() * Vector3::FORWARD;
  1397. Vector3 pos = camera_->GetWorldPosition() - extrusionDistance * lightWorldDirection;
  1398. Quaternion rot(Vector3::FORWARD, lightWorldDirection);
  1399. cameraNode->SetTransform(pos, rot);
  1400. // Calculate main camera shadowed frustum in light's view space
  1401. float sceneMaxZ = camera_->GetFarClip();
  1402. // When shadow focusing is enabled, use the scene far Z to limit maximum frustum size
  1403. if ((shadowOcclusion) || (parameters.focus_))
  1404. sceneMaxZ = Min(sceneViewBox_.max_.z_, sceneMaxZ);
  1405. Matrix3x4 lightView(shadowCamera->GetInverseWorldTransform());
  1406. Frustum lightViewSplitFrustum = camera_->GetSplitFrustum(light->GetNearSplit() - light->GetNearFadeRange(),
  1407. Min(light->GetFarSplit(), sceneMaxZ)).Transformed(lightView);
  1408. // Fit the frustum inside a bounding box. If uniform size, use a sphere instead
  1409. BoundingBox shadowBox;
  1410. if ((!shadowOcclusion) && (parameters.nonUniform_))
  1411. shadowBox.Define(lightViewSplitFrustum);
  1412. else
  1413. {
  1414. Sphere shadowSphere;
  1415. shadowSphere.Define(lightViewSplitFrustum);
  1416. shadowBox.Define(shadowSphere);
  1417. }
  1418. shadowCamera->SetOrthographic(true);
  1419. shadowCamera->SetNearClip(0.0f);
  1420. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1421. // Center shadow camera on the bounding box, snap to whole texels
  1422. QuantizeDirShadowCamera(light, shadowBox);
  1423. }
  1424. break;
  1425. case LIGHT_SPOT:
  1426. case LIGHT_SPLITPOINT:
  1427. {
  1428. cameraNode->SetTransform(light->GetWorldPosition(), light->GetWorldRotation());
  1429. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1430. shadowCamera->SetFarClip(light->GetRange());
  1431. shadowCamera->SetOrthographic(false);
  1432. shadowCamera->SetFov(light->GetFov());
  1433. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1434. // For spot lights, zoom out shadowmap if far away (reduces fillrate)
  1435. if ((light->GetLightType() == LIGHT_SPOT) && (parameters.zoomOut_))
  1436. {
  1437. // Make sure the out-zooming does not start while we are inside the spot
  1438. float distance = Max((camera_->GetInverseWorldTransform() * light->GetWorldPosition()).z_ - light->GetRange(), 1.0f);
  1439. float lightPixels = (((float)height_ * light->GetRange() * camera_->GetZoom() * 0.5f) / distance);
  1440. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  1441. if (lightPixels < SHADOW_MIN_PIXELS)
  1442. lightPixels = SHADOW_MIN_PIXELS;
  1443. float zoolevel_ = Min(lightPixels / (float)light->GetShadowMap()->GetHeight(), 1.0f);
  1444. shadowCamera->SetZoom(zoolevel_);
  1445. }
  1446. }
  1447. break;
  1448. }
  1449. }
  1450. void View::FocusShadowCamera(Light* light, const BoundingBox& geometryBox, const BoundingBox& shadowCasterBox)
  1451. {
  1452. // If either no geometries or no shadow casters, do nothing
  1453. if ((!geometryBox.defined_) || (!shadowCasterBox.defined_))
  1454. return;
  1455. Camera* shadowCamera = light->GetShadowCamera();
  1456. const FocusParameters& parameters = light->GetShadowFocus();
  1457. switch (light->GetLightType())
  1458. {
  1459. case LIGHT_DIRECTIONAL:
  1460. {
  1461. BoundingBox combinedBox;
  1462. combinedBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1463. combinedBox.max_.x_ = shadowCamera->GetAspectRatio() * combinedBox.max_.y_;
  1464. combinedBox.min_.y_ = -combinedBox.max_.y_;
  1465. combinedBox.min_.x_ = -combinedBox.max_.x_;
  1466. combinedBox.Intersect(geometryBox);
  1467. combinedBox.Intersect(shadowCasterBox);
  1468. QuantizeDirShadowCamera(light, combinedBox);
  1469. }
  1470. break;
  1471. case LIGHT_SPOT:
  1472. // Can not move, but can zoom the shadow camera. Check for out-zooming (distant shadow map), do nothing in that case
  1473. if (shadowCamera->GetZoom() >= 1.0f)
  1474. {
  1475. BoundingBox combinedBox(-1.0f, 1.0f);
  1476. combinedBox.Intersect(geometryBox);
  1477. combinedBox.Intersect(shadowCasterBox);
  1478. float viewSizeX = Max(fabsf(combinedBox.min_.x_), fabsf(combinedBox.max_.x_));
  1479. float viewSizeY = Max(fabsf(combinedBox.min_.y_), fabsf(combinedBox.max_.y_));
  1480. float viewSize = Max(viewSizeX, viewSizeY);
  1481. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  1482. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  1483. float quantize = parameters.quantize_ * invOrthoSize;
  1484. float minView = parameters.minView_ * invOrthoSize;
  1485. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  1486. if (viewSize < 1.0f)
  1487. shadowCamera->SetZoom(1.0f / viewSize);
  1488. }
  1489. break;
  1490. }
  1491. }
  1492. void View::QuantizeDirShadowCamera(Light* light, const BoundingBox& viewBox)
  1493. {
  1494. Camera* shadowCamera = light->GetShadowCamera();
  1495. Node* cameraNode = shadowCamera->GetNode();
  1496. const FocusParameters& parameters = light->GetShadowFocus();
  1497. float minX = viewBox.min_.x_;
  1498. float minY = viewBox.min_.y_;
  1499. float maxX = viewBox.max_.x_;
  1500. float maxY = viewBox.max_.y_;
  1501. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  1502. Vector2 viewSize(maxX - minX, maxY - minY);
  1503. // Quantize size to reduce swimming
  1504. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  1505. if (parameters.nonUniform_)
  1506. {
  1507. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1508. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  1509. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1510. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  1511. }
  1512. else if (parameters.focus_)
  1513. {
  1514. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  1515. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1516. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1517. viewSize.y_ = viewSize.x_;
  1518. }
  1519. shadowCamera->SetOrthoSize(viewSize);
  1520. // Center shadow camera to the view space bounding box
  1521. Vector3 pos = shadowCamera->GetWorldPosition();
  1522. Quaternion rot = shadowCamera->GetWorldRotation();
  1523. Vector3 adjust(center.x_, center.y_, 0.0f);
  1524. cameraNode->Translate(rot * adjust);
  1525. // If there is a shadow map, snap to its whole texels
  1526. Texture2D* shadowMap = light->GetShadowMap();
  1527. if (shadowMap)
  1528. {
  1529. Vector3 viewPos(rot.Inverse() * shadowCamera->GetWorldPosition());
  1530. // Take into account that shadow map border will not be used
  1531. float invActualSize = 1.0f / (float)(shadowMap->GetWidth() - 2);
  1532. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  1533. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  1534. cameraNode->Translate(rot * snap);
  1535. }
  1536. }
  1537. void View::OptimizeLightByScissor(Light* light)
  1538. {
  1539. if (light)
  1540. graphics_->SetScissorTest(true, GetLightScissor(light));
  1541. else
  1542. graphics_->SetScissorTest(false);
  1543. }
  1544. const Rect& View::GetLightScissor(Light* light)
  1545. {
  1546. Map<Light*, Rect>::Iterator i = lightScissorCache_.Find(light);
  1547. if (i != lightScissorCache_.End())
  1548. return i->second_;
  1549. Matrix3x4 view(camera_->GetInverseWorldTransform());
  1550. Matrix4 projection(camera_->GetProjection());
  1551. switch (light->GetLightType())
  1552. {
  1553. case LIGHT_POINT:
  1554. {
  1555. BoundingBox viewBox = light->GetWorldBoundingBox().Transformed(view);
  1556. return lightScissorCache_[light] = viewBox.Projected(projection);
  1557. }
  1558. case LIGHT_SPOT:
  1559. case LIGHT_SPLITPOINT:
  1560. {
  1561. Frustum viewFrustum = light->GetFrustum().Transformed(view);
  1562. return lightScissorCache_[light] = viewFrustum.Projected(projection);
  1563. }
  1564. default:
  1565. return lightScissorCache_[light] = Rect::FULL;
  1566. }
  1567. }
  1568. unsigned View::SplitLight(Light* light)
  1569. {
  1570. LightType type = light->GetLightType();
  1571. if (type == LIGHT_DIRECTIONAL)
  1572. {
  1573. const CascadeParameters& cascade = light->GetShadowCascade();
  1574. unsigned splits = cascade.splits_;
  1575. if (splits > MAX_LIGHT_SPLITS - 1)
  1576. splits = MAX_LIGHT_SPLITS;
  1577. // Orthographic view actually has near clip 0, but clamp it to a theoretical minimum
  1578. float farClip = Min(cascade.shadowRange_, camera_->GetFarClip()); // Shadow range end
  1579. float nearClip = Max(camera_->GetNearClip(), M_MIN_NEARCLIP); // Shadow range start
  1580. bool CreateExtraSplit = farClip < camera_->GetFarClip();
  1581. // Practical split scheme (Zhang et al.)
  1582. unsigned i;
  1583. for (i = 0; i < splits; ++i)
  1584. {
  1585. // Set a minimum for the fade range to avoid boundary artifacts (missing lighting)
  1586. float splitFadeRange = Max(cascade.splitFadeRange_, 0.001f);
  1587. float iPerM = (float)i / (float)splits;
  1588. float log = nearClip * powf(farClip / nearClip, iPerM);
  1589. float uniform = nearClip + (farClip - nearClip) * iPerM;
  1590. float nearSplit = log * cascade.lambda_ + uniform * (1.0f - cascade.lambda_);
  1591. float nearFadeRange = nearSplit * splitFadeRange;
  1592. iPerM = (float)(i + 1) / (float)splits;
  1593. log = nearClip * powf(farClip / nearClip, iPerM);
  1594. uniform = nearClip + (farClip - nearClip) * iPerM;
  1595. float farSplit = log * cascade.lambda_ + uniform * (1.0f - cascade.lambda_);
  1596. float farFadeRange = farSplit * splitFadeRange;
  1597. // If split is completely beyond camera far clip, we are done
  1598. if ((nearSplit - nearFadeRange) > camera_->GetFarClip())
  1599. break;
  1600. Light* SplitLight = renderer_->CreateSplitLight(light);
  1601. splitLights_[i] = SplitLight;
  1602. // Though the near clip was previously clamped, use the real near clip value for the first split,
  1603. // so that there are no unlit portions
  1604. if (i)
  1605. SplitLight->SetNearSplit(nearSplit);
  1606. else
  1607. SplitLight->SetNearSplit(camera_->GetNearClip());
  1608. SplitLight->SetNearFadeRange(nearFadeRange);
  1609. SplitLight->SetFarSplit(farSplit);
  1610. // The final split will not fade
  1611. if ((CreateExtraSplit) || (i < splits - 1))
  1612. SplitLight->SetFarFadeRange(farFadeRange);
  1613. // Create an extra unshadowed split if necessary
  1614. if ((CreateExtraSplit) && (i == splits - 1))
  1615. {
  1616. Light* SplitLight = renderer_->CreateSplitLight(light);
  1617. splitLights_[i + 1] = SplitLight;
  1618. SplitLight->SetNearSplit(farSplit);
  1619. SplitLight->SetNearFadeRange(farFadeRange);
  1620. SplitLight->SetCastShadows(false);
  1621. }
  1622. }
  1623. if (CreateExtraSplit)
  1624. return i + 1;
  1625. else
  1626. return i;
  1627. }
  1628. if (type == LIGHT_POINT)
  1629. {
  1630. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1631. {
  1632. Light* SplitLight = renderer_->CreateSplitLight(light);
  1633. Node* lightNode = SplitLight->GetNode();
  1634. splitLights_[i] = SplitLight;
  1635. SplitLight->SetLightType(LIGHT_SPLITPOINT);
  1636. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1637. lightNode->SetDirection(directions[i]);
  1638. SplitLight->SetFov(90.0f);
  1639. SplitLight->SetAspectRatio(1.0f);
  1640. }
  1641. return MAX_CUBEMAP_FACES;
  1642. }
  1643. // A spot light does not actually need splitting. However, we may be rendering several views,
  1644. // and in some the light might be unshadowed, so better create an unique copy
  1645. Light* SplitLight = renderer_->CreateSplitLight(light);
  1646. splitLights_[0] = SplitLight;
  1647. return 1;
  1648. }
  1649. Technique* View::GetTechnique(Drawable* drawable, Material*& material)
  1650. {
  1651. if (!material)
  1652. material = renderer_->GetDefaultMaterial();
  1653. if (!material)
  1654. return 0;
  1655. float lodDistance = drawable->GetLodDistance();
  1656. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  1657. if (techniques.Empty())
  1658. return 0;
  1659. // Check for suitable technique. Techniques should be ordered like this:
  1660. // Most distant & highest quality
  1661. // Most distant & lowest quality
  1662. // Second most distant & highest quality
  1663. // ...
  1664. for (unsigned i = 0; i < techniques.Size(); ++i)
  1665. {
  1666. const TechniqueEntry& entry = techniques[i];
  1667. Technique* technique = entry.technique_;
  1668. if ((!technique) || ((technique->IsSM3()) && (!graphics_->GetSM3Support())) || (materialQuality_ < entry.qualityLevel_))
  1669. continue;
  1670. if (lodDistance >= entry.lodDistance_)
  1671. return technique;
  1672. }
  1673. // If no suitable technique found, fallback to the last
  1674. return techniques.Back().technique_;
  1675. }
  1676. void View::CheckMaterialForAuxView(Material* material)
  1677. {
  1678. const Vector<SharedPtr<Texture> >& textures = material->GetTextures();
  1679. for (unsigned i = 0; i < textures.Size(); ++i)
  1680. {
  1681. // Have to check cube & 2D textures separately
  1682. Texture* texture = textures[i];
  1683. if (texture)
  1684. {
  1685. if (texture->GetType() == Texture2D::GetTypeStatic())
  1686. {
  1687. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1688. RenderSurface* target = tex2D->GetRenderSurface();
  1689. if (target)
  1690. {
  1691. const Viewport& viewport = target->GetViewport();
  1692. if ((viewport.scene_) && (viewport.camera_))
  1693. renderer_->AddView(target, viewport);
  1694. }
  1695. }
  1696. else if (texture->GetType() == TextureCube::GetTypeStatic())
  1697. {
  1698. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1699. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1700. {
  1701. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  1702. if (target)
  1703. {
  1704. const Viewport& viewport = target->GetViewport();
  1705. if ((viewport.scene_) && (viewport.camera_))
  1706. renderer_->AddView(target, viewport);
  1707. }
  1708. }
  1709. }
  1710. }
  1711. }
  1712. // Set frame number so that we can early-out next time we come across this material on the same frame
  1713. material->MarkForAuxView(frame_.frameNumber_);
  1714. }
  1715. void View::SortBatches()
  1716. {
  1717. PROFILE(SortBatches);
  1718. if (mode_ != RENDER_FORWARD)
  1719. {
  1720. gBufferQueue_.SortFrontToBack();
  1721. noShadowLightQueue_.SortFrontToBack();
  1722. }
  1723. baseQueue_.SortFrontToBack();
  1724. extraQueue_.SortFrontToBack();
  1725. transparentQueue_.SortBackToFront();
  1726. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1727. {
  1728. lightQueues_[i].shadowBatches_.SortFrontToBack();
  1729. lightQueues_[i].litBatches_.SortFrontToBack();
  1730. }
  1731. }
  1732. void View::PrepareInstancingBuffer()
  1733. {
  1734. PROFILE(PrepareInstancingBuffer);
  1735. unsigned totalInstances = 0;
  1736. if (mode_ != RENDER_FORWARD)
  1737. totalInstances += gBufferQueue_.GetNumInstances();
  1738. totalInstances += baseQueue_.GetNumInstances();
  1739. totalInstances += extraQueue_.GetNumInstances();
  1740. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1741. {
  1742. totalInstances += lightQueues_[i].shadowBatches_.GetNumInstances();
  1743. totalInstances += lightQueues_[i].litBatches_.GetNumInstances();
  1744. }
  1745. // If fail to set buffer size, fall back to per-group locking
  1746. if ((totalInstances) && (renderer_->ResizeInstancingBuffer(totalInstances)))
  1747. {
  1748. unsigned freeIndex = 0;
  1749. void* lockedData = renderer_->instancingBuffer_->Lock(0, totalInstances, LOCK_DISCARD);
  1750. if (lockedData)
  1751. {
  1752. if (mode_ != RENDER_FORWARD)
  1753. gBufferQueue_.SetTransforms(lockedData, freeIndex);
  1754. baseQueue_.SetTransforms(lockedData, freeIndex);
  1755. extraQueue_.SetTransforms(lockedData, freeIndex);
  1756. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1757. {
  1758. lightQueues_[i].shadowBatches_.SetTransforms(lockedData, freeIndex);
  1759. lightQueues_[i].litBatches_.SetTransforms(lockedData, freeIndex);
  1760. }
  1761. renderer_->instancingBuffer_->Unlock();
  1762. }
  1763. }
  1764. }
  1765. void View::CalculateShaderParameters()
  1766. {
  1767. Time* time = GetSubsystem<Time>();
  1768. float fogStart = zone_->GetFogStart();
  1769. float fogEnd = zone_->GetFogEnd();
  1770. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  1771. float farClip = camera_->GetFarClip();
  1772. float nearClip = camera_->GetNearClip();
  1773. Vector4 fogParams(fogStart / farClip, fogEnd / farClip, 1.0f / (fogRange / farClip), 0.0f);
  1774. Vector4 elapsedTime((time->GetTotalMSec() & 0x3fffff) / 1000.0f, 0.0f, 0.0f, 0.0f);
  1775. shaderParameters_.Clear();
  1776. shaderParameters_[VSP_ELAPSEDTIME] = elapsedTime;
  1777. shaderParameters_[PSP_AMBIENTCOLOR] = zone_->GetAmbientColor().ToVector4();
  1778. shaderParameters_[PSP_ELAPSEDTIME] = elapsedTime;
  1779. shaderParameters_[PSP_FOGCOLOR] = zone_->GetFogColor().ToVector4(),
  1780. shaderParameters_[PSP_FOGPARAMS] = fogParams;
  1781. }
  1782. void View::DrawSplitLightToStencil(Camera& camera, Light* light, bool clear)
  1783. {
  1784. graphics_->ClearTransformSources();
  1785. Matrix3x4 view(camera.GetInverseWorldTransform());
  1786. switch (light->GetLightType())
  1787. {
  1788. case LIGHT_SPLITPOINT:
  1789. if (!clear)
  1790. {
  1791. Matrix4 projection(camera.GetProjection());
  1792. const Matrix3x4& model = light->GetVolumeTransform(camera);
  1793. float lightExtent = light->GetVolumeExtent();
  1794. float lightViewDist = (light->GetWorldPosition() - camera.GetWorldPosition()).LengthFast();
  1795. bool drawBackFaces = lightViewDist < (lightExtent + camera.GetNearClip());
  1796. graphics_->SetAlphaTest(false);
  1797. graphics_->SetColorWrite(false);
  1798. graphics_->SetDepthWrite(false);
  1799. graphics_->SetCullMode(drawBackFaces ? CULL_CW : CULL_CCW);
  1800. graphics_->SetDepthTest(drawBackFaces ? CMP_GREATER : CMP_LESS);
  1801. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1802. graphics_->SetShaderParameter(VSP_MODEL, model);
  1803. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1804. // Draw the faces to stencil which we should draw (where no light has not been rendered yet)
  1805. graphics_->SetStencilTest(true, CMP_EQUAL, OP_INCR, OP_KEEP, OP_KEEP, 0);
  1806. renderer_->spotLightGeometry_->Draw(graphics_);
  1807. // Draw the other faces to stencil to mark where we should not draw ("frees up" the pixels for other faces)
  1808. graphics_->SetCullMode(drawBackFaces ? CULL_CCW : CULL_CW);
  1809. graphics_->SetStencilTest(true, CMP_EQUAL, OP_DECR, OP_KEEP, OP_KEEP, 1);
  1810. renderer_->spotLightGeometry_->Draw(graphics_);
  1811. // Now set stencil test for rendering the lit geometries (also marks the pixels so that they will not be used again)
  1812. graphics_->SetStencilTest(true, CMP_EQUAL, OP_INCR, OP_KEEP, OP_KEEP, 1);
  1813. graphics_->SetColorWrite(true);
  1814. }
  1815. else
  1816. {
  1817. // Clear stencil with a scissored clear operation
  1818. OptimizeLightByScissor(light->GetOriginalLight());
  1819. graphics_->Clear(CLEAR_STENCIL);
  1820. graphics_->SetScissorTest(false);
  1821. graphics_->SetStencilTest(false);
  1822. }
  1823. break;
  1824. case LIGHT_DIRECTIONAL:
  1825. // If light encompasses whole frustum, no drawing to frustum necessary
  1826. if ((light->GetNearSplit() <= camera.GetNearClip()) && (light->GetFarSplit() >= camera.GetFarClip()))
  1827. return;
  1828. else
  1829. {
  1830. if (!clear)
  1831. {
  1832. // Get projection without jitter offset to ensure the whole screen is filled
  1833. Matrix4 projection(camera.GetProjection(false));
  1834. Matrix3x4 nearTransform(light->GetDirLightTransform(camera, true));
  1835. Matrix3x4 farTransform(light->GetDirLightTransform(camera, false));
  1836. graphics_->SetAlphaTest(false);
  1837. graphics_->SetColorWrite(false);
  1838. graphics_->SetDepthWrite(false);
  1839. graphics_->SetCullMode(CULL_NONE);
  1840. // If the split begins at the near plane (first split), draw at split far plane
  1841. if (light->GetNearSplit() <= camera.GetNearClip())
  1842. {
  1843. graphics_->SetDepthTest(CMP_GREATEREQUAL);
  1844. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1845. graphics_->SetShaderParameter(VSP_MODEL, farTransform);
  1846. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1847. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_ZERO, OP_ZERO, 1);
  1848. }
  1849. // Otherwise draw at split near plane
  1850. else
  1851. {
  1852. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1853. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1854. graphics_->SetShaderParameter(VSP_MODEL, nearTransform);
  1855. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1856. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_ZERO, OP_ZERO, 1);
  1857. }
  1858. renderer_->dirLightGeometry_->Draw(graphics_);
  1859. graphics_->SetColorWrite(true);
  1860. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 1);
  1861. }
  1862. else
  1863. {
  1864. // Clear the whole stencil
  1865. graphics_->SetScissorTest(false);
  1866. graphics_->Clear(CLEAR_STENCIL);
  1867. graphics_->SetStencilTest(false);
  1868. }
  1869. }
  1870. break;
  1871. }
  1872. }
  1873. void View::RenderBatchQueue(const BatchQueue& queue, bool useScissor, bool useLightBuffer, bool disableScissor)
  1874. {
  1875. Texture2D* diffBuffer = 0;
  1876. VertexBuffer* instancingBuffer = 0;
  1877. if (useLightBuffer)
  1878. diffBuffer = graphics_->GetDiffBuffer();
  1879. if (renderer_->GetDynamicInstancing())
  1880. instancingBuffer = renderer_->instancingBuffer_;
  1881. if (disableScissor)
  1882. graphics_->SetScissorTest(false);
  1883. graphics_->SetStencilTest(false);
  1884. // Priority instanced
  1885. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.priorityBatchGroups_.Begin(); i !=
  1886. queue.priorityBatchGroups_.End(); ++i)
  1887. {
  1888. const BatchGroup& group = i->second_;
  1889. if ((useLightBuffer) && (!group.light_))
  1890. graphics_->SetTexture(TU_LIGHTBUFFER, diffBuffer);
  1891. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1892. }
  1893. // Priority non-instanced
  1894. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1895. {
  1896. Batch* batch = *i;
  1897. if ((useLightBuffer) && (!batch->light_))
  1898. graphics_->SetTexture(TU_LIGHTBUFFER, diffBuffer);
  1899. batch->Draw(graphics_, shaderParameters_);
  1900. }
  1901. // Non-priority instanced
  1902. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.batchGroups_.Begin(); i !=
  1903. queue.batchGroups_.End(); ++i)
  1904. {
  1905. const BatchGroup& group = i->second_;
  1906. if ((useScissor) && (group.light_))
  1907. OptimizeLightByScissor(group.light_);
  1908. else
  1909. graphics_->SetScissorTest(false);
  1910. if ((useLightBuffer) && (!group.light_))
  1911. graphics_->SetTexture(TU_LIGHTBUFFER, diffBuffer);
  1912. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1913. }
  1914. // Non-priority non-instanced
  1915. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1916. {
  1917. Batch* batch = *i;
  1918. // For the transparent queue, both priority and non-priority batches are copied here, so check the flag
  1919. if ((useScissor) && (batch->light_) && (!batch->hasPriority_))
  1920. OptimizeLightByScissor(batch->light_);
  1921. else
  1922. graphics_->SetScissorTest(false);
  1923. if ((useLightBuffer) && (!batch->light_))
  1924. graphics_->SetTexture(TU_LIGHTBUFFER, diffBuffer);
  1925. batch->Draw(graphics_, shaderParameters_);
  1926. }
  1927. }
  1928. void View::RenderForwardLightBatchQueue(const BatchQueue& queue, Light* light)
  1929. {
  1930. VertexBuffer* instancingBuffer = 0;
  1931. if (renderer_->GetDynamicInstancing())
  1932. instancingBuffer = renderer_->instancingBuffer_;
  1933. graphics_->SetScissorTest(false);
  1934. graphics_->SetStencilTest(false);
  1935. // Priority instanced
  1936. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.priorityBatchGroups_.Begin(); i !=
  1937. queue.priorityBatchGroups_.End(); ++i)
  1938. {
  1939. const BatchGroup& group = i->second_;
  1940. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1941. }
  1942. // Priority non-instanced
  1943. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1944. {
  1945. Batch* batch = *i;
  1946. batch->Draw(graphics_, shaderParameters_);
  1947. }
  1948. // All base passes have been drawn. Optimize at this point by both scissor and stencil
  1949. if (light)
  1950. {
  1951. OptimizeLightByScissor(light);
  1952. LightType type = light->GetLightType();
  1953. if ((type == LIGHT_SPLITPOINT) || (type == LIGHT_DIRECTIONAL))
  1954. DrawSplitLightToStencil(*camera_, light);
  1955. }
  1956. // Non-priority instanced
  1957. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.batchGroups_.Begin(); i !=
  1958. queue.batchGroups_.End(); ++i)
  1959. {
  1960. const BatchGroup& group = i->second_;
  1961. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1962. }
  1963. // Non-priority non-instanced
  1964. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1965. {
  1966. Batch* batch = *i;
  1967. batch->Draw(graphics_, shaderParameters_);
  1968. }
  1969. }
  1970. void View::RenderShadowMap(const LightBatchQueue& queue)
  1971. {
  1972. PROFILE(RenderShadowMap);
  1973. Texture2D* shadowMap = queue.light_->GetShadowMap();
  1974. graphics_->ClearLastParameterSources();
  1975. graphics_->SetColorWrite(false);
  1976. graphics_->SetStencilTest(false);
  1977. graphics_->SetTexture(TU_SHADOWMAP, 0);
  1978. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  1979. graphics_->SetDepthStencil(shadowMap);
  1980. graphics_->Clear(CLEAR_DEPTH);
  1981. // Set shadow depth bias
  1982. BiasParameters parameters = queue.light_->GetShadowBias();
  1983. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  1984. // Set a scissor rectangle to match possible shadow map size reduction by out-zooming
  1985. // However, do not do this for point lights
  1986. if (queue.light_->GetLightType() != LIGHT_SPLITPOINT)
  1987. {
  1988. float zoom = Min(queue.light_->GetShadowCamera()->GetZoom(),
  1989. (float)(shadowMap->GetWidth() - 2) / (float)shadowMap->GetWidth());
  1990. Rect zoomRect(Vector2(-1.0f, -1.0f) * zoom, Vector2(1.0f, 1.0f) * zoom);
  1991. graphics_->SetScissorTest(true, zoomRect, false);
  1992. }
  1993. else
  1994. graphics_->SetScissorTest(false);
  1995. // Draw instanced and non-instanced shadow casters
  1996. RenderBatchQueue(queue.shadowBatches_, false, false, false);
  1997. graphics_->SetColorWrite(true);
  1998. graphics_->SetDepthBias(0.0f, 0.0f);
  1999. }