Batch.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "Geometry.h"
  26. #include "Graphics.h"
  27. #include "GraphicsImpl.h"
  28. #include "Light.h"
  29. #include "Node.h"
  30. #include "Renderer.h"
  31. #include "Profiler.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. inline bool CompareBatchesFrontToBack(Batch* lhs, Batch* rhs)
  41. {
  42. if (lhs->sortKey_ == rhs->sortKey_)
  43. return lhs->distance_ < rhs->distance_;
  44. else
  45. return lhs->sortKey_ > rhs->sortKey_;
  46. }
  47. inline bool CompareBatchesBackToFront(Batch* lhs, Batch* rhs)
  48. {
  49. if (lhs->distance_ == rhs->distance_)
  50. return lhs->sortKey_ > rhs->sortKey_;
  51. else
  52. return lhs->distance_ > rhs->distance_;
  53. }
  54. inline bool CompareInstancesFrontToBack(const InstanceData& lhs, const InstanceData& rhs)
  55. {
  56. return lhs.distance_ < rhs.distance_;
  57. }
  58. inline bool CompareBatchGroupsFrontToBack(BatchGroup* lhs, BatchGroup* rhs)
  59. {
  60. return lhs->distance_ < rhs->distance_;
  61. }
  62. void CalculateShadowMatrix(Matrix4& dest, LightBatchQueue* queue, unsigned split, Renderer* renderer, const Vector3& translation)
  63. {
  64. Camera* shadowCamera = queue->shadowSplits_[split].shadowCamera_;
  65. const IntRect& viewport = queue->shadowSplits_[split].shadowViewport_;
  66. Matrix3x4 posAdjust(translation, Quaternion::IDENTITY, 1.0f);
  67. Matrix3x4 shadowView(shadowCamera->GetInverseWorldTransform());
  68. Matrix4 shadowProj(shadowCamera->GetProjection());
  69. Matrix4 texAdjust(Matrix4::IDENTITY);
  70. Texture2D* shadowMap = queue->shadowMap_;
  71. if (!shadowMap)
  72. return;
  73. float width = (float)shadowMap->GetWidth();
  74. float height = (float)shadowMap->GetHeight();
  75. Vector2 offset(
  76. (float)viewport.left_ / width,
  77. (float)viewport.top_ / height
  78. );
  79. Vector2 scale(
  80. 0.5f * (float)(viewport.right_ - viewport.left_) / width,
  81. 0.5f * (float)(viewport.bottom_ - viewport.top_) / height
  82. );
  83. #ifdef USE_OPENGL
  84. offset.x_ += scale.x_;
  85. offset.y_ += scale.y_;
  86. offset.y_ = 1.0f - offset.y_;
  87. // If using 4 shadow samples, offset the position diagonally by half pixel
  88. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  89. {
  90. offset.x_ -= 0.5f / width;
  91. offset.y_ -= 0.5f / height;
  92. }
  93. texAdjust.SetTranslation(Vector3(offset.x_, offset.y_, 0.5f));
  94. texAdjust.SetScale(Vector3(scale.x_, scale.y_, 0.5f));
  95. #else
  96. offset.x_ += scale.x_ + 0.5f / width;
  97. offset.y_ += scale.y_ + 0.5f / height;
  98. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  99. {
  100. offset.x_ -= 0.5f / width;
  101. offset.y_ -= 0.5f / height;
  102. }
  103. scale.y_ = -scale.y_;
  104. texAdjust.SetTranslation(Vector3(offset.x_, offset.y_, 0.0f));
  105. texAdjust.SetScale(Vector3(scale.x_, scale.y_, 1.0f));
  106. #endif
  107. dest = texAdjust * shadowProj * shadowView * posAdjust;
  108. }
  109. void CalculateSpotMatrix(Matrix4& dest, Light* light, const Vector3& translation)
  110. {
  111. Node* lightNode = light->GetNode();
  112. Matrix3x4 posAdjust(translation, Quaternion::IDENTITY, 1.0f);
  113. Matrix3x4 spotView = lightNode->GetWorldTransform();
  114. // Remove any scaling
  115. spotView.SetRotation(spotView.RotationMatrix());
  116. Matrix4 spotProj(Matrix4::ZERO);
  117. Matrix4 texAdjust(Matrix4::IDENTITY);
  118. // Make the projected light slightly smaller than the shadow map to prevent light spill
  119. float h = 1.005f / tanf(light->GetFov() * M_DEGTORAD * 0.5f);
  120. float w = h / light->GetAspectRatio();
  121. spotProj.m00_ = w;
  122. spotProj.m11_ = h;
  123. spotProj.m22_ = 1.0f / Max(light->GetRange(), M_EPSILON);
  124. spotProj.m32_ = 1.0f;
  125. #ifdef USE_OPENGL
  126. texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
  127. texAdjust.SetScale(Vector3(0.5f, -0.5f, 0.5f));
  128. #else
  129. texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.0f));
  130. texAdjust.SetScale(Vector3(0.5f, -0.5f, 1.0f));
  131. #endif
  132. dest = texAdjust * spotProj * spotView.Inverse() * posAdjust;
  133. }
  134. void Batch::CalculateSortKey()
  135. {
  136. unsigned lightQueue = (*((unsigned*)&lightQueue_) / sizeof(LightBatchQueue)) & 0x7fff;
  137. unsigned pass = (*((unsigned*)&pass_) / sizeof(Pass)) & 0xffff;
  138. unsigned material = (*((unsigned*)&material_) / sizeof(Material)) & 0xffff;
  139. unsigned geometry = (*((unsigned*)&geometry_) / sizeof(Geometry)) & 0xffff;
  140. if (isBase_)
  141. lightQueue |= 0x8000;
  142. sortKey_ = (((unsigned long long)lightQueue) << 48) | (((unsigned long long)pass) << 32) |
  143. (((unsigned long long)material) << 16) | geometry;
  144. }
  145. void Batch::Prepare(Graphics* graphics, Renderer* renderer, bool setModelTransform) const
  146. {
  147. if (!vertexShader_ || !pixelShader_)
  148. return;
  149. Node* cameraNode = camera_ ? camera_->GetNode() : 0;
  150. // Set pass / material-specific renderstates
  151. if (pass_ && material_)
  152. {
  153. if (pass_->GetAlphaTest())
  154. graphics->SetAlphaTest(true, CMP_GREATEREQUAL, 0.5f);
  155. else
  156. graphics->SetAlphaTest(false);
  157. graphics->SetBlendMode(pass_->GetBlendMode());
  158. renderer->SetCullMode(pass_->GetType() != PASS_SHADOW ? material_->GetCullMode() : material_->GetShadowCullMode(),
  159. camera_);
  160. graphics->SetDepthTest(pass_->GetDepthTestMode());
  161. graphics->SetDepthWrite(pass_->GetDepthWrite());
  162. }
  163. // Set shaders
  164. graphics->SetShaders(vertexShader_, pixelShader_);
  165. // Set camera shader parameters
  166. unsigned cameraHash = overrideView_ ? (unsigned)camera_ + 4 : (unsigned)camera_;
  167. if (graphics->NeedParameterUpdate(SP_CAMERA, (void*)cameraHash))
  168. {
  169. // Calculate camera rotation just once
  170. Matrix3 cameraWorldRotation = cameraNode->GetWorldTransform().RotationMatrix();
  171. graphics->SetShaderParameter(VSP_CAMERAPOS, cameraNode->GetWorldPosition());
  172. graphics->SetShaderParameter(VSP_CAMERAROT, cameraWorldRotation);
  173. Vector4 depthMode = Vector4::ZERO;
  174. if (camera_->IsOrthographic())
  175. {
  176. depthMode.x_ = 1.0f;
  177. #ifdef USE_OPENGL
  178. depthMode.z_ = 0.5f;
  179. depthMode.w_ = 0.5f;
  180. #else
  181. depthMode.z_ = 1.0f;
  182. #endif
  183. }
  184. else
  185. depthMode.w_ = 1.0f / camera_->GetFarClip();
  186. graphics->SetShaderParameter(VSP_DEPTHMODE, depthMode);
  187. Vector3 nearVector, farVector;
  188. camera_->GetFrustumSize(nearVector, farVector);
  189. Vector4 viewportParams(farVector.x_, farVector.y_, farVector.z_, 0.0f);
  190. graphics->SetShaderParameter(VSP_FRUSTUMSIZE, viewportParams);
  191. if (overrideView_)
  192. graphics->SetShaderParameter(VSP_VIEWPROJ, camera_->GetProjection());
  193. else
  194. graphics->SetShaderParameter(VSP_VIEWPROJ, camera_->GetProjection() * camera_->GetInverseWorldTransform());
  195. graphics->SetShaderParameter(VSP_VIEWRIGHTVECTOR, cameraWorldRotation * Vector3::RIGHT);
  196. graphics->SetShaderParameter(VSP_VIEWUPVECTOR, cameraWorldRotation * Vector3::UP);
  197. float farClip = camera_->GetFarClip();
  198. float nearClip = camera_->GetNearClip();
  199. Vector4 depthReconstruct(farClip / (farClip - nearClip), -nearClip / (farClip - nearClip), 0.0f, 0.0f);
  200. graphics->SetShaderParameter(PSP_DEPTHRECONSTRUCT, depthReconstruct);
  201. }
  202. // Set viewport shader parameters
  203. IntVector2 rtSize = graphics->GetRenderTargetDimensions();
  204. IntRect viewport = graphics->GetViewport();
  205. unsigned viewportHash = (viewport.left_) | (viewport.top_ << 8) | (viewport.right_ << 16) | (viewport.bottom_ << 24);
  206. if (graphics->NeedParameterUpdate(SP_VIEWPORT, (void*)viewportHash))
  207. {
  208. float rtWidth = (float)rtSize.x_;
  209. float rtHeight = (float)rtSize.y_;
  210. float widthRange = 0.5f * (viewport.right_ - viewport.left_) / rtWidth;
  211. float heightRange = 0.5f * (viewport.bottom_ - viewport.top_) / rtHeight;
  212. #ifdef USE_OPENGL
  213. Vector4 bufferUVOffset(((float)viewport.left_) / rtWidth + widthRange,
  214. 1.0f - (((float)viewport.top_) / rtHeight + heightRange), widthRange, heightRange);
  215. #else
  216. Vector4 bufferUVOffset((0.5f + (float)viewport.left_) / rtWidth + widthRange,
  217. (0.5f + (float)viewport.top_) / rtHeight + heightRange, widthRange, heightRange);
  218. #endif
  219. graphics->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  220. float sizeX = 1.0f / rtWidth;
  221. float sizeY = 1.0f / rtHeight;
  222. graphics->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f));
  223. }
  224. // Set model transform
  225. if (setModelTransform && graphics->NeedParameterUpdate(SP_OBJECTTRANSFORM, worldTransform_))
  226. graphics->SetShaderParameter(VSP_MODEL, *worldTransform_);
  227. // Set skinning transforms
  228. if (shaderData_ && shaderDataSize_ && graphics->NeedParameterUpdate(SP_OBJECTDATA, shaderData_))
  229. graphics->SetShaderParameter(VSP_SKINMATRICES, shaderData_, shaderDataSize_);
  230. // Set zone-related shader parameters
  231. BlendMode blend = graphics->GetBlendMode();
  232. Zone* fogColorZone = (blend == BLEND_ADD || blend == BLEND_ADDALPHA) ? renderer->GetDefaultZone() : zone_;
  233. unsigned zoneHash = (unsigned)zone_ + (unsigned)fogColorZone;
  234. if (zone_ && graphics->NeedParameterUpdate(SP_ZONE, (void*)zoneHash))
  235. {
  236. graphics->SetShaderParameter(VSP_AMBIENTSTARTCOLOR, zone_->GetAmbientStartColor());
  237. graphics->SetShaderParameter(VSP_AMBIENTENDCOLOR, zone_->GetAmbientEndColor().ToVector4() - zone_->GetAmbientStartColor().ToVector4());
  238. const BoundingBox& box = zone_->GetBoundingBox();
  239. Vector3 boxSize = box.Size();
  240. Matrix3x4 adjust(Matrix3x4::IDENTITY);
  241. adjust.SetScale(Vector3(1.0f / boxSize.x_, 1.0f / boxSize.y_, 1.0f / boxSize.z_));
  242. adjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
  243. Matrix3x4 zoneTransform = adjust * zone_->GetInverseWorldTransform();
  244. graphics->SetShaderParameter(VSP_ZONE, zoneTransform);
  245. graphics->SetShaderParameter(PSP_AMBIENTCOLOR, zone_->GetAmbientColor());
  246. // If the pass is additive, override fog color to black so that shaders do not need a separate additive path
  247. graphics->SetShaderParameter(PSP_FOGCOLOR, fogColorZone->GetFogColor());
  248. float farClip = camera_->GetFarClip();
  249. float nearClip = camera_->GetNearClip();
  250. float fogStart = Min(zone_->GetFogStart(), farClip);
  251. float fogEnd = Min(zone_->GetFogEnd(), farClip);
  252. if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON))
  253. fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
  254. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  255. Vector4 fogParams(fogEnd / farClip, farClip / fogRange, 0.0f, 0.0f);
  256. graphics->SetShaderParameter(PSP_FOGPARAMS, fogParams);
  257. }
  258. // Set light-related shader parameters
  259. Light* light = 0;
  260. Texture2D* shadowMap = 0;
  261. if (lightQueue_)
  262. {
  263. light = lightQueue_->light_;
  264. shadowMap = lightQueue_->shadowMap_;
  265. if (graphics->NeedParameterUpdate(SP_VERTEXLIGHTS, lightQueue_) && graphics->HasShaderParameter(VS, VSP_VERTEXLIGHTS))
  266. {
  267. Vector4 vertexLights[MAX_VERTEX_LIGHTS * 3];
  268. const PODVector<Light*>& lights = lightQueue_->vertexLights_;
  269. for (unsigned i = 0; i < lights.Size(); ++i)
  270. {
  271. Light* vertexLight = lights[i];
  272. Node* vertexLightNode = vertexLight->GetNode();
  273. LightType type = vertexLight->GetLightType();
  274. // Attenuation
  275. float invRange, cutoff, invCutoff;
  276. if (type == LIGHT_DIRECTIONAL)
  277. invRange = 0.0f;
  278. else
  279. invRange = 1.0f / Max(vertexLight->GetRange(), M_EPSILON);
  280. if (type == LIGHT_SPOT)
  281. {
  282. cutoff = cosf(vertexLight->GetFov() * 0.5f * M_DEGTORAD);
  283. invCutoff = 1.0f / (1.0f - cutoff);
  284. }
  285. else
  286. {
  287. cutoff = -1.0f;
  288. invCutoff = 1.0f;
  289. }
  290. // Color
  291. float fade = 1.0f;
  292. float fadeEnd = vertexLight->GetDrawDistance();
  293. float fadeStart = vertexLight->GetFadeDistance();
  294. // Do fade calculation for light if both fade & draw distance defined
  295. if (vertexLight->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  296. fade = Min(1.0f - (vertexLight->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  297. Color color = vertexLight->GetColor() * fade;
  298. vertexLights[i * 3] = Vector4(color.r_, color.g_, color.b_, invRange);
  299. // Direction
  300. vertexLights[i * 3 + 1] = Vector4(-(vertexLightNode->GetWorldDirection()), cutoff);
  301. // Position
  302. vertexLights[i * 3 + 2] = Vector4(vertexLightNode->GetWorldPosition(), invCutoff);
  303. }
  304. if (lights.Size())
  305. graphics->SetShaderParameter(VSP_VERTEXLIGHTS, vertexLights[0].Data(), lights.Size() * 3 * 4);
  306. }
  307. }
  308. if (light && graphics->NeedParameterUpdate(SP_LIGHT, light))
  309. {
  310. Node* lightNode = light->GetNode();
  311. Matrix3 lightWorldRotation = lightNode->GetWorldTransform().RotationMatrix();
  312. graphics->SetShaderParameter(VSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
  313. float atten = 1.0f / Max(light->GetRange(), M_EPSILON);
  314. graphics->SetShaderParameter(VSP_LIGHTPOS, Vector4(lightNode->GetWorldPosition(), atten));
  315. if (graphics->HasShaderParameter(VS, VSP_LIGHTMATRICES))
  316. {
  317. switch (light->GetLightType())
  318. {
  319. case LIGHT_DIRECTIONAL:
  320. {
  321. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  322. unsigned numSplits = lightQueue_->shadowSplits_.Size();
  323. for (unsigned i = 0; i < numSplits; ++i)
  324. CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, Vector3::ZERO);
  325. graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
  326. }
  327. break;
  328. case LIGHT_SPOT:
  329. {
  330. Matrix4 shadowMatrices[2];
  331. CalculateSpotMatrix(shadowMatrices[0], light, Vector3::ZERO);
  332. bool isShadowed = shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP);
  333. if (isShadowed)
  334. CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, Vector3::ZERO);
  335. graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
  336. }
  337. break;
  338. case LIGHT_POINT:
  339. {
  340. Matrix4 lightVecRot(lightNode->GetWorldTransform().RotationMatrix());
  341. // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
  342. // the next parameter
  343. #ifdef USE_OPENGL
  344. graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 16);
  345. #else
  346. graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 12);
  347. #endif
  348. }
  349. break;
  350. }
  351. }
  352. float fade = 1.0f;
  353. float fadeEnd = light->GetDrawDistance();
  354. float fadeStart = light->GetFadeDistance();
  355. // Do fade calculation for light if both fade & draw distance defined
  356. if (light->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
  357. fade = Min(1.0f - (light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
  358. graphics->SetShaderParameter(PSP_LIGHTCOLOR, Vector4(light->GetColor().RGBValues(), light->GetSpecularIntensity()) * fade);
  359. graphics->SetShaderParameter(PSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
  360. graphics->SetShaderParameter(PSP_LIGHTPOS, Vector4(lightNode->GetWorldPosition() - cameraNode->GetWorldPosition(), atten));
  361. if (graphics->HasShaderParameter(PS, PSP_LIGHTMATRICES))
  362. {
  363. switch (light->GetLightType())
  364. {
  365. case LIGHT_DIRECTIONAL:
  366. {
  367. Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
  368. unsigned numSplits = lightQueue_->shadowSplits_.Size();
  369. for (unsigned i = 0; i < numSplits; ++i)
  370. CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, cameraNode->GetWorldPosition());
  371. graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
  372. }
  373. break;
  374. case LIGHT_SPOT:
  375. {
  376. Matrix4 shadowMatrices[2];
  377. CalculateSpotMatrix(shadowMatrices[0], light, cameraNode->GetWorldPosition());
  378. bool isShadowed = lightQueue_->shadowMap_ != 0;
  379. if (isShadowed)
  380. CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, cameraNode->GetWorldPosition());
  381. graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
  382. }
  383. break;
  384. case LIGHT_POINT:
  385. {
  386. Matrix4 lightVecRot(lightNode->GetWorldTransform().RotationMatrix());
  387. // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
  388. // the next parameter
  389. #ifdef USE_OPENGL
  390. graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 16);
  391. #else
  392. graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 12);
  393. #endif
  394. }
  395. break;
  396. }
  397. }
  398. // Set shadow mapping shader parameters
  399. if (shadowMap)
  400. {
  401. {
  402. unsigned faceWidth = shadowMap->GetWidth() / 2;
  403. unsigned faceHeight = shadowMap->GetHeight() / 3;
  404. float width = (float)shadowMap->GetWidth();
  405. float height = (float)shadowMap->GetHeight();
  406. #ifdef USE_OPENGL
  407. float mulX = (float)(faceWidth - 3) / width;
  408. float mulY = (float)(faceHeight - 3) / height;
  409. float addX = 1.5f / width;
  410. float addY = 1.5f / height;
  411. #else
  412. float mulX = (float)(faceWidth - 4) / width;
  413. float mulY = (float)(faceHeight - 4) / height;
  414. float addX = 2.5f / width;
  415. float addY = 2.5f / height;
  416. #endif
  417. // If using 4 shadow samples, offset the position diagonally by half pixel
  418. if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
  419. {
  420. addX -= 0.5f / width;
  421. addY -= 0.5f / height;
  422. }
  423. graphics->SetShaderParameter(PSP_SHADOWCUBEADJUST, Vector4(mulX, mulY, addX, addY));
  424. }
  425. {
  426. Camera* shadowCamera = lightQueue_->shadowSplits_[0].shadowCamera_;
  427. float nearClip = shadowCamera->GetNearClip();
  428. float farClip = shadowCamera->GetFarClip();
  429. float q = farClip / (farClip - nearClip);
  430. float r = -q * nearClip;
  431. const CascadeParameters& parameters = light->GetShadowCascade();
  432. float viewFarClip = camera_->GetFarClip();
  433. float shadowRange = parameters.GetShadowRange();
  434. float fadeStart = parameters.fadeStart_ * shadowRange / viewFarClip;
  435. float fadeEnd = shadowRange / viewFarClip;
  436. float fadeRange = fadeEnd - fadeStart;
  437. graphics->SetShaderParameter(PSP_SHADOWDEPTHFADE, Vector4(q, r, fadeStart, 1.0f / fadeRange));
  438. }
  439. {
  440. float intensity = light->GetShadowIntensity();
  441. float fadeStart = light->GetShadowFadeDistance();
  442. float fadeEnd = light->GetShadowDistance();
  443. if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart)
  444. intensity = Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f));
  445. float pcfValues = (1.0f - intensity);
  446. float samples = renderer->GetShadowQuality() >= SHADOWQUALITY_HIGH_16BIT ? 4.0f : 1.0f;
  447. graphics->SetShaderParameter(PSP_SHADOWINTENSITY, Vector4(pcfValues / samples, intensity, 0.0f, 0.0f));
  448. }
  449. float sizeX = 1.0f / (float)shadowMap->GetWidth();
  450. float sizeY = 1.0f / (float)shadowMap->GetHeight();
  451. graphics->SetShaderParameter(PSP_SHADOWMAPINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f));
  452. Vector4 lightSplits(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE);
  453. if (lightQueue_->shadowSplits_.Size() > 1)
  454. lightSplits.x_ = lightQueue_->shadowSplits_[0].farSplit_ / camera_->GetFarClip();
  455. if (lightQueue_->shadowSplits_.Size() > 2)
  456. lightSplits.y_ = lightQueue_->shadowSplits_[1].farSplit_ / camera_->GetFarClip();
  457. if (lightQueue_->shadowSplits_.Size() > 3)
  458. lightSplits.z_ = lightQueue_->shadowSplits_[2].farSplit_ / camera_->GetFarClip();
  459. graphics->SetShaderParameter(PSP_SHADOWSPLITS, lightSplits);
  460. }
  461. }
  462. // Set material-specific shader parameters and textures
  463. if (material_)
  464. {
  465. if (graphics->NeedParameterUpdate(SP_MATERIAL, material_))
  466. {
  467. const HashMap<StringHash, MaterialShaderParameter>& parameters = material_->GetShaderParameters();
  468. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
  469. graphics->SetShaderParameter(i->first_, i->second_.value_);
  470. }
  471. const SharedPtr<Texture>* textures = material_->GetTextures();
  472. if (graphics->HasTextureUnit(TU_DIFFUSE))
  473. graphics->SetTexture(TU_DIFFUSE, textures[TU_DIFFUSE]);
  474. if (graphics->HasTextureUnit(TU_NORMAL))
  475. graphics->SetTexture(TU_NORMAL, textures[TU_NORMAL]);
  476. if (graphics->HasTextureUnit(TU_SPECULAR))
  477. graphics->SetTexture(TU_NORMAL, textures[TU_SPECULAR]);
  478. if (graphics->HasTextureUnit(TU_DETAIL))
  479. graphics->SetTexture(TU_DETAIL, textures[TU_DETAIL]);
  480. if (graphics->HasTextureUnit(TU_ENVIRONMENT))
  481. graphics->SetTexture(TU_ENVIRONMENT, textures[TU_ENVIRONMENT]);
  482. }
  483. // Set light-related textures
  484. if (light)
  485. {
  486. if (shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP))
  487. graphics->SetTexture(TU_SHADOWMAP, shadowMap);
  488. if (graphics->HasTextureUnit(TU_LIGHTRAMP))
  489. {
  490. Texture* rampTexture = light->GetRampTexture();
  491. if (!rampTexture)
  492. rampTexture = renderer->GetDefaultLightRamp();
  493. graphics->SetTexture(TU_LIGHTRAMP, rampTexture);
  494. }
  495. if (graphics->HasTextureUnit(TU_LIGHTSHAPE))
  496. {
  497. Texture* shapeTexture = light->GetShapeTexture();
  498. if (!shapeTexture && light->GetLightType() == LIGHT_SPOT)
  499. shapeTexture = renderer->GetDefaultLightSpot();
  500. graphics->SetTexture(TU_LIGHTSHAPE, shapeTexture);
  501. }
  502. }
  503. }
  504. void Batch::Draw(Graphics* graphics, Renderer* renderer) const
  505. {
  506. Prepare(graphics, renderer);
  507. geometry_->Draw(graphics);
  508. }
  509. void BatchGroup::SetTransforms(Renderer* renderer, void* lockedData, unsigned& freeIndex)
  510. {
  511. // Do not use up buffer space if not going to draw as instanced
  512. if (geometry_->GetIndexCount() > (unsigned)renderer->GetMaxInstanceTriangles() * 3)
  513. return;
  514. startIndex_ = freeIndex;
  515. Matrix3x4* dest = (Matrix3x4*)lockedData;
  516. dest += freeIndex;
  517. for (unsigned i = 0; i < instances_.Size(); ++i)
  518. *dest++ = *instances_[i].worldTransform_;
  519. freeIndex += instances_.Size();
  520. }
  521. void BatchGroup::Draw(Graphics* graphics, Renderer* renderer) const
  522. {
  523. if (!instances_.Size())
  524. return;
  525. // Draw as individual objects if instancing not supported
  526. VertexBuffer* instanceBuffer = renderer->GetInstancingBuffer();
  527. if (!instanceBuffer || geometry_->GetIndexCount() > (unsigned)renderer->GetMaxInstanceTriangles() * 3)
  528. {
  529. Batch::Prepare(graphics, renderer, false);
  530. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  531. graphics->SetVertexBuffers(geometry_->GetVertexBuffers(), geometry_->GetVertexElementMasks());
  532. for (unsigned i = 0; i < instances_.Size(); ++i)
  533. {
  534. graphics->SetShaderParameter(VSP_MODEL, *instances_[i].worldTransform_);
  535. graphics->Draw(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  536. geometry_->GetVertexStart(), geometry_->GetVertexCount());
  537. }
  538. graphics->ClearTransformSources();
  539. }
  540. else
  541. {
  542. Batch::Prepare(graphics, renderer, false);
  543. // Get the geometry vertex buffers, then add the instancing stream buffer
  544. // Hack: use a const_cast to avoid dynamic allocation of new temp vectors
  545. Vector<SharedPtr<VertexBuffer> >& vertexBuffers = const_cast<Vector<SharedPtr<VertexBuffer> >&>
  546. (geometry_->GetVertexBuffers());
  547. PODVector<unsigned>& elementMasks = const_cast<PODVector<unsigned>&>(geometry_->GetVertexElementMasks());
  548. vertexBuffers.Push(SharedPtr<VertexBuffer>(instanceBuffer));
  549. elementMasks.Push(instanceBuffer->GetElementMask());
  550. // No stream offset support, instancing buffer not pre-filled with transforms: have to lock and fill now
  551. if (startIndex_ == M_MAX_UNSIGNED)
  552. {
  553. unsigned startIndex = 0;
  554. while (startIndex < instances_.Size())
  555. {
  556. unsigned instances = instances_.Size() - startIndex;
  557. if (instances > instanceBuffer->GetVertexCount())
  558. instances = instanceBuffer->GetVertexCount();
  559. // Lock the instance stream buffer and copy the transforms
  560. void* data = instanceBuffer->Lock(0, instances, LOCK_DISCARD);
  561. if (!data)
  562. {
  563. // Remember to remove the instancing buffer and element mask
  564. vertexBuffers.Pop();
  565. elementMasks.Pop();
  566. return;
  567. }
  568. Matrix3x4* dest = (Matrix3x4*)data;
  569. for (unsigned i = 0; i < instances; ++i)
  570. dest[i] = *instances_[i + startIndex].worldTransform_;
  571. instanceBuffer->Unlock();
  572. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  573. graphics->SetVertexBuffers(vertexBuffers, elementMasks);
  574. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  575. geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances);
  576. startIndex += instances;
  577. }
  578. }
  579. // Stream offset supported, and instancing buffer has been already filled, so just draw
  580. else
  581. {
  582. graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
  583. graphics->SetVertexBuffers(vertexBuffers, elementMasks, startIndex_);
  584. graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
  585. geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances_.Size());
  586. }
  587. // Remove the instancing buffer & element mask now
  588. vertexBuffers.Pop();
  589. elementMasks.Pop();
  590. }
  591. }
  592. unsigned BatchGroupKey::ToHash() const
  593. {
  594. return ((unsigned)zone_) / sizeof(Zone) + ((unsigned)lightQueue_) / sizeof(LightBatchQueue) + ((unsigned)pass_) / sizeof(Pass)
  595. + ((unsigned)material_) / sizeof(Material) + ((unsigned)geometry_) / sizeof(Geometry);
  596. }
  597. void BatchQueue::Clear(int maxSortedInstances)
  598. {
  599. batches_.Clear();
  600. sortedBaseBatches_.Clear();
  601. sortedBatches_.Clear();
  602. baseBatchGroups_.Clear();
  603. batchGroups_.Clear();
  604. maxSortedInstances_ = maxSortedInstances;
  605. }
  606. void BatchQueue::SortBackToFront()
  607. {
  608. sortedBaseBatches_.Clear();
  609. sortedBatches_.Resize(batches_.Size());
  610. for (unsigned i = 0; i < batches_.Size(); ++i)
  611. sortedBatches_[i] = &batches_[i];
  612. Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesBackToFront);
  613. // Do not actually sort batch groups, just list them
  614. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  615. sortedBatchGroups_.Resize(batchGroups_.Size());
  616. unsigned index = 0;
  617. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  618. sortedBaseBatchGroups_[index++] = &i->second_;
  619. index = 0;
  620. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  621. sortedBatchGroups_[index++] = &i->second_;
  622. }
  623. void BatchQueue::SortFrontToBack()
  624. {
  625. sortedBaseBatches_.Clear();
  626. sortedBatches_.Clear();
  627. // Must explicitly divide into base and non-base batches, so that priorities do not get mixed up between
  628. // instanced and non-instanced batches
  629. for (unsigned i = 0; i < batches_.Size(); ++i)
  630. {
  631. if (batches_[i].isBase_)
  632. sortedBaseBatches_.Push(&batches_[i]);
  633. else
  634. sortedBatches_.Push(&batches_[i]);
  635. }
  636. Sort(sortedBaseBatches_.Begin(), sortedBaseBatches_.End(), CompareBatchesFrontToBack);
  637. Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesFrontToBack);
  638. // Sort each group front to back
  639. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  640. {
  641. if (i->second_.instances_.Size() <= maxSortedInstances_)
  642. {
  643. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  644. if (i->second_.instances_.Size())
  645. i->second_.distance_ = i->second_.instances_[0].distance_;
  646. }
  647. else
  648. {
  649. float minDistance = M_INFINITY;
  650. for (PODVector<InstanceData>::ConstIterator j = i->second_.instances_.Begin(); j != i->second_.instances_.End(); ++j)
  651. minDistance = Min(minDistance, j->distance_);
  652. i->second_.distance_ = minDistance;
  653. }
  654. }
  655. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  656. {
  657. if (i->second_.instances_.Size() <= maxSortedInstances_)
  658. {
  659. Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack);
  660. if (i->second_.instances_.Size())
  661. i->second_.distance_ = i->second_.instances_[0].distance_;
  662. }
  663. else
  664. {
  665. float minDistance = M_INFINITY;
  666. for (PODVector<InstanceData>::ConstIterator j = i->second_.instances_.Begin(); j != i->second_.instances_.End(); ++j)
  667. minDistance = Min(minDistance, j->distance_);
  668. i->second_.distance_ = minDistance;
  669. }
  670. }
  671. // Now sort batch groups by the distance of the first batch
  672. sortedBaseBatchGroups_.Resize(baseBatchGroups_.Size());
  673. sortedBatchGroups_.Resize(batchGroups_.Size());
  674. unsigned index = 0;
  675. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  676. sortedBaseBatchGroups_[index++] = &i->second_;
  677. index = 0;
  678. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  679. sortedBatchGroups_[index++] = &i->second_;
  680. Sort(sortedBaseBatchGroups_.Begin(), sortedBaseBatchGroups_.End(), CompareBatchGroupsFrontToBack);
  681. Sort(sortedBatchGroups_.Begin(), sortedBatchGroups_.End(), CompareBatchGroupsFrontToBack);
  682. }
  683. void BatchQueue::SetTransforms(Renderer* renderer, void* lockedData, unsigned& freeIndex)
  684. {
  685. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  686. i->second_.SetTransforms(renderer, lockedData, freeIndex);
  687. for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  688. i->second_.SetTransforms(renderer, lockedData, freeIndex);
  689. }
  690. void BatchQueue::Draw(Graphics* graphics, Renderer* renderer, bool useScissor, bool markToStencil) const
  691. {
  692. graphics->SetScissorTest(false);
  693. // During G-buffer rendering, mark opaque pixels to stencil buffer
  694. if (!markToStencil)
  695. graphics->SetStencilTest(false);
  696. // Base instanced
  697. for (PODVector<BatchGroup*>::ConstIterator i = sortedBaseBatchGroups_.Begin(); i != sortedBaseBatchGroups_.End(); ++i)
  698. {
  699. BatchGroup* group = *i;
  700. if (markToStencil)
  701. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  702. group->Draw(graphics, renderer);
  703. }
  704. // Base non-instanced
  705. for (PODVector<Batch*>::ConstIterator i = sortedBaseBatches_.Begin(); i != sortedBaseBatches_.End(); ++i)
  706. {
  707. Batch* batch = *i;
  708. if (markToStencil)
  709. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  710. batch->Draw(graphics, renderer);
  711. }
  712. // Non-base instanced
  713. for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i)
  714. {
  715. BatchGroup* group = *i;
  716. if (useScissor && group->lightQueue_)
  717. renderer->OptimizeLightByScissor(group->lightQueue_->light_, group->camera_);
  718. if (markToStencil)
  719. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  720. group->Draw(graphics, renderer);
  721. }
  722. // Non-base non-instanced
  723. for (PODVector<Batch*>::ConstIterator i = sortedBatches_.Begin(); i != sortedBatches_.End(); ++i)
  724. {
  725. Batch* batch = *i;
  726. if (useScissor)
  727. {
  728. if (!batch->isBase_ && batch->lightQueue_)
  729. renderer->OptimizeLightByScissor(batch->lightQueue_->light_, batch->camera_);
  730. else
  731. graphics->SetScissorTest(false);
  732. }
  733. if (markToStencil)
  734. graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  735. batch->Draw(graphics, renderer);
  736. }
  737. }
  738. void BatchQueue::Draw(Light* light, Graphics* graphics, Renderer* renderer) const
  739. {
  740. graphics->SetScissorTest(false);
  741. graphics->SetStencilTest(false);
  742. // Base instanced
  743. for (PODVector<BatchGroup*>::ConstIterator i = sortedBaseBatchGroups_.Begin(); i != sortedBaseBatchGroups_.End(); ++i)
  744. {
  745. BatchGroup* group = *i;
  746. group->Draw(graphics, renderer);
  747. }
  748. // Base non-instanced
  749. for (PODVector<Batch*>::ConstIterator i = sortedBaseBatches_.Begin(); i != sortedBaseBatches_.End(); ++i)
  750. {
  751. Batch* batch = *i;
  752. batch->Draw(graphics, renderer);
  753. }
  754. // All base passes have been drawn. Optimize at this point by both stencil volume and scissor
  755. bool optimized = false;
  756. // Non-base instanced
  757. for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i)
  758. {
  759. BatchGroup* group = *i;
  760. if (!optimized)
  761. {
  762. renderer->OptimizeLightByStencil(light, group->camera_);
  763. renderer->OptimizeLightByScissor(light, group->camera_);
  764. optimized = true;
  765. }
  766. group->Draw(graphics, renderer);
  767. }
  768. // Non-base non-instanced
  769. for (PODVector<Batch*>::ConstIterator i = sortedBatches_.Begin(); i != sortedBatches_.End(); ++i)
  770. {
  771. Batch* batch = *i;
  772. if (!optimized)
  773. {
  774. renderer->OptimizeLightByStencil(light, batch->camera_);
  775. renderer->OptimizeLightByScissor(light, batch->camera_);
  776. optimized = true;
  777. }
  778. batch->Draw(graphics, renderer);
  779. }
  780. }
  781. unsigned BatchQueue::GetNumInstances(Renderer* renderer) const
  782. {
  783. unsigned total = 0;
  784. unsigned maxIndexCount = renderer->GetMaxInstanceTriangles() * 3;
  785. // As this function is for the purpose of calculating how much space is needed in the instancing buffer, do not add groups
  786. // that have too many triangles to be instanced
  787. for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = baseBatchGroups_.Begin(); i != baseBatchGroups_.End(); ++i)
  788. {
  789. if (i->second_.geometry_->GetIndexCount() <= maxIndexCount)
  790. total += i->second_.instances_.Size();
  791. }
  792. for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
  793. {
  794. if (i->second_.geometry_->GetIndexCount() <= maxIndexCount)
  795. total += i->second_.instances_.Size();
  796. }
  797. return total;
  798. }