Batch.cpp 40 KB

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