main.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. /** Example 010 Shaders
  2. This tutorial shows how to use shaders for D3D9, and OpenGL with the
  3. engine and how to create new material types with them. It also shows how to
  4. disable the generation of mipmaps at texture loading, and how to use text scene
  5. nodes.
  6. This tutorial does not explain how shaders work. I would recommend to read the
  7. D3D or OpenGL, documentation, to search a tutorial, or to read a book about
  8. this.
  9. At first, we need to include all headers and do the stuff we always do, like in
  10. nearly all other tutorials:
  11. */
  12. #include <irrlicht.h>
  13. #include <iostream>
  14. #include "driverChoice.h"
  15. #include "exampleHelper.h"
  16. using namespace irr;
  17. #ifdef _MSC_VER
  18. #pragma comment(lib, "Irrlicht.lib")
  19. #endif
  20. /*
  21. Because we want to use some interesting shaders in this tutorials, we need to
  22. set some data for them to make them able to compute nice colors. In this
  23. example, we'll use a simple vertex shader which will calculate the color of the
  24. vertex based on the position of the camera.
  25. For this, the shader needs the following data: The inverted world matrix for
  26. transforming the normal, the clip matrix for transforming the position, the
  27. camera position and the world position of the object for the calculation of the
  28. angle of light, and the color of the light. To be able to tell the shader all
  29. this data every frame, we have to derive a class from the
  30. IShaderConstantSetCallBack interface and override its only method, namely
  31. OnSetConstants(). This method will be called every time the material is set.
  32. The method setVertexShaderConstant() of the IMaterialRendererServices interface
  33. is used to set the data the shader needs. If the user chose to use a High Level
  34. shader language like HLSL instead of Assembler in this example, you have to set
  35. the variable name as parameter instead of the register index.
  36. */
  37. IrrlichtDevice* device = 0;
  38. bool UseHighLevelShaders = false;
  39. class MyShaderCallBack : public video::IShaderConstantSetCallBack
  40. {
  41. public:
  42. MyShaderCallBack() : WorldViewProjID(-1), TransWorldID(-1), InvWorldID(-1), PositionID(-1),
  43. ColorID(-1), TextureID(-1), FirstUpdate(true)
  44. {
  45. }
  46. virtual void OnSetConstants(video::IMaterialRendererServices* services,
  47. s32 userData)
  48. {
  49. video::IVideoDriver* driver = services->getVideoDriver();
  50. // get shader constants id.
  51. if (UseHighLevelShaders && FirstUpdate)
  52. {
  53. WorldViewProjID = services->getVertexShaderConstantID("mWorldViewProj");
  54. TransWorldID = services->getVertexShaderConstantID("mTransWorld");
  55. InvWorldID = services->getVertexShaderConstantID("mInvWorld");
  56. PositionID = services->getVertexShaderConstantID("mLightPos");
  57. ColorID = services->getVertexShaderConstantID("mLightColor");
  58. // Textures ID are important only for OpenGL interface.
  59. if(driver->getDriverType() == video::EDT_OPENGL)
  60. TextureID = services->getVertexShaderConstantID("myTexture");
  61. FirstUpdate = false;
  62. }
  63. // set inverted world matrix
  64. // if we are using highlevel shaders (the user can select this when
  65. // starting the program), we must set the constants by name.
  66. core::matrix4 invWorld = driver->getTransform(video::ETS_WORLD);
  67. invWorld.makeInverse();
  68. if (UseHighLevelShaders)
  69. services->setVertexShaderConstant(InvWorldID, invWorld.pointer(), 16);
  70. else
  71. services->setVertexShaderConstant(invWorld.pointer(), 0, 4);
  72. // set clip matrix
  73. core::matrix4 worldViewProj;
  74. worldViewProj = driver->getTransform(video::ETS_PROJECTION);
  75. worldViewProj *= driver->getTransform(video::ETS_VIEW);
  76. worldViewProj *= driver->getTransform(video::ETS_WORLD);
  77. if (UseHighLevelShaders)
  78. services->setVertexShaderConstant(WorldViewProjID, worldViewProj.pointer(), 16);
  79. else
  80. services->setVertexShaderConstant(worldViewProj.pointer(), 4, 4);
  81. // set camera position
  82. core::vector3df pos = device->getSceneManager()->
  83. getActiveCamera()->getAbsolutePosition();
  84. if (UseHighLevelShaders)
  85. services->setVertexShaderConstant(PositionID, reinterpret_cast<f32*>(&pos), 3);
  86. else
  87. services->setVertexShaderConstant(reinterpret_cast<f32*>(&pos), 8, 1);
  88. // set light color
  89. video::SColorf col(0.0f,1.0f,1.0f,0.0f);
  90. if (UseHighLevelShaders)
  91. services->setVertexShaderConstant(ColorID,
  92. reinterpret_cast<f32*>(&col), 4);
  93. else
  94. services->setVertexShaderConstant(reinterpret_cast<f32*>(&col), 9, 1);
  95. // set transposed world matrix
  96. core::matrix4 world = driver->getTransform(video::ETS_WORLD);
  97. world = world.getTransposed();
  98. if (UseHighLevelShaders)
  99. {
  100. services->setVertexShaderConstant(TransWorldID, world.pointer(), 16);
  101. // set texture, for textures you can use both an int and a float setPixelShaderConstant interfaces (You need it only for an OpenGL driver).
  102. s32 TextureLayerID = 0;
  103. services->setPixelShaderConstant(TextureID, &TextureLayerID, 1);
  104. }
  105. else
  106. services->setVertexShaderConstant(world.pointer(), 10, 4);
  107. }
  108. private:
  109. s32 WorldViewProjID;
  110. s32 TransWorldID;
  111. s32 InvWorldID;
  112. s32 PositionID;
  113. s32 ColorID;
  114. s32 TextureID;
  115. bool FirstUpdate;
  116. };
  117. /*
  118. The next few lines start up the engine just like in most other tutorials
  119. before. But in addition, we ask the user if he wants to use high level shaders
  120. in this example, if he selected a driver which is capable of doing so.
  121. */
  122. int main()
  123. {
  124. // ask user for driver
  125. video::E_DRIVER_TYPE driverType=driverChoiceConsole();
  126. if (driverType==video::EDT_COUNT)
  127. return 1;
  128. // ask the user if we should use high level shaders for this example
  129. if (driverType == video::EDT_DIRECT3D9 ||
  130. driverType == video::EDT_OPENGL)
  131. {
  132. char i = 'y';
  133. printf("Please press 'y' if you want to use high level shaders.\n");
  134. std::cin >> i;
  135. if (i == 'y')
  136. {
  137. UseHighLevelShaders = true;
  138. }
  139. }
  140. // create device
  141. device = createDevice(driverType, core::dimension2d<u32>(640, 480));
  142. if (device == 0)
  143. return 1; // could not create selected driver.
  144. video::IVideoDriver* driver = device->getVideoDriver();
  145. scene::ISceneManager* smgr = device->getSceneManager();
  146. gui::IGUIEnvironment* gui = device->getGUIEnvironment();
  147. const io::path mediaPath = getExampleMediaPath();
  148. /*
  149. Now for the more interesting parts. If we are using Direct3D, we want
  150. to load vertex and pixel shader programs, if we have OpenGL, we want to
  151. use ARB fragment and vertex programs. I wrote the corresponding
  152. programs down into the files d3d9.ps, d3d9.vs, opengl.ps and opengl.vs.
  153. We only need the right filenames now. This is done in the following switch.
  154. Note, that it is not necessary to write the shaders into text files,
  155. like in this example. You can even write the shaders directly as strings
  156. into the cpp source file, and use later addShaderMaterial() instead of
  157. addShaderMaterialFromFiles().
  158. */
  159. io::path vsFileName; // filename for the vertex shader
  160. io::path psFileName; // filename for the pixel shader
  161. switch(driverType)
  162. {
  163. case video::EDT_DIRECT3D9:
  164. if (UseHighLevelShaders)
  165. {
  166. psFileName = mediaPath + "d3d9.hlsl";
  167. vsFileName = psFileName; // both shaders are in the same file
  168. }
  169. else
  170. {
  171. psFileName = mediaPath + "d3d9.psh";
  172. vsFileName = mediaPath + "d3d9.vsh";
  173. }
  174. break;
  175. case video::EDT_OPENGL:
  176. if (UseHighLevelShaders)
  177. {
  178. psFileName = mediaPath + "opengl.frag";
  179. vsFileName = mediaPath + "opengl.vert";
  180. }
  181. else
  182. {
  183. psFileName = mediaPath + "opengl.psh";
  184. vsFileName = mediaPath + "opengl.vsh";
  185. }
  186. break;
  187. default:
  188. break;
  189. }
  190. /*
  191. In addition, we check if the hardware and the selected renderer is
  192. capable of executing the shaders we want. If not, we simply set the
  193. filename string to 0. This is not necessary, but useful in this
  194. example: For example, if the hardware is able to execute vertex shaders
  195. but not pixel shaders, we create a new material which only uses the
  196. vertex shader, and no pixel shader. Otherwise, if we would tell the
  197. engine to create this material and the engine sees that the hardware
  198. wouldn't be able to fulfill the request completely, it would not
  199. create any new material at all. So in this example you would see at
  200. least the vertex shader in action, without the pixel shader.
  201. */
  202. if (!driver->queryFeature(video::EVDF_PIXEL_SHADER_1_1) &&
  203. !driver->queryFeature(video::EVDF_ARB_FRAGMENT_PROGRAM_1))
  204. {
  205. device->getLogger()->log("WARNING: Pixel shaders disabled "\
  206. "because of missing driver/hardware support.");
  207. psFileName = "";
  208. }
  209. if (!driver->queryFeature(video::EVDF_VERTEX_SHADER_1_1) &&
  210. !driver->queryFeature(video::EVDF_ARB_VERTEX_PROGRAM_1))
  211. {
  212. device->getLogger()->log("WARNING: Vertex shaders disabled "\
  213. "because of missing driver/hardware support.");
  214. vsFileName = "";
  215. }
  216. /*
  217. Now lets create the new materials. As you maybe know from previous
  218. examples, a material type in the Irrlicht engine is set by simply
  219. changing the MaterialType value in the SMaterial struct. And this value
  220. is just a simple 32 bit value, like video::EMT_SOLID. So we only need
  221. the engine to create a new value for us which we can set there. To do
  222. this, we get a pointer to the IGPUProgrammingServices and call
  223. addShaderMaterialFromFiles(), which returns such a new 32 bit value.
  224. That's all.
  225. The parameters to this method are the following: First, the names of
  226. the files containing the code of the vertex and the pixel shader. If
  227. you would use addShaderMaterial() instead, you would not need file
  228. names, then you could write the code of the shader directly as string.
  229. The following parameter is a pointer to the IShaderConstantSetCallBack
  230. class we wrote at the beginning of this tutorial. If you don't want to
  231. set constants, set this to 0. The last parameter tells the engine which
  232. material it should use as base material.
  233. To demonstrate this, we create two materials with a different base
  234. material, one with EMT_SOLID and one with EMT_TRANSPARENT_ADD_COLOR.
  235. */
  236. // create materials
  237. video::IGPUProgrammingServices* gpu = driver->getGPUProgrammingServices();
  238. s32 newMaterialType1 = 0;
  239. s32 newMaterialType2 = 0;
  240. if (gpu)
  241. {
  242. /*
  243. Create one callback instance for each shader material you add.
  244. Reason is that the getVertexShaderConstantID returns ID's which are
  245. only valid per added material (The ID's tend to be identical
  246. as long as the shader code is exactly identical, but it's not good
  247. style to depend on that).
  248. */
  249. MyShaderCallBack* mcSolid = new MyShaderCallBack();
  250. MyShaderCallBack* mcTransparentAdd = new MyShaderCallBack();
  251. // create the shaders depending on if the user wanted high level
  252. // or low level shaders:
  253. if (UseHighLevelShaders)
  254. {
  255. // create material from high level shaders (hlsl, glsl)
  256. newMaterialType1 = gpu->addHighLevelShaderMaterialFromFiles(
  257. vsFileName, "vertexMain", video::EVST_VS_1_1,
  258. psFileName, "pixelMain", video::EPST_PS_1_1,
  259. mcSolid, video::EMT_SOLID, 0);
  260. newMaterialType2 = gpu->addHighLevelShaderMaterialFromFiles(
  261. vsFileName, "vertexMain", video::EVST_VS_1_1,
  262. psFileName, "pixelMain", video::EPST_PS_1_1,
  263. mcTransparentAdd, video::EMT_TRANSPARENT_ADD_COLOR, 0);
  264. }
  265. else
  266. {
  267. // create material from low level shaders (asm or arb_asm)
  268. newMaterialType1 = gpu->addShaderMaterialFromFiles(vsFileName,
  269. psFileName, mcSolid, video::EMT_SOLID);
  270. newMaterialType2 = gpu->addShaderMaterialFromFiles(vsFileName,
  271. psFileName, mcTransparentAdd, video::EMT_TRANSPARENT_ADD_COLOR);
  272. }
  273. mcSolid->drop();
  274. mcTransparentAdd->drop();
  275. }
  276. /*
  277. Now it's time for testing the materials. We create a test cube and set
  278. the material we created. In addition, we add a text scene node to the
  279. cube and a rotation animator to make it look more interesting and
  280. important.
  281. */
  282. // create test scene node 1, with the new created material type 1
  283. scene::ISceneNode* node = smgr->addCubeSceneNode(50);
  284. node->setPosition(core::vector3df(0,0,0));
  285. node->setMaterialTexture(0, driver->getTexture(mediaPath + "wall.bmp"));
  286. node->setMaterialFlag(video::EMF_LIGHTING, false);
  287. node->setMaterialType((video::E_MATERIAL_TYPE)newMaterialType1);
  288. smgr->addTextSceneNode(gui->getBuiltInFont(),
  289. L"PS & VS & EMT_SOLID",
  290. video::SColor(255,255,255,255), node);
  291. scene::ISceneNodeAnimator* anim = smgr->createRotationAnimator(
  292. core::vector3df(0,0.3f,0));
  293. node->addAnimator(anim);
  294. anim->drop();
  295. /*
  296. Same for the second cube, but with the second material we created.
  297. */
  298. // create test scene node 2, with the new created material type 2
  299. node = smgr->addCubeSceneNode(50);
  300. node->setPosition(core::vector3df(0,-10,50));
  301. node->setMaterialTexture(0, driver->getTexture(mediaPath + "wall.bmp"));
  302. node->setMaterialFlag(video::EMF_LIGHTING, false);
  303. node->setMaterialFlag(video::EMF_BLEND_OPERATION, true);
  304. node->setMaterialType((video::E_MATERIAL_TYPE)newMaterialType2);
  305. smgr->addTextSceneNode(gui->getBuiltInFont(),
  306. L"PS & VS & EMT_TRANSPARENT",
  307. video::SColor(255,255,255,255), node);
  308. anim = smgr->createRotationAnimator(core::vector3df(0,0.3f,0));
  309. node->addAnimator(anim);
  310. anim->drop();
  311. /*
  312. Then we add a third cube without a shader on it, to be able to compare
  313. the cubes.
  314. */
  315. // add a scene node with no shader
  316. node = smgr->addCubeSceneNode(50);
  317. node->setPosition(core::vector3df(0,50,25));
  318. node->setMaterialTexture(0, driver->getTexture(mediaPath + "wall.bmp"));
  319. node->setMaterialFlag(video::EMF_LIGHTING, false);
  320. smgr->addTextSceneNode(gui->getBuiltInFont(), L"NO SHADER",
  321. video::SColor(255,255,255,255), node);
  322. /*
  323. And last, we add a skybox and a user controlled camera to the scene.
  324. For the skybox textures, we disable mipmap generation, because we don't
  325. need mipmaps on it.
  326. */
  327. // add a nice skybox
  328. driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
  329. smgr->addSkyBoxSceneNode(
  330. driver->getTexture(mediaPath + "irrlicht2_up.jpg"),
  331. driver->getTexture(mediaPath + "irrlicht2_dn.jpg"),
  332. driver->getTexture(mediaPath + "irrlicht2_lf.jpg"),
  333. driver->getTexture(mediaPath + "irrlicht2_rt.jpg"),
  334. driver->getTexture(mediaPath + "irrlicht2_ft.jpg"),
  335. driver->getTexture(mediaPath + "irrlicht2_bk.jpg"));
  336. driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, true);
  337. // add a camera and disable the mouse cursor
  338. scene::ICameraSceneNode* cam = smgr->addCameraSceneNodeFPS();
  339. cam->setPosition(core::vector3df(-100,50,100));
  340. cam->setTarget(core::vector3df(0,0,0));
  341. device->getCursorControl()->setVisible(false);
  342. /*
  343. Now draw everything. That's all.
  344. */
  345. int lastFPS = -1;
  346. while(device->run())
  347. if (device->isWindowActive())
  348. {
  349. driver->beginScene(video::ECBF_COLOR | video::ECBF_DEPTH, video::SColor(255,0,0,0));
  350. smgr->drawAll();
  351. driver->endScene();
  352. int fps = driver->getFPS();
  353. if (lastFPS != fps)
  354. {
  355. core::stringw str = L"Irrlicht Engine - Vertex and pixel shader example [";
  356. str += driver->getName();
  357. str += "] FPS:";
  358. str += fps;
  359. device->setWindowCaption(str.c_str());
  360. lastFPS = fps;
  361. }
  362. }
  363. device->drop();
  364. return 0;
  365. }
  366. /*
  367. Compile and run this, and I hope you have fun with your new little shader
  368. writing tool :).
  369. **/