This tutorial shows how to use one of the built in more complex materials in irrlicht: Per pixel lighted surfaces using normal maps and parallax mapping. It will also show how to use fog and moving particle systems. And don't panic: You do not need any experience with shaders to use these materials in Irrlicht.
At first, we need to include all headers and do the stuff we always do, like in nearly all other tutorials.
#ifdef _MSC_VER
#pragma comment(lib, "Irrlicht.lib")
#endif
Main header file of the irrlicht, the only file needed to include.
Everything in the Irrlicht Engine can be found in this namespace.
For this example, we need an event receiver, to make it possible for the user to switch between the three available material types. In addition, the event receiver will create some small GUI window which displays what material is currently being used. There is nothing special done in this class, so maybe you want to skip reading it.
{
public:
{
Room = room;
Earth = earth;
Driver = driver;
if (font)
ListBox->addItem(L"Bump mapping");
ListBox->addItem(L"Parallax mapping");
ListBox->setSelected(1);
L"Your hardware or this renderer is not able to use the "\
L"needed shaders for this material. Using fall back materials.",
Driver->getMaterialRenderer(video::EMT_PARALLAX_MAP_SOLID);
ListBox->setSelected(2);
setMaterial();
}
bool OnEvent(
const SEvent& event)
{
{
int sel = ListBox->getSelected();
++sel;
else
--sel;
else
return false;
if (sel > 2) sel = 0;
if (sel < 0) sel = 2;
ListBox->setSelected(sel);
setMaterial();
}
return false;
}
private:
void setMaterial()
{
switch(ListBox->getSelected())
{
case 0: type = video::EMT_SOLID;
break;
case 1: type = video::EMT_NORMAL_MAP_SOLID;
break;
case 2: type = video::EMT_PARALLAX_MAP_SOLID;
break;
}
Room->setMaterialType(type);
switch(ListBox->getSelected())
{
case 0: type = video::EMT_TRANSPARENT_VERTEX_ALPHA;
break;
case 1: type = video::EMT_NORMAL_MAP_TRANSPARENT_VERTEX_ALPHA;
break;
case 2: type = video::EMT_PARALLAX_MAP_TRANSPARENT_VERTEX_ALPHA;
break;
}
Earth->setMaterialType(type);
Interface of an object which can receive events.
Axis aligned bounding box in 3d dimensional space.
GUI Environment. Used as factory and manager of all other GUI elements.
virtual IGUIFont * getFont(const io::path &filename)=0
Returns pointer to the font with the specified filename.
virtual IGUIListBox * addListBox(const core::rect< s32 > &rectangle, IGUIElement *parent=0, s32 id=-1, bool drawBackground=false)=0
Adds a list box element.
virtual IGUIStaticText * addStaticText(const wchar_t *text, const core::rect< s32 > &rectangle, bool border=false, bool wordWrap=true, IGUIElement *parent=0, s32 id=-1, bool fillBackground=false)=0
Adds a static text.
virtual IGUISkin * getSkin() const =0
Returns pointer to the current gui skin.
virtual IGUIWindow * addWindow(const core::rect< s32 > &rectangle, bool modal=false, const wchar_t *text=0, IGUIElement *parent=0, s32 id=-1)=0
Adds an empty window element.
virtual u32 addItem(const wchar_t *text)=0
adds an list item, returns id of item
A skin modifies the look of the GUI elements.
virtual void setFont(IGUIFont *font, EGUI_DEFAULT_FONT which=EGDF_DEFAULT)=0
sets a default font
virtual void setOverrideColor(video::SColor color)=0
Sets another color for the text.
Default moveable window GUI element with border, caption and close icons.
Interface for material rendering.
virtual s32 getRenderCapability() const
Returns the render capability of the material.
Interface to driver which is able to perform 2d and 3d graphics functions.
Class representing a 32 bit ARGB color.
E_MATERIAL_TYPE
Abstracted and easy to use fixed function/programmable pipeline material modes.
@ EET_KEY_INPUT_EVENT
A key input event.
SEvents hold information about an event. See irr::IEventReceiver for details on event handling.
struct SKeyInput KeyInput
We need to add a warning if the materials will not be able to be displayed 100% correctly. This is no problem, they will be rendered using fall back materials, but at least the user should know that it would look better on better hardware. We simply check if the material renderer is able to draw at full quality on the current hardware. The IMaterialRenderer::getRenderCapability() returns 0 if this is the case.
ProblemText->setVisible(true);
else
ProblemText->setVisible(false);
}
private:
};
Default list box GUI element.
Multi or single line text label.
Now for the real fun. We create an Irrlicht Device and start to setup the scene.
int main()
{
if (driverType==video::EDT_COUNT)
return 1;
if (device == 0)
return 1;
The Irrlicht device. You can create it with createDevice() or createDeviceEx().
E_DRIVER_TYPE
An enum for all types of drivers the Irrlicht Engine supports.
Before we start with the interesting stuff, we do some simple things: Store pointers to the most important parts of the engine (video driver, scene manager, gui environment) to safe us from typing too much, add an irrlicht engine logo to the window and a user controlled first person shooter style camera. Also, we let the engine know that it should store all textures in 32 bit. This necessary because for parallax mapping, we need 32 bit textures.
virtual gui::ICursorControl * getCursorControl()=0
Provides access to the cursor control.
virtual scene::ISceneManager * getSceneManager()=0
Provides access to the scene manager.
virtual video::IVideoDriver * getVideoDriver()=0
Provides access to the video driver for drawing 3d and 2d geometry.
virtual gui::IGUIEnvironment * getGUIEnvironment()=0
Provides access to the 2d user interface environment.
virtual void setVisible(bool visible)=0
Changes the visible state of the mouse cursor.
virtual IGUIImage * addImage(video::ITexture *image, core::position2d< s32 > pos, bool useAlphaChannel=true, IGUIElement *parent=0, s32 id=-1, const wchar_t *text=0)=0
Adds an image element.
Scene Node which is a (controlable) camera.
The Scene Manager manages scene nodes, mesh recources, cameras and all the other stuff.
virtual ICameraSceneNode * addCameraSceneNodeFPS(ISceneNode *parent=0, f32 rotateSpeed=100.0f, f32 moveSpeed=0.5f, s32 id=-1, SKeyMap *keyMapArray=0, s32 keyMapSize=0, bool noVerticalMovement=false, f32 jumpSpeed=0.f, bool invertMouse=false, bool makeActive=true)=0
Adds a camera scene node with an animator which provides mouse and keyboard control appropriate for f...
virtual void setPosition(const core::vector3df &newpos)
Sets the position of the node relative to its parent.
virtual ITexture * getTexture(const io::path &filename)=0
Get access to a named texture.
virtual void setTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag, bool enabled=true)=0
Enables or disables a texture creation flag.
Because we want the whole scene to look a little bit scarier, we add some fog to it. This is done by a call to IVideoDriver::setFog(). There you can set various fog settings. In this example, we use pixel fog, because it will work well with the materials we'll use in this example. Please note that you will have to set the material flag EMF_FOG_ENABLE to 'true' in every scene node which should be affected by this fog.
driver->
setFog(
video::SColor(0,138,125,81), video::EFT_FOG_LINEAR, 250, 1000, .003f,
true,
false);
virtual void setFog(SColor color=SColor(0, 255, 255, 255), E_FOG_TYPE fogType=EFT_FOG_LINEAR, f32 start=50.0f, f32 end=100.0f, f32 density=0.01f, bool pixelFog=false, bool rangeFog=false)=0
Sets the fog mode.
To be able to display something interesting, we load a mesh from a .3ds file which is a room I modeled with anim8or. It is the same room as from the specialFX example. Maybe you remember from that tutorial, I am no good modeler at all and so I totally messed up the texture mapping in this model, but we can simply repair it with the IMeshManipulator::makePlanarTextureMapping() method.
if (roomMesh)
{
Interface for an animated mesh.
virtual IMesh * getMesh(s32 frame, s32 detailLevel=255, s32 startFrameLoop=-1, s32 endFrameLoop=-1)=0
Returns the IMesh interface for a frame.
virtual void makePlanarTextureMapping(IMesh *mesh, f32 resolution=0.001f) const =0
Creates a planar texture mapping on the mesh.
virtual IAnimatedMesh * getMesh(const io::path &filename)=0
Get pointer to an animateable mesh. Loads the file if not loaded already.
virtual IMeshManipulator * getMeshManipulator()=0
Get pointer to the mesh manipulator.
Now for the first exciting thing: If we successfully loaded the mesh we need to apply textures to it. Because we want this room to be displayed with a very cool material, we have to do a little bit more than just set the textures. Instead of only loading a color map as usual, we also load a height map which is simply a grayscale texture. From this height map, we create a normal map which we will set as second texture of the room. If you already have a normal map, you could directly set it, but I simply didn't find a nice normal map for this texture. The normal map texture is being generated by the makeNormalMapTexture method of the VideoDriver. The second parameter specifies the height of the heightmap. If you set it to a bigger value, the map will look more rocky.
driver->
getTexture(
"../../media/rockwall_height.bmp");
if (normalMap)
Interface of a Video Driver dependent Texture.
virtual void makeNormalMapTexture(video::ITexture *texture, f32 amplitude=1.0f) const =0
Creates a normal map from a height map texture.
The Normal Map and the displacement map/height map in the alpha channel video::ITexture* normalMap = driver->getTexture("../../media/rockwall_NRM.tga");
But just setting color and normal map is not everything. The material we want to use needs some additional informations per vertex like tangents and binormals. Because we are too lazy to calculate that information now, we let Irrlicht do this for us. That's why we call IMeshManipulator::createMeshWithTangents(). It creates a mesh copy with tangents and binormals from another mesh. After we've done that, we simply create a standard mesh scene node with this mesh copy, set color and normal map and adjust some other material settings. Note that we set EMF_FOG_ENABLE to true to enable fog in the room.
createMeshWithTangents(roomMesh->
getMesh(0));
}
bool drop() const
Drops the object. Decrements the reference counter by one.
Class which holds the geometry of an object.
virtual IMeshSceneNode * addMeshSceneNode(IMesh *mesh, ISceneNode *parent=0, s32 id=-1, const core::vector3df &position=core::vector3df(0, 0, 0), const core::vector3df &rotation=core::vector3df(0, 0, 0), const core::vector3df &scale=core::vector3df(1.0f, 1.0f, 1.0f), bool alsoAddIfMeshPointerZero=false)=0
Adds a scene node for rendering a static mesh.
void setMaterialTexture(u32 textureLayer, video::ITexture *texture)
Sets the texture of the specified layer in all materials of this scene node to the new texture.
void setMaterialFlag(video::E_MATERIAL_FLAG flag, bool newvalue)
Sets all material flags at once to a new value.
void setMaterialType(video::E_MATERIAL_TYPE newType)
Sets the material type of all materials in this scene node to a new material type.
virtual video::SMaterial & getMaterial(u32 num)
Returns the material based on the zero based index i.
void set(u32 a, u32 r, u32 g, u32 b)
Sets all four components of the color at once.
SColor SpecularColor
How much specular light (highlights from a light) is reflected.
f32 Shininess
Value affecting the size of specular highlights.
f32 MaterialTypeParam
Free parameter, dependent on the material type.
After we've created a room shaded by per pixel lighting, we add a sphere into it with the same material, but we'll make it transparent. In addition, because the sphere looks somehow like a familiar planet, we make it rotate. The procedure is similar as before. The difference is that we are loading the mesh from an .x file which already contains a color map so we do not need to load it manually. But the sphere is a little bit too small for our needs, so we scale it by the factor 50.
if (earthMesh)
{
manipulator->
transform( tangentSphereMesh, m );
if (earthNormalMap)
{
}
tangentSphereMesh->
drop();
}
4x4 matrix. Mostly used as transformation matrix for 3d calculations.
CMatrix4< T > & setScale(const vector3d< T > &scale)
Set Scale.
An interface for easy manipulation of meshes.
void setVertexColorAlpha(IMesh *mesh, s32 alpha) const
Sets the alpha vertex color value of the whole mesh to a new value.
void transform(IMesh *mesh, const core::matrix4 &m) const
Applies a transformation to a mesh.
virtual IMesh * createMeshWithTangents(IMesh *mesh, bool recalculateNormals=false, bool smooth=false, bool angleWeighted=false, bool recalculateTangents=true) const =0
Creates a copy of the mesh, which will only consist of S3DVertexTangents vertices.
virtual ISceneNodeAnimator * createRotationAnimator(const core::vector3df &rotationSpeed)=0
Creates a rotation animator, which rotates the attached scene node around itself.
Animates a scene node. Can animate position, rotation, material, and so on.
virtual void addAnimator(ISceneNodeAnimator *animator)
Adds an animator which should animate this node.
Per pixel lighted materials only look cool when there are moving lights. So we add some. And because moving lights alone are so boring, we add billboards to them, and a whole particle system to one of them. We start with the first light which is red and has only the billboard attached.
Scene node which is a dynamic light.
virtual IBillboardSceneNode * addBillboardSceneNode(ISceneNode *parent=0, const core::dimension2d< f32 > &size=core::dimension2d< f32 >(10.0f, 10.0f), const core::vector3df &position=core::vector3df(0, 0, 0), s32 id=-1, video::SColor colorTop=0xFFFFFFFF, video::SColor colorBottom=0xFFFFFFFF)=0
Adds a billboard scene node to the scene graph.
virtual ILightSceneNode * addLightSceneNode(ISceneNode *parent=0, const core::vector3df &position=core::vector3df(0, 0, 0), video::SColorf color=video::SColorf(1.0f, 1.0f, 1.0f), f32 radius=100.0f, s32 id=-1)=0
Adds a dynamic light scene node to the scene graph.
virtual ISceneNodeAnimator * createFlyCircleAnimator(const core::vector3df ¢er=core::vector3df(0.f, 0.f, 0.f), f32 radius=100.f, f32 speed=0.001f, const core::vector3df &direction=core::vector3df(0.f, 1.f, 0.f), f32 startPosition=0.f, f32 radiusEllipsoid=0.f)=0
Creates a fly circle animator, which lets the attached scene node fly around a center.
virtual void setDebugDataVisible(u32 state)
Sets if debug data like bounding boxes should be drawn.
Class representing a color with four floats.
Now the same again, with the second light. The difference is that we add a particle system to it too. And because the light moves, the particles of the particlesystem will follow. If you want to know more about how particle systems are created in Irrlicht, take a look at the specialFx example. Maybe you will have noticed that we only add 2 lights, this has a simple reason: The low end version of this material was written in ps1.1 and vs1.1, which doesn't allow more lights. You could add a third light to the scene, but it won't be used to shade the walls. But of course, this will change in future versions of Irrlicht where higher versions of pixel/vertex shaders will be implemented too.
80,100,
400,1100);
MyEventReceiver receiver(room, earth, env, driver);
virtual void setEventReceiver(IEventReceiver *receiver)=0
Sets a new user event receiver which will receive events from the engine.
A particle affector modifies particles.
A particle emitter for using with particle systems.
virtual void setMinStartSize(const core::dimension2df &size)=0
Set the minimum starting size for particles.
virtual void setMaxStartSize(const core::dimension2df &size)=0
Set the maximum starting size for particles.
A particle system scene node for creating snow, fire, exlosions, smoke...
virtual IParticleFadeOutAffector * createFadeOutParticleAffector(const video::SColor &targetColor=video::SColor(0, 0, 0, 0), u32 timeNeededToFadeOut=1000)=0
Creates a fade out particle affector.
virtual void addAffector(IParticleAffector *affector)=0
Adds new particle effector to the particle system.
virtual IParticleBoxEmitter * createBoxEmitter(const core::aabbox3df &box=core::aabbox3df(-10, 28,-10, 10, 30, 10), const core::vector3df &direction=core::vector3df(0.0f, 0.03f, 0.0f), u32 minParticlesPerSecond=5, u32 maxParticlesPerSecond=10, const video::SColor &minStartColor=video::SColor(255, 0, 0, 0), const video::SColor &maxStartColor=video::SColor(255, 255, 255, 255), u32 lifeTimeMin=2000, u32 lifeTimeMax=4000, s32 maxAngleDegrees=0, const core::dimension2df &minStartSize=core::dimension2df(5.0f, 5.0f), const core::dimension2df &maxStartSize=core::dimension2df(5.0f, 5.0f))=0
Creates a box particle emitter.
virtual void setEmitter(IParticleEmitter *emitter)=0
Sets the particle emitter, which creates the particles.
virtual IParticleSystemSceneNode * addParticleSystemSceneNode(bool withDefaultEmitter=true, ISceneNode *parent=0, s32 id=-1, const core::vector3df &position=core::vector3df(0, 0, 0), const core::vector3df &rotation=core::vector3df(0, 0, 0), const core::vector3df &scale=core::vector3df(1.0f, 1.0f, 1.0f))=0
Adds a particle system scene node to the scene graph.
Finally, draw everything. That's it.
int lastFPS = -1;
{
if (lastFPS != fps)
{
core::stringw str = L
"Per pixel lighting example - Irrlicht Engine [";
str += "] FPS:";
str += fps;
lastFPS = fps;
}
}
return 0;
}
virtual bool run()=0
Runs the device.
virtual void setWindowCaption(const wchar_t *text)=0
Sets the caption of the window.
virtual bool isWindowActive() const =0
Returns if the window is active.
virtual void drawAll()=0
Draws all gui elements by traversing the GUI environment starting at the root node.
virtual void drawAll()=0
Draws all the scene nodes.
virtual bool beginScene(bool backBuffer=true, bool zBuffer=true, SColor color=SColor(255, 0, 0, 0), const SExposedVideoData &videoData=SExposedVideoData(), core::rect< s32 > *sourceRect=0)=0
Applications must call this method before performing any rendering.
virtual s32 getFPS() const =0
Returns current frames per second value.
virtual const wchar_t * getName() const =0
Gets name of this video driver.
virtual bool endScene()=0
Presents the rendered image to the screen.