Batch.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "Geometry.h"
  26. #include "Graphics.h"
  27. #include "GraphicsImpl.h"
  28. #include "Light.h"
  29. #include "Material.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 "Zone.h"
  38. #include "DebugNew.h"
  39. inline bool CompareBatchesFrontToBack(Batch* lhs, Batch* rhs)
  40. {
  41. if (lhs->sortKey_ == rhs->sortKey_)
  42. return lhs->distance_ < rhs->distance_;
  43. else
  44. return lhs->sortKey_ > rhs->sortKey_;
  45. }
  46. inline bool CompareBatchesBackToFront(Batch* lhs, Batch* rhs)
  47. {
  48. if (lhs->distance_ == rhs->distance_)
  49. return lhs->sortKey_ > rhs->sortKey_;
  50. else
  51. return lhs->distance_ > rhs->distance_;
  52. }
  53. inline bool CompareInstancesFrontToBack(const InstanceData& lhs, const InstanceData& rhs)
  54. {
  55. return lhs.distance_ < rhs.distance_;
  56. }
  57. inline bool CompareBatchGroupsFrontToBack(BatchGroup* lhs, BatchGroup* rhs)
  58. {
  59. return lhs->instances_[0].distance_ < rhs->instances_[0].distance_;
  60. }
  61. void Batch::CalculateSortKey()
  62. {
  63. unsigned lightQueue = (*((unsigned*)&lightQueue_) / sizeof(LightBatchQueue)) & 0x7fff;
  64. unsigned pass = (*((unsigned*)&pass_) / sizeof(Pass)) & 0xffff;
  65. unsigned material = (*((unsigned*)&material_) / sizeof(Material)) & 0xffff;
  66. unsigned geometry = (*((unsigned*)&geometry_) / sizeof(Geometry)) & 0xffff;
  67. if (isBase_)
  68. lightQueue |= 0x8000;
  69. sortKey_ = (((unsigned long long)lightQueue) << 48) | (((unsigned long long)pass) << 32) |
  70. (((unsigned long long)material) << 16) | geometry;
  71. }
  72. void Batch::Prepare(Graphics* graphics, Renderer* renderer, bool setModelTransform) const
  73. {
  74. if (!vertexShader_ || !pixelShader_)
  75. return;
  76. // Set pass / material-specific renderstates
  77. if (pass_ && material_)
  78. {
  79. if (pass_->GetAlphaTest())
  80. graphics->SetAlphaTest(true, CMP_GREATEREQUAL, 0.5f);
  81. else
  82. graphics->SetAlphaTest(false);
  83. graphics->SetBlendMode(pass_->GetBlendMode());
  84. graphics->SetCullMode(pass_->GetType() != PASS_SHADOW ? material_->GetCullMode() : material_->GetShadowCullMode());
  85. graphics->SetDepthTest(pass_->GetDepthTestMode());
  86. graphics->SetDepthWrite(pass_->GetDepthWrite());
  87. }
  88. // Set shaders
  89. graphics->SetShaders(vertexShader_, pixelShader_);
  90. // Set viewport and camera shader parameters
  91. if (graphics->NeedParameterUpdate(VSP_CAMERAPOS, camera_))
  92. graphics->SetShaderParameter(VSP_CAMERAPOS, camera_->GetWorldPosition());
  93. if (graphics->NeedParameterUpdate(VSP_CAMERAROT, camera_))
  94. graphics->SetShaderParameter(VSP_CAMERAROT, camera_->GetWorldTransform().RotationMatrix());
  95. if (graphics->NeedParameterUpdate(VSP_DEPTHMODE, camera_))
  96. {
  97. Vector4 depthMode = Vector4::ZERO;
  98. if (camera_->IsOrthographic())
  99. {
  100. depthMode.x_ = 1.0f;
  101. #ifdef USE_OPENGL
  102. depthMode.z_ = 0.5f;
  103. depthMode.w_ = 0.5f;
  104. #else
  105. depthMode.z_ = 1.0f;
  106. #endif
  107. }
  108. else
  109. depthMode.w_ = 1.0f / camera_->GetFarClip();
  110. graphics->SetShaderParameter(VSP_DEPTHMODE, depthMode);
  111. }
  112. if (graphics->NeedParameterUpdate(VSP_FRUSTUMSIZE, camera_))
  113. {
  114. Vector3 nearVector, farVector;
  115. camera_->GetFrustumSize(nearVector, farVector);
  116. Vector4 viewportParams(farVector.x_, farVector.y_, farVector.z_, 0.0f);
  117. graphics->SetShaderParameter(VSP_FRUSTUMSIZE, viewportParams);
  118. }
  119. IntRect viewport = graphics->GetViewport();
  120. unsigned viewportHash = (viewport.left_) | (viewport.top_ << 8) | (viewport.right_ << 16) | (viewport.bottom_ << 24);
  121. if (graphics->NeedParameterUpdate(VSP_GBUFFEROFFSETS, (const void*)viewportHash))
  122. {
  123. IntVector2 screenSize = graphics->GetRenderTargetDimensions();
  124. float gBufferWidth = (float)screenSize.x_;
  125. float gBufferHeight = (float)screenSize.y_;
  126. float widthRange = 0.5f * (viewport.right_ - viewport.left_) / gBufferWidth;
  127. float heightRange = 0.5f * (viewport.bottom_ - viewport.top_) / gBufferHeight;
  128. #ifdef USE_OPENGL
  129. Vector4 bufferUVOffset(((float)viewport.left_) / gBufferWidth + widthRange,
  130. ((float)viewport.top_) / gBufferHeight + heightRange, widthRange, heightRange);
  131. #else
  132. Vector4 bufferUVOffset((0.5f + (float)viewport.left_) / gBufferWidth + widthRange,
  133. (0.5f + (float)viewport.top_) / gBufferHeight + heightRange, widthRange, heightRange);
  134. #endif
  135. graphics->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  136. }
  137. if (overrideView_)
  138. {
  139. if (graphics->NeedParameterUpdate(VSP_VIEWPROJ, ((unsigned char*)camera_) + 4))
  140. graphics->SetShaderParameter(VSP_VIEWPROJ, camera_->GetProjection());
  141. }
  142. else
  143. {
  144. if (graphics->NeedParameterUpdate(VSP_VIEWPROJ, camera_))
  145. graphics->SetShaderParameter(VSP_VIEWPROJ, camera_->GetProjection() *
  146. camera_->GetInverseWorldTransform());
  147. }
  148. if (graphics->NeedParameterUpdate(VSP_VIEWRIGHTVECTOR, camera_))
  149. graphics->SetShaderParameter(VSP_VIEWRIGHTVECTOR, camera_->GetRightVector());
  150. if (graphics->NeedParameterUpdate(VSP_VIEWUPVECTOR, camera_))
  151. graphics->SetShaderParameter(VSP_VIEWUPVECTOR, camera_->GetUpVector());
  152. // Set model transform
  153. if (setModelTransform && graphics->NeedParameterUpdate(VSP_MODEL, worldTransform_))
  154. graphics->SetShaderParameter(VSP_MODEL, *worldTransform_);
  155. // Set skinning transforms
  156. if (shaderData_ && shaderDataSize_)
  157. {
  158. if (graphics->NeedParameterUpdate(VSP_SKINMATRICES, shaderData_))
  159. graphics->SetShaderParameter(VSP_SKINMATRICES, shaderData_, shaderDataSize_);
  160. }
  161. // Set zone-related shader parameters
  162. if (zone_)
  163. {
  164. if (graphics->NeedParameterUpdate(VSP_ZONE, zone_))
  165. {
  166. const BoundingBox& box = zone_->GetBoundingBox();
  167. Vector3 boxSize = box.Size();
  168. Matrix3x4 adjust(Matrix3x4::IDENTITY);
  169. adjust.SetScale(Vector3(1.0f / boxSize.x_, 1.0f / boxSize.y_, 1.0f / boxSize.z_));
  170. adjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
  171. Matrix3x4 zoneTransform = adjust * zone_->GetWorldTransform().Inverse();
  172. graphics->SetShaderParameter(VSP_ZONE, zoneTransform);
  173. }
  174. if (graphics->NeedParameterUpdate(PSP_AMBIENTSTARTCOLOR, zone_))
  175. graphics->SetShaderParameter(PSP_AMBIENTSTARTCOLOR, zone_->GetAmbientStartColor().ToVector4());
  176. if (graphics->NeedParameterUpdate(PSP_AMBIENTENDCOLOR, zone_))
  177. graphics->SetShaderParameter(PSP_AMBIENTENDCOLOR, zone_->GetAmbientEndColor().ToVector4() - zone_->GetAmbientStartColor().ToVector4());
  178. // If the pass is additive, override fog color to black so that shaders do not need a separate additive path
  179. BlendMode blend = pass_->GetBlendMode();
  180. Zone* fogColorZone = (blend == BLEND_ADD || blend == BLEND_ADDALPHA) ? renderer->GetDefaultZone() : zone_;
  181. if (graphics->NeedParameterUpdate(PSP_FOGCOLOR, fogColorZone))
  182. graphics->SetShaderParameter(PSP_FOGCOLOR, fogColorZone->GetFogColor().ToVector4());
  183. if (graphics->NeedParameterUpdate(PSP_FOGPARAMS, zone_))
  184. {
  185. float farClip = camera_->GetFarClip();
  186. float nearClip = camera_->GetNearClip();
  187. float fogStart = Min(zone_->GetFogStart(), farClip);
  188. float fogEnd = Min(zone_->GetFogEnd(), farClip);
  189. if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON))
  190. fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
  191. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  192. Vector4 fogParams(fogStart / farClip, fogEnd / farClip, farClip / fogRange, 0.0f);
  193. graphics->SetShaderParameter(PSP_FOGPARAMS, fogParams);
  194. }
  195. }
  196. if (graphics->NeedParameterUpdate(PSP_DEPTHRECONSTRUCT, camera_))
  197. {
  198. float farClip = camera_->GetFarClip();
  199. float nearClip = camera_->GetNearClip();
  200. Vector4 depthReconstruct(farClip / (farClip - nearClip), -nearClip / (farClip - nearClip), 0.0f, 0.0f);
  201. graphics->SetShaderParameter(PSP_DEPTHRECONSTRUCT, depthReconstruct);
  202. }
  203. // Set light-related shader parameters
  204. Light* light = 0;
  205. Texture2D* shadowMap = 0;
  206. if (lightQueue_)
  207. {
  208. light = lightQueue_->light_;
  209. shadowMap = lightQueue_->shadowMap_;
  210. if (graphics->NeedParameterUpdate(VSP_LIGHTDIR, light))
  211. graphics->SetShaderParameter(VSP_LIGHTDIR, light->GetWorldRotation() * Vector3::BACK);
  212. if (graphics->NeedParameterUpdate(VSP_LIGHTPOS, light))
  213. {
  214. float atten = 1.0f / Max(light->GetRange(), M_EPSILON);
  215. graphics->SetShaderParameter(VSP_LIGHTPOS, Vector4(light->GetWorldPosition(), atten));
  216. }
  217. if (graphics->NeedParameterUpdate(VSP_LIGHTVECROT, light))
  218. {
  219. Matrix3x4 lightVecRot(Vector3::ZERO, light->GetWorldRotation(), Vector3::ONE);
  220. graphics->SetShaderParameter(VSP_LIGHTVECROT, lightVecRot);
  221. }
  222. if (graphics->NeedParameterUpdate(VSP_SPOTPROJ, light))
  223. {
  224. Matrix3x4 spotView(light->GetWorldPosition(), light->GetWorldRotation(), 1.0f);
  225. Matrix4 spotProj(Matrix4::ZERO);
  226. Matrix4 texAdjust(Matrix4::IDENTITY);
  227. // Make the projected light slightly smaller than the shadow map to prevent light spill
  228. float h = 1.005f / tanf(light->GetFov() * M_DEGTORAD * 0.5f);
  229. float w = h / light->GetAspectRatio();
  230. spotProj.m00_ = w;
  231. spotProj.m11_ = h;
  232. spotProj.m22_ = 1.0f / Max(light->GetRange(), M_EPSILON);
  233. spotProj.m32_ = 1.0f;
  234. #ifdef USE_OPENGL
  235. texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
  236. texAdjust.SetScale(Vector3(0.5f, -0.5f, 0.5f));
  237. #else
  238. texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.0f));
  239. texAdjust.SetScale(Vector3(0.5f, -0.5f, 1.0f));
  240. #endif
  241. graphics->SetShaderParameter(VSP_SPOTPROJ, texAdjust * spotProj * spotView.Inverse());
  242. }
  243. if (graphics->NeedParameterUpdate(VSP_VERTEXLIGHTS, lightQueue_))
  244. {
  245. Vector4 vertexLights[MAX_VERTEX_LIGHTS * 3];
  246. const PODVector<Light*>& lights = lightQueue_->vertexLights_;
  247. for (unsigned i = 0; i < lights.Size(); ++i)
  248. {
  249. Light* vertexLight = lights[i];
  250. LightType type = vertexLight->GetLightType();
  251. // Attenuation
  252. float invRange, cutoff, invCutoff;
  253. if (type == LIGHT_DIRECTIONAL)
  254. invRange = 0.0f;
  255. else
  256. invRange = 1.0f / Max(vertexLight->GetRange(), M_EPSILON);
  257. if (type == LIGHT_SPOT)
  258. {
  259. cutoff = cosf(vertexLight->GetFov() * 0.5f * M_DEGTORAD);
  260. invCutoff = 1.0f / (1.0f - cutoff);
  261. }
  262. else
  263. {
  264. cutoff = -1.0f;
  265. invCutoff = 1.0f;
  266. }
  267. // Color
  268. float fade = 1.0f;
  269. float fadeEnd = vertexLight->GetDrawDistance();
  270. float fadeStart = vertexLight->GetFadeDistance();
  271. // Do fade calculation for light if both fade & draw distance defined
  272. if (vertexLight->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  273. fade = Min(1.0f - (vertexLight->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  274. Color color = vertexLight->GetColor() * fade;
  275. vertexLights[i * 3] = Vector4(color.r_, color.g_, color.b_, invRange);
  276. // Direction
  277. vertexLights[i * 3 + 1] = Vector4(-(vertexLight->GetNode()->GetWorldDirection()), cutoff);
  278. // Position
  279. vertexLights[i * 3 + 2] = Vector4(vertexLight->GetWorldPosition(), invCutoff);
  280. }
  281. if (lights.Size())
  282. graphics->SetShaderParameter(VSP_VERTEXLIGHTS, vertexLights[0].GetData(), lights.Size() * 3 * 4);
  283. }
  284. if (graphics->NeedParameterUpdate(PSP_LIGHTCOLOR, light))
  285. {
  286. float fade = 1.0f;
  287. float fadeEnd = light->GetDrawDistance();
  288. float fadeStart = light->GetFadeDistance();
  289. // Do fade calculation for light if both fade & draw distance defined
  290. if (light->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  291. fade = Min(1.0f - (light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  292. graphics->SetShaderParameter(PSP_LIGHTCOLOR, Vector4(light->GetColor().RGBValues(),
  293. light->GetSpecularIntensity()) * fade);
  294. }
  295. // Set shadow mapping shader parameters
  296. if (shadowMap)
  297. {
  298. if (graphics->NeedParameterUpdate(VSP_SHADOWPROJ, light))
  299. {
  300. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  301. unsigned numSplits = 1;
  302. if (light->GetLightType() == LIGHT_DIRECTIONAL)
  303. numSplits = lightQueue_->shadowSplits_.Size();
  304. for (unsigned i = 0; i < numSplits; ++i)
  305. {
  306. Camera* shadowCamera = lightQueue_->shadowSplits_[i].shadowCamera_;
  307. const IntRect& viewport = lightQueue_->shadowSplits_[i].shadowViewport_;
  308. Matrix3x4 shadowView(shadowCamera->GetInverseWorldTransform());
  309. Matrix4 shadowProj(shadowCamera->GetProjection());
  310. Matrix4 texAdjust(Matrix4::IDENTITY);
  311. float width = (float)shadowMap->GetWidth();
  312. float height = (float)shadowMap->GetHeight();
  313. Vector2 offset(
  314. (float)viewport.left_ / width,
  315. (float)viewport.top_ / height
  316. );
  317. Vector2 scale(
  318. 0.5f * (float)(viewport.right_ - viewport.left_) / width,
  319. 0.5f * (float)(viewport.bottom_ - viewport.top_) / height
  320. );
  321. #ifdef USE_OPENGL
  322. offset.x_ += scale.x_;
  323. offset.y_ += scale.y_;
  324. offset.y_ = 1.0f - offset.y_;
  325. // If using 4 shadow samples, offset the position diagonally by half pixel
  326. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  327. {
  328. offset.x_ -= 0.5f / width;
  329. offset.y_ -= 0.5f / height;
  330. }
  331. texAdjust.SetTranslation(Vector3(offset.x_, offset.y_, 0.5f));
  332. texAdjust.SetScale(Vector3(scale.x_, scale.y_, 0.5f));
  333. #else
  334. offset.x_ += scale.x_ + 0.5f / width;
  335. offset.y_ += scale.y_ + 0.5f / height;
  336. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  337. {
  338. offset.x_ -= 0.5f / width;
  339. offset.y_ -= 0.5f / height;
  340. }
  341. // If using 2 shadow samples (fallback mode), offset the position horizontally only
  342. if (graphics->GetFallback())
  343. offset.x_ -= 0.5f / width;
  344. scale.y_ = -scale.y_;
  345. texAdjust.SetTranslation(Vector3(offset.x_, offset.y_, 0.0f));
  346. texAdjust.SetScale(Vector3(scale.x_, scale.y_, 1.0f));
  347. #endif
  348. shadowMatrices[i] = texAdjust * shadowProj * shadowView;
  349. }
  350. graphics->SetShaderParameter(VSP_SHADOWPROJ, shadowMatrices[0].GetData(), 16 * numSplits);
  351. }
  352. if (graphics->NeedParameterUpdate(PSP_SAMPLEOFFSETS, shadowMap))
  353. {
  354. float addX = 1.0f / (float)shadowMap->GetWidth();
  355. float addY = 1.0f / (float)shadowMap->GetHeight();
  356. graphics->SetShaderParameter(PSP_SAMPLEOFFSETS, Vector4(addX, addY, 0.0f, 0.0f));
  357. }
  358. if (graphics->NeedParameterUpdate(PSP_SHADOWCUBEADJUST, light))
  359. {
  360. unsigned faceWidth = shadowMap->GetWidth() / 2;
  361. unsigned faceHeight = shadowMap->GetHeight() / 3;
  362. float width = (float)shadowMap->GetWidth();
  363. float height = (float)shadowMap->GetHeight();
  364. #ifdef USE_OPENGL
  365. float mulX = (float)(faceWidth - 3) / width;
  366. float mulY = (float)(faceHeight - 3) / height;
  367. float addX = 1.5f / width;
  368. float addY = 1.5f / height;
  369. #else
  370. float mulX = (float)(faceWidth - 4) / width;
  371. float mulY = (float)(faceHeight - 4) / height;
  372. float addX = 2.5f / width;
  373. float addY = 2.5f / height;
  374. #endif
  375. // If using 4 shadow samples, offset the position diagonally by half pixel
  376. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  377. {
  378. addX -= 0.5f / width;
  379. addY -= 0.5f / height;
  380. }
  381. // If using 2 shadow samples (fallback mode), offset the position horizontally only
  382. if (graphics->GetFallback())
  383. addX -= 0.5f / width;
  384. graphics->SetShaderParameter(PSP_SHADOWCUBEADJUST, Vector4(mulX, mulY, addX, addY));
  385. }
  386. if (graphics->NeedParameterUpdate(PSP_SHADOWDEPTHFADE, light))
  387. {
  388. // Note: we use the shadow camera of the first cube face. All are assumed to use the same projection
  389. Camera* shadowCamera = lightQueue_->shadowSplits_[0].shadowCamera_;
  390. float nearClip = shadowCamera->GetNearClip();
  391. float farClip = shadowCamera->GetFarClip();
  392. float q = farClip / (farClip - nearClip);
  393. float r = -q * nearClip;
  394. const CascadeParameters& parameters = light->GetShadowCascade();
  395. float viewFarClip = camera_->GetFarClip();
  396. float shadowRange = parameters.GetShadowRange();
  397. float fadeStart = parameters.fadeStart_ * shadowRange / viewFarClip;
  398. float fadeEnd = shadowRange / viewFarClip;
  399. float fadeRange = fadeEnd - fadeStart;
  400. graphics->SetShaderParameter(PSP_SHADOWDEPTHFADE, Vector4(q, r, fadeStart, 1.0f / fadeRange));
  401. }
  402. if (graphics->NeedParameterUpdate(PSP_SHADOWINTENSITY, light))
  403. {
  404. float intensity = light->GetShadowIntensity();
  405. float fadeStart = light->GetShadowFadeDistance();
  406. float fadeEnd = light->GetShadowDistance();
  407. if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart)
  408. intensity = Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f));
  409. float pcfValues = (1.0f - intensity);
  410. float samples = 4.0f;
  411. float fallbackBias = 0.0f;
  412. // Fallback mode requires manual depth biasing. We do not do proper slope scale biasing,
  413. // instead just fudge the bias values together
  414. if (graphics->GetFallback())
  415. {
  416. samples = 2.0f;
  417. fallbackBias = graphics->GetDepthConstantBias() + 2.0f * graphics->GetDepthSlopeScaledBias() *
  418. graphics->GetDepthConstantBias();
  419. }
  420. graphics->SetShaderParameter(PSP_SHADOWINTENSITY, Vector4(pcfValues, pcfValues / samples, intensity, fallbackBias));
  421. }
  422. if (graphics->NeedParameterUpdate(PSP_SHADOWSPLITS, light))
  423. {
  424. Vector4 lightSplits(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE);
  425. if (lightQueue_->shadowSplits_.Size() > 1)
  426. lightSplits.x_ = lightQueue_->shadowSplits_[0].farSplit_ / camera_->GetFarClip();
  427. if (lightQueue_->shadowSplits_.Size() > 2)
  428. lightSplits.y_ = lightQueue_->shadowSplits_[1].farSplit_ / camera_->GetFarClip();
  429. if (lightQueue_->shadowSplits_.Size() > 3)
  430. lightSplits.z_ = lightQueue_->shadowSplits_[2].farSplit_ / camera_->GetFarClip();
  431. graphics->SetShaderParameter(PSP_SHADOWSPLITS, lightSplits);
  432. }
  433. }
  434. }
  435. // Set material-specific shader parameters and textures
  436. if (material_)
  437. {
  438. const HashMap<StringHash, MaterialShaderParameter>& parameters = material_->GetShaderParameters();
  439. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
  440. {
  441. if (graphics->NeedParameterUpdate(i->first_, material_))
  442. graphics->SetShaderParameter(i->first_, i->second_.value_);
  443. }
  444. const Vector<SharedPtr<Texture> >& textures = material_->GetTextures();
  445. if (graphics->NeedTextureUnit(TU_DIFFUSE))
  446. graphics->SetTexture(TU_DIFFUSE, textures[TU_DIFFUSE]);
  447. if (graphics->NeedTextureUnit(TU_NORMAL))
  448. graphics->SetTexture(TU_NORMAL, textures[TU_NORMAL]);
  449. if (graphics->NeedTextureUnit(TU_SPECULAR))
  450. graphics->SetTexture(TU_NORMAL, textures[TU_SPECULAR]);
  451. if (graphics->NeedTextureUnit(TU_DETAIL))
  452. graphics->SetTexture(TU_DETAIL, textures[TU_DETAIL]);
  453. if (graphics->NeedTextureUnit(TU_ENVIRONMENT))
  454. graphics->SetTexture(TU_ENVIRONMENT, textures[TU_ENVIRONMENT]);
  455. }
  456. // Set light-related textures
  457. if (light)
  458. {
  459. if (shadowMap && graphics->NeedTextureUnit(TU_SHADOWMAP))
  460. graphics->SetTexture(TU_SHADOWMAP, shadowMap);
  461. if (graphics->NeedTextureUnit(TU_LIGHTRAMP))
  462. {
  463. Texture* rampTexture = light->GetRampTexture();
  464. if (!rampTexture)
  465. rampTexture = renderer->GetDefaultLightRamp();
  466. graphics->SetTexture(TU_LIGHTRAMP, rampTexture);
  467. }
  468. if (graphics->NeedTextureUnit(TU_LIGHTSHAPE))
  469. {
  470. Texture* shapeTexture = light->GetShapeTexture();
  471. if (!shapeTexture && light->GetLightType() == LIGHT_SPOT)
  472. shapeTexture = renderer->GetDefaultLightSpot();
  473. graphics->SetTexture(TU_LIGHTSHAPE, shapeTexture);
  474. }
  475. }
  476. }
  477. void Batch::Draw(Graphics* graphics, Renderer* renderer) const
  478. {
  479. Prepare(graphics, renderer);
  480. geometry_->Draw(graphics);
  481. }
  482. void BatchGroup::SetTransforms(Renderer* renderer, void* lockedData, unsigned& freeIndex)
  483. {
  484. // Do not use up buffer space if not going to draw as instanced
  485. if (geometry_->GetIndexCount() > (unsigned)renderer->GetMaxInstanceTriangles() * 3)
  486. return;
  487. startIndex_ = freeIndex;
  488. Matrix3x4* dest = (Matrix3x4*)lockedData;
  489. dest += freeIndex;
  490. for (unsigned i = 0; i < instances_.Size(); ++i)
  491. *dest++ = *instances_[i].worldTransform_;
  492. freeIndex += instances_.Size();
  493. }
  494. void BatchGroup::Draw(Graphics* graphics, Renderer* renderer) const
  495. {
  496. if (!instances_.Size())
  497. return;
  498. // Draw as individual objects if instancing not supported
  499. VertexBuffer* instanceBuffer = renderer->GetInstancingBuffer();
  500. if (!instanceBuffer || geometry_->GetIndexCount() > (unsigned)renderer->GetMaxInstanceTriangles() * 3)
  501. {
  502. Batch::Prepare(graphics, renderer, false);
  503. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  504. graphics->SetVertexBuffers(geometry_->GetVertexBuffers(), geometry_->GetVertexElementMasks());
  505. for (unsigned i = 0; i < instances_.Size(); ++i)
  506. {
  507. graphics->SetShaderParameter(VSP_MODEL, *instances_[i].worldTransform_);
  508. graphics->Draw(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  509. geometry_->GetVertexStart(), geometry_->GetVertexCount());
  510. }
  511. graphics->ClearTransformSources();
  512. }
  513. else
  514. {
  515. Batch::Prepare(graphics, renderer, false);
  516. // Get the geometry vertex buffers, then add the instancing stream buffer
  517. // Hack: use a const_cast to avoid dynamic allocation of new temp vectors
  518. Vector<SharedPtr<VertexBuffer> >& vertexBuffers = const_cast<Vector<SharedPtr<VertexBuffer> >&>
  519. (geometry_->GetVertexBuffers());
  520. PODVector<unsigned>& elementMasks = const_cast<PODVector<unsigned>&>(geometry_->GetVertexElementMasks());
  521. vertexBuffers.Push(SharedPtr<VertexBuffer>(instanceBuffer));
  522. elementMasks.Push(instanceBuffer->GetElementMask());
  523. // No stream offset support, instancing buffer not pre-filled with transforms: have to lock and fill now
  524. if (startIndex_ == M_MAX_UNSIGNED)
  525. {
  526. unsigned startIndex = 0;
  527. while (startIndex < instances_.Size())
  528. {
  529. unsigned instances = instances_.Size() - startIndex;
  530. if (instances > instanceBuffer->GetVertexCount())
  531. instances = instanceBuffer->GetVertexCount();
  532. // Lock the instance stream buffer and copy the transforms
  533. void* data = instanceBuffer->Lock(0, instances, LOCK_DISCARD);
  534. if (!data)
  535. {
  536. // Remember to remove the instancing buffer and element mask
  537. vertexBuffers.Pop();
  538. elementMasks.Pop();
  539. return;
  540. }
  541. Matrix3x4* dest = (Matrix3x4*)data;
  542. for (unsigned i = 0; i < instances; ++i)
  543. dest[i] = *instances_[i + startIndex].worldTransform_;
  544. instanceBuffer->Unlock();
  545. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  546. graphics->SetVertexBuffers(vertexBuffers, elementMasks);
  547. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  548. geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances);
  549. startIndex += instances;
  550. }
  551. }
  552. // Stream offset supported, and instancing buffer has been already filled, so just draw
  553. else
  554. {
  555. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  556. graphics->SetVertexBuffers(vertexBuffers, elementMasks, startIndex_);
  557. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  558. geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances_.Size());
  559. }
  560. // Remove the instancing buffer & element mask now
  561. vertexBuffers.Pop();
  562. elementMasks.Pop();
  563. }
  564. }
  565. void BatchQueue::Clear()
  566. {
  567. batches_.Clear();
  568. sortedBaseBatches_.Clear();
  569. sortedBatches_.Clear();
  570. baseBatchGroups_.Clear();
  571. batchGroups_.Clear();
  572. }
  573. void BatchQueue::AddBatch(const Batch& batch)
  574. {
  575. // Important: this function does not check whether the batch can actually be instanced. It must have been checked before,
  576. // including setting the correct vertex shader (non-instanced or instanced)
  577. if (batch.geometryType_ != GEOM_INSTANCED)
  578. batches_.Push(batch);
  579. else
  580. {
  581. Map<BatchGroupKey, BatchGroup>* groups = batch.isBase_ ? &baseBatchGroups_ : &batchGroups_;
  582. BatchGroupKey key(batch);
  583. Map<BatchGroupKey, BatchGroup>::Iterator i = groups->Find(key);
  584. if (i == groups->End())
  585. {
  586. // Create a new group based on the batch
  587. BatchGroup newGroup(batch);
  588. newGroup.instances_.Push(InstanceData(batch.worldTransform_, batch.distance_));
  589. groups->Insert(MakePair(key, newGroup));
  590. }
  591. else
  592. i->second_.instances_.Push(InstanceData(batch.worldTransform_, batch.distance_));
  593. }
  594. }
  595. void BatchQueue::SortBackToFront()
  596. {
  597. sortedBaseBatches_.Clear();
  598. sortedBatches_.Resize(batches_.Size());
  599. for (unsigned i = 0; i < batches_.Size(); ++i)
  600. sortedBatches_[i] = &batches_[i];
  601. Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesBackToFront);
  602. // Do not actually sort batch groups, just list them
  603. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  604. sortedBatchGroups_.Resize(batchGroups_.Size());
  605. unsigned index = 0;
  606. for (Map<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  607. sortedBaseBatchGroups_[index++] = &i->second_;
  608. index = 0;
  609. for (Map<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  610. sortedBatchGroups_[index++] = &i->second_;
  611. }
  612. void BatchQueue::SortFrontToBack()
  613. {
  614. sortedBaseBatches_.Clear();
  615. sortedBatches_.Clear();
  616. // Must explicitly divide into base and non-base batches, so that priorities do not get mixed up between
  617. // instanced and non-instanced batches
  618. for (unsigned i = 0; i < batches_.Size(); ++i)
  619. {
  620. if (batches_[i].isBase_)
  621. sortedBaseBatches_.Push(&batches_[i]);
  622. else
  623. sortedBatches_.Push(&batches_[i]);
  624. }
  625. Sort(sortedBaseBatches_.Begin(), sortedBaseBatches_.End(), CompareBatchesFrontToBack);
  626. Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesFrontToBack);
  627. // Sort each group front to back
  628. for (Map<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  629. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  630. for (Map<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  631. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  632. // Now sort batch groups by the distance of the first batch
  633. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  634. sortedBatchGroups_.Resize(batchGroups_.Size());
  635. unsigned index = 0;
  636. for (Map<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  637. sortedBaseBatchGroups_[index++] = &i->second_;
  638. index = 0;
  639. for (Map<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  640. sortedBatchGroups_[index++] = &i->second_;
  641. Sort(sortedBaseBatchGroups_.Begin(), sortedBaseBatchGroups_.End(), CompareBatchGroupsFrontToBack);
  642. Sort(sortedBatchGroups_.Begin(), sortedBatchGroups_.End(), CompareBatchGroupsFrontToBack);
  643. }
  644. void BatchQueue::SetTransforms(Renderer* renderer, void* lockedData, unsigned& freeIndex)
  645. {
  646. for (Map<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  647. i->second_.SetTransforms(renderer, lockedData, freeIndex);
  648. for (Map<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  649. i->second_.SetTransforms(renderer, lockedData, freeIndex);
  650. }
  651. unsigned BatchQueue::GetNumInstances(Renderer* renderer) const
  652. {
  653. unsigned total = 0;
  654. unsigned maxIndexCount = renderer->GetMaxInstanceTriangles() * 3;
  655. // This is for the purpose of calculating how much space is needed in the instancing buffer. Do not add groups
  656. // that have too many triangles
  657. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  658. {
  659. if (i->second_.geometry_->GetIndexCount() <= maxIndexCount)
  660. total += i->second_.instances_.Size();
  661. }
  662. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  663. {
  664. if (i->second_.geometry_->GetIndexCount() <= maxIndexCount)
  665. total += i->second_.instances_.Size();
  666. }
  667. return total;
  668. }