main.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /** Example 027 Post Processing
  2. This tutorial shows how to implement post processing for D3D9 and OpenGL with
  3. the engine. In order to do post processing, scene objects are firstly rendered
  4. to render target. With the help of screen quad, the render target texture
  5. is then drawn on the quad with shader-defined effects applied.
  6. This tutorial shows how to create a screen quad. It also shows how to create a
  7. render target texture and associate it with the quad. Effects are defined as
  8. shaders which are applied during rendering the quad with the render target
  9. texture attached to it.
  10. A simple color inverse example is presented in this tutorial. The effect is
  11. written in HLSL and GLSL.
  12. @author Boshen Guan
  13. We include all headers and define necessary variables as we have done before.
  14. */
  15. #include <irrlicht.h>
  16. #include "driverChoice.h"
  17. #include "exampleHelper.h"
  18. using namespace irr;
  19. #ifdef _MSC_VER
  20. #pragma comment(lib, "Irrlicht.lib")
  21. #endif
  22. /*
  23. We write a class derived from IShaderConstantSetCallBack class and implement
  24. OnSetConstants callback interface. In this callback, we will set constants
  25. used by the shader.
  26. In this example, our HLSL shader needs texture size as input in its vertex
  27. shader. Therefore, we set texture size in OnSetConstants callback using
  28. setVertexShaderConstant function.
  29. */
  30. class QuadShaderCallBack : public video::IShaderConstantSetCallBack
  31. {
  32. public:
  33. QuadShaderCallBack() : FirstUpdate(true), TextureSizeID(-1), TextureSamplerID(-1)
  34. { }
  35. virtual void OnSetConstants(video::IMaterialRendererServices* services,
  36. s32 userData)
  37. {
  38. if ( FirstUpdate )
  39. {
  40. FirstUpdate = false;
  41. TextureSizeID = services->getVertexShaderConstantID("TextureSize");
  42. TextureSamplerID = services->getPixelShaderConstantID("TextureSampler");
  43. }
  44. // get texture size array (for our simple example HLSL just needs that to calculate pixel centers)
  45. core::dimension2d<u32> size = services->getVideoDriver()->getCurrentRenderTargetSize();
  46. f32 textureSize[2];
  47. textureSize[0] = (f32)size.Width;
  48. textureSize[1] = (f32)size.Height;
  49. // set texture size to vertex shader
  50. services->setVertexShaderConstant(TextureSizeID, textureSize, 2);
  51. // set texture for an OpenGL driver
  52. s32 textureLayer = 0;
  53. services->setPixelShaderConstant(TextureSamplerID, &textureLayer, 1);
  54. }
  55. private:
  56. bool FirstUpdate;
  57. s32 TextureSizeID;
  58. s32 TextureSamplerID;
  59. };
  60. class ScreenQuad : public IReferenceCounted
  61. {
  62. public:
  63. ScreenQuad(video::IVideoDriver* driver)
  64. : Driver(driver)
  65. {
  66. // --------------------------------> u
  67. // |[1](-1, 1)----------[2](1, 1)
  68. // | | ( 0, 0) / | (1, 0)
  69. // | | / |
  70. // | | / |
  71. // | | / |
  72. // | | / |
  73. // | | / |
  74. // | | / |
  75. // | | / |
  76. // | | / |
  77. // |[0](-1, -1)---------[3](1, -1)
  78. // | ( 0, 1) (1, 1)
  79. // V
  80. // v
  81. /*
  82. A screen quad is composed of two adjacent triangles with 4 vertices.
  83. Vertex [0], [1] and [2] create the first triangle and Vertex [0],
  84. [2] and [3] create the second one. To map texture on the quad, UV
  85. coordinates are assigned to the vertices. The origin of UV coordinate
  86. locates on the top-left corner. And the value of UVs range from 0 to 1.
  87. */
  88. // define vertices array
  89. Vertices[0] = irr::video::S3DVertex(-1.0f, -1.0f, 0.0f, 1, 1, 0, irr::video::SColor(0,255,255,255), 0.0f, 1.0f);
  90. Vertices[1] = irr::video::S3DVertex(-1.0f, 1.0f, 0.0f, 1, 1, 0, irr::video::SColor(0,255,255,255), 0.0f, 0.0f);
  91. Vertices[2] = irr::video::S3DVertex( 1.0f, 1.0f, 0.0f, 1, 1, 0, irr::video::SColor(0,255,255,255), 1.0f, 0.0f);
  92. Vertices[3] = irr::video::S3DVertex( 1.0f, -1.0f, 0.0f, 1, 1, 0, irr::video::SColor(0,255,255,255), 1.0f, 1.0f);
  93. // define indices for triangles
  94. Indices[0] = 0;
  95. Indices[1] = 1;
  96. Indices[2] = 2;
  97. Indices[3] = 0;
  98. Indices[4] = 2;
  99. Indices[5] = 3;
  100. // turn off lighting as default
  101. Material.setFlag(video::EMF_LIGHTING, false);
  102. // set texture warp settings to clamp to edge pixel
  103. for (u32 i = 0; i < video::MATERIAL_MAX_TEXTURES; i++)
  104. {
  105. Material.TextureLayer[i].TextureWrapU = video::ETC_CLAMP_TO_EDGE;
  106. Material.TextureLayer[i].TextureWrapV = video::ETC_CLAMP_TO_EDGE;
  107. }
  108. }
  109. virtual ~ScreenQuad() {}
  110. //! render the screen quad
  111. virtual void render()
  112. {
  113. // set the material of screen quad
  114. Driver->setMaterial(Material);
  115. // set world matrix to fit the quad to full viewport
  116. Driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
  117. // view & projection not used in shader, but matter to burnings driver
  118. Driver->setTransform(video::ETS_VIEW, core::IdentityMatrix);
  119. Driver->setTransform(video::ETS_PROJECTION, core::IdentityMatrix);
  120. // draw screen quad
  121. Driver->drawVertexPrimitiveList(Vertices, 4, Indices, 2);
  122. }
  123. //! Access the material
  124. virtual video::SMaterial& getMaterial()
  125. {
  126. return Material;
  127. }
  128. private:
  129. video::IVideoDriver *Driver;
  130. video::S3DVertex Vertices[4];
  131. u16 Indices[6];
  132. video::SMaterial Material;
  133. };
  134. /*
  135. We start up the engine just like before. Then shader programs are selected
  136. according to the driver type.
  137. */
  138. int main()
  139. {
  140. // ask user for driver
  141. video::E_DRIVER_TYPE driverType=driverChoiceConsole();
  142. if (driverType==video::EDT_COUNT)
  143. return 1;
  144. // create device
  145. IrrlichtDevice* device = createDevice(driverType, core::dimension2d<u32>(640, 480));
  146. if (device == 0)
  147. return 1; // could not create selected driver.
  148. video::IVideoDriver* driver = device->getVideoDriver();
  149. scene::ISceneManager* smgr = device->getSceneManager();
  150. /*
  151. In this example, high level post processing shaders are loaded for both
  152. Direct3D and OpenGL drivers.
  153. File pp_d3d9.hlsl is for Direct3D 9, and pp_opengl.frag/pp_opengl.vert
  154. are for OpenGL.
  155. */
  156. const io::path mediaPath = getExampleMediaPath();
  157. io::path vsFileName; // filename for the vertex shader
  158. io::path psFileName; // filename for the pixel shader
  159. switch(driverType)
  160. {
  161. case video::EDT_DIRECT3D9:
  162. psFileName = mediaPath + "pp_d3d9.hlsl";
  163. vsFileName = psFileName; // both shaders are in the same file
  164. break;
  165. case video::EDT_OPENGL:
  166. case video::EDT_BURNINGSVIDEO:
  167. psFileName = mediaPath + "pp_opengl.frag";
  168. vsFileName = mediaPath + "pp_opengl.vert";
  169. break;
  170. }
  171. /*
  172. Check for hardware capability of executing the corresponding shaders
  173. on selected renderer. This is not necessary though.
  174. */
  175. if (!driver->queryFeature(video::EVDF_PIXEL_SHADER_1_1) &&
  176. !driver->queryFeature(video::EVDF_ARB_FRAGMENT_PROGRAM_1))
  177. {
  178. device->getLogger()->log("WARNING: Pixel shaders disabled "\
  179. "because of missing driver/hardware support.");
  180. psFileName = "";
  181. }
  182. if (!driver->queryFeature(video::EVDF_VERTEX_SHADER_1_1) &&
  183. !driver->queryFeature(video::EVDF_ARB_VERTEX_PROGRAM_1))
  184. {
  185. device->getLogger()->log("WARNING: Vertex shaders disabled "\
  186. "because of missing driver/hardware support.");
  187. vsFileName = "";
  188. }
  189. /*
  190. An animated mesh is loaded to be displayed. As in most examples,
  191. we'll take the fairy md2 model.
  192. */
  193. // load and display animated fairy mesh
  194. scene::IAnimatedMeshSceneNode* fairy = smgr->addAnimatedMeshSceneNode(
  195. smgr->getMesh(mediaPath + "faerie.md2"));
  196. if (fairy)
  197. {
  198. fairy->setMaterialTexture(0,
  199. driver->getTexture(mediaPath + "faerie2.bmp")); // set diffuse texture
  200. fairy->setMaterialFlag(video::EMF_LIGHTING, false); // disable dynamic lighting
  201. fairy->setPosition(core::vector3df(-10,0,-100));
  202. fairy->setMD2Animation ( scene::EMAT_STAND );
  203. }
  204. // add scene camera
  205. smgr->addCameraSceneNode(0, core::vector3df(10,10,-80),
  206. core::vector3df(-10,10,-100));
  207. /*
  208. We create a render target texture (RTT) with the same size as frame buffer.
  209. Instead of rendering the scene directly to the frame buffer, we firstly
  210. render it to this RTT. Post processing is then applied based on this RTT.
  211. RTT size needs not to be the same with frame buffer though. However in this
  212. example, we expect the result of rendering to RTT to be consistent with the
  213. result of rendering directly to the frame buffer. Therefore, the size of
  214. RTT keeps the same with frame buffer.
  215. */
  216. // create render target
  217. video::ITexture* rt = 0;
  218. if (driver->queryFeature(video::EVDF_RENDER_TO_TARGET))
  219. {
  220. rt = driver->addRenderTargetTexture(core::dimension2d<u32>(640, 480), "RTT1");
  221. }
  222. else
  223. {
  224. device->getLogger()->log("Your hardware or this renderer is not able to use the "\
  225. "render to texture feature. RTT Disabled.");
  226. }
  227. /*
  228. Post processing is achieved by rendering a screen quad with this RTT (with
  229. previously rendered result) as a texture on the quad. A screen quad is
  230. geometry of flat plane composed of two adjacent triangles covering the
  231. entire area of viewport. In this pass of rendering, RTT works just like
  232. a normal texture and is drawn on the quad during rendering. We can then
  233. take control of this rendering process by applying various shader-defined
  234. materials to the quad. In other words, we can achieve different effect by
  235. writing different shaders.
  236. This process is called post processing because it normally does not rely
  237. on scene geometry. The inputs of this process are just textures, or in
  238. other words, just images. With the help of screen quad, we can draw these
  239. images on the screen with different effects. For example, we can adjust
  240. contrast, make grayscale, add noise, do more fancy effect such as blur,
  241. bloom, ghost, or just like in this example, we invert the color to produce
  242. negative image.
  243. Note that post processing is not limited to use only one texture. It can
  244. take multiple textures as shader inputs to provide desired result. In
  245. addition, post processing can also be chained to produce compound result.
  246. */
  247. // we create a screen quad
  248. ScreenQuad *screenQuad = new ScreenQuad(driver);
  249. video::SMaterial& screenQuadMaterial = screenQuad->getMaterial();
  250. // turn off mip maps and bilinear filter since we do not want interpolated results
  251. screenQuadMaterial.setFlag(video::EMF_USE_MIP_MAPS, false);
  252. screenQuadMaterial.setFlag(video::EMF_BILINEAR_FILTER, false);
  253. // turn off depth buffer, because our full screen 2D overlay doesn't process depth
  254. screenQuadMaterial.setFlag(video::EMF_ZBUFFER, false);
  255. // set quad texture to RTT we just create
  256. screenQuadMaterial.setTexture(0, rt);
  257. /*
  258. Let's create material for the quad. Like in other example, we create material
  259. using IGPUProgrammingServices and call addShaderMaterialFromFiles, which
  260. returns a material type identifier.
  261. */
  262. // create materials
  263. video::IGPUProgrammingServices* gpu = driver->getGPUProgrammingServices();
  264. s32 ppMaterialType = 0;
  265. if (gpu)
  266. {
  267. // We write a QuadShaderCallBack class that implements OnSetConstants
  268. // callback of IShaderConstantSetCallBack class at the beginning of
  269. // this tutorial. We set shader constants in this callback.
  270. // create an instance of callback class
  271. QuadShaderCallBack* mc = new QuadShaderCallBack();
  272. // create material from post processing shaders
  273. ppMaterialType = gpu->addHighLevelShaderMaterialFromFiles(
  274. vsFileName, "vertexMain", video::EVST_VS_1_1,
  275. psFileName, "pixelMain", video::EPST_PS_1_1, mc);
  276. mc->drop();
  277. }
  278. // set post processing material type to the quad
  279. screenQuadMaterial.MaterialType = (video::E_MATERIAL_TYPE)ppMaterialType;
  280. /*
  281. Now draw everything. That's all.
  282. */
  283. int lastFPS = -1;
  284. while(device->run())
  285. {
  286. if (device->isWindowActive())
  287. {
  288. driver->beginScene(true, true, video::SColor(255,0,0,0));
  289. if (rt)
  290. {
  291. // draw scene into render target
  292. // set render target to RTT
  293. driver->setRenderTarget(rt, true, true, video::SColor(255,0,0,0));
  294. // draw scene to RTT just like normal rendering
  295. smgr->drawAll();
  296. // after rendering to RTT, we change render target back
  297. driver->setRenderTarget(0, true, true, video::SColor(255,0,0,0));
  298. // render screen quad to apply post processing
  299. screenQuad->render();
  300. }
  301. else
  302. {
  303. // draw scene normally
  304. smgr->drawAll();
  305. }
  306. driver->endScene();
  307. int fps = driver->getFPS();
  308. if (lastFPS != fps)
  309. {
  310. core::stringw str = L"Irrlicht Engine - Post processing example [";
  311. str += driver->getName();
  312. str += "] FPS:";
  313. str += fps;
  314. device->setWindowCaption(str.c_str());
  315. lastFPS = fps;
  316. }
  317. }
  318. }
  319. // do not forget to manually drop the screen quad
  320. screenQuad->drop();
  321. device->drop();
  322. return 0;
  323. }
  324. /*
  325. **/