Batch.cpp 36 KB

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