Пример #1
0
bool CMainMenu::run(bool& outFullscreen, bool& outMusic, bool& outShadows,
			bool& outAdditive, bool& outVSync, bool& outAA,
			video::E_DRIVER_TYPE& outDriver)
{
	//video::E_DRIVER_TYPE driverType = video::EDT_DIRECT3D9;
	video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
	//video::E_DRIVER_TYPE driverType = video::EDT_BURNINGSVIDEO;
	//video::E_DRIVER_TYPE driverType = video::EDT_SOFTWARE;

	MenuDevice = createDevice(driverType,
		core::dimension2d<u32>(512, 384), 16, false, false, false, this);

	if (MenuDevice->getFileSystem()->existFile("irrlicht.dat"))
		MenuDevice->getFileSystem()->addFileArchive("irrlicht.dat");
	else
		MenuDevice->getFileSystem()->addFileArchive("../../media/irrlicht.dat");

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

	core::stringw str = "Irrlicht Engine Demo v";
	str += MenuDevice->getVersion();
	MenuDevice->setWindowCaption(str.c_str());

	// set new Skin
	gui::IGUISkin* newskin = guienv->createSkin(gui::EGST_BURNING_SKIN);
	guienv->setSkin(newskin);
	newskin->drop();

	// load font
	gui::IGUIFont* font = guienv->getFont("../../media/fonthaettenschweiler.bmp");
	if (font)
		guienv->getSkin()->setFont(font);

	// add images

	const s32 leftX = 260;

	// add tab control
	gui::IGUITabControl* tabctrl = guienv->addTabControl(core::rect<int>(leftX,10,512-10,384-10),
		0, true, true);
	gui::IGUITab* optTab = tabctrl->addTab(L"Demo");
	gui::IGUITab* aboutTab = tabctrl->addTab(L"About");

	// add list box

	gui::IGUIListBox* box = guienv->addListBox(core::rect<int>(10,10,220,120), optTab, 1);
	box->addItem(L"OpenGL 1.5");
	box->addItem(L"Direct3D 8.1");
	box->addItem(L"Direct3D 9.0c");
	box->addItem(L"Burning's Video 0.47");
	box->addItem(L"Irrlicht Software Renderer 1.0");
	box->setSelected(selected);

	// add button

	startButton = guienv->addButton(core::rect<int>(30,295,200,324), optTab, 2, L"Start Demo");

	// add checkbox

	const s32 d = 50;

	guienv->addCheckBox(fullscreen, core::rect<int>(20,85+d,130,110+d),
		optTab, 3, L"Fullscreen");
	guienv->addCheckBox(music, core::rect<int>(135,85+d,245,110+d),
		optTab, 4, L"Music & Sfx");
	guienv->addCheckBox(shadows, core::rect<int>(20,110+d,135,135+d),
		optTab, 5, L"Realtime shadows");
	guienv->addCheckBox(additive, core::rect<int>(20,135+d,230,160+d),
		optTab, 6, L"Old HW compatible blending");
	guienv->addCheckBox(vsync, core::rect<int>(20,160+d,230,185+d),
		optTab, 7, L"Vertical synchronisation");
	guienv->addCheckBox(aa, core::rect<int>(20,185+d,230,210+d),
		optTab, 8, L"Antialiasing");

	// add about text

	const wchar_t* text2 = L"This is the tech demo of the Irrlicht engine. To start, "\
		L"select a video driver which works best with your hardware and press 'Start Demo'.\n"\
		L"What you currently see is displayed using the Burning Software Renderer (Thomas Alten).\n"\
		L"The Irrlicht Engine was written by me, Nikolaus Gebhardt. The models, "\
		L"maps and textures were placed at my disposal by B.Collins, M.Cook and J.Marton. The music was created by "\
		L"M.Rohde and is played back by irrKlang.\n"\
		L"For more informations, please visit the homepage of the Irrlicht engine:\nhttp://irrlicht.sourceforge.net";

	guienv->addStaticText(text2, core::rect<int>(10, 10, 230, 320),
		true, true, aboutTab);

	// add md2 model

	scene::IAnimatedMesh* mesh = smgr->getMesh("../../media/faerie.md2");
	scene::IAnimatedMeshSceneNode* modelNode = smgr->addAnimatedMeshSceneNode(mesh);
	if (modelNode)
	{
		modelNode->setPosition( core::vector3df(0.f, 0.f, -5.f) );
		modelNode->setMaterialTexture(0, driver->getTexture("../../media/faerie2.bmp"));
		modelNode->setMaterialFlag(video::EMF_LIGHTING, true);
		modelNode->getMaterial(0).Shininess = 50.f;
		modelNode->getMaterial(0).NormalizeNormals = true;
		modelNode->setMD2Animation(scene::EMAT_STAND);
	}

	// set ambient light (no sun light in the catacombs)
	smgr->setAmbientLight( video::SColorf(0.2f, 0.2f, 0.2f) );

	scene::ILightSceneNode *light;
	scene::ISceneNodeAnimator* anim;
	scene::ISceneNode* bill;

	enum eLightParticle
	{
		LIGHT_NONE,
		LIGHT_GLOBAL,
		LIGHT_RED,
		LIGHT_BLUE
	};
	core::vector3df lightDir[2] = {
		core::vector3df(0.f, 0.1f, 0.4f),
		core::vector3df(0.f, 0.1f, -0.4f),
	};

	struct SLightParticle
	{
		eLightParticle type;
		u32 dir;
	};
	const SLightParticle lightParticle[] =
	{
		//LIGHT_GLOBAL,0,
		{LIGHT_RED,0},
		{LIGHT_BLUE,0},
		{LIGHT_RED,1},
		{LIGHT_BLUE,1},
		{LIGHT_NONE,0}
	};

	const SLightParticle *l = lightParticle;
	while ( l->type != LIGHT_NONE )
	{
		switch ( l->type )
		{
			case LIGHT_GLOBAL:
				// add illumination from the background
				light = smgr->addLightSceneNode(0, core::vector3df(10.f,40.f,-5.f),
					video::SColorf(0.2f, 0.2f, 0.2f), 90.f);
				break;
			case LIGHT_RED:
				// add light nearly red
				light = smgr->addLightSceneNode(0, core::vector3df(0,1,0),
					video::SColorf(0.8f, 0.f, 0.f, 0.0f), 30.0f);
				// attach red billboard to the light
				bill = smgr->addBillboardSceneNode(light, core::dimension2d<f32>(10, 10));
				if ( bill )
				{
					bill->setMaterialFlag(video::EMF_LIGHTING, false);
					bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
					bill->setMaterialTexture(0, driver->getTexture("../../media/particlered.bmp"));
				}
				// add fly circle animator to the light
				anim = smgr->createFlyCircleAnimator(core::vector3df(0.f,0.f,-5.f),20.f,
					0.002f, lightDir [l->dir] );
				light->addAnimator(anim);
				anim->drop();
				break;
			case LIGHT_BLUE:
				// add light nearly blue
				light = smgr->addLightSceneNode(0, core::vector3df(0,1,0),
					video::SColorf(0.f, 0.0f, 0.8f, 0.0f), 30.0f);
				// attach blue billboard to the light
				bill = smgr->addBillboardSceneNode(light, core::dimension2d<f32>(10, 10));
				if (bill)
				{
					bill->setMaterialFlag(video::EMF_LIGHTING, false);
					bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
					bill->setMaterialTexture(0, driver->getTexture("../../media/portal1.bmp"));
				}
				// add fly circle animator to the light
				anim = smgr->createFlyCircleAnimator(core::vector3df(0.f,0.f,-5.f),20.f,
					-0.002f, lightDir [l->dir], 0.5f);
				light->addAnimator(anim);
				anim->drop();
				break;
			case LIGHT_NONE:
				break;
		}
		l += 1;
	}

	// create a fixed camera
	smgr->addCameraSceneNode(0, core::vector3df(45,0,0), core::vector3df(0,0,10));


	// irrlicht logo and background
	// add irrlicht logo
	bool oldMipMapState = driver->getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS);
	driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);

	guienv->addImage(driver->getTexture("../../media/irrlichtlogo3.png"),
		core::position2d<s32>(5,5));

	video::ITexture* irrlichtBack = driver->getTexture("../../media/demoback.jpg");

	driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, oldMipMapState);

	// query original skin color
	getOriginalSkinColor();

	// set transparency
	setTransparency();

	// draw all

	while(MenuDevice->run())
	{
		if (MenuDevice->isWindowActive())
		{
			driver->beginScene(false, true, video::SColor(0,0,0,0));

			if (irrlichtBack)
				driver->draw2DImage(irrlichtBack,
						core::position2d<int>(0,0));

			smgr->drawAll();
			guienv->drawAll();
			driver->endScene();
		}
	}

	MenuDevice->drop();

	outFullscreen = fullscreen;
	outMusic = music;
	outShadows = shadows;
	outAdditive = additive;
	outVSync = vsync;
	outAA = aa;

	switch(selected)
	{
	case 0:	outDriver = video::EDT_OPENGL; break;
	case 1:	outDriver = video::EDT_DIRECT3D8; break;
	case 2:	outDriver = video::EDT_DIRECT3D9; break;
	case 3:	outDriver = video::EDT_BURNINGSVIDEO; break;
	case 4:	outDriver = video::EDT_SOFTWARE; break;
	}

	return start;
}
Пример #2
0
int main()
{
	Input input;
	IrrlichtDevice *device = createDevice(video::EDT_DIRECT3D9, dimension2d<u32>(800, 600), 16, false, true, false, &input);
	device->setWindowCaption(L"Seas of Gold");
	IVideoDriver* driver = device->getVideoDriver();
	ISceneManager* smgr = device->getSceneManager();
	IGUIEnvironment* guienv = device->getGUIEnvironment();
	E_DRIVER_TYPE driverType = driverChoiceConsole();
	EffectHandler *effect = new EffectHandler(device, driver->getScreenSize(), false, true);
	E_FILTER_TYPE filterType = (E_FILTER_TYPE)core::clamp<u32>((u32)3 - '1', 0, 4);

	int skyR = 30, skyG = 30, skyB = 70;
	int timer = 0;
	SColor sky = SColor(255, skyR, skyG, skyB);
	float plPos_x = 0.0f, plPos_y = 0.0f, plPos_z = 0.0f;
	bool updateCam = true;
	bool menu1 = false;
	int state = Main;
	LoadMap loadMap;
	Player player;
	Interface playerInterface(driver);
	ITriangleSelector* selector = 0;
	ISceneNodeAnimator* anim = 0;

	// Load the map scene
	//loadMap.Load(smgr, device, Map_Africa);
	//loadMap.Load(smgr, device, Map_India);
	//loadMap.Load(smgr, device, selector, plyrNode, anim, Map_England);

	IAnimatedMeshSceneNode* plyrNode = player.loadPlayerNode(device, smgr);
	//plyrNode->setDebugDataVisible((scene::E_DEBUG_SCENE_TYPE)(plyrNode->isDebugDataVisible() ^ scene::EDS_BBOX));

	ICameraSceneNode* camera = smgr->addCameraSceneNode(0, plyrNode->getPosition() + vector3df(0, 2, 2), vector3df(0, 0, 100));

	loadMap.Load(smgr, device, selector, plyrNode, anim, Map_England);

	//loadMap.setCollisions(smgr, selector, plyrNode, anim);

	if (loadMap.CollNode)
	{
		selector = smgr->createOctreeTriangleSelector(loadMap.CollNode->getMesh(), loadMap.CollNode, 32);
		for (int i = 0; i < loadMap.CollNode->getMaterialCount(); i++)
		{
			loadMap.CollNode->getMaterial(i).NormalizeNormals = true;
		}
		loadMap.CollNode->setTriangleSelector(selector);
	}

	if (selector)
	{
		anim = smgr->createCollisionResponseAnimator(selector, plyrNode, vector3df(0.6f, 0.75f, 0.4f), core::vector3df(0.0f, -0.05f, 0.0f),
			core::vector3df(0.0f, -0.725f, 0.0f));
		plyrNode->addAnimator(anim);
	}

	ISceneCollisionManager* collMan = smgr->getSceneCollisionManager();

	////////////// The Sun ////////////
	ILightSceneNode *sun_node;
	SLight sun_data;
	ISceneNode *sun_billboard;
	float sun_angle = 0;
	video::SColorf Diffuse_Night = video::SColorf(0.0f, 0.0f, 0.0f, 1.0f);
	video::SColorf Diffuse_Day = video::SColorf(1.0f, 1.0f, 1.0f, 1.0f);

	sun_node = smgr->addLightSceneNode();
	sun_data.Direction = vector3df(0, 0, 0);
	sun_data.Type = video::ELT_DIRECTIONAL;
	sun_data.AmbientColor = video::SColorf(0.1f, 0.1f, 0.1f, 1);
	sun_data.SpecularColor = video::SColorf(0, 0, 0, 0);
	sun_data.DiffuseColor = Diffuse_Day;
	sun_data.CastShadows = true;
	sun_node->setLightData(sun_data);
	sun_node->setPosition(vector3df(0, 0, 0));
	sun_node->setRotation(vector3df(0, 0, 0));

	sun_billboard = smgr->addBillboardSceneNode(sun_node, core::dimension2d<f32>(60, 60));
	if (sun_billboard)
	{
		sun_billboard->setPosition(vector3df(0, 0, -100));
		sun_billboard->setMaterialFlag(video::EMF_LIGHTING, false);
		sun_billboard->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
		sun_billboard->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
		sun_billboard->setMaterialTexture(0, driver->getTexture("Assets/particlewhite.bmp"));
	}
	/////////// End ////////////

	//------- candleLight -----//
	ILightSceneNode *candleLight = smgr->addLightSceneNode();
	SLight candleLight_data;

	candleLight_data.Type = video::ELT_POINT;
	candleLight_data.DiffuseColor = SColorf(1.0f, 0.546f, 0.016f, 1.0f);
	candleLight_data.SpecularColor = video::SColorf(0, 0, 0, 0);
	candleLight->setPosition(vector3df(2.43467f, 1.55795f, -3.94657));
	candleLight_data.Radius = 1.5f;
	candleLight->setLightData(candleLight_data);
	//------- end -----//

	// Make the player
	player.AddGold(1000);
	player.SetCurrentPort(eMapDest::South);
	Item* itemCi = new Item("Iron Ore", 1);
	player.getItems()->addItem(itemCi);
	Item* itemCb = new Item("Bronze Ore", 1);
	player.getItems()->addItem(itemCb);

	Vendor vN;
	Item* itemG = new Item("Gold Ore", 1000);
	vN.getItems()->addItem(itemG);
	Vendor vS;
	Item* itemI = new Item("Iron Ore", 1000);
	vS.getItems()->addItem(itemI);
	Vendor vE;
	Item* itemB = new Item("Bronze Ore", 1000);
	vE.getItems()->addItem(itemB);

	// Make the menus
	MainMenu mainMenu(device);

	MapMenu mapMenu(device, driver);
	mapMenu.SetPlayer(&player);

	TradeMenu tradeMenu(device, driver);
	tradeMenu.SetPlayer(&player);
	tradeMenu.SetVendor(&vS);

	CraftingMenu craftMenu(device, driver);
	craftMenu.SetPlayer(&player);

	//////////////////////////////////////////////////////////////////////////
	// Initialize timer to compute elapsed time between frames
	//////////////////////////////////////////////////////////////////////////
	__int64 cntsPerSec = 0;
	QueryPerformanceFrequency((LARGE_INTEGER*)&cntsPerSec);
	float secsPerCnt = 1.0f / (float)cntsPerSec;

	__int64 prevTimeStamp = 0;
	QueryPerformanceCounter((LARGE_INTEGER*)&prevTimeStamp);

	while (device->run())
	{
		//for scaling animation by time, not by frame
		__int64 currTimeStamp = 0;
		QueryPerformanceCounter((LARGE_INTEGER*)&currTimeStamp);
		float dt = (currTimeStamp - prevTimeStamp) * secsPerCnt;

		sun_node->setRotation(vector3df(sun_angle, 0.0f, 0.0f));
		sun_angle += dt;
		if ((sun_angle > 0 && sun_angle < 109) || (sun_angle>350))
		{
			timer++;
			if (timer > 10)
			{
				if (skyR < 100) skyR += 1;
				if (skyG < 100) skyG += 1;
				if (skyB < 140) skyB += 1;
				timer = 0;
			}
		}
		if (sun_angle > 170 && sun_angle < 330)
		{
			timer++;
			if (timer > 10)
			{
				if (skyR > 0) skyR -= 1;
				if (skyG > 0) skyG -= 1;
				if (skyB > 40) skyB -= 1;
				timer = 0;
			}
		}

		player.updatePlayer(plyrNode, dt, collMan, selector);
		playerInterface.update(plyrNode, loadMap, driver, device, input, updateCam, state);

		int test = state;
		int test2 = 0;

		switch (state)
		{
		case Map:
		{
			int out = mapMenu.Update(&input);

			switch (out)
			{
			case eMapDest::Exit:
			{
				state = None;
				break;
			}
			case eMapDest::East:
			{
				state = None;
				Item* itemB = new Item("Bronze Ore", 1000);
				vE.getItems()->addItem(itemB);
				tradeMenu.SetVendor(&vE);
				loadMap.Load(smgr, device, selector, plyrNode, anim, Map_India);
				if (loadMap.CollNode)
				{
					selector = smgr->createOctreeTriangleSelector(loadMap.CollNode->getMesh(), loadMap.CollNode, 32);

					for (int i = 0; i < loadMap.CollNode->getMaterialCount(); i++)
					{
						loadMap.CollNode->getMaterial(i).NormalizeNormals = true;
					}
					loadMap.CollNode->setTriangleSelector(selector);
				}

				if (selector)
				{
					anim = smgr->createCollisionResponseAnimator(selector, plyrNode, vector3df(0.6f, 0.75f, 0.4f), core::vector3df(0.0f, -0.05f, 0.0f),
						core::vector3df(0.0f, -0.725f, 0.0f));
					plyrNode->addAnimator(anim);
				}
				collMan = smgr->getSceneCollisionManager();
				break;
			}
			case eMapDest::North:
			{
				state = None;
				Item *itemG = new Item("Gold Ore", 1000);
				vN.getItems()->addItem(itemG);
				tradeMenu.SetVendor(&vN);
				loadMap.Load(smgr, device, selector, plyrNode, anim, Map_England);
				if (loadMap.CollNode)
				{
					selector = smgr->createOctreeTriangleSelector(loadMap.CollNode->getMesh(), loadMap.CollNode, 32);

					for (int i = 0; i < loadMap.CollNode->getMaterialCount(); i++)
					{
						loadMap.CollNode->getMaterial(i).NormalizeNormals = true;
					}
					loadMap.CollNode->setTriangleSelector(selector);
				}

				if (selector)
				{
					anim = smgr->createCollisionResponseAnimator(selector, plyrNode, vector3df(0.6f, 0.75f, 0.4f), core::vector3df(0.0f, -0.05f, 0.0f),
						core::vector3df(0.0f, -0.725f, 0.0f));
					plyrNode->addAnimator(anim);
				}
				collMan = smgr->getSceneCollisionManager();
				break;
			}
			case eMapDest::South:
			{
				state = None;
				Item *itemI = new Item("Iron Ore", 1000);
				vS.getItems()->addItem(itemI);
				tradeMenu.SetVendor(&vS);
				loadMap.Load(smgr, device, selector, plyrNode, anim, Map_Africa);
				if (loadMap.CollNode)
				{
					selector = smgr->createOctreeTriangleSelector(loadMap.CollNode->getMesh(), loadMap.CollNode, 32);

					for (int i = 0; i < loadMap.CollNode->getMaterialCount(); i++)
					{
						loadMap.CollNode->getMaterial(i).NormalizeNormals = true;
					}
					loadMap.CollNode->setTriangleSelector(selector);
				}

				if (selector)
				{
					anim = smgr->createCollisionResponseAnimator(selector, plyrNode, vector3df(0.6f, 0.75f, 0.4f), core::vector3df(0.0f, -0.05f, 0.0f),
						core::vector3df(0.0f, -0.725f, 0.0f));
					plyrNode->addAnimator(anim);
				}
				collMan = smgr->getSceneCollisionManager();
				break;
			}
			default:
				break;
			}

			break;
		}
		case Trade:
		{
			bool out = tradeMenu.Update(&input);
			if (out)
				state = None;
			break;
		}
		case Main:
		{
			int out = mainMenu.Update(&input);

			switch (out)
			{
			case MSstart:
			{
				state = None;
				break;
			}
			case MSexit:
			{
				device->closeDevice();
				break;
			}
			default:
				break;
			}

			break;
		}
		case Craft:
		{
			bool out = craftMenu.Update(&input);
			if (out)
				state = None;
			break;
		}
		default:
			// Do nothing
			break;
		}

		if (updateCam) moveCameraControl(plyrNode, device, camera);

		////////////////////////////////////////////////////////

		if (sun_angle > 360) sun_angle = 0;
		if (sun_angle < 180) sun_data.DiffuseColor = Diffuse_Day; else sun_data.DiffuseColor = Diffuse_Night;
		sun_node->setLightData(sun_data);

		sky.setRed(skyR);
		sky.setGreen(skyG);
		sky.setBlue(skyB);
		driver->beginScene(true, true, sky);

		smgr->drawAll();

		playerInterface.render(driver, state);

		// Draw the menu
		switch (state)
		{
		case Map:
		{
			mapMenu.Draw(driver);
			break;
		}
		case Trade:
		{
			tradeMenu.Draw(driver);
			break;
		}
		case Main:
		{
			mainMenu.Draw(driver);
			break;
		}
		case Craft:
		{
			craftMenu.Draw(driver);
			break;
		}
		default:
			// Do nothing
			break;
		}

		driver->endScene();
		
		// Update the prev time stamp to current
		prevTimeStamp = currTimeStamp;

	}

	//device->drop();

	return 0;
}
Пример #3
0
Renderer::Renderer(Window& window) {
	createDevice(window);
	createRenderTarget();
}
Пример #4
0
int main(int argc, char* argv[]){
    // Check fullscreen
    for (int i=1;i<argc;i++) fullscreen |= !strcmp("-f", argv[i]);

    MyEventReceiver receiver;
    std::shared_ptr<irr::IrrlichtDevice> device(
            createDevice(irr::video::EDT_OPENGL, 
                irr::core::dimension2d<irr::u32>(SCREEN_WIDTH, SCREEN_HEIGHT), 
                16, fullscreen, false, vsync, &receiver),
            [](irr::IrrlichtDevice *p){ p->drop(); }
            );
    receiver.device = device.get();
	auto cursor=device->getCursorControl();
    receiver.cursor = cursor;

    irr::video::IVideoDriver* driver = device->getVideoDriver();
    irr::scene::ISceneManager* smgr = device->getSceneManager();
    irr::gui::IGUIEnvironment* guienv = device->getGUIEnvironment();
    irr::video::IGPUProgrammingServices* gpu = driver->getGPUProgrammingServices();

    HMDDescriptor HMD;
    // Parameters from the Oculus Rift DK1
    HMD.hResolution = 1280;
    HMD.vResolution = 800;
    HMD.hScreenSize = 0.14976;
    HMD.vScreenSize = 0.0936;
    HMD.interpupillaryDistance = 0.064;
    HMD.lensSeparationDistance = 0.064;
    HMD.eyeToScreenDistance = 0.041;
    HMD.distortionK[0] = 1.0;
    HMD.distortionK[1] = 0.22;
    HMD.distortionK[2] = 0.24;
    HMD.distortionK[3] = 0.0;

    HMDStereoRender renderer(device.get(), HMD, 10);

    // load the quake map
    device->getFileSystem()->addFileArchive("../../media/map-20kdm2.pk3");

    irr::scene::IAnimatedMesh* q3levelmesh = smgr->getMesh("20kdm2.bsp");
    irr::scene::IMeshSceneNode* q3node = 0;

    if (q3levelmesh){
        q3node = smgr->addOctreeSceneNode(q3levelmesh->getMesh(0), 0, -1);
	}
	if(!q3node){
		return 1;
	}

    irr::scene::ITriangleSelector* selector = 0;

    if (q3node)
    {
        q3node->setPosition(irr::core::vector3df(-1350,-130,-1400));

        selector = smgr->createOctreeTriangleSelector(
                q3node->getMesh(), q3node, 128);
		if(!selector){
			return 2;
		}
        q3node->setTriangleSelector(selector);
        // We're not done with this selector yet, so don't drop it.
    }

    // Create world
    irr::core::array<irr::SKeyMap> keymaps;
    keymaps.push_back(irr::SKeyMap(irr::EKA_MOVE_FORWARD, irr::KEY_KEY_W));
    keymaps.push_back(irr::SKeyMap(irr::EKA_MOVE_BACKWARD, irr::KEY_KEY_S));
    keymaps.push_back(irr::SKeyMap(irr::EKA_STRAFE_LEFT, irr::KEY_KEY_A));
    keymaps.push_back(irr::SKeyMap(irr::EKA_STRAFE_RIGHT, irr::KEY_KEY_D));
    keymaps.push_back(irr::SKeyMap(irr::EKA_JUMP_UP, irr::KEY_SPACE));
    auto camera= irr::scene::CSceneNodeAnimatorCameraOculusOnFPS::addCameraSceneNodeOclusOnFPS(
            smgr, cursor,
			0, 
                80.0f, .1f, -1, 
                keymaps.pointer(), keymaps.size(), 
                true, .5f, false, true);
    camera->setPosition(irr::core::vector3df(50,50,-60));
    camera->setTarget(irr::core::vector3df(-70,30,-60));
    {
        irr::scene::ISceneNodeAnimator* anim = smgr->createCollisionResponseAnimator(
                selector, camera, 
                irr::core::vector3df(30,50,30),
                irr::core::vector3df(0,-10,0), 
                irr::core::vector3df(0,30,0));
        selector->drop(); // As soon as we're done with the selector, drop it.
        camera->addAnimator(anim);
        anim->drop();  // And likewise, drop the animator when we're done referring to it.
    }

    // load a faerie 
    auto faerie = smgr->getMesh(MEDIA_PATH "faerie.md2");
    auto faerieNode = smgr->addAnimatedMeshSceneNode(faerie);
    faerieNode->setMaterialTexture(0, driver->getTexture(MEDIA_PATH "faerie2.bmp"));
    faerieNode->setMaterialFlag(irr::video::EMF_LIGHTING, false);
    faerieNode->setPosition(irr::core::vector3df(40,190,-1030));
    faerieNode->setRotation(irr::core::vector3df(0,-90,0));
    faerieNode->setMD2Animation(irr::scene::EMAT_SALUTE);

    // load a dwarf
    auto dwarf = smgr->getMesh(MEDIA_PATH "dwarf.x");
    auto dwarfNode = smgr->addAnimatedMeshSceneNode(dwarf);
    dwarfNode->setPosition(irr::core::vector3df(40,-25,20));

    device->getCursorControl()->setVisible(false);

    // Render loop
    irr::core::vector3df rot;
    while(device->run()){
        driver->beginScene(true,true,irr::video::SColor(0,100,100,100));

        renderer.drawAll(smgr);

        // end scene
        driver->endScene();
    }

    return 0;
}
Пример #5
0
int t07()
{
    // ask user for driver
    video::E_DRIVER_TYPE driverType = driverChoiceConsole();
    if (driverType == video::EDT_COUNT) return 1;

    // create device

    IrrlichtDevice *device = createDevice(driverType, core::dimension2d<u32>(640, 480), 16, false);

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

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

    device->getFileSystem()->addFileArchive("media/map-20kdm2.pk3");

    scene::IAnimatedMesh* q3levelmesh = smgr->getMesh("20kdm2.bsp");
    scene::IMeshSceneNode* q3node = 0;

    // The Quake mesh is pickable, but doesn't get highlighted.
    if (q3levelmesh) q3node = smgr->addOctreeSceneNode(q3levelmesh->getMesh(0), 0,
            IDFlag_IsPickable);

    /*
     So far so good, we've loaded the quake 3 level like in tutorial 2. Now,
     here comes something different: We create a triangle selector. A
     triangle selector is a class which can fetch the triangles from scene
     nodes for doing different things with them, for example collision
     detection. There are different triangle selectors, and all can be
     created with the ISceneManager. In this example, we create an
     OctreeTriangleSelector, which optimizes the triangle output a little
     bit by reducing it like an octree. This is very useful for huge meshes
     like quake 3 levels. After we created the triangle selector, we attach
     it to the q3node. This is not necessary, but in this way, we do not
     need to care for the selector, for example dropping it after we do not
     need it anymore.
     */

    scene::ITriangleSelector* selector = 0;

    if (q3node) {
        q3node->setPosition(core::vector3df(-1350, -130, -1400));

        selector = smgr->createOctreeTriangleSelector(q3node->getMesh(), q3node, 128);
        q3node->setTriangleSelector(selector);
        // We're not done with this selector yet, so don't drop it.
    }

    /*
     We add a first person shooter camera to the scene so that we can see and
     move in the quake 3 level like in tutorial 2. But this, time, we add a
     special animator to the camera: A Collision Response animator. This
     animator modifies the scene node to which it is attached to in order to
     prevent it moving through walls, and to add gravity to it. The
     only thing we have to tell the animator is how the world looks like,
     how big the scene node is, how much gravity to apply and so on. After the
     collision response animator is attached to the camera, we do not have to do
     anything more for collision detection, anything is done automatically.
     The rest of the collision detection code below is for picking. And please
     note another cool feature: The collision response animator can be
     attached also to all other scene nodes, not only to cameras. And it can
     be mixed with other scene node animators. In this way, collision
     detection and response in the Irrlicht engine is really easy.

     Now we'll take a closer look on the parameters of
     createCollisionResponseAnimator(). The first parameter is the
     TriangleSelector, which specifies how the world, against collision
     detection is done looks like. The second parameter is the scene node,
     which is the object, which is affected by collision detection, in our
     case it is the camera. The third defines how big the object is, it is
     the radius of an ellipsoid. Try it out and change the radius to smaller
     values, the camera will be able to move closer to walls after this. The
     next parameter is the direction and speed of gravity.  We'll set it to
     (0, -10, 0), which approximates to realistic gravity, assuming that our
     units are metres. You could set it to (0,0,0) to disable gravity. And the
     last value is just a translation: Without this, the ellipsoid with which
     collision detection is done would be around the camera, and the camera would
     be in the middle of the ellipsoid. But as human beings, we are used to have our
     eyes on top of the body, with which we collide with our world, not in
     the middle of it. So we place the scene node 50 units over the center
     of the ellipsoid with this parameter. And that's it, collision
     detection works now.
     */

    // Set a jump speed of 3 units per second, which gives a fairly realistic jump
    // when used with the gravity of (0, -10, 0) in the collision response animator.
    scene::ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS(0, 100.0f, .3f, ID_IsNotPickable,
            0, 0, true, 3.f);
    camera->setPosition(core::vector3df(50, 50, -60));
    camera->setTarget(core::vector3df(-70, 30, -60));

    if (selector) {
        scene::ISceneNodeAnimator* anim = smgr->createCollisionResponseAnimator(selector, camera,
                core::vector3df(30, 50, 30), core::vector3df(0, -10, 0), core::vector3df(0, 30, 0));
        selector->drop(); // As soon as we're done with the selector, drop it.
        camera->addAnimator(anim);
        anim->drop();  // And likewise, drop the animator when we're done referring to it.
    }

    // Now I create three animated characters which we can pick, a dynamic light for
    // lighting them, and a billboard for drawing where we found an intersection.

    // First, let's get rid of the mouse cursor.  We'll use a billboard to show
    // what we're looking at.
    device->getCursorControl()->setVisible(false);

    // Add the billboard.
    scene::IBillboardSceneNode * bill = smgr->addBillboardSceneNode();
    bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
    bill->setMaterialTexture(0, driver->getTexture("media/particle.bmp"));
    bill->setMaterialFlag(video::EMF_LIGHTING, false);
    bill->setMaterialFlag(video::EMF_ZBUFFER, false);
    bill->setSize(core::dimension2d<f32>(20.0f, 20.0f));
    bill->setID(ID_IsNotPickable); // This ensures that we don't accidentally ray-pick it

    /* Add 3 animated hominids, which we can pick using a ray-triangle intersection.
     They all animate quite slowly, to make it easier to see that accurate triangle
     selection is being performed. */
    scene::IAnimatedMeshSceneNode* node = 0;

    video::SMaterial material;

    // Add an MD2 node, which uses vertex-based animation.
    node = smgr->addAnimatedMeshSceneNode(smgr->getMesh("media/faerie.md2"), 0,
            IDFlag_IsPickable | IDFlag_IsHighlightable);
    node->setPosition(core::vector3df(-90, -15, -140)); // Put its feet on the floor.
    node->setScale(core::vector3df(1.6f)); // Make it appear realistically scaled
    node->setMD2Animation(scene::EMAT_POINT);
    node->setAnimationSpeed(20.f);
    material.setTexture(0, driver->getTexture("media/faerie2.bmp"));
    material.Lighting = true;
    material.NormalizeNormals = true;
    node->getMaterial(0) = material;

    // Now create a triangle selector for it.  The selector will know that it
    // is associated with an animated node, and will update itself as necessary.
    selector = smgr->createTriangleSelector(node);
    node->setTriangleSelector(selector);
    selector->drop(); // We're done with this selector, so drop it now.

    // And this B3D file uses skinned skeletal animation.
    node = smgr->addAnimatedMeshSceneNode(smgr->getMesh("media/ninja.b3d"), 0,
            IDFlag_IsPickable | IDFlag_IsHighlightable);
    node->setScale(core::vector3df(10));
    node->setPosition(core::vector3df(-75, -66, -80));
    node->setRotation(core::vector3df(0, 90, 0));
    node->setAnimationSpeed(8.f);
    node->getMaterial(0).NormalizeNormals = true;
    node->getMaterial(0).Lighting = true;
    // Just do the same as we did above.
    selector = smgr->createTriangleSelector(node);
    node->setTriangleSelector(selector);
    selector->drop();

    // This X files uses skeletal animation, but without skinning.
    node = smgr->addAnimatedMeshSceneNode(smgr->getMesh("media/dwarf.x"), 0,
            IDFlag_IsPickable | IDFlag_IsHighlightable);
    node->setPosition(core::vector3df(-70, -66, -30)); // Put its feet on the floor.
    node->setRotation(core::vector3df(0, -90, 0)); // And turn it towards the camera.
    node->setAnimationSpeed(20.f);
    node->getMaterial(0).Lighting = true;
    selector = smgr->createTriangleSelector(node);
    node->setTriangleSelector(selector);
    selector->drop();

    // And this mdl file uses skinned skeletal animation.
    node = smgr->addAnimatedMeshSceneNode(smgr->getMesh("media/yodan.mdl"), 0,
            IDFlag_IsPickable | IDFlag_IsHighlightable);
    node->setPosition(core::vector3df(-90, -25, 20));
    node->setScale(core::vector3df(0.8f));
    node->getMaterial(0).Lighting = true;
    node->setAnimationSpeed(20.f);

    // Just do the same as we did above.
    selector = smgr->createTriangleSelector(node);
    node->setTriangleSelector(selector);
    selector->drop();

    material.setTexture(0, 0);
    material.Lighting = false;

    // Add a light, so that the unselected nodes aren't completely dark.
    scene::ILightSceneNode * light = smgr->addLightSceneNode(0, core::vector3df(-60, 100, 400),
            video::SColorf(1.0f, 1.0f, 1.0f, 1.0f), 600.0f);
    light->setID(ID_IsNotPickable); // Make it an invalid target for selection.

    // Remember which scene node is highlighted
    scene::ISceneNode* highlightedSceneNode = 0;
    scene::ISceneCollisionManager* collMan = smgr->getSceneCollisionManager();
    int lastFPS = -1;

    // draw the selection triangle only as wireframe
    material.Wireframe = true;

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

            // Unlight any currently highlighted scene node
            if (highlightedSceneNode) {
                highlightedSceneNode->setMaterialFlag(video::EMF_LIGHTING, true);
                highlightedSceneNode = 0;
            }

            // All intersections in this example are done with a ray cast out from the camera to
            // a distance of 1000.  You can easily modify this to check (e.g.) a bullet
            // trajectory or a sword's position, or create a ray from a mouse click position using
            // ISceneCollisionManager::getRayFromScreenCoordinates()
            core::line3d<f32> ray;
            ray.start = camera->getPosition();
            ray.end = ray.start + (camera->getTarget() - ray.start).normalize() * 1000.0f;

            // Tracks the current intersection point with the level or a mesh
            core::vector3df intersection;
            // Used to show with triangle has been hit
            core::triangle3df hitTriangle;

            // This call is all you need to perform ray/triangle collision on every scene node
            // that has a triangle selector, including the Quake level mesh.  It finds the nearest
            // collision point/triangle, and returns the scene node containing that point.
            // Irrlicht provides other types of selection, including ray/triangle selector,
            // ray/box and ellipse/triangle selector, plus associated helpers.
            // See the methods of ISceneCollisionManager
            scene::ISceneNode * selectedSceneNode = collMan->getSceneNodeAndCollisionPointFromRay(
                    ray, intersection, // This will be the position of the collision
                    hitTriangle, // This will be the triangle hit in the collision
                    IDFlag_IsPickable, // This ensures that only nodes that we have
                    // set up to be pickable are considered
                    0);// Check the entire scene (this is actually the implicit default)

            // If the ray hit anything, move the billboard to the collision position
            // and draw the triangle that was hit.
            if (selectedSceneNode) {
                bill->setPosition(intersection);

                // We need to reset the transform before doing our own rendering.
                driver->setTransform(video::ETS_WORLD, core::matrix4());
                driver->setMaterial(material);
                driver->draw3DTriangle(hitTriangle, video::SColor(0, 255, 0, 0));

                // We can check the flags for the scene node that was hit to see if it should be
                // highlighted. The animated nodes can be highlighted, but not the Quake level mesh
                if ((selectedSceneNode->getID() & IDFlag_IsHighlightable)
                        == IDFlag_IsHighlightable) {
                    highlightedSceneNode = selectedSceneNode;

                    // Highlighting in this case means turning lighting OFF for this node,
                    // which means that it will be drawn with full brightness.
                    highlightedSceneNode->setMaterialFlag(video::EMF_LIGHTING, false);
                }
            }

            // We're all done drawing, so end the scene.
            driver->endScene();

            int fps = driver->getFPS();

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

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

    device->drop();

    return 0;
}
Пример #6
0
int main()
{
	//int avg = 2 * 90 + 3 * 88 + 4 * 87 + 3 * 84 + 4 * 92 + 2 * 93 + 2 * 83 + 2 * 80 + 2 * 95;
	//std::cout << "Avg : " << avg << std::endl;

	SDeviceContextSettings settings;
	settings.MultiSamplingCount = 4;
	settings.MultiSamplingQuality = 32;

	IDevice* device = createDevice(EDT_DIRECT3D11, 800, 600, EWS_NONE, true, settings);
	IVideoDriver* driver = device->getVideoDriver();
	ISceneManager* smgr = device->getSceneManager();
	IMeshManager* meshManager = driver->getMeshManager();
	IMaterialManager* materialManager = driver->getMaterialManager();

	IResourceGroupManager* resourceGroupManager = driver->getResourceGroupManager();
	resourceGroupManager->init("Resources.cfg");
	resourceGroupManager->loadResourceGroup("General");

	ISimpleMesh* cubeMesh = meshManager->createCubeMesh("cube1");
	IMeshNode* cubeMeshNode = smgr->addMeshNode(cubeMesh, nullptr, nullptr, XMFLOAT3(0, 3.0f, 0));
	cubeMeshNode->setMaterialName("test/material01");
	//cubeMeshNode->remove();

	ISimpleMesh* planeMesh = meshManager->createPlaneMesh("plane1", 10.0, 10.0f, 50, 50, 10.0f, 10.0f);
	IMeshNode* planeMeshNode = smgr->addMeshNode(planeMesh, nullptr);
	planeMeshNode->setMaterialName("test/ground_material");

	IAnimatedMesh* animMesh = meshManager->getAnimatedMesh("lxq.mesh");
	IAnimatedMeshNode* animNode = smgr->addAnimatedMeshNode(animMesh);
	animNode->scale(0.02f, 0.02f, 0.02f);
	IModelMesh* heroMesh = meshManager->getModelMesh("hero.mesh");
	IMeshNode* heroNode = smgr->addModelMeshNode(heroMesh);	
	
	heroNode->scale(0.01f, 0.01f, 0.01f);
	heroNode->translate(2.0f, 0.5f, 0);

	// create sampler state
	SSamplerDesc samplerDesc;
	samplerDesc.Filter = ESF_FILTER_MIN_MAG_MIP_LINEAR;
	samplerDesc.AddressU = EAM_WRAP;
	samplerDesc.AddressV = EAM_WRAP;
	samplerDesc.AddressW = EAM_WRAP;
	ISampler* sampler = driver->getSamplerManager()->create(std::string("sampler1"), samplerDesc);

	IPipeline* pipeline = driver->getPipelineManager()->get("test/pipeline01");
	//pipeline->setSampler(std::string("sampleType"), sampler);

	ILightNode* light = smgr->addLightNode(1);
	light->setType(ELT_POINT);
	light->setAmbient(XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f));
	light->setPosition(2.0f, 5.0f, -3.0f);
	light->setSpecular(XMFLOAT4(1.0f, 1.0f, 1.0f, 32.0f));
	light->setDiffuse(XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f));
	light->setAttenuation(1.0f, 0.0f, 0.0f);
	light->setRange(100.0f);

	materialManager->destroy(std::string("test/material02"));

	//ICameraNode* camera = smgr->addFpsCameraNode(1, nullptr, XMFLOAT3(0, 1.0f, -4.0f), XMFLOAT3(0, 1.0f, 0.0f));
	ICameraNode* camera = smgr->addFpsCameraNode(1, nullptr, XMFLOAT3(0, 1.0f, -4.0f), XMFLOAT3(0, 1.0f, 0.0f));

	f32 rotx = 0;
	f32 roty = 0;
	f32 rotz = 0;

	char caption[200];

	//FILE* fp = fopen("log.txt", "w");

	ITimer* timer = device->createTimer();
	timer->reset();

	while (device->run())
	{
		const float clearColor[] = { 0.0f, 0.0f, 0.0f, 1.0f };
		driver->beginScene(true, true, clearColor);

		float dt = timer->tick();
		
		rotx += dt * 2.0f;
		roty += dt * 1.0f;
		rotz += dt * 0.5f;
		if (rotx > XM_2PI) rotx -= XM_2PI;
		if (roty > XM_2PI) roty -= XM_2PI;
		if (rotz > XM_2PI) rotz -= XM_2PI;

		XMMATRIX Mx = XMMatrixRotationX(rotx);
		XMMATRIX My = XMMatrixRotationY(roty);
		XMMATRIX Mz = XMMatrixRotationZ(rotz);
		XMMATRIX rotM = Mx * My * Mz;

		cubeMeshNode->setOrientation(rotM);
	//	heroNode->yaw(dt);
		animNode->addTime(dt * 3000.0f);

		updateCamera(camera, dt);
	//	std::cout << dt << std::endl;

		smgr->drawAll();

		driver->endScene();

		sprintf(caption, "FPS:%f", getFps(dt));
		device->setWindowCaption(caption);
	}

	device->drop();

	return 0;
}
Пример #7
0
// PRIVATE METHODS ..
// initilazitions editor.
void Editor::initEditor(){

	// Receivers ..
	myRecEditor = new MastEventReceiver();
	// create Devices.
#if defined(_WIN32) || defined(_WIN64)
	deviceEditor = createDevice(video::EDT_OPENGL, dimension2d<u32>(EDITOR_SCREEN_WIDTH, EDITOR_SCREEN_HEIGHT), 16, false, false, false, myRecEditor);
	
#else

	deviceEditor = createDevice(video::EDT_OPENGL, dimension2d<u32>(EDITOR_SCREEN_WIDTH, EDITOR_SCREEN_HEIGHT), 16, false, false, false, myRecEditor);
#endif

	if (!deviceEditor) // Errors creating device.
		return;
	deviceEditor->setWindowCaption(L"Editor Platform  X - Y Ekseni ");// set Header of Window .
	// Video driver..
	driverEditor = deviceEditor->getVideoDriver();
	// Scene Manager.
	smgrEditor = deviceEditor->getSceneManager();
	//Gui environment.
	guienvEditor = deviceEditor->getGUIEnvironment();
	//Edit box
	eBoxEditor = guienvEditor->addEditBox(L"", rect<s32>(10, 10, 260, 22), true, 0, 101);
	positionNodes = vector < vector3df >(0);
	// Scene NODES ..
	editorParentNode = smgrEditor->addEmptySceneNode();
	editorParentNode->setVisible(true);
	editorChildNode = smgrEditor->addSphereSceneNode();
	nodeEditorCurrMouse = editorChildNode->clone();

	if (nodeEditorCurrMouse && editorChildNode){

		editorParentNode->setVisible(true);
		editorChildNode->setMaterialFlag(EMF_LIGHTING, false);
		editorChildNode->setScale(editorChildNode->getScale()*0.60f);
#if defined(_WIN32) || defined(_WIN64)
		editorChildNode->setMaterialTexture(0, driverEditor->getTexture("media/blueTexture.png"));

#else

		editorChildNode->setMaterialTexture(0, driverEditor->getTexture("../media/blueTexture.png"));
#endif

		editorChildNode->setVisible(false);

		nodeEditorCurrMouse->setMaterialFlag(EMF_LIGHTING, false);
#if defined(_WIN32) || defined(_WIN64)
		nodeEditorCurrMouse->setMaterialTexture(0, driverEditor->getTexture("media/redTexture.png"));

#else

		nodeEditorCurrMouse->setMaterialTexture(0, driverEditor->getTexture("../media/redTexture.png"));
#endif

		nodeEditorCurrMouse->setVisible(true);
		nodeEditorCurrMouse->setScale(nodeEditorCurrMouse->getScale()*1.3f);
	}


	// add camera
	editorCam = smgrEditor->addCameraSceneNode(0, vector3df(0, 0, CAM_POS_DEFAULT), vector3df(0, 0, -CAM_POS_DEFAULT));
	X = 0;
	Y = 0;
	Z = 0;

	// camera View ..
	currentEksen = EKSEN_Z;
	editorParentNode->addChild(nodeEditorCurrMouse);
	deviceEditor->getCursorControl()->setVisible(false); // Unvisible mouse cursor
	mouseWheelBefore = 0; // mouse depth value set 0.
	smgrEditor->setActiveCamera(editorCam);
}
Пример #8
0
    static void run(){
	IrrlichtDevice *device = createDevice( video::EDT_OPENGL, dimension2d<u32>(1024, 768), 32, false, false, true, 0);
	IVideoDriver* driver = device->getVideoDriver();
	ISceneManager* smgr = device->getSceneManager();

	smgr->addCameraSceneNodeFPS();

    const s32 randLength = 1024;
    srand(device->getTimer()->getRealTime());


    //Creating the grid for unit measure, etc
    u32 tileNumber = 128;
	IAnimatedMesh* groundMesh = smgr->addHillPlaneMesh("", dimension2d<float>(8,8),dimension2d<u32>(tileNumber,tileNumber),0,0.0f,dimension2df(0,0),dimension2df(tileNumber,tileNumber));
    IAnimatedMeshSceneNode * groundNode = smgr->addAnimatedMeshSceneNode(groundMesh);
    groundNode->setMaterialTexture(0,driver->getTexture(resPath("../../media/grid2.png")));
    groundNode->setMaterialFlag(EMF_LIGHTING,false);
    groundNode->setPosition(vector3df(0,-2,0));


    //obstacles for stuff
    EntityGroup obstacles;

    for(int i = 0; i < 20; i++)
    {
        ISceneNode* s = smgr->addSphereSceneNode(20);
        IrrlichtBaseEntity * e = new IrrlichtBaseEntity(s);
        s->setPosition(vector3df(rand()%randLength - (randLength/2),0,rand()%randLength - (randLength/2)));
        obstacles.push_back(e);
    }

    //Nodes for vehicles
    ISceneNode * cube = smgr->addCubeSceneNode(4);
    ISceneNode * cube2 = smgr->addCubeSceneNode(4);
    cube->setMaterialFlag(EMF_LIGHTING,false);
    cube->setMaterialTexture(0,driver->getTexture(resPath("../../media/v1-solid.png")));
    cube2->setMaterialFlag(EMF_LIGHTING,false);
    cube2->setMaterialTexture(0,driver->getTexture(resPath("../../media/v2-solid.png")));

    //Creating the actual vehicles
    IrrlichtMobileEntity * Entity1 = new IrrlichtMobileEntity(cube ,vector3df(0,0,0), 1, 60, 150);
    IrrlichtMobileEntity * Entity2 = new IrrlichtMobileEntity(cube2,vector3df(0,0,300), 1, 60, 150);

    //Creating the steering conrollers, constructor also sets steering on entity
    SimpleSteeringController* Entity1Steering = new SimpleSteeringController(Entity1);
    SimpleSteeringController * Entity2Steering = new SimpleSteeringController(Entity2);

    //Setting up other params for behaviors
    Entity1Steering->SetObstacles(obstacles);
    Entity1Steering->SetHideTarget(Entity2);
    Entity1Steering->SetBehaviorFlag(EBF_HIDE,true);
    Entity1Steering->SetBehaviorFlag(EBF_AVOID,true);

    Entity2Steering->SetObstacles(obstacles);
    Entity2Steering->SetPursuitTarget(Entity1);
    Entity2Steering->SetBehaviorFlag(EBF_PURSUIT,true);
    Entity2Steering->SetBehaviorFlag(EBF_AVOID,true);

    //vars for tracking time between frames. This allows framerate independent motion state updates.
    u32 then = device->getTimer()->getTime();
    float timeUpdate = 0;

    while(device->run())
	{
	    const u32 now = device->getTimer()->getTime();
        const float frameDeltaTime = (float)(now - then) / 1000.f; // Time in seconds
        then = now;
        timeUpdate += frameDeltaTime;

        if(timeUpdate > 1)
        {
            core::stringw str = L"desteer v0.0.1  FPS: ";
            str += (s32)driver->getFPS();
			device->setWindowCaption(str.c_str());
			timeUpdate = 0;
		}

        //Do behavior updates before the rendering.
        Entity1->Update(frameDeltaTime);
        Entity2->Update(frameDeltaTime);

        driver->beginScene(true, true, SColor(255,100,101,140));
            smgr->drawAll();
		driver->endScene();
	}
    //Clean up irrlicht.
	device->drop();
    }
Пример #9
0
int main(int argc, char *argv[])
{
#ifdef _WIN32
	AllocConsole();
#endif
	vector<string> args(argv,argv+argc);

	// initialize Zoidcom
	scoped_ptr<ZoidCom> zcom(new ZoidCom(zoidcom_logger));

	if (!zcom || !zcom->Init())
	{
		throw std::runtime_error("Unable to initialize ZoidCom!");
	}

	zcom->setLogLevel(0);

	intrusive_ptr<IrrlichtDevice> device;

	if(args.size() > 1 && args[1] == "server")
	{
		// Skip graphical interface
		// Dedicated server uses 'null' graphics device..
		device = intrusive_ptr<IrrlichtDevice>(
			createDevice(video::EDT_NULL, core::dimension2d<u32>(640,480), 16, false, true, true),
			false /* don't addref */
		);
		device->getLogger()->setLogLevel(ELL_INFORMATION);
		addHeightMapLoader(get_pointer(device));

		// Start server, run game instances in loop
		while(true)
		{
			std::cout << "Loading server instance...";

			scoped_ptr<Sarona::PhysWorld> serverworld(
				new Sarona::PhysWorld(get_pointer(device))
			);

			serverworld->SetLevel("testlevel/");
			serverworld->Bind(9192, false);

			serverworld->Start();
			serverworld->Wait();
		}
	}
	else
	{
		// Display main menu, graphical interface needed
		device = intrusive_ptr<IrrlichtDevice>(
			createDevice(video::EDT_OPENGL, core::dimension2d<u32>(800,600), 16, false, true, true),
			false /* don't addref */
		);
		device->getLogger()->setLogLevel(ELL_WARNING);
		addHeightMapLoader(get_pointer(device));

		Sarona::GameMenu menu(get_pointer(device));

		bool local_game = true;
		bool server = true;

		if(args.size()>1)
			local_game = server = args[1]!="client";

		// Run the main menu, let user decide what to do
		//menu.Run(local_game, server);

		scoped_ptr<Sarona::NetWorld> clientworld;
		scoped_ptr<Sarona::PhysWorld> serverworld;

		if(server)
		{
			serverworld.reset(new Sarona::PhysWorld(get_pointer(device)));

			serverworld->SetLevel("testlevel/");
			serverworld->Bind(9192, local_game);
			serverworld->Start();
			std::cout << "Server started" << std::endl;
		}

		clientworld.reset(new Sarona::NetWorld(get_pointer(device)));
		clientworld->SetLevel("testlevel/");
		clientworld->Connect("localhost:9192", local_game);


		// The main thread has to run the irrlicht loop, apparently..
		clientworld->Loop();

		if(serverworld)
		{
			serverworld->Shutdown();
			serverworld->Wait();
		}
	}
	return 0;
}
Пример #10
0
int main(int argc, char *argv[])
{
	/*
		Initialization
	*/

	log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
	log_add_output_all_levs(&main_dstream_no_stderr_log_out);

	log_register_thread("main");

	// Set locale. This is for forcing '.' as the decimal point.
	std::locale::global(std::locale("C"));
	// This enables printing all characters in bitmap font
	setlocale(LC_CTYPE, "en_US");

	/*
		Parse command line
	*/
	
	// List all allowed options
	core::map<std::string, ValueSpec> allowed_options;
	allowed_options.insert("help", ValueSpec(VALUETYPE_FLAG,
			"Show allowed options"));
	allowed_options.insert("server", ValueSpec(VALUETYPE_FLAG,
			"Run server directly"));
	allowed_options.insert("config", ValueSpec(VALUETYPE_STRING,
			"Load configuration from specified file"));
	allowed_options.insert("port", ValueSpec(VALUETYPE_STRING,
			"Set network port to connect to"));
	allowed_options.insert("address", ValueSpec(VALUETYPE_STRING,
			"Address to connect to"));
	allowed_options.insert("random-input", ValueSpec(VALUETYPE_FLAG,
			"Enable random user input, for testing"));
	allowed_options.insert("disable-unittests", ValueSpec(VALUETYPE_FLAG,
			"Disable unit tests"));
	allowed_options.insert("enable-unittests", ValueSpec(VALUETYPE_FLAG,
			"Enable unit tests"));
	allowed_options.insert("map-dir", ValueSpec(VALUETYPE_STRING,
			"Map directory (where everything in the world is stored)"));
#ifdef _WIN32
	allowed_options.insert("dstream-on-stderr", ValueSpec(VALUETYPE_FLAG));
#endif
	allowed_options.insert("speedtests", ValueSpec(VALUETYPE_FLAG,
			"Run speed tests"));
	allowed_options.insert("info-on-stderr", ValueSpec(VALUETYPE_FLAG,
			"Print debug information to console"));

	Settings cmd_args;
	
	bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);

	if(ret == false || cmd_args.getFlag("help"))
	{
		dstream<<"Allowed options:"<<std::endl;
		for(core::map<std::string, ValueSpec>::Iterator
				i = allowed_options.getIterator();
				i.atEnd() == false; i++)
		{
			dstream<<"  --"<<i.getNode()->getKey();
			if(i.getNode()->getValue().type == VALUETYPE_FLAG)
			{
			}
			else
			{
				dstream<<" <value>";
			}
			dstream<<std::endl;

			if(i.getNode()->getValue().help != NULL)
			{
				dstream<<"      "<<i.getNode()->getValue().help
						<<std::endl;
			}
		}

		return cmd_args.getFlag("help") ? 0 : 1;
	}
	
	/*
		Low-level initialization
	*/

	bool disable_stderr = false;
#ifdef _WIN32
	if(cmd_args.getFlag("dstream-on-stderr") == false)
		disable_stderr = true;
#endif
	
	if(cmd_args.getFlag("info-on-stderr"))
		log_add_output(&main_stderr_log_out, LMT_INFO);

	porting::signal_handler_init();
	bool &kill = *porting::signal_handler_killstatus();
	
	// Initialize porting::path_data and porting::path_userdata
	porting::initializePaths();

	// Create user data directory
	fs::CreateDir(porting::path_userdata);

	init_gettext((porting::path_data+DIR_DELIM+".."+DIR_DELIM+"locale").c_str());
	
	// Initialize debug streams
#ifdef RUN_IN_PLACE
	std::string debugfile = DEBUGFILE;
#else
	std::string debugfile = porting::path_userdata+DIR_DELIM+DEBUGFILE;
#endif
	debugstreams_init(disable_stderr, debugfile.c_str());
	// Initialize debug stacks
	debug_stacks_init();

	DSTACK(__FUNCTION_NAME);

	// Init material properties table
	//initializeMaterialProperties();

	// Debug handler
	BEGIN_DEBUG_EXCEPTION_HANDLER

	// Print startup message
	actionstream<<PROJECT_NAME<<
			" with SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
			<<", "<<BUILD_INFO
			<<std::endl;
	
	/*
		Basic initialization
	*/

	// Initialize default settings
	set_default_settings(g_settings);
	
	// Initialize sockets
	sockets_init();
	atexit(sockets_cleanup);
	
	/*
		Read config file
	*/
	
	// Path of configuration file in use
	std::string configpath = "";
	
	if(cmd_args.exists("config"))
	{
		bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
		if(r == false)
		{
			errorstream<<"Could not read configuration from \""
					<<cmd_args.get("config")<<"\""<<std::endl;
			return 1;
		}
		configpath = cmd_args.get("config");
	}
	else
	{
		core::array<std::string> filenames;
		filenames.push_back(porting::path_userdata +
				DIR_DELIM + "minetest.conf");
#ifdef RUN_IN_PLACE
		filenames.push_back(porting::path_userdata +
				DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
#endif

		for(u32 i=0; i<filenames.size(); i++)
		{
			bool r = g_settings->readConfigFile(filenames[i].c_str());
			if(r)
			{
				configpath = filenames[i];
				break;
			}
		}
		
		// If no path found, use the first one (menu creates the file)
		if(configpath == "")
			configpath = filenames[0];
	}

	// Initialize random seed
	srand(time(0));
	mysrand(time(0));

	/*
		Run unit tests
	*/

	if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
			|| cmd_args.getFlag("enable-unittests") == true)
	{
		run_tests();
	}
	
	/*for(s16 y=-100; y<100; y++)
	for(s16 x=-100; x<100; x++)
	{
		std::cout<<noise2d_gradient((double)x/10,(double)y/10, 32415)<<std::endl;
	}
	return 0;*/
	
	/*
		Game parameters
	*/

	// Port
	u16 port = 30000;
	if(cmd_args.exists("port"))
		port = cmd_args.getU16("port");
	else if(g_settings->exists("port"))
		port = g_settings->getU16("port");
	if(port == 0)
		port = 30000;
	
	// Map directory
	std::string map_dir = porting::path_userdata+DIR_DELIM+"world";
	if(cmd_args.exists("map-dir"))
		map_dir = cmd_args.get("map-dir");
	else if(g_settings->exists("map-dir"))
		map_dir = g_settings->get("map-dir");
	
	// Run dedicated server if asked to
	if(cmd_args.getFlag("server"))
	{
		DSTACK("Dedicated server branch");

		// Create time getter
		g_timegetter = new SimpleTimeGetter();
		
		// Create server
		Server server(map_dir.c_str(), configpath);
		server.start(port);
		
		// Run server
		dedicated_server_loop(server, kill);

		return 0;
	}


	/*
		More parameters
	*/
	
	// Address to connect to
	std::string address = "";
	
	if(cmd_args.exists("address"))
	{
		address = cmd_args.get("address");
	}
	else
	{
		address = g_settings->get("address");
	}
	
	std::string playername = g_settings->get("name");

	/*
		Device initialization
	*/

	// Resolution selection
	
	bool fullscreen = false;
	u16 screenW = g_settings->getU16("screenW");
	u16 screenH = g_settings->getU16("screenH");

	// Determine driver

	video::E_DRIVER_TYPE driverType;
	
	std::string driverstring = g_settings->get("video_driver");

	if(driverstring == "null")
		driverType = video::EDT_NULL;
	else if(driverstring == "software")
		driverType = video::EDT_SOFTWARE;
	else if(driverstring == "burningsvideo")
		driverType = video::EDT_BURNINGSVIDEO;
	else if(driverstring == "direct3d8")
		driverType = video::EDT_DIRECT3D8;
	else if(driverstring == "direct3d9")
		driverType = video::EDT_DIRECT3D9;
	else if(driverstring == "opengl")
		driverType = video::EDT_OPENGL;
	else
	{
		errorstream<<"WARNING: Invalid video_driver specified; defaulting "
				"to opengl"<<std::endl;
		driverType = video::EDT_OPENGL;
	}

	/*
		Create device and exit if creation failed
	*/

	MyEventReceiver receiver;

	IrrlichtDevice *device;
	device = createDevice(driverType,
			core::dimension2d<u32>(screenW, screenH),
			16, fullscreen, false, false, &receiver);

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

	video::IVideoDriver* driver = device->getVideoDriver();

	// Disable mipmaps (because some of them look ugly)
	driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);

	/*
		This changes the minimum allowed number of vertices in a VBO.
		Default is 500.
	*/
	//driver->setMinHardwareBufferVertexCount(50);

	// Set the window caption
	device->setWindowCaption(L"Minetest [Main Menu]");
	
	// Create time getter
	g_timegetter = new IrrlichtTimeGetter(device);
	
	// Create game callback for menus
	g_gamecallback = new MainGameCallback(device);
	
	/*
		Speed tests (done after irrlicht is loaded to get timer)
	*/
	if(cmd_args.getFlag("speedtests"))
	{
		dstream<<"Running speed tests"<<std::endl;
		SpeedTests();
		return 0;
	}
	
	device->setResizable(true);

	bool random_input = g_settings->getBool("random_input")
			|| cmd_args.getFlag("random-input");
	InputHandler *input = NULL;
	if(random_input)
		input = new RandomInputHandler();
	else
		input = new RealInputHandler(device, &receiver);
	
	scene::ISceneManager* smgr = device->getSceneManager();

	guienv = device->getGUIEnvironment();
	gui::IGUISkin* skin = guienv->getSkin();
	gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
	if(font)
		skin->setFont(font);
	else
		errorstream<<"WARNING: Font file was not found."
				" Using default font."<<std::endl;
	// If font was not found, this will get us one
	font = skin->getFont();
	assert(font);
	
	u32 text_height = font->getDimension(L"Hello, world!").Height;
	infostream<<"text_height="<<text_height<<std::endl;

	//skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
	skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
	//skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
	//skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
	skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
	skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
	
	/*
		GUI stuff
	*/

	/*
		If an error occurs, this is set to something and the
		menu-game loop is restarted. It is then displayed before
		the menu.
	*/
	std::wstring error_message = L"";

	// The password entered during the menu screen,
	std::string password;

	/*
		Menu-game loop
	*/
	while(device->run() && kill == false)
	{

		// This is used for catching disconnects
		try
		{

			/*
				Clear everything from the GUIEnvironment
			*/
			guienv->clear();
			
			/*
				We need some kind of a root node to be able to add
				custom gui elements directly on the screen.
				Otherwise they won't be automatically drawn.
			*/
			guiroot = guienv->addStaticText(L"",
					core::rect<s32>(0, 0, 10000, 10000));
			
			/*
				Out-of-game menu loop.

				Loop quits when menu returns proper parameters.
			*/
			while(kill == false)
			{
				// Cursor can be non-visible when coming from the game
				device->getCursorControl()->setVisible(true);
				// Some stuff are left to scene manager when coming from the game
				// (map at least?)
				smgr->clear();
				// Reset or hide the debug gui texts
				/*guitext->setText(L"Minetest-c55");
				guitext2->setVisible(false);
				guitext_info->setVisible(false);
				guitext_chat->setVisible(false);*/
				
				// Initialize menu data
				MainMenuData menudata;
				menudata.address = narrow_to_wide(address);
				menudata.name = narrow_to_wide(playername);
				menudata.port = narrow_to_wide(itos(port));
				menudata.fancy_trees = g_settings->getBool("new_style_leaves");
				menudata.smooth_lighting = g_settings->getBool("smooth_lighting");
				menudata.clouds_3d = g_settings->getBool("enable_3d_clouds");
				menudata.opaque_water = g_settings->getBool("opaque_water");
				menudata.creative_mode = g_settings->getBool("creative_mode");
				menudata.enable_damage = g_settings->getBool("enable_damage");

				GUIMainMenu *menu =
						new GUIMainMenu(guienv, guiroot, -1, 
							&g_menumgr, &menudata, g_gamecallback);
				menu->allowFocusRemoval(true);

				if(error_message != L"")
				{
					errorstream<<"error_message = "
							<<wide_to_narrow(error_message)<<std::endl;

					GUIMessageMenu *menu2 =
							new GUIMessageMenu(guienv, guiroot, -1, 
								&g_menumgr, error_message.c_str());
					menu2->drop();
					error_message = L"";
				}

				video::IVideoDriver* driver = device->getVideoDriver();
				
				infostream<<"Created main menu"<<std::endl;

				while(device->run() && kill == false)
				{
					if(menu->getStatus() == true)
						break;

					//driver->beginScene(true, true, video::SColor(255,0,0,0));
					driver->beginScene(true, true, video::SColor(255,128,128,128));

					drawMenuBackground(driver);

					guienv->drawAll();
					
					driver->endScene();
					
					// On some computers framerate doesn't seem to be
					// automatically limited
					sleep_ms(25);
				}
				
				// Break out of menu-game loop to shut down cleanly
				if(device->run() == false || kill == true)
					break;
				
				infostream<<"Dropping main menu"<<std::endl;

				menu->drop();
				
				// Delete map if requested
				if(menudata.delete_map)
				{
					bool r = fs::RecursiveDeleteContent(map_dir);
					if(r == false)
						error_message = L"Delete failed";
					continue;
				}

				playername = wide_to_narrow(menudata.name);

				password = translatePassword(playername, menudata.password);

				//infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;

				address = wide_to_narrow(menudata.address);
				int newport = stoi(wide_to_narrow(menudata.port));
				if(newport != 0)
					port = newport;
				g_settings->set("new_style_leaves", itos(menudata.fancy_trees));
				g_settings->set("smooth_lighting", itos(menudata.smooth_lighting));
				g_settings->set("enable_3d_clouds", itos(menudata.clouds_3d));
				g_settings->set("opaque_water", itos(menudata.opaque_water));
				g_settings->set("creative_mode", itos(menudata.creative_mode));
				g_settings->set("enable_damage", itos(menudata.enable_damage));
				
				// NOTE: These are now checked server side; no need to do it
				//       here, so let's not do it here.
				/*// Check for valid parameters, restart menu if invalid.
				if(playername == "")
				{
					error_message = L"Name required.";
					continue;
				}
				// Check that name has only valid chars
				if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)==false)
				{
					error_message = L"Characters allowed: "
							+narrow_to_wide(PLAYERNAME_ALLOWED_CHARS);
					continue;
				}*/

				// Save settings
				g_settings->set("name", playername);
				g_settings->set("address", address);
				g_settings->set("port", itos(port));
				// Update configuration file
				if(configpath != "")
					g_settings->updateConfigFile(configpath.c_str());
			
				// Continue to game
				break;
			}
			
			// Break out of menu-game loop to shut down cleanly
			if(device->run() == false || kill == true)
				break;
			
			/*
				Run game
			*/
			the_game(
				kill,
				random_input,
				input,
				device,
				font,
				map_dir,
				playername,
				password,
				address,
				port,
				error_message,
				configpath
			);

		} //try
		catch(con::PeerNotFoundException &e)
		{
			errorstream<<"Connection error (timed out?)"<<std::endl;
			error_message = L"Connection error (timed out?)";
		}
		catch(SocketException &e)
		{
			errorstream<<"Socket error (port already in use?)"<<std::endl;
			error_message = L"Socket error (port already in use?)";
		}
		catch(ModError &e)
		{
			errorstream<<e.what()<<std::endl;
			error_message = narrow_to_wide(e.what()) + L"\nCheck debug.txt for details.";
		}
#ifdef NDEBUG
		catch(std::exception &e)
		{
			std::string narrow_message = "Some exception, what()=\"";
			narrow_message += e.what();
			narrow_message += "\"";
			errorstream<<narrow_message<<std::endl;
			error_message = narrow_to_wide(narrow_message);
		}
#endif

	} // Menu-game loop
	
	delete input;

	/*
		In the end, delete the Irrlicht device.
	*/
	device->drop();
	
	END_DEBUG_EXCEPTION_HANDLER(errorstream)
	
	debugstreams_deinit();
	
	return 0;
}
Пример #11
0
int main()
{
  // Initialization of Device, Video Driver and Scene Manager
  video::E_DRIVER_TYPE driverType=video::EDT_OPENGL; 
  MyEventReceiver receiver;  
  IrrlichtDevice* device = createDevice(driverType,
					core::dimension2d<u32>(960, 720), 16, false, false, false, &receiver);
  if (device == 0) return 1; 
  video::IVideoDriver* driver = device->getVideoDriver();
  scene::ISceneManager* smgr = device->getSceneManager();

  // Building the scene.

  // open level file
  ifstream infile;
  infile.open("enigma3d.app/Contents/Resources/field.lvl");
  if (infile.fail()) error("Could not open level file\n");

  // checking the file starts with "Enigma-3D"
  string line;
  infile >> line;
  if (line!="Enigma-3D") error("Illegal Level file: "+line+"\n"); 

  // Playground is a two-dimensional array of pointers to fields:
  Field * playground[dimx][dimy];
  
  // now reading from level file one number for each field
  // and creating a wall or floor of the appropriate sub-class
  for(int j=0; j<dimy; j++){
    for(int i=0; i<dimx; i++){
      // determine filed type
      int fieldtype;
      infile >> fieldtype;

      playground[i][j]=makefield(fieldtype,smgr,driver,i,j,playground);
    } 
  } 
  // the level file may contain additional requests for introducing
  // some fields to each other:
  while ((infile >> line), line!="end"){
    // must have the form "introduce x1 y1 to x1 y2"
    if (line!="introduce") error("Level File: mistake in introduce lines");
    int x1,x2,y1,y2;
    infile >> x1 >> y1 >> line >> x2 >> y2;
    if (   (x1 < 0) || x1>=dimx 
	|| (x2 < 0) || x2>=dimx 
        || (y1 < 0) || y1>=dimy 
	|| (y2 < 0) || y2>=dimy 
	|| line !="to" )
      error("Level File: mistake in introduce lines");
    // call the introduceTo method of field x1 y1:
    playground[x1][y1]->introduceTo(*(playground[x2][y2]));
  }
  infile.close();


  Sphere *sphere=new Sphere(smgr,driver);

  scene::ICameraSceneNode* camera=smgr->addCameraSceneNode(NULL,core::vector3df(offsety+50.f,100.f,offsetx),
							        core::vector3df(offsety,0.f,offsetx));
  // to change the camera position use: 
  //    camera->setPosition(core::vector3df(...));
  // see docmentation of  ICameraSceneNode  for more (like setting target, rotation, aspect)

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

  // for time measurement: get an initial time reference 
  u32 then = device->getTimer()->getTime();

  // for mouse-move measurement: get an initial mouse position
  core::position2di RefPosition=receiver.Position;

  // compute the field number where the sphere is and notify that field
  int fieldx=getFieldx(sphere->getPosition());
  int fieldy=getFieldy(sphere->getPosition());
  playground[fieldx][fieldy]->sphereEnter(*sphere);

  // Running function introduceSphere for every wall/floor ONCE
  for(int j=0; j<dimy; j++)
    for(int i=0; i<dimx; i++)
      playground[i][j]-> introduceSphere(*sphere); 
	 

  while(device->run())
    {
      if(receiver.IsKeyDown(irr::KEY_KEY_Q)) exit(0); // quit game on key Q
      
      // Adapt speed by the difference in mouse position
      core::position2di mousemove;
      mousemove.X=(receiver.Position.X-RefPosition.X);
      mousemove.Y=(receiver.Position.Y-RefPosition.Y);
      // eliminating too rapid movements of the mouse
      if (fabs((float)mousemove.X)>10) mousemove.X=0;
	  if (fabs((float)mousemove.Y)>10) mousemove.Y = 0;
      // remember current mouse position
      RefPosition=receiver.Position;

      // Measure the time that has passed since last round 
      const u32 now = device->getTimer()->getTime();
      const f32 frameDeltaTime = (f32)(now - then) / 1000.f; 
      then = now;

      /* The field that the sphere is currently on is now in control
	 to decide how the sphere moves within the time
	 frameDeltaTime.  This will typically NOT include collision
	 detection with surrounding walls---that will be done
	 later. */
      playground[fieldx][fieldy]->handleSphere(*sphere,mousemove,frameDeltaTime);

      // tell also all other fields that time has passed:
      for(int j=0; j<dimy; j++)
	for(int i=0; i<dimx; i++)
	  if (i!=fieldx || j!=fieldy)
	    playground[i][j]->timeProgress(frameDeltaTime);

      /* Now we turn to collision detection:
	 - compute what field the sphere is on now
	 - compute overlap with adjacent fields 
	 - notify all fields where overlap is non-zero
      */
      core::vector3df spherePosition = sphere->getPosition();
      int new_fieldx=getFieldx(spherePosition);
      int new_fieldy=getFieldy(spherePosition);

      f32 xoE=getOverlapx(spherePosition,new_fieldx+1);
      f32 xoW=getOverlapx(spherePosition,new_fieldx-1);
      f32 yoN=getOverlapy(spherePosition,new_fieldy+1);
      f32 yoS=getOverlapy(spherePosition,new_fieldy-1);
      // E = east, W = west...
      
      if (xoE) playground[new_fieldx+1][new_fieldy]->sphereOverlap(*sphere,xoE,0.f);
      if (xoW) playground[new_fieldx-1][new_fieldy]->sphereOverlap(*sphere,xoW,0.f);
      if (yoN) playground[new_fieldx][new_fieldy+1]->sphereOverlap(*sphere,0.f,yoN);
      if (yoS) playground[new_fieldx][new_fieldy-1]->sphereOverlap(*sphere,0.f,yoS);
      
      /*
      if (spherePosition==sphere->getPosition()){ 
	// if there was no collision with E,W,N, or S, check for overlaps with diagonal fields
	if (xoE && yoN) playground[new_fieldx+1][new_fieldy+1]->sphereOverlap(*sphere,xoE/4,yoN/4);
	if (xoE && yoS) playground[new_fieldx+1][new_fieldy-1]->sphereOverlap(*sphere,xoE/4,yoS/4);
	if (xoW && yoN) playground[new_fieldx-1][new_fieldy+1]->sphereOverlap(*sphere,xoW/4,yoN/4);
	if (xoW && yoS) playground[new_fieldx-1][new_fieldy-1]->sphereOverlap(*sphere,xoW/4,yoS/4);
      }
      */

      // If all the movements and collisions have changed the field the sphere is on, notify both 
      // the field it leaves and the field it enters: 
      if (new_fieldx!=fieldx || new_fieldy!=fieldy){
	playground[fieldx][fieldy]->sphereExit(*sphere);
	fieldx=new_fieldx;
	fieldy=new_fieldy;
	playground[fieldx][fieldy]->sphereEnter(*sphere);
      }

      // Draw the picture anew and go to a next round
      driver->beginScene(true, true, video::SColor(255,113,113,133));
      smgr->drawAll();
      driver->endScene();
    }
  device->drop();
  return 0;
}
Пример #12
0
void VulkanBase::initVulkan(bool enableValidation) {
	VkResult err = createInstance(enableValidation);
	if (err) vkTools::exitFatal("Could not create Vulkan instance : \n" + vkTools::errorString(err), "Fatal error");

	uint32_t gpuCount = 0;
	err = vkEnumeratePhysicalDevices(instance, &gpuCount, nullptr);
	assert(!err);
	assert(gpuCount > 0);

	std::vector<VkPhysicalDevice> physicalDevices(gpuCount);
	err = vkEnumeratePhysicalDevices(instance, &gpuCount, physicalDevices.data());
	if (err) vkTools::exitFatal("Could not enumerate phyiscal devices : \n" + vkTools::errorString(err), "Fatal error");

	physicalDevice = physicalDevices[0];

	uint32_t graphicsQueueIndex = 0;
	uint32_t queueCount;
	vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueCount, NULL);
	assert(queueCount >= 1);

	std::vector<VkQueueFamilyProperties> queueProps;
	queueProps.resize(queueCount);
	vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueCount, queueProps.data());

	for (graphicsQueueIndex = 0; graphicsQueueIndex < queueCount; graphicsQueueIndex++)
		if (queueProps[graphicsQueueIndex].queueFlags & VK_QUEUE_GRAPHICS_BIT)
			break;
	assert(graphicsQueueIndex < queueCount);

	std::array<float, 1> queuePriorities = { 0.0f };
	VkDeviceQueueCreateInfo queueCreateInfo = {};
	queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
	queueCreateInfo.queueFamilyIndex = graphicsQueueIndex;
	queueCreateInfo.queueCount = 1;
	queueCreateInfo.pQueuePriorities = queuePriorities.data();

	err = createDevice(queueCreateInfo, enableValidation);
	assert(!err);

	vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);

	vkGetPhysicalDeviceMemoryProperties(physicalDevice, &deviceMemoryProperties);

	vkGetDeviceQueue(device, graphicsQueueIndex, 0, &queue);

	VkBool32 validDepthFormat = vkTools::getSupportedDepthFormat(physicalDevice, &depthFormat);
	assert(validDepthFormat);

	swapChain.connect(instance, physicalDevice, device);

	VkSemaphoreCreateInfo semaphoreCreateInfo = vkTools::initializers::semaphoreCreateInfo();

	err = vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &semaphores.presentComplete);
	assert(!err);

	err = vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &semaphores.renderComplete);
	assert(!err);

	submitInfo = vkTools::initializers::submitInfo();
	submitInfo.pWaitDstStageMask = &submitPipelineStages;
	submitInfo.waitSemaphoreCount = 1;
	submitInfo.pWaitSemaphores = &semaphores.presentComplete;
	submitInfo.signalSemaphoreCount = 1;
	submitInfo.pSignalSemaphores = &semaphores.renderComplete;
}
Пример #13
0
int main()
{
	Context m;
	m.running = true;

	// Register all formats and codecs
	av_register_all();

#ifdef SOUND_OPENAL
	// signal handler
	if (signal(SIGINT, handle_sigint) == SIG_ERR) {
		fprintf(stderr, "Unable to set handler for SIGINT!\n");
		return -1;
	}

	// audio temp buffer
	m._abData = (ALbyte *)malloc(BUFFER_SIZE);
	if (!m._abData) {
		fprintf(stderr, "Out of memory allocating temp buffer!\n");
		return -1;
	}

	// Initialize ALUT with default settings 
	if (alutInit(NULL, NULL) == AL_FALSE) {
		free(m._abData);
		fprintf(stderr, "Could not initialize ALUT (%s)!\n", alutGetErrorString(alutGetError()));
		return -1;
	}
#endif

	// Event Receiver
	EventReceiver receiver;

	// start up the engine
	m.device = createDevice(video::EDT_OPENGL,
		core::dimension2d<u32>(1680,1050), 16, true, // fullscreen
//		core::dimension2d<u32>(1280,800), 16, true, // fullscreen
//		core::dimension2d<u32>(800,600), 16, false,
					 false, false, &receiver);

	m.driver = m.device->getVideoDriver();
	m.scenemgr = m.device->getSceneManager();

	// add a first person shooter style user controlled camera
	m.camera = m.scenemgr->addCameraSceneNodeFPS(0, 100.0f, .3f, -1, 0, 0, true, 3.f);

	// add terrain scene node
	TerrainSceneNode* terrain = new TerrainSceneNode(&m);

	m.origin = terrain->getTerrainCenter();
	resetCamera(&m);

	// File manager listing
	m.filemgr = new FileManagerSceneNode(&m);
	m.filemgr->drop();

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

	u32 frames = 0;
	// draw everything
	while(m.device->run() && m.driver && m.running)
	{
		if (receiver.IsKeyDown(KEY_KEY_Q))
			m.running = false;

		if (receiver.IsKeyDown(KEY_ESCAPE))
			resetCamera(&m);

		core::stringw caption =(L"FPS: ");
		caption += m.driver->getFPS();
		m.device->setWindowCaption(caption.c_str());
		m.driver->beginScene(true, true, video::SColor(255,133,133,133));
		m.scenemgr->drawAll();

		for (u32 i = 0; i != m.cleanup.size(); i++) {
			m.camera->removeAnimator(m.cleanup[i]->anim);
			m.cleanup[i]->anim->drop();
			m.cleanup[i]->drop();
		}
		m.cleanup.clear();

		for (u32 i = 0; i != m.videos.size(); i++) {
			if (m.videos[i]->videoPlayer->psVideostate == Playing) {  // play active 
				if (!m.videos[i]->videoPlayer->refresh()) {  // no more AV 
					m.videos[i]->videoPlayer->goToFrame(0);
				} else {
					m.videos[i]->videoPlayer->drawVideoTexture();
				}
			}
		}

		m.driver->endScene();

		terrain->shift(m.camera);
	}

	// delete device
	m.device->drop();

#ifdef SOUND_OPENAL
	alutExit();
	free(m._abData);
#endif

	return 0;
}
Пример #14
0
int main()
{

	int d = 1;
	GF_PRINT_CONSOLE_INFO("Hello:%d\n", d);

	SDeviceContextSettings settings;
	settings.MultiSamplingCount = 4;
	settings.MultiSamplingQuality = 32;

	IDevice* device = createDevice(EDT_DIRECT3D11, 800, 600, EWS_NONE, true, settings);
	IVideoDriver* driver = device->getVideoDriver();
	IShaderManager* shaderManager = driver->getShaderManager();
	IInputLayoutManager* inputlayoutManager = driver->getInputLayoutManager();
	IPipelineManager* pipelineMgr = driver->getPipelineManager();

	IShader* vs = shaderManager->load(EST_VERTEX_SHADER, "color.hlsl", "ColorVertexShader");
	IShader* ps = shaderManager->load(EST_PIXEL_SHADER, "PixelShader.hlsl", "ColorPixelShader");

	std::vector<SInputLayoutElement> elements;
	elements.resize(2);
	elements[0].SemanticName = "POSITION";
	elements[0].SemanticIndex = 0;
	elements[0].Format = EGF_R32G32B32_FLOAT;
	elements[0].Offset = 0;
	elements[1].SemanticName = "COLOR";
	elements[1].SemanticIndex = 0;
	elements[1].Format = EGF_R32G32B32A32_FLOAT;
	elements[1].Offset = 12;

	IInputLayout* layout = inputlayoutManager->create(elements, vs);


	IShader* shaders[2] = { vs, ps };
	IPipeline* pipeline = pipelineMgr->create("color", shaders, 2, layout, EPT_TRIANGLELIST);

	ISceneManager* smgr = device->getSceneManager();
	
	Vertex vertices[3];
	vertices[0] = Vertex(XMFLOAT3(-1.0f, -0.6f, 0.0f), XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f));
	vertices[1] = Vertex(XMFLOAT3(0.0f,   0.6f, 0.0f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f));
	vertices[2] = Vertex(XMFLOAT3(1.0f,  -0.6f, 0.0f), XMFLOAT4(1.0f, 0.0f, 1.0f, 1.0f));
	//IMesh* mesh = smgr->createSimpleMesh(&vertices, 3, sizeof(Vertex), nullptr, 0, 0);
	IMesh* mesh = smgr->createCubeMesh();
	IMeshNode* meshNode = smgr->addMeshNode(mesh, pipeline);

	//CD3D11ShaderManager* s = new CD3D11ShaderManager(nullptr);

	XMVECTOR eye = XMVectorSet(0.0f, 0.0f, -5.0f, 1.0f);
	XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
	XMVECTOR at = XMVectorZero();

	XMMATRIX view = XMMatrixLookAtLH(eye, at, up);

	XMMATRIX proj = XMMatrixPerspectiveFovLH(0.25f * 3.14f,
		static_cast<float>(SCREEN_WIDTH) / static_cast<float>(SCREEN_HEIGHT),
		1.0f, 1000.0f);


	meshNode->translate(0, 0, 5.0f);
	XMMATRIX world = meshNode->getAbsoluteTransformation();
	//XMMATRIX world = XMMatrixIdentity();

	
	pipeline->setMatrix("viewMatrix", reinterpret_cast<f32*>(&view));
	pipeline->setMatrix("projectionMatrix", reinterpret_cast<f32*>(&proj));

	SShaderAutoVariable var;
	var.Type = ESAVT_WORLD_MATRIX;
	var.ShaderType = EST_VERTEX_SHADER;
	var.VariableName = "worldMatrix";

	pipeline->addShaderAutoVariable(var);

	std::cout << "Hello World" << std::endl;

	ITimer* timer = device->createTimer();
	timer->reset();
	while (device->run())
	{
		const float clearColor[] = { 0.0f, 0.0f, 0.0f, 1.0f };
		driver->beginScene(true, true, clearColor);

		f32 dt = timer->tick();
		//std::cout << dt << std::endl;

		meshNode->setPosition(0, 0, -2.0f);
		meshNode->yaw(1.0f * dt);

		smgr->drawAll();

		//XMMATRIX world = meshNode->getAbsoluteTransformation();
		//pipeline->setMatrix("worldMatrix", reinterpret_cast<f32*>(&world));

		driver->endScene();
	}

	return 0;
}
Пример #15
0
/**
 * Main.
 */
int main()
{
    ofw_core::init_i18n();

    // Select driver: gui or terminal
    video::E_DRIVER_TYPE driverType=driverChoiceConsole();

    IrrlichtDevice *device = createDevice(driverType, core::dimension2d<u32>(640, 480), 16, false);
    //if (device == 0)
    //  return 1;
    //IrrlichtDevice* device = ofw_core::init_device();

    // init_driver
    //device->setWindowCaption(L"OFW");

    // Load video, scene and gui
    video::IVideoDriver* driver = device->getVideoDriver();
    scene::ISceneManager* smgr = device->getSceneManager();
    gui::IGUIEnvironment* guienv = device->getGUIEnvironment();

    smgr->setAmbientLight(video::SColorf(0.3,0.3,0.3,1));

    scene::IAnimatedMesh* mesh = smgr->getMesh("../media/Escenario.obj");
    scene::ISceneNode* node = 0;

    // SCENARIUM
    if (mesh) {
        // The optimization with the Octree is only useful when drawing huge
        // meshes consisting of lots of geometry.
        //node = smgr->addOctreeSceneNode(mesh->getMesh(0), 0, 512);
        node = smgr->addMeshSceneNode(mesh->getMesh(0));
    }
    if (node) {
        //node->setScale(core::vector3df(0.2,0.2,0.2));
        cout << "NODESSS: " << node->getMaterialCount() << endl;
        for (u32 j = 0; j < node->getMaterialCount(); ++j) {
            cout << &node->getMaterial(j) << endl;
        }
        node->getMaterial(0).setTexture(0, driver->getTexture("../media/Templo_frontal _color.JPG"));
        node->getMaterial(1).setTexture(0, driver->getTexture("../media/Templo_frontal _color.JPG"));
        node->getMaterial(2).setTexture(0, driver->getTexture("../media/Cliffs0016_1_S_wall.jpg"));
        node->getMaterial(3).setTexture(0, driver->getTexture("../media/Cliffs0016_1_S_wall.jpg"));
        node->getMaterial(4).setTexture(0, driver->getTexture("../media/Cliffs0016_1_S_wall.jpg"));
        node->getMaterial(5).setTexture(0, driver->getTexture("../media/Cliffs0454_S_suelo.jpg"));
        node->getMaterial(6).setTexture(0, driver->getTexture("../media/Templo_frontal _color.JPG"));
        //node->setMaterialFlag(video::EMF_LIGHTING, true);
        //node->setMaterialType(video::EMT_SOLID_2_LAYER);
        node->setPosition(core::vector3df(0,0,0));
    }

    // SCENE: insert player
    scene::IAnimatedMesh* player = smgr->getMesh("../media/Gliptodont_Lv1_03.b3d");
    if (!player) {
        device->drop();
        return 1;
    }
    scene::IAnimatedMeshSceneNode* player_ani = smgr->addAnimatedMeshSceneNode(player);
    if (player_ani) {
        player_ani->setMaterialTexture(0, driver->getTexture("../media/Gliptodon_Lv1_Color.jpg"));
        player_ani->setMaterialTexture(1, driver->getTexture("../media/Gliptodon_Lv1_specular.JPG"));
        player_ani->setMaterialFlag(video::EMF_LIGHTING, false);
        //player_ani->getMaterial(1).SpecularColor.set(255,255,255,255);
        //player_ani->setFrameLoop(0, 6000);  // nº frame
        //player_ani->setAnimationSpeed(300); // fps
        //player_ani->setMaterialType(video::EMT_SOLID);
        player_ani->setScale(core::vector3df(6,6,6));
        player_ani->setPosition(core::vector3df(0,20,60));
        player_ani->setRotation(core::vector3df(0,140,0));
    }

    // SCENE: insert weapon
    scene::IAnimatedMesh* weapon = smgr->getMesh("../media/pico.3ds");
    if (!weapon)
    {
        device->drop();
        return 1;
    }
    scene::IAnimatedMeshSceneNode* weapon_ani = smgr->addAnimatedMeshSceneNode(weapon);
    if (weapon_ani)
    {
        weapon_ani->setMaterialTexture(0, driver->getTexture("../media/Pico_color02.PNG"));
        weapon_ani->setMaterialTexture(1, driver->getTexture("../media/Pico_01bump.PNG"));
        weapon_ani->getMaterial(1).Shininess = 20.0f;
        //weapon_ani->setMaterialTexture(1, driver->getTexture("../media/picacode_tex.jpg"));
        weapon_ani->setMaterialFlag(video::EMF_LIGHTING, false);
        //weapon_ani->setMaterialType(video::EMT_NORMAL_MAP_TRANSPARENT_VERTEX_ALPHA);
        //weapon_ani->setMaterialType(video::EMT_REFLECTION_2_LAYER);
        weapon_ani->setScale(core::vector3df(0.2,0.2,0.2));
        //weapon_ani->setPosition(core::vector3df(0,0,0));
        //weapon_ani->setRotation(core::vector3df(0,0,0));
    }
    irr::scene::ISceneNode* hand = player_ani->getJointNode("Gliptodont_Lv1");

    scene::ISkinnedMesh* player_b = (scene::ISkinnedMesh*) smgr->getMesh("../media/Gliptodont_Lv1_04.b3d");
    cout << _("HUESOS") << endl;
    for (int i=0; i < player_ani->getJointCount(); i++)
    {
        cout << _("hello") << endl;
        cout << i << endl;
        cout << player_b->getAllJoints()[i]->Name.c_str() << endl;
    }
    hand->addChild(weapon_ani);

    // SCENE: insert camera
    scene::ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS();
    camera->setPosition(core::vector3df(40,15,40));
    camera->setTarget(player_ani->getPosition() - core::vector3df(0,-15,0));

    //FPS
    int lastFPS = -1;

    // BUCLE
    while(device->run())
    {
        if (device->isWindowActive())
        {
            driver->beginScene(true, true, video::SColor(255,113,113,133));
            smgr->drawAll();
            guienv->drawAll(); // draw the gui environment
            driver->endScene();

            int fps = driver->getFPS();

            if (lastFPS != fps)
            {
                core::stringw str = L"EXAMPLE OFW";
                str += driver->getName();
                str += "] FPS:";
                str += fps;

                device->setWindowCaption(str.c_str());
                lastFPS = fps;
            }
        }
        else
            device->yield();
    }
    device->drop();
    return 0;
}
Пример #16
0
  void
  XorgFunction::clearState(void) {
    deleteDevice(dev) ;
    dev = createDevice(ctrl_num, ctrl_den, ctrl_threshold, scheme, 
		       predictableProfile, corr_mul, const_acceleration, min_acceleration) ;
  }
Пример #17
0
void VulkanExampleBase::initVulkan(bool enableValidation)
{
	VkResult err;

	// Vulkan instance
	err = createInstance(enableValidation);
	if (err)
	{
		vkTools::exitFatal("Could not create Vulkan instance : \n" + vkTools::errorString(err), "Fatal error");
	}

#if defined(__ANDROID__)
	loadVulkanFunctions(instance);
#endif

	// Physical device
	uint32_t gpuCount = 0;
	// Get number of available physical devices
	err = vkEnumeratePhysicalDevices(instance, &gpuCount, nullptr);
	assert(!err);
	assert(gpuCount > 0);
	// Enumerate devices
	std::vector<VkPhysicalDevice> physicalDevices(gpuCount);
	err = vkEnumeratePhysicalDevices(instance, &gpuCount, physicalDevices.data());
	if (err)
	{
		vkTools::exitFatal("Could not enumerate phyiscal devices : \n" + vkTools::errorString(err), "Fatal error");
	}

	// Note :
	// This example will always use the first physical device reported,
	// change the vector index if you have multiple Vulkan devices installed
	// and want to use another one
	physicalDevice = physicalDevices[0];

	// Find a queue that supports graphics operations
	uint32_t graphicsQueueIndex = 0;
	uint32_t queueCount;
	vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueCount, NULL);
	assert(queueCount >= 1);

	std::vector<VkQueueFamilyProperties> queueProps;
	queueProps.resize(queueCount);
	vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueCount, queueProps.data());

	for (graphicsQueueIndex = 0; graphicsQueueIndex < queueCount; graphicsQueueIndex++)
	{
		if (queueProps[graphicsQueueIndex].queueFlags & VK_QUEUE_GRAPHICS_BIT)
			break;
	}
	assert(graphicsQueueIndex < queueCount);

	// Vulkan device
	std::array<float, 1> queuePriorities = { 0.0f };
	VkDeviceQueueCreateInfo queueCreateInfo = {};
	queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
	queueCreateInfo.queueFamilyIndex = graphicsQueueIndex;
	queueCreateInfo.queueCount = 1;
	queueCreateInfo.pQueuePriorities = queuePriorities.data();

	err = createDevice(queueCreateInfo, enableValidation);
	assert(!err);

	vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);

#if defined(__ANDROID__)
	LOGD(deviceProperties.deviceName);
#endif

	// Gather physical device memory properties
	vkGetPhysicalDeviceMemoryProperties(physicalDevice, &deviceMemoryProperties);

	// Get the graphics queue
	vkGetDeviceQueue(device, graphicsQueueIndex, 0, &queue);

	// Find a suitable depth format
	VkBool32 validDepthFormat = vkTools::getSupportedDepthFormat(physicalDevice, &depthFormat);
	assert(validDepthFormat);

	swapChain.connect(instance, physicalDevice, device);

	// Create synchronization objects
	VkSemaphoreCreateInfo semaphoreCreateInfo = vkTools::initializers::semaphoreCreateInfo();
	// Create a semaphore used to synchronize image presentation
	// Ensures that the image is displayed before we start submitting new commands to the queu
	err = vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &semaphores.presentComplete);
	assert(!err);
	// Create a semaphore used to synchronize command submission
	// Ensures that the image is not presented until all commands have been sumbitted and executed
	err = vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &semaphores.renderComplete);
	assert(!err);

	// Set up submit info structure
	// Semaphores will stay the same during application lifetime
	// Command buffer submission info is set by each example
	submitInfo = vkTools::initializers::submitInfo();
	submitInfo.pWaitDstStageMask = &submitPipelineStages;
	submitInfo.waitSemaphoreCount = 1;
	submitInfo.pWaitSemaphores = &semaphores.presentComplete;
	submitInfo.signalSemaphoreCount = 1;
	submitInfo.pSignalSemaphores = &semaphores.renderComplete;
}
Пример #18
0
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE , LPSTR ,  int )
{

	CMyEventReceiver receiver;
	IrrlichtDevice* device = createDevice( EDT_DIRECT3D9,dimension2d<u32>(1024,768),16,false,true);
	if (device == 0)
		return 0;

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

	env->getSkin()->setColor ( EGDC_BUTTON_TEXT, video::SColor(240,0xFF,0xFF,0xFF) );
	env->getSkin()->setColor ( EGDC_3D_HIGH_LIGHT, video::SColor(240,0x1f,0x26,0x24) );
	env->getSkin()->setColor ( EGDC_3D_FACE, video::SColor(240,0x4f,0x83,0x6c) );
	env->getSkin()->setColor ( EGDC_WINDOW, video::SColor(240,0x76,0x76,0x76) );
	
	device->setWindowCaption(L"My CS");

	env->getSkin()->setFont(env->getFont("font\\myfont.xml"));

	device->setEventReceiver(&receiver);

	CInitUI InitUI;
	CSelectGame selectGameUI;
	CDoGame		doGameUI;

	//------------------------------
	//Desc:初始化静态值
	//------------------------------
	IMyUIScene::m_device = device;
	IMyUIScene::m_driver = driver;
	IMyUIScene::m_smgr = smgr;
	IMyUIScene::m_guienv = env;
	IMyUIScene::m_event = &receiver;

	IGlobe::g_device = device;
	IGlobe::g_driver = driver;
	IGlobe::g_smgr = smgr;
	IGlobe::g_guienv = env;


	InitUI.m_next = &selectGameUI;
	selectGameUI.m_front = &InitUI;
	selectGameUI.m_next = &doGameUI;
	doGameUI.m_front = &selectGameUI;

	InitUI.InitUI();

	IMyUIScene::m_CurrentUI = &g_currentUI;

	g_currentUI = &InitUI;

	
	int lastFPS = 0;
	irr::ITimer* timer = device->getTimer();
	s32 oldtime = timer->getRealTime();
	s32 nowtime = 0;
	s32 bt;
	while(device->run())
	{
		nowtime = timer->getRealTime();
		bt = nowtime - oldtime;
		if (bt < 15)			//帧速控制
		{
			Sleep(1);			//让出CPU 防止CPU消耗
			continue;
		}
		oldtime = nowtime;		

		g_currentUI->Updata();

		driver->beginScene(true, true, SColor(255,100,101,140));
		smgr->drawAll();
		if (device->getGUIEnvironment() != NULL)
		{
			device->getGUIEnvironment()->drawAll(); 
		}		
		driver->endScene();

		/*int fps = driver->getFPS();

		if (lastFPS != fps)
		{
			core::stringw str = L"MyCS —— By Tian QQ:78001229 FPS:";
			str += fps;

			device->setWindowCaption(str.c_str());
			lastFPS = fps;
		}*/
	}	
	return 0;
}
Пример #19
0
// initilazitions editorView ..
void Editor::initEditorView(){

	// Receiver ..
	myRecEditorView = new MastEventReceiver();

#if defined(_WIN32) || defined(_WIN64)
	// create Device.
	deviceEditorView = createDevice(video::EDT_OPENGL, dimension2d<u32>(EDITORVIEW_SCREEN_WIDTH, EDITORVIEW_SCREEN_HEIGHT), 16, false, false, false, myRecEditorView);

#else

	// create Device.
	deviceEditorView = createDevice(video::EDT_OPENGL, dimension2d<u32>(EDITORVIEW_SCREEN_WIDTH, EDITORVIEW_SCREEN_HEIGHT), 16, false, false, false, myRecEditorView);
#endif

	if (!deviceEditorView) // Errors creating device.
		return;

	// set Header of Window .
	deviceEditorView->setWindowCaption(L"Editor View");
	// Video driver ..
	driverEditorView = deviceEditorView->getVideoDriver();
	// Scene Manager.
	smgrEditorView = deviceEditorView->getSceneManager();
	//gui Environment
	guienvEditorView = deviceEditorView->getGUIEnvironment();
	//Create Edit box
	eBoxEditorView = guienvEditorView->addEditBox(L"", rect<s32>(10, 10, 400, 22), true, 0, 102);
	// Scene NODES ..

	editorViewParentNode = smgrEditorView->addEmptySceneNode();
	editorViewParentNode->setVisible(true);
	editorViewChildNode = smgrEditorView->addSphereSceneNode();
	nodeEditorViewCurrMouse = editorViewChildNode->clone();

	if (editorViewChildNode && nodeEditorViewCurrMouse){ // Child Node sets .
		editorViewChildNode->setMaterialFlag(EMF_LIGHTING, false);
		editorViewChildNode->setScale(editorViewChildNode->getScale()*0.75f);
#if defined(_WIN32) || defined(_WIN64)
		editorViewChildNode->setMaterialTexture(0, driverEditorView->getTexture("media/blueTexture.png"));

#else

		editorViewChildNode->setMaterialTexture(0, driverEditorView->getTexture("../media/blueTexture.png"));
#endif

		editorViewChildNode->setVisible(false);
		nodeEditorViewCurrMouse->setMaterialFlag(EMF_LIGHTING, false);
		nodeEditorViewCurrMouse->setScale(nodeEditorViewCurrMouse->getScale()*1.3f);
#if defined(_WIN32) || defined(_WIN64)
		nodeEditorViewCurrMouse->setMaterialTexture(0, driverEditorView->getTexture("media/redTexture.png"));

#else

		nodeEditorViewCurrMouse->setMaterialTexture(0, driverEditorView->getTexture("../media/redTexture.png"));
#endif

		nodeEditorViewCurrMouse->setVisible(true);
	}
	// add camera
	editorViewCam = smgrEditorView->addCameraSceneNode(0, vector3df(0, 0, CAM_POS_DEFAULT), vector3df(0, 0, -CAM_POS_DEFAULT));
	// Editor view Camera ..
	CAMPOSX = 0;
	CAMPOSY = 0;
	CAMPOSZ = -105;
	ROTX = 0;
	ROTY = 0;
	ROTZ = 0;
	editorViewParentNode->addChild(nodeEditorViewCurrMouse);
	smgrEditorView->setActiveCamera(editorViewCam);
}
Пример #20
0
int main(int argc, const char** argv)
{
/*	- deviceType: Type of the device. This can currently be the Null-device,
	   one of the two software renderers, D3D8, D3D9, or OpenGL. In this
	   example we use EDT_SOFTWARE, but to try out, you might want to
	   change it to EDT_BURNINGSVIDEO, EDT_NULL, EDT_DIRECT3D8,
	   EDT_DIRECT3D9, or EDT_OPENGL.
	*/
	MyEventReceiver receiver;
	ISoundEngine* music = createIrrKlangDevice();
	IrrlichtDevice *device =
		createDevice( EDT_DIRECT3D9, dimension2d<u32>(640, 480), 32,
			false, false, false, &receiver);

	music->play2D("../media/MUSIC/Dark Impetus.mp3",true,false,true);

	IVideoDriver* driver = device->getVideoDriver();
	ISceneManager* smgr = device->getSceneManager();
	IGUIEnvironment* guienv = device->getGUIEnvironment();
	ICameraSceneNode *camera = smgr->addCameraSceneNode();
	IGUIFont* font = device->getGUIEnvironment()->getFont("../media/fonthaettenschweiler.bmp");
	camera->setFarValue(900);

	IAnimatedMesh* map = smgr->getMesh(DC_01);
	IAnimatedMeshSceneNode* mapnode = smgr->addAnimatedMeshSceneNode(map);
	mapnode->setMaterialFlag(EMF_LIGHTING,false);

	IAnimatedMesh* player1 = smgr->getMesh(SORA);
	IAnimatedMeshSceneNode* p1node = smgr->addAnimatedMeshSceneNode(player1);
	p1node->setMaterialFlag(EMF_LIGHTING, false);
	p1node->setScale(SORA_VECTOR3D);

	IAnimatedMesh* player2 = smgr->getMesh(AQUA);
	IAnimatedMeshSceneNode* p2node = smgr->addAnimatedMeshSceneNode(player2);
	p2node->setMaterialFlag(EMF_LIGHTING, false);
	p2node->setScale(NORMAL_VECTOR3D);

	vector3df Position = p1node->getPosition();
	vector3df P2Pos = p2node->getPosition();
	vector3df PosCam = p1node->getPosition();
	vector3df Rotate = p1node->getPosition();

	int CurrentHP = 300;
	int MaxHP = 400;
	int HeartP = 10;
	bool LockOn = false;
	bool LockCheck = false;
	stringw CoorCheck;

	while(device->run())
	{
		CoorCheck +=L"Your position\nX:";
		CoorCheck +=Position.X;
		CoorCheck +=L"\nY:";
		CoorCheck +=Position.Y;
		CoorCheck +=L"\nZ:";
		CoorCheck +=Position.Z;
		CoorCheck +=L"\n\nTarget Position:";
		CoorCheck +=P2Pos.X;
		if(LockCheck != true){
			if(receiver.IsKeyDown(KEY_KEY_J)){LockOn = true; LockCheck = true;}}
		else{
			if(receiver.IsKeyDown(KEY_KEY_J)){LockOn = false;LockCheck = false;}}

		//3D Rendering.
		MaximizeKey(receiver,device);
		GetCaption(driver,device);
		driver->beginScene(true, true, SColor(255,100,101,140));
		p1node->setPosition(Position);
		camera->setPosition(vector3df(PosCam.X,PosCam.Y+2,PosCam.Z+3));
		if(LockOn != false){camera->setTarget(P2Pos);}
		else{camera->setTarget(Position);}
		smgr->drawAll();

		//2D Rendering.
		if(CurrentHP<=0){font->draw(L"You are dead!!!",rect<s32>(120,140,250,210),SColor(255,255,255,255));}
		else{if(receiver.IsKeyDown(KEY_KEY_L)){--CurrentHP;}}
		if(CurrentHP>=MaxHP){}else{if(receiver.IsKeyDown(KEY_KEY_K)){++CurrentHP;}}

		if(receiver.IsKeyDown(KEY_KEY_N)){++MaxHP;}
		if(receiver.IsKeyDown(KEY_KEY_M) && CurrentHP<MaxHP){--MaxHP;}
		if(HeartP>=86){}else{
			if(receiver.IsKeyDown(KEY_KEY_F)){++HeartP;}}

		font->draw
		(L"Press O for full screen.\nPress Up-Down-Left-right to move.\nPress L to hurt the character.\nPress K to heal the character.\nPress N to increase Max HP.\nPress M to decrease Max HP.\nPress F to fill the Heart gauge.",rect<s32>(20,40,150,110),SColor(255,0,0,0));
		font->draw(CoorCheck,rect<s32>(20,140,150,110),SColor(255,0,0,0));

		//Button detection.
		if(receiver.IsKeyDown(KEY_UP)){
			Position.Z -= 0.1f;
			PosCam.Z = Position.Z;
			p1node->setRotation(vector3df(Rotate.X,Rotate.Y = 0,Rotate.Z));
			p1node->setPosition(Position);}
		if(receiver.IsKeyDown(KEY_DOWN)){
			Position.Z += 0.1f;
			PosCam.Z = Position.Z;
			p1node->setRotation(vector3df(Rotate.X,Rotate.Y -180,Rotate.Z));
			p1node->setPosition(Position);}
		if(receiver.IsKeyDown(KEY_LEFT)){
			Position.X += 0.1f;
			PosCam.X = Position.X;
			p1node->setRotation(vector3df(Rotate.X,Rotate.Y -90,Rotate.Z));
			p1node->setPosition(Position);}
		if(receiver.IsKeyDown(KEY_RIGHT)){
			Position.X -= 0.1f;
			PosCam.X = Position.X;
			p1node->setRotation(vector3df(Rotate.X,Rotate.Y +90,Rotate.Z));
			p1node->setPosition(Position);}

		HUD_Display(device,driver,receiver,font,CurrentHP,MaxHP,HeartP);

		guienv->drawAll();
		CoorCheck = L"";
		driver->endScene();
	}
	music->drop();
	device->drop();
	return 0;
}
Пример #21
0
void VulkanBase::createInstance() {
    // Application info init
    const VkApplicationInfo applicationInfo = {
        .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
        .pNext = NULL,
        .pApplicationName = name.c_str(),
        .applicationVersion = 1,
        .pEngineName = engineName.c_str(),
        .engineVersion = 1,
        .apiVersion = VK_API_VERSION,       //FIXME  Nvidia driver not updated to latest Vulkan Version
    };


    VkInstanceCreateInfo instanceCreateInfo = {
        .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
        .pNext = NULL,
        .flags = VK_FLAGS_NONE,
        .pApplicationInfo = &applicationInfo,
        .enabledLayerCount = 0,
        .ppEnabledLayerNames = NULL,
        .enabledExtensionCount = 0,
        .ppEnabledExtensionNames = NULL,
    };

    std::vector<const char*> enabledExtensions = { VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_XCB_SURFACE_EXTENSION_NAME};
    //Check if extensions are present
    vkUtils::checkGlobalExtensionPresent(VK_KHR_SURFACE_EXTENSION_NAME);
    vkUtils::checkGlobalExtensionPresent(VK_KHR_XCB_SURFACE_EXTENSION_NAME);

#ifdef _DEBUG
    if (enableValidation) {
        //Extensions management
        enabledExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
        vkUtils::checkGlobalExtensionPresent(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);

        // Layer management
        instanceCreateInfo.enabledLayerCount = vkDebug::validationLayerCount;
        instanceCreateInfo.ppEnabledLayerNames = vkDebug::validationLayerNames;
        // Check standard debug layers are present
        for(uint32_t i = 0; i < instanceCreateInfo.enabledLayerCount; i++) {
            vkUtils::checkGlobalLayerPresent(vkDebug::validationLayerNames[i]);
        }
    }
#endif // DEBUG

    instanceCreateInfo.ppEnabledExtensionNames = enabledExtensions.data();
    instanceCreateInfo.enabledExtensionCount = (uint32_t) enabledExtensions.size();

    CHECK_RESULT(vkCreateInstance(&instanceCreateInfo, nullptr, &instance));
}




void VulkanBase::selectVkPhysicalDevice() {
    uint32_t physicalDeviceCount = 0;
    CHECK_RESULT(vkEnumeratePhysicalDevices(instance,&physicalDeviceCount,nullptr));

    if (physicalDeviceCount<=0) {
        ERROR("No physical device found");
    }

    std::vector<VkPhysicalDevice> physicalDevicesVector(physicalDeviceCount);
    CHECK_RESULT(vkEnumeratePhysicalDevices(instance,&physicalDeviceCount,physicalDevicesVector.data()));

#ifdef _DEBUG
    int deviceIndex = 0;
    for(const auto & phyDev : physicalDevicesVector) {
        VkPhysicalDeviceProperties phyDevProperties;
        vkGetPhysicalDeviceProperties(phyDev, &phyDevProperties);

        std::cout << "--- Physical device: " << phyDevProperties.deviceName << " (index: " << (deviceIndex++) << ")" << std::endl;
        std::cout << "        apiVersion: " << phyDevProperties.apiVersion << std::endl;
        std::cout << "     driverVersion: " << phyDevProperties.driverVersion << std::endl;
        std::cout << "          vendorID: " << phyDevProperties.vendorID << std::endl;
        std::cout << "          deviceID: " << phyDevProperties.deviceID << std::endl;
        std::cout << "        deviceType: ";
        switch(phyDevProperties.deviceType) {
        case VK_PHYSICAL_DEVICE_TYPE_OTHER:
            std::cout << "OTHER";
            break;
        case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
            std::cout << "INTEGRATED_GPU";
            break;
        case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
            std::cout << "DISCRETE_GPU";
            break;
        case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
            std::cout << "VIRTUAL_GPU";
            break;
        case VK_PHYSICAL_DEVICE_TYPE_CPU:
            std::cout << "CPU";
            break;
        default:
            std::cout << "UNKNOWN!!!";
            break;
        }

        std::cout << std::endl;
    }
#endif // _DEBUG

    physicalDevice = physicalDevicesVector.at(0);

    // Gather Physical Device Memory Properties
    vkGetPhysicalDeviceMemoryProperties(physicalDevice,&physicalDeviceMemoryProperties);

}

void VulkanBase::selectQueue() {
    uint32_t queueFamilyPropertyCount = 0;

    vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice,&queueFamilyPropertyCount,nullptr);
    if (queueFamilyPropertyCount<=0)
        ERROR("Physical device has no queue families");

    std::vector<VkQueueFamilyProperties> queueFamilyPropertiesVector(queueFamilyPropertyCount);
    vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice,&queueFamilyPropertyCount,queueFamilyPropertiesVector.data());

    uint32_t queueFamilyIndex = 0;
    int32_t selectedQueueFamilyIndex = -1;
    VkBool32 presentSupport = VK_FALSE;

#ifdef _DEBUG
    std::cout << std::endl << "--- Number of queue families " << queueFamilyPropertyCount << std::endl;
#endif // _DEBUG

    for(const auto & queueFamProp : queueFamilyPropertiesVector) {
        CHECK_RESULT(vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, queueFamilyIndex, swapchain.surface, &presentSupport));
#ifdef _DEBUG
        std::cout << "--- Properties for queue family " << queueFamilyIndex << std::endl;
        std::cout << "                     queueFlags:";

        if(queueFamProp.queueFlags & VK_QUEUE_GRAPHICS_BIT)
            std::cout << " G";
        if(queueFamProp.queueFlags & VK_QUEUE_COMPUTE_BIT)
            std::cout << " C";
        if(queueFamProp.queueFlags & VK_QUEUE_TRANSFER_BIT)
            std::cout << " T";
        if(queueFamProp.queueFlags & VK_QUEUE_SPARSE_BINDING_BIT)
            std::cout << " S";

        std::cout << '\n';
        std::cout << "                     queueCount: " << queueFamProp.queueCount << std::endl;
        std::cout << "             timestampValidBits: " << queueFamProp.timestampValidBits << std::endl;
        std::cout << "    minImageTransferGranularity: " << queueFamProp.minImageTransferGranularity.width
                  << ", " << queueFamProp.minImageTransferGranularity.height
                  << ", " << queueFamProp.minImageTransferGranularity.depth
                  << std::endl;

        std::cout << "       Supports present?: " << std::boolalpha << bool(presentSupport) << std::endl << std::endl;
#endif // _DEBUG

        if (bool(queueFamProp.queueFlags & VK_QUEUE_GRAPHICS_BIT) && presentSupport == VK_TRUE) {
            if (selectedQueueFamilyIndex < 0)
                selectedQueueFamilyIndex = queueFamilyIndex;
        }
        queueFamilyIndex++;
    }

    if (selectedQueueFamilyIndex<0)
        ERROR("No queue with both graphics and present capabilities found");

    // Create device after selecting the queue
    std::array<float,1> queuePriorities = {0.0f};

    VkDeviceQueueCreateInfo queueCreateInfo = {
        .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
        .pNext = nullptr,
        .flags = VK_FLAGS_NONE,
        .queueFamilyIndex = (uint32_t) selectedQueueFamilyIndex,
        .queueCount = 1,                            //Number of queues to create
        .pQueuePriorities = queuePriorities.data()
    };

    // Call to createDevice
    createDevice(queueCreateInfo,1);

    //Get a handle to the selected queue
    vkGetDeviceQueue(device, (uint32_t) selectedQueueFamilyIndex, 0, &queue);      //TODO get handle if using multiple queues
    queueFamilyIndex = (uint32_t) selectedQueueFamilyIndex;

}


void VulkanBase::createDevice(VkDeviceQueueCreateInfo requestedQueues, uint32_t requestedQueuesCount) {
    //Check extensions available on the selected physical device before creating it
    // Check swap chain extension
    vkUtils::checkDeviceExtensionPresent(physicalDevice,VK_KHR_SWAPCHAIN_EXTENSION_NAME);
    std::vector<const char*> enabledExtensions = {VK_KHR_SWAPCHAIN_EXTENSION_NAME};

    VkDeviceCreateInfo deviceCreateInfo = {
        .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
        .pNext = nullptr,
        .flags = VK_FLAGS_NONE,
        .queueCreateInfoCount = requestedQueuesCount,
        .pQueueCreateInfos = &requestedQueues,
        .enabledLayerCount = 0,
        .ppEnabledLayerNames = nullptr,
        .enabledExtensionCount = (uint32_t) enabledExtensions.size(),
        .ppEnabledExtensionNames = enabledExtensions.data(),
        .pEnabledFeatures = NULL
    };

#ifdef _DEBUG
    if (enableValidation) {
        deviceCreateInfo.enabledLayerCount = vkDebug::validationLayerCount;
        deviceCreateInfo.ppEnabledLayerNames = vkDebug::validationLayerNames;
        // Check standard debug layers are present on the device
        for(uint32_t i = 0; i < deviceCreateInfo.enabledLayerCount; i++) {
            vkUtils::checkGlobalLayerPresent(vkDebug::validationLayerNames[i]);
        }
    }
#endif // _DEBUG

    CHECK_RESULT(vkCreateDevice(physicalDevice, &deviceCreateInfo, nullptr, &device));
}

void VulkanBase::createCommandPool(const uint32_t queueFamilyIndex, const VkCommandPoolCreateFlagBits createFlagBits) {
    const VkCommandPoolCreateInfo commandPoolCreateInfo= {
        .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
        .pNext = NULL,
        .flags = createFlagBits,
        .queueFamilyIndex = queueFamilyIndex
    };

    CHECK_RESULT(vkCreateCommandPool(device, &commandPoolCreateInfo,nullptr,&commandPool));

#ifdef _DEBUG
    std::cout << "\n+++ Created command pool" << std::endl;
#endif // _DEBUG
}

void VulkanBase::createSynchroItems()
{
    // Semaphores

    VkSemaphoreCreateInfo semaphoreCreateInfo = {
        .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
        .pNext = NULL,
        .flags = VK_FLAGS_NONE
    };

    // Semaphore signaled on swapchain image ready to use and wait on the queue before rendering/present
    CHECK_RESULT(vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &imageAcquiredSemaphore));

    // Semaphore signaled on queue rendering termination and waited on present operation
    CHECK_RESULT(vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &renderingCompletedSemaphore));

    // Fences

    VkFenceCreateInfo fenceCreateInfo = {
        .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
        .pNext = NULL,
        .flags = VK_FLAGS_NONE
    };

    CHECK_RESULT(vkCreateFence(device, &fenceCreateInfo, nullptr, &presentFence));

    #ifdef _DEBUG
    std::cout << "\n+++ Created semaphores and fences\n";
    #endif // _DEBUG
}



void VulkanBase::createCommandBuffers(VkCommandBuffer* cmdBuffer, uint32_t commandBufferCount, VkCommandBufferLevel cmdBufferLevel)
{
    const VkCommandBufferAllocateInfo commandBufferAllocateInfo = {
        .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
        .pNext = NULL,
        .commandPool = commandPool,
        .level = cmdBufferLevel,
        .commandBufferCount = commandBufferCount
    };

    CHECK_RESULT(vkAllocateCommandBuffers(device, &commandBufferAllocateInfo, cmdBuffer));

    #ifdef _DEBUG
    std::cout << "\n+++ Allocated " << commandBufferCount << " command buffers" << std::endl;
    #endif // _DEBUG
}

void VulkanBase::setupInitCommandBuffer()
{
    VkCommandBufferBeginInfo commandBufferBeginInfo = {
        .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
        .pNext = NULL,
        .flags = VK_FLAGS_NONE,
        .pInheritanceInfo = NULL
    };

    CHECK_RESULT(vkBeginCommandBuffer(initCommandBuffer, &commandBufferBeginInfo));

    // Creates an image memory barrier to change the layout for every image on the swapchain
    VkImageMemoryBarrier imageMemoryBarrier = {
        .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
        .pNext = NULL,
        .srcAccessMask = VK_FLAGS_NONE,
        .dstAccessMask = VK_FLAGS_NONE,
        .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
        .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
        .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
        .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
        .image = 0,
        .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}
    };


	// Pipeline Barrier for each swapchain image
    for (const auto& image: swapchain.swapchainImagesVector){
        imageMemoryBarrier.image = image;

        vkCmdPipelineBarrier(initCommandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, //Put barrier on top of the pipeline
        VK_FLAGS_NONE,
        0, nullptr,                 // memoryBarrier
        0, nullptr,                 // bufferMemoryBarrier
        1, &imageMemoryBarrier);    // imageMemoryBarrier
    }

    CHECK_RESULT(vkEndCommandBuffer(initCommandBuffer));

    #ifdef _DEBUG
    std::cout << "\n+++ Finished recording initCommandBuffer\n";
    #endif // _DEBUG
}

void VulkanBase::setupPresentCommandBuffer(const VkImage currentSwapchainImage, const float* clearColors)
{

 VkCommandBufferBeginInfo commandBufferBeginInfo = {
        .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
        .pNext = NULL,
        .flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
        .pInheritanceInfo = NULL
    };

    CHECK_RESULT(vkBeginCommandBuffer(presentCommandBuffer, &commandBufferBeginInfo));

    VkImageMemoryBarrier imageMemoryBarrier = {
        .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
        .pNext = NULL,
        .srcAccessMask = VK_ACCESS_MEMORY_READ_BIT,
        .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
        .oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
        .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
        .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
        .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
        .image = currentSwapchainImage,
        .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}
    };

    //Set barrier on top to change layout and access
    vkCmdPipelineBarrier(presentCommandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
    VK_FLAGS_NONE, 0, nullptr, 0, nullptr, 1, &imageMemoryBarrier);

    VkClearColorValue clearColorValue;
    VkImageSubresourceRange imageSubresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};

    clearColorValue.float32[0] = clearColors[0];
    clearColorValue.float32[1] = clearColors[1];
    clearColorValue.float32[2] = clearColors[2];
    clearColorValue.float32[3] = 1.0f;

    // Command to clear the swapchain image
    vkCmdClearColorImage(presentCommandBuffer,currentSwapchainImage,
    VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &clearColorValue, 1, &imageSubresourceRange);

    /*
	 * Transition the swapchain image from VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
	 * to VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
	 */
	imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
	imageMemoryBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
	imageMemoryBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
	imageMemoryBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;

    // Set barrier end of pipeline
	vkCmdPipelineBarrier(presentCommandBuffer,
		VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
		0, 0, nullptr, 0, nullptr, 1, &imageMemoryBarrier
	);

    CHECK_RESULT(vkEndCommandBuffer(presentCommandBuffer));

    #ifdef _DEBUG
    //std::cout << "\n+++ Finished recording presentCommandBuffer\n";
    #endif // _DEBUG
}

void VulkanBase::renderFrame(const float* clearColors)
{
    // Wait on previous frame fence (render too fast)
    //CHECK_RESULT(vkWaitForFences(device, 1, &presentFence, VK_TRUE, UINT64_MAX));
    //CHECK_RESULT(vkResetFences(device, 1, &presentFence));

    // Acquire next image on the swapchain
    uint32_t imageIndex = UINT64_MAX;
    CHECK_RESULT(vkAcquireNextImageKHR(device, swapchain.swapchain, UINT64_MAX, imageAcquiredSemaphore, VK_NULL_HANDLE, &imageIndex));

    // Setup the present command buffer
    setupPresentCommandBuffer(swapchain.swapchainImagesVector.at(imageIndex),clearColors);
    // Submit present command buffer to the queue
    // Waits on imageAcquiredSemaphore so it doesnt start rendering until the image from the swapchain is ready and
    // it also signals the renderingCompletedSemaphore used by the later present

    VkPipelineStageFlags pipelineStageFlags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
    VkSubmitInfo submitInfo = {
        .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
        .pNext = NULL,
        .waitSemaphoreCount = 1,
        .pWaitSemaphores = &imageAcquiredSemaphore,
        .pWaitDstStageMask = &pipelineStageFlags,
        .commandBufferCount = 1,
        .pCommandBuffers = &presentCommandBuffer,
        .signalSemaphoreCount = 1,
        .pSignalSemaphores = &renderingCompletedSemaphore
    };

    CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));

    // Present the rendered image
    VkPresentInfoKHR presentInfo = {
        .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
        .pNext = NULL,
        .waitSemaphoreCount = 1,
        .pWaitSemaphores = &renderingCompletedSemaphore,
        .swapchainCount = 1,
        .pSwapchains = &swapchain.swapchain,
        .pImageIndices = &imageIndex,
        .pResults = nullptr
    };

    CHECK_RESULT(vkQueuePresentKHR(queue,&presentInfo));

    CHECK_RESULT(vkQueueWaitIdle(queue)); //TODO Not sure this is the correct way...


}



void VulkanBase::prepare()
{
    //Allocate command Buffers
    createCommandBuffers(&initCommandBuffer, 1, VK_COMMAND_BUFFER_LEVEL_PRIMARY);
    createCommandBuffers(&presentCommandBuffer, 1, VK_COMMAND_BUFFER_LEVEL_PRIMARY);
    commandBuffersVector.push_back(initCommandBuffer);
    commandBuffersVector.push_back(presentCommandBuffer);
    //Initialize command Buffers
    setupInitCommandBuffer();
    // Submit initialization command buffer to the queue
    VkSubmitInfo submitInfo = {
        .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
        .pNext = nullptr,
        .waitSemaphoreCount = 0,
        .pWaitSemaphores = nullptr,
        .pWaitDstStageMask = VK_FLAGS_NONE,
        .commandBufferCount = 1,
        .pCommandBuffers = &initCommandBuffer,
        .signalSemaphoreCount = 0,
        .pSignalSemaphores = nullptr
    };

    CHECK_RESULT(vkQueueSubmit(queue,1,&submitInfo, VK_NULL_HANDLE));

    CHECK_RESULT(vkQueueWaitIdle(queue));

    vkFreeCommandBuffers(device, commandPool, 1, &initCommandBuffer);

#ifdef _DEBUG
    std::cout << "\n+++ initCommandBuffer work complete!\n";
    std::cout << "\n******* Rendering Start ******\n";
#endif // _DEBUG

}
Пример #22
0
//-----------------------------------------------------------------------------
// Initialize - create window, device, etc
//-----------------------------------------------------------------------------
void GFXPCD3D9Device::init( const GFXVideoMode &mode, PlatformWindow *window /* = NULL */ )
{
   AssertFatal(window, "GFXPCD3D9Device::init - must specify a window!");

   initD3DXFnTable();

   Win32Window *win = dynamic_cast<Win32Window*>( window );
   AssertISV( win, "GFXD3D9Device::init - got a non Win32Window window passed in! Did DX go crossplatform?" );

   HWND winHwnd = win->getHWND();

   // Create D3D Presentation params
   D3DPRESENT_PARAMETERS d3dpp = setupPresentParams( mode, winHwnd );
   mMultisampleType = d3dpp.MultiSampleType;
   mMultisampleLevel = d3dpp.MultiSampleQuality;
      
#ifndef TORQUE_SHIPPING
   bool usePerfHud = GFXPCD3D9Device::mEnableNVPerfHUD || Con::getBoolVariable("$Video::useNVPerfHud", false);   
#else
   bool usePerfHud = false;
#endif

   HRESULT hres = E_FAIL;
   if ( usePerfHud )
   {  
      hres = createDevice(  mD3D->GetAdapterCount() - 1, D3DDEVTYPE_REF, winHwnd, D3DCREATE_MIXED_VERTEXPROCESSING, &d3dpp);
   }
   else 
   {
      // Vertex processing was changed from MIXED to HARDWARE because of the switch to a pure D3D device.

      // Set up device flags from our compile flags.
      U32 deviceFlags = 0;
      deviceFlags = D3DCREATE_HARDWARE_VERTEXPROCESSING;

      // Currently, offscreen rendering is only used by WPF apps and we need to create with D3DCREATE_MULTITHREAD for it
      // In all other cases, you can do better by locking/creating resources in the primary thread
      // and passing them to worker threads.
      if (window->getOffscreenRender())
      {
         deviceFlags |= D3DCREATE_MULTITHREADED;
         d3dpp.Windowed = TRUE;
         d3dpp.BackBufferHeight = 1;
         d3dpp.BackBufferWidth = 1;
         d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
         d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
         d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
      }

      // DirectX will switch the floating poing control word to single precision
      // and disable exceptions by default.  There are a few issues with this...
      //
      // 1. It can cause rendering problems when running in WPF.
      // 2. Firefox embedding issues.
      // 3. Physics engines depend on the higher precision.
      //
      // Interestingly enough... DirectX 10 and 11 do not modifiy the floating point
      // settings and are always in full precision.
      //
      // The down side is we supposedly loose some performance, but so far i've not
      // seen a measurable impact.
      // 
      deviceFlags |= D3DCREATE_FPU_PRESERVE;

      // Try to do pure, unless we're doing debug (and thus doing more paranoid checking).
#ifndef TORQUE_DEBUG_RENDER
      deviceFlags |= D3DCREATE_PUREDEVICE;
#endif

      hres = createDevice( mAdapterIndex, D3DDEVTYPE_HAL, winHwnd, deviceFlags, &d3dpp);

      if (FAILED(hres) && hres != D3DERR_OUTOFVIDEOMEMORY)
      {
         Con::errorf("   Failed to create hardware device, trying mixed device");
         // turn off pure
         deviceFlags &= (~D3DCREATE_PUREDEVICE);

         // try mixed mode
         deviceFlags &= (~D3DCREATE_HARDWARE_VERTEXPROCESSING);
         deviceFlags |= D3DCREATE_MIXED_VERTEXPROCESSING;
         hres = createDevice( mAdapterIndex, D3DDEVTYPE_HAL, 
            winHwnd, deviceFlags, 
            &d3dpp);

         // try software 
         if (FAILED(hres) && hres != D3DERR_OUTOFVIDEOMEMORY)
         {
            Con::errorf("   Failed to create mixed mode device, trying software device");
            deviceFlags &= (~D3DCREATE_MIXED_VERTEXPROCESSING);
            deviceFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
            hres = createDevice( mAdapterIndex, D3DDEVTYPE_HAL, 
               winHwnd, deviceFlags,
               &d3dpp);

            if (FAILED(hres) && hres != D3DERR_OUTOFVIDEOMEMORY)
               Con::errorf("   Failed to create software device, giving up");
            D3D9Assert(hres, "GFXPCD3D9Device::init - CreateDevice failed!");
         }
      }
   }

   // Gracefully die if they can't give us a device.
   if(!mD3DDevice)
   {
      if (hres == D3DERR_OUTOFVIDEOMEMORY)
      {
         char errorMsg[4096];
         dSprintf(errorMsg, sizeof(errorMsg),
            "Out of video memory. Close other windows, reboot, and/or upgrade your video card drivers. Your video card is: %s", getAdapter().getName());
         Platform::AlertOK("DirectX Error", errorMsg);
      }
      else
      {
         Platform::AlertOK("DirectX Error!", "Failed to initialize Direct3D! Make sure you have DirectX 9 installed, and "
            "are running a graphics card that supports Pixel Shader 1.1.");
      }
      Platform::forceShutdown(1);
   }

   // Check up on things
   Con::printf("   Cur. D3DDevice ref count=%d", mD3DDevice->AddRef() - 1);
   mD3DDevice->Release();
   
   mTextureManager = new GFXD3D9TextureManager( mD3DDevice, mAdapterIndex );

   // Now reacquire all the resources we trashed earlier
   reacquireDefaultPoolResources();
      
   // Setup default states
   initStates();

   //-------- Output init info ---------   
   D3DCAPS9 caps;
   mD3DDevice->GetDeviceCaps( &caps );

   U8 *pxPtr = (U8*) &caps.PixelShaderVersion;
   mPixVersion = pxPtr[1] + pxPtr[0] * 0.1;
   if (mPixVersion >= 2.0f && mPixVersion < 3.0f && caps.PS20Caps.NumTemps >= 32)
      mPixVersion += 0.2f;
   else if (mPixVersion >= 2.0f && mPixVersion < 3.0f && caps.PS20Caps.NumTemps >= 22)
      mPixVersion += 0.1f;
   Con::printf( "   Pix version detected: %f", mPixVersion );

   if ( smForcedPixVersion >= 0.0f && smForcedPixVersion < mPixVersion )
   {
      mPixVersion = smForcedPixVersion;
      Con::errorf( "   Forced pix version: %f", mPixVersion );
   }

   U8 *vertPtr = (U8*) &caps.VertexShaderVersion;
   F32 vertVersion = vertPtr[1] + vertPtr[0] * 0.1;
   Con::printf( "   Vert version detected: %f", vertVersion );

   // The sampler count is based on the shader model and
   // not found in the caps.
   //
   // MaxSimultaneousTextures is only valid for fixed
   // function rendering.
   //
   if ( mPixVersion >= 2.0f )
      mNumSamplers = 16;
   else if ( mPixVersion >= 1.4f )
      mNumSamplers = 6;
   else if ( mPixVersion > 0.0f )
      mNumSamplers = 4;
   else
      mNumSamplers = caps.MaxSimultaneousTextures;      

   // This shouldn't happen until SM5 or some other
   // radical change in GPU hardware occurs.
   AssertFatal( mNumSamplers <= TEXTURE_STAGE_COUNT, 
      "GFXPCD3D9Device::init - Sampler count greater than TEXTURE_STAGE_COUNT!" );
            
   Con::printf( "   Maximum number of simultaneous samplers: %d", mNumSamplers );

   // detect max number of simultaneous render targets
   mNumRenderTargets = caps.NumSimultaneousRTs;
   Con::printf( "   Number of simultaneous render targets: %d", mNumRenderTargets );
   
   // detect occlusion query support
   if (SUCCEEDED(mD3DDevice->CreateQuery( D3DQUERYTYPE_OCCLUSION, NULL )))
	   mOcclusionQuerySupported = true;
      
   Con::printf( "   Hardware occlusion query detected: %s", mOcclusionQuerySupported ? "Yes" : "No" );      

   Con::printf( "   Using Direct3D9Ex: %s", isD3D9Ex() ? "Yes" : "No" );
   
   mCardProfiler = new GFXD3D9CardProfiler(mAdapterIndex);
   mCardProfiler->init();

   gScreenShot = new ScreenShotD3D;

   // Set the video capture frame grabber.
   mVideoFrameGrabber = new VideoFrameGrabberD3D9();
   VIDCAP->setFrameGrabber( mVideoFrameGrabber );

   // Grab the depth-stencil...
   SAFE_RELEASE(mDeviceDepthStencil);
   D3D9Assert(mD3DDevice->GetDepthStencilSurface(&mDeviceDepthStencil), "GFXD3D9Device::init - couldn't grab reference to device's depth-stencil surface.");  

   mInitialized = true;

   deviceInited();

   // Uncomment to dump out code needed in initStates, you may also need to enable the reference device (get rid of code in initStates first as well)
   // regenStates();
}
Пример #23
0
XM_APP_MAIN_END

KD_API KDvoid KD_APIENTRY xmEventProc ( const KDEvent* event )
{
	switch ( event->type )
	{
		case KD_EVENT_NATIVE :  
			{
//				#if !defined ( SHP ) && defined ( _WIN32 ) 
//				KDEventNativeWin32*  proc = (KDEventNativeWin32*) event->data.native.p;
//				#endif
			}
			break;
		
		case KD_EVENT_CREATE :
			{
				// event->data.size.width;
				// event->data.size.height;

				// create device and exit if creation failed
				CTutorial::s_pDevice = createDevice ( video::EDT_OGLES1, core::dimension2d<u32> ( event->data.size.width, event->data.size.height ), 32, false, false, false, 0 );
				kdAssert ( CTutorial::s_pDevice );

				CTutorial::s_pDriver = CTutorial::s_pDevice->getVideoDriver ( );
				CTutorial::SetTutorial ( 0 );
			}
			break;

		case KD_EVENT_DESTROY :      
			{
				/*
					In the end, delete the Irrlicht device.
				*/
				CTutorial::s_pDevice->drop ( );
				CTutorial::s_pDevice = KD_NULL;
			}
			break;

		case KD_EVENT_RESIZE :       

			break;

		case KD_EVENT_FOCUS :        
			{
				// event->data.value.i;
				// 1 : focus
			}
			break;

		case KD_EVENT_VISIBLE :    
			{
				// event->data.value.i;
				// 1 : visible
			}
			break;

		case KD_EVENT_REDRAW :     
			{
				CTutorial::Redraw ( );
			}
			break;

		case KD_EVENT_UPDATE :      
			{
				// event->data.update.msec;
			}
			break;

		case KD_EVENT_TOUCH_BEGAN :     
			{
				// event->data.touch.touches;
				// event->data.touch.count;
			}
			break;

		case KD_EVENT_TOUCH_MOVED :            
			{

			}
			break;

		case KD_EVENT_TOUCH_ENDED :            
			{

			}
			break;

		case KD_EVENT_TOUCH_CANCELLED :          
			{

			}
			break;

		case KD_EVENT_KEY_RELEASED :    
			{
				// event->data.keypad.code;		
			}
			break;

		case KD_EVENT_KEY_PRESSED :    
			{

			}
			break;

		case KD_EVENT_ACCELEROMETER :   
			{
				// event->data.accelerometer.x;
				// event->data.accelerometer.y;
				// event->data.accelerometer.z;
			}
			break;

		case KD_EVENT_LOCATION :                 
			{
				// event->data.value.i;
				// KD_NMEA_UPDATED_GPS, KD_NMEA_UPDATED_USER
			}
			break;

		case KD_EVENT_INSERT_TEXT :               
			{
				// event->data.insert.utf8;
			}
			break;

		case KD_EVENT_SERIALIZE :                
			{
				// event->data.serialize.type;
				// event->data.serialize.data;
				// event->data.serialize.size;
			}
			break;
	}

	if ( CTutorial::s_pDevice )
	{
		CTutorial::s_pDevice->EventProc ( event );
	}
}
Пример #24
0
bool CMainMenu::run(bool& outFullscreen, bool& outMusic, bool& outShadows,
					bool& outAdditive, bool &outVSync, video::E_DRIVER_TYPE& outDriver)
{
	device = createDevice(video::EDT_SOFTWARE2,
		core::dimension2d<s32>(512, 384), 16, false, false, false, this);

	device->getFileSystem()->addZipFileArchive("irrlicht.dat");
	device->getFileSystem()->addZipFileArchive("../../media/irrlicht.dat");

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

	core::stringw str = "Irrlicht Engine Demo v";
	str += device->getVersion();
	device->setWindowCaption(str.c_str());

	// load font

	gui::IGUIFont* font = guienv->getFont("../../media/fonthaettenschweiler.bmp");
	if (font)
		guienv->getSkin()->setFont(font);

	// add images

	//gui::IGUIImage* img = guienv->addImage(core::rect<int>(0,0,512,384));
	//img->setImage(driver->getTexture("../../media/demoback.bmp"));

	const s32 leftX = 260;

	// add tab control
	gui::IGUITabControl* tabctrl = guienv->addTabControl(core::rect<int>(leftX,10,512-10,384-10),
		0, true, true);
	gui::IGUITab* optTab = tabctrl->addTab(L"Demo");
	gui::IGUITab* aboutTab = tabctrl->addTab(L"About");

	// add list box

	gui::IGUIListBox* box = guienv->addListBox(core::rect<int>(10,10,220,105), optTab, 1);
	box->addItem(L"OpenGL 1.5");
	box->addItem(L"Direct3D 8.1");
	box->addItem(L"Direct3D 9.0c");
	box->addItem(L"Apfelbaum Software Renderer 1.0");
	box->addItem(L"Irrlicht Software Renderer 1.0");
	box->setSelected(selected);

	// add button

	startButton = guienv->addButton(core::rect<int>(30,295,200,324), optTab, 2, L"Start Demo");

	// add checkbox

	const s32 d = 50;

	guienv->addCheckBox(fullscreen, core::rect<int>(20,85+d,130,110+d),
		optTab, 3, L"Fullscreen");
	guienv->addCheckBox(music, core::rect<int>(20,110+d,130,135+d),
		optTab, 4, L"Music & Sfx");
	guienv->addCheckBox(shadows, core::rect<int>(20,135+d,230,160+d),
		optTab, 5, L"Realtime shadows");
	guienv->addCheckBox(additive, core::rect<int>(20,160+d,230,185+d),
		optTab, 6, L"Old HW compatible blending");
	guienv->addCheckBox(vsync, core::rect<int>(20,185+d,230,210+d),
		optTab, 7, L"Vertical synchronisation");

	// add text

	/*wchar_t* text = L"Welcome to the Irrlicht Engine. Please select "\
		L"the settings you prefer and press 'Start Demo'. "\
		L"Right click for changing menu style.";

	guienv->addStaticText(text, core::rect<int>(10, 220, 220, 280),
		true, true, optTab);*/

	// add about text

	wchar_t* text2 = L"This is the tech demo of the Irrlicht engine. To start, "\
		L"select a device which works best with your hardware and press 'start demo'. "\
		L"What you currently see is displayed using the Software Renderer, but this would be too slow "\
		L"for the demo. The Irrlicht Engine was written by me, Nikolaus Gebhardt. The models, "\
		L"maps and textures were placed at my disposal by B.Collins, M.Cook and J.Marton. The music was created by "\
		L"M.Rohde and is played back by Audiere.\n"\
		L"For more informations, please visit the homepage of the Irrlicht engine:\nhttp://www.irrlicht.sourceforge.net";

	guienv->addStaticText(text2, core::rect<int>(20, 40, 220, 300),
		true, true, aboutTab);


	// add md2 model

	scene::IAnimatedMesh* mesh = smgr->getMesh("../../media/faerie.md2");
	scene::IAnimatedMeshSceneNode* node = smgr->addAnimatedMeshSceneNode(mesh);
	if (node)
	{
		node->setMaterialTexture(0, driver->getTexture("../../media/faerie2.bmp"));
		node->setMaterialFlag(video::EMF_LIGHTING, true);
		node->setMD2Animation ( scene::EMAT_STAND );
	}

	// set ambient light
	driver->setAmbientLight ( video::SColorf ( 0x005F6613 ) );

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

	light1->getLightData().Type = video::ELT_DIRECTIONAL;

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

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

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

	// add light 2 (nearly green)
	scene::ILightSceneNode* light2 =
		smgr->addLightSceneNode(0, core::vector3df(0,0,0),
		video::SColorf(0.f, 0.f, 0.8f, 0.0f), 200.0f);

	light2->getLightData().Type = video::ELT_DIRECTIONAL;

	// add fly circle animator to light 2
	anim = smgr->createFlyCircleAnimator (core::vector3df(0,-10.f,0),10.0f, 0.003f);
	light2->addAnimator(anim);
	anim->drop();

	// attach billboard to the light
	bill = smgr->addBillboardSceneNode(light2, core::dimension2d<f32>(10, 10));

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

	smgr->addCameraSceneNode(0, core::vector3df(45,0,0), core::vector3df(0,0,10));

	// irrlicht logo
	// add irrlicht logo
	guienv->addImage(driver->getTexture("../../media/irrlichtlogoalpha2.tga"),
		core::position2d<s32>(5,5));

	video::ITexture* irrlichtBack = driver->getTexture("../../media/demoback.bmp");

	// set transparency
	setTransparency();

	// draw all

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

			if ( irrlichtBack )
				driver->draw2DImage(irrlichtBack,
									core::position2d<int>(0,0)
									);

			smgr->drawAll();
			guienv->drawAll();
			driver->endScene();
		}
	}

	device->drop();

	outFullscreen = fullscreen;
	outMusic = music;
	outShadows = shadows;
	outAdditive = additive;
	outVSync = vsync;

	switch(selected)
	{
	case 0:	outDriver = video::EDT_OPENGL; break;
	case 1:	outDriver = video::EDT_DIRECT3D8; break;
	case 2:	outDriver = video::EDT_DIRECT3D9; break;
	case 3:	outDriver = video::EDT_SOFTWARE2; break;
	case 4:	outDriver = video::EDT_SOFTWARE; break;
	}

	return start;
}
Пример #25
0
int main()
{
	int idCenario = 0;
	
	int quadId;

	vector3df p1, p2, p3, p4;

	SMatrix mtxCenario; 

	CArquivoMatrizes *_fileMtx = new CArquivoMatrizes();

	CSampleSceneNode *myQuad[2500];

	CGerEventos eventos;

	IrrlichtDevice *device =  createDevice(EDT_OPENGL, dimension2d<s32>(800, 600), 16, false,false,false, &eventos);

	device->setWindowCaption(L"Editor de matrizes - Warbugs");

	IVideoDriver* driver = device->getVideoDriver();
	ISceneManager* smgr = device->getSceneManager();

	

	smgr->addCameraSceneNodeFPS();
	//smgr->addCameraSceneNode(0, vector3df(0,100,0), vector3df(0,0,0));

	smgr->loadScene(pathCenario[idCenario]);
	mtxCenario = _fileMtx->getMatrix(idCenario);

	ITerrainSceneNode *sceneTerrain = (ITerrainSceneNode*)smgr->getSceneNodeFromType(ESNT_TERRAIN, 0);
	ITriangleSelector *sceneTris = smgr->createTerrainTriangleSelector(sceneTerrain, 0);
	sceneTerrain->setTriangleSelector(sceneTris);

	for(int i=0; i<50; i++) // z
	{
		for(int j=0; j<50;j++) // x
		{
			//if(
			//{
				p1.X = 10.0;
				p1.Y = 1.0;
				p1.Z = 0.0;

				p2.X = 10.0;
				p2.Y = 1.0;
				p2.Z = 500.0;

				p3.X = 0.0;
				p3.Y = 1.0;
				p3.Z = 500.0;

				p4.X = 0.0;
				p4.Y = 1.0;
				p4.Z = 0.0;

				quadId = j + (i * 10);
				myQuad[quadId] = new CSampleSceneNode(smgr->getRootSceneNode(), smgr, quadId, p1, p2, p3, p4);
			//}
		}
	}

	while(device->run())
	{
		driver->beginScene(true, true, SColor(0,100,100,100));

		smgr->drawAll();

		driver->endScene();
	}

	device->drop();

	return 0;
} 
Пример #26
0
bool Display::initialize()
{
    if (isInitialized())
    {
        return true;
    }

    mD3d9Module = LoadLibrary(TEXT("d3d9.dll"));
    if (mD3d9Module == NULL)
    {
        terminate();
        return false;
    }

    typedef IDirect3D9* (WINAPI *Direct3DCreate9Func)(UINT);
    Direct3DCreate9Func Direct3DCreate9Ptr = reinterpret_cast<Direct3DCreate9Func>(GetProcAddress(mD3d9Module, "Direct3DCreate9"));

    if (Direct3DCreate9Ptr == NULL)
    {
        terminate();
        return false;
    }

    typedef HRESULT (WINAPI *Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex**);
    Direct3DCreate9ExFunc Direct3DCreate9ExPtr = reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));

    // Use Direct3D9Ex if available. Among other things, this version is less
    // inclined to report a lost context, for example when the user switches
    // desktop. Direct3D9Ex is available in Windows Vista and later if suitable drivers are available.
    if (Direct3DCreate9ExPtr && SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &mD3d9ex)))
    {
        ASSERT(mD3d9ex);
        mD3d9ex->QueryInterface(IID_IDirect3D9, reinterpret_cast<void**>(&mD3d9));
        ASSERT(mD3d9);
    }
    else
    {
        mD3d9 = Direct3DCreate9Ptr(D3D_SDK_VERSION);
    }

    if (mD3d9)
    {
        if (mDc != NULL)
        {
        //  UNIMPLEMENTED();   // FIXME: Determine which adapter index the device context corresponds to
        }

        HRESULT result = mD3d9->GetDeviceCaps(mAdapter, mDeviceType, &mDeviceCaps);

        if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY)
        {
            return error(EGL_BAD_ALLOC, false);
        }

        if (mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
        {
            terminate();
            return error(EGL_NOT_INITIALIZED, false);
        }

        mMinSwapInterval = 4;
        mMaxSwapInterval = 0;

        if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE) {mMinSwapInterval = std::min(mMinSwapInterval, 0); mMaxSwapInterval = std::max(mMaxSwapInterval, 0);}
        if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE)       {mMinSwapInterval = std::min(mMinSwapInterval, 1); mMaxSwapInterval = std::max(mMaxSwapInterval, 1);}
        if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_TWO)       {mMinSwapInterval = std::min(mMinSwapInterval, 2); mMaxSwapInterval = std::max(mMaxSwapInterval, 2);}
        if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_THREE)     {mMinSwapInterval = std::min(mMinSwapInterval, 3); mMaxSwapInterval = std::max(mMaxSwapInterval, 3);}
        if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_FOUR)      {mMinSwapInterval = std::min(mMinSwapInterval, 4); mMaxSwapInterval = std::max(mMaxSwapInterval, 4);}

        const D3DFORMAT renderTargetFormats[] =
        {
            D3DFMT_A1R5G5B5,
        //  D3DFMT_A2R10G10B10,   // The color_ramp conformance test uses ReadPixels with UNSIGNED_BYTE causing it to think that rendering skipped a colour value.
            D3DFMT_A8R8G8B8,
            D3DFMT_R5G6B5,
            D3DFMT_X1R5G5B5,
            D3DFMT_X8R8G8B8
        };

        const D3DFORMAT depthStencilFormats[] =
        {
        //  D3DFMT_D16_LOCKABLE,
            D3DFMT_D32,
        //  D3DFMT_D15S1,
            D3DFMT_D24S8,
            D3DFMT_D24X8,
        //  D3DFMT_D24X4S4,
            D3DFMT_D16,
        //  D3DFMT_D32F_LOCKABLE,
        //  D3DFMT_D24FS8
        };

        D3DDISPLAYMODE currentDisplayMode;
        mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);

        ConfigSet configSet;

        for (int formatIndex = 0; formatIndex < sizeof(renderTargetFormats) / sizeof(D3DFORMAT); formatIndex++)
        {
            D3DFORMAT renderTargetFormat = renderTargetFormats[formatIndex];

            HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, renderTargetFormat);

            if (SUCCEEDED(result))
            {
                for (int depthStencilIndex = 0; depthStencilIndex < sizeof(depthStencilFormats) / sizeof(D3DFORMAT); depthStencilIndex++)
                {
                    D3DFORMAT depthStencilFormat = depthStencilFormats[depthStencilIndex];
                    HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, depthStencilFormat);

                    if (SUCCEEDED(result))
                    {
                        HRESULT result = mD3d9->CheckDepthStencilMatch(mAdapter, mDeviceType, currentDisplayMode.Format, renderTargetFormat, depthStencilFormat);

                        if (SUCCEEDED(result))
                        {
                            // FIXME: enumerate multi-sampling

                            configSet.add(currentDisplayMode, mMinSwapInterval, mMaxSwapInterval, renderTargetFormat, depthStencilFormat, 0);
                        }
                    }
                }
            }
        }

        // Give the sorted configs a unique ID and store them internally
        EGLint index = 1;
        for (ConfigSet::Iterator config = configSet.mSet.begin(); config != configSet.mSet.end(); config++)
        {
            Config configuration = *config;
            configuration.mConfigID = index;
            index++;

            mConfigSet.mSet.insert(configuration);
        }

        if (!createDevice())
        {
            terminate();

            return false;
        }
    }

    if (!isInitialized())
    {
        terminate();

        return false;
    }

    return true;
}