Batch.cpp 38 KB

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