Is.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. #include <boost/lexical_cast.hpp>
  2. #include "Is.h"
  3. #include "Renderer.h"
  4. #include "Camera.h"
  5. #include "Light.h"
  6. #include "PointLight.h"
  7. #include "SpotLight.h"
  8. #include "LightData.h"
  9. #include "App.h"
  10. #include "Scene.h"
  11. #include "LightData.h"
  12. #include "Collision.h"
  13. #include "Vao.h"
  14. #include "Sm.h"
  15. #include "Smo.h"
  16. //======================================================================================================================
  17. // Constructor =
  18. //======================================================================================================================
  19. Is::Is(Renderer& r_, Object* parent):
  20. RenderingPass(r_, parent),
  21. sm(new Sm(r_, this)),
  22. smo(new Smo(r_, this))
  23. {}
  24. //======================================================================================================================
  25. // calcViewVectors =
  26. //======================================================================================================================
  27. void Is::calcViewVectors()
  28. {
  29. Vec3 viewVectors[4];
  30. const Camera& cam = r.getCamera();
  31. const uint& w = r.getWidth();
  32. const uint& h = r.getHeight();
  33. // From right up and CC wise to right down, Just like we render the quad
  34. uint pixels[4][2]={{w, h}, {0, h}, {0, 0}, {w, 0}};
  35. uint viewport[4]={0, 0, w, h};
  36. for(int i=0; i<4; i++)
  37. {
  38. /*
  39. Original Code:
  40. Renderer::unProject(pixels[i][0], pixels[i][1], 10, cam.getViewMatrix(), cam.getProjectionMatrix(), viewport,
  41. viewVectors[i].x, viewVectors[i].y, viewVectors[i].z);
  42. viewVectors[i] = cam.getViewMatrix() * viewVectors[i];
  43. The original code is the above 3 lines. The optimized follows:
  44. */
  45. Vec3 vec;
  46. vec.x = (2.0 * (pixels[i][0] - viewport[0])) / viewport[2] - 1.0;
  47. vec.y = (2.0 * (pixels[i][1] - viewport[1])) / viewport[3] - 1.0;
  48. vec.z = 1.0;
  49. viewVectors[i] = vec.getTransformed(cam.getInvProjectionMatrix());
  50. // end of optimized code
  51. }
  52. viewVectorsVbo->write(viewVectors, sizeof(viewVectors));
  53. }
  54. //======================================================================================================================
  55. // calcPlanes =
  56. //======================================================================================================================
  57. void Is::calcPlanes()
  58. {
  59. const Camera& cam = r.getCamera();
  60. planes.x = cam.getZFar() / (cam.getZNear() - cam.getZFar());
  61. planes.y = (cam.getZFar() * cam.getZNear()) / (cam.getZNear() -cam.getZFar());
  62. }
  63. //======================================================================================================================
  64. // initFbo =
  65. //======================================================================================================================
  66. void Is::initFbo()
  67. {
  68. try
  69. {
  70. // create FBO
  71. fbo.create();
  72. fbo.bind();
  73. // init the stencil render buffer
  74. glGenRenderbuffers(1, &stencilRb);
  75. glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
  76. glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX, r.getWidth(), r.getHeight());
  77. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, stencilRb);
  78. // inform in what buffers we draw
  79. fbo.setNumOfColorAttachements(1);
  80. // create the FAI
  81. fai.createEmpty2D(r.getWidth(), r.getHeight(), GL_RGB, GL_RGB, GL_FLOAT);
  82. // attach
  83. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fai.getGlId(), 0);
  84. //glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, r.ms.depthFai.getGlId(), 0);
  85. // test if success
  86. fbo.checkIfGood();
  87. // unbind
  88. fbo.unbind();
  89. }
  90. catch(std::exception& e)
  91. {
  92. throw EXCEPTION("Cannot create deferred shading illumination stage FBO: " + e.what());
  93. }
  94. }
  95. //======================================================================================================================
  96. // init =
  97. //======================================================================================================================
  98. void Is::init(const RendererInitializer& initializer)
  99. {
  100. // init passes
  101. smo->init(initializer);
  102. sm->init(initializer);
  103. // load the shaders
  104. ambientPassSProg.loadRsrc("shaders/IsAp.glsl");
  105. // point light
  106. pointLightSProg.loadRsrc(ShaderProg::createSrcCodeToCache("shaders/IsLpGeneric.glsl", "#define POINT_LIGHT_ENABLED\n",
  107. "Point").c_str());
  108. // spot light no shadow
  109. spotLightNoShadowSProg.loadRsrc(ShaderProg::createSrcCodeToCache("shaders/IsLpGeneric.glsl",
  110. "#define SPOT_LIGHT_ENABLED\n",
  111. "SpotNoShadow").c_str());
  112. // spot light w/t shadow
  113. std::string pps = std::string("\n#define SPOT_LIGHT_ENABLED\n#define SHADOW_ENABLED\n") +
  114. "#define SHADOWMAP_SIZE " + boost::lexical_cast<std::string>(sm->getResolution()) + "\n";
  115. std::string prefix = "SpotShadowSmSize" + boost::lexical_cast<std::string>(sm->getResolution());
  116. if(sm->isPcfEnabled())
  117. {
  118. pps += "#define PCF_ENABLED\n";
  119. prefix += "Pcf";
  120. }
  121. spotLightShadowSProg.loadRsrc(ShaderProg::createSrcCodeToCache("shaders/IsLpGeneric.glsl", pps.c_str(),
  122. prefix.c_str()).c_str());
  123. // init the rest
  124. initFbo();
  125. // The VBOs and VAOs
  126. float quadVertCoords[][2] = {{1.0, 1.0}, {0.0, 1.0}, {0.0, 0.0}, {1.0, 0.0}};
  127. quadPositionsVbo = new Vbo(GL_ARRAY_BUFFER, sizeof(quadVertCoords), quadVertCoords, GL_STATIC_DRAW, this);
  128. ushort quadVertIndeces[2][3] = {{0, 1, 3}, {1, 2, 3}};
  129. quadVertIndecesVbo = new Vbo(GL_ELEMENT_ARRAY_BUFFER, sizeof(quadVertIndeces), quadVertIndeces, GL_STATIC_DRAW, this);
  130. viewVectorsVbo = new Vbo(GL_ARRAY_BUFFER, 4 * sizeof(Vec3), NULL, GL_DYNAMIC_DRAW, this);
  131. vao = new Vao(this);
  132. vao->attachArrayBufferVbo(*quadPositionsVbo, 0, 2, GL_FLOAT, false, 0, NULL);
  133. vao->attachArrayBufferVbo(*viewVectorsVbo, 1, 3, GL_FLOAT, false, 0, NULL);
  134. vao->attachElementArrayBufferVbo(*quadVertIndecesVbo);
  135. }
  136. //======================================================================================================================
  137. // drawLightPassQuad =
  138. //======================================================================================================================
  139. void Is::drawLightPassQuad() const
  140. {
  141. vao->bind();
  142. glDrawElements(GL_TRIANGLES, 2 * 3, GL_UNSIGNED_SHORT, 0);
  143. vao->unbind();
  144. }
  145. //======================================================================================================================
  146. // ambientPass =
  147. //======================================================================================================================
  148. void Is::ambientPass(const Vec3& color)
  149. {
  150. glDisable(GL_BLEND);
  151. // set the shader
  152. ambientPassSProg->bind();
  153. // set the uniforms
  154. ambientPassSProg->findUniVar("ambientCol")->setVec3(&color);
  155. ambientPassSProg->findUniVar("sceneColMap")->setTexture(r.getMs().diffuseFai, 0);
  156. // Draw quad
  157. r.drawQuad();
  158. }
  159. //======================================================================================================================
  160. // pointLightPass =
  161. //======================================================================================================================
  162. void Is::pointLightPass(const PointLight& light)
  163. {
  164. const Camera& cam = r.getCamera();
  165. // frustum test
  166. Sphere sphere(light.getWorldTransform().origin, light.getRadius());
  167. if(!cam.insideFrustum(sphere))
  168. {
  169. return;
  170. }
  171. // stencil optimization
  172. smo->run(light);
  173. // shader prog
  174. const ShaderProg& shader = *pointLightSProg; // ensure the const-ness
  175. shader.bind();
  176. shader.findUniVar("msNormalFai")->setTexture(r.getMs().normalFai, 0);
  177. shader.findUniVar("msDiffuseFai")->setTexture(r.getMs().diffuseFai, 1);
  178. shader.findUniVar("msSpecularFai")->setTexture(r.getMs().specularFai, 2);
  179. shader.findUniVar("msDepthFai")->setTexture(r.getMs().depthFai, 3);
  180. shader.findUniVar("planes")->setVec2(&planes);
  181. Vec3 lightPosEyeSpace = light.getWorldTransform().origin.getTransformed(cam.getViewMatrix());
  182. shader.findUniVar("lightPos")->setVec3(&lightPosEyeSpace);
  183. shader.findUniVar("lightRadius")->setFloat(light.getRadius());
  184. shader.findUniVar("lightDiffuseCol")->setVec3(&light.lightData->getDiffuseCol());
  185. shader.findUniVar("lightSpecularCol")->setVec3(&light.lightData->getSpecularCol());
  186. // render quad
  187. drawLightPassQuad();
  188. }
  189. //======================================================================================================================
  190. // spotLightPass =
  191. //======================================================================================================================
  192. void Is::spotLightPass(const SpotLight& light)
  193. {
  194. const Camera& cam = r.getCamera();
  195. // frustum test
  196. if(!cam.insideFrustum(light.getCamera()))
  197. {
  198. return;
  199. }
  200. // shadow mapping
  201. if(light.castsShadow() && sm->isEnabled())
  202. {
  203. sm->run(light.getCamera());
  204. // restore the IS FBO
  205. fbo.bind();
  206. // and restore blending and depth test
  207. glEnable(GL_BLEND);
  208. glBlendFunc(GL_ONE, GL_ONE);
  209. glDisable(GL_DEPTH_TEST);
  210. Renderer::setViewport(0, 0, r.getWidth(), r.getHeight());
  211. }
  212. // stencil optimization
  213. smo->run(light);
  214. // set the texture
  215. light.lightData->getTexture().setRepeat(false);
  216. // shader prog
  217. const ShaderProg* shdr;
  218. if(light.castsShadow() && sm->isEnabled())
  219. {
  220. shdr = spotLightShadowSProg.get();
  221. }
  222. else
  223. {
  224. shdr = spotLightNoShadowSProg.get();
  225. }
  226. shdr->bind();
  227. // bind the FAIs
  228. shdr->findUniVar("msNormalFai")->setTexture(r.getMs().normalFai, 0);
  229. shdr->findUniVar("msDiffuseFai")->setTexture(r.getMs().diffuseFai, 1);
  230. shdr->findUniVar("msSpecularFai")->setTexture(r.getMs().specularFai, 2);
  231. shdr->findUniVar("msDepthFai")->setTexture(r.getMs().depthFai, 3);
  232. // the planes
  233. shdr->findUniVar("planes")->setVec2(&planes);
  234. // the light params
  235. Vec3 lightPosEyeSpace = light.getWorldTransform().origin.getTransformed(cam.getViewMatrix());
  236. shdr->findUniVar("lightPos")->setVec3(&lightPosEyeSpace);
  237. shdr->findUniVar("lightRadius")->setFloat(light.getDistance());
  238. shdr->findUniVar("lightDiffuseCol")->setVec3(&light.lightData->getDiffuseCol());
  239. shdr->findUniVar("lightSpecularCol")->setVec3(&light.lightData->getSpecularCol());
  240. shdr->findUniVar("lightTex")->setTexture(light.lightData->getTexture(), 4);
  241. // set texture matrix for texture & shadowmap projection
  242. // Bias * P_light * V_light * inv(V_cam)
  243. static Mat4 biasMat4(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0);
  244. Mat4 texProjectionMat;
  245. texProjectionMat = biasMat4 * light.getCamera().getProjectionMatrix() *
  246. Mat4::combineTransformations(light.getCamera().getViewMatrix(), Mat4(cam.getWorldTransform()));
  247. shdr->findUniVar("texProjectionMat")->setMat4(&texProjectionMat);
  248. // the shadowmap
  249. if(light.castsShadow() && sm->isEnabled())
  250. {
  251. shdr->findUniVar("shadowMap")->setTexture(sm->shadowMap, 5);
  252. }
  253. // render quad
  254. drawLightPassQuad();
  255. }
  256. //======================================================================================================================
  257. // run =
  258. //======================================================================================================================
  259. void Is::run()
  260. {
  261. // FBO
  262. fbo.bind();
  263. // OGL stuff
  264. Renderer::setViewport(0, 0, r.getWidth(), r.getHeight());
  265. glMatrixMode(GL_MODELVIEW);
  266. glLoadIdentity();
  267. glDisable(GL_DEPTH_TEST);
  268. // ambient pass
  269. ambientPass(app->getScene().getAmbientCol());
  270. // light passes
  271. glEnable(GL_BLEND);
  272. glBlendFunc(GL_ONE, GL_ONE);
  273. glEnable(GL_STENCIL_TEST);
  274. calcViewVectors();
  275. calcPlanes();
  276. // for all lights
  277. for(uint i=0; i<app->getScene().lights.size(); i++)
  278. {
  279. const Light& light = *app->getScene().lights[i];
  280. switch(light.getType())
  281. {
  282. case Light::LT_POINT:
  283. {
  284. const PointLight& pointl = static_cast<const PointLight&>(light);
  285. pointLightPass(pointl);
  286. break;
  287. }
  288. case Light::LT_SPOT:
  289. {
  290. const SpotLight& projl = static_cast<const SpotLight&>(light);
  291. spotLightPass(projl);
  292. break;
  293. }
  294. default:
  295. RASSERT_THROW_EXCEPTION("WTF?");
  296. }
  297. }
  298. glDisable(GL_STENCIL_TEST);
  299. // FBO
  300. fbo.unbind();
  301. }