Batch.cpp 37 KB

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