View.cpp 89 KB

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