Batch.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Camera.h"
  24. #include "Geometry.h"
  25. #include "Graphics.h"
  26. #include "GraphicsImpl.h"
  27. #include "Material.h"
  28. #include "Node.h"
  29. #include "Renderer.h"
  30. #include "Profiler.h"
  31. #include "Scene.h"
  32. #include "ShaderVariation.h"
  33. #include "Sort.h"
  34. #include "Technique.h"
  35. #include "Texture2D.h"
  36. #include "VertexBuffer.h"
  37. #include "View.h"
  38. #include "Zone.h"
  39. #include "DebugNew.h"
  40. namespace Urho3D
  41. {
  42. inline bool CompareBatchesState(Batch* lhs, Batch* rhs)
  43. {
  44. if (lhs->sortKey_ != rhs->sortKey_)
  45. return lhs->sortKey_ < rhs->sortKey_;
  46. else
  47. return lhs->distance_ < rhs->distance_;
  48. }
  49. inline bool CompareBatchesFrontToBack(Batch* lhs, Batch* rhs)
  50. {
  51. if (lhs->distance_ != rhs->distance_)
  52. return lhs->distance_ < rhs->distance_;
  53. else
  54. return lhs->sortKey_ < rhs->sortKey_;
  55. }
  56. inline bool CompareBatchesBackToFront(Batch* lhs, Batch* rhs)
  57. {
  58. if (lhs->distance_ != rhs->distance_)
  59. return lhs->distance_ > rhs->distance_;
  60. else
  61. return lhs->sortKey_ < rhs->sortKey_;
  62. }
  63. inline bool CompareInstancesFrontToBack(const InstanceData& lhs, const InstanceData& rhs)
  64. {
  65. return lhs.distance_ < rhs.distance_;
  66. }
  67. void CalculateShadowMatrix(Matrix4& dest, LightBatchQueue* queue, unsigned split, Renderer* renderer, const Vector3& translation)
  68. {
  69. Camera* shadowCamera = queue->shadowSplits_[split].shadowCamera_;
  70. const IntRect& viewport = queue->shadowSplits_[split].shadowViewport_;
  71. Matrix3x4 posAdjust(translation, Quaternion::IDENTITY, 1.0f);
  72. Matrix3x4 shadowView(shadowCamera->GetView());
  73. Matrix4 shadowProj(shadowCamera->GetProjection());
  74. Matrix4 texAdjust(Matrix4::IDENTITY);
  75. Texture2D* shadowMap = queue->shadowMap_;
  76. if (!shadowMap)
  77. return;
  78. float width = (float)shadowMap->GetWidth();
  79. float height = (float)shadowMap->GetHeight();
  80. Vector2 offset(
  81. (float)viewport.left_ / width,
  82. (float)viewport.top_ / height
  83. );
  84. Vector2 scale(
  85. 0.5f * (float)viewport.Width() / width,
  86. 0.5f * (float)viewport.Height() / height
  87. );
  88. #ifdef USE_OPENGL
  89. offset.x_ += scale.x_;
  90. offset.y_ += scale.y_;
  91. offset.y_ = 1.0f - offset.y_;
  92. // If using 4 shadow samples, offset the position diagonally by half pixel
  93. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  94. {
  95. offset.x_ -= 0.5f / width;
  96. offset.y_ -= 0.5f / height;
  97. }
  98. texAdjust.SetTranslation(Vector3(offset.x_, offset.y_, 0.5f));
  99. texAdjust.SetScale(Vector3(scale.x_, scale.y_, 0.5f));
  100. #else
  101. offset.x_ += scale.x_ + 0.5f / width;
  102. offset.y_ += scale.y_ + 0.5f / height;
  103. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  104. {
  105. offset.x_ -= 0.5f / width;
  106. offset.y_ -= 0.5f / height;
  107. }
  108. scale.y_ = -scale.y_;
  109. texAdjust.SetTranslation(Vector3(offset.x_, offset.y_, 0.0f));
  110. texAdjust.SetScale(Vector3(scale.x_, scale.y_, 1.0f));
  111. #endif
  112. dest = texAdjust * shadowProj * shadowView * posAdjust;
  113. }
  114. void CalculateSpotMatrix(Matrix4& dest, Light* light, const Vector3& translation)
  115. {
  116. Node* lightNode = light->GetNode();
  117. Matrix3x4 posAdjust(translation, Quaternion::IDENTITY, 1.0f);
  118. Matrix3x4 spotView = Matrix3x4(lightNode->GetWorldPosition(), lightNode->GetWorldRotation(), 1.0f).Inverse();
  119. Matrix4 spotProj(Matrix4::ZERO);
  120. Matrix4 texAdjust(Matrix4::IDENTITY);
  121. // Make the projected light slightly smaller than the shadow map to prevent light spill
  122. float h = 1.005f / tanf(light->GetFov() * M_DEGTORAD * 0.5f);
  123. float w = h / light->GetAspectRatio();
  124. spotProj.m00_ = w;
  125. spotProj.m11_ = h;
  126. spotProj.m22_ = 1.0f / Max(light->GetRange(), M_EPSILON);
  127. spotProj.m32_ = 1.0f;
  128. #ifdef USE_OPENGL
  129. texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
  130. texAdjust.SetScale(Vector3(0.5f, -0.5f, 0.5f));
  131. #else
  132. texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.0f));
  133. texAdjust.SetScale(Vector3(0.5f, -0.5f, 1.0f));
  134. #endif
  135. dest = texAdjust * spotProj * spotView * posAdjust;
  136. }
  137. void Batch::CalculateSortKey()
  138. {
  139. unsigned shaderID = ((*((unsigned*)&vertexShader_) / sizeof(ShaderVariation)) + (*((unsigned*)&pixelShader_) / sizeof(ShaderVariation))) & 0x3fff;
  140. if (!isBase_)
  141. shaderID |= 0x8000;
  142. if (pass_ && pass_->GetAlphaMask())
  143. shaderID |= 0x4000;
  144. unsigned lightQueueID = (*((unsigned*)&lightQueue_) / sizeof(LightBatchQueue)) & 0xffff;
  145. unsigned materialID = (*((unsigned*)&material_) / sizeof(Material)) & 0xffff;
  146. unsigned geometryID = (*((unsigned*)&geometry_) / sizeof(Geometry)) & 0xffff;
  147. sortKey_ = (((unsigned long long)shaderID) << 48) | (((unsigned long long)lightQueueID) << 32) |
  148. (((unsigned long long)materialID) << 16) | geometryID;
  149. }
  150. void Batch::Prepare(View* view, bool setModelTransform) const
  151. {
  152. if (!vertexShader_ || !pixelShader_)
  153. return;
  154. Graphics* graphics = view->GetGraphics();
  155. Renderer* renderer = view->GetRenderer();
  156. Node* cameraNode = camera_ ? camera_->GetNode() : 0;
  157. // Set pass / material-specific renderstates
  158. if (pass_ && material_)
  159. {
  160. bool isShadowPass = pass_->GetType() == PASS_SHADOW;
  161. graphics->SetBlendMode(pass_->GetBlendMode());
  162. renderer->SetCullMode(isShadowPass ? material_->GetShadowCullMode() : material_->GetCullMode(), camera_);
  163. if (!isShadowPass)
  164. {
  165. const BiasParameters& depthBias = material_->GetDepthBias();
  166. graphics->SetDepthBias(depthBias.constantBias_, depthBias.slopeScaledBias_);
  167. }
  168. graphics->SetDepthTest(pass_->GetDepthTestMode());
  169. graphics->SetDepthWrite(pass_->GetDepthWrite());
  170. }
  171. // Set shaders
  172. graphics->SetShaders(vertexShader_, pixelShader_);
  173. // Set global frame parameters
  174. if (graphics->NeedParameterUpdate(SP_FRAME, (void*)0))
  175. {
  176. Scene* scene = view->GetScene();
  177. if (scene)
  178. {
  179. float elapsedTime = scene->GetElapsedTime();
  180. graphics->SetShaderParameter(VSP_ELAPSEDTIME, elapsedTime);
  181. graphics->SetShaderParameter(PSP_ELAPSEDTIME, elapsedTime);
  182. }
  183. }
  184. // Set camera shader parameters
  185. unsigned cameraHash = overrideView_ ? (unsigned)(size_t)camera_ + 4 : (unsigned)(size_t)camera_;
  186. if (graphics->NeedParameterUpdate(SP_CAMERA, reinterpret_cast<void*>(cameraHash)))
  187. {
  188. // Calculate camera rotation just once
  189. Matrix3 cameraWorldRotation = cameraNode->GetWorldRotation().RotationMatrix();
  190. graphics->SetShaderParameter(VSP_CAMERAPOS, cameraNode->GetWorldPosition());
  191. graphics->SetShaderParameter(VSP_CAMERAROT, cameraWorldRotation);
  192. Vector4 depthMode = Vector4::ZERO;
  193. if (camera_->IsOrthographic())
  194. {
  195. depthMode.x_ = 1.0f;
  196. #ifdef USE_OPENGL
  197. depthMode.z_ = 0.5f;
  198. depthMode.w_ = 0.5f;
  199. #else
  200. depthMode.z_ = 1.0f;
  201. #endif
  202. }
  203. else
  204. depthMode.w_ = 1.0f / camera_->GetFarClip();
  205. graphics->SetShaderParameter(VSP_DEPTHMODE, depthMode);
  206. Vector3 nearVector, farVector;
  207. camera_->GetFrustumSize(nearVector, farVector);
  208. Vector4 viewportParams(farVector.x_, farVector.y_, farVector.z_, 0.0f);
  209. graphics->SetShaderParameter(VSP_FRUSTUMSIZE, viewportParams);
  210. Matrix4 projection = camera_->GetProjection();
  211. #ifdef USE_OPENGL
  212. // Add constant depth bias manually to the projection matrix due to glPolygonOffset() inconsistency
  213. float constantBias = 2.0f * graphics->GetDepthConstantBias();
  214. // On OpenGL ES slope-scaled bias can not be guaranteed to be available, and the shadow filtering is more coarse,
  215. // so use a higher constant bias
  216. #ifdef GL_ES_VERSION_2_0
  217. constantBias *= 1.5f;
  218. #endif
  219. projection.m22_ += projection.m32_ * constantBias;
  220. projection.m23_ += projection.m33_ * constantBias;
  221. #endif
  222. if (overrideView_)
  223. graphics->SetShaderParameter(VSP_VIEWPROJ, projection);
  224. else
  225. graphics->SetShaderParameter(VSP_VIEWPROJ, projection * camera_->GetView());
  226. graphics->SetShaderParameter(VSP_VIEWRIGHTVECTOR, cameraWorldRotation * Vector3::RIGHT);
  227. graphics->SetShaderParameter(VSP_VIEWUPVECTOR, cameraWorldRotation * Vector3::UP);
  228. }
  229. // Set viewport shader parameters
  230. IntVector2 rtSize = graphics->GetRenderTargetDimensions();
  231. IntRect viewport = graphics->GetViewport();
  232. unsigned viewportHash = (viewport.left_) | (viewport.top_ << 8) | (viewport.right_ << 16) | (viewport.bottom_ << 24);
  233. if (graphics->NeedParameterUpdate(SP_VIEWPORT, reinterpret_cast<void*>(viewportHash)))
  234. {
  235. float rtWidth = (float)rtSize.x_;
  236. float rtHeight = (float)rtSize.y_;
  237. float widthRange = 0.5f * viewport.Width() / rtWidth;
  238. float heightRange = 0.5f * viewport.Height() / rtHeight;
  239. #ifdef USE_OPENGL
  240. Vector4 bufferUVOffset(((float)viewport.left_) / rtWidth + widthRange,
  241. 1.0f - (((float)viewport.top_) / rtHeight + heightRange), widthRange, heightRange);
  242. #else
  243. Vector4 bufferUVOffset((0.5f + (float)viewport.left_) / rtWidth + widthRange,
  244. (0.5f + (float)viewport.top_) / rtHeight + heightRange, widthRange, heightRange);
  245. #endif
  246. graphics->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  247. float sizeX = 1.0f / rtWidth;
  248. float sizeY = 1.0f / rtHeight;
  249. graphics->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f));
  250. }
  251. // Set model or skinning transforms
  252. if (setModelTransform && graphics->NeedParameterUpdate(SP_OBJECTTRANSFORM, worldTransform_))
  253. {
  254. if (geometryType_ == GEOM_SKINNED)
  255. {
  256. graphics->SetShaderParameter(VSP_SKINMATRICES, reinterpret_cast<const float*>(worldTransform_),
  257. 12 * numWorldTransforms_);
  258. }
  259. else
  260. graphics->SetShaderParameter(VSP_MODEL, *worldTransform_);
  261. }
  262. // Set zone-related shader parameters
  263. BlendMode blend = graphics->GetBlendMode();
  264. Zone* fogColorZone = (blend == BLEND_ADD || blend == BLEND_ADDALPHA) ? renderer->GetDefaultZone() : zone_;
  265. unsigned zoneHash = (unsigned)(size_t)zone_ + (unsigned)(size_t)fogColorZone;
  266. if (zone_ && graphics->NeedParameterUpdate(SP_ZONE, reinterpret_cast<void*>(zoneHash)))
  267. {
  268. graphics->SetShaderParameter(VSP_AMBIENTSTARTCOLOR, zone_->GetAmbientStartColor());
  269. graphics->SetShaderParameter(VSP_AMBIENTENDCOLOR, zone_->GetAmbientEndColor().ToVector4() - zone_->GetAmbientStartColor().ToVector4());
  270. const BoundingBox& box = zone_->GetBoundingBox();
  271. Vector3 boxSize = box.Size();
  272. Matrix3x4 adjust(Matrix3x4::IDENTITY);
  273. adjust.SetScale(Vector3(1.0f / boxSize.x_, 1.0f / boxSize.y_, 1.0f / boxSize.z_));
  274. adjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
  275. Matrix3x4 zoneTransform = adjust * zone_->GetInverseWorldTransform();
  276. graphics->SetShaderParameter(VSP_ZONE, zoneTransform);
  277. graphics->SetShaderParameter(PSP_AMBIENTCOLOR, zone_->GetAmbientColor());
  278. // If the pass is additive, override fog color to black so that shaders do not need a separate additive path
  279. graphics->SetShaderParameter(PSP_FOGCOLOR, fogColorZone->GetFogColor());
  280. float farClip = camera_->GetFarClip();
  281. float fogStart = Min(zone_->GetFogStart(), farClip);
  282. float fogEnd = Min(zone_->GetFogEnd(), farClip);
  283. if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON))
  284. fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
  285. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  286. Vector4 fogParams(fogEnd / farClip, farClip / fogRange, 0.0f, 0.0f);
  287. graphics->SetShaderParameter(PSP_FOGPARAMS, fogParams);
  288. }
  289. // Set light-related shader parameters
  290. Light* light = 0;
  291. Texture2D* shadowMap = 0;
  292. if (lightQueue_)
  293. {
  294. light = lightQueue_->light_;
  295. shadowMap = lightQueue_->shadowMap_;
  296. if (graphics->NeedParameterUpdate(SP_VERTEXLIGHTS, lightQueue_) && graphics->HasShaderParameter(VS, VSP_VERTEXLIGHTS))
  297. {
  298. Vector4 vertexLights[MAX_VERTEX_LIGHTS * 3];
  299. const PODVector<Light*>& lights = lightQueue_->vertexLights_;
  300. for (unsigned i = 0; i < lights.Size(); ++i)
  301. {
  302. Light* vertexLight = lights[i];
  303. Node* vertexLightNode = vertexLight->GetNode();
  304. LightType type = vertexLight->GetLightType();
  305. // Attenuation
  306. float invRange, cutoff, invCutoff;
  307. if (type == LIGHT_DIRECTIONAL)
  308. invRange = 0.0f;
  309. else
  310. invRange = 1.0f / Max(vertexLight->GetRange(), M_EPSILON);
  311. if (type == LIGHT_SPOT)
  312. {
  313. cutoff = Cos(vertexLight->GetFov() * 0.5f);
  314. invCutoff = 1.0f / (1.0f - cutoff);
  315. }
  316. else
  317. {
  318. cutoff = -1.0f;
  319. invCutoff = 1.0f;
  320. }
  321. // Color
  322. float fade = 1.0f;
  323. float fadeEnd = vertexLight->GetDrawDistance();
  324. float fadeStart = vertexLight->GetFadeDistance();
  325. // Do fade calculation for light if both fade & draw distance defined
  326. if (vertexLight->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  327. fade = Min(1.0f - (vertexLight->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  328. Color color = vertexLight->GetColor() * fade;
  329. vertexLights[i * 3] = Vector4(color.r_, color.g_, color.b_, invRange);
  330. // Direction
  331. vertexLights[i * 3 + 1] = Vector4(-(vertexLightNode->GetWorldDirection()), cutoff);
  332. // Position
  333. vertexLights[i * 3 + 2] = Vector4(vertexLightNode->GetWorldPosition(), invCutoff);
  334. }
  335. if (lights.Size())
  336. graphics->SetShaderParameter(VSP_VERTEXLIGHTS, vertexLights[0].Data(), lights.Size() * 3 * 4);
  337. }
  338. }
  339. if (light && graphics->NeedParameterUpdate(SP_LIGHT, light))
  340. {
  341. Node* lightNode = light->GetNode();
  342. Matrix3 lightWorldRotation = lightNode->GetWorldRotation().RotationMatrix();
  343. graphics->SetShaderParameter(VSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
  344. float atten = 1.0f / Max(light->GetRange(), M_EPSILON);
  345. graphics->SetShaderParameter(VSP_LIGHTPOS, Vector4(lightNode->GetWorldPosition(), atten));
  346. if (graphics->HasShaderParameter(VS, VSP_LIGHTMATRICES))
  347. {
  348. switch (light->GetLightType())
  349. {
  350. case LIGHT_DIRECTIONAL:
  351. {
  352. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  353. unsigned numSplits = lightQueue_->shadowSplits_.Size();
  354. for (unsigned i = 0; i < numSplits; ++i)
  355. CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, Vector3::ZERO);
  356. graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
  357. }
  358. break;
  359. case LIGHT_SPOT:
  360. {
  361. Matrix4 shadowMatrices[2];
  362. CalculateSpotMatrix(shadowMatrices[0], light, Vector3::ZERO);
  363. bool isShadowed = shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP);
  364. if (isShadowed)
  365. CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, Vector3::ZERO);
  366. graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
  367. }
  368. break;
  369. case LIGHT_POINT:
  370. {
  371. Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
  372. // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
  373. // the next parameter
  374. #ifdef USE_OPENGL
  375. graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 16);
  376. #else
  377. graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 12);
  378. #endif
  379. }
  380. break;
  381. }
  382. }
  383. float fade = 1.0f;
  384. float fadeEnd = light->GetDrawDistance();
  385. float fadeStart = light->GetFadeDistance();
  386. // Do fade calculation for light if both fade & draw distance defined
  387. if (light->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  388. fade = Min(1.0f - (light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  389. graphics->SetShaderParameter(PSP_LIGHTCOLOR, Color(light->GetColor(), light->GetSpecularIntensity()) * fade);
  390. graphics->SetShaderParameter(PSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
  391. graphics->SetShaderParameter(PSP_LIGHTPOS, Vector4(lightNode->GetWorldPosition() - cameraNode->GetWorldPosition(), atten));
  392. if (graphics->HasShaderParameter(PS, PSP_LIGHTMATRICES))
  393. {
  394. switch (light->GetLightType())
  395. {
  396. case LIGHT_DIRECTIONAL:
  397. {
  398. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  399. unsigned numSplits = lightQueue_->shadowSplits_.Size();
  400. for (unsigned i = 0; i < numSplits; ++i)
  401. CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, cameraNode->GetWorldPosition());
  402. graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
  403. }
  404. break;
  405. case LIGHT_SPOT:
  406. {
  407. Matrix4 shadowMatrices[2];
  408. CalculateSpotMatrix(shadowMatrices[0], light, cameraNode->GetWorldPosition());
  409. bool isShadowed = lightQueue_->shadowMap_ != 0;
  410. if (isShadowed)
  411. CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, cameraNode->GetWorldPosition());
  412. graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
  413. }
  414. break;
  415. case LIGHT_POINT:
  416. {
  417. Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
  418. // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
  419. // the next parameter
  420. #ifdef USE_OPENGL
  421. graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 16);
  422. #else
  423. graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 12);
  424. #endif
  425. }
  426. break;
  427. }
  428. }
  429. // Set shadow mapping shader parameters
  430. if (shadowMap)
  431. {
  432. {
  433. unsigned faceWidth = shadowMap->GetWidth() / 2;
  434. unsigned faceHeight = shadowMap->GetHeight() / 3;
  435. float width = (float)shadowMap->GetWidth();
  436. float height = (float)shadowMap->GetHeight();
  437. #ifdef USE_OPENGL
  438. float mulX = (float)(faceWidth - 3) / width;
  439. float mulY = (float)(faceHeight - 3) / height;
  440. float addX = 1.5f / width;
  441. float addY = 1.5f / height;
  442. #else
  443. float mulX = (float)(faceWidth - 4) / width;
  444. float mulY = (float)(faceHeight - 4) / height;
  445. float addX = 2.5f / width;
  446. float addY = 2.5f / height;
  447. #endif
  448. // If using 4 shadow samples, offset the position diagonally by half pixel
  449. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  450. {
  451. addX -= 0.5f / width;
  452. addY -= 0.5f / height;
  453. }
  454. graphics->SetShaderParameter(PSP_SHADOWCUBEADJUST, Vector4(mulX, mulY, addX, addY));
  455. }
  456. {
  457. Camera* shadowCamera = lightQueue_->shadowSplits_[0].shadowCamera_;
  458. float nearClip = shadowCamera->GetNearClip();
  459. float farClip = shadowCamera->GetFarClip();
  460. float q = farClip / (farClip - nearClip);
  461. float r = -q * nearClip;
  462. const CascadeParameters& parameters = light->GetShadowCascade();
  463. float viewFarClip = camera_->GetFarClip();
  464. float shadowRange = parameters.GetShadowRange();
  465. float fadeStart = parameters.fadeStart_ * shadowRange / viewFarClip;
  466. float fadeEnd = shadowRange / viewFarClip;
  467. float fadeRange = fadeEnd - fadeStart;
  468. graphics->SetShaderParameter(PSP_SHADOWDEPTHFADE, Vector4(q, r, fadeStart, 1.0f / fadeRange));
  469. }
  470. {
  471. float intensity = light->GetShadowIntensity();
  472. float fadeStart = light->GetShadowFadeDistance();
  473. float fadeEnd = light->GetShadowDistance();
  474. if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart)
  475. intensity = Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f));
  476. float pcfValues = (1.0f - intensity);
  477. float samples = renderer->GetShadowQuality() >= SHADOWQUALITY_HIGH_16BIT ? 4.0f : 1.0f;
  478. graphics->SetShaderParameter(PSP_SHADOWINTENSITY, Vector4(pcfValues / samples, intensity, 0.0f, 0.0f));
  479. }
  480. float sizeX = 1.0f / (float)shadowMap->GetWidth();
  481. float sizeY = 1.0f / (float)shadowMap->GetHeight();
  482. graphics->SetShaderParameter(PSP_SHADOWMAPINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f));
  483. Vector4 lightSplits(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE);
  484. if (lightQueue_->shadowSplits_.Size() > 1)
  485. lightSplits.x_ = lightQueue_->shadowSplits_[0].farSplit_ / camera_->GetFarClip();
  486. if (lightQueue_->shadowSplits_.Size() > 2)
  487. lightSplits.y_ = lightQueue_->shadowSplits_[1].farSplit_ / camera_->GetFarClip();
  488. if (lightQueue_->shadowSplits_.Size() > 3)
  489. lightSplits.z_ = lightQueue_->shadowSplits_[2].farSplit_ / camera_->GetFarClip();
  490. graphics->SetShaderParameter(PSP_SHADOWSPLITS, lightSplits);
  491. }
  492. }
  493. // Set material-specific shader parameters and textures
  494. if (material_)
  495. {
  496. if (graphics->NeedParameterUpdate(SP_MATERIAL, material_))
  497. {
  498. const HashMap<StringHash, MaterialShaderParameter>& parameters = material_->GetShaderParameters();
  499. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
  500. graphics->SetShaderParameter(i->first_, i->second_.value_);
  501. }
  502. const SharedPtr<Texture>* textures = material_->GetTextures();
  503. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  504. {
  505. TextureUnit unit = (TextureUnit)i;
  506. if (graphics->HasTextureUnit(unit))
  507. graphics->SetTexture(i, textures[i]);
  508. }
  509. }
  510. // Set light-related textures
  511. if (light)
  512. {
  513. if (shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP))
  514. graphics->SetTexture(TU_SHADOWMAP, shadowMap);
  515. if (graphics->HasTextureUnit(TU_LIGHTRAMP))
  516. {
  517. Texture* rampTexture = light->GetRampTexture();
  518. if (!rampTexture)
  519. rampTexture = renderer->GetDefaultLightRamp();
  520. graphics->SetTexture(TU_LIGHTRAMP, rampTexture);
  521. }
  522. if (graphics->HasTextureUnit(TU_LIGHTSHAPE))
  523. {
  524. Texture* shapeTexture = light->GetShapeTexture();
  525. if (!shapeTexture && light->GetLightType() == LIGHT_SPOT)
  526. shapeTexture = renderer->GetDefaultLightSpot();
  527. graphics->SetTexture(TU_LIGHTSHAPE, shapeTexture);
  528. }
  529. }
  530. }
  531. void Batch::Draw(View* view) const
  532. {
  533. if (!geometry_->IsEmpty())
  534. {
  535. Prepare(view);
  536. geometry_->Draw(view->GetGraphics());
  537. }
  538. }
  539. void BatchGroup::SetTransforms(void* lockedData, unsigned& freeIndex)
  540. {
  541. // Do not use up buffer space if not going to draw as instanced
  542. if (geometryType_ != GEOM_INSTANCED)
  543. return;
  544. startIndex_ = freeIndex;
  545. Matrix3x4* dest = (Matrix3x4*)lockedData;
  546. dest += freeIndex;
  547. for (unsigned i = 0; i < instances_.Size(); ++i)
  548. *dest++ = *instances_[i].worldTransform_;
  549. freeIndex += instances_.Size();
  550. }
  551. void BatchGroup::Draw(View* view) const
  552. {
  553. Graphics* graphics = view->GetGraphics();
  554. Renderer* renderer = view->GetRenderer();
  555. if (instances_.Size() && !geometry_->IsEmpty())
  556. {
  557. // Draw as individual objects if instancing not supported
  558. VertexBuffer* instanceBuffer = renderer->GetInstancingBuffer();
  559. if (!instanceBuffer || geometryType_ != GEOM_INSTANCED)
  560. {
  561. Batch::Prepare(view, false);
  562. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  563. graphics->SetVertexBuffers(geometry_->GetVertexBuffers(), geometry_->GetVertexElementMasks());
  564. for (unsigned i = 0; i < instances_.Size(); ++i)
  565. {
  566. if (graphics->NeedParameterUpdate(SP_OBJECTTRANSFORM, instances_[i].worldTransform_))
  567. graphics->SetShaderParameter(VSP_MODEL, *instances_[i].worldTransform_);
  568. graphics->Draw(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  569. geometry_->GetVertexStart(), geometry_->GetVertexCount());
  570. }
  571. }
  572. else
  573. {
  574. Batch::Prepare(view, false);
  575. // Get the geometry vertex buffers, then add the instancing stream buffer
  576. // Hack: use a const_cast to avoid dynamic allocation of new temp vectors
  577. Vector<SharedPtr<VertexBuffer> >& vertexBuffers = const_cast<Vector<SharedPtr<VertexBuffer> >&>
  578. (geometry_->GetVertexBuffers());
  579. PODVector<unsigned>& elementMasks = const_cast<PODVector<unsigned>&>(geometry_->GetVertexElementMasks());
  580. vertexBuffers.Push(SharedPtr<VertexBuffer>(instanceBuffer));
  581. elementMasks.Push(instanceBuffer->GetElementMask());
  582. // No stream offset support, instancing buffer not pre-filled with transforms: have to fill now
  583. if (startIndex_ == M_MAX_UNSIGNED)
  584. {
  585. unsigned startIndex = 0;
  586. while (startIndex < instances_.Size())
  587. {
  588. unsigned instances = instances_.Size() - startIndex;
  589. if (instances > instanceBuffer->GetVertexCount())
  590. instances = instanceBuffer->GetVertexCount();
  591. // Copy the transforms
  592. Matrix3x4* dest = (Matrix3x4*)instanceBuffer->Lock(0, instances, true);
  593. if (dest)
  594. {
  595. for (unsigned i = 0; i < instances; ++i)
  596. dest[i] = *instances_[i + startIndex].worldTransform_;
  597. instanceBuffer->Unlock();
  598. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  599. graphics->SetVertexBuffers(vertexBuffers, elementMasks);
  600. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(),
  601. geometry_->GetIndexCount(), geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances);
  602. }
  603. startIndex += instances;
  604. }
  605. }
  606. // Stream offset supported and instancing buffer has been already filled, so just draw
  607. else
  608. {
  609. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  610. graphics->SetVertexBuffers(vertexBuffers, elementMasks, startIndex_);
  611. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  612. geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances_.Size());
  613. }
  614. // Remove the instancing buffer & element mask now
  615. vertexBuffers.Pop();
  616. elementMasks.Pop();
  617. }
  618. }
  619. }
  620. unsigned BatchGroupKey::ToHash() const
  621. {
  622. return ((unsigned)(size_t)zone_) / sizeof(Zone) +
  623. ((unsigned)(size_t)lightQueue_) / sizeof(LightBatchQueue) +
  624. ((unsigned)(size_t)pass_) / sizeof(Pass) +
  625. ((unsigned)(size_t)material_) / sizeof(Material) +
  626. ((unsigned)(size_t)geometry_) / sizeof(Geometry);
  627. }
  628. void BatchQueue::Clear(int maxSortedInstances)
  629. {
  630. batches_.Clear();
  631. sortedBaseBatches_.Clear();
  632. sortedBatches_.Clear();
  633. baseBatchGroups_.Clear();
  634. batchGroups_.Clear();
  635. maxSortedInstances_ = maxSortedInstances;
  636. }
  637. void BatchQueue::SortBackToFront()
  638. {
  639. sortedBaseBatches_.Clear();
  640. sortedBatches_.Resize(batches_.Size());
  641. for (unsigned i = 0; i < batches_.Size(); ++i)
  642. sortedBatches_[i] = &batches_[i];
  643. Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesBackToFront);
  644. // Do not actually sort batch groups, just list them
  645. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  646. sortedBatchGroups_.Resize(batchGroups_.Size());
  647. unsigned index = 0;
  648. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  649. sortedBaseBatchGroups_[index++] = &i->second_;
  650. index = 0;
  651. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  652. sortedBatchGroups_[index++] = &i->second_;
  653. }
  654. void BatchQueue::SortFrontToBack()
  655. {
  656. sortedBaseBatches_.Clear();
  657. sortedBatches_.Clear();
  658. // Need to divide into base and non-base batches here to ensure proper order in relation to grouped batches
  659. for (unsigned i = 0; i < batches_.Size(); ++i)
  660. {
  661. if (batches_[i].isBase_)
  662. sortedBaseBatches_.Push(&batches_[i]);
  663. else
  664. sortedBatches_.Push(&batches_[i]);
  665. }
  666. SortFrontToBack2Pass(sortedBaseBatches_);
  667. SortFrontToBack2Pass(sortedBatches_);
  668. // Sort each group front to back
  669. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  670. {
  671. if (i->second_.instances_.Size() <= maxSortedInstances_)
  672. {
  673. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  674. if (i->second_.instances_.Size())
  675. i->second_.distance_ = i->second_.instances_[0].distance_;
  676. }
  677. else
  678. {
  679. float minDistance = M_INFINITY;
  680. for (PODVector<InstanceData>::ConstIterator j = i->second_.instances_.Begin(); j != i->second_.instances_.End(); ++j)
  681. minDistance = Min(minDistance, j->distance_);
  682. i->second_.distance_ = minDistance;
  683. }
  684. }
  685. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  686. {
  687. if (i->second_.instances_.Size() <= maxSortedInstances_)
  688. {
  689. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  690. if (i->second_.instances_.Size())
  691. i->second_.distance_ = i->second_.instances_[0].distance_;
  692. }
  693. else
  694. {
  695. float minDistance = M_INFINITY;
  696. for (PODVector<InstanceData>::ConstIterator j = i->second_.instances_.Begin(); j != i->second_.instances_.End(); ++j)
  697. minDistance = Min(minDistance, j->distance_);
  698. i->second_.distance_ = minDistance;
  699. }
  700. }
  701. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  702. sortedBatchGroups_.Resize(batchGroups_.Size());
  703. unsigned index = 0;
  704. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  705. sortedBaseBatchGroups_[index++] = &i->second_;
  706. index = 0;
  707. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  708. sortedBatchGroups_[index++] = &i->second_;
  709. SortFrontToBack2Pass(reinterpret_cast<PODVector<Batch*>& >(sortedBaseBatchGroups_));
  710. SortFrontToBack2Pass(reinterpret_cast<PODVector<Batch*>& >(sortedBatchGroups_));
  711. }
  712. void BatchQueue::SortFrontToBack2Pass(PODVector<Batch*>& batches)
  713. {
  714. // Mobile devices likely use a tiled deferred approach, with which front-to-back sorting is irrelevant. The 2-pass
  715. // method is also time consuming, so just sort with state having priority
  716. #ifdef GL_ES_VERSION_2_0
  717. Sort(batches.Begin(), batches.End(), CompareBatchesState);
  718. #else
  719. // For desktop, first sort by distance and remap shader/material/geometry IDs in the sort key
  720. Sort(batches.Begin(), batches.End(), CompareBatchesFrontToBack);
  721. unsigned freeShaderID = 0;
  722. unsigned short freeMaterialID = 0;
  723. unsigned short freeGeometryID = 0;
  724. for (PODVector<Batch*>::Iterator i = batches.Begin(); i != batches.End(); ++i)
  725. {
  726. Batch* batch = *i;
  727. unsigned shaderID = (batch->sortKey_ >> 32);
  728. HashMap<unsigned, unsigned>::ConstIterator j = shaderRemapping_.Find(shaderID);
  729. if (j != shaderRemapping_.End())
  730. shaderID = j->second_;
  731. else
  732. {
  733. shaderID = shaderRemapping_[shaderID] = freeShaderID | (shaderID & 0xc0000000);
  734. ++freeShaderID;
  735. }
  736. unsigned short materialID = (unsigned short)(batch->sortKey_ & 0xffff0000);
  737. HashMap<unsigned short, unsigned short>::ConstIterator k = materialRemapping_.Find(materialID);
  738. if (k != materialRemapping_.End())
  739. materialID = k->second_;
  740. else
  741. {
  742. materialID = materialRemapping_[materialID] = freeMaterialID;
  743. ++freeMaterialID;
  744. }
  745. unsigned short geometryID = (unsigned short)(batch->sortKey_ & 0xffff);
  746. HashMap<unsigned short, unsigned short>::ConstIterator l = geometryRemapping_.Find(geometryID);
  747. if (l != geometryRemapping_.End())
  748. geometryID = l->second_;
  749. else
  750. {
  751. geometryID = geometryRemapping_[geometryID] = freeGeometryID;
  752. ++freeGeometryID;
  753. }
  754. batch->sortKey_ = (((unsigned long long)shaderID) << 32) || (((unsigned long long)materialID) << 16) | geometryID;
  755. }
  756. shaderRemapping_.Clear();
  757. materialRemapping_.Clear();
  758. geometryRemapping_.Clear();
  759. // Finally sort again with the rewritten ID's
  760. Sort(batches.Begin(), batches.End(), CompareBatchesState);
  761. #endif
  762. }
  763. void BatchQueue::SetTransforms(void* lockedData, unsigned& freeIndex)
  764. {
  765. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  766. i->second_.SetTransforms(lockedData, freeIndex);
  767. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  768. i->second_.SetTransforms(lockedData, freeIndex);
  769. }
  770. void BatchQueue::Draw(View* view, bool useScissor, bool markToStencil) const
  771. {
  772. Graphics* graphics = view->GetGraphics();
  773. Renderer* renderer = view->GetRenderer();
  774. graphics->SetScissorTest(false);
  775. // During G-buffer rendering, mark opaque pixels to stencil buffer
  776. if (!markToStencil)
  777. graphics->SetStencilTest(false);
  778. // Base instanced
  779. for (PODVector<BatchGroup*>::ConstIterator i = sortedBaseBatchGroups_.Begin(); i != sortedBaseBatchGroups_.End(); ++i)
  780. {
  781. BatchGroup* group = *i;
  782. if (markToStencil)
  783. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  784. group->Draw(view);
  785. }
  786. // Base non-instanced
  787. for (PODVector<Batch*>::ConstIterator i = sortedBaseBatches_.Begin(); i != sortedBaseBatches_.End(); ++i)
  788. {
  789. Batch* batch = *i;
  790. if (markToStencil)
  791. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  792. batch->Draw(view);
  793. }
  794. // Non-base instanced
  795. for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i)
  796. {
  797. BatchGroup* group = *i;
  798. if (useScissor && group->lightQueue_)
  799. renderer->OptimizeLightByScissor(group->lightQueue_->light_, group->camera_);
  800. if (markToStencil)
  801. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  802. group->Draw(view);
  803. }
  804. // Non-base non-instanced
  805. for (PODVector<Batch*>::ConstIterator i = sortedBatches_.Begin(); i != sortedBatches_.End(); ++i)
  806. {
  807. Batch* batch = *i;
  808. if (useScissor)
  809. {
  810. if (!batch->isBase_ && batch->lightQueue_)
  811. renderer->OptimizeLightByScissor(batch->lightQueue_->light_, batch->camera_);
  812. else
  813. graphics->SetScissorTest(false);
  814. }
  815. if (markToStencil)
  816. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  817. batch->Draw(view);
  818. }
  819. }
  820. void BatchQueue::Draw(Light* light, View* view) const
  821. {
  822. Graphics* graphics = view->GetGraphics();
  823. Renderer* renderer = view->GetRenderer();
  824. graphics->SetScissorTest(false);
  825. graphics->SetStencilTest(false);
  826. // Base instanced
  827. for (PODVector<BatchGroup*>::ConstIterator i = sortedBaseBatchGroups_.Begin(); i != sortedBaseBatchGroups_.End(); ++i)
  828. {
  829. BatchGroup* group = *i;
  830. group->Draw(view);
  831. }
  832. // Base non-instanced
  833. for (PODVector<Batch*>::ConstIterator i = sortedBaseBatches_.Begin(); i != sortedBaseBatches_.End(); ++i)
  834. {
  835. Batch* batch = *i;
  836. batch->Draw(view);
  837. }
  838. // All base passes have been drawn. Optimize at this point by both stencil volume and scissor
  839. bool optimized = false;
  840. // Non-base instanced
  841. for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i)
  842. {
  843. BatchGroup* group = *i;
  844. if (!optimized)
  845. {
  846. renderer->OptimizeLightByStencil(light, group->camera_);
  847. renderer->OptimizeLightByScissor(light, group->camera_);
  848. optimized = true;
  849. }
  850. group->Draw(view);
  851. }
  852. // Non-base non-instanced
  853. for (PODVector<Batch*>::ConstIterator i = sortedBatches_.Begin(); i != sortedBatches_.End(); ++i)
  854. {
  855. Batch* batch = *i;
  856. if (!optimized)
  857. {
  858. renderer->OptimizeLightByStencil(light, batch->camera_);
  859. renderer->OptimizeLightByScissor(light, batch->camera_);
  860. optimized = true;
  861. }
  862. batch->Draw(view);
  863. }
  864. }
  865. unsigned BatchQueue::GetNumInstances() const
  866. {
  867. unsigned total = 0;
  868. for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  869. {
  870. if (i->second_.geometryType_ == GEOM_INSTANCED)
  871. total += i->second_.instances_.Size();
  872. }
  873. for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  874. {
  875. if (i->second_.geometryType_ == GEOM_INSTANCED)
  876. total += i->second_.instances_.Size();
  877. }
  878. return total;
  879. }
  880. }