Batch.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  1. //
  2. // Copyright (c) 2008-2014 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. Matrix3x4 cameraEffectiveTransform = camera_->GetEffectiveWorldTransform();
  189. graphics->SetShaderParameter(VSP_CAMERAPOS, cameraEffectiveTransform.Translation());
  190. graphics->SetShaderParameter(VSP_CAMERAROT, cameraEffectiveTransform.RotationMatrix());
  191. float nearClip = camera_->GetNearClip();
  192. float farClip = camera_->GetFarClip();
  193. graphics->SetShaderParameter(VSP_NEARCLIP, nearClip);
  194. graphics->SetShaderParameter(VSP_FARCLIP, farClip);
  195. graphics->SetShaderParameter(PSP_NEARCLIP, nearClip);
  196. graphics->SetShaderParameter(PSP_FARCLIP, farClip);
  197. Vector4 depthMode = Vector4::ZERO;
  198. if (camera_->IsOrthographic())
  199. {
  200. depthMode.x_ = 1.0f;
  201. #ifdef USE_OPENGL
  202. depthMode.z_ = 0.5f;
  203. depthMode.w_ = 0.5f;
  204. #else
  205. depthMode.z_ = 1.0f;
  206. #endif
  207. }
  208. else
  209. depthMode.w_ = 1.0f / camera_->GetFarClip();
  210. graphics->SetShaderParameter(VSP_DEPTHMODE, depthMode);
  211. Vector3 nearVector, farVector;
  212. camera_->GetFrustumSize(nearVector, farVector);
  213. Vector4 viewportParams(farVector.x_, farVector.y_, farVector.z_, 0.0f);
  214. graphics->SetShaderParameter(VSP_FRUSTUMSIZE, viewportParams);
  215. Matrix4 projection = camera_->GetProjection();
  216. #ifdef USE_OPENGL
  217. // Add constant depth bias manually to the projection matrix due to glPolygonOffset() inconsistency
  218. float constantBias = 2.0f * graphics->GetDepthConstantBias();
  219. // On OpenGL ES slope-scaled bias can not be guaranteed to be available, and the shadow filtering is more coarse,
  220. // so use a higher constant bias
  221. #ifdef GL_ES_VERSION_2_0
  222. constantBias *= 1.5f;
  223. #endif
  224. projection.m22_ += projection.m32_ * constantBias;
  225. projection.m23_ += projection.m33_ * constantBias;
  226. #endif
  227. if (overrideView_)
  228. graphics->SetShaderParameter(VSP_VIEWPROJ, projection);
  229. else
  230. graphics->SetShaderParameter(VSP_VIEWPROJ, projection * camera_->GetView());
  231. }
  232. // Set viewport shader parameters
  233. IntVector2 rtSize = graphics->GetRenderTargetDimensions();
  234. IntRect viewport = graphics->GetViewport();
  235. unsigned viewportHash = (viewport.left_) | (viewport.top_ << 8) | (viewport.right_ << 16) | (viewport.bottom_ << 24);
  236. if (graphics->NeedParameterUpdate(SP_VIEWPORT, reinterpret_cast<void*>(viewportHash)))
  237. {
  238. float rtWidth = (float)rtSize.x_;
  239. float rtHeight = (float)rtSize.y_;
  240. float widthRange = 0.5f * viewport.Width() / rtWidth;
  241. float heightRange = 0.5f * viewport.Height() / rtHeight;
  242. #ifdef USE_OPENGL
  243. Vector4 bufferUVOffset(((float)viewport.left_) / rtWidth + widthRange,
  244. 1.0f - (((float)viewport.top_) / rtHeight + heightRange), widthRange, heightRange);
  245. #else
  246. Vector4 bufferUVOffset((0.5f + (float)viewport.left_) / rtWidth + widthRange,
  247. (0.5f + (float)viewport.top_) / rtHeight + heightRange, widthRange, heightRange);
  248. #endif
  249. graphics->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  250. float sizeX = 1.0f / rtWidth;
  251. float sizeY = 1.0f / rtHeight;
  252. graphics->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f));
  253. }
  254. // Set model or skinning transforms
  255. if (setModelTransform && graphics->NeedParameterUpdate(SP_OBJECTTRANSFORM, worldTransform_))
  256. {
  257. if (geometryType_ == GEOM_SKINNED)
  258. {
  259. graphics->SetShaderParameter(VSP_SKINMATRICES, reinterpret_cast<const float*>(worldTransform_),
  260. 12 * numWorldTransforms_);
  261. }
  262. else
  263. graphics->SetShaderParameter(VSP_MODEL, *worldTransform_);
  264. // Set the orientation for billboards, either from the object itself or from the camera
  265. if (geometryType_ == GEOM_BILLBOARD)
  266. {
  267. if (numWorldTransforms_ > 1)
  268. graphics->SetShaderParameter(VSP_BILLBOARDROT, worldTransform_[1].RotationMatrix());
  269. else
  270. graphics->SetShaderParameter(VSP_BILLBOARDROT, cameraNode->GetWorldRotation().RotationMatrix());
  271. }
  272. }
  273. // Set zone-related shader parameters
  274. BlendMode blend = graphics->GetBlendMode();
  275. Zone* fogColorZone = (blend == BLEND_ADD || blend == BLEND_ADDALPHA) ? renderer->GetDefaultZone() : zone_;
  276. unsigned zoneHash = (unsigned)(size_t)zone_ + (unsigned)(size_t)fogColorZone;
  277. if (zone_ && graphics->NeedParameterUpdate(SP_ZONE, reinterpret_cast<void*>(zoneHash)))
  278. {
  279. graphics->SetShaderParameter(VSP_AMBIENTSTARTCOLOR, zone_->GetAmbientStartColor());
  280. graphics->SetShaderParameter(VSP_AMBIENTENDCOLOR, zone_->GetAmbientEndColor().ToVector4() - zone_->GetAmbientStartColor().ToVector4());
  281. const BoundingBox& box = zone_->GetBoundingBox();
  282. Vector3 boxSize = box.Size();
  283. Matrix3x4 adjust(Matrix3x4::IDENTITY);
  284. adjust.SetScale(Vector3(1.0f / boxSize.x_, 1.0f / boxSize.y_, 1.0f / boxSize.z_));
  285. adjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
  286. Matrix3x4 zoneTransform = adjust * zone_->GetInverseWorldTransform();
  287. graphics->SetShaderParameter(VSP_ZONE, zoneTransform);
  288. graphics->SetShaderParameter(PSP_AMBIENTCOLOR, zone_->GetAmbientColor());
  289. // If the pass is additive, override fog color to black so that shaders do not need a separate additive path
  290. graphics->SetShaderParameter(PSP_FOGCOLOR, fogColorZone->GetFogColor());
  291. float farClip = camera_->GetFarClip();
  292. float fogStart = Min(zone_->GetFogStart(), farClip);
  293. float fogEnd = Min(zone_->GetFogEnd(), farClip);
  294. float fogHeight = zone_->GetFogHeight();
  295. float fogHeightScale = zone_->GetFogHeightScale();
  296. if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON))
  297. fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
  298. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  299. float fogHeightY = box.min_.y_;
  300. if (fogHeight < 0.0f)
  301. fogHeightY = box.max_.y_;
  302. Vector4 fogParams(fogEnd / farClip, farClip / fogRange, fogHeightY + fogHeight, fogHeightScale);
  303. graphics->SetShaderParameter(PSP_FOGPARAMS, fogParams);
  304. }
  305. // Set light-related shader parameters
  306. Light* light = 0;
  307. Texture2D* shadowMap = 0;
  308. if (lightQueue_)
  309. {
  310. light = lightQueue_->light_;
  311. shadowMap = lightQueue_->shadowMap_;
  312. if (graphics->NeedParameterUpdate(SP_VERTEXLIGHTS, lightQueue_) && graphics->HasShaderParameter(VS, VSP_VERTEXLIGHTS))
  313. {
  314. Vector4 vertexLights[MAX_VERTEX_LIGHTS * 3];
  315. const PODVector<Light*>& lights = lightQueue_->vertexLights_;
  316. for (unsigned i = 0; i < lights.Size(); ++i)
  317. {
  318. Light* vertexLight = lights[i];
  319. Node* vertexLightNode = vertexLight->GetNode();
  320. LightType type = vertexLight->GetLightType();
  321. // Attenuation
  322. float invRange, cutoff, invCutoff;
  323. if (type == LIGHT_DIRECTIONAL)
  324. invRange = 0.0f;
  325. else
  326. invRange = 1.0f / Max(vertexLight->GetRange(), M_EPSILON);
  327. if (type == LIGHT_SPOT)
  328. {
  329. cutoff = Cos(vertexLight->GetFov() * 0.5f);
  330. invCutoff = 1.0f / (1.0f - cutoff);
  331. }
  332. else
  333. {
  334. cutoff = -1.0f;
  335. invCutoff = 1.0f;
  336. }
  337. // Color
  338. float fade = 1.0f;
  339. float fadeEnd = vertexLight->GetDrawDistance();
  340. float fadeStart = vertexLight->GetFadeDistance();
  341. // Do fade calculation for light if both fade & draw distance defined
  342. if (vertexLight->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  343. fade = Min(1.0f - (vertexLight->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  344. Color color = vertexLight->GetColor() * fade;
  345. vertexLights[i * 3] = Vector4(color.r_, color.g_, color.b_, invRange);
  346. // Direction
  347. vertexLights[i * 3 + 1] = Vector4(-(vertexLightNode->GetWorldDirection()), cutoff);
  348. // Position
  349. vertexLights[i * 3 + 2] = Vector4(vertexLightNode->GetWorldPosition(), invCutoff);
  350. }
  351. if (lights.Size())
  352. graphics->SetShaderParameter(VSP_VERTEXLIGHTS, vertexLights[0].Data(), lights.Size() * 3 * 4);
  353. }
  354. }
  355. if (light && graphics->NeedParameterUpdate(SP_LIGHT, light))
  356. {
  357. Matrix3x4 cameraEffectiveTransform = camera_->GetEffectiveWorldTransform();
  358. Vector3 cameraEffectivePos = cameraEffectiveTransform.Translation();
  359. Node* lightNode = light->GetNode();
  360. Matrix3 lightWorldRotation = lightNode->GetWorldRotation().RotationMatrix();
  361. graphics->SetShaderParameter(VSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
  362. float atten = 1.0f / Max(light->GetRange(), M_EPSILON);
  363. graphics->SetShaderParameter(VSP_LIGHTPOS, Vector4(lightNode->GetWorldPosition(), atten));
  364. if (graphics->HasShaderParameter(VS, VSP_LIGHTMATRICES))
  365. {
  366. switch (light->GetLightType())
  367. {
  368. case LIGHT_DIRECTIONAL:
  369. {
  370. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  371. unsigned numSplits = lightQueue_->shadowSplits_.Size();
  372. for (unsigned i = 0; i < numSplits; ++i)
  373. CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, Vector3::ZERO);
  374. graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
  375. }
  376. break;
  377. case LIGHT_SPOT:
  378. {
  379. Matrix4 shadowMatrices[2];
  380. CalculateSpotMatrix(shadowMatrices[0], light, Vector3::ZERO);
  381. bool isShadowed = shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP);
  382. if (isShadowed)
  383. CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, Vector3::ZERO);
  384. graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
  385. }
  386. break;
  387. case LIGHT_POINT:
  388. {
  389. Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
  390. // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
  391. // the next parameter
  392. #ifdef USE_OPENGL
  393. graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 16);
  394. #else
  395. graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 12);
  396. #endif
  397. }
  398. break;
  399. }
  400. }
  401. float fade = 1.0f;
  402. float fadeEnd = light->GetDrawDistance();
  403. float fadeStart = light->GetFadeDistance();
  404. // Do fade calculation for light if both fade & draw distance defined
  405. if (light->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  406. fade = Min(1.0f - (light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  407. graphics->SetShaderParameter(PSP_LIGHTCOLOR, Color(light->GetColor(), light->GetSpecularIntensity()) * fade);
  408. graphics->SetShaderParameter(PSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
  409. graphics->SetShaderParameter(PSP_LIGHTPOS, Vector4(lightNode->GetWorldPosition() - cameraEffectivePos, atten));
  410. if (graphics->HasShaderParameter(PS, PSP_LIGHTMATRICES))
  411. {
  412. switch (light->GetLightType())
  413. {
  414. case LIGHT_DIRECTIONAL:
  415. {
  416. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  417. unsigned numSplits = lightQueue_->shadowSplits_.Size();
  418. for (unsigned i = 0; i < numSplits; ++i)
  419. CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, cameraEffectivePos);
  420. graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
  421. }
  422. break;
  423. case LIGHT_SPOT:
  424. {
  425. Matrix4 shadowMatrices[2];
  426. CalculateSpotMatrix(shadowMatrices[0], light, cameraEffectivePos);
  427. bool isShadowed = lightQueue_->shadowMap_ != 0;
  428. if (isShadowed)
  429. CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, cameraEffectivePos);
  430. graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
  431. }
  432. break;
  433. case LIGHT_POINT:
  434. {
  435. Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
  436. // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
  437. // the next parameter
  438. #ifdef USE_OPENGL
  439. graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 16);
  440. #else
  441. graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 12);
  442. #endif
  443. }
  444. break;
  445. }
  446. }
  447. // Set shadow mapping shader parameters
  448. if (shadowMap)
  449. {
  450. {
  451. unsigned faceWidth = shadowMap->GetWidth() / 2;
  452. unsigned faceHeight = shadowMap->GetHeight() / 3;
  453. float width = (float)shadowMap->GetWidth();
  454. float height = (float)shadowMap->GetHeight();
  455. #ifdef USE_OPENGL
  456. float mulX = (float)(faceWidth - 3) / width;
  457. float mulY = (float)(faceHeight - 3) / height;
  458. float addX = 1.5f / width;
  459. float addY = 1.5f / height;
  460. #else
  461. float mulX = (float)(faceWidth - 4) / width;
  462. float mulY = (float)(faceHeight - 4) / height;
  463. float addX = 2.5f / width;
  464. float addY = 2.5f / height;
  465. #endif
  466. // If using 4 shadow samples, offset the position diagonally by half pixel
  467. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  468. {
  469. addX -= 0.5f / width;
  470. addY -= 0.5f / height;
  471. }
  472. graphics->SetShaderParameter(PSP_SHADOWCUBEADJUST, Vector4(mulX, mulY, addX, addY));
  473. }
  474. {
  475. Camera* shadowCamera = lightQueue_->shadowSplits_[0].shadowCamera_;
  476. float nearClip = shadowCamera->GetNearClip();
  477. float farClip = shadowCamera->GetFarClip();
  478. float q = farClip / (farClip - nearClip);
  479. float r = -q * nearClip;
  480. const CascadeParameters& parameters = light->GetShadowCascade();
  481. float viewFarClip = camera_->GetFarClip();
  482. float shadowRange = parameters.GetShadowRange();
  483. float fadeStart = parameters.fadeStart_ * shadowRange / viewFarClip;
  484. float fadeEnd = shadowRange / viewFarClip;
  485. float fadeRange = fadeEnd - fadeStart;
  486. graphics->SetShaderParameter(PSP_SHADOWDEPTHFADE, Vector4(q, r, fadeStart, 1.0f / fadeRange));
  487. }
  488. {
  489. float intensity = light->GetShadowIntensity();
  490. float fadeStart = light->GetShadowFadeDistance();
  491. float fadeEnd = light->GetShadowDistance();
  492. if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart)
  493. intensity = Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f));
  494. float pcfValues = (1.0f - intensity);
  495. float samples = renderer->GetShadowQuality() >= SHADOWQUALITY_HIGH_16BIT ? 4.0f : 1.0f;
  496. graphics->SetShaderParameter(PSP_SHADOWINTENSITY, Vector4(pcfValues / samples, intensity, 0.0f, 0.0f));
  497. }
  498. float sizeX = 1.0f / (float)shadowMap->GetWidth();
  499. float sizeY = 1.0f / (float)shadowMap->GetHeight();
  500. graphics->SetShaderParameter(PSP_SHADOWMAPINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f));
  501. Vector4 lightSplits(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE);
  502. if (lightQueue_->shadowSplits_.Size() > 1)
  503. lightSplits.x_ = lightQueue_->shadowSplits_[0].farSplit_ / camera_->GetFarClip();
  504. if (lightQueue_->shadowSplits_.Size() > 2)
  505. lightSplits.y_ = lightQueue_->shadowSplits_[1].farSplit_ / camera_->GetFarClip();
  506. if (lightQueue_->shadowSplits_.Size() > 3)
  507. lightSplits.z_ = lightQueue_->shadowSplits_[2].farSplit_ / camera_->GetFarClip();
  508. graphics->SetShaderParameter(PSP_SHADOWSPLITS, lightSplits);
  509. }
  510. }
  511. // Set material-specific shader parameters and textures
  512. if (material_)
  513. {
  514. if (graphics->NeedParameterUpdate(SP_MATERIAL, material_))
  515. {
  516. const HashMap<StringHash, MaterialShaderParameter>& parameters = material_->GetShaderParameters();
  517. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
  518. graphics->SetShaderParameter(i->first_, i->second_.value_);
  519. }
  520. const SharedPtr<Texture>* textures = material_->GetTextures();
  521. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  522. {
  523. TextureUnit unit = (TextureUnit)i;
  524. if (textures[i] && graphics->HasTextureUnit(unit))
  525. graphics->SetTexture(i, textures[i]);
  526. }
  527. }
  528. // Set light-related textures
  529. if (light)
  530. {
  531. if (shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP))
  532. graphics->SetTexture(TU_SHADOWMAP, shadowMap);
  533. if (graphics->HasTextureUnit(TU_LIGHTRAMP))
  534. {
  535. Texture* rampTexture = light->GetRampTexture();
  536. if (!rampTexture)
  537. rampTexture = renderer->GetDefaultLightRamp();
  538. graphics->SetTexture(TU_LIGHTRAMP, rampTexture);
  539. }
  540. if (graphics->HasTextureUnit(TU_LIGHTSHAPE))
  541. {
  542. Texture* shapeTexture = light->GetShapeTexture();
  543. if (!shapeTexture && light->GetLightType() == LIGHT_SPOT)
  544. shapeTexture = renderer->GetDefaultLightSpot();
  545. graphics->SetTexture(TU_LIGHTSHAPE, shapeTexture);
  546. }
  547. }
  548. }
  549. void Batch::Draw(View* view) const
  550. {
  551. if (!geometry_->IsEmpty())
  552. {
  553. Prepare(view);
  554. geometry_->Draw(view->GetGraphics());
  555. }
  556. }
  557. void BatchGroup::SetTransforms(void* lockedData, unsigned& freeIndex)
  558. {
  559. // Do not use up buffer space if not going to draw as instanced
  560. if (geometryType_ != GEOM_INSTANCED)
  561. return;
  562. startIndex_ = freeIndex;
  563. Matrix3x4* dest = (Matrix3x4*)lockedData;
  564. dest += freeIndex;
  565. for (unsigned i = 0; i < instances_.Size(); ++i)
  566. *dest++ = *instances_[i].worldTransform_;
  567. freeIndex += instances_.Size();
  568. }
  569. void BatchGroup::Draw(View* view) const
  570. {
  571. Graphics* graphics = view->GetGraphics();
  572. Renderer* renderer = view->GetRenderer();
  573. if (instances_.Size() && !geometry_->IsEmpty())
  574. {
  575. // Draw as individual objects if instancing not supported
  576. VertexBuffer* instanceBuffer = renderer->GetInstancingBuffer();
  577. if (!instanceBuffer || geometryType_ != GEOM_INSTANCED)
  578. {
  579. Batch::Prepare(view, false);
  580. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  581. graphics->SetVertexBuffers(geometry_->GetVertexBuffers(), geometry_->GetVertexElementMasks());
  582. for (unsigned i = 0; i < instances_.Size(); ++i)
  583. {
  584. if (graphics->NeedParameterUpdate(SP_OBJECTTRANSFORM, instances_[i].worldTransform_))
  585. graphics->SetShaderParameter(VSP_MODEL, *instances_[i].worldTransform_);
  586. graphics->Draw(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  587. geometry_->GetVertexStart(), geometry_->GetVertexCount());
  588. }
  589. }
  590. else
  591. {
  592. Batch::Prepare(view, false);
  593. // Get the geometry vertex buffers, then add the instancing stream buffer
  594. // Hack: use a const_cast to avoid dynamic allocation of new temp vectors
  595. Vector<SharedPtr<VertexBuffer> >& vertexBuffers = const_cast<Vector<SharedPtr<VertexBuffer> >&>
  596. (geometry_->GetVertexBuffers());
  597. PODVector<unsigned>& elementMasks = const_cast<PODVector<unsigned>&>(geometry_->GetVertexElementMasks());
  598. vertexBuffers.Push(SharedPtr<VertexBuffer>(instanceBuffer));
  599. elementMasks.Push(instanceBuffer->GetElementMask());
  600. // No stream offset support, instancing buffer not pre-filled with transforms: have to fill now
  601. if (startIndex_ == M_MAX_UNSIGNED)
  602. {
  603. unsigned startIndex = 0;
  604. while (startIndex < instances_.Size())
  605. {
  606. unsigned instances = instances_.Size() - startIndex;
  607. if (instances > instanceBuffer->GetVertexCount())
  608. instances = instanceBuffer->GetVertexCount();
  609. // Copy the transforms
  610. Matrix3x4* dest = (Matrix3x4*)instanceBuffer->Lock(0, instances, true);
  611. if (dest)
  612. {
  613. for (unsigned i = 0; i < instances; ++i)
  614. dest[i] = *instances_[i + startIndex].worldTransform_;
  615. instanceBuffer->Unlock();
  616. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  617. graphics->SetVertexBuffers(vertexBuffers, elementMasks);
  618. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(),
  619. geometry_->GetIndexCount(), geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances);
  620. }
  621. startIndex += instances;
  622. }
  623. }
  624. // Stream offset supported and instancing buffer has been already filled, so just draw
  625. else
  626. {
  627. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  628. graphics->SetVertexBuffers(vertexBuffers, elementMasks, startIndex_);
  629. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  630. geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances_.Size());
  631. }
  632. // Remove the instancing buffer & element mask now
  633. vertexBuffers.Pop();
  634. elementMasks.Pop();
  635. }
  636. }
  637. }
  638. unsigned BatchGroupKey::ToHash() const
  639. {
  640. return ((unsigned)(size_t)zone_) / sizeof(Zone) +
  641. ((unsigned)(size_t)lightQueue_) / sizeof(LightBatchQueue) +
  642. ((unsigned)(size_t)pass_) / sizeof(Pass) +
  643. ((unsigned)(size_t)material_) / sizeof(Material) +
  644. ((unsigned)(size_t)geometry_) / sizeof(Geometry);
  645. }
  646. void BatchQueue::Clear(int maxSortedInstances)
  647. {
  648. batches_.Clear();
  649. sortedBaseBatches_.Clear();
  650. sortedBatches_.Clear();
  651. baseBatchGroups_.Clear();
  652. batchGroups_.Clear();
  653. maxSortedInstances_ = maxSortedInstances;
  654. }
  655. void BatchQueue::SortBackToFront()
  656. {
  657. sortedBaseBatches_.Clear();
  658. sortedBatches_.Resize(batches_.Size());
  659. for (unsigned i = 0; i < batches_.Size(); ++i)
  660. sortedBatches_[i] = &batches_[i];
  661. Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesBackToFront);
  662. // Do not actually sort batch groups, just list them
  663. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  664. sortedBatchGroups_.Resize(batchGroups_.Size());
  665. unsigned index = 0;
  666. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  667. sortedBaseBatchGroups_[index++] = &i->second_;
  668. index = 0;
  669. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  670. sortedBatchGroups_[index++] = &i->second_;
  671. }
  672. void BatchQueue::SortFrontToBack()
  673. {
  674. sortedBaseBatches_.Clear();
  675. sortedBatches_.Clear();
  676. // Need to divide into base and non-base batches here to ensure proper order in relation to grouped batches
  677. for (unsigned i = 0; i < batches_.Size(); ++i)
  678. {
  679. if (batches_[i].isBase_)
  680. sortedBaseBatches_.Push(&batches_[i]);
  681. else
  682. sortedBatches_.Push(&batches_[i]);
  683. }
  684. SortFrontToBack2Pass(sortedBaseBatches_);
  685. SortFrontToBack2Pass(sortedBatches_);
  686. // Sort each group front to back
  687. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  688. {
  689. if (i->second_.instances_.Size() <= maxSortedInstances_)
  690. {
  691. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  692. if (i->second_.instances_.Size())
  693. i->second_.distance_ = i->second_.instances_[0].distance_;
  694. }
  695. else
  696. {
  697. float minDistance = M_INFINITY;
  698. for (PODVector<InstanceData>::ConstIterator j = i->second_.instances_.Begin(); j != i->second_.instances_.End(); ++j)
  699. minDistance = Min(minDistance, j->distance_);
  700. i->second_.distance_ = minDistance;
  701. }
  702. }
  703. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  704. {
  705. if (i->second_.instances_.Size() <= maxSortedInstances_)
  706. {
  707. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  708. if (i->second_.instances_.Size())
  709. i->second_.distance_ = i->second_.instances_[0].distance_;
  710. }
  711. else
  712. {
  713. float minDistance = M_INFINITY;
  714. for (PODVector<InstanceData>::ConstIterator j = i->second_.instances_.Begin(); j != i->second_.instances_.End(); ++j)
  715. minDistance = Min(minDistance, j->distance_);
  716. i->second_.distance_ = minDistance;
  717. }
  718. }
  719. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  720. sortedBatchGroups_.Resize(batchGroups_.Size());
  721. unsigned index = 0;
  722. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  723. sortedBaseBatchGroups_[index++] = &i->second_;
  724. index = 0;
  725. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  726. sortedBatchGroups_[index++] = &i->second_;
  727. SortFrontToBack2Pass(reinterpret_cast<PODVector<Batch*>& >(sortedBaseBatchGroups_));
  728. SortFrontToBack2Pass(reinterpret_cast<PODVector<Batch*>& >(sortedBatchGroups_));
  729. }
  730. void BatchQueue::SortFrontToBack2Pass(PODVector<Batch*>& batches)
  731. {
  732. // Mobile devices likely use a tiled deferred approach, with which front-to-back sorting is irrelevant. The 2-pass
  733. // method is also time consuming, so just sort with state having priority
  734. #ifdef GL_ES_VERSION_2_0
  735. Sort(batches.Begin(), batches.End(), CompareBatchesState);
  736. #else
  737. // For desktop, first sort by distance and remap shader/material/geometry IDs in the sort key
  738. Sort(batches.Begin(), batches.End(), CompareBatchesFrontToBack);
  739. unsigned freeShaderID = 0;
  740. unsigned short freeMaterialID = 0;
  741. unsigned short freeGeometryID = 0;
  742. for (PODVector<Batch*>::Iterator i = batches.Begin(); i != batches.End(); ++i)
  743. {
  744. Batch* batch = *i;
  745. unsigned shaderID = (batch->sortKey_ >> 32);
  746. HashMap<unsigned, unsigned>::ConstIterator j = shaderRemapping_.Find(shaderID);
  747. if (j != shaderRemapping_.End())
  748. shaderID = j->second_;
  749. else
  750. {
  751. shaderID = shaderRemapping_[shaderID] = freeShaderID | (shaderID & 0xc0000000);
  752. ++freeShaderID;
  753. }
  754. unsigned short materialID = (unsigned short)(batch->sortKey_ & 0xffff0000);
  755. HashMap<unsigned short, unsigned short>::ConstIterator k = materialRemapping_.Find(materialID);
  756. if (k != materialRemapping_.End())
  757. materialID = k->second_;
  758. else
  759. {
  760. materialID = materialRemapping_[materialID] = freeMaterialID;
  761. ++freeMaterialID;
  762. }
  763. unsigned short geometryID = (unsigned short)(batch->sortKey_ & 0xffff);
  764. HashMap<unsigned short, unsigned short>::ConstIterator l = geometryRemapping_.Find(geometryID);
  765. if (l != geometryRemapping_.End())
  766. geometryID = l->second_;
  767. else
  768. {
  769. geometryID = geometryRemapping_[geometryID] = freeGeometryID;
  770. ++freeGeometryID;
  771. }
  772. batch->sortKey_ = (((unsigned long long)shaderID) << 32) || (((unsigned long long)materialID) << 16) | geometryID;
  773. }
  774. shaderRemapping_.Clear();
  775. materialRemapping_.Clear();
  776. geometryRemapping_.Clear();
  777. // Finally sort again with the rewritten ID's
  778. Sort(batches.Begin(), batches.End(), CompareBatchesState);
  779. #endif
  780. }
  781. void BatchQueue::SetTransforms(void* lockedData, unsigned& freeIndex)
  782. {
  783. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  784. i->second_.SetTransforms(lockedData, freeIndex);
  785. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  786. i->second_.SetTransforms(lockedData, freeIndex);
  787. }
  788. void BatchQueue::Draw(View* view, bool useScissor, bool markToStencil) const
  789. {
  790. Graphics* graphics = view->GetGraphics();
  791. Renderer* renderer = view->GetRenderer();
  792. graphics->SetScissorTest(false);
  793. // During G-buffer rendering, mark opaque pixels to stencil buffer
  794. if (!markToStencil)
  795. graphics->SetStencilTest(false);
  796. // Base instanced
  797. for (PODVector<BatchGroup*>::ConstIterator i = sortedBaseBatchGroups_.Begin(); i != sortedBaseBatchGroups_.End(); ++i)
  798. {
  799. BatchGroup* group = *i;
  800. if (markToStencil)
  801. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  802. group->Draw(view);
  803. }
  804. // Base non-instanced
  805. for (PODVector<Batch*>::ConstIterator i = sortedBaseBatches_.Begin(); i != sortedBaseBatches_.End(); ++i)
  806. {
  807. Batch* batch = *i;
  808. if (markToStencil)
  809. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  810. batch->Draw(view);
  811. }
  812. // Non-base instanced
  813. for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i)
  814. {
  815. BatchGroup* group = *i;
  816. if (useScissor && group->lightQueue_)
  817. renderer->OptimizeLightByScissor(group->lightQueue_->light_, group->camera_);
  818. if (markToStencil)
  819. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  820. group->Draw(view);
  821. }
  822. // Non-base non-instanced
  823. for (PODVector<Batch*>::ConstIterator i = sortedBatches_.Begin(); i != sortedBatches_.End(); ++i)
  824. {
  825. Batch* batch = *i;
  826. if (useScissor)
  827. {
  828. if (!batch->isBase_ && batch->lightQueue_)
  829. renderer->OptimizeLightByScissor(batch->lightQueue_->light_, batch->camera_);
  830. else
  831. graphics->SetScissorTest(false);
  832. }
  833. if (markToStencil)
  834. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  835. batch->Draw(view);
  836. }
  837. }
  838. void BatchQueue::Draw(Light* light, View* view) const
  839. {
  840. Graphics* graphics = view->GetGraphics();
  841. Renderer* renderer = view->GetRenderer();
  842. graphics->SetScissorTest(false);
  843. graphics->SetStencilTest(false);
  844. // Base instanced
  845. for (PODVector<BatchGroup*>::ConstIterator i = sortedBaseBatchGroups_.Begin(); i != sortedBaseBatchGroups_.End(); ++i)
  846. {
  847. BatchGroup* group = *i;
  848. group->Draw(view);
  849. }
  850. // Base non-instanced
  851. for (PODVector<Batch*>::ConstIterator i = sortedBaseBatches_.Begin(); i != sortedBaseBatches_.End(); ++i)
  852. {
  853. Batch* batch = *i;
  854. batch->Draw(view);
  855. }
  856. // All base passes have been drawn. Optimize at this point by both stencil volume and scissor
  857. bool optimized = false;
  858. // Non-base instanced
  859. for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i)
  860. {
  861. BatchGroup* group = *i;
  862. if (!optimized)
  863. {
  864. renderer->OptimizeLightByStencil(light, group->camera_);
  865. renderer->OptimizeLightByScissor(light, group->camera_);
  866. optimized = true;
  867. }
  868. group->Draw(view);
  869. }
  870. // Non-base non-instanced
  871. for (PODVector<Batch*>::ConstIterator i = sortedBatches_.Begin(); i != sortedBatches_.End(); ++i)
  872. {
  873. Batch* batch = *i;
  874. if (!optimized)
  875. {
  876. renderer->OptimizeLightByStencil(light, batch->camera_);
  877. renderer->OptimizeLightByScissor(light, batch->camera_);
  878. optimized = true;
  879. }
  880. batch->Draw(view);
  881. }
  882. }
  883. unsigned BatchQueue::GetNumInstances() const
  884. {
  885. unsigned total = 0;
  886. for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  887. {
  888. if (i->second_.geometryType_ == GEOM_INSTANCED)
  889. total += i->second_.instances_.Size();
  890. }
  891. for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  892. {
  893. if (i->second_.geometryType_ == GEOM_INSTANCED)
  894. total += i->second_.instances_.Size();
  895. }
  896. return total;
  897. }
  898. }