View.cpp 95 KB

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