View.cpp 89 KB

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