Batch.cpp 42 KB

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