Demo Code: Sample RenderMonkey Code

Post those lines of code you feel like sharing or find what you require for your project here; or simply use them as tutorials.
dlangdev
Posts: 1324
Joined: Tue Aug 07, 2007 7:28 pm
Location: Beaverton OR
Contact:

Demo Code: Sample RenderMonkey Code

Post by dlangdev »

Choose option 'C' only. Other options will not work, you're on your own.

Ref: http://irrlicht.sourceforge.net/phpBB2/ ... hp?t=30801

Code: Select all

/*
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 dont 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.
*/
#include <irrlicht.h>
#include <iostream>


using namespace irr;

#pragma comment(lib, "Irrlicht.lib")

IrrlichtDevice* device = 0;

bool UseHighLevelShaders = true;
scene::ICameraSceneNode* camera;
scene::ISceneNode* light2;


class MyShaderCallBack : public video::IShaderConstantSetCallBack
{
public:

	virtual void OnSetConstants(video::IMaterialRendererServices* services, s32 userData)
	{
		video::IVideoDriver* driver = services->getVideoDriver();

		// set inverted world matrix
		// if we are using highlevel shaders (the user can select this when
		// starting the program), we must set the constants by name.

		core::matrix4 invWorld = driver->getTransform(video::ETS_WORLD);
		invWorld.makeInverse();

		if (UseHighLevelShaders)
			services->setVertexShaderConstant("mInvWorld", invWorld.pointer(), 16);
		else
			services->setVertexShaderConstant(invWorld.pointer(), 0, 4);

		// set clip matrix

		core::matrix4 worldViewProj;
		worldViewProj = driver->getTransform(video::ETS_PROJECTION);			
		worldViewProj *= driver->getTransform(video::ETS_VIEW);
		worldViewProj *= driver->getTransform(video::ETS_WORLD);

		if (UseHighLevelShaders)
			services->setVertexShaderConstant("mWorldViewProj", worldViewProj.pointer(), 16);
		else
			services->setVertexShaderConstant(worldViewProj.pointer(), 4, 4);		

		core::vector3df posLight2 = light2->getAbsolutePosition();
			services->setVertexShaderConstant("mLight2Pos", reinterpret_cast<f32*>(&posLight2), 3);

		// set camera position

		core::vector3df pos = device->getSceneManager()->
			getActiveCamera()->getAbsolutePosition();

		if (UseHighLevelShaders)
			services->setVertexShaderConstant("mLightPos", reinterpret_cast<f32*>(&pos), 3);
		else
			services->setVertexShaderConstant(reinterpret_cast<f32*>(&pos), 8, 1);

		// set light color 

		video::SColorf col(0.0f,1.0f,1.0f,0.0f);

		if (UseHighLevelShaders)
			services->setVertexShaderConstant("mLightColor", reinterpret_cast<f32*>(&col), 4);
		else
			services->setVertexShaderConstant(reinterpret_cast<f32*>(&col), 9, 1);


		video::SColorf fvAmbient(0.368f,0.368f,0.368f,1.0f);
		services->setVertexShaderConstant("fvAmbient", reinterpret_cast<f32*>(&fvAmbient), 4);

		video::SColorf fvSpecular(0.490f,0.488f,0.488f,1.0f);
		services->setVertexShaderConstant("fvSpecular", reinterpret_cast<f32*>(&fvSpecular), 4);

		video::SColorf fvDiffuse(0.490f,0.488f,0.488f,1.0f);
		services->setVertexShaderConstant("fvDiffuse", reinterpret_cast<f32*>(&fvDiffuse), 4);



		// set transposed world matrix
			
		core::matrix4 world = driver->getTransform(video::ETS_WORLD);
		world = world.getTransposed();

		if (UseHighLevelShaders)
			services->setVertexShaderConstant("mTransWorld", world.pointer(), 16);
		else
			services->setVertexShaderConstant(world.pointer(), 10, 4);
		
		//irr::core::vector3df camPos = camera->getAbsolutePosition();
		//services->setVertexShaderConstant("camPos", reinterpret_cast<f32*>(&camPos), 3);
	}
};


/*
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.
*/
class MyEventReceiver : public IEventReceiver
{
public:

	MyEventReceiver(scene::ISceneNode* room,
		gui::IGUIEnvironment* env, video::IVideoDriver* driver)
	{
		// store pointer to room so we can change its drawing mode
		Room = room;
		Driver = driver;

		// set a nicer font
		gui::IGUISkin* skin = env->getSkin();
		gui::IGUIFont* font = env->getFont("../../media/fonthaettenschweiler.bmp");
		if (font)
			skin->setFont(font);

		// add window and listbox
		gui::IGUIWindow* window = env->addWindow(
			core::rect<s32>(460,375,630,470), false, L"Use 'E' + 'R' to change");

		ListBox = env->addListBox(
			core::rect<s32>(2,22,165,88), window);

		ListBox->addItem(L"Diffuse");
		ListBox->addItem(L"Bump mapping");
		ListBox->addItem(L"Parallax mapping");
		ListBox->setSelected(1);

		// create problem text
		ProblemText = env->addStaticText(
			L"Your hardware or this renderer is not able to use the "\
			L"needed shaders for this material. Using fall back materials.",
			core::rect<s32>(150,20,470,80));

		ProblemText->setOverrideColor(video::SColor(100,255,255,255));

		// set start material (prefer parallax mapping if available)
		video::IMaterialRenderer* renderer =
			Driver->getMaterialRenderer(video::EMT_PARALLAX_MAP_SOLID);
		if (renderer && renderer->getRenderCapability() == 0)
			ListBox->setSelected(2);

		// set the material which is selected in the listbox
		setMaterial();
	}

	bool OnEvent(const SEvent& event)
	{
		// check if user presses the key 'E' or 'R'
		if (event.EventType == irr::EET_KEY_INPUT_EVENT &&
			!event.KeyInput.PressedDown && Room && ListBox)
		{
			// change selected item in listbox

			int sel = ListBox->getSelected();
			if (event.KeyInput.Key == irr::KEY_KEY_R)
				++sel;
			else
			if (event.KeyInput.Key == irr::KEY_KEY_E)
				--sel;
			else
				return false;

			if (sel > 2) sel = 0;
			if (sel < 0) sel = 2;
			ListBox->setSelected(sel);

			// set the material which is selected in the listbox
			setMaterial();
		}

		return false;
	}

private:

	// sets the material of the room mesh the the one set in the
	// list box.
	void setMaterial()
	{
		video::E_MATERIAL_TYPE type = video::EMT_SOLID;

		// change material setting
		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);

		/*
		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 renderered
		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.
		*/
		video::IMaterialRenderer* renderer = Driver->getMaterialRenderer(type);

		// display some problem text when problem
		if (!renderer || renderer->getRenderCapability() != 0)
			ProblemText->setVisible(true);
		else
			ProblemText->setVisible(false);
	}

private:

	gui::IGUIStaticText* ProblemText;
	gui::IGUIListBox* ListBox;

	scene::ISceneNode* Room;
	video::IVideoDriver* Driver;
};


/*
Now for the real fun. We create an Irrlicht Device and start to setup the scene.
*/
int main()
{
	// let user select driver type

	video::E_DRIVER_TYPE driverType = video::EDT_DIRECT3D9;

	printf("Please select the driver you want for this example:\n"\
		" (a) Direct3D 9.0c\n (b) Direct3D 8.1\n (c) OpenGL 1.5\n"\
		" (d) Software Renderer\n (e) Burning's Software Renderer\n"\
		" (f) NullDevice\n (otherKey) exit\n\n");

	char i;
	std::cin >> i;

	switch(i)
	{
		case 'a': driverType = video::EDT_DIRECT3D9;break;
		case 'b': driverType = video::EDT_DIRECT3D8;break;
		case 'c': driverType = video::EDT_OPENGL;   break;
		case 'd': driverType = video::EDT_SOFTWARE; break;
		case 'e': driverType = video::EDT_BURNINGSVIDEO;break;
		case 'f': driverType = video::EDT_NULL;     break;
		default: return 0;
	}

	// create device

	//IrrlichtDevice* 
	device = createDevice(driverType, core::dimension2d<s32>(640, 480));

	if (device == 0)
		return 1; // could not create selected driver.


	/*
	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 now
	that it should store all textures in 32 bit. This necessary because
	for parallax mapping, we need 32 bit textures.
	*/

	video::IVideoDriver* driver = device->getVideoDriver();
	scene::ISceneManager* smgr = device->getSceneManager();
	gui::IGUIEnvironment* env = device->getGUIEnvironment();

	driver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);

	// add irrlicht logo
	env->addImage(driver->getTexture("../../media/irrlichtlogo2.png"),
		core::position2d<s32>(10,10));

	// add camera
	//scene::ICameraSceneNode* camera =
	camera =	smgr->addCameraSceneNodeFPS(0,100.0f,300.0f);
	camera->setPosition(core::vector3df(-200,200,-200));

	// disable mouse cursor
	device->getCursorControl()->setVisible(false);


	/*
	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), true, 250, 1000, 0, true);



	c8* vsFileName = 0; // filename for the vertex shader
	c8* psFileName = 0; // filename for the pixel shader

	switch(driverType)
	{
	case video::EDT_DIRECT3D8:
		psFileName = "../../media/d3d8.psh";
		vsFileName = "../../media/d3d8.vsh";
		break;
	case video::EDT_DIRECT3D9:
		if (UseHighLevelShaders)
		{
			psFileName = "../../media/d3d9.hlsl";
			vsFileName = psFileName; // both shaders are in the same file
		}
		else
		{
			psFileName = "../../media/d3d9.psh";
			vsFileName = "../../media/d3d9.vsh";
		}
		break;

	case video::EDT_OPENGL:
		if (UseHighLevelShaders)
		{
			psFileName = "../../media/rmonkey01.frag";
			vsFileName = "../../media/rmonkey01.vert";
		}
		else
		{
			psFileName = "../../media/opengl.psh";
			vsFileName = "../../media/opengl.vsh";
		}
		break;
	}
	if (!driver->queryFeature(video::EVDF_PIXEL_SHADER_1_1) &&
		!driver->queryFeature(video::EVDF_ARB_FRAGMENT_PROGRAM_1))
	{
		device->getLogger()->log("WARNING: Pixel shaders disabled "\
			"because of missing driver/hardware support.");
		psFileName = 0;
	}
	
	if (!driver->queryFeature(video::EVDF_VERTEX_SHADER_1_1) &&
		!driver->queryFeature(video::EVDF_ARB_VERTEX_PROGRAM_1))
	{
		device->getLogger()->log("WARNING: Vertex shaders disabled "\
			"because of missing driver/hardware support.");
		vsFileName = 0;
	}
	video::IGPUProgrammingServices* gpu = driver->getGPUProgrammingServices();
	s32 newMaterialType1 = 0;
	s32 newMaterialType2 = 0;
	if (gpu)
	{
		MyShaderCallBack* mc = new MyShaderCallBack();

		// create the shaders depending on if the user wanted high level
		// or low level shaders:

		if (UseHighLevelShaders)
		{
			// create material from high level shaders (hlsl or glsl)

			newMaterialType1 = gpu->addHighLevelShaderMaterialFromFiles(
				vsFileName, "vertexMain", video::EVST_VS_1_1,
				psFileName, "pixelMain", video::EPST_PS_1_1,
				mc, video::EMT_SOLID);

			newMaterialType2 = gpu->addHighLevelShaderMaterialFromFiles(
				vsFileName, "vertexMain", video::EVST_VS_1_1,
				psFileName, "pixelMain", video::EPST_PS_1_1,
				mc, video::EMT_TRANSPARENT_ADD_COLOR);
		}
		else
		{
			// create material from low level shaders (asm or arb_asm)

			newMaterialType1 = gpu->addShaderMaterialFromFiles(vsFileName,
				psFileName, mc, video::EMT_SOLID);

			newMaterialType2 = gpu->addShaderMaterialFromFiles(vsFileName,
				psFileName, mc, video::EMT_TRANSPARENT_ADD_COLOR);
		}

		mc->drop();
	}


	/*
	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.
	*/

	scene::IAnimatedMesh* roomMesh = smgr->getMesh(
		"../../media/room.3ds");
	scene::ISceneNode* room = 0;

	if (roomMesh)
	{
		smgr->getMeshManipulator()->makePlanarTextureMapping(
				roomMesh->getMesh(0), 0.003f);

		/*
		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.
		*/

		video::ITexture* colorMap = driver->getTexture("../../media/rockwall.bmp");
		video::ITexture* normalMap = driver->getTexture("../../media/rockwall_height.bmp");

		driver->makeNormalMapTexture(normalMap, 9.0f);

		/*
		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 any other 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.
		*/

		scene::IMesh* tangentMesh = smgr->getMeshManipulator()->createMeshWithTangents(
			roomMesh->getMesh(0));

		room = smgr->addMeshSceneNode(tangentMesh);
		room->setMaterialTexture(0, colorMap);
		room->setMaterialTexture(1, normalMap);

		room->getMaterial(0).SpecularColor.set(0,0,0,0);

		//room->setMaterialFlag(video::EMF_FOG_ENABLE, true);
		//room->setMaterialType(video::EMT_PARALLAX_MAP_SOLID);
		room->setMaterialType((video::E_MATERIAL_TYPE)newMaterialType1);

		room->getMaterial(0).MaterialTypeParam = 0.035f; // adjust height for parallax effect



		// drop mesh because we created it with a create.. call.
		tangentMesh->drop();
	}

	/*
	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.
	*/

	// add earth sphere

	scene::IAnimatedMesh* earthMesh = smgr->getMesh("../../media/earth.x");
	if (earthMesh)
	{
		//perform various task with the mesh manipulator
		scene::IMeshManipulator *manipulator = smgr->getMeshManipulator();

		// create mesh copy with tangent informations from original earth.x mesh
		scene::IMesh* tangentSphereMesh =
			manipulator->createMeshWithTangents(earthMesh->getMesh(0));

		// set the alpha value of all vertices to 200
		manipulator->setVertexColorAlpha(tangentSphereMesh, 200);

		// scale the mesh by factor 50
		core::matrix4 m;
		m.setScale ( core::vector3df(50,50,50) );
		manipulator->transformMesh( tangentSphereMesh, m );

		scene::ISceneNode *sphere = smgr->addMeshSceneNode(tangentSphereMesh);

		sphere->setPosition(core::vector3df(-70,130,45));

		// load heightmap, create normal map from it and set it
		video::ITexture* earthNormalMap = driver->getTexture("../../media/earthbump.bmp");
		driver->makeNormalMapTexture(earthNormalMap, 20.0f);
		sphere->setMaterialTexture(1, earthNormalMap);

		// adjust material settings
		sphere->setMaterialFlag(video::EMF_FOG_ENABLE, true);
		sphere->setMaterialType(video::EMT_NORMAL_MAP_TRANSPARENT_VERTEX_ALPHA);

		// add rotation animator
		scene::ISceneNodeAnimator* anim =
			smgr->createRotationAnimator(core::vector3df(0,0.1f,0));
		sphere->addAnimator(anim);
		anim->drop();

		// drop mesh because we created it with a create.. call.
		tangentSphereMesh->drop();
	}

	/*
	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.
	*/

	// add light 1 (nearly red)
	scene::ILightSceneNode* light1 =
		smgr->addLightSceneNode(0, core::vector3df(0,0,0),
		video::SColorf(0.5f, 1.0f, 0.5f, 0.0f), 800.0f);


	// add fly circle animator to light 1
	scene::ISceneNodeAnimator* anim =
		smgr->createFlyCircleAnimator (core::vector3df(50,300,0),190.0f, -0.003f);
	light1->addAnimator(anim);
	anim->drop();

	// attach billboard to the light
	scene::ISceneNode* bill =
		smgr->addBillboardSceneNode(light1, core::dimension2d<f32>(60, 60));

	bill->setMaterialFlag(video::EMF_LIGHTING, false);
	bill->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
	bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
	bill->setMaterialTexture(0, driver->getTexture("../../media/particlered.bmp"));

	/*
	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 were
	higher versions of pixel/vertex shaders will be implemented too.
	*/

	// add light 2 (gray)
	//scene::ISceneNode* light2 =
	light2 =	smgr->addLightSceneNode(0, core::vector3df(0,0,0),
		video::SColorf(1.0f, 0.2f, 0.2f, 0.0f), 800.0f);

	// add fly circle animator to light 2
	anim = smgr->createFlyCircleAnimator (core::vector3df(0,150,0),200.0f, 0.001f, core::vector3df ( 0.2f, 0.9f, 0.f ));
	light2->addAnimator(anim);
	anim->drop();

	// attach billboard to light
	bill = smgr->addBillboardSceneNode(light2, core::dimension2d<f32>(120, 120));
	bill->setMaterialFlag(video::EMF_LIGHTING, false);
	bill->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
	bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
	bill->setMaterialTexture(0, driver->getTexture("../../media/particlewhite.bmp"));

	// add particle system
	scene::IParticleSystemSceneNode* ps =
		smgr->addParticleSystemSceneNode(false, light2);

	ps->setParticleSize(core::dimension2d<f32>(30.0f, 40.0f));

	// create and set emitter
	scene::IParticleEmitter* em = ps->createBoxEmitter(
		core::aabbox3d<f32>(-3,0,-3,3,1,3),
		core::vector3df(0.0f,0.03f,0.0f),
		80,100,
		video::SColor(0,255,255,255), video::SColor(0,255,255,255),
		400,1100);
	ps->setEmitter(em);
	em->drop();

	// create and set affector
	scene::IParticleAffector* paf = ps->createFadeOutParticleAffector();
	ps->addAffector(paf);
	paf->drop();

	// adjust some material settings
	ps->setMaterialFlag(video::EMF_LIGHTING, false);
	ps->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
	ps->setMaterialTexture(0, driver->getTexture("../../media/fireball.bmp"));
	ps->setMaterialType(video::EMT_TRANSPARENT_VERTEX_ALPHA);


	MyEventReceiver receiver(room, env, driver);
	device->setEventReceiver(&receiver);

	/*
	Finally, draw everything. That's it.
	*/

	int lastFPS = -1;

	while(device->run())
	if (device->isWindowActive())
	{
		driver->beginScene(true, true, 0);

		smgr->drawAll();
		env->drawAll();

		driver->endScene();

		int fps = driver->getFPS();

		if (lastFPS != fps)
		{
			core::stringw str = L"Per pixel lighting example - Irrlicht Engine [";
			str += driver->getName();
			str += "] FPS:";
			str += fps;

			device->setWindowCaption(str.c_str());
			lastFPS = fps;
		}
	}

	device->drop();

	return 0;
}

Last edited by dlangdev on Tue Oct 28, 2008 11:31 pm, edited 2 times in total.
Image
dlangdev
Posts: 1324
Joined: Tue Aug 07, 2007 7:28 pm
Location: Beaverton OR
Contact:

Post by dlangdev »

file: rmonkey01.vert

Code: Select all



uniform mat4 mWorldViewProj;
uniform mat4 mInvWorld;
uniform mat4 mTransWorld;
uniform vec3 mLightPos;
uniform vec4 mLightColor;

uniform vec3 mLight2Pos;

varying vec2 Texcoord;
varying vec3 ViewDirection;
varying vec3 LightDirection;
varying vec3 Normal;

void main(void)
{
	gl_Position = mWorldViewProj * gl_Vertex;
	
	vec4 normal = vec4(gl_Normal, 0.0);
	normal = mInvWorld * normal;
	normal = normalize(normal);
	
	vec4 worldpos = gl_Vertex * mTransWorld;
	
	vec4 lightVector = worldpos - vec4(mLightPos,1.0);
	lightVector = normalize(lightVector);
	
	float tmp2 = dot(-lightVector, normal);
	
	vec4 tmp = mLightColor * tmp2;
	gl_FrontColor = gl_BackColor = vec4(tmp.x, tmp.y, tmp.z, 0.0);
	
	gl_TexCoord[0] = gl_MultiTexCoord0;
	
	vec4 fvObjectPosition = gl_ModelViewMatrix * gl_Vertex;
	
	Texcoord    = gl_MultiTexCoord0.xy;
	ViewDirection  = mLightPos - fvObjectPosition.xyz;
	LightDirection = mLight2Pos - fvObjectPosition.xyz;
	Normal         = gl_NormalMatrix * gl_Normal;
}

Last edited by dlangdev on Wed Oct 29, 2008 4:50 am, edited 2 times in total.
Image
dlangdev
Posts: 1324
Joined: Tue Aug 07, 2007 7:28 pm
Location: Beaverton OR
Contact:

Post by dlangdev »

file: rmonkey01.frag

Code: Select all


uniform vec4 fvAmbient;
uniform vec4 fvSpecular;
uniform vec4 fvDiffuse;
uniform float fSpecularPower;

uniform sampler2D colormap;

varying vec2 Texcoord;
varying vec3 ViewDirection;
varying vec3 LightDirection;
varying vec3 Normal;

void main (void)
{

   fSpecularPower = 1.0;
   
   vec3  fvLightDirection = normalize( LightDirection );
   vec3  fvNormal         = normalize( Normal );
   float fNDotL           = dot( fvNormal, fvLightDirection ); 
   
   vec3  fvReflection     = normalize( ( ( 2.0 * fvNormal ) * fNDotL ) - fvLightDirection ); 
   vec3  fvViewDirection  = normalize( ViewDirection );
   float fRDotV           = max( 0.0, dot( fvReflection, fvViewDirection ) );
   
   vec4  fvBaseColor      = texture2D( colormap, Texcoord );
   
   vec4  fvTotalAmbient   = fvAmbient * fvBaseColor; 
   vec4  fvTotalDiffuse   = fvDiffuse * fNDotL * fvBaseColor; 
   vec4  fvTotalSpecular  = fvSpecular * ( pow( fRDotV, fSpecularPower ) );
  
   gl_FragColor = ( fvTotalAmbient + fvTotalDiffuse + fvTotalSpecular );
}


Last edited by dlangdev on Wed Oct 29, 2008 4:50 am, edited 1 time in total.
Image
dlangdev
Posts: 1324
Joined: Tue Aug 07, 2007 7:28 pm
Location: Beaverton OR
Contact:

Post by dlangdev »

Code: Select all


uniform mat4 mWorldViewProj;
uniform mat4 mInvWorld;
uniform mat4 mTransWorld;
uniform vec3 mLightPos;
uniform vec4 mLightColor;

uniform vec3 mLight2Pos;

varying vec2 Texcoord;
varying vec3 ViewDirection;
varying vec3 LightDirection;
varying vec3 Normal;

varying vec3 rm_Binormal;
varying vec3 rm_Tangent;

void main(void)
{
	gl_Position = mWorldViewProj * gl_Vertex;
	
	vec4 normal = vec4(gl_Normal, 0.0);
	normal = mInvWorld * normal;
	normal = normalize(normal);
	
	vec4 worldpos = gl_Vertex * mTransWorld;
	
	vec4 lightVector = worldpos - vec4(mLightPos,1.0);
	lightVector = normalize(lightVector);
	
	float tmp2 = dot(-lightVector, normal);
	
	vec4 tmp = mLightColor * tmp2;
	gl_FrontColor = gl_BackColor = vec4(tmp.x, tmp.y, tmp.z, 0.0);
	
	
	
	gl_TexCoord[0] = gl_MultiTexCoord0;
	
	vec4 fvObjectPosition = gl_ModelViewMatrix * gl_Vertex;
	
	Texcoord    = gl_MultiTexCoord0.xy;
	ViewDirection  = mLightPos - fvObjectPosition.xyz;
	LightDirection = mLight2Pos - fvObjectPosition.xyz;
	Normal         = gl_NormalMatrix * gl_Normal;

	rm_Tangent = gl_MultiTexCoord1;
	rm_Binormal = gl_MultiTexCoord2; 
	
	vec3 fvNormal         = gl_NormalMatrix * gl_Normal;
	vec3 fvBinormal       = gl_NormalMatrix * rm_Binormal;
	vec3 fvTangent        = gl_NormalMatrix * rm_Tangent;

	vec3 fvViewDirection  = mLightPos - fvObjectPosition.xyz;
	vec3 fvLightDirection = mLight2Pos - fvObjectPosition.xyz;

	ViewDirection.x  = dot( fvTangent, fvViewDirection );
	ViewDirection.y  = dot( fvBinormal, fvViewDirection );
	ViewDirection.z  = dot( fvNormal, fvViewDirection );

	LightDirection.x  = dot( fvTangent, fvLightDirection.xyz );
	LightDirection.y  = dot( fvBinormal, fvLightDirection.xyz );
	LightDirection.z  = dot( fvNormal, fvLightDirection.xyz );
	
	

}
Image
dlangdev
Posts: 1324
Joined: Tue Aug 07, 2007 7:28 pm
Location: Beaverton OR
Contact:

Post by dlangdev »

Code: Select all

uniform vec4 fvAmbient;
uniform vec4 fvSpecular;
uniform vec4 fvDiffuse;
uniform float fSpecularPower;

uniform sampler2D colormap;
uniform sampler2D bumpMap;

varying vec2 Texcoord;
varying vec3 ViewDirection;
varying vec3 LightDirection;
varying vec3 Normal;

void main (void)
{

   fSpecularPower = 10.0;
   
   vec3  fvLightDirection = normalize( LightDirection );
   //vec3  fvNormal         = normalize( Normal );
   vec3  fvNormal         = normalize( ( texture2D( bumpMap, Texcoord ).xyz * 4.0 ) - 1.0 );

   float fNDotL           = dot( fvNormal, fvLightDirection ); 
   
   vec3  fvReflection     = normalize( ( ( 2.0 * fvNormal ) * fNDotL ) - fvLightDirection ); 
   vec3  fvViewDirection  = normalize( ViewDirection );
   float fRDotV           = max( 0.0, dot( fvReflection, fvViewDirection ) );
   
   vec4  fvBaseColor      = texture2D( colormap, Texcoord );
   
   vec4  fvTotalAmbient   = fvAmbient * fvBaseColor; 
   vec4  fvTotalDiffuse   = fvDiffuse * fNDotL * fvBaseColor; 
   vec4  fvTotalSpecular  = fvSpecular * ( pow( fRDotV, fSpecularPower ) );
  
   gl_FragColor = ( fvTotalAmbient*1.0 + fvTotalDiffuse + fvTotalSpecular );
}
Image
JP
Posts: 4526
Joined: Tue Sep 13, 2005 2:56 pm
Location: UK
Contact:

Post by JP »

:lol: why bother giving the user an option of what driver to use if only one works? better idea to hard code it! Just sloppy software design otherwise!

a binary would be nice too ;)
Image Image Image
dlangdev
Posts: 1324
Joined: Tue Aug 07, 2007 7:28 pm
Location: Beaverton OR
Contact:

Post by dlangdev »

Waitasec, more demo code coming...
Image
dlangdev
Posts: 1324
Joined: Tue Aug 07, 2007 7:28 pm
Location: Beaverton OR
Contact:

Post by dlangdev »

The cool thing about this code:

1) Normal map is generated in the shader.
2) Colormap is required. Normalmap is optional.

Code: Select all

/*
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 dont 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.
*/
#include <irrlicht.h>
#include <iostream>


using namespace irr;

#pragma comment(lib, "Irrlicht.lib")

IrrlichtDevice* device = 0;

bool UseHighLevelShaders = true;
scene::ICameraSceneNode* camera;
scene::ISceneNode* light2;


class MyShaderCallBack : public video::IShaderConstantSetCallBack
{
public:

	virtual void OnSetConstants(video::IMaterialRendererServices* services, s32 userData)
	{
		video::IVideoDriver* driver = services->getVideoDriver();

		// set inverted world matrix
		// if we are using highlevel shaders (the user can select this when
		// starting the program), we must set the constants by name.

		core::matrix4 invWorld = driver->getTransform(video::ETS_WORLD);
		invWorld.makeInverse();

		if (UseHighLevelShaders)
			services->setVertexShaderConstant("mInvWorld", invWorld.pointer(), 16);
		else
			services->setVertexShaderConstant(invWorld.pointer(), 0, 4);

		// set clip matrix

		core::matrix4 worldViewProj;
		worldViewProj = driver->getTransform(video::ETS_PROJECTION);			
		worldViewProj *= driver->getTransform(video::ETS_VIEW);
		worldViewProj *= driver->getTransform(video::ETS_WORLD);

		if (UseHighLevelShaders)
			services->setVertexShaderConstant("mWorldViewProj", worldViewProj.pointer(), 16);
		else
			services->setVertexShaderConstant(worldViewProj.pointer(), 4, 4);		

		core::vector3df posLight2 = light2->getAbsolutePosition();
			services->setVertexShaderConstant("mLight2Pos", reinterpret_cast<f32*>(&posLight2), 3);

		// set camera position

		core::vector3df pos = device->getSceneManager()->
			getActiveCamera()->getAbsolutePosition();

		if (UseHighLevelShaders)
			services->setVertexShaderConstant("mLightPos", reinterpret_cast<f32*>(&pos), 3);
		else
			services->setVertexShaderConstant(reinterpret_cast<f32*>(&pos), 8, 1);

		// set light color 

		video::SColorf col(0.0f,1.0f,1.0f,0.0f);

		if (UseHighLevelShaders)
			services->setVertexShaderConstant("mLightColor", reinterpret_cast<f32*>(&col), 4);
		else
			services->setVertexShaderConstant(reinterpret_cast<f32*>(&col), 9, 1);


		video::SColorf fvAmbient(0.368f,0.368f,0.368f,1.0f);
		services->setVertexShaderConstant("fvAmbient", reinterpret_cast<f32*>(&fvAmbient), 4);

		video::SColorf fvSpecular(0.790f,0.488f,0.488f,1.0f);
		services->setVertexShaderConstant("fvSpecular", reinterpret_cast<f32*>(&fvSpecular), 4);

		video::SColorf fvDiffuse(0.886f,0.885f,0.885f,1.0f);
		services->setVertexShaderConstant("fvDiffuse", reinterpret_cast<f32*>(&fvDiffuse), 4);

		f32 fSpecularPower = 50.0f;
		services->setVertexShaderConstant("fSpecularPower", reinterpret_cast<f32*>(&fSpecularPower), 1);

		// set transposed world matrix
			
		core::matrix4 world = driver->getTransform(video::ETS_WORLD);
		world = world.getTransposed();

		if (UseHighLevelShaders)
			services->setVertexShaderConstant("mTransWorld", world.pointer(), 16);
		else
			services->setVertexShaderConstant(world.pointer(), 10, 4);
		
		//irr::core::vector3df camPos = camera->getAbsolutePosition();
		//services->setVertexShaderConstant("camPos", reinterpret_cast<f32*>(&camPos), 3);
	}
};


/*
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.
*/
class MyEventReceiver : public IEventReceiver
{
public:

	MyEventReceiver(scene::ISceneNode* room,
		gui::IGUIEnvironment* env, video::IVideoDriver* driver)
	{
		// store pointer to room so we can change its drawing mode
		Room = room;
		Driver = driver;

		// set a nicer font
		gui::IGUISkin* skin = env->getSkin();
		gui::IGUIFont* font = env->getFont("../../media/fonthaettenschweiler.bmp");
		if (font)
			skin->setFont(font);

		// add window and listbox
		gui::IGUIWindow* window = env->addWindow(
			core::rect<s32>(460,375,630,470), false, L"Use 'E' + 'R' to change");

		ListBox = env->addListBox(
			core::rect<s32>(2,22,165,88), window);

		ListBox->addItem(L"Diffuse");
		ListBox->addItem(L"Bump mapping");
		ListBox->addItem(L"Parallax mapping");
		ListBox->setSelected(1);

		// create problem text
		ProblemText = env->addStaticText(
			L"Your hardware or this renderer is not able to use the "\
			L"needed shaders for this material. Using fall back materials.",
			core::rect<s32>(150,20,470,80));

		ProblemText->setOverrideColor(video::SColor(100,255,255,255));

		// set start material (prefer parallax mapping if available)
		video::IMaterialRenderer* renderer =
			Driver->getMaterialRenderer(video::EMT_PARALLAX_MAP_SOLID);
		if (renderer && renderer->getRenderCapability() == 0)
			ListBox->setSelected(2);

		// set the material which is selected in the listbox
		setMaterial();
	}

	bool OnEvent(const SEvent& event)
	{
		// check if user presses the key 'E' or 'R'
		if (event.EventType == irr::EET_KEY_INPUT_EVENT &&
			!event.KeyInput.PressedDown && Room && ListBox)
		{
			// change selected item in listbox

			int sel = ListBox->getSelected();
			if (event.KeyInput.Key == irr::KEY_KEY_R)
				++sel;
			else
			if (event.KeyInput.Key == irr::KEY_KEY_E)
				--sel;
			else
				return false;

			if (sel > 2) sel = 0;
			if (sel < 0) sel = 2;
			ListBox->setSelected(sel);

			// set the material which is selected in the listbox
			setMaterial();
		}

		return false;
	}

private:

	// sets the material of the room mesh the the one set in the
	// list box.
	void setMaterial()
	{
		video::E_MATERIAL_TYPE type = video::EMT_SOLID;

		// change material setting
		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);

		/*
		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 renderered
		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.
		*/
		video::IMaterialRenderer* renderer = Driver->getMaterialRenderer(type);

		// display some problem text when problem
		if (!renderer || renderer->getRenderCapability() != 0)
			ProblemText->setVisible(true);
		else
			ProblemText->setVisible(false);
	}

private:

	gui::IGUIStaticText* ProblemText;
	gui::IGUIListBox* ListBox;

	scene::ISceneNode* Room;
	video::IVideoDriver* Driver;
};


/*
Now for the real fun. We create an Irrlicht Device and start to setup the scene.
*/
int main()
{
	// let user select driver type

	video::E_DRIVER_TYPE driverType = video::EDT_DIRECT3D9;

	printf("Please select the driver you want for this example:\n"\
		" (a) Direct3D 9.0c\n (b) Direct3D 8.1\n (c) OpenGL 1.5\n"\
		" (d) Software Renderer\n (e) Burning's Software Renderer\n"\
		" (f) NullDevice\n (otherKey) exit\n\n");

	char i;
	//std::cin >> i;

	i = 'c';
	switch(i)
	{
		case 'a': driverType = video::EDT_DIRECT3D9;break;
		case 'b': driverType = video::EDT_DIRECT3D8;break;
		case 'c': driverType = video::EDT_OPENGL;   break;
		case 'd': driverType = video::EDT_SOFTWARE; break;
		case 'e': driverType = video::EDT_BURNINGSVIDEO;break;
		case 'f': driverType = video::EDT_NULL;     break;
		default: return 0;
	}

	// create device

	//IrrlichtDevice* 
	device = createDevice(driverType, core::dimension2d<s32>(1440, 900));

	if (device == 0)
		return 1; // could not create selected driver.


	/*
	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 now
	that it should store all textures in 32 bit. This necessary because
	for parallax mapping, we need 32 bit textures.
	*/

	video::IVideoDriver* driver = device->getVideoDriver();
	scene::ISceneManager* smgr = device->getSceneManager();
	gui::IGUIEnvironment* env = device->getGUIEnvironment();

	driver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);

	// add irrlicht logo
	env->addImage(driver->getTexture("../../media/irrlichtlogo2.png"),
		core::position2d<s32>(10,10));

	// add camera
	//scene::ICameraSceneNode* camera =
	camera =	smgr->addCameraSceneNodeFPS(0,100.0f,300.0f);
	camera->setPosition(core::vector3df(-200,200,-200));

	// disable mouse cursor
	device->getCursorControl()->setVisible(false);


	/*
	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), true, 250, 1000, 0, true);



	c8* vsFileName = 0; // filename for the vertex shader
	c8* psFileName = 0; // filename for the pixel shader

	switch(driverType)
	{
	case video::EDT_DIRECT3D8:
		psFileName = "../../media/d3d8.psh";
		vsFileName = "../../media/d3d8.vsh";
		break;
	case video::EDT_DIRECT3D9:
		if (UseHighLevelShaders)
		{
			psFileName = "../../media/d3d9.hlsl";
			vsFileName = psFileName; // both shaders are in the same file
		}
		else
		{
			psFileName = "../../media/d3d9.psh";
			vsFileName = "../../media/d3d9.vsh";
		}
		break;

	case video::EDT_OPENGL:
		if (UseHighLevelShaders)
		{
			psFileName = "../../media/rmonkey01.frag";
			vsFileName = "../../media/rmonkey01.vert";
		}
		else
		{
			psFileName = "../../media/opengl.psh";
			vsFileName = "../../media/opengl.vsh";
		}
		break;
	}
	if (!driver->queryFeature(video::EVDF_PIXEL_SHADER_1_1) &&
		!driver->queryFeature(video::EVDF_ARB_FRAGMENT_PROGRAM_1))
	{
		device->getLogger()->log("WARNING: Pixel shaders disabled "\
			"because of missing driver/hardware support.");
		psFileName = 0;
	}
	
	if (!driver->queryFeature(video::EVDF_VERTEX_SHADER_1_1) &&
		!driver->queryFeature(video::EVDF_ARB_VERTEX_PROGRAM_1))
	{
		device->getLogger()->log("WARNING: Vertex shaders disabled "\
			"because of missing driver/hardware support.");
		vsFileName = 0;
	}
	video::IGPUProgrammingServices* gpu = driver->getGPUProgrammingServices();
	s32 newMaterialType1 = 0;
	s32 newMaterialType2 = 0;
	if (gpu)
	{
		MyShaderCallBack* mc = new MyShaderCallBack();

		// create the shaders depending on if the user wanted high level
		// or low level shaders:

		if (UseHighLevelShaders)
		{
			// create material from high level shaders (hlsl or glsl)

			newMaterialType1 = gpu->addHighLevelShaderMaterialFromFiles(
				vsFileName, "vertexMain", video::EVST_VS_2_0,
				psFileName, "pixelMain", video::EPST_PS_2_0,
				mc, video::EMT_SOLID);

			newMaterialType2 = gpu->addHighLevelShaderMaterialFromFiles(
				vsFileName, "vertexMain", video::EVST_VS_3_0,
				psFileName, "pixelMain", video::EPST_PS_3_0,
				mc, video::EMT_TRANSPARENT_ADD_COLOR);
		}
		else
		{
			// create material from low level shaders (asm or arb_asm)

			newMaterialType1 = gpu->addShaderMaterialFromFiles(vsFileName,
				psFileName, mc, video::EMT_SOLID);

			newMaterialType2 = gpu->addShaderMaterialFromFiles(vsFileName,
				psFileName, mc, video::EMT_TRANSPARENT_ADD_COLOR);
		}

		mc->drop();
	}


	/*
	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.
	*/

	scene::IAnimatedMesh* roomMesh = smgr->getMesh(
		"../../media/room.3ds");
	scene::ISceneNode* room = 0;

	if (roomMesh)
	{
		smgr->getMeshManipulator()->makePlanarTextureMapping(
				roomMesh->getMesh(0), 0.003f);

		/*
		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.
		*/

		video::ITexture* colorMap = driver->getTexture("../../media/rockwall.bmp");
		video::ITexture* normalMap = driver->getTexture("../../media/rockwall_height.bmp");
		video::ITexture* normalMap2 = driver->getTexture("../../media/rockwall_normalmap.bmp");
		
		driver->makeNormalMapTexture(normalMap, 9.0f);

		/*
		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 any other 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.
		*/

		scene::IMesh* tangentMesh = smgr->getMeshManipulator()->createMeshWithTangents(
			roomMesh->getMesh(0));

		room = smgr->addMeshSceneNode(tangentMesh);
		room->setMaterialTexture(0, colorMap);
		room->setMaterialTexture(1, normalMap);
		room->setMaterialTexture(2, normalMap2);

		//room->getMaterial(0).setTexture(0, colorMap);
		//room->getMaterial(0).setTexture(1, normalMap2);

		room->getMaterial(0).SpecularColor.set(0,0,0,0);

		room->setMaterialFlag(video::EMF_FOG_ENABLE, true);
		//room->setMaterialType(video::EMT_PARALLAX_MAP_SOLID);
		room->setMaterialType((video::E_MATERIAL_TYPE)newMaterialType1);

		room->getMaterial(0).MaterialTypeParam = 0.035f; // adjust height for parallax effect



		// drop mesh because we created it with a create.. call.
		tangentMesh->drop();
	}

	/*
	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.
	*/

	// add earth sphere

	scene::IAnimatedMesh* earthMesh = smgr->getMesh("../../media/earth.x");
	if (earthMesh)
	{
		//perform various task with the mesh manipulator
		scene::IMeshManipulator *manipulator = smgr->getMeshManipulator();

		// create mesh copy with tangent informations from original earth.x mesh
		scene::IMesh* tangentSphereMesh =
			manipulator->createMeshWithTangents(earthMesh->getMesh(0));

		// set the alpha value of all vertices to 200
		manipulator->setVertexColorAlpha(tangentSphereMesh, 200);

		// scale the mesh by factor 50
		core::matrix4 m;
		m.setScale ( core::vector3df(50,50,50) );
		manipulator->transformMesh( tangentSphereMesh, m );

		scene::ISceneNode *sphere = smgr->addMeshSceneNode(tangentSphereMesh);

		sphere->setPosition(core::vector3df(-70,130,45));

		// load heightmap, create normal map from it and set it
		video::ITexture* earthNormalMap = driver->getTexture("../../media/earthbump.bmp");
		driver->makeNormalMapTexture(earthNormalMap, 20.0f);
		sphere->setMaterialTexture(1, earthNormalMap);

		// adjust material settings
		sphere->setMaterialFlag(video::EMF_FOG_ENABLE, true);
		sphere->setMaterialType(video::EMT_NORMAL_MAP_TRANSPARENT_VERTEX_ALPHA);

		// add rotation animator
		scene::ISceneNodeAnimator* anim =
			smgr->createRotationAnimator(core::vector3df(0,0.1f,0));
		sphere->addAnimator(anim);
		anim->drop();

		// drop mesh because we created it with a create.. call.
		tangentSphereMesh->drop();
	}

	/*
	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.
	*/

	// add light 1 (nearly red)
	scene::ILightSceneNode* light1 =
		smgr->addLightSceneNode(0, core::vector3df(0,0,0),
		video::SColorf(0.5f, 1.0f, 0.5f, 0.0f), 800.0f);


	// add fly circle animator to light 1
	scene::ISceneNodeAnimator* anim =
		smgr->createFlyCircleAnimator (core::vector3df(50,300,0),190.0f, -0.003f);
	light1->addAnimator(anim);
	anim->drop();

	// attach billboard to the light
	scene::ISceneNode* bill =
		smgr->addBillboardSceneNode(light1, core::dimension2d<f32>(60, 60));

	bill->setMaterialFlag(video::EMF_LIGHTING, false);
	bill->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
	bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
	bill->setMaterialTexture(0, driver->getTexture("../../media/particlered.bmp"));

	/*
	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 were
	higher versions of pixel/vertex shaders will be implemented too.
	*/

	// add light 2 (gray)
	//scene::ISceneNode* light2 =
	light2 =	smgr->addLightSceneNode(0, core::vector3df(0,0,0),
		video::SColorf(1.0f, 0.2f, 0.2f, 0.0f), 800.0f);

	// add fly circle animator to light 2
	anim = smgr->createFlyCircleAnimator (core::vector3df(0,150,0),200.0f, 0.001f, core::vector3df ( 0.2f, 0.9f, 0.f ));
	light2->addAnimator(anim);
	anim->drop();

	// attach billboard to light
	bill = smgr->addBillboardSceneNode(light2, core::dimension2d<f32>(120, 120));
	bill->setMaterialFlag(video::EMF_LIGHTING, false);
	bill->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
	bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
	bill->setMaterialTexture(0, driver->getTexture("../../media/particlewhite.bmp"));

	// add particle system
	scene::IParticleSystemSceneNode* ps =
		smgr->addParticleSystemSceneNode(false, light2);

	ps->setParticleSize(core::dimension2d<f32>(30.0f, 40.0f));

	// create and set emitter
	scene::IParticleEmitter* em = ps->createBoxEmitter(
		core::aabbox3d<f32>(-3,0,-3,3,1,3),
		core::vector3df(0.0f,0.03f,0.0f),
		80,100,
		video::SColor(0,255,255,255), video::SColor(0,255,255,255),
		400,1100);
	ps->setEmitter(em);
	em->drop();

	// create and set affector
	scene::IParticleAffector* paf = ps->createFadeOutParticleAffector();
	ps->addAffector(paf);
	paf->drop();

	// adjust some material settings
	ps->setMaterialFlag(video::EMF_LIGHTING, false);
	ps->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
	ps->setMaterialTexture(0, driver->getTexture("../../media/fireball.bmp"));
	ps->setMaterialType(video::EMT_TRANSPARENT_VERTEX_ALPHA);


	MyEventReceiver receiver(room, env, driver);
	device->setEventReceiver(&receiver);

	/*
	Finally, draw everything. That's it.
	*/

	int lastFPS = -1;

	while(device->run())
	if (device->isWindowActive())
	{
		driver->beginScene(true, true, 0);

		smgr->drawAll();
		env->drawAll();

		driver->endScene();

		int fps = driver->getFPS();

		if (lastFPS != fps)
		{
			core::stringw str = L"Per pixel lighting example - Irrlicht Engine [";
			str += driver->getName();
			str += "] FPS:";
			str += fps;

			device->setWindowCaption(str.c_str());
			lastFPS = fps;
		}
	}

	device->drop();

	return 0;
}

Code: Select all


uniform mat4 mWorldViewProj; 
uniform mat4 mInvWorld; 
uniform mat4 mTransWorld; 
uniform vec3 mLightPos; 
uniform vec4 mLightColor; 

uniform vec3 mLight2Pos; 

varying vec2 Texcoord; 
varying vec3 ViewDirection; 
varying vec3 LightDirection; 
varying vec3 Normal; 

varying vec3 rm_Binormal; 
varying vec3 rm_Tangent; 

varying vec4 vTexCoords00;
varying vec4 vTexCoords01;
varying vec4 vTexCoords02;
varying vec4 vTexCoords10;
varying vec4 vTexCoords12;
varying vec4 vTexCoords20;
varying vec4 vTexCoords21;
varying vec4 vTexCoords22;

void main(void) 
{ 

	//
	//  Calculate normalmap values here
	//

	float TextureSize;
	TextureSize = 512.0;
   vec4 Pos = mWorldViewProj * gl_Vertex;

   // Clean up inaccuracies
   //Pos.xy = sign(Pos.xy);

   //gl_Position = vec4(Pos.xy, 0, 1);
   // Image-space
   vec4 BaseTexCoord;
   BaseTexCoord.x = 0.5 * (1.0 + Pos.x);
   BaseTexCoord.y = 0.5 * (1.0 - Pos.y);
   BaseTexCoord.zw = vec2(0.0, 1.0);
   
   float vOffset = (1.0 / TextureSize);
   
   vTexCoords00 = BaseTexCoord + vec4(-vOffset, -vOffset, 0.0, 0.0);
   vTexCoords01 = BaseTexCoord + vec4( 0.0,     -vOffset, 0.0, 0.0);
   vTexCoords02 = BaseTexCoord + vec4( vOffset, -vOffset, 0.0, 0.0);

   vTexCoords10 = BaseTexCoord + vec4(-vOffset,  0.0, 0.0, 0.0);
   vTexCoords12 = BaseTexCoord + vec4( vOffset,  0.0, 0.0, 0.0);
   
   vTexCoords20 = BaseTexCoord + vec4(-vOffset,  vOffset, 0.0, 0.0);
   vTexCoords21 = BaseTexCoord + vec4( 0.0,      vOffset, 0.0, 0.0);
   vTexCoords22 = BaseTexCoord + vec4( vOffset,  vOffset, 0.0, 0.0);   


	//
	//  More code
	//



   gl_Position = mWorldViewProj * gl_Vertex; 
    //gl_Position = ftransform();
    
   vec4 fvObjectPosition = gl_ModelViewMatrix * gl_Vertex; 
    
   Texcoord    = gl_MultiTexCoord0.xy; 
   ViewDirection  = mLightPos - fvObjectPosition.xyz; 
   LightDirection = mLight2Pos - fvObjectPosition.xyz; 
   Normal         = gl_NormalMatrix * gl_Normal; 
 
   rm_Tangent = gl_MultiTexCoord1.xyz; 
   rm_Binormal = gl_MultiTexCoord2.xyz;    
   
   vec3 fvNormal         = gl_NormalMatrix * gl_Normal; 
   vec3 fvBinormal       = gl_NormalMatrix * rm_Binormal; 
   vec3 fvTangent        = gl_NormalMatrix * rm_Tangent;    

   vec3 fvViewDirection  = mLightPos - fvObjectPosition.xyz; 
   vec3 fvLightDirection = mLight2Pos - fvObjectPosition.xyz; 

   ViewDirection.x  = dot( fvTangent, fvViewDirection ); 
   ViewDirection.y  = dot( fvBinormal, fvViewDirection ); 
   ViewDirection.z  = dot( fvNormal, fvViewDirection ); 

   LightDirection.x  = dot( fvTangent, fvLightDirection.xyz ); 
   LightDirection.y  = dot( fvBinormal, fvLightDirection.xyz ); 
   LightDirection.z  = dot( fvNormal, fvLightDirection.xyz );    
   
   
   
   
} 

Code: Select all

uniform vec4 fvAmbient; 
uniform vec4 fvSpecular; 
uniform vec4 fvDiffuse; 
uniform float fSpecularPower; 

uniform sampler2D colormap; 
uniform sampler2D bumpMap; 

varying vec2 Texcoord; 
varying vec3 ViewDirection; 
varying vec3 LightDirection; 
varying vec3 Normal; 


varying vec4 vTexCoords00;
varying vec4 vTexCoords01;
varying vec4 vTexCoords02;
varying vec4 vTexCoords10;
varying vec4 vTexCoords12;
varying vec4 vTexCoords20;
varying vec4 vTexCoords21;
varying vec4 vTexCoords22;

void main (void)
{
	//
	//  Calculate normalmap values here
	//

	vec4 lightness;
	lightness = vec4(0.3, 0.59, 0.11, 0.0);
	
   vec4 s00;
   vec4 s01;
   vec4 s02;

   vec4 s10;
   vec4 s12;
   
   vec4 s20;
   vec4 s21;
   vec4 s22;
  
   s00 = texture2DProj(colormap, vTexCoords00);
   s01 = texture2DProj(colormap, vTexCoords01);
   s02 = texture2DProj(colormap, vTexCoords02);

   s10 = texture2DProj(colormap, vTexCoords10);
   s12 = texture2DProj(colormap, vTexCoords12);
   
   s20 = texture2DProj(colormap, vTexCoords20);
   s21 = texture2DProj(colormap, vTexCoords21);
   s22 = texture2DProj(colormap, vTexCoords22);

   // Slope in X direction
   vec4 sobelX = s00 + 2.0 * s10 + s20 - s02 - 2.0 * s12 - s22;
   // Slope in Y direction
   vec4 sobelY = s00 + 2.0 * s01 + s02 - s20 - 2.0 * s21 - s22;
   
   // Weight the slope in all channels, we use grayscale as height
   float sx = dot(sobelX.xyz, lightness.xyz);
   float sy = dot(sobelY.xyz, lightness.xyz);
   
   // Compose the normal
   vec3 normal = normalize(vec3(sx, sy, 1.0));
   
   // Pack [-1, 1] into [0, 1]
   vec4 normalMapPixel;
   normalMapPixel = vec4(normal * 0.5 + 0.5, 1.0);
   
   //
   //  Etc
   //	
	

   vec3  fvLightDirection = normalize( LightDirection ); 
   vec3  fvNormal         = normalize( ( normalMapPixel.xyz * 4.0 ) - 1.0 );
   
   float fNDotL           = dot( fvNormal, fvLightDirection ); 
    
   vec3  fvReflection     = normalize( ( ( 2.0 * fvNormal ) * fNDotL ) - fvLightDirection ); 
   vec3  fvViewDirection  = normalize( ViewDirection ); 
   float fRDotV           = max( 0.0, dot( fvReflection, fvViewDirection ) ); 
    
   vec4  fvBaseColor      = texture2D( colormap, Texcoord ); 
    
   vec4  fvTotalAmbient   = fvAmbient * fvBaseColor; 
   vec4  fvTotalDiffuse   = fvDiffuse * fNDotL * fvBaseColor; 
   vec4  fvTotalSpecular  = fvSpecular * ( pow( fRDotV, fSpecularPower ) ); 
  
   gl_FragColor = ( fvTotalAmbient + fvTotalDiffuse + fvTotalSpecular );    
   //gl_FragColor =  fvTotalDiffuse + fvTotalSpecular;  
   //gl_FragColor = texture2D( colormap, Texcoord ); 

}
Image
dlangdev
Posts: 1324
Joined: Tue Aug 07, 2007 7:28 pm
Location: Beaverton OR
Contact:

Post by dlangdev »

Image
Image
dlangdev
Posts: 1324
Joined: Tue Aug 07, 2007 7:28 pm
Location: Beaverton OR
Contact:

Post by dlangdev »

Image
Image
dlangdev
Posts: 1324
Joined: Tue Aug 07, 2007 7:28 pm
Location: Beaverton OR
Contact:

Post by dlangdev »

Image
Image
dlangdev
Posts: 1324
Joined: Tue Aug 07, 2007 7:28 pm
Location: Beaverton OR
Contact:

Post by dlangdev »

Image
Image
Halifax
Posts: 1424
Joined: Sun Apr 29, 2007 10:40 pm
Location: $9D95

Post by Halifax »

JP wrote:a binary would be nice too ;)
Eh, it seems as though dlangdev is out of that phase these days. :lol: He has adopted a more minimalistic release style.

But at any rate, is it just me, or am I the only one not seeing any normal/parallax mapping occuring? All I see is the specular.
TheQuestion = 2B || !2B
dlangdev
Posts: 1324
Joined: Tue Aug 07, 2007 7:28 pm
Location: Beaverton OR
Contact:

Post by dlangdev »

I borrowed the code and mashed it with the other code. The result is a simple demo showing a bumpmap shader taken from RenderMonkey.

The next one will be about Parallax Occlusion Mapping, taken from RenderMonkey code. The code is written in HLSL so I will have to switch to DX9 for this demo to work.

Sorry for disappointing you guys. It's just the way it is as I'm saving my effort for later demos.
Image
dlangdev
Posts: 1324
Joined: Tue Aug 07, 2007 7:28 pm
Location: Beaverton OR
Contact:

Post by dlangdev »

Turns out someone wrote a GLSL Parallax Occlusion Mapping program and it is published here...

http://3d.benjamin-thaut.de/?p=3

Anyway...
Image
Post Reply