Batch.cpp 36 KB

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