Batch.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. //
  2. // Copyright (c) 2008-2015 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 "../Graphics/Camera.h"
  24. #include "../Graphics/Geometry.h"
  25. #include "../Graphics/Graphics.h"
  26. #include "../Graphics/GraphicsImpl.h"
  27. #include "../Graphics/Material.h"
  28. #include "../Scene/Node.h"
  29. #include "../Graphics/Renderer.h"
  30. #include "../Core/Profiler.h"
  31. #include "../Scene/Scene.h"
  32. #include "../Graphics/ShaderVariation.h"
  33. #include "../Container/Sort.h"
  34. #include "../Graphics/Technique.h"
  35. #include "../Graphics/Texture2D.h"
  36. #include "../Graphics/VertexBuffer.h"
  37. #include "../Graphics/View.h"
  38. #include "../Graphics/Zone.h"
  39. #include "../DebugNew.h"
  40. namespace Atomic
  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. Vector3 offset(
  81. (float)viewport.left_ / width,
  82. (float)viewport.top_ / height,
  83. 0.0f
  84. );
  85. Vector3 scale(
  86. 0.5f * (float)viewport.Width() / width,
  87. 0.5f * (float)viewport.Height() / height,
  88. 1.0f
  89. );
  90. // Add pixel-perfect offset if needed by the graphics API
  91. const Vector2& pixelUVOffset = Graphics::GetPixelUVOffset();
  92. offset.x_ += scale.x_ + pixelUVOffset.x_ / width;
  93. offset.y_ += scale.y_ + pixelUVOffset.y_ / height;
  94. #ifdef ATOMIC_OPENGL
  95. offset.z_ = 0.5f;
  96. scale.z_ = 0.5f;
  97. offset.y_ = 1.0f - offset.y_;
  98. #else
  99. scale.y_ = -scale.y_;
  100. #endif
  101. // If using 4 shadow samples, offset the position diagonally by half pixel
  102. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  103. {
  104. offset.x_ -= 0.5f / width;
  105. offset.y_ -= 0.5f / height;
  106. }
  107. texAdjust.SetTranslation(offset);
  108. texAdjust.SetScale(scale);
  109. dest = texAdjust * shadowProj * shadowView * posAdjust;
  110. }
  111. void CalculateSpotMatrix(Matrix4& dest, Light* light, const Vector3& translation)
  112. {
  113. Node* lightNode = light->GetNode();
  114. Matrix3x4 posAdjust(translation, Quaternion::IDENTITY, 1.0f);
  115. Matrix3x4 spotView = Matrix3x4(lightNode->GetWorldPosition(), lightNode->GetWorldRotation(), 1.0f).Inverse();
  116. Matrix4 spotProj(Matrix4::ZERO);
  117. Matrix4 texAdjust(Matrix4::IDENTITY);
  118. // Make the projected light slightly smaller than the shadow map to prevent light spill
  119. float h = 1.005f / tanf(light->GetFov() * M_DEGTORAD * 0.5f);
  120. float w = h / light->GetAspectRatio();
  121. spotProj.m00_ = w;
  122. spotProj.m11_ = h;
  123. spotProj.m22_ = 1.0f / Max(light->GetRange(), M_EPSILON);
  124. spotProj.m32_ = 1.0f;
  125. #ifdef ATOMIC_OPENGL
  126. texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
  127. texAdjust.SetScale(Vector3(0.5f, -0.5f, 0.5f));
  128. #else
  129. texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.0f));
  130. texAdjust.SetScale(Vector3(0.5f, -0.5f, 1.0f));
  131. #endif
  132. dest = texAdjust * spotProj * spotView * posAdjust;
  133. }
  134. void Batch::CalculateSortKey()
  135. {
  136. unsigned shaderID = ((*((unsigned*)&vertexShader_) / sizeof(ShaderVariation)) + (*((unsigned*)&pixelShader_) / sizeof(ShaderVariation))) & 0x3fff;
  137. if (!isBase_)
  138. shaderID |= 0x8000;
  139. if (pass_ && pass_->GetAlphaMask())
  140. shaderID |= 0x4000;
  141. unsigned lightQueueID = (*((unsigned*)&lightQueue_) / sizeof(LightBatchQueue)) & 0xffff;
  142. unsigned materialID = (*((unsigned*)&material_) / sizeof(Material)) & 0xffff;
  143. unsigned geometryID = (*((unsigned*)&geometry_) / sizeof(Geometry)) & 0xffff;
  144. sortKey_ = (((unsigned long long)shaderID) << 48) | (((unsigned long long)lightQueueID) << 32) |
  145. (((unsigned long long)materialID) << 16) | geometryID;
  146. }
  147. void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) const
  148. {
  149. if (!vertexShader_ || !pixelShader_)
  150. return;
  151. Graphics* graphics = view->GetGraphics();
  152. Renderer* renderer = view->GetRenderer();
  153. Node* cameraNode = camera_ ? camera_->GetNode() : 0;
  154. Light* light = lightQueue_ ? lightQueue_->light_ : 0;
  155. Texture2D* shadowMap = lightQueue_ ? lightQueue_->shadowMap_ : 0;
  156. // Set shaders first. The available shader parameters and their register/uniform positions depend on the currently set shaders
  157. graphics->SetShaders(vertexShader_, pixelShader_);
  158. // Set pass / material-specific renderstates
  159. if (pass_ && material_)
  160. {
  161. BlendMode blend = pass_->GetBlendMode();
  162. // Turn additive blending into subtract if the light is negative
  163. if (light && light->IsNegative())
  164. {
  165. if (blend == BLEND_ADD)
  166. blend = BLEND_SUBTRACT;
  167. else if (blend == BLEND_ADDALPHA)
  168. blend = BLEND_SUBTRACTALPHA;
  169. }
  170. graphics->SetBlendMode(blend);
  171. bool isShadowPass = pass_->GetIndex() == Technique::shadowPassIndex;
  172. renderer->SetCullMode(isShadowPass ? material_->GetShadowCullMode() : material_->GetCullMode(), camera_);
  173. if (!isShadowPass)
  174. {
  175. const BiasParameters& depthBias = material_->GetDepthBias();
  176. graphics->SetDepthBias(depthBias.constantBias_, depthBias.slopeScaledBias_);
  177. }
  178. // Use the "least filled" fill mode combined from camera & material
  179. graphics->SetFillMode((FillMode)(Max(camera_->GetFillMode(), material_->GetFillMode())));
  180. graphics->SetDepthTest(pass_->GetDepthTestMode());
  181. graphics->SetDepthWrite(pass_->GetDepthWrite() && allowDepthWrite);
  182. }
  183. // Set global (per-frame) shader parameters
  184. if (graphics->NeedParameterUpdate(SP_FRAME, (void*)0))
  185. view->SetGlobalShaderParameters();
  186. // Set camera & viewport shader parameters
  187. unsigned cameraHash = (unsigned)(size_t)camera_;
  188. IntRect viewport = graphics->GetViewport();
  189. IntVector2 viewSize = IntVector2(viewport.Width(), viewport.Height());
  190. unsigned viewportHash = viewSize.x_ | (viewSize.y_ << 16);
  191. if (graphics->NeedParameterUpdate(SP_CAMERA, reinterpret_cast<const void*>(cameraHash + viewportHash)))
  192. {
  193. view->SetCameraShaderParameters(camera_, true);
  194. // During renderpath commands the G-Buffer or viewport texture is assumed to always be viewport-sized
  195. view->SetGBufferShaderParameters(viewSize, IntRect(0, 0, viewSize.x_, viewSize.y_));
  196. }
  197. // Set model or skinning transforms
  198. if (setModelTransform && graphics->NeedParameterUpdate(SP_OBJECT, worldTransform_))
  199. {
  200. if (geometryType_ == GEOM_SKINNED)
  201. {
  202. graphics->SetShaderParameter(VSP_SKINMATRICES, reinterpret_cast<const float*>(worldTransform_),
  203. 12 * numWorldTransforms_);
  204. }
  205. else
  206. graphics->SetShaderParameter(VSP_MODEL, *worldTransform_);
  207. // Set the orientation for billboards, either from the object itself or from the camera
  208. if (geometryType_ == GEOM_BILLBOARD)
  209. {
  210. if (numWorldTransforms_ > 1)
  211. graphics->SetShaderParameter(VSP_BILLBOARDROT, worldTransform_[1].RotationMatrix());
  212. else
  213. graphics->SetShaderParameter(VSP_BILLBOARDROT, cameraNode->GetWorldRotation().RotationMatrix());
  214. }
  215. }
  216. if (lightmapTilingOffset_)
  217. {
  218. graphics->SetShaderParameter(VSP_LMOFFSET, *lightmapTilingOffset_);
  219. }
  220. // Set zone-related shader parameters
  221. BlendMode blend = graphics->GetBlendMode();
  222. // If the pass is additive, override fog color to black so that shaders do not need a separate additive path
  223. bool overrideFogColorToBlack = blend == BLEND_ADD || blend == BLEND_ADDALPHA;
  224. unsigned zoneHash = (unsigned)(size_t)zone_;
  225. if (overrideFogColorToBlack)
  226. zoneHash += 0x80000000;
  227. if (zone_ && graphics->NeedParameterUpdate(SP_ZONE, reinterpret_cast<const void*>(zoneHash)))
  228. {
  229. graphics->SetShaderParameter(VSP_AMBIENTSTARTCOLOR, zone_->GetAmbientStartColor());
  230. graphics->SetShaderParameter(VSP_AMBIENTENDCOLOR, zone_->GetAmbientEndColor().ToVector4() - zone_->GetAmbientStartColor().ToVector4());
  231. const BoundingBox& box = zone_->GetBoundingBox();
  232. Vector3 boxSize = box.Size();
  233. Matrix3x4 adjust(Matrix3x4::IDENTITY);
  234. adjust.SetScale(Vector3(1.0f / boxSize.x_, 1.0f / boxSize.y_, 1.0f / boxSize.z_));
  235. adjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
  236. Matrix3x4 zoneTransform = adjust * zone_->GetInverseWorldTransform();
  237. graphics->SetShaderParameter(VSP_ZONE, zoneTransform);
  238. graphics->SetShaderParameter(PSP_AMBIENTCOLOR, zone_->GetAmbientColor());
  239. graphics->SetShaderParameter(PSP_FOGCOLOR, overrideFogColorToBlack ? Color::BLACK : zone_->GetFogColor());
  240. float farClip = camera_->GetFarClip();
  241. float fogStart = Min(zone_->GetFogStart(), farClip);
  242. float fogEnd = Min(zone_->GetFogEnd(), farClip);
  243. if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON))
  244. fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
  245. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  246. Vector4 fogParams(fogEnd / farClip, farClip / fogRange, 0.0f, 0.0f);
  247. Node* zoneNode = zone_->GetNode();
  248. if (zone_->GetHeightFog() && zoneNode)
  249. {
  250. Vector3 worldFogHeightVec = zoneNode->GetWorldTransform() * Vector3(0.0f, zone_->GetFogHeight(), 0.0f);
  251. fogParams.z_ = worldFogHeightVec.y_;
  252. fogParams.w_ = zone_->GetFogHeightScale() / Max(zoneNode->GetWorldScale().y_, M_EPSILON);
  253. }
  254. graphics->SetShaderParameter(PSP_FOGPARAMS, fogParams);
  255. }
  256. // Set light-related shader parameters
  257. if (lightQueue_)
  258. {
  259. if (light && graphics->NeedParameterUpdate(SP_LIGHT, lightQueue_))
  260. {
  261. // Deferred light volume batches operate in a camera-centered space. Detect from material, zone & pass all being null
  262. bool isLightVolume = !material_ && !pass_ && !zone_;
  263. Matrix3x4 cameraEffectiveTransform = camera_->GetEffectiveWorldTransform();
  264. Vector3 cameraEffectivePos = cameraEffectiveTransform.Translation();
  265. Node* lightNode = light->GetNode();
  266. Matrix3 lightWorldRotation = lightNode->GetWorldRotation().RotationMatrix();
  267. graphics->SetShaderParameter(VSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
  268. float atten = 1.0f / Max(light->GetRange(), M_EPSILON);
  269. graphics->SetShaderParameter(VSP_LIGHTPOS, Vector4(lightNode->GetWorldPosition(), atten));
  270. if (graphics->HasShaderParameter(VSP_LIGHTMATRICES))
  271. {
  272. switch (light->GetLightType())
  273. {
  274. case LIGHT_DIRECTIONAL:
  275. {
  276. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  277. unsigned numSplits = Min(MAX_CASCADE_SPLITS, (int)lightQueue_->shadowSplits_.Size());
  278. for (unsigned i = 0; i < numSplits; ++i)
  279. CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, Vector3::ZERO);
  280. graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
  281. }
  282. break;
  283. case LIGHT_SPOT:
  284. {
  285. Matrix4 shadowMatrices[2];
  286. CalculateSpotMatrix(shadowMatrices[0], light, Vector3::ZERO);
  287. bool isShadowed = shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP);
  288. if (isShadowed)
  289. CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, Vector3::ZERO);
  290. graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
  291. }
  292. break;
  293. case LIGHT_POINT:
  294. {
  295. Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
  296. // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
  297. // the next parameter
  298. #ifdef ATOMIC_OPENGL
  299. graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 16);
  300. #else
  301. graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 12);
  302. #endif
  303. }
  304. break;
  305. }
  306. }
  307. float fade = 1.0f;
  308. float fadeEnd = light->GetDrawDistance();
  309. float fadeStart = light->GetFadeDistance();
  310. // Do fade calculation for light if both fade & draw distance defined
  311. if (light->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  312. fade = Min(1.0f - (light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  313. // Negative lights will use subtract blending, so write absolute RGB values to the shader parameter
  314. graphics->SetShaderParameter(PSP_LIGHTCOLOR, Color(light->GetEffectiveColor().Abs(),
  315. light->GetEffectiveSpecularIntensity()) * fade);
  316. graphics->SetShaderParameter(PSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
  317. graphics->SetShaderParameter(PSP_LIGHTPOS, Vector4((isLightVolume ? (lightNode->GetWorldPosition() -
  318. cameraEffectivePos) : lightNode->GetWorldPosition()), atten));
  319. if (graphics->HasShaderParameter(PSP_LIGHTMATRICES))
  320. {
  321. switch (light->GetLightType())
  322. {
  323. case LIGHT_DIRECTIONAL:
  324. {
  325. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  326. unsigned numSplits = Min(MAX_CASCADE_SPLITS, (int)lightQueue_->shadowSplits_.Size());
  327. for (unsigned i = 0; i < numSplits; ++i)
  328. {
  329. CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, isLightVolume ? cameraEffectivePos :
  330. Vector3::ZERO);
  331. }
  332. graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
  333. }
  334. break;
  335. case LIGHT_SPOT:
  336. {
  337. Matrix4 shadowMatrices[2];
  338. CalculateSpotMatrix(shadowMatrices[0], light, cameraEffectivePos);
  339. bool isShadowed = lightQueue_->shadowMap_ != 0;
  340. if (isShadowed)
  341. {
  342. CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, isLightVolume ? cameraEffectivePos :
  343. Vector3::ZERO);
  344. }
  345. graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
  346. }
  347. break;
  348. case LIGHT_POINT:
  349. {
  350. Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
  351. // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
  352. // the next parameter
  353. #ifdef ATOMIC_OPENGL
  354. graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 16);
  355. #else
  356. graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 12);
  357. #endif
  358. }
  359. break;
  360. }
  361. }
  362. // Set shadow mapping shader parameters
  363. if (shadowMap)
  364. {
  365. {
  366. // Calculate point light shadow sampling offsets (unrolled cube map)
  367. unsigned faceWidth = shadowMap->GetWidth() / 2;
  368. unsigned faceHeight = shadowMap->GetHeight() / 3;
  369. float width = (float)shadowMap->GetWidth();
  370. float height = (float)shadowMap->GetHeight();
  371. #ifdef ATOMIC_OPENGL
  372. float mulX = (float)(faceWidth - 3) / width;
  373. float mulY = (float)(faceHeight - 3) / height;
  374. float addX = 1.5f / width;
  375. float addY = 1.5f / height;
  376. #else
  377. float mulX = (float)(faceWidth - 4) / width;
  378. float mulY = (float)(faceHeight - 4) / height;
  379. float addX = 2.5f / width;
  380. float addY = 2.5f / height;
  381. #endif
  382. // If using 4 shadow samples, offset the position diagonally by half pixel
  383. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  384. {
  385. addX -= 0.5f / width;
  386. addY -= 0.5f / height;
  387. }
  388. graphics->SetShaderParameter(PSP_SHADOWCUBEADJUST, Vector4(mulX, mulY, addX, addY));
  389. }
  390. {
  391. // Calculate shadow camera depth parameters for point light shadows and shadow fade parameters for
  392. // directional light shadows, stored in the same uniform
  393. Camera* shadowCamera = lightQueue_->shadowSplits_[0].shadowCamera_;
  394. float nearClip = shadowCamera->GetNearClip();
  395. float farClip = shadowCamera->GetFarClip();
  396. float q = farClip / (farClip - nearClip);
  397. float r = -q * nearClip;
  398. const CascadeParameters& parameters = light->GetShadowCascade();
  399. float viewFarClip = camera_->GetFarClip();
  400. float shadowRange = parameters.GetShadowRange();
  401. float fadeStart = parameters.fadeStart_ * shadowRange / viewFarClip;
  402. float fadeEnd = shadowRange / viewFarClip;
  403. float fadeRange = fadeEnd - fadeStart;
  404. graphics->SetShaderParameter(PSP_SHADOWDEPTHFADE, Vector4(q, r, fadeStart, 1.0f / fadeRange));
  405. }
  406. {
  407. float intensity = light->GetShadowIntensity();
  408. float fadeStart = light->GetShadowFadeDistance();
  409. float fadeEnd = light->GetShadowDistance();
  410. if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart)
  411. intensity = Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f));
  412. float pcfValues = (1.0f - intensity);
  413. float samples = renderer->GetShadowQuality() >= SHADOWQUALITY_HIGH_16BIT ? 4.0f : 1.0f;
  414. graphics->SetShaderParameter(PSP_SHADOWINTENSITY, Vector4(pcfValues / samples, intensity, 0.0f, 0.0f));
  415. }
  416. float sizeX = 1.0f / (float)shadowMap->GetWidth();
  417. float sizeY = 1.0f / (float)shadowMap->GetHeight();
  418. graphics->SetShaderParameter(PSP_SHADOWMAPINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f));
  419. Vector4 lightSplits(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE);
  420. if (lightQueue_->shadowSplits_.Size() > 1)
  421. lightSplits.x_ = lightQueue_->shadowSplits_[0].farSplit_ / camera_->GetFarClip();
  422. if (lightQueue_->shadowSplits_.Size() > 2)
  423. lightSplits.y_ = lightQueue_->shadowSplits_[1].farSplit_ / camera_->GetFarClip();
  424. if (lightQueue_->shadowSplits_.Size() > 3)
  425. lightSplits.z_ = lightQueue_->shadowSplits_[2].farSplit_ / camera_->GetFarClip();
  426. graphics->SetShaderParameter(PSP_SHADOWSPLITS, lightSplits);
  427. }
  428. }
  429. else if (lightQueue_->vertexLights_.Size() && graphics->HasShaderParameter(VSP_VERTEXLIGHTS) &&
  430. graphics->NeedParameterUpdate(SP_LIGHT, lightQueue_))
  431. {
  432. Vector4 vertexLights[MAX_VERTEX_LIGHTS * 3];
  433. const PODVector<Light*>& lights = lightQueue_->vertexLights_;
  434. for (unsigned i = 0; i < lights.Size(); ++i)
  435. {
  436. Light* vertexLight = lights[i];
  437. Node* vertexLightNode = vertexLight->GetNode();
  438. LightType type = vertexLight->GetLightType();
  439. // Attenuation
  440. float invRange, cutoff, invCutoff;
  441. if (type == LIGHT_DIRECTIONAL)
  442. invRange = 0.0f;
  443. else
  444. invRange = 1.0f / Max(vertexLight->GetRange(), M_EPSILON);
  445. if (type == LIGHT_SPOT)
  446. {
  447. cutoff = Cos(vertexLight->GetFov() * 0.5f);
  448. invCutoff = 1.0f / (1.0f - cutoff);
  449. }
  450. else
  451. {
  452. cutoff = -1.0f;
  453. invCutoff = 1.0f;
  454. }
  455. // Color
  456. float fade = 1.0f;
  457. float fadeEnd = vertexLight->GetDrawDistance();
  458. float fadeStart = vertexLight->GetFadeDistance();
  459. // Do fade calculation for light if both fade & draw distance defined
  460. if (vertexLight->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  461. fade = Min(1.0f - (vertexLight->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  462. Color color = vertexLight->GetEffectiveColor() * fade;
  463. vertexLights[i * 3] = Vector4(color.r_, color.g_, color.b_, invRange);
  464. // Direction
  465. vertexLights[i * 3 + 1] = Vector4(-(vertexLightNode->GetWorldDirection()), cutoff);
  466. // Position
  467. vertexLights[i * 3 + 2] = Vector4(vertexLightNode->GetWorldPosition(), invCutoff);
  468. }
  469. graphics->SetShaderParameter(VSP_VERTEXLIGHTS, vertexLights[0].Data(), lights.Size() * 3 * 4);
  470. }
  471. }
  472. // Set material-specific shader parameters and textures
  473. if (material_)
  474. {
  475. if (graphics->NeedParameterUpdate(SP_MATERIAL, reinterpret_cast<const void*>(material_->GetShaderParameterHash())))
  476. {
  477. const HashMap<StringHash, MaterialShaderParameter>& parameters = material_->GetShaderParameters();
  478. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
  479. graphics->SetShaderParameter(i->first_, i->second_.value_);
  480. }
  481. const HashMap<TextureUnit, SharedPtr<Texture> >& textures = material_->GetTextures();
  482. for (HashMap<TextureUnit, SharedPtr<Texture> >::ConstIterator i = textures.Begin(); i != textures.End(); ++i)
  483. {
  484. if (graphics->HasTextureUnit(i->first_))
  485. graphics->SetTexture(i->first_, i->second_.Get());
  486. }
  487. }
  488. // Set light-related textures
  489. if (light)
  490. {
  491. if (shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP))
  492. graphics->SetTexture(TU_SHADOWMAP, shadowMap);
  493. if (graphics->HasTextureUnit(TU_LIGHTRAMP))
  494. {
  495. Texture* rampTexture = light->GetRampTexture();
  496. if (!rampTexture)
  497. rampTexture = renderer->GetDefaultLightRamp();
  498. graphics->SetTexture(TU_LIGHTRAMP, rampTexture);
  499. }
  500. if (graphics->HasTextureUnit(TU_LIGHTSHAPE))
  501. {
  502. Texture* shapeTexture = light->GetShapeTexture();
  503. if (!shapeTexture && light->GetLightType() == LIGHT_SPOT)
  504. shapeTexture = renderer->GetDefaultLightSpot();
  505. graphics->SetTexture(TU_LIGHTSHAPE, shapeTexture);
  506. }
  507. }
  508. // Set zone texture if necessary
  509. #ifdef DESKTOP_GRAPHICS
  510. if (zone_ && graphics->HasTextureUnit(TU_ZONE))
  511. graphics->SetTexture(TU_ZONE, zone_->GetZoneTexture());
  512. #endif
  513. }
  514. void Batch::Draw(View* view, bool allowDepthWrite) const
  515. {
  516. if (!geometry_->IsEmpty())
  517. {
  518. Prepare(view, true, allowDepthWrite);
  519. geometry_->Draw(view->GetGraphics());
  520. }
  521. }
  522. void BatchGroup::SetTransforms(void* lockedData, unsigned& freeIndex)
  523. {
  524. // Do not use up buffer space if not going to draw as instanced
  525. if (geometryType_ != GEOM_INSTANCED)
  526. return;
  527. startIndex_ = freeIndex;
  528. Matrix3x4* dest = (Matrix3x4*)lockedData;
  529. dest += freeIndex;
  530. for (unsigned i = 0; i < instances_.Size(); ++i)
  531. *dest++ = *instances_[i].worldTransform_;
  532. freeIndex += instances_.Size();
  533. }
  534. void BatchGroup::Draw(View* view, bool allowDepthWrite) const
  535. {
  536. Graphics* graphics = view->GetGraphics();
  537. Renderer* renderer = view->GetRenderer();
  538. if (instances_.Size() && !geometry_->IsEmpty())
  539. {
  540. // Draw as individual objects if instancing not supported or could not fill the instancing buffer
  541. VertexBuffer* instanceBuffer = renderer->GetInstancingBuffer();
  542. if (!instanceBuffer || geometryType_ != GEOM_INSTANCED || startIndex_ == M_MAX_UNSIGNED)
  543. {
  544. Batch::Prepare(view, false, allowDepthWrite);
  545. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  546. graphics->SetVertexBuffers(geometry_->GetVertexBuffers(), geometry_->GetVertexElementMasks());
  547. for (unsigned i = 0; i < instances_.Size(); ++i)
  548. {
  549. if (graphics->NeedParameterUpdate(SP_OBJECT, instances_[i].worldTransform_))
  550. graphics->SetShaderParameter(VSP_MODEL, *instances_[i].worldTransform_);
  551. graphics->Draw(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  552. geometry_->GetVertexStart(), geometry_->GetVertexCount());
  553. }
  554. }
  555. else
  556. {
  557. Batch::Prepare(view, false, allowDepthWrite);
  558. // Get the geometry vertex buffers, then add the instancing stream buffer
  559. // Hack: use a const_cast to avoid dynamic allocation of new temp vectors
  560. Vector<SharedPtr<VertexBuffer> >& vertexBuffers = const_cast<Vector<SharedPtr<VertexBuffer> >&>
  561. (geometry_->GetVertexBuffers());
  562. PODVector<unsigned>& elementMasks = const_cast<PODVector<unsigned>&>(geometry_->GetVertexElementMasks());
  563. vertexBuffers.Push(SharedPtr<VertexBuffer>(instanceBuffer));
  564. elementMasks.Push(instanceBuffer->GetElementMask());
  565. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  566. graphics->SetVertexBuffers(vertexBuffers, elementMasks, startIndex_);
  567. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  568. geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances_.Size());
  569. // Remove the instancing buffer & element mask now
  570. vertexBuffers.Pop();
  571. elementMasks.Pop();
  572. }
  573. }
  574. }
  575. unsigned BatchGroupKey::ToHash() const
  576. {
  577. return ((unsigned)(size_t)zone_) / sizeof(Zone) +
  578. ((unsigned)(size_t)lightQueue_) / sizeof(LightBatchQueue) +
  579. ((unsigned)(size_t)pass_) / sizeof(Pass) +
  580. ((unsigned)(size_t)material_) / sizeof(Material) +
  581. ((unsigned)(size_t)geometry_) / sizeof(Geometry);
  582. }
  583. void BatchQueue::Clear(int maxSortedInstances)
  584. {
  585. batches_.Clear();
  586. sortedBatches_.Clear();
  587. batchGroups_.Clear();
  588. maxSortedInstances_ = maxSortedInstances;
  589. }
  590. void BatchQueue::SortBackToFront()
  591. {
  592. sortedBatches_.Resize(batches_.Size());
  593. for (unsigned i = 0; i < batches_.Size(); ++i)
  594. sortedBatches_[i] = &batches_[i];
  595. Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesBackToFront);
  596. // Do not actually sort batch groups, just list them
  597. sortedBatchGroups_.Resize(batchGroups_.Size());
  598. unsigned index = 0;
  599. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  600. sortedBatchGroups_[index++] = &i->second_;
  601. }
  602. void BatchQueue::SortFrontToBack()
  603. {
  604. sortedBatches_.Clear();
  605. for (unsigned i = 0; i < batches_.Size(); ++i)
  606. sortedBatches_.Push(&batches_[i]);
  607. SortFrontToBack2Pass(sortedBatches_);
  608. // Sort each group front to back
  609. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  610. {
  611. if (i->second_.instances_.Size() <= maxSortedInstances_)
  612. {
  613. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  614. if (i->second_.instances_.Size())
  615. i->second_.distance_ = i->second_.instances_[0].distance_;
  616. }
  617. else
  618. {
  619. float minDistance = M_INFINITY;
  620. for (PODVector<InstanceData>::ConstIterator j = i->second_.instances_.Begin(); j != i->second_.instances_.End(); ++j)
  621. minDistance = Min(minDistance, j->distance_);
  622. i->second_.distance_ = minDistance;
  623. }
  624. }
  625. sortedBatchGroups_.Resize(batchGroups_.Size());
  626. unsigned index = 0;
  627. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  628. sortedBatchGroups_[index++] = &i->second_;
  629. SortFrontToBack2Pass(reinterpret_cast<PODVector<Batch*>& >(sortedBatchGroups_));
  630. }
  631. void BatchQueue::SortFrontToBack2Pass(PODVector<Batch*>& batches)
  632. {
  633. // Mobile devices likely use a tiled deferred approach, with which front-to-back sorting is irrelevant. The 2-pass
  634. // method is also time consuming, so just sort with state having priority
  635. #ifdef GL_ES_VERSION_2_0
  636. Sort(batches.Begin(), batches.End(), CompareBatchesState);
  637. #else
  638. // For desktop, first sort by distance and remap shader/material/geometry IDs in the sort key
  639. Sort(batches.Begin(), batches.End(), CompareBatchesFrontToBack);
  640. unsigned freeShaderID = 0;
  641. unsigned short freeMaterialID = 0;
  642. unsigned short freeGeometryID = 0;
  643. for (PODVector<Batch*>::Iterator i = batches.Begin(); i != batches.End(); ++i)
  644. {
  645. Batch* batch = *i;
  646. unsigned shaderID = (batch->sortKey_ >> 32);
  647. HashMap<unsigned, unsigned>::ConstIterator j = shaderRemapping_.Find(shaderID);
  648. if (j != shaderRemapping_.End())
  649. shaderID = j->second_;
  650. else
  651. {
  652. shaderID = shaderRemapping_[shaderID] = freeShaderID | (shaderID & 0xc0000000);
  653. ++freeShaderID;
  654. }
  655. unsigned short materialID = (unsigned short)(batch->sortKey_ & 0xffff0000);
  656. HashMap<unsigned short, unsigned short>::ConstIterator k = materialRemapping_.Find(materialID);
  657. if (k != materialRemapping_.End())
  658. materialID = k->second_;
  659. else
  660. {
  661. materialID = materialRemapping_[materialID] = freeMaterialID;
  662. ++freeMaterialID;
  663. }
  664. unsigned short geometryID = (unsigned short)(batch->sortKey_ & 0xffff);
  665. HashMap<unsigned short, unsigned short>::ConstIterator l = geometryRemapping_.Find(geometryID);
  666. if (l != geometryRemapping_.End())
  667. geometryID = l->second_;
  668. else
  669. {
  670. geometryID = geometryRemapping_[geometryID] = freeGeometryID;
  671. ++freeGeometryID;
  672. }
  673. batch->sortKey_ = (((unsigned long long)shaderID) << 32) || (((unsigned long long)materialID) << 16) | geometryID;
  674. }
  675. shaderRemapping_.Clear();
  676. materialRemapping_.Clear();
  677. geometryRemapping_.Clear();
  678. // Finally sort again with the rewritten ID's
  679. Sort(batches.Begin(), batches.End(), CompareBatchesState);
  680. #endif
  681. }
  682. void BatchQueue::SetTransforms(void* lockedData, unsigned& freeIndex)
  683. {
  684. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  685. i->second_.SetTransforms(lockedData, freeIndex);
  686. }
  687. void BatchQueue::Draw(View* view, bool markToStencil, bool usingLightOptimization, bool allowDepthWrite) const
  688. {
  689. Graphics* graphics = view->GetGraphics();
  690. Renderer* renderer = view->GetRenderer();
  691. // If View has set up its own light optimizations, do not disturb the stencil/scissor test settings
  692. if (!usingLightOptimization)
  693. {
  694. graphics->SetScissorTest(false);
  695. // During G-buffer rendering, mark opaque pixels' lightmask to stencil buffer if requested
  696. if (!markToStencil)
  697. graphics->SetStencilTest(false);
  698. }
  699. // Instanced
  700. for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i)
  701. {
  702. BatchGroup* group = *i;
  703. if (markToStencil)
  704. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  705. group->Draw(view, allowDepthWrite);
  706. }
  707. // Non-instanced
  708. for (PODVector<Batch*>::ConstIterator i = sortedBatches_.Begin(); i != sortedBatches_.End(); ++i)
  709. {
  710. Batch* batch = *i;
  711. if (markToStencil)
  712. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  713. if (!usingLightOptimization)
  714. {
  715. // If drawing an alpha batch, we can optimize fillrate by scissor test
  716. if (!batch->isBase_ && batch->lightQueue_)
  717. renderer->OptimizeLightByScissor(batch->lightQueue_->light_, batch->camera_);
  718. else
  719. graphics->SetScissorTest(false);
  720. }
  721. batch->Draw(view, allowDepthWrite);
  722. }
  723. }
  724. unsigned BatchQueue::GetNumInstances() const
  725. {
  726. unsigned total = 0;
  727. for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  728. {
  729. if (i->second_.geometryType_ == GEOM_INSTANCED)
  730. total += i->second_.instances_.Size();
  731. }
  732. return total;
  733. }
  734. }