View.cpp 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "DebugRenderer.h"
  26. #include "Geometry.h"
  27. #include "Graphics.h"
  28. #include "Light.h"
  29. #include "Log.h"
  30. #include "Material.h"
  31. #include "OcclusionBuffer.h"
  32. #include "Octree.h"
  33. #include "OctreeQuery.h"
  34. #include "Renderer.h"
  35. #include "Profiler.h"
  36. #include "Scene.h"
  37. #include "ShaderVariation.h"
  38. #include "Sort.h"
  39. #include "Technique.h"
  40. #include "Texture2D.h"
  41. #include "TextureCube.h"
  42. #include "VertexBuffer.h"
  43. #include "View.h"
  44. #include "WorkQueue.h"
  45. #include "Zone.h"
  46. #include "DebugNew.h"
  47. static const Vector3 directions[] =
  48. {
  49. Vector3(1.0f, 0.0f, 0.0f),
  50. Vector3(-1.0f, 0.0f, 0.0f),
  51. Vector3(0.0f, 1.0f, 0.0f),
  52. Vector3(0.0f, -1.0f, 0.0f),
  53. Vector3(0.0f, 0.0f, 1.0f),
  54. Vector3(0.0f, 0.0f, -1.0f)
  55. };
  56. void UpdateDrawableGeometriesWork(const WorkItem* item, unsigned threadIndex)
  57. {
  58. const FrameInfo& frame = *(reinterpret_cast<FrameInfo*>(item->aux_));
  59. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  60. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  61. while (start != end)
  62. {
  63. Drawable* drawable = *start;
  64. drawable->UpdateGeometry(frame);
  65. ++start;
  66. }
  67. }
  68. void SortBatchQueueFrontToBackWork(const WorkItem* item, unsigned threadIndex)
  69. {
  70. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  71. queue->SortFrontToBack();
  72. }
  73. void SortBatchQueueBackToFrontWork(const WorkItem* item, unsigned threadIndex)
  74. {
  75. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  76. queue->SortBackToFront();
  77. }
  78. void SortLightQueuesWork(const WorkItem* item, unsigned threadIndex)
  79. {
  80. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  81. LightBatchQueue* end = reinterpret_cast<LightBatchQueue*>(item->end_);
  82. while (start != end)
  83. {
  84. for (unsigned i = 0; i < start->shadowSplits_.Size(); ++i)
  85. start->shadowSplits_[i].shadowBatches_.SortFrontToBack();
  86. start->litBatches_.SortFrontToBack();
  87. ++start;
  88. }
  89. }
  90. OBJECTTYPESTATIC(View);
  91. View::View(Context* context) :
  92. Object(context),
  93. graphics_(GetSubsystem<Graphics>()),
  94. renderer_(GetSubsystem<Renderer>()),
  95. octree_(0),
  96. camera_(0),
  97. cameraZone_(0),
  98. farClipZone_(0),
  99. renderTarget_(0),
  100. depthStencil_(0)
  101. {
  102. frame_.camera_ = 0;
  103. }
  104. View::~View()
  105. {
  106. }
  107. bool View::Define(RenderSurface* renderTarget, const Viewport& viewport)
  108. {
  109. if (!viewport.scene_ || !viewport.camera_)
  110. return false;
  111. // If scene is loading asynchronously, it is incomplete and should not be rendered
  112. if (viewport.scene_->IsAsyncLoading())
  113. return false;
  114. Octree* octree = viewport.scene_->GetComponent<Octree>();
  115. if (!octree)
  116. return false;
  117. octree_ = octree;
  118. camera_ = viewport.camera_;
  119. renderTarget_ = renderTarget;
  120. if (!renderTarget)
  121. depthStencil_ = 0;
  122. else
  123. depthStencil_ = renderTarget->GetLinkedDepthBuffer();
  124. // Validate the rect and calculate size. If zero rect, use whole render target size
  125. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  126. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  127. if (viewport.rect_ != IntRect::ZERO)
  128. {
  129. screenRect_.left_ = Clamp(viewport.rect_.left_, 0, rtWidth - 1);
  130. screenRect_.top_ = Clamp(viewport.rect_.top_, 0, rtHeight - 1);
  131. screenRect_.right_ = Clamp(viewport.rect_.right_, screenRect_.left_ + 1, rtWidth);
  132. screenRect_.bottom_ = Clamp(viewport.rect_.bottom_, screenRect_.top_ + 1, rtHeight);
  133. }
  134. else
  135. screenRect_ = IntRect(0, 0, rtWidth, rtHeight);
  136. width_ = screenRect_.right_ - screenRect_.left_;
  137. height_ = screenRect_.bottom_ - screenRect_.top_;
  138. // Set possible quality overrides from the camera
  139. drawShadows_ = renderer_->GetDrawShadows();
  140. materialQuality_ = renderer_->GetMaterialQuality();
  141. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  142. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  143. if (viewOverrideFlags & VO_LOW_MATERIAL_QUALITY)
  144. materialQuality_ = QUALITY_LOW;
  145. if (viewOverrideFlags & VO_DISABLE_SHADOWS)
  146. drawShadows_ = false;
  147. if (viewOverrideFlags & VO_DISABLE_OCCLUSION)
  148. maxOccluderTriangles_ = 0;
  149. return true;
  150. }
  151. void View::Update(const FrameInfo& frame)
  152. {
  153. if (!camera_ || !octree_)
  154. return;
  155. frame_.camera_ = camera_;
  156. frame_.timeStep_ = frame.timeStep_;
  157. frame_.frameNumber_ = frame.frameNumber_;
  158. frame_.viewSize_ = IntVector2(width_, height_);
  159. // Clear old light scissor cache, geometry, light, occluder & batch lists
  160. lightScissorCache_.Clear();
  161. geometries_.Clear();
  162. allGeometries_.Clear();
  163. geometryDepthBounds_.Clear();
  164. lights_.Clear();
  165. occluders_.Clear();
  166. shadowOccluders_.Clear();
  167. baseQueue_.Clear();
  168. preAlphaQueue_.Clear();
  169. alphaQueue_.Clear();
  170. postAlphaQueue_.Clear();
  171. lightQueues_.Clear();
  172. // Do not update if camera projection is illegal
  173. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  174. if (!camera_->IsProjectionValid())
  175. return;
  176. // Set automatic aspect ratio if required
  177. if (camera_->GetAutoAspectRatio())
  178. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  179. // Cache the camera frustum to avoid recalculating it constantly
  180. frustum_ = camera_->GetFrustum();
  181. // Reset shadow map allocations; they can be reused between views as each is rendered completely at a time
  182. renderer_->ResetShadowMapAllocations();
  183. GetDrawables();
  184. GetBatches();
  185. UpdateGeometries();
  186. }
  187. void View::Render()
  188. {
  189. if (!octree_ || !camera_)
  190. return;
  191. // Forget parameter sources from the previous view
  192. graphics_->ClearParameterSources();
  193. // If stream offset is supported, write all instance transforms to a single large buffer
  194. // Else we must lock the instance buffer for each batch group
  195. if (renderer_->GetDynamicInstancing() && graphics_->GetStreamOffsetSupport())
  196. PrepareInstancingBuffer();
  197. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  198. // again to ensure correct projection will be used
  199. if (camera_->GetAutoAspectRatio())
  200. camera_->SetAspectRatio((float)(screenRect_.right_ - screenRect_.left_) / (float)(screenRect_.bottom_ - screenRect_.top_));
  201. graphics_->SetColorWrite(true);
  202. graphics_->SetFillMode(FILL_SOLID);
  203. // Bind the face selection and indirection cube maps for point light shadows
  204. graphics_->SetTexture(TU_FACESELECT, renderer_->GetFaceSelectCubeMap());
  205. graphics_->SetTexture(TU_INDIRECTION, renderer_->GetIndirectionCubeMap());
  206. // Reset the light optimization stencil reference value
  207. lightStencilValue_ = 1;
  208. // Render
  209. RenderBatches();
  210. graphics_->SetScissorTest(false);
  211. graphics_->SetStencilTest(false);
  212. graphics_->ResetStreamFrequencies();
  213. // If this is a main view, draw the associated debug geometry now
  214. if (!renderTarget_)
  215. {
  216. Scene* scene = static_cast<Scene*>(octree_->GetNode());
  217. if (scene)
  218. {
  219. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  220. if (debug)
  221. {
  222. debug->SetView(camera_);
  223. debug->Render();
  224. }
  225. }
  226. }
  227. // "Forget" the camera, octree and zone after rendering
  228. camera_ = 0;
  229. octree_ = 0;
  230. cameraZone_ = 0;
  231. farClipZone_ = 0;
  232. frame_.camera_ = 0;
  233. }
  234. void View::GetDrawables()
  235. {
  236. int highestZonePriority = M_MIN_INT;
  237. {
  238. PROFILE(GetZones);
  239. // Get default zone first in case we do not have zones defined
  240. Zone* defaultZone = renderer_->GetDefaultZone();
  241. cameraZone_ = farClipZone_ = defaultZone;
  242. FrustumOctreeQuery query(reinterpret_cast<PODVector<Drawable*>&>(zones_), frustum_, DRAWABLE_ZONE);
  243. octree_->GetDrawables(query);
  244. // Find the visible zones, and the zone the camera is in. Determine also the highest zone priority to aid in seeing
  245. // whether a zone query result for a drawable is conclusive
  246. int bestPriority = M_MIN_INT;
  247. Vector3 cameraPos = camera_->GetWorldPosition();
  248. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  249. {
  250. int priority = (*i)->GetPriority();
  251. if (priority > highestZonePriority)
  252. highestZonePriority = priority;
  253. if ((*i)->IsInside(cameraPos) && priority > bestPriority)
  254. {
  255. cameraZone_ = *i;
  256. bestPriority = priority;
  257. }
  258. }
  259. // Determine the zone at far clip distance. If not found, or camera zone has override mode, use camera zone
  260. cameraZoneOverride_ = cameraZone_->GetOverride();
  261. if (!cameraZoneOverride_)
  262. {
  263. Vector3 farClipPos = cameraPos + camera_->GetNode()->GetWorldDirection() * Vector3(0, 0, camera_->GetFarClip());
  264. bestPriority = M_MIN_INT;
  265. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  266. {
  267. int priority = (*i)->GetPriority();
  268. if ((*i)->IsInside(farClipPos) && priority > bestPriority)
  269. {
  270. farClipZone_ = *i;
  271. bestPriority = priority;
  272. }
  273. }
  274. }
  275. if (farClipZone_ == defaultZone)
  276. farClipZone_ = cameraZone_;
  277. }
  278. {
  279. PROFILE(GetDrawables);
  280. // If occlusion in use, get & render the occluders, then build the depth buffer hierarchy
  281. OcclusionBuffer* buffer = 0;
  282. if (maxOccluderTriangles_ > 0)
  283. {
  284. FrustumOctreeQuery query(occluders_, frustum_, DRAWABLE_GEOMETRY, camera_->GetViewMask(), true, false);
  285. octree_->GetDrawables(query);
  286. UpdateOccluders(occluders_, camera_);
  287. if (occluders_.Size())
  288. {
  289. buffer = renderer_->GetOrCreateOcclusionBuffer(camera_, maxOccluderTriangles_);
  290. DrawOccluders(buffer, occluders_);
  291. buffer->BuildDepthHierarchy();
  292. }
  293. }
  294. if (!buffer)
  295. {
  296. // Get geometries & lights without occlusion
  297. FrustumOctreeQuery query(tempDrawables_, frustum_, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  298. octree_->GetDrawables(query);
  299. }
  300. else
  301. {
  302. // Get geometries & lights using occlusion
  303. OccludedFrustumOctreeQuery query(tempDrawables_, frustum_, buffer, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT,
  304. camera_->GetViewMask());
  305. octree_->GetDrawables(query);
  306. }
  307. // Add unculled geometries & lights
  308. octree_->GetUnculledDrawables(tempDrawables_, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  309. // Sort into geometries & lights, and build visible scene bounding boxes in world and view space
  310. sceneBox_.min_ = sceneBox_.max_ = Vector3::ZERO;
  311. sceneBox_.defined_ = false;
  312. sceneViewBox_.min_ = sceneViewBox_.max_ = Vector3::ZERO;
  313. sceneViewBox_.defined_ = false;
  314. Matrix3x4 view(camera_->GetInverseWorldTransform());
  315. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  316. {
  317. Drawable* drawable = tempDrawables_[i];
  318. drawable->UpdateDistance(frame_);
  319. // If draw distance non-zero, check it
  320. float maxDistance = drawable->GetDrawDistance();
  321. if (maxDistance > 0.0f && drawable->GetDistance() > maxDistance)
  322. continue;
  323. unsigned flags = drawable->GetDrawableFlags();
  324. if (flags & DRAWABLE_GEOMETRY)
  325. {
  326. // Find new zone for the drawable if necessary
  327. if (!drawable->GetZone() && !cameraZoneOverride_)
  328. FindZone(drawable, highestZonePriority);
  329. drawable->ClearLights();
  330. drawable->MarkInView(frame_);
  331. // Expand the scene bounding boxes. However, do not take "infinite" objects such as the skybox into account,
  332. // as the bounding boxes are also used for shadow focusing
  333. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  334. BoundingBox geomViewBox = geomBox.Transformed(view);
  335. if (geomBox.Size().LengthFast() < M_LARGE_VALUE)
  336. {
  337. sceneBox_.Merge(geomBox);
  338. sceneViewBox_.Merge(geomViewBox);
  339. }
  340. // Store depth info for split directional light queries
  341. GeometryDepthBounds bounds;
  342. bounds.min_ = geomViewBox.min_.z_;
  343. bounds.max_ = geomViewBox.max_.z_;
  344. geometryDepthBounds_.Push(bounds);
  345. geometries_.Push(drawable);
  346. allGeometries_.Push(drawable);
  347. }
  348. else if (flags & DRAWABLE_LIGHT)
  349. {
  350. Light* light = static_cast<Light*>(drawable);
  351. light->MarkInView(frame_);
  352. lights_.Push(light);
  353. }
  354. }
  355. // Sort the lights to brightest/closest first
  356. for (unsigned i = 0; i < lights_.Size(); ++i)
  357. {
  358. Light* light = lights_[i];
  359. light->SetIntensitySortValue(camera_->GetDistance(light->GetWorldPosition()));
  360. }
  361. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  362. }
  363. }
  364. void View::GetBatches()
  365. {
  366. maxLightsDrawables_.Clear();
  367. lightQueueIndex_.Clear();
  368. bool fallback = graphics_->GetFallback();
  369. // Go through lights
  370. {
  371. PROFILE_MULTIPLE(GetLightBatches, lights_.Size());
  372. // Preallocate enough light queues so that we can store pointers to them without having to worry about the
  373. // vector reallocating itself
  374. lightQueues_.Resize(lights_.Size());
  375. unsigned lightQueueCount = 0;
  376. for (unsigned i = 0; i < lights_.Size(); ++i)
  377. {
  378. Light* light = lights_[i];
  379. unsigned shadowSplits = ProcessLight(light);
  380. if (litGeometries_.Empty())
  381. continue;
  382. // Initialize light queue. Store pointer-to-index mapping so that the queue can be found later
  383. LightBatchQueue& lightQueue = lightQueues_[lightQueueCount];
  384. lightQueueIndex_[light] = lightQueueCount;
  385. lightQueue.light_ = light;
  386. lightQueue.litBatches_.Clear();
  387. // Allocate shadow map now
  388. lightQueue.shadowMap_ = 0;
  389. if (shadowSplits > 0)
  390. {
  391. lightQueue.shadowMap_ = renderer_->GetShadowMap(light, camera_, width_, height_);
  392. // If did not manage to get a shadow map, convert the light to unshadowed
  393. if (!lightQueue.shadowMap_)
  394. shadowSplits = 0;
  395. }
  396. // Setup shadow batch queues
  397. lightQueue.shadowSplits_.Resize(shadowSplits);
  398. for (unsigned j = 0; j < shadowSplits; ++j)
  399. {
  400. ShadowBatchQueue& shadowQueue = lightQueue.shadowSplits_[j];
  401. Camera* shadowCamera = shadowCameras_[j];
  402. shadowQueue.shadowCamera_ = shadowCameras_[j];
  403. shadowQueue.nearSplit_ = shadowNearSplits_[j];
  404. shadowQueue.farSplit_ = shadowFarSplits_[j];
  405. // Setup the shadow split viewport and finalize shadow camera parameters
  406. shadowQueue.shadowViewport_ = GetShadowMapViewport(light, j, lightQueue.shadowMap_);
  407. FinalizeShadowCamera(shadowCamera, light, shadowQueue.shadowViewport_, shadowCasterBox_[j]);
  408. // Loop through shadow casters
  409. for (unsigned k = 0; k < shadowCasters_[j].Size(); ++k)
  410. {
  411. Drawable* drawable = shadowCasters_[j][k];
  412. unsigned numBatches = drawable->GetNumBatches();
  413. for (unsigned l = 0; l < numBatches; ++l)
  414. {
  415. Batch shadowBatch;
  416. drawable->GetBatch(shadowBatch, frame_, l);
  417. Technique* tech = GetTechnique(drawable, shadowBatch.material_);
  418. if (!shadowBatch.geometry_ || !tech)
  419. continue;
  420. Pass* pass = tech->GetPass(PASS_SHADOW);
  421. // Skip if material has no shadow pass
  422. if (!pass)
  423. continue;
  424. // Fill the rest of the batch
  425. shadowBatch.camera_ = shadowCamera;
  426. shadowBatch.lightQueue_ = &lightQueue;
  427. FinalizeBatch(shadowBatch, tech, pass);
  428. shadowQueue.shadowBatches_.AddBatch(shadowBatch);
  429. }
  430. }
  431. }
  432. // Loop through lit geometries
  433. for (unsigned j = 0; j < litGeometries_.Size(); ++j)
  434. {
  435. Drawable* drawable = litGeometries_[j];
  436. drawable->AddLight(light);
  437. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  438. if (!drawable->GetMaxLights())
  439. GetLitBatches(drawable, lightQueue);
  440. else
  441. maxLightsDrawables_.Insert(drawable);
  442. }
  443. ++lightQueueCount;
  444. }
  445. // Resize the light queue vector now that final size is known
  446. lightQueues_.Resize(lightQueueCount);
  447. }
  448. // Process drawables with limited light count
  449. if (maxLightsDrawables_.Size())
  450. {
  451. PROFILE(GetMaxLightsBatches);
  452. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  453. {
  454. Drawable* drawable = *i;
  455. drawable->LimitLights();
  456. const PODVector<Light*>& lights = drawable->GetLights();
  457. for (unsigned i = 0; i < lights.Size(); ++i)
  458. {
  459. Light* light = lights[i];
  460. // Find the correct light queue again
  461. Map<Light*, unsigned>::Iterator j = lightQueueIndex_.Find(light);
  462. if (j != lightQueueIndex_.End())
  463. GetLitBatches(drawable, lightQueues_[j->second_]);
  464. }
  465. }
  466. }
  467. // Go through geometries for base pass batches
  468. {
  469. PROFILE(GetBaseBatches);
  470. for (unsigned i = 0; i < geometries_.Size(); ++i)
  471. {
  472. Drawable* drawable = geometries_[i];
  473. unsigned numBatches = drawable->GetNumBatches();
  474. for (unsigned j = 0; j < numBatches; ++j)
  475. {
  476. Batch baseBatch;
  477. drawable->GetBatch(baseBatch, frame_, j);
  478. Technique* tech = GetTechnique(drawable, baseBatch.material_);
  479. if (!baseBatch.geometry_ || !tech)
  480. continue;
  481. // Check here if the material technique refers to a render target texture with camera(s) attached
  482. // Only check this for the main view (null rendertarget)
  483. if (!renderTarget_ && baseBatch.material_ && baseBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_)
  484. CheckMaterialForAuxView(baseBatch.material_);
  485. // If object already has a lit base pass, can skip the unlit base pass
  486. if (drawable->HasBasePass(j))
  487. continue;
  488. // Fill the rest of the batch
  489. baseBatch.camera_ = camera_;
  490. baseBatch.zone_ = GetZone(drawable);
  491. baseBatch.isBase_ = true;
  492. Pass* pass = 0;
  493. // Check for unlit base pass
  494. pass = tech->GetPass(PASS_BASE);
  495. if (pass)
  496. {
  497. if (pass->GetBlendMode() == BLEND_REPLACE)
  498. {
  499. FinalizeBatch(baseBatch, tech, pass);
  500. baseQueue_.AddBatch(baseBatch);
  501. }
  502. else
  503. {
  504. // Transparent batches can not be instanced
  505. FinalizeBatch(baseBatch, tech, pass, false);
  506. alphaQueue_.AddBatch(baseBatch);
  507. }
  508. continue;
  509. }
  510. // If no base pass, finally check for pre-alpha / post-alpha custom passes
  511. pass = tech->GetPass(PASS_PREALPHA);
  512. if (pass)
  513. {
  514. FinalizeBatch(baseBatch, tech, pass);
  515. preAlphaQueue_.AddBatch(baseBatch);
  516. continue;
  517. }
  518. pass = tech->GetPass(PASS_POSTALPHA);
  519. if (pass)
  520. {
  521. // Post-alpha pass is treated similarly as alpha, and is not instanced
  522. FinalizeBatch(baseBatch, tech, pass, false);
  523. postAlphaQueue_.AddBatch(baseBatch);
  524. continue;
  525. }
  526. }
  527. }
  528. }
  529. }
  530. void View::UpdateGeometries()
  531. {
  532. PROFILE(UpdateGeometries);
  533. WorkQueue* queue = GetSubsystem<WorkQueue>();
  534. // Sort batches
  535. {
  536. WorkItem item;
  537. item.workFunction_ = SortBatchQueueFrontToBackWork;
  538. item.start_ = &baseQueue_;
  539. queue->AddWorkItem(item);
  540. item.start_ = &preAlphaQueue_;
  541. queue->AddWorkItem(item);
  542. item.workFunction_ = SortBatchQueueBackToFrontWork;
  543. item.start_ = &alphaQueue_;
  544. queue->AddWorkItem(item);
  545. item.start_ = &postAlphaQueue_;
  546. queue->AddWorkItem(item);
  547. if (lightQueues_.Size())
  548. {
  549. item.workFunction_ = SortLightQueuesWork;
  550. item.start_ = &lightQueues_.Front();
  551. item.end_ = &lightQueues_.Back() + 1;
  552. queue->AddWorkItem(item);
  553. }
  554. }
  555. // Update geometries. Split into threaded and non-threaded updates.
  556. {
  557. nonThreadedGeometries_.Clear();
  558. threadedGeometries_.Clear();
  559. for (PODVector<Drawable*>::Iterator i = allGeometries_.Begin(); i != allGeometries_.End(); ++i)
  560. {
  561. UpdateGeometryType type = (*i)->GetUpdateGeometryType();
  562. if (type == UPDATE_MAIN_THREAD)
  563. nonThreadedGeometries_.Push(*i);
  564. else if (type == UPDATE_WORKER_THREAD)
  565. threadedGeometries_.Push(*i);
  566. }
  567. if (threadedGeometries_.Size())
  568. {
  569. PODVector<Drawable*>::Iterator start = threadedGeometries_.Begin();
  570. while (start != threadedGeometries_.End())
  571. {
  572. PODVector<Drawable*>::Iterator end = start;
  573. while (end - start < DRAWABLES_PER_WORK_ITEM && end != threadedGeometries_.End())
  574. ++end;
  575. WorkItem item;
  576. item.workFunction_ = UpdateDrawableGeometriesWork;
  577. item.start_ = &(*start);
  578. item.end_ = &(*end);
  579. item.aux_ = const_cast<FrameInfo*>(&frame_);
  580. queue->AddWorkItem(item);
  581. start = end;
  582. }
  583. }
  584. // While the work queue is processed, update non-threaded geometries
  585. for (PODVector<Drawable*>::ConstIterator i = nonThreadedGeometries_.Begin(); i != nonThreadedGeometries_.End(); ++i)
  586. (*i)->UpdateGeometry(frame_);
  587. }
  588. // Finally ensure all threaded work has completed
  589. queue->Complete();
  590. }
  591. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue)
  592. {
  593. Light* light = lightQueue.light_;
  594. Light* firstLight = drawable->GetFirstLight();
  595. // Shadows on transparencies can only be rendered if shadow maps are not reused
  596. bool allowTransparentShadows = !renderer_->GetReuseShadowMaps();
  597. unsigned numBatches = drawable->GetNumBatches();
  598. for (unsigned i = 0; i < numBatches; ++i)
  599. {
  600. Batch litBatch;
  601. drawable->GetBatch(litBatch, frame_, i);
  602. Technique* tech = GetTechnique(drawable, litBatch.material_);
  603. if (!litBatch.geometry_ || !tech)
  604. continue;
  605. Pass* pass = 0;
  606. // Check for lit base pass. Because it uses the replace blend mode, it must be ensured to be the first light
  607. if (light == firstLight && !drawable->HasBasePass(i))
  608. {
  609. pass = tech->GetPass(PASS_LITBASE);
  610. if (pass)
  611. {
  612. litBatch.isBase_ = true;
  613. drawable->SetBasePass(i);
  614. }
  615. }
  616. // If no lit base pass, get ordinary light pass
  617. if (!pass)
  618. pass = tech->GetPass(PASS_LIGHT);
  619. // Skip if material does not receive light at all
  620. if (!pass)
  621. continue;
  622. // Fill the rest of the batch
  623. litBatch.camera_ = camera_;
  624. litBatch.lightQueue_ = &lightQueue;
  625. litBatch.zone_ = GetZone(drawable);
  626. // Check from the ambient pass whether the object is opaque or transparent
  627. Pass* ambientPass = tech->GetPass(PASS_BASE);
  628. if (!ambientPass || ambientPass->GetBlendMode() == BLEND_REPLACE)
  629. {
  630. FinalizeBatch(litBatch, tech, pass);
  631. lightQueue.litBatches_.AddBatch(litBatch);
  632. }
  633. else
  634. {
  635. // Transparent batches can not be instanced
  636. FinalizeBatch(litBatch, tech, pass, false, allowTransparentShadows);
  637. alphaQueue_.AddBatch(litBatch);
  638. }
  639. }
  640. }
  641. void View::RenderBatches()
  642. {
  643. // If not reusing shadowmaps, render all of them first
  644. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  645. {
  646. PROFILE(RenderShadowMaps);
  647. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  648. {
  649. LightBatchQueue& queue = lightQueues_[i];
  650. if (queue.shadowMap_)
  651. RenderShadowMap(queue);
  652. }
  653. }
  654. graphics_->SetRenderTarget(0, renderTarget_);
  655. graphics_->SetDepthStencil(depthStencil_);
  656. graphics_->SetViewport(screenRect_);
  657. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, farClipZone_->GetFogColor());
  658. if (!baseQueue_.IsEmpty())
  659. {
  660. // Render opaque object unlit base pass
  661. PROFILE(RenderBase);
  662. RenderBatchQueue(baseQueue_);
  663. }
  664. if (!lightQueues_.Empty())
  665. {
  666. // Render shadow maps + opaque objects' shadowed additive lighting
  667. PROFILE(RenderLights);
  668. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  669. {
  670. LightBatchQueue& queue = lightQueues_[i];
  671. // If reusing shadowmaps, render each of them before the lit batches
  672. if (renderer_->GetReuseShadowMaps() && queue.shadowMap_)
  673. {
  674. RenderShadowMap(queue);
  675. graphics_->SetRenderTarget(0, renderTarget_);
  676. graphics_->SetDepthStencil(depthStencil_);
  677. graphics_->SetViewport(screenRect_);
  678. }
  679. RenderLightBatchQueue(queue.litBatches_, queue.light_);
  680. }
  681. }
  682. graphics_->SetScissorTest(false);
  683. graphics_->SetStencilTest(false);
  684. graphics_->SetRenderTarget(0, renderTarget_);
  685. graphics_->SetDepthStencil(depthStencil_);
  686. graphics_->SetViewport(screenRect_);
  687. if (!preAlphaQueue_.IsEmpty())
  688. {
  689. // Render pre-alpha custom pass
  690. PROFILE(RenderPreAlpha);
  691. RenderBatchQueue(preAlphaQueue_);
  692. }
  693. if (!alphaQueue_.IsEmpty())
  694. {
  695. // Render transparent objects (both base passes & additive lighting)
  696. PROFILE(RenderAlpha);
  697. RenderBatchQueue(alphaQueue_, true);
  698. }
  699. if (!postAlphaQueue_.IsEmpty())
  700. {
  701. // Render pre-alpha custom pass
  702. PROFILE(RenderPostAlpha);
  703. RenderBatchQueue(postAlphaQueue_);
  704. }
  705. }
  706. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  707. {
  708. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  709. float halfViewSize = camera->GetHalfViewSize();
  710. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  711. Vector3 cameraPos = camera->GetWorldPosition();
  712. for (unsigned i = 0; i < occluders.Size(); ++i)
  713. {
  714. Drawable* occluder = occluders[i];
  715. bool erase = false;
  716. if (!occluder->IsInView(frame_, false))
  717. occluder->UpdateDistance(frame_);
  718. // Check occluder's draw distance (in main camera view)
  719. float maxDistance = occluder->GetDrawDistance();
  720. if (maxDistance > 0.0f && occluder->GetDistance() > maxDistance)
  721. erase = true;
  722. else
  723. {
  724. // Check that occluder is big enough on the screen
  725. const BoundingBox& box = occluder->GetWorldBoundingBox();
  726. float diagonal = (box.max_ - box.min_).LengthFast();
  727. float compare;
  728. if (!camera->IsOrthographic())
  729. compare = diagonal * halfViewSize / occluder->GetDistance();
  730. else
  731. compare = diagonal * invOrthoSize;
  732. if (compare < occluderSizeThreshold_)
  733. erase = true;
  734. else
  735. {
  736. // Store amount of triangles divided by screen size as a sorting key
  737. // (best occluders are big and have few triangles)
  738. occluder->SetSortValue((float)occluder->GetNumOccluderTriangles() / compare);
  739. }
  740. }
  741. if (erase)
  742. {
  743. occluders.Erase(occluders.Begin() + i);
  744. --i;
  745. }
  746. }
  747. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  748. if (occluders.Size())
  749. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  750. }
  751. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  752. {
  753. for (unsigned i = 0; i < occluders.Size(); ++i)
  754. {
  755. Drawable* occluder = occluders[i];
  756. if (i > 0)
  757. {
  758. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  759. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  760. continue;
  761. }
  762. // Check for running out of triangles
  763. if (!occluder->DrawOcclusion(buffer))
  764. return;
  765. }
  766. }
  767. unsigned View::ProcessLight(Light* light)
  768. {
  769. // Check if light should be shadowed
  770. bool isShadowed = drawShadows_ && light->GetCastShadows() && light->GetShadowIntensity() < 1.0f;
  771. unsigned shadowSplits = 0;
  772. // If shadow distance non-zero, check it
  773. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  774. isShadowed = false;
  775. LightType type = light->GetLightType();
  776. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  777. litGeometries_.Clear();
  778. switch (type)
  779. {
  780. case LIGHT_DIRECTIONAL:
  781. for (unsigned i = 0; i < geometries_.Size(); ++i)
  782. {
  783. if (GetLightMask(geometries_[i]) & light->GetLightMask())
  784. litGeometries_.Push(geometries_[i]);
  785. }
  786. break;
  787. case LIGHT_SPOT:
  788. {
  789. FrustumOctreeQuery query(tempDrawables_, light->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask());
  790. octree_->GetDrawables(query);
  791. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  792. {
  793. if (tempDrawables_[i]->IsInView(frame_) && (GetLightMask(tempDrawables_[i]) & light->GetLightMask()))
  794. litGeometries_.Push(tempDrawables_[i]);
  795. }
  796. }
  797. break;
  798. case LIGHT_POINT:
  799. {
  800. SphereOctreeQuery query(tempDrawables_, Sphere(light->GetWorldPosition(), light->GetRange()), DRAWABLE_GEOMETRY,
  801. camera_->GetViewMask());
  802. octree_->GetDrawables(query);
  803. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  804. {
  805. if (tempDrawables_[i]->IsInView(frame_) && (GetLightMask(tempDrawables_[i]) & light->GetLightMask()))
  806. litGeometries_.Push(tempDrawables_[i]);
  807. }
  808. }
  809. break;
  810. }
  811. // If no lit geometries or not shadowed, no need to process shadow cameras
  812. if (litGeometries_.Empty() || !isShadowed)
  813. return 0;
  814. // Determine number of shadow cameras and setup their initial positions
  815. shadowSplits = SetupShadowCameras(light);
  816. // For a shadowed directional light, get occluders once using the whole (non-split) light frustum
  817. bool useOcclusion = false;
  818. OcclusionBuffer* buffer = 0;
  819. if (maxOccluderTriangles_ > 0 && isShadowed && light->GetLightType() == LIGHT_DIRECTIONAL)
  820. {
  821. // This shadow camera is never used for actually querying shadow casters, just occluders
  822. Camera* shadowCamera = renderer_->CreateShadowCamera();
  823. SetupDirLightShadowCamera(shadowCamera, light, 0.0f, Min(light->GetShadowCascade().GetShadowRange(), camera_->GetFarClip()),
  824. true);
  825. // Get occluders, which must be shadow-casting themselves
  826. FrustumOctreeQuery query(shadowOccluders_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask(),
  827. true, true);
  828. octree_->GetDrawables(query);
  829. UpdateOccluders(shadowOccluders_, shadowCamera);
  830. if (shadowOccluders_.Size())
  831. {
  832. // Shadow viewport is rectangular and consumes more CPU fillrate, so halve size
  833. buffer = renderer_->GetOrCreateOcclusionBuffer(shadowCamera, maxOccluderTriangles_, true);
  834. DrawOccluders(buffer, shadowOccluders_);
  835. buffer->BuildDepthHierarchy();
  836. useOcclusion = true;
  837. }
  838. }
  839. // Process each split for shadow casters
  840. bool hasShadowCasters = false;
  841. for (unsigned i = 0; i < shadowSplits; ++i)
  842. {
  843. shadowCasters_[i].Clear();
  844. shadowCasterBox_[i].defined_ = false;
  845. Camera* shadowCamera = shadowCameras_[i];
  846. Frustum shadowCameraFrustum = shadowCamera->GetFrustum();
  847. // For point light check that the face is visible: if not, can skip the split
  848. if (type == LIGHT_POINT)
  849. {
  850. BoundingBox shadowCameraBox(shadowCameraFrustum);
  851. if (frustum_.IsInsideFast(shadowCameraBox) == OUTSIDE)
  852. continue;
  853. }
  854. // For directional light check that the split is inside the visible scene: if not, can skip the split
  855. if (type == LIGHT_DIRECTIONAL)
  856. {
  857. if (sceneViewBox_.min_.z_ > shadowFarSplits_[i])
  858. continue;
  859. if (sceneViewBox_.max_.z_ < shadowNearSplits_[i])
  860. continue;
  861. }
  862. if (!useOcclusion)
  863. {
  864. // For spot light (which has only one shadow split) we can optimize by reusing the query for
  865. // lit geometries, whose result still exists in tempDrawables_
  866. if (type != LIGHT_SPOT)
  867. {
  868. FrustumOctreeQuery query(tempDrawables_, shadowCameraFrustum, DRAWABLE_GEOMETRY, camera_->GetViewMask(),
  869. false, true);
  870. octree_->GetDrawables(query);
  871. }
  872. }
  873. else
  874. {
  875. OccludedFrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), buffer,
  876. DRAWABLE_GEOMETRY, camera_->GetViewMask(), false, true);
  877. octree_->GetDrawables(query);
  878. }
  879. // Check which shadow casters actually contribute to the shadowing
  880. ProcessShadowCasters(light, i, tempDrawables_, shadowCasterBox_[i]);
  881. if (shadowCasters_[i].Size())
  882. hasShadowCasters = true;
  883. }
  884. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  885. // only cost has been the shadow camera setup & queries
  886. if (!hasShadowCasters)
  887. shadowSplits = 0;
  888. return shadowSplits;
  889. }
  890. void View::ProcessShadowCasters(Light* light, unsigned splitIndex, const PODVector<Drawable*>& result, BoundingBox& shadowCasterBox)
  891. {
  892. Matrix3x4 lightView;
  893. Matrix4 lightProj;
  894. Camera* shadowCamera = shadowCameras_[splitIndex];
  895. lightView = shadowCamera->GetInverseWorldTransform();
  896. lightProj = shadowCamera->GetProjection();
  897. bool dirLight = shadowCamera->IsOrthographic();
  898. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  899. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  900. // frustum, so that shadow casters do not get rendered into unnecessary splits
  901. Frustum lightViewFrustum;
  902. if (!dirLight)
  903. lightViewFrustum = camera_->GetSplitFrustum(sceneViewBox_.min_.z_, sceneViewBox_.max_.z_).Transformed(lightView);
  904. else
  905. lightViewFrustum = camera_->GetSplitFrustum(Max(sceneViewBox_.min_.z_, shadowNearSplits_[splitIndex]),
  906. Min(sceneViewBox_.max_.z_, shadowFarSplits_[splitIndex])).Transformed(lightView);
  907. BoundingBox lightViewFrustumBox(lightViewFrustum);
  908. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  909. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  910. return;
  911. BoundingBox lightViewBox;
  912. BoundingBox lightProjBox;
  913. for (unsigned i = 0; i < result.Size(); ++i)
  914. {
  915. Drawable* drawable = static_cast<Drawable*>(result[i]);
  916. // In case this is a spot light query result reused for optimization, we may have non-shadowcasters included.
  917. // Check for that first
  918. if (!drawable->GetCastShadows())
  919. continue;
  920. if (!drawable->IsInView(frame_, false))
  921. drawable->UpdateDistance(frame_);
  922. // Check shadow distance
  923. float maxShadowDistance = drawable->GetShadowDistance();
  924. if (maxShadowDistance > 0.0f && drawable->GetDistance() > maxShadowDistance)
  925. continue;
  926. // Check light mask
  927. if (!(GetLightMask(drawable) & light->GetLightMask()))
  928. continue;
  929. // Project shadow caster bounding box to light view space for visibility check
  930. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  931. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  932. {
  933. if (!drawable->IsInView(frame_, false))
  934. {
  935. drawable->MarkInView(frame_, false);
  936. allGeometries_.Push(drawable);
  937. }
  938. // Merge to shadow caster bounding box and add to the list
  939. if (dirLight)
  940. shadowCasterBox.Merge(lightViewBox);
  941. else
  942. {
  943. lightProjBox = lightViewBox.Projected(lightProj);
  944. shadowCasterBox.Merge(lightProjBox);
  945. }
  946. shadowCasters_[splitIndex].Push(drawable);
  947. }
  948. }
  949. }
  950. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  951. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  952. {
  953. if (shadowCamera->IsOrthographic())
  954. {
  955. // If shadow caster is also an occluder, must let it be visible, because it has potentially already culled
  956. // away other shadow casters (could also check the actual shadow occluder vector, but that would be slower)
  957. if (drawable->IsOccluder())
  958. return true;
  959. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  960. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  961. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  962. }
  963. else
  964. {
  965. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  966. if (drawable->IsInView(frame_))
  967. return true;
  968. // For perspective lights, extrusion direction depends on the position of the shadow caster
  969. Vector3 center = lightViewBox.Center();
  970. Ray extrusionRay(center, center.Normalized());
  971. float extrusionDistance = shadowCamera->GetFarClip();
  972. float originalDistance = Clamp(center.LengthFast(), M_EPSILON, extrusionDistance);
  973. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  974. float sizeFactor = extrusionDistance / originalDistance;
  975. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  976. // than necessary, so the test will be conservative
  977. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  978. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  979. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  980. lightViewBox.Merge(extrudedBox);
  981. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  982. }
  983. }
  984. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  985. {
  986. unsigned width = shadowMap->GetWidth();
  987. unsigned height = shadowMap->GetHeight();
  988. int maxCascades = renderer_->GetMaxShadowCascades();
  989. switch (light->GetLightType())
  990. {
  991. case LIGHT_DIRECTIONAL:
  992. if (maxCascades == 1)
  993. return IntRect(0, 0, width, height);
  994. else if (maxCascades == 2)
  995. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  996. else
  997. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  998. (splitIndex / 2 + 1) * height / 2);
  999. case LIGHT_SPOT:
  1000. return IntRect(0, 0, width, height);
  1001. case LIGHT_POINT:
  1002. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  1003. (splitIndex / 2 + 1) * height / 3);
  1004. }
  1005. return IntRect();
  1006. }
  1007. void View::OptimizeLightByScissor(Light* light)
  1008. {
  1009. if (light)
  1010. graphics_->SetScissorTest(true, GetLightScissor(light));
  1011. else
  1012. graphics_->SetScissorTest(false);
  1013. }
  1014. void View::OptimizeLightByStencil(Light* light)
  1015. {
  1016. if (light && renderer_->GetLightStencilMasking())
  1017. {
  1018. Geometry* geometry = renderer_->GetLightGeometry(light);
  1019. if (!geometry)
  1020. {
  1021. graphics_->SetStencilTest(false);
  1022. return;
  1023. }
  1024. LightType type = light->GetLightType();
  1025. Matrix3x4 view(camera_->GetInverseWorldTransform());
  1026. Matrix4 projection(camera_->GetProjection());
  1027. float lightDist;
  1028. if (type == LIGHT_POINT)
  1029. lightDist = Sphere(light->GetWorldPosition(), light->GetRange() * 1.25f).DistanceFast(camera_->GetWorldPosition());
  1030. else
  1031. lightDist = light->GetFrustum().Distance(camera_->GetWorldPosition());
  1032. // If the camera is actually inside the light volume, do not draw to stencil as it would waste fillrate
  1033. if (lightDist < M_EPSILON)
  1034. {
  1035. graphics_->SetStencilTest(false);
  1036. return;
  1037. }
  1038. // If the stencil value has wrapped, clear the whole stencil first
  1039. if (!lightStencilValue_)
  1040. {
  1041. graphics_->Clear(CLEAR_STENCIL);
  1042. lightStencilValue_ = 1;
  1043. }
  1044. // If possible, render the stencil volume front faces. However, close to the near clip plane render back faces instead
  1045. // to avoid clipping the front faces.
  1046. if (lightDist < camera_->GetNearClip() * 2.0f)
  1047. {
  1048. graphics_->SetCullMode(CULL_CW);
  1049. graphics_->SetDepthTest(CMP_GREATER);
  1050. }
  1051. else
  1052. {
  1053. graphics_->SetCullMode(CULL_CCW);
  1054. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1055. }
  1056. graphics_->SetColorWrite(false);
  1057. graphics_->SetDepthWrite(false);
  1058. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, lightStencilValue_);
  1059. graphics_->SetShaders(renderer_->GetStencilVS(), renderer_->GetStencilPS());
  1060. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1061. graphics_->SetShaderParameter(VSP_MODEL, light->GetVolumeTransform());
  1062. geometry->Draw(graphics_);
  1063. graphics_->ClearTransformSources();
  1064. graphics_->SetColorWrite(true);
  1065. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, lightStencilValue_);
  1066. // Increase stencil value for next light
  1067. ++lightStencilValue_;
  1068. }
  1069. else
  1070. graphics_->SetStencilTest(false);
  1071. }
  1072. const Rect& View::GetLightScissor(Light* light)
  1073. {
  1074. HashMap<Light*, Rect>::Iterator i = lightScissorCache_.Find(light);
  1075. if (i != lightScissorCache_.End())
  1076. return i->second_;
  1077. Matrix3x4 view(camera_->GetInverseWorldTransform());
  1078. Matrix4 projection(camera_->GetProjection());
  1079. switch (light->GetLightType())
  1080. {
  1081. case LIGHT_POINT:
  1082. {
  1083. BoundingBox viewBox(light->GetWorldBoundingBox().Transformed(view));
  1084. return lightScissorCache_[light] = viewBox.Projected(projection);
  1085. }
  1086. case LIGHT_SPOT:
  1087. {
  1088. Frustum viewFrustum(light->GetFrustum().Transformed(view));
  1089. return lightScissorCache_[light] = viewFrustum.Projected(projection);
  1090. }
  1091. default:
  1092. return lightScissorCache_[light] = Rect::FULL;
  1093. }
  1094. }
  1095. unsigned View::SetupShadowCameras(Light* light)
  1096. {
  1097. LightType type = light->GetLightType();
  1098. if (type == LIGHT_DIRECTIONAL)
  1099. {
  1100. const CascadeParameters& cascade = light->GetShadowCascade();
  1101. int splits = 0;
  1102. float nearSplit = camera_->GetNearClip();
  1103. float farSplit;
  1104. while (splits < renderer_->GetMaxShadowCascades())
  1105. {
  1106. // If split is completely beyond camera far clip, we are done
  1107. if (nearSplit > camera_->GetFarClip())
  1108. break;
  1109. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  1110. if (farSplit <= nearSplit)
  1111. break;
  1112. // Setup the shadow camera for the split
  1113. Camera* shadowCamera = renderer_->CreateShadowCamera();
  1114. shadowCameras_[splits] = shadowCamera;
  1115. shadowNearSplits_[splits] = nearSplit;
  1116. shadowFarSplits_[splits] = farSplit;
  1117. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit, false);
  1118. nearSplit = farSplit;
  1119. ++splits;
  1120. }
  1121. return splits;
  1122. }
  1123. if (type == LIGHT_SPOT)
  1124. {
  1125. Camera* shadowCamera = renderer_->CreateShadowCamera();
  1126. shadowCameras_[0] = shadowCamera;
  1127. Node* cameraNode = shadowCamera->GetNode();
  1128. cameraNode->SetTransform(light->GetWorldPosition(), light->GetWorldRotation());
  1129. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1130. shadowCamera->SetFarClip(light->GetRange());
  1131. shadowCamera->SetFov(light->GetFov());
  1132. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1133. return 1;
  1134. }
  1135. if (type == LIGHT_POINT)
  1136. {
  1137. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1138. {
  1139. Camera* shadowCamera = renderer_->CreateShadowCamera();
  1140. shadowCameras_[i] = shadowCamera;
  1141. Node* cameraNode = shadowCamera->GetNode();
  1142. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1143. cameraNode->SetPosition(light->GetWorldPosition());
  1144. cameraNode->SetDirection(directions[i]);
  1145. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1146. shadowCamera->SetFarClip(light->GetRange());
  1147. shadowCamera->SetFov(90.0f);
  1148. shadowCamera->SetAspectRatio(1.0f);
  1149. }
  1150. return MAX_CUBEMAP_FACES;
  1151. }
  1152. return 0;
  1153. }
  1154. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit, bool shadowOcclusion)
  1155. {
  1156. Node* cameraNode = shadowCamera->GetNode();
  1157. float extrusionDistance = camera_->GetFarClip();
  1158. const FocusParameters& parameters = light->GetShadowFocus();
  1159. // Calculate initial position & rotation
  1160. Vector3 lightWorldDirection = light->GetWorldRotation() * Vector3::FORWARD;
  1161. Vector3 pos = camera_->GetWorldPosition() - extrusionDistance * lightWorldDirection;
  1162. cameraNode->SetTransform(pos, light->GetWorldRotation());
  1163. // Calculate main camera shadowed frustum in light's view space
  1164. farSplit = Min(farSplit, camera_->GetFarClip());
  1165. // Use the scene Z bounds to limit frustum size if applicable
  1166. if (shadowOcclusion || parameters.focus_)
  1167. {
  1168. nearSplit = Max(sceneViewBox_.min_.z_, nearSplit);
  1169. farSplit = Min(sceneViewBox_.max_.z_, farSplit);
  1170. }
  1171. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  1172. frustumVolume_.Define(splitFrustum);
  1173. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  1174. if (!shadowOcclusion && parameters.focus_)
  1175. {
  1176. PROFILE(ClipFrustumVolume);
  1177. BoundingBox litGeometriesBox;
  1178. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1179. {
  1180. // Skip "infinite" objects like the skybox
  1181. const BoundingBox& geomBox = geometries_[i]->GetWorldBoundingBox();
  1182. if (geomBox.Size().LengthFast() < M_LARGE_VALUE)
  1183. {
  1184. if (geometryDepthBounds_[i].min_ <= farSplit && geometryDepthBounds_[i].max_ >= nearSplit &&
  1185. (GetLightMask(geometries_[i]) & light->GetLightMask()))
  1186. litGeometriesBox.Merge(geomBox);
  1187. }
  1188. }
  1189. if (litGeometriesBox.defined_)
  1190. {
  1191. frustumVolume_.Clip(litGeometriesBox);
  1192. // If volume became empty, restore it to avoid zero size
  1193. if (frustumVolume_.Empty())
  1194. frustumVolume_.Define(splitFrustum);
  1195. }
  1196. }
  1197. // Transform frustum volume to light space
  1198. Matrix3x4 lightView(shadowCamera->GetInverseWorldTransform());
  1199. frustumVolume_.Transform(lightView);
  1200. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  1201. BoundingBox shadowBox;
  1202. if (shadowOcclusion || !parameters.nonUniform_)
  1203. shadowBox.Define(Sphere(frustumVolume_));
  1204. else
  1205. shadowBox.Define(frustumVolume_);
  1206. shadowCamera->SetOrthographic(true);
  1207. shadowCamera->SetAspectRatio(1.0f);
  1208. shadowCamera->SetNearClip(0.0f);
  1209. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1210. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  1211. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  1212. }
  1213. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1214. const BoundingBox& shadowCasterBox)
  1215. {
  1216. const FocusParameters& parameters = light->GetShadowFocus();
  1217. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1218. LightType type = light->GetLightType();
  1219. if (type == LIGHT_DIRECTIONAL)
  1220. {
  1221. BoundingBox shadowBox;
  1222. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1223. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  1224. shadowBox.min_.y_ = -shadowBox.max_.y_;
  1225. shadowBox.min_.x_ = -shadowBox.max_.x_;
  1226. // Requantize and snap to shadow map texels
  1227. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  1228. }
  1229. if (type == LIGHT_SPOT)
  1230. {
  1231. if (parameters.focus_)
  1232. {
  1233. float viewSizeX = Max(fabsf(shadowCasterBox.min_.x_), fabsf(shadowCasterBox.max_.x_));
  1234. float viewSizeY = Max(fabsf(shadowCasterBox.min_.y_), fabsf(shadowCasterBox.max_.y_));
  1235. float viewSize = Max(viewSizeX, viewSizeY);
  1236. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  1237. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  1238. float quantize = parameters.quantize_ * invOrthoSize;
  1239. float minView = parameters.minView_ * invOrthoSize;
  1240. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  1241. if (viewSize < 1.0f)
  1242. shadowCamera->SetZoom(1.0f / viewSize);
  1243. }
  1244. }
  1245. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  1246. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  1247. if (shadowCamera->GetZoom() >= 1.0f)
  1248. {
  1249. if (light->GetLightType() != LIGHT_POINT)
  1250. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  1251. else
  1252. {
  1253. #ifdef USE_OPENGL
  1254. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  1255. #else
  1256. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  1257. #endif
  1258. }
  1259. }
  1260. }
  1261. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1262. const BoundingBox& viewBox)
  1263. {
  1264. Node* cameraNode = shadowCamera->GetNode();
  1265. const FocusParameters& parameters = light->GetShadowFocus();
  1266. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1267. float minX = viewBox.min_.x_;
  1268. float minY = viewBox.min_.y_;
  1269. float maxX = viewBox.max_.x_;
  1270. float maxY = viewBox.max_.y_;
  1271. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  1272. Vector2 viewSize(maxX - minX, maxY - minY);
  1273. // Quantize size to reduce swimming
  1274. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  1275. if (parameters.nonUniform_)
  1276. {
  1277. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1278. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  1279. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1280. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  1281. }
  1282. else if (parameters.focus_)
  1283. {
  1284. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  1285. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1286. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1287. viewSize.y_ = viewSize.x_;
  1288. }
  1289. shadowCamera->SetOrthoSize(viewSize);
  1290. // Center shadow camera to the view space bounding box
  1291. Vector3 pos(shadowCamera->GetWorldPosition());
  1292. Quaternion rot(shadowCamera->GetWorldRotation());
  1293. Vector3 adjust(center.x_, center.y_, 0.0f);
  1294. cameraNode->Translate(rot * adjust);
  1295. // If the shadow map viewport is known, snap to whole texels
  1296. if (shadowMapWidth > 0.0f)
  1297. {
  1298. Vector3 viewPos(rot.Inverse() * cameraNode->GetWorldPosition());
  1299. // Take into account that shadow map border will not be used
  1300. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  1301. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  1302. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  1303. cameraNode->Translate(rot * snap);
  1304. }
  1305. }
  1306. void View::FindZone(Drawable* drawable, int highestZonePriority)
  1307. {
  1308. Vector3 center = drawable->GetWorldBoundingBox().Center();
  1309. int bestPriority = M_MIN_INT;
  1310. Zone* newZone = 0;
  1311. // If bounding box center is in view, can use the visible zones. Else must query via the octree
  1312. if (frustum_.IsInside(center))
  1313. {
  1314. // First check if the last zone remains a conclusive result
  1315. Zone* lastZone = drawable->GetLastZone();
  1316. if (lastZone && lastZone->IsInside(center) && (drawable->GetZoneMask() & lastZone->GetZoneMask()) &&
  1317. lastZone->GetPriority() >= highestZonePriority)
  1318. newZone = lastZone;
  1319. else
  1320. {
  1321. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  1322. {
  1323. int priority = (*i)->GetPriority();
  1324. if ((*i)->IsInside(center) && (drawable->GetZoneMask() & (*i)->GetZoneMask()) && priority > bestPriority)
  1325. {
  1326. newZone = *i;
  1327. bestPriority = priority;
  1328. }
  1329. }
  1330. }
  1331. }
  1332. else
  1333. {
  1334. PointOctreeQuery query(reinterpret_cast<PODVector<Drawable*>&>(tempZones_), center, DRAWABLE_ZONE);
  1335. octree_->GetDrawables(query);
  1336. bestPriority = M_MIN_INT;
  1337. for (PODVector<Zone*>::Iterator i = tempZones_.Begin(); i != tempZones_.End(); ++i)
  1338. {
  1339. int priority = (*i)->GetPriority();
  1340. if ((*i)->IsInside(center) && (drawable->GetZoneMask() & (*i)->GetZoneMask()) && priority > bestPriority)
  1341. {
  1342. newZone = *i;
  1343. bestPriority = priority;
  1344. }
  1345. }
  1346. }
  1347. drawable->SetZone(newZone);
  1348. }
  1349. Zone* View::GetZone(Drawable* drawable)
  1350. {
  1351. if (cameraZoneOverride_)
  1352. return cameraZone_;
  1353. Zone* drawableZone = drawable->GetZone();
  1354. return drawableZone ? drawableZone : cameraZone_;
  1355. }
  1356. unsigned View::GetLightMask(Drawable* drawable)
  1357. {
  1358. return drawable->GetLightMask() & GetZone(drawable)->GetLightMask();
  1359. }
  1360. Technique* View::GetTechnique(Drawable* drawable, Material*& material)
  1361. {
  1362. if (!material)
  1363. material = renderer_->GetDefaultMaterial();
  1364. if (!material)
  1365. return 0;
  1366. float lodDistance = drawable->GetLodDistance();
  1367. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  1368. if (techniques.Empty())
  1369. return 0;
  1370. // Check for suitable technique. Techniques should be ordered like this:
  1371. // Most distant & highest quality
  1372. // Most distant & lowest quality
  1373. // Second most distant & highest quality
  1374. // ...
  1375. for (unsigned i = 0; i < techniques.Size(); ++i)
  1376. {
  1377. const TechniqueEntry& entry = techniques[i];
  1378. Technique* technique = entry.technique_;
  1379. if (!technique || (technique->IsSM3() && !graphics_->GetSM3Support()) || materialQuality_ < entry.qualityLevel_)
  1380. continue;
  1381. if (lodDistance >= entry.lodDistance_)
  1382. return technique;
  1383. }
  1384. // If no suitable technique found, fallback to the last
  1385. return techniques.Back().technique_;
  1386. }
  1387. void View::CheckMaterialForAuxView(Material* material)
  1388. {
  1389. const Vector<SharedPtr<Texture> >& textures = material->GetTextures();
  1390. for (unsigned i = 0; i < textures.Size(); ++i)
  1391. {
  1392. // Have to check cube & 2D textures separately
  1393. Texture* texture = textures[i];
  1394. if (texture)
  1395. {
  1396. if (texture->GetType() == Texture2D::GetTypeStatic())
  1397. {
  1398. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1399. RenderSurface* target = tex2D->GetRenderSurface();
  1400. if (target)
  1401. {
  1402. const Viewport& viewport = target->GetViewport();
  1403. if (viewport.scene_ && viewport.camera_)
  1404. renderer_->AddView(target, viewport);
  1405. }
  1406. }
  1407. else if (texture->GetType() == TextureCube::GetTypeStatic())
  1408. {
  1409. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1410. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1411. {
  1412. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  1413. if (target)
  1414. {
  1415. const Viewport& viewport = target->GetViewport();
  1416. if (viewport.scene_ && viewport.camera_)
  1417. renderer_->AddView(target, viewport);
  1418. }
  1419. }
  1420. }
  1421. }
  1422. }
  1423. // Set frame number so that we can early-out next time we come across this material on the same frame
  1424. material->MarkForAuxView(frame_.frameNumber_);
  1425. }
  1426. void View::FinalizeBatch(Batch& batch, Technique* tech, Pass* pass, bool allowInstancing, bool allowShadows)
  1427. {
  1428. // Convert to instanced if possible
  1429. if (allowInstancing && batch.geometryType_ == GEOM_STATIC && !batch.shaderData_ && !batch.overrideView_)
  1430. batch.geometryType_ = GEOM_INSTANCED;
  1431. batch.pass_ = pass;
  1432. renderer_->SetBatchShaders(batch, tech, pass, allowShadows);
  1433. batch.CalculateSortKey();
  1434. }
  1435. void View::PrepareInstancingBuffer()
  1436. {
  1437. PROFILE(PrepareInstancingBuffer);
  1438. unsigned totalInstances = 0;
  1439. totalInstances += baseQueue_.GetNumInstances(renderer_);
  1440. totalInstances += preAlphaQueue_.GetNumInstances(renderer_);
  1441. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1442. {
  1443. for (unsigned j = 0; j < lightQueues_[i].shadowSplits_.Size(); ++j)
  1444. totalInstances += lightQueues_[i].shadowSplits_[j].shadowBatches_.GetNumInstances(renderer_);
  1445. totalInstances += lightQueues_[i].litBatches_.GetNumInstances(renderer_);
  1446. }
  1447. // If fail to set buffer size, fall back to per-group locking
  1448. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  1449. {
  1450. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  1451. unsigned freeIndex = 0;
  1452. void* lockedData = instancingBuffer->Lock(0, totalInstances, LOCK_DISCARD);
  1453. if (lockedData)
  1454. {
  1455. baseQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1456. preAlphaQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1457. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1458. {
  1459. for (unsigned j = 0; j < lightQueues_[i].shadowSplits_.Size(); ++j)
  1460. lightQueues_[i].shadowSplits_[j].shadowBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  1461. lightQueues_[i].litBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  1462. }
  1463. instancingBuffer->Unlock();
  1464. }
  1465. }
  1466. }
  1467. void View::RenderBatchQueue(const BatchQueue& queue, bool useScissor)
  1468. {
  1469. graphics_->SetScissorTest(false);
  1470. graphics_->SetStencilTest(false);
  1471. // Base instanced
  1472. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBaseBatchGroups_.Begin(); i !=
  1473. queue.sortedBaseBatchGroups_.End(); ++i)
  1474. {
  1475. BatchGroup* group = *i;
  1476. group->Draw(graphics_, renderer_);
  1477. }
  1478. // Base non-instanced
  1479. for (PODVector<Batch*>::ConstIterator i = queue.sortedBaseBatches_.Begin(); i != queue.sortedBaseBatches_.End(); ++i)
  1480. {
  1481. Batch* batch = *i;
  1482. batch->Draw(graphics_, renderer_);
  1483. }
  1484. // Non-base instanced
  1485. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBatchGroups_.Begin(); i != queue.sortedBatchGroups_.End(); ++i)
  1486. {
  1487. BatchGroup* group = *i;
  1488. if (useScissor && group->lightQueue_)
  1489. OptimizeLightByScissor(group->lightQueue_->light_);
  1490. group->Draw(graphics_, renderer_);
  1491. }
  1492. // Non-base non-instanced
  1493. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1494. {
  1495. Batch* batch = *i;
  1496. if (useScissor)
  1497. {
  1498. if (!batch->isBase_ && batch->lightQueue_)
  1499. OptimizeLightByScissor(batch->lightQueue_->light_);
  1500. else
  1501. graphics_->SetScissorTest(false);
  1502. }
  1503. batch->Draw(graphics_, renderer_);
  1504. }
  1505. }
  1506. void View::RenderLightBatchQueue(const BatchQueue& queue, Light* light)
  1507. {
  1508. graphics_->SetScissorTest(false);
  1509. graphics_->SetStencilTest(false);
  1510. // Base instanced
  1511. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBaseBatchGroups_.Begin(); i !=
  1512. queue.sortedBaseBatchGroups_.End(); ++i)
  1513. {
  1514. BatchGroup* group = *i;
  1515. group->Draw(graphics_, renderer_);
  1516. }
  1517. // Base non-instanced
  1518. for (PODVector<Batch*>::ConstIterator i = queue.sortedBaseBatches_.Begin(); i != queue.sortedBaseBatches_.End(); ++i)
  1519. {
  1520. Batch* batch = *i;
  1521. batch->Draw(graphics_, renderer_);
  1522. }
  1523. // All base passes have been drawn. Optimize at this point by both stencil volume and scissor
  1524. OptimizeLightByStencil(light);
  1525. OptimizeLightByScissor(light);
  1526. // Non-base instanced
  1527. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBatchGroups_.Begin(); i != queue.sortedBatchGroups_.End(); ++i)
  1528. {
  1529. BatchGroup* group = *i;
  1530. group->Draw(graphics_, renderer_);
  1531. }
  1532. // Non-base non-instanced
  1533. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1534. {
  1535. Batch* batch = *i;
  1536. batch->Draw(graphics_, renderer_);
  1537. }
  1538. }
  1539. void View::RenderShadowMap(const LightBatchQueue& queue)
  1540. {
  1541. PROFILE(RenderShadowMap);
  1542. Texture2D* shadowMap = queue.shadowMap_;
  1543. graphics_->SetStencilTest(false);
  1544. graphics_->SetTexture(TU_SHADOWMAP, 0);
  1545. if (!graphics_->GetFallback())
  1546. {
  1547. graphics_->SetColorWrite(false);
  1548. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  1549. graphics_->SetDepthStencil(shadowMap);
  1550. graphics_->Clear(CLEAR_DEPTH);
  1551. }
  1552. else
  1553. {
  1554. graphics_->SetColorWrite(true);
  1555. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface());
  1556. graphics_->SetDepthStencil(shadowMap->GetRenderSurface()->GetLinkedDepthBuffer());
  1557. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH, Color::WHITE);
  1558. }
  1559. // Set shadow depth bias
  1560. BiasParameters parameters = queue.light_->GetShadowBias();
  1561. // Adjust the light's constant depth bias according to global shadow map resolution
  1562. /// \todo Should remove this adjustment and find a more flexible solution
  1563. unsigned shadowMapSize = renderer_->GetShadowMapSize();
  1564. if (shadowMapSize <= 512)
  1565. parameters.constantBias_ *= 2.0f;
  1566. else if (shadowMapSize >= 2048)
  1567. parameters.constantBias_ *= 0.5f;
  1568. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  1569. // Render each of the splits
  1570. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  1571. {
  1572. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  1573. if (!shadowQueue.shadowBatches_.IsEmpty())
  1574. {
  1575. graphics_->SetViewport(shadowQueue.shadowViewport_);
  1576. // Set a scissor rectangle to match possible shadow map size reduction by out-zooming
  1577. // However, do not do this for point lights, which need to render continuously across cube faces
  1578. float width = (float)(shadowQueue.shadowViewport_.right_ - shadowQueue.shadowViewport_.left_);
  1579. if (queue.light_->GetLightType() != LIGHT_POINT)
  1580. {
  1581. float zoom = Min(shadowQueue.shadowCamera_->GetZoom(), width - 2.0f / width);
  1582. Rect zoomRect(Vector2(-1.0f, -1.0f) * zoom, Vector2(1.0f, 1.0f) * zoom);
  1583. graphics_->SetScissorTest(true, zoomRect, false);
  1584. }
  1585. else
  1586. graphics_->SetScissorTest(false);
  1587. // Draw instanced and non-instanced shadow casters
  1588. RenderBatchQueue(shadowQueue.shadowBatches_);
  1589. }
  1590. }
  1591. graphics_->SetColorWrite(true);
  1592. graphics_->SetDepthBias(0.0f, 0.0f);
  1593. }