Batch.cpp 36 KB

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