Example #1
0
void CameraToolKit::setCameraTarget( unsigned int iID, vector3df target )
{
	ICameraSceneNode *pCamera = getCamera( iID );

	if ( pCamera )
		pCamera->setTarget( target );
}
Example #2
0
void PlayerCamera::setCameraPos(vector3d<float> pos, bool player1){
	ICameraSceneNode *camera = device->getSceneManager()->getActiveCamera();
	//vector3df cameraPos = camera->getAbsolutePosition();

	float x = pos.X;// - sin( -90.0f * PI / 180.0f ) * 0.0f;
    float y = pos.Y - sin( -90.0f * PI / 180.0f ) * 8.0f;
	float z;
	if(player1)
		z = pos.Z - sin( 90.0f * PI / 180.0f ) * 8.0f;
	else
		z = pos.Z + sin( 90.0f * PI / 180.0f ) * 8.0f;

	cout<< "xpos " << x << "\nypos " << y << "\nzpos " << z << "\n";
	camera->setPosition(vector3df( x, y, z));
	camera->setTarget(vector3df(pos.X, pos.Y, pos.Z));
}
void CSceneNodeAnimatorCameraFollowShip::animateNode( ISceneNode* node, u32 timeMs )
{
	ICameraSceneNode* camera = static_cast<ICameraSceneNode*>( node );
	IShip* ship = static_cast<IShip*>(Target);

	vector3df direction = (ship->getTarget() - ship->getPosition()).normalize();
	vector3df offset = direction * Distance;
	/*vector3df upoffset = ship->getUpVector();
	upoffset = upoffset.normalize() * 10;*/

	camera->setPosition( ship->getPosition() + offset/* + upoffset */);
	camera->setRotation( ship->getRotation() );
	camera->setUpVector( ship->getUpVector() );
	camera->setTarget( ship->getTarget() );


}
void CameraAnimator::animateNode(ISceneNode* node, u32 timeMs)
{
  ICameraSceneNode* camera = static_cast<ICameraSceneNode*> (node);
  if (NULL != camera)
  {
    int x = pc->GetPosition().X;
    int y = pc->GetPosition().Y;

    vector3df newPos = ct->TranslateMapCoords(position2d<s32> (x, y), zAxis);
    camera->setPosition(newPos);

    //Reset z depth to zero for target.
    //TODO: This is hardcoded at -1, make this configurable on creature class.
    newPos.Z = -1.0;
    camera->setTarget(newPos);
    camera->updateAbsolutePosition();
  }
}
Example #5
0
// ----------------------------------------------------------------------------
void Editor::initAfterDataDirKnown()
{
    m_rcs = RoadCrossSectionWndw::get();

    // fonts
    IGUISkin* skin = m_gui_env->getSkin();
    m_font = m_gui_env->getFont(m_data_loc + L"editor/font/font.xml");
    skin->setFont(m_font);

    // removing gui transparency
    for (s32 i = 0; i < EGDC_COUNT; ++i)
    {
        video::SColor col = skin->getColor((EGUI_DEFAULT_COLOR)i);
        col.setAlpha(255);
        skin->setColor((EGUI_DEFAULT_COLOR)i, col);
    }

    // free camera
    ICameraSceneNode* cam;
    cam = m_scene_manager->addCameraSceneNodeMaya();
    cam->setID(1);
    cam->setFarValue(20000.f);
    cam->setTarget(vector3df(0, 0, 0));
    cam->setInputReceiverEnabled(false);

    // viewport init
    ICameraSceneNode* norm_cam;
    norm_cam = m_scene_manager->addCameraSceneNode(0, vector3df(25, 50, 30),
        vector3df(5, 10, 6));
    norm_cam->setID(2);
    m_viewport = Viewport::get(norm_cam, &m_mouse, &m_keys);
    m_viewport->setFreeCamera(cam);
    m_indicator = m_viewport->getIndicator();
    m_scene_manager->setActiveCamera(norm_cam);

    m_msg_wndw = MsgWndw::get();

    m_toolbar = ToolBar::getToolBar();
    m_new_dialog_wndw = NewDialogWndw::get();
    m_new_dialog_wndw->hide();
    m_welcome_screen = WelcomeScreen::get();
} // initAfterDataDirKnown
Example #6
0
int main()
{
	MyEventReceiver receiver;

    IrrlichtDevice* device = createDevice(video::EDT_OPENGL,
            core::dimension2d<u32>(640, 480), 16, false, false, false, &receiver);
	IVideoDriver* driver = device->getVideoDriver();
    ISceneManager* smgr = device->getSceneManager();
	smgr->addLightSceneNode(0,vector3df(50,50,50));
	ICameraSceneNode *camera = smgr->addCameraSceneNode();

	IMeshSceneNode *node = smgr->addCubeSceneNode();
	
	node->setPosition(vector3df(0,75,0));

	camera->setTarget(vector3df(0,1,0));

	
	smgr->getMeshManipulator()->setVertexColors(node->getMesh(), SColor(0,0,255,255));
	smgr->addLightSceneNode();

	while(device->run()){

		if(receiver.IsKeyDown(irr::KEY_LEFT)){
			node->setPosition(node->getPosition()+vector3df(0,0,-0.1));
		}
		else if(receiver.IsKeyDown(irr::KEY_RIGHT)){
			node->setPosition(node->getPosition()+vector3df(0,0,0.1));
		}
		else if(receiver.IsKeyDown(irr::KEY_SPACE)){
			
		}
		driver->beginScene(true, true, SColor(123,100,100,100));
        smgr->drawAll();
		driver->endScene();
	}



	return 0;
}
//! OnAnimate() is called just before rendering the whole scene.
//! nodes may calculate or store animations here, and may do other useful things,
//! dependent on what they are.
void CSceneNodeAnimatorCameraMaya::animateNode(ISceneNode *node, u32 timeMs)
{
	//Alt + LM = Rotate around camera pivot
	//Alt + LM + MM = Dolly forth/back in view direction (speed % distance camera pivot - max distance to pivot)
	//Alt + MM = Move on camera plane (Screen center is about the mouse pointer, depending on move speed)

	if (!node || node->getType() != ESNT_CAMERA)
		return;

	ICameraSceneNode* camera = static_cast<ICameraSceneNode*>(node);

	// If the camera isn't the active camera, and receiving input, then don't process it.
	if(!camera->isInputReceiverEnabled())
		return;

	scene::ISceneManager * smgr = camera->getSceneManager();
	if(smgr && smgr->getActiveCamera() != camera)
		return;

	if (OldCamera != camera)
	{
		OldTarget = camera->getTarget();
		OldCamera = camera;
		LastCameraTarget = OldTarget;
	}
	else
	{
		OldTarget += camera->getTarget() - LastCameraTarget;
	}

	core::vector3df target = camera->getTarget();

	f32 nRotX = RotX;
	f32 nRotY = RotY;
	f32 nZoom = CurrentZoom;

	if ( (isMouseKeyDown(0) && isMouseKeyDown(2)) || isMouseKeyDown(1) )
	{
		if (!Zooming)
		{
			ZoomStart = MousePos;
			Zooming = true;
			nZoom = CurrentZoom;
		}
		else
		{
			const f32 targetMinDistance = 0.1f;
			nZoom += (ZoomStart.X - MousePos.X) * ZoomSpeed;

			if (nZoom < targetMinDistance) // jox: fixed bug: bounce back when zooming to close
				nZoom = targetMinDistance;
		}
	}
	else if (Zooming)
	{
		const f32 old = CurrentZoom;
		CurrentZoom = CurrentZoom + (ZoomStart.X - MousePos.X ) * ZoomSpeed;
		nZoom = CurrentZoom;

		if (nZoom < 0)
			nZoom = CurrentZoom = old;
		Zooming = false;
	}

	// Translation ---------------------------------

	core::vector3df translate(OldTarget), upVector(camera->getUpVector());

	core::vector3df tvectX = Pos - target;
	tvectX = tvectX.crossProduct(upVector);
	tvectX.normalize();

	const SViewFrustum* const va = camera->getViewFrustum();
	core::vector3df tvectY = (va->getFarLeftDown() - va->getFarRightDown());
	tvectY = tvectY.crossProduct(upVector.Y > 0 ? Pos - target : target - Pos);
	tvectY.normalize();

	if (isMouseKeyDown(2) && !Zooming)
	{
		if (!Translating)
		{
			TranslateStart = MousePos;
			Translating = true;
		}
		else
		{
			translate +=  tvectX * (TranslateStart.X - MousePos.X)*TranslateSpeed +
			              tvectY * (TranslateStart.Y - MousePos.Y)*TranslateSpeed;
		}
	}
	else if (Translating)
	{
		translate += tvectX * (TranslateStart.X - MousePos.X)*TranslateSpeed +
		             tvectY * (TranslateStart.Y - MousePos.Y)*TranslateSpeed;
		OldTarget = translate;
		Translating = false;
	}

	// Rotation ------------------------------------

	if (isMouseKeyDown(0) && !Zooming)
	{
		if (!Rotating)
		{
			RotateStart = MousePos;
			Rotating = true;
			nRotX = RotX;
			nRotY = RotY;
		}
		else
		{
			nRotX += (RotateStart.X - MousePos.X) * RotateSpeed;
			nRotY += (RotateStart.Y - MousePos.Y) * RotateSpeed;
		}
	}
	else if (Rotating)
	{
		RotX += (RotateStart.X - MousePos.X) * RotateSpeed;
		RotY += (RotateStart.Y - MousePos.Y) * RotateSpeed;
		nRotX = RotX;
		nRotY = RotY;
		Rotating = false;
	}

	// Set Pos ------------------------------------

	target = translate;

	Pos.X = nZoom + target.X;
	Pos.Y = target.Y;
	Pos.Z = target.Z;

	Pos.rotateXYBy(nRotY, target);
	Pos.rotateXZBy(-nRotX, target);

	// Rotation Error ----------------------------

	// jox: fixed bug: jitter when rotating to the top and bottom of y
	upVector.set(0,1,0);
	upVector.rotateXYBy(-nRotY);
	upVector.rotateXZBy(-nRotX+180.f);

	camera->setPosition(Pos);
	camera->setTarget(target);
	camera->setUpVector(upVector);
	LastCameraTarget = camera->getTarget();
}
void CSceneNodeAnimatorCameraFPS::animateNode(IDummyTransformationSceneNode* node, uint32_t timeMs)
{
	if (!node || node->getType() != ESNT_CAMERA)
		return;

	ICameraSceneNode* camera = static_cast<ICameraSceneNode*>(node);

	if (firstUpdate)
	{
		camera->updateAbsolutePosition();
		if (CursorControl )
		{
			CursorControl->setPosition(0.5f, 0.5f);
			CursorPos = CenterCursor = CursorControl->getRelativePosition();
		}

		LastAnimationTime = timeMs;

		firstUpdate = false;
	}

	// If the camera isn't the active camera, and receiving input, then don't process it.
	if(!camera->isInputReceiverEnabled())
	{
		firstInput = true;
		return;
	}

	if ( firstInput )
	{
		allKeysUp();
		firstInput = false;
	}

	scene::ISceneManager * smgr = camera->getSceneManager();
	if(smgr && smgr->getActiveCamera() != camera)
		return;

	// get time
	float timeDiff = (float) ( timeMs - LastAnimationTime );
	LastAnimationTime = timeMs;

	// update position
	core::vector3df pos = camera->getPosition();

	// Update rotation
	core::vector3df target = (camera->getTarget() - camera->getAbsolutePosition());
	core::vector3df relativeRotation = target.getHorizontalAngle();

	if (CursorControl)
	{
		if (CursorPos != CenterCursor)
		{
			relativeRotation.Y -= (0.5f - CursorPos.X) * RotateSpeed;
			relativeRotation.X -= (0.5f - CursorPos.Y) * RotateSpeed * MouseYDirection;

			// X < MaxVerticalAngle or X > 360-MaxVerticalAngle

			if (relativeRotation.X > MaxVerticalAngle*2 &&
				relativeRotation.X < 360.0f-MaxVerticalAngle)
			{
				relativeRotation.X = 360.0f-MaxVerticalAngle;
			}
			else
			if (relativeRotation.X > MaxVerticalAngle &&
				relativeRotation.X < 360.0f-MaxVerticalAngle)
			{
				relativeRotation.X = MaxVerticalAngle;
			}

			// Do the fix as normal, special case below
			// reset cursor position to the centre of the window.
			CursorControl->setPosition(0.5f, 0.5f);
			CenterCursor = CursorControl->getRelativePosition();

			// needed to avoid problems when the event receiver is disabled
			CursorPos = CenterCursor;
		}

		// Special case, mouse is whipped outside of window before it can update.
		video::IVideoDriver* driver = smgr->getVideoDriver();
		core::vector2d<uint32_t> mousepos(uint32_t(CursorControl->getPosition().X), uint32_t(CursorControl->getPosition().Y));
		core::rect<uint32_t> screenRect(0, 0, driver->getScreenSize().Width, driver->getScreenSize().Height);

		// Only if we are moving outside quickly.
		bool reset = !screenRect.isPointInside(mousepos);

		if(reset)
		{
			// Force a reset.
			CursorControl->setPosition(0.5f, 0.5f);
			CenterCursor = CursorControl->getRelativePosition();
			CursorPos = CenterCursor;
 		}
	}

	// set target

	target.set(0,0, core::max_(1.f, pos.getLength()));
	core::vector3df movedir = target;

	core::matrix4x3 mat;
	mat.setRotationDegrees(core::vector3df(relativeRotation.X, relativeRotation.Y, 0));
	mat.transformVect(&target.X);

	if (NoVerticalMovement)
	{
		mat.setRotationDegrees(core::vector3df(0, relativeRotation.Y, 0));
		mat.transformVect(&movedir.X);
	}
	else
	{
		movedir = target;
	}

	movedir.normalize();

	if (CursorKeys[EKA_MOVE_FORWARD])
		pos += movedir * timeDiff * MoveSpeed;

	if (CursorKeys[EKA_MOVE_BACKWARD])
		pos -= movedir * timeDiff * MoveSpeed;

	// strafing

	core::vector3df strafevect = target;
	strafevect = strafevect.crossProduct(camera->getUpVector());

	if (NoVerticalMovement)
		strafevect.Y = 0.0f;

	strafevect.normalize();

	if (CursorKeys[EKA_STRAFE_LEFT])
		pos += strafevect * timeDiff * MoveSpeed;

	if (CursorKeys[EKA_STRAFE_RIGHT])
		pos -= strafevect * timeDiff * MoveSpeed;

	// write translation
	camera->setPosition(pos);

	// write right target
	target += pos;
	camera->setTarget(target);
}
Example #9
0
bool terrainSceneNode(void)
{
    IrrlichtDevice *device =
        createDevice(video::EDT_OPENGL, dimension2di(160, 120), 32);

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

    ITerrainSceneNode* terrain = smgr->addTerrainSceneNode(
        "../media/terrain-heightmap.bmp");
    terrain->setScale(core::vector3df(40.f, .1f, 40.f));

    terrain->setMaterialFlag(video::EMF_LIGHTING, false);
    terrain->setMaterialTexture(0, driver->getTexture("../media/terrain-texture.jpg"));
    terrain->setDebugDataVisible(scene::EDS_FULL);

    ICameraSceneNode* camera = smgr->addCameraSceneNode();

    const core::vector3df center (terrain->getBoundingBox().getCenter());
    camera->setTarget (center);

    // yes, Y is intentionally being set to X here
    const core::vector3df above (center.X, center.X, center.Z);
    camera->setPosition (above);
	camera->setUpVector(vector3df(1.f, 0.f, 0.f));
    camera->setFarValue(above.Y);

    device->run();
    smgr->drawAll();


	// This shouldn't cause a recalc
	camera->setUpVector(vector3df(1.f, 0.f, .01f).normalize());
    device->run();
	driver->beginScene(true, true, video::SColor(255,100,101,140));
	smgr->drawAll();
	driver->endScene();

	// Note that this has to be a slightly fuzzier than usual compare to satisfy multiple OpenGL environments
	bool result = takeScreenshotAndCompareAgainstReference(driver, "-terrainSceneNode-1.png", 98.3f);
	if(!result)
	{
		logTestString("Small camera up rotation caused bad recalc.\n");
		assert(false);
	}


	// This is big enough to cause a recalc
	camera->setUpVector(vector3df(1.f, 0.f, .1f).normalize());
    device->run();
	driver->beginScene(true, true, video::SColor(255,100,101,140));
	smgr->drawAll();
	driver->endScene();

	result &= takeScreenshotAndCompareAgainstReference(driver, "-terrainSceneNode-2.png", 98.9f);
	if(!result)
	{
		logTestString("Large camera up rotation caused bad recalc.\n");
		assert(false);
	}

    device->drop();
    return result;
}
Example #10
0
int main( ) {
	// Boring stuff: set up the scene, object & camera as usual
	// To make things more interesting, we add many Sydneys and a textured floor this time
	IrrlichtDevice* device = createDevice( DRIVER, dimension2d<s32>( 640, 480 ), 16, false, false, false, 0 );
	IVideoDriver* driver = device->getVideoDriver( );
	ISceneManager* smgr = device->getSceneManager( );
	IGUIEnvironment* guienv = device->getGUIEnvironment( );
	device->getFileSystem( )->changeWorkingDirectoryTo( MEDIA_DIRECTORY );
	guienv->addStaticText( L"Depth of Field", rect<s32>( 10, 10, 260, 22 ), true );
	IAnimatedMesh* mesh = smgr->getMesh("sydney.md2");

	// Create the required material. This is a simple shader which draws the texture with no lights.
	// Use GL_PLAIN1 / DX_PLANE1 or GL_PLAIN2 / DX_PLANE2 to support 1 or 2 basic point-lights
	u32 matid;
	IGPUProgrammingServices* gpu = driver->getGPUProgrammingServices( );
	switch( driver->getDriverType( ) ) {
		case EDT_OPENGL:
			matid = gpu->addHighLevelShaderMaterial( GL_V_MAT, "main", EVST_VS_1_1, GL_PLAIN, "main", EPST_PS_1_1, new CTexturesShaderCallback( ), EMT_SOLID, 1 );
			break;
		case EDT_DIRECT3D8:
		case EDT_DIRECT3D9:
		default:
			matid = gpu->addHighLevelShaderMaterial( DX_V_MAT, "main", EVST_VS_1_1, DX_PLAIN, "main", EPST_PS_2_0, new CTexturesShaderCallback( ), EMT_SOLID, 0 );
	}

	for( u8 x = 0u; x != 2u; ++ x )
		for( u8 i = 0u; i != 5u; ++ i ) {
			IAnimatedMeshSceneNode* node = smgr->addAnimatedMeshSceneNode( mesh );
			node->setMaterialFlag(EMF_LIGHTING, false);
			node->setMD2Animation(scene::EMAT_STAND);
			node->setMaterialTexture( 0, driver->getTexture("sydney.bmp") );
			node->setMaterialType( (E_MATERIAL_TYPE) matid );
			node->setPosition( vector3df( -x * 20.0f, 0.0f, i * 40.0f ) );
		}
	ISceneNode* node2 = smgr->addMeshSceneNode( smgr->addHillPlaneMesh( "", dimension2df( 200.0f, 200.0f ), dimension2d<u32>( 10, 10 ), NULL, 0.0f, dimension2df( 0.0f, 0.0f ), dimension2df( 100.0f, 100.0f ) ) );
	node2->setMaterialFlag(EMF_LIGHTING, false);
	node2->setMaterialTexture( 0, driver->getTexture("terrain-heightmap.bmp") );
	node2->setMaterialType( (E_MATERIAL_TYPE) matid );
	node2->setPosition( vector3df( 0.0f, -22.0f, 0.0f ) );
	ICameraSceneNode* cam = smgr->addCameraSceneNode( 0, vector3df( 40.0f, 60.0f, -40.0f ), vector3df( 0.0f, 5.0f, 50.0f ) );

	IPostProc* ppRenderer = new CRendererPostProc( smgr, dimension2di( 1024, 512 ), true, true, SColor( 255u, 100u, 101u, 140u ) );
	CEffectPostProc* ppBlurDOF = new CEffectPostProc( ppRenderer, dimension2di( 1024, 512 ), PP_BLURDOF );
	// We could set parameters on creation, but no need since we will animate it anyway.
	// Parameters are: near blur, near focus, far focus, far blur, blur level
	// You can also use PP_BLURDOFNEAR or PP_BLURDOFFAR to have only near or far blurring

	// These variables aren't important - they are just for showing the FPS
	wchar_t tmp[255]; u8 t = 0u;

	while( device->run( ) ) {
		// Change the camera angle
		cam->setTarget( vector3df( -(device->getCursorControl( )->getPosition( ).X - 320.0f) * 0.1f, (device->getCursorControl( )->getPosition( ).Y - 240.0f) * 0.2f, 0.0f ) );

		// Animate the depth of field:
		f32 p = sinf( device->getTimer( )->getTime( ) * 0.0005f ) * 0.5f - 0.2f;
		ppBlurDOF->setParameters( p * 100.0f + 80.0f, p * 100.0f + 110.0f, p * 100.0f + 160.0f, p * 100.0f + 240.0f, 0.01f );

		driver->beginScene( false, driver->getDriverType( ) == video::EDT_DIRECT3D9 );
		ppBlurDOF->render( NULL );
		guienv->drawAll( );
		driver->endScene( );

		// Show the current FPS
		if( ++ t == 30u ) { t = 0u; swprintf(tmp, 255, L"%ls fps:%3d", driver->getName(), driver->getFPS() ); device->setWindowCaption( tmp ); }
	}

	delete ppBlurDOF;
	delete ppRenderer;

	// Back to boring stuff
	device->drop();
	return 0;
}
Example #11
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;
}
Example #12
0
int main(int argc, char **argv) {

	// Help?
	if (argv[1] && argv[1][0] == '-') die(helpmsg);

	putenv((char *) "vblank_mode=0"); // No vsync for us, thanks.

	MyEventReceiver *r = new MyEventReceiver();
	IrrlichtDevice *dev = createDevice(EDT_OPENGL, core::dimension2d<u32>(1024,768), 32,
				false, false, false, r);
	if (!dev) die("Can't initialize Irrlicht");

	IVideoDriver *drv = dev->getVideoDriver();
	ISceneManager *smgr = dev->getSceneManager();
	IGPUProgrammingServices *gpu = drv->getGPUProgrammingServices();
	ICameraSceneNode *cam = NULL;
	ITexture *pic = NULL;
	IMeshSceneNode *ball = NULL;
	bool showpic = false;

	IReadFile *areamap = createMemoryReadFile(AreaMap33, sizeof(AreaMap33), "AreaMap33", false);
	if (!areamap) die("Failed to load areamap");
	ITexture *areamaptex = drv->getTexture(areamap);
	areamap->drop();

	// If there's an argument, assume it is a pic to load; otherwise, draw a sphere

	if (argv[1] && access(argv[1], R_OK) == 0) {
		showpic = true;
		pic = drv->getTexture(argv[1]);
		if (!pic) die("Can't load image");

		cam = smgr->addCameraSceneNode();
	} else {
		cam = smgr->addCameraSceneNodeMaya();
		cam->setTarget(vector3df(0, 0, 0));
		ball = smgr->addSphereSceneNode(40, 8);

		int ballshader = gpu->addHighLevelShaderMaterial(rnd,0,EVST_VS_1_1,0);
		ball->setMaterialType((E_MATERIAL_TYPE) ballshader);

		ISceneNodeAnimator *cool = smgr->createRotationAnimator(vector3df(-0.1, 0.1, -0.1));
		ball->addAnimator(cool);
		cool->drop();
	}

	// Set up static defines, RTTs, quads
	dimension2d<u32> screensize = drv->getScreenSize();
	char defines[128];
	snprintf(defines, 128,
		"#define PIXEL_SIZE vec2(1.0f / %u.0, 1.0f / %u.0)\n"
		"#define MAX_SEARCH_STEPS 8.0\n#define MAX_DISTANCE 33.0\n",
		screensize.Width, screensize.Height);

	ITexture *rt1 = drv->addRenderTargetTexture(screensize, "rt1", ECF_A8R8G8B8);
	ITexture *rt2 = drv->addRenderTargetTexture(screensize, "rt2", ECF_A8R8G8B8);
	ITexture *rt3 = drv->addRenderTargetTexture(screensize, "rt3", ECF_A8R8G8B8);
	if (!rt1 || !rt2 || !rt3) die("No RTT");

	ScreenQuad *def = new ScreenQuad(drv);
	ScreenQuad *sq = new ScreenQuad(drv);
	ScreenQuad *sq2 = new ScreenQuad(drv);
	ScreenQuad *sq3 = new ScreenQuad(drv);
	ScreenQuad *norm = new ScreenQuad(drv);
	if (showpic) def->SetTexture(pic);
	sq->SetTexture(rt1);
	sq->GetMaterial().setFlag(EMF_BILINEAR_FILTER, false);
	norm->SetTexture(rt1);
	norm->GetMaterial().setFlag(EMF_BILINEAR_FILTER, false);

	sq2->SetTexture(rt2);
	sq2->SetTexture(rt2, 1);
	sq2->SetTexture(areamaptex, 2);
	sq2->GetMaterial().TextureLayer[2].BilinearFilter = false;

	sq3->SetTexture(rt3);
	sq3->GetMaterial().setFlag(EMF_BILINEAR_FILTER, false);
	sq3->SetTexture(rt1,1);
	state_t state = MLAA_OFF;

	stringc tmp1, tmp2;
	tmp1 = defines;
	tmp1 += offsetvs;
	tmp2 = defines;
	tmp2 += color1fs;

	// Load shaders
	int edge = gpu->addHighLevelShaderMaterial(tmp1.c_str(),0,EVST_VS_1_1,tmp2.c_str());
	sq->SetMaterialType((E_MATERIAL_TYPE) edge);

	tmp2 = defines;
	tmp2 += blend2fs;

	blendcb *bcb = new blendcb();
	edge = gpu->addHighLevelShaderMaterial(tmp1.c_str(),0,EVST_VS_1_1,tmp2.c_str(),0,EPST_PS_1_1,bcb);
	sq2->SetMaterialType((E_MATERIAL_TYPE) edge);

	tmp2 = defines;
	tmp2 += neigh3fs;

	neighcb *ncb = new neighcb();
	edge = gpu->addHighLevelShaderMaterial(tmp1.c_str(),0,EVST_VS_1_1,tmp2.c_str(),0,EPST_PS_1_1,ncb);
	sq3->SetMaterialType((E_MATERIAL_TYPE) edge);

	// Record start time
	int lastfps = -1, minfps = 10000;
	unsigned long long total_frames = 0, fxtimer = 0, tmplong, onframes = 0;
	struct timeval starttime, tick1, tick2;
	float glsltime = 0;
	gettimeofday(&starttime, NULL);
	wchar_t cap[20];
	glEnable(GL_STENCIL_TEST);
	unsigned char firstrun = 1; // To avoid the glsl compiler in the timing

	// Main loop
	while (dev->run()) {

		gettimeofday(&tick1, NULL);
		drv->beginScene();

		switch (state) {
			case MLAA_OFF:
				if (showpic) def->Render(false);
				else smgr->drawAll();
			break;
			case MLAA_ON:
				if (showpic) def->Render(rt1);
				else {
					drv->setRenderTarget(rt1);
					smgr->drawAll();
				}


				glClear(GL_STENCIL_BUFFER_BIT);
				glStencilFunc(GL_ALWAYS, 1, ~0);
				glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
				sq->Render(rt2);

				glStencilFunc(GL_EQUAL, 1, ~0);
				glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
				sq2->Render(rt3);
				drv->setRenderTarget(rt1, false, false);

				// Overlay the smoothed edges on the initial image
				sq3->Render(false);

				// Blit the final image to the framebuffer
				glStencilFunc(GL_ALWAYS, 1, ~0);
				norm->Render();

			break;
		}

		drv->endScene();

		if (state == MLAA_ON) {
			gettimeofday(&tick2, NULL);
			if (!firstrun) {
				tmplong = (tick2.tv_sec - tick1.tv_sec) * 10000;
				tmplong += (tick2.tv_usec - tick1.tv_usec) / 100;
				fxtimer += tmplong;

				onframes++;
			} else {
				firstrun = 0;

				glsltime = tick2.tv_sec - tick1.tv_sec;
				glsltime += (tick2.tv_usec - tick1.tv_usec) / 1000000.0;
			}
		}

		int fps = drv->getFPS();
		if (minfps > fps) minfps = fps;
		if (lastfps != fps) {
			swprintf(cap, 20, L"%d fps, MLAA %s", fps, state == MLAA_ON ? "on" : "off");
			dev->setWindowCaption(cap);
			lastfps = fps;
		}

		if (r->IsKeyDown(KEY_KEY_M)) {
			if (state == MLAA_ON) state = MLAA_OFF;
			else state = MLAA_ON;

			lastfps++;
		}

		usleep(1); // 16?
		total_frames++;
	}

	dev->drop();
	delete ncb;
	delete bcb;
	delete def;
	delete sq;
	delete sq2;
	delete sq3;
	delete norm;
	delete r;

	struct timeval endtime;
	gettimeofday(&endtime, NULL);
	float sec = endtime.tv_sec - starttime.tv_sec;
	sec += ((float) endtime.tv_usec - starttime.tv_usec) / 1000000;
	printf("\nRan %.3fs, ", sec);
	sec -= glsltime;

	printf("average fps %.2f, min %d\n", (float) total_frames/sec, minfps);

	if (onframes) {
		printf("\nAverage on fps %.2f, average off fps %.2f\n\n", (float) onframes/(fxtimer/10000.0),
					(float) (total_frames - onframes)/(sec - (fxtimer/10000.0)));

//		printf("MLAA took on average %.1fms\n", (float) (fxtimer / onframes) / 10.0);
	}

	return 0;
}
		void CSSceneNodeAnimatorFPS::animateNode(ISceneNode* node, u32 timeMs)
		{
			if (!node || node->getType() != ESNT_CAMERA)
				return;

			ICameraSceneNode* camera = static_cast<ICameraSceneNode*>(node);

			if (firstUpdate)
			{
				camera->updateAbsolutePosition();
				if (CursorControl)
				{
					CursorControl->setPosition(m_CursorOffsetX, m_CursorOffsetY);
					CursorPos = CenterCursor = CursorControl->getRelativePosition();
				}

				LastAnimationTime = timeMs;

				firstUpdate = false;
			}

			// If the camera isn't the active camera, and receiving input, then don't process it.
			if (!camera->isInputReceiverEnabled())
			{
				firstInput = true;
				return;
			}

			if (firstInput)
			{
				allKeysUp();
				firstInput = false;
			}

			scene::ISceneManager * smgr = camera->getSceneManager();
			if (smgr && smgr->getActiveCamera() != camera)
				return;

			// get time
			f32 timeDiff = (f32)(timeMs - LastAnimationTime);
			LastAnimationTime = timeMs;

			// update position
			core::vector3df pos = camera->getPosition();

			// Update rotation
			core::vector3df target = (camera->getTarget() - camera->getAbsolutePosition());
			core::vector3df relativeRotation = target.getHorizontalAngle();

			if (CursorControl)
			{
				if (CursorPos != CenterCursor)
				{
					relativeRotation.Y -= (m_CursorOffsetX - CursorPos.X) * RotateSpeed;
					relativeRotation.X -= (m_CursorOffsetY - CursorPos.Y) * RotateSpeed * MouseYDirection;

					// X < MaxVerticalAngle or X > 360-MaxVerticalAngle

					if (relativeRotation.X > MaxVerticalAngle * 2 &&
						relativeRotation.X < 360.0f - MaxVerticalAngle)
					{
						relativeRotation.X = 360.0f - MaxVerticalAngle;
					}
					else
						if (relativeRotation.X > MaxVerticalAngle &&
							relativeRotation.X < 360.0f - MaxVerticalAngle)
						{
						relativeRotation.X = MaxVerticalAngle;
						}

					// Do the fix as normal, special case below
					// reset cursor position to the centre of the window.
					CursorControl->setPosition(m_CursorOffsetX, m_CursorOffsetY);
					CenterCursor = CursorControl->getRelativePosition();

					// needed to avoid problems when the event receiver is disabled
					CursorPos = CenterCursor;
				}

				// Special case, mouse is whipped outside of window before it can update.
				video::IVideoDriver* driver = smgr->getVideoDriver();
				core::vector2d<u32> mousepos(u32(CursorControl->getPosition().X), u32(CursorControl->getPosition().Y));
				core::rect<u32> screenRect(0, 0, driver->getScreenSize().Width, driver->getScreenSize().Height);

				// Only if we are moving outside quickly.
				bool reset = !screenRect.isPointInside(mousepos);

				if (reset)
				{
					// Force a reset.
					CursorControl->setPosition(m_CursorOffsetX, m_CursorOffsetY);
					CenterCursor = CursorControl->getRelativePosition();
					CursorPos = CenterCursor;
				}
			}

			// set target

			target.set(0, 0, core::max_(1.f, pos.getLength()));
			core::vector3df movedir = target;

			core::matrix4 mat;
			mat.setRotationDegrees(core::vector3df(relativeRotation.X, relativeRotation.Y, 0));
			mat.transformVect(target);

			if (NoVerticalMovement)
			{
				mat.setRotationDegrees(core::vector3df(0, relativeRotation.Y, 0));
				mat.transformVect(movedir);
			}
			else
			{
				movedir = target;
			}

			movedir.normalize();

			if (CursorKeys[EKA_MOVE_FORWARD])
				pos += movedir * timeDiff * MoveSpeed;

			if (CursorKeys[EKA_MOVE_BACKWARD])
				pos -= movedir * timeDiff * MoveSpeed;

			// strafing

			core::vector3df strafevect = target;
			strafevect = strafevect.crossProduct(camera->getUpVector());

			if (NoVerticalMovement)
				strafevect.Y = 0.0f;

			strafevect.normalize();

			if (CursorKeys[EKA_STRAFE_LEFT])
				pos += strafevect * timeDiff * MoveSpeed;

			if (CursorKeys[EKA_STRAFE_RIGHT])
				pos -= strafevect * timeDiff * MoveSpeed;

			// For jumping, we find the collision response animator attached to our camera
			// and if it's not falling, we tell it to jump.
			if (CursorKeys[EKA_JUMP_UP])
			{
				const ISceneNodeAnimatorList& animators = camera->getAnimators();
				ISceneNodeAnimatorList::ConstIterator it = animators.begin();
				while (it != animators.end())
				{
					if (ESNAT_COLLISION_RESPONSE == (*it)->getType())
					{
						ISceneNodeAnimatorCollisionResponse * collisionResponse =
							static_cast<ISceneNodeAnimatorCollisionResponse *>(*it);

						if (!collisionResponse->isFalling())
							collisionResponse->jump(JumpSpeed);
					}

					it++;
				}
			}

			// write translation
			camera->setPosition(pos);

			// write right target
			target += pos;
			camera->setTarget(target);
		}
void dns_cache_prune(DnsCache *c) {
        usec_t t = 0;

        assert(c);

        /* Remove all entries that are past their TTL */

        for (;;) {
                _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
                DnsCacheItem *i;

                i = prioq_peek(c->by_expiry);
                if (!i)
                        break;

                if (t <= 0)
                        t = now(CLOCK_BOOTTIME);

                if (i->until > t)
                        break;

                /* Take an extra reference to the key so that it
                 * doesn't go away in the middle of the remove call */
                key = dns_resource_key_ref(i->key);
                dns_cache_remove(c, key);
        }
}

static int dns_cache_item_prioq_compare_func(const void *a, const void *b) {
        const DnsCacheItem *x = a, *y = b;

        if (x->until < y->until)
                return -1;
        if (x->until > y->until)
                return 1;
        return 0;
}

static int dns_cache_init(DnsCache *c) {
        int r;

        assert(c);

        r = prioq_ensure_allocated(&c->by_expiry, dns_cache_item_prioq_compare_func);
        if (r < 0)
                return r;

        r = hashmap_ensure_allocated(&c->by_key, &dns_resource_key_hash_ops);
        if (r < 0)
                return r;

        return r;
}

static int dns_cache_link_item(DnsCache *c, DnsCacheItem *i) {
        DnsCacheItem *first;
        int r;

        assert(c);
        assert(i);

        r = prioq_put(c->by_expiry, i, &i->prioq_idx);
        if (r < 0)
                return r;

        first = hashmap_get(c->by_key, i->key);
        if (first) {
                LIST_PREPEND(by_key, first, i);
                assert_se(hashmap_replace(c->by_key, first->key, first) >= 0);
        } else {
                r = hashmap_put(c->by_key, i->key, i);
                if (r < 0) {
                        prioq_remove(c->by_expiry, i, &i->prioq_idx);
                        return r;
                }
        }

        return 0;
}

static DnsCacheItem* dns_cache_get(DnsCache *c, DnsResourceRecord *rr) {
        DnsCacheItem *i;

        assert(c);
        assert(rr);

        LIST_FOREACH(by_key, i, hashmap_get(c->by_key, rr->key))
                if (i->rr && dns_resource_record_equal(i->rr, rr) > 0)
                        return i;

        return NULL;
}

static void dns_cache_item_update_positive(DnsCache *c, DnsCacheItem *i, DnsResourceRecord *rr, usec_t timestamp) {
        assert(c);
        assert(i);
        assert(rr);

        i->type = DNS_CACHE_POSITIVE;

        if (!i->by_key_prev) {
                /* We are the first item in the list, we need to
                 * update the key used in the hashmap */

                assert_se(hashmap_replace(c->by_key, rr->key, i) >= 0);
        }

        dns_resource_record_ref(rr);
        dns_resource_record_unref(i->rr);
        i->rr = rr;

        dns_resource_key_unref(i->key);
        i->key = dns_resource_key_ref(rr->key);

        i->until = timestamp + MIN(rr->ttl * USEC_PER_SEC, CACHE_TTL_MAX_USEC);

        prioq_reshuffle(c->by_expiry, i, &i->prioq_idx);
}

static int dns_cache_put_positive(
                DnsCache *c,
                DnsResourceRecord *rr,
                usec_t timestamp,
                int owner_family,
                const union in_addr_union *owner_address) {

        _cleanup_(dns_cache_item_freep) DnsCacheItem *i = NULL;
        DnsCacheItem *existing;
        int r;

        assert(c);
        assert(rr);
        assert(owner_address);

        /* New TTL is 0? Delete the entry... */
        if (rr->ttl <= 0) {
                dns_cache_remove(c, rr->key);
                return 0;
        }

        if (rr->key->class == DNS_CLASS_ANY)
                return 0;
        if (rr->key->type == DNS_TYPE_ANY)
                return 0;

        /* Entry exists already? Update TTL and timestamp */
        existing = dns_cache_get(c, rr);
        if (existing) {
                dns_cache_item_update_positive(c, existing, rr, timestamp);
                return 0;
        }

        /* Otherwise, add the new RR */
        r = dns_cache_init(c);
        if (r < 0)
                return r;

        dns_cache_make_space(c, 1);

        i = new0(DnsCacheItem, 1);
        if (!i)
                return -ENOMEM;

        i->type = DNS_CACHE_POSITIVE;
        i->key = dns_resource_key_ref(rr->key);
        i->rr = dns_resource_record_ref(rr);
        i->until = timestamp + MIN(i->rr->ttl * USEC_PER_SEC, CACHE_TTL_MAX_USEC);
        i->prioq_idx = PRIOQ_IDX_NULL;
        i->owner_family = owner_family;
        i->owner_address = *owner_address;

        r = dns_cache_link_item(c, i);
        if (r < 0)
                return r;

        i = NULL;
        return 0;
}

static int dns_cache_put_negative(
                DnsCache *c,
                DnsResourceKey *key,
                int rcode,
                usec_t timestamp,
                uint32_t soa_ttl,
                int owner_family,
                const union in_addr_union *owner_address) {

        _cleanup_(dns_cache_item_freep) DnsCacheItem *i = NULL;
        int r;

        assert(c);
        assert(key);
        assert(owner_address);

        dns_cache_remove(c, key);

        if (key->class == DNS_CLASS_ANY)
                return 0;
        if (key->type == DNS_TYPE_ANY)
                return 0;
        if (soa_ttl <= 0)
                return 0;

        if (!IN_SET(rcode, DNS_RCODE_SUCCESS, DNS_RCODE_NXDOMAIN))
                return 0;

        r = dns_cache_init(c);
        if (r < 0)
                return r;

        dns_cache_make_space(c, 1);

        i = new0(DnsCacheItem, 1);
        if (!i)
                return -ENOMEM;

        i->type = rcode == DNS_RCODE_SUCCESS ? DNS_CACHE_NODATA : DNS_CACHE_NXDOMAIN;
        i->key = dns_resource_key_ref(key);
        i->until = timestamp + MIN(soa_ttl * USEC_PER_SEC, CACHE_TTL_MAX_USEC);
        i->prioq_idx = PRIOQ_IDX_NULL;
        i->owner_family = owner_family;
        i->owner_address = *owner_address;

        r = dns_cache_link_item(c, i);
        if (r < 0)
                return r;

        i = NULL;
        return 0;
}

int dns_cache_put(
                DnsCache *c,
                DnsQuestion *q,
                int rcode,
                DnsAnswer *answer,
                unsigned max_rrs,
                usec_t timestamp,
                int owner_family,
                const union in_addr_union *owner_address) {

        unsigned i;
        int r;

        assert(c);
        assert(q);
WxIrrMainWindow::WxIrrMainWindow(const wxString& title, void (*draw)(WxIrrViewportManager*), void (*update)(void),
                                 bool (*irrlichtLeftMouseDown)(bool controlDown, bool shiftDown, int x, int y),
                                 bool (*irrlichtLeftMouseUp)(bool controlDown, bool shiftDown, int x, int y),
                                 bool (*irrlichtLeftMouseDoubleClick)(bool controlDown, bool shiftDown, int x, int y),
                                 bool (*irrlichtMouseMove)(bool controlDown, bool shiftDown, int x, int y, int moveX, int moveY),
                                 void (*irrlichtCameraMouseMove)(int moveX, int moveY, WxIrrViewport* selectedViewport),
                                 void (*irrlichtCameraKeyDown)(int id, WxIrrViewport* selectedViewport),	void (*irrlichtCameraKeyUp)(int id), void (*irrlichtCameraKeyboardReset)(void),
                                 void (*simulationMouseMove)(wxPoint mousePos, bool isShiftDown, WxIrrViewport* mouseOverViewport),
                                 bool (*simulationMouseClick)(bool isShiftDown, bool isControlDown), bool (*simulationMouseDoubleClick)(void), void (*SimulationStartMouseChecking)(void),
                                 void (*onSimulationShowAxesFunctionPointer)(bool), void (*onSimulationShowObjectNameFunctionPointer)(bool),
                                 SColor (*onSimulationXAxisGetColorFunctionPointer)(void), SColor (*onSimulationYAxisGetColorFunctionPointer)(void), SColor (*onSimulationZAxisGetColorFunctionPointer)(void),
                                 void (*onSimulationXAxisChangeColorFunctionPointer)(wxColour& color), void (*onSimulationYAxisChangeColorFunctionPointer)(wxColour& color), void (*onSimulationZAxisChangeColorFunctionPointer)(wxColour& color),
                                 void (*onSimulationShowXYGridFunctionPointer)(bool), void (*onSimulationShowXZGridFunctionPointer)(bool), void (*onSimulationShowYZGridFunctionPointer)(bool))
    : wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(800, 600))
{
    OnSimulationShowAxesFunctionPointer = onSimulationShowAxesFunctionPointer;
    OnSimulationShowObjectNameFunctionPointer = onSimulationShowObjectNameFunctionPointer;

    OnSimulationXAxisGetColorFunctionPointer = onSimulationXAxisGetColorFunctionPointer;
    OnSimulationYAxisGetColorFunctionPointer = onSimulationYAxisGetColorFunctionPointer;
    OnSimulationZAxisGetColorFunctionPointer = onSimulationZAxisGetColorFunctionPointer;
    OnSimulationXAxisChangeColorFunctionPointer = onSimulationXAxisChangeColorFunctionPointer;
    OnSimulationYAxisChangeColorFunctionPointer = onSimulationYAxisChangeColorFunctionPointer;
    OnSimulationZAxisChangeColorFunctionPointer = onSimulationZAxisChangeColorFunctionPointer;

    OnSimulationShowXYGridFunctionPointer = onSimulationShowXYGridFunctionPointer;
    OnSimulationShowXZGridFunctionPointer = onSimulationShowXZGridFunctionPointer;
    OnSimulationShowYZGridFunctionPointer = onSimulationShowYZGridFunctionPointer;

    leftPanel = new WxIrrViewportWindow(this, 1000);
    leftPanel->SetBackgroundColour(wxColour(wxT("Black")));

    irr::SIrrlichtCreationParameters param;
#if defined _WX_IRR_WINDOWS

    param.DriverType = EDT_DIRECT3D9;
    param.AntiAlias = false;
    param.WindowId = reinterpret_cast<void*>(GetLeftPanelHandle());

#elif defined _WX_IRR_LINUX

    param.DriverType = EDT_OPENGL;
    param.AntiAlias = false;
    GtkWidget* handle = (GtkWidget*)GetLeftPanelHandle();
    gtk_widget_realize(handle);
    Window xHandle = GDK_WINDOW_XWINDOW(handle->window);
    param.WindowId = (void*)(xHandle);

#elif defined _WX_IRR_MACOS

    //param.DriverType = EDT_OPENGL;

#else

    //return false;
    Close();

#endif

    leftPanel->InitalizeViewportManager();
    SetupDevice(param, draw, update, irrlichtLeftMouseDown, irrlichtLeftMouseUp, irrlichtLeftMouseDoubleClick, irrlichtMouseMove, irrlichtCameraMouseMove, irrlichtCameraKeyDown, irrlichtCameraKeyUp, irrlichtCameraKeyboardReset,
                simulationMouseMove, simulationMouseClick, simulationMouseDoubleClick, SimulationStartMouseChecking);

    //Main camera
    ICameraSceneNode* camera = GetDevice()->getSceneManager()->addCameraSceneNode();
    camera->setPosition(Vector3(30,-10,30));
    //camera->bindTargetAndRotation(true);
    //camera->setTarget(Vector3(0,0,0));
    Vector3 currentCameraRot = camera->getRotation();
    Vector3 rot = currentCameraRot.rotationToDirection();
    Vector3 pos = camera->getPosition();
    camera->setTarget(rot + pos);
    camera->setFarValue(100000);
    SetCamera(camera);

    rightPanel = new SimulationPanel(this, 1001, wxDefaultPosition, wxDefaultSize);
    rightPanel->SetBackgroundColour(wxColour(wxT("Black")));

    m_mgr.SetManagedWindow(this);

    //Create Main Menu
    menuBar = new wxMenuBar();
    menuBarManager = new PhysicsHelperMenuBar(menuBar);

    SetMenuBar( menuBar );
    //Status bar
    CreateStatusBar();
    SetStatusText( wxT("PhysicsHelper") );
    statusBarText = wxT("PhysicsHelper");

    toolBarsManager = new PhysicsHelperToolbars(this, m_mgr);

    //add the normal panes
    m_mgr.AddPane(leftPanel, wxAuiPaneInfo().CenterPane().Name(wxT("leftPanel")));
    m_mgr.AddPane(rightPanel, wxAuiPaneInfo().CloseButton(false).Right().PinButton(true).MinimizeButton(true).Name(wxT("rightPanel")));

    m_mgr.Update();

    //Centre();
}
Example #16
0
/** Diese Funktion wird zum Zeichnen der 3D Grafik missbraucht, das funktioniert mehr schlecht als recht
* Alle Zeichenrelevanten dinge sind in die Klasse CombatShip verlagert worden, wo sie ja auch berechnet werden.
* Hier wird nur noch rudimänter berechnet was notwendig ist. Wenn die MFC weg ist soll auch das weg.
* @todo Aufräumen der vielen MemoryLeaks 
*/
void CCombatSimulatorView::OnDraw(CDC* pDC)
{
	//wenn der Timer steht lass in laufen
	if (!(p_timer->go))
	{
		p_timer->go = true;
		p_timer->ResumeThread() ;
	}
	//Ab hier geht nur noch ein Thread sonst gibts kuddelmuttel 
	m_lock.Lock();
	CCombatSimulatorDoc* pDoc = GetDocument();

	if (!pDoc)
		return;

  p_device->setWindowCaption(L"Hello World! - Irrlicht Engine Demo");

	bool bExit = true;
	//ist der Kampf noch nicht beendet Zeichne 3D
	if (pDoc->repeat == 0)
	{

		if (pDoc->combat.m_bReady)
		{
			bExit = false;
			
			pDoc->combat.CalculateCombat(winner);
			//Ticks zählen
			core::stringw s ;
			s += L"TICK: "; 
			s += pDoc->combat.m_iTime;
			text1->setText(s.c_str());
			//Torpedos fliegen lassen
			for (std::list<CTorpedo*>::const_iterator it = pDoc->combat.m_CT.begin(); it != pDoc->combat.m_CT.end(); ++it)
			{

				(*it)->GetNode()->addAnimator(p_smgr->createFlyStraightAnimator(p_node->getAbsolutePosition(),vector3df((*it)->m_KO.x,(*it)->m_KO.y,(*it)->m_KO.z),false,false));

			}
			//Zähler hoch
				counter++;
				if (counter%200 == 0)
					xy_ebene = !xy_ebene;
				int time = 0;

		    //hier wird gezeichnet
				p_driver->beginScene(true, true, SColor(255,100,101,140));
				ICameraSceneNode* c = p_smgr->getActiveCamera();
			//eventuell noch mal der Kamerrazoom verändert
				c->setPosition(vector3df(0,0,m_iCameraZoom));

				c->setTarget(vector3df(m_iCameraX,m_iCameraY,0));
			//Ab gehts die Szene wird gemalt
				p_smgr->drawAll();
				p_guienv->drawAll();

				p_driver->endScene();
								
            //verschossene Laser werden entfernt
			for (int q = 0; q < pDoc->combat.m_CS.GetSize(); q++)
			{
				pDoc->combat.m_CS.GetAt(q)->GetBulletParent()->removeAll();
			}
			//ab jetzt können wieder mehr Threads ran
			m_lock.Unlock();
			return;
		}
		// ************** TEST DES KAMPFMODUSES ZEICHNEN ist hier zu Ende **************

}

	//		return;
		if (!pDoc->combat.m_bReady)
		{
			bExit = true;
			for (std::map<CString, BYTE>::const_iterator it = winner.begin(); it != winner.end(); ++it)
				if (it->second == 1)
					AfxMessageBox("Race " + it->first + " wins the combat");

			// Das Log-File über die vernichteten Schiffe anlegen
			CString fileName="Combat.log";														// Name des zu Öffnenden Files 
			CStdioFile file;																	// Varibale vom Typ CStdioFile
			if (file.Open(fileName, CFile::modeCreate | CFile::modeWrite | CFile::typeText))	// Datei wird geöffnet
			{
				file.WriteString("Birth of the Empires - Combat Log file\n\n");
				for (set<CString>::const_iterator it = pDoc->combat.m_mInvolvedRaces.begin(); it != pDoc->combat.m_mInvolvedRaces.end(); ++it)
				{
					CString s;
					s.Format("----------------------------------------\nlost ships of race: %s\n", *it);
					file.WriteString(s);
					for (int j = 0; j < pDoc->m_ShipArray.GetSize(); j++)
						if (pDoc->m_ShipArray.GetAt(j).GetOwnerOfShip() == *it)
							if (pDoc->m_ShipArray.GetAt(j).GetHull()->GetCurrentHull() == 0)
								file.WriteString(pDoc->m_ShipArray.GetAt(j).GetShipClass()+"\n");
				}
			}
			file.Close();

			
			return;
		}

		p_timer->SuspendThread();
		Invalidate(FALSE);



		GetClientRect(r);

		CString fileName="Stats.log";														// Name des zu Öffnenden Files 
		CStdioFile file;																	// Varibale vom Typ CStdioFile
		if (file.Open(fileName, CFile::modeCreate | CFile::modeWrite | CFile::typeText))	// Datei wird geöffnet
		{
			CString s;
			file.WriteString("Birth of the Empires - Stats Log file\n\n");
			s.Format("overall combats: %d\n",pDoc->repeat);
			file.WriteString(s);
			for (std::map<CString, int>::const_iterator it = pDoc->wins.begin(); it != pDoc->wins.end(); ++it)
			{
				s.Format("----------------------------------------\nrace: %s wins %d combats", it->first, it->second);
				file.WriteString(s);
				s.Format(" -> %d%%\n", it->second * 100 / pDoc->repeat);
				file.WriteString(s);				
			}
		}
		file.Close();
		AfxMessageBox("Generating statsfile... ready\n\nClose this application or run a new one");
		
	
	}
Example #17
0
int main()
{
	
	order_map<S3DVertex, int> map;
	S3DVertex s = S3DVertex(Vector3(23, 12, 14), Vector3(231, 33, 22), ColourValue::getColourValue(255,255,255,255), Vector2(12, 34));
	map.insert(s, 1);
	order_map<S3DVertex, int>::Node* nofe = map.find(s);
	int i = nofe->getValue();
	

	/*
	The most important function of the engine is the createDevice()
	function. The IrrlichtDevice is created by it, which is the root
	object for doing anything with the engine. createDevice() has 7
	parameters:

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

	- windowSize: Size of the Window or screen in FullScreenMode to be
	created. In this example we use 640x480.

	- bits: Amount of color bits per pixel. This should be 16 or 32. The
	parameter is often ignored when running in windowed mode.

	- fullscreen: Specifies if we want the device to run in fullscreen mode
	or not.

	- stencilbuffer: Specifies if we want to use the stencil buffer (for
	drawing shadows).

	- vsync: Specifies if we want to have vsync enabled, this is only useful
	in fullscreen mode.

	- eventReceiver: An object to receive events. We do not want to use this
	parameter here, and set it to 0.

	Always check the return value to cope with unsupported drivers,
	dimensions, etc.
	*/
	Device *device =
		createDevice(EDT_OPENGL, dimension2d<Sapphire::UINT32>(1920, 1080), 32,
		false, false, false, 0);

	if (!device)
		return 1;
	
	/*
	Set the caption of the window to some nice text. Note that there is an
	'L' in front of the string. The Irrlicht Engine uses wide character
	strings when displaying text.
	*/
	device->setWindowCaption(L"HELLO WORLD!");

	/*
	Get a pointer to the VideoDriver, the SceneManager and the graphical
	user interface environment, so that we do not always have to write
	device->getVideoDriver(), device->getSceneManager(), or
	device->getGUIEnvironment().
	*/
	IVideoDriver* driver = device->getVideoDriver();
	ISceneManager* smgr = device->getSceneManager();
	IGUIEnvironment* guienv = device->getGUIEnvironment();

	/*
	We add a hello world label to the window, using the GUI environment.
	The text is placed at the position (10,10) as top left corner and
	(260,22) as lower right corner.
	*/
	guienv->addStaticText(L"Hello World!",
		rect<SINT32>(10, 10, 260, 22), true);

	/*
	To show something interesting, we load a Quake 2 model and display it.
	We only have to get the Mesh from the Scene Manager with getMesh() and add
	a SceneNode to display the mesh with addAnimatedMeshSceneNode(). We
	check the return value of getMesh() to become aware of loading problems
	and other errors.

	Instead of writing the filename sydney.md2, it would also be possible
	to load a Maya object file (.obj), a complete Quake3 map (.bsp) or any
	other supported file format. By the way, that cool Quake 2 model
	called sydney was modelled by Brian Collins.
	*/
	//IAnimatedMesh* mesh = smgr->getMesh("../../media/sydney.md2");
	//IAnimatedMesh* mesh = smgr->getMesh("media/q2mdl-wham/tris.md2");
	//IAnimatedMesh* mesh = smgr->getMesh("media/sydney.md2");
	IAnimatedMesh* mesh = smgr->getMesh("media/kokoro/kokoro.obj");
	if (!mesh)
	{
		device->drop();
		return 1;
	}
	
	IAnimatedMeshSceneNode* node = smgr->addAnimatedMeshSceneNode(mesh);
	//node->setDebugDataVisible(EDS_BBOX );
	/*
	To let the mesh look a little bit nicer, we change its material. We
	disable lighting because we do not have a dynamic light in here, and
	the mesh would be totally black otherwise. Then we set the frame loop,
	such that the predefined STAND animation is used. And last, we apply a
	texture to the mesh. Without it the mesh would be drawn using only a
	color.
	*/
	if (node)
	{
		node->setMaterialFlag(EMF_LIGHTING, false);
	//	node->setMD2Animation(EMAT_STAND);
		//node->setMaterialTexture(0, driver->getTexture("../../media/sydney.bmp"));
		
		//node->setMaterialTexture(0, driver->getTexture("media/sydney.bmp"));
	    // node->setMaterialTexture(0, driver->getTexture("media/q2mdl-wham/tundra.bmp"));
		//node->setMaterialTexture(0, driver->getTexture("media/kokoro/kok_face_d.tga"));
		//node->setMaterialTexture(0, driver->getTexture("media/kokoro/kok_acc1_d.tga"));
		//node->setMaterialTexture(0, driver->getTexture("media/kokoro/kok_body_d.tga"));
		//node->setMaterialTexture(0, driver->getTexture("media/kokoro/kok_body_d.tga"));
		//node->setMaterialTexture(0, driver->getTexture("media/kokoro/kok_hairback_s.tga"));
		node->setPosition(Vector3(1, 29, -39));
	    node->setRotation(Vector3(Math::DegreesToRadians(45), 0, 0));
		node->setRotation(Vector3(0, Math::DegreesToRadians(180), 0));
		
	}

	/*
	To look at the mesh, we place a camera into 3d space at the position
	(0, 30, -40). The camera looks from there to (0,5,0), which is
	approximately the place where our md2 model is.
	*/
	//smgr->addCameraSceneNode(0, Vector3(0, 30, -40), Vector3(0, 5, 0));
	ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS(0, 50.0f, 0.01f);
	camera->setTarget(Vector3(5, 10, 0));
	camera->setPosition(Vector3(0, 30, -40));

	/*
	Ok, now we have set up the scene, lets draw everything: We run the
	device in a while() loop, until the device does not want to run any
	more. This would be when the user closes the window or presses ALT+F4
	(or whatever keycode closes a window).
	*/
	while (device->run())
	{
		/*
		Anything can be drawn between a beginScene() and an endScene()
		call. The beginScene() call clears the screen with a color and
		the depth buffer, if desired. Then we let the Scene Manager and
		the GUI Environment draw their content. With the endScene()
		call everything is presented on the screen.
		*/
		driver->beginScene(true, true, ColourValue::getColourValue(255, 100, 101, 140));

 		smgr->drawAll();
		guienv->drawAll();

		driver->endScene();
	}

	/*
	After we are done with the render loop, we have to delete the Irrlicht 
	Device created before with createDevice(). In the Irrlicht Engine, you
	have to delete all objects you created with a method or function which
	starts with 'create'. The object is simply deleted by calling ->drop().
	See the documentation at irr::IReferenceCounted::drop() for more
	information.
	*/
	device->drop();

	return 0;
	return 0;
}
void CSceneNodeAnimatorCameraFPS::animateNode(ISceneNode* node, u32 timeMs)
{
	if (node->getType() != ESNT_CAMERA)
		return;

	ICameraSceneNode* camera = static_cast<ICameraSceneNode*>(node);

	if (firstUpdate)
	{
		camera->updateAbsolutePosition();
		if (CursorControl && camera)
		{
			CursorControl->setPosition(0.5f, 0.5f);
			CursorPos = CenterCursor = CursorControl->getRelativePosition();
		}

		LastAnimationTime = timeMs;

		firstUpdate = false;
	}

	// get time
	f32 timeDiff = (f32) ( timeMs - LastAnimationTime );
	LastAnimationTime = timeMs;

	// update position
	core::vector3df pos = camera->getPosition();

	// Update rotation
	core::vector3df target = (camera->getTarget() - camera->getAbsolutePosition());
	core::vector3df relativeRotation = target.getHorizontalAngle();

	if (CursorControl)
	{
		if (CursorPos != CenterCursor)
		{
			relativeRotation.Y -= (0.5f - CursorPos.X) * RotateSpeed;
			relativeRotation.X -= (0.5f - CursorPos.Y) * RotateSpeed;

			// X < MaxVerticalAngle or X > 360-MaxVerticalAngle

			if (relativeRotation.X > MaxVerticalAngle*2 &&
				relativeRotation.X < 360.0f-MaxVerticalAngle)
			{
				relativeRotation.X = 360.0f-MaxVerticalAngle;
			}
			else
			if (relativeRotation.X > MaxVerticalAngle &&
				relativeRotation.X < 360.0f-MaxVerticalAngle)
			{
				relativeRotation.X = MaxVerticalAngle;
			}

			// reset cursor position
			CursorControl->setPosition(0.5f, 0.5f);
			CenterCursor = CursorControl->getRelativePosition();
			// needed to avoid problems when the ecent receiver is
			// disabled
			CursorPos = CenterCursor;
		}
	}

	// set target

	target.set(0,0, core::max_(1.f, pos.getLength()));
	core::vector3df movedir = target;

	core::matrix4 mat;
	mat.setRotationDegrees(core::vector3df(relativeRotation.X, relativeRotation.Y, 0));
	mat.transformVect(target);

	if (NoVerticalMovement)
	{
		mat.setRotationDegrees(core::vector3df(0, relativeRotation.Y, 0));
		mat.transformVect(movedir);
	}
	else
	{
		movedir = target;
	}

	movedir.normalize();

	if (CursorKeys[EKA_MOVE_FORWARD])
		pos += movedir * timeDiff * MoveSpeed;

	if (CursorKeys[EKA_MOVE_BACKWARD])
		pos -= movedir * timeDiff * MoveSpeed;

	// strafing

	core::vector3df strafevect = target;
	strafevect = strafevect.crossProduct(camera->getUpVector());

	if (NoVerticalMovement)
		strafevect.Y = 0.0f;

	strafevect.normalize();

	if (CursorKeys[EKA_STRAFE_LEFT])
		pos += strafevect * timeDiff * MoveSpeed;

	if (CursorKeys[EKA_STRAFE_RIGHT])
		pos -= strafevect * timeDiff * MoveSpeed;

	// For jumping, we find the collision response animator attached to our camera
	// and if it's not falling, we tell it to jump.
	if (CursorKeys[EKA_JUMP_UP])
	{
		const core::list<ISceneNodeAnimator*> & animators = camera->getAnimators();
		core::list<ISceneNodeAnimator*>::ConstIterator it = animators.begin();
		while(it != animators.end())
		{
			if(ESNAT_COLLISION_RESPONSE == (*it)->getType())
			{
				ISceneNodeAnimatorCollisionResponse * collisionResponse = 
					static_cast<ISceneNodeAnimatorCollisionResponse *>(*it);

				if(!collisionResponse->isFalling())
					collisionResponse->jump(JumpSpeed);
			}

			it++;
		}
	}

	// write translation
	camera->setPosition(pos);

	// write right target

	TargetVector = target;
	target += pos;
	camera->setTarget(target);
}
Example #19
0
int main()
{
	// create device
    EventHandler receiver;
	Init();
	Output();
	ISceneNode* objects [MAX_OBJECTS];



	 IrrlichtDevice *device = createDevice(EDT_OPENGL, dimension2d<u32>(ResX, ResY), 32, fullscreen, false, vsync, &receiver); 
	 
	 receiver.device = device; 

    if (!device)
        return 1;

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

	HMDDescriptor HMD;
	// Parameters from the Oculus Rift DK1
	HMD.hResolution = ResX;
	HMD.vResolution = ResY;
	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, HMD, 10); 


	#ifdef OCCULUS
		ICameraSceneNode* camera = smgr->addCameraSceneNode();
		camera->bindTargetAndRotation(false);
		camera->setTarget(vector3df(1,0,0));
	#else	
		ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS();
	#endif	

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


	// load a faerie 
	IAnimatedMesh* faerie = smgr->getMesh("media/faerie.md2");
	IAnimatedMeshSceneNode* faerieNode = smgr->addAnimatedMeshSceneNode(faerie);
	faerieNode->setMaterialTexture(0, driver->getTexture("media/faerie2.bmp"));
	faerieNode->setMaterialFlag(EMF_LIGHTING, false);
	faerieNode->setPosition(vector3df(40,190,-1030));
	faerieNode->setRotation(vector3df(0,-90,0));
	faerieNode->setMD2Animation(EMAT_SALUTE);

	// load a dwarf
	IAnimatedMesh* dwarf = smgr->getMesh("media/dwarf.x");
	IAnimatedMeshSceneNode* dwarfNode = smgr->addAnimatedMeshSceneNode(dwarf);
	dwarfNode->setPosition(vector3df(40,-25,20));
	  
	
	Level currentLevel(device);
	currentLevel.makeLevel(0);

	smgr->setAmbientLight(video::SColorf(0.1,0.1,0.1,1));
	ILightSceneNode* light1 = smgr->addLightSceneNode( camera , vector3df(0,0,0), video::SColorf(0.3f,0.4f,0.4f), 80.0f, 1 );


	vector3df pos = vector3df(0,0,0);

	//naplníme tunel pøekážkama

	 srand (time(NULL));
	/* generate secret number between 1 and 10: */
	
	for(int i = 0; i < MAX_OBJECTS; i++){
		objects[i] = smgr->addCubeSceneNode(2);
		objects[i]->setMaterialFlag(EMF_LIGHTING, false);
		objects[i]->setPosition( vector3df( (rand() % 30) - 5, (rand() % 30) - 5, rand() % 80) );
	}

	//device->setInputReceivingSceneManager(smgr);
	
	//použivane pro 
	vector3df tempRot; 
	irr::core::quaternion tempQ;
	irr::core::matrix4 tempM;

	float round = 0;

    while(device->run())
    {
		round += 0.01;
        driver->beginScene(true, true, SColor(255,100,101,140));
		
		for(int i = 0; i < MAX_OBJECTS; i++){
			vector3df tmpPos = objects[i]->getPosition();
			if(tmpPos.Z > pos.Z) continue;
			
			objects[i]->setPosition( vector3df( (rand() % 30) - 15, (rand() % 30) - 15, rand() % 80 + pos.Z) );
		}
		
	#ifndef OCCULUS
			tempM.setRotationDegrees(vector3df(sin(round*0.5)*360-180, sin(round)*360-180, cos(round*0.8)*360-180));
			
			// transform forward vector of camera
			irr::core::vector3df frv = irr::core::vector3df (0.0f, 0.0f, 1.0f);
			tempM.transformVect(frv);
    
			// transform upvector of camera
		    irr::core::vector3df upv = irr::core::vector3df (0.0f, 1.0f, 0.0f);
			tempM.transformVect(upv);

		    camera->setUpVector(upv); //set up vector of camera
			camera->setTarget(frv); //set target of camera (look at point) (thx Zeuss for correcting it)

	#endif

		
		if(pSensor){
			Quatf quaternion = FusionResult.GetOrientation();

		   ICameraSceneNode* camera = smgr->getActiveCamera();
   
		   tempQ.set(-quaternion.z,quaternion.y,-quaternion.x, quaternion.w);
		   tempQ.normalize();
		   tempQ.toEuler(tempRot);
    
		   
			tempM.setRotationDegrees(tempRot);

			// transform forward vector of camera
			irr::core::vector3df frv = irr::core::vector3df (0.0f, 0.0f, 1.0f);
			tempM.transformVect(frv);
    
			// transform upvector of camera
		    irr::core::vector3df upv = irr::core::vector3df (0.0f, 1.0f, 0.0f);
			tempM.transformVect(upv);

		    camera->setUpVector(upv); //set up vector of camera
			camera->setTarget(frv); //set target of camera (look at point) (thx Zeuss for correcting it)

			// update absolute position
			camera->updateAbsolutePosition();



			float yaw, pitch, roll;
			quaternion.GetEulerAngles<Axis_Y, Axis_X, Axis_Z>(&yaw, &pitch, &roll);
			camera->getParent()->setRotation( vector3df(RadToDegree(pitch),RadToDegree(yaw),RadToDegree(roll)));
			//camera->setRotation( vector3df(RadToDegree(-pitch),RadToDegree(-yaw),RadToDegree(roll)));
			//camera->setProjectionMatrix(ToMatrix(quaternion));
			cout << " Yaw: " << RadToDegree(yaw) << 
				", Pitch: " << RadToDegree(pitch) << 
				", Roll: " << RadToDegree(roll) << endl;
		
			if (_kbhit()) exit(0);
		}

		#ifdef OCCULUS
			renderer.drawAll(smgr); 
		#else
			smgr->drawAll();
		#endif

        guienv->drawAll();

        driver->endScene();
    }


    device->drop();
	Clear();
    return 0;
}
Example #20
0
int main(int argc, char* argv[])
{
	// ask user for driver
	video::E_DRIVER_TYPE driverType=driverChoiceConsole();
	if (driverType==video::EDT_COUNT)
		return 1;

	MyEventReceiver receiver;
	IrrlichtDevice* device = createDevice(driverType,
			core::dimension2du(800, 600), 32, false, false, false,
			&receiver);

	if(device == 0)
		return 1;

	IVideoDriver *driver = device->getVideoDriver();
	ISceneManager *smgr = device->getSceneManager();
	device->setWindowCaption(L"Irrlicht Example for SMesh usage.");

	/*
	Create the custom mesh and initialize with a heightmap
	*/
	TMesh mesh;
	HeightMap hm = HeightMap(255, 255);
	hm.generate(eggbox);
	mesh.init(hm, 50.f, grey, driver);

	// Add the mesh to the scene graph
	IMeshSceneNode* meshnode = smgr -> addMeshSceneNode(mesh.Mesh);
	meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING, false);

	// light is just for nice effects
	ILightSceneNode *node = smgr->addLightSceneNode(0, vector3df(0,100,0),
		SColorf(1.0f, 0.6f, 0.7f, 1.0f), 500.0f);
	if (node)
	{
		node->getLightData().Attenuation.set(0.f, 1.f/500.f, 0.f);
		ISceneNodeAnimator* anim = smgr->createFlyCircleAnimator(vector3df(0,150,0),250.0f);
		if (anim)
		{
			node->addAnimator(anim);
			anim->drop();
		}
	}

	ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS();
	if (camera)
	{
		camera->setPosition(vector3df(-20.f, 150.f, -20.f));
		camera->setTarget(vector3df(200.f, -80.f, 150.f));
		camera->setFarValue(20000.0f);
	}

	/*
	Just a usual render loop with event handling. The custom mesh is
	a usual part of the scene graph which gets rendered by drawAll.
	*/
	while(device->run())
	{
		if(!device->isWindowActive())
		{
			device->sleep(100);
			continue;
		}

		if(receiver.IsKeyDown(irr::KEY_KEY_W))
		{
			meshnode->setMaterialFlag(video::EMF_WIREFRAME, !meshnode->getMaterial(0).Wireframe);
		}
		else if(receiver.IsKeyDown(irr::KEY_KEY_1))
		{
			hm.generate(eggbox);
			mesh.init(hm, 50.f, grey, driver);
		}
		else if(receiver.IsKeyDown(irr::KEY_KEY_2))
		{
			hm.generate(moresine);
			mesh.init(hm, 50.f, yellow, driver);
		}
		else if(receiver.IsKeyDown(irr::KEY_KEY_3))
		{
			hm.generate(justexp);
			mesh.init(hm, 50.f, yellow, driver);
		}

		driver->beginScene(video::ECBF_COLOR | video::ECBF_DEPTH, SColor(0xff000000));
		smgr->drawAll();
		driver->endScene();
	}

	device->drop();

	return 0;
}
//! OnAnimate() is called just before rendering the whole scene.
//! nodes may calculate or store animations here, and may do other useful things,
//! dependent on what they are.
void CSceneNodeAnimatorCameraMaya::animateNode(ISceneNode *node, u32 timeMs)
{
	//Alt + LM = Rotate around camera pivot
	//Alt + LM + MM = Dolly forth/back in view direction (speed % distance camera pivot - max distance to pivot)
	//Alt + MM = Move on camera plane (Screen center is about the mouse pointer, depending on move speed)

	if (node->getType() != ESNT_CAMERA)
		return;

	ICameraSceneNode* camera = static_cast<ICameraSceneNode*>(node);

	if (OldCamera != camera)
	{
		OldTarget = camera->getTarget();
		OldCamera = camera;
	}

	Target = camera->getTarget();

	const SViewFrustum* va = camera->getViewFrustum();

	f32 nRotX = RotX;
	f32 nRotY = RotY;
	f32 nZoom = CurrentZoom;

	if ( (isMouseKeyDown(0) && isMouseKeyDown(2)) || isMouseKeyDown(1) )
	{
		if (!Zooming)
		{
			ZoomStartX = MousePos.X;
			ZoomStartY = MousePos.Y;
			Zooming = true;
			nZoom = CurrentZoom;
		}
		else
		{
			f32 old = nZoom;
			nZoom += (ZoomStartX - MousePos.X) * ZoomSpeed;

			f32 targetMinDistance = 0.1f;
			if (nZoom < targetMinDistance) // jox: fixed bug: bounce back when zooming to close
				nZoom = targetMinDistance;

			if (nZoom < 0)
				nZoom = old;
		}
	}
	else
	{
		if (Zooming)
		{
			f32 old = CurrentZoom;
			CurrentZoom = CurrentZoom + (ZoomStartX - MousePos.X ) * ZoomSpeed;
			nZoom = CurrentZoom;

			if (nZoom < 0)
				nZoom = CurrentZoom = old;
		}

		Zooming = false;
	}

	// Translation ---------------------------------

	core::vector3df translate(OldTarget), UpVector(camera->getUpVector());

	core::vector3df tvectX = Pos - Target;
	tvectX = tvectX.crossProduct(UpVector);
	tvectX.normalize();

	core::vector3df tvectY = (va->getFarLeftDown() - va->getFarRightDown());
	tvectY = tvectY.crossProduct(UpVector.Y > 0 ? Pos - Target : Target - Pos);
	tvectY.normalize();
	

	if (isMouseKeyDown(2) && !Zooming)
	{
		if (!Translating)
		{
			TranslateStartX = MousePos.X;
			TranslateStartY = MousePos.Y;
			Translating = true;
		}
		else
		{
			translate +=  tvectX * (TranslateStartX - MousePos.X)*TranslateSpeed + 
			              tvectY * (TranslateStartY - MousePos.Y)*TranslateSpeed;
		}
	}
	else
	{
		if (Translating)
		{
			translate += tvectX * (TranslateStartX - MousePos.X)*TranslateSpeed + 
			             tvectY * (TranslateStartY - MousePos.Y)*TranslateSpeed;
			OldTarget = translate;
		}

		Translating = false;
	}

	// Rotation ------------------------------------

	if (isMouseKeyDown(0) && !Zooming)
	{
		if (!Rotating)
		{
			RotateStartX = MousePos.X;
			RotateStartY = MousePos.Y;
			Rotating = true;
			nRotX = RotX;
			nRotY = RotY;
		}
		else
		{
			nRotX += (RotateStartX - MousePos.X) * RotateSpeed;
			nRotY += (RotateStartY - MousePos.Y) * RotateSpeed;
		}
	}
	else
	{
		if (Rotating)
		{
			RotX = RotX + (RotateStartX - MousePos.X) * RotateSpeed;
			RotY = RotY + (RotateStartY - MousePos.Y) * RotateSpeed;
			nRotX = RotX;
			nRotY = RotY;
		}

		Rotating = false;
	}

	// Set Pos ------------------------------------

	Target = translate;

	Pos.X = nZoom + Target.X;
	Pos.Y = Target.Y;
	Pos.Z = Target.Z;

	Pos.rotateXYBy(nRotY, Target);
	Pos.rotateXZBy(-nRotX, Target);

	// Rotation Error ----------------------------

	// jox: fixed bug: jitter when rotating to the top and bottom of y
	UpVector.set(0,1,0);
	UpVector.rotateXYBy(-nRotY);
	UpVector.rotateXZBy(-nRotX+180.f);

	camera->setPosition(Pos);
	camera->setTarget(Target);
	camera->setUpVector(UpVector);
}
Example #22
0
void loop(s4 &game_state)
{
    ICameraSceneNode* camera = irrlicht->smgr->addCameraSceneNode();
    matrix4 ortho;
    ortho.buildProjectionMatrixOrthoLH(
        irrlicht->driver->getScreenSize().Width/ortho_scale,
        irrlicht->driver->getScreenSize().Height/ortho_scale,-1.0,1000.0);
    camera->setProjectionMatrix(ortho);
    camera->setPosition({0,0,-100});
    camera->setTarget({0,0,0});

    irrlicht->hud->setActiveCamera(camera);

    IBillboardSceneNode* qnode = irrlicht->smgr->addBillboardSceneNode();
    qnode->setMaterialFlag(EMF_WIREFRAME,true);

    // --------------------------------------
 
    p("---- Game loop start ----");

    d32         dt = 0.0f;
    const d32   maxDelta = 1.0f/60.0f * 5.0f; 
    const d32   tick_ms = 0.01666f; // TODO: change this back to 30ms?
    d32         render_dt = 0.0f;
    const d32   render_ms = RENDER_TIME_STEP;
    uint32      time_physics_prev = btclock->getTimeMicroseconds();

    while(irrlicht->device->run() && game_state == GAME_STATE_PLAY)
    {
        const uint32 time_physics_curr = btclock->getTimeMicroseconds();
        const d32 frameTime = ((d32)(time_physics_curr - time_physics_prev)) / 1000000.0; // todo: is this truncated correctly?
        time_physics_prev = time_physics_curr;
        d32 capped_dt = frameTime;
        if (capped_dt > maxDelta) { capped_dt = maxDelta; }

        render_dt += capped_dt;
        if ( render_dt >= render_ms )
        {
            render_dt = 0.0f;

            update_player();
            update_enemies();
            update_missiles(ply->missiles,ply->num_missile);

            irrlicht->hud->getRootSceneNode()->setPosition(camera->getPosition() + vector3df(0,0,100));

            irrlicht->driver->beginScene(true, true, SColor(255,59,120,140));
            irrlicht->smgr->drawAll();  
            irrlicht->driver->clearZBuffer(); 
            irrlicht->hud->drawAll();

            irrlicht->driver->endScene();
        }

        dt += capped_dt;
        while( dt >= tick_ms ) 
        {
            dt -= tick_ms;
            receiver->input();

            clear_quads(quadtree);
            step_player();
            step_enemies();
            step_missiles(ply->missiles, ply->num_missile); 

            QuadTree::Quad* fq = get_quad_from_pos(quadtree,ply->curr_pos);
            qnode->setSize(dimension2d<f32>(1,1));
            qnode->setPosition(fq->pos.irr());
            qnode->setSize(dimension2d<f32>(fq->width,fq->width));
 
            if (receiver->debug_key.state)
            {
                for (s4 i = 0; i < fleet->num_squad; i++)
                {
                    if (fleet->squads[i].mode != scatter)
                        fleet->squads[i].mode = scatter;
                    else
                        fleet->squads[i].mode = to_positions;
                }
            }
            if (receiver->restart.state) { game_state = GAME_STATE_RESET; return; }
            if (receiver->QUIT) { game_state = GAME_STATE_QUIT; return; }

            empty_transient_soft(memory);
        }

        alpha = dt / tick_ms;

        core::stringw str = L"Coquelicot // score: ";
        str += score;
        str += L" // FPS: ";
        str += (s32)irrlicht->driver->getFPS();
        irrlicht->device->setWindowCaption(str.c_str());
    } 
}
Example #23
0
void loop_ctr(s4 &game_state)
{ 
    ISceneNode* empty_node = irrlicht->smgr->addEmptySceneNode();
    empty_node->setPosition(vector3df(0,0,0));
    ICameraSceneNode* camera = irrlicht->smgr->addCameraSceneNode(); 
    camera->setPosition({0,-250,-100});
    camera->setUpVector({0,0,-1});
    camera->setTarget({0,0,0});
    camera->setParent(empty_node);
    camera->setFOV(70);

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

    irrlicht->smgr->setAmbientLight(SColorf(1,1,1,1));
    irrlicht->hud = irrlicht->smgr->createNewSceneManager(false);
    ICameraSceneNode* hud_camera = irrlicht->hud->addCameraSceneNode();
    matrix4 ortho;
    ortho.buildProjectionMatrixOrthoLH(
        irrlicht->driver->getScreenSize().Width/ortho_scale,
        irrlicht->driver->getScreenSize().Height/ortho_scale,-1.0,1000.0);
    hud_camera->setProjectionMatrix(ortho);
    hud_camera->setPosition({0,0,-100});
    hud_camera->setTarget({0,0,0});
    
    // temp objects ----------------------------------
    blist cmpnt_list, joint_list, tree_list;
    b_set(cmpnt_list,memory,sizeof(Component));
    b_set(joint_list,memory,sizeof(Joint)); 
    b_set(tree_list,memory,sizeof(CTree));

    irr::core::map<ISceneNode*,Component*> node_cmpnt_map;
    ISceneNode* ctr_parent = irrlicht->smgr->addEmptySceneNode();
    IMesh* cube_mesh = irrlicht->smgr->getGeometryCreator()->createCubeMesh();

    auto add_object_to_world = [&] (vec3 pos, vec3 scale, s4 a, s4 r, s4 g, s4 b) -> Component*
    {
        const f4 floor_position = 10.0f;
        Component make_cmpnt;
        make_cmpnt.id = CMPNT_ID; CMPNT_ID++;
        make_cmpnt.node = irrlicht->smgr->addMeshSceneNode(cube_mesh,ctr_parent);
        make_cmpnt.node->setPosition(pos.irr()); 
        make_cmpnt.node->setScale(scale.irr());
        make_cmpnt.node->getMaterial(0).AmbientColor.set(a,r,g,b);
        make_cmpnt.shadow = irrlicht->smgr->addMeshSceneNode(cube_mesh,0);
        make_cmpnt.shadow->setScale({scale.x, scale.y, 0.1f}); 
        make_cmpnt.shadow->setPosition({pos.x, pos.y,floor_position}); 
        make_cmpnt.shadow->getMaterial(0).AmbientColor.set(GREY_BLUE_SHADOW);
        for (s4 i = 0; i < MAX_JOINTS; i++)
            make_cmpnt.joints[i] = 0;
        make_cmpnt.tree = 0;
        
        b_copy(cmpnt_list,&make_cmpnt);
        node_cmpnt_map.insert(make_cmpnt.node, (Component*)blast_address(cmpnt_list) );
        
        return (Component*)blast_address(cmpnt_list);
    };

    auto add_joint = [&] (Component* A, Component* B, vec3 posA, vec3 posB)
    {
        Joint C;
        C.A = A;
        C.posA = A->node->getTransformedBoundingBox().getExtent() * A->node->getScale();
        C.posA *= (posA * 0.5f);
        C.B = B;
        C.posB = B->node->getTransformedBoundingBox().getExtent() * B->node->getScale();
        C.posB *= (posB * 0.5f);
        C.type = Joint::SNAP;
        C.is_connected = false;

        b_copy(joint_list,&C);

        for (s4 i = 0; i < MAX_JOINTS; i++)
        {
            if (C.A->joints[i] == 0)
            {
                C.A->joints[i] = (Joint*)blast_address(joint_list);
                break;
            } else if (i == MAX_JOINTS-1)
            {
                std::cout << "ERROR: Joint could not be added to C.A." << std::endl;
            }
        }

        for (s4 i = 0; i < MAX_JOINTS; i++)
        {
            if (C.B->joints[i] == 0)
            {
                C.B->joints[i] = (Joint*)blast_address(joint_list);
                break;
            } else if (i == MAX_JOINTS-1)
            {
                std::cout << "ERROR: Joint could not be added to C.B." << std::endl;
            }
        }
    };

    {
        Component* A = add_object_to_world(vec3(0,30,-20),vec3(3,3,3),BLUE_LIGHT);
        Component* B = add_object_to_world(vec3(0,60,-20),vec3(9,3,2),BLACK);
        add_joint(A,B,vec3(0.0f,0.0f,1.0f),vec3(0.0f,0.0f,-1.0f));

        Component* C = add_object_to_world(vec3(0,-90,-20),vec3(3,3,3),YELLOW_LIGHT);
        Component* D = add_object_to_world(vec3(0,-40,-20),vec3(8,10,4),GREEN_LIGHT);
        add_joint(C,D,vec3(0.0f,1.0f,0.0f),vec3(0.0f,-1.0f,0.0f)); 

        add_joint(A,D,vec3(0.0f,0.0f,-1.0f),vec3(0.0f,0.0f,1.0f)); 
    }
    // temp objects ----------------------------------

    SimpleNodeEditor* sneditor = simple_node_editor_init();
    sneditor->root_node = ctr_parent;  

    f4 target_z_rotation = empty_node->getRotation().Z; 
 

    p("---- Game loop start ----");

    f4         dt = 0.0f;
    const f4   maxDelta = 1.0f/60.0f * 5.0f; 
    const f4   tick_ms = 0.01666f;
    f4         render_dt = 0.0f;
    const f4   render_ms = 0.016667f;
    u4         time_physics_prev = btclock->getTimeMicroseconds();

    while(irrlicht->device->run() && game_state == GAME_STATE_PLAY)
    {
        const u4 time_physics_curr = btclock->getTimeMicroseconds();
        const f4 frameTime = ((f4)(time_physics_curr - time_physics_prev)) / 1000000.0; // todo: is this truncated correctly?
        time_physics_prev = time_physics_curr;
        f4 capped_dt = frameTime;
        if (capped_dt > maxDelta) { capped_dt = maxDelta; }

        render_dt += capped_dt;
        if ( render_dt >= render_ms )
        {
            render_dt = 0.0f;

            f4 curr_rotation = empty_node->getRotation().Z;
            if (curr_rotation != target_z_rotation)
            {
                weighted_average(curr_rotation,target_z_rotation, 20.0f);

                if (curr_rotation >= 360.0f) {
                    curr_rotation -= 360.0f;
                    target_z_rotation -= 360.0f;
                }
                else if (curr_rotation < 0) {
                    curr_rotation += 360.0f;
                    target_z_rotation += 360.0f;
                }

                empty_node->setRotation({0,0,curr_rotation});
            }

            if (sneditor->selected_node)
            {
                position2d<s32> screen_coord = irrlicht->colmgr->getScreenCoordinatesFrom3DPosition(sneditor->selected_node->getPosition(), camera);
                sneditor->hand_icon->setPosition({(screen_coord.X - (SCREEN_WIDTH/2)) / ortho_scale,
                                              (screen_coord.Y - (SCREEN_HEIGHT/2)) / -ortho_scale,0});
            } else {
                sneditor->hand_icon->setPosition({(sneditor->cursor->getPosition().X - (SCREEN_WIDTH/2)) / ortho_scale,
                                              (sneditor->cursor->getPosition().Y - (SCREEN_HEIGHT/2)) / -ortho_scale,0});
            } 
            
            // Render
            irrlicht->driver->beginScene(true, true, SColor(GREY_BLUE));
                irrlicht->smgr->drawAll();  
                irrlicht->driver->clearZBuffer();
                irrlicht->hud->drawAll();
            irrlicht->driver->endScene();
        }

        dt += capped_dt;
        while( dt >= tick_ms ) 
        {
            dt -= tick_ms;
            receiver->input();

            if (receiver->a.state)
                target_z_rotation -= 90.0f;
            if (receiver->d.state)
                target_z_rotation += 90.0f;

            simple_node_editor_update(
                sneditor, receiver->mouse.left.state, receiver->mouse.left.released, receiver->mouse.right.state,
                false, receiver->tab.state, camera, &node_cmpnt_map);

            // TODO: Change this to:
            // - only test what the user is holding
            // - and only if the user is holding the smaller inserting part.
            // example: holding a screw in a large box

            bloop(joint_list, i)
            {
                Joint* c = (Joint*)b_get_mem_address(joint_list,i);
                
                if (c->A->tree != sneditor->selected_tree && c->B->tree != sneditor->selected_tree )
                {
                    continue;
                }

                if (!c->is_connected)
                { 

                    vec3 A = c->A->node->getPosition();
                    vec3 B = c->B->node->getPosition();
                    A += c->posA;
                    B += c->posB;

                    if (A.distance(B) < 13 /* && receiver->spacebar*/)
                    { 
                        std::cout << "Comparing " << i << std::endl;
                        c->is_connected = true;
                        connect_joints(c,sneditor,camera,tree_list);
                    }
                }
            }

            bloop(tree_list, i)
            {
                CTree* tree = (CTree*)b_get_mem_address(tree_list,i);
                if (tree->translation == vec3(0,0,0))
                {
                    continue;
                }
                for (s4 k = 0; k < tree->child_list.length;k++)
                { 
                    Component* cmpnt = (Component*)b_get_value(tree->child_list,k); 
                    cmpnt->node->setPosition(cmpnt->node->getPosition() + tree->translation.irr());
                    cmpnt->shadow->setPosition(cmpnt->node->getPosition() * vector3df(1,1,0) + vector3df(0,0,10));
                }
                tree->translation = vec3(0,0,0);
            }

            if (receiver->restart.state) { game_state = GAME_STATE_RESET; }
            if (receiver->QUIT) { game_state = GAME_STATE_QUIT; }
        }
void CSceneNodeAnimatorCollisionResponse::animateNode(ISceneNode* node, u32 timeMs)
{
	CollisionOccurred = false;

	if (node != Object)
		setNode(node);

	if(!Object || !World)
		return;

	// trigger reset
	if ( timeMs == 0 )
	{
		FirstUpdate = true;
		timeMs = LastTime;
	}

	if ( FirstUpdate )
	{
		LastPosition = Object->getPosition();
		Falling = false;
		LastTime = timeMs;
		FallingVelocity.set ( 0, 0, 0 );

		FirstUpdate = false;
	}

	const u32 diff = timeMs - LastTime;
	LastTime = timeMs;

	CollisionResultPosition = Object->getPosition();
	core::vector3df vel = CollisionResultPosition - LastPosition;

	FallingVelocity += Gravity * (f32)diff * 0.001f;

	CollisionTriangle = RefTriangle;
	CollisionPoint = core::vector3df();
	CollisionResultPosition = core::vector3df();
	CollisionNode = 0;

	core::vector3df force = vel + FallingVelocity;

	if ( AnimateCameraTarget )
	{
		// TODO: divide SlidingSpeed by frame time

		bool f = false;
		CollisionResultPosition
			= SceneManager->getSceneCollisionManager()->getCollisionResultPosition(
				World, LastPosition-Translation,
				Radius, vel, CollisionTriangle, CollisionPoint, f,
				CollisionNode, SlidingSpeed, FallingVelocity);

		CollisionOccurred = (CollisionTriangle != RefTriangle);

		CollisionResultPosition += Translation;

		if (f)//CollisionTriangle == RefTriangle)
		{
			Falling = true;
		}
		else
		{
			Falling = false;
			FallingVelocity.set(0, 0, 0);
		}

		bool collisionConsumed = false;

		if (CollisionOccurred && CollisionCallback)
			collisionConsumed = CollisionCallback->onCollision(*this);

		if(!collisionConsumed)
			Object->setPosition(CollisionResultPosition);
	}

	// move camera target
	if (AnimateCameraTarget && IsCamera)
	{
		const core::vector3df pdiff = Object->getPosition() - LastPosition - vel;
		ICameraSceneNode* cam = (ICameraSceneNode*)Object;
		cam->setTarget(cam->getTarget() + pdiff);
	}

	LastPosition = Object->getPosition();
}
Example #25
0
int main(int argc, char** argv) {
	CustomEventReceiver receiver;
	IrrlichtDevice *device = createDevice( video::EDT_OPENGL, dimension2d<u32>(800, 600), 16, false, false, false, &receiver);
	if (!device) {
		return EXIT_FAILURE;
    }
	device->setWindowCaption(L"Solar System Simulator");
	IVideoDriver* driver = device->getVideoDriver();
	ISceneManager* sceneManager = device->getSceneManager();
	scene::ISceneCollisionManager* collisionManager= sceneManager->getSceneCollisionManager();
	IGUIEnvironment* guiEnv = device->getGUIEnvironment();
	guiEnv->addStaticText(L"Click on a planet to attach the camera to it", rect<s32>(10,10,260,22), false);

	sf::SoundBuffer buffer;
	if (buffer.loadFromFile(currentPath() + "/sounds/burning.aif")) {
		sf::Listener::setPosition(0, 0,0);

		sf::Sound sound;
		sound.setBuffer(buffer);
		sound.setPosition(0, 0, 0);
		sound.setLoop(true);
		sound.play();
	}

	const char* spaceTexturePath = ( currentPath() + "/textures/space.jpg" ).c_str();
	video::ITexture* space = driver->getTexture(spaceTexturePath);
	scene::ISceneNode* skybox = sceneManager->addSkyBoxSceneNode(space, space, space, space, space, space);

	sceneManager->addLightSceneNode(0, vector3df(0, 0, -50),  video::SColorf(1.0f, 1.0f, 1.0f), 50.0f, 1001);

	PlanetFactory planetFactory(sceneManager, driver);
	Planet sun = planetFactory.create(PlanetId::Sun);
	Planet earth = planetFactory.create(PlanetId::Earth);
	Planet pluto = planetFactory.create(PlanetId::Pluto);
	Planet jupiter = planetFactory.create(PlanetId::Jupiter);
	Planet uranus = planetFactory.create(PlanetId::Uranus);
	Planet neptune = planetFactory.create(PlanetId::Neptune);

	vector<Planet> planets = { sun, planetFactory.create(PlanetId::Mercury) };
	planets.push_back(planetFactory.create(PlanetId::Venus));
	planets.push_back(earth);
	planets.push_back(planetFactory.create(PlanetId::Mars));
	planets.push_back(jupiter);
	planets.push_back(planetFactory.create(PlanetId::Saturn));
	planets.push_back(uranus);
	planets.push_back(neptune);
	planets.push_back(pluto);

	ICameraSceneNode* camera = sceneManager->addCameraSceneNode(0, vector3df(0,0,40), vector3df(0,0,0));
	rect<s32> mainCameraViewPortRect(0, 0, 800, 600);

	ICameraSceneNode* topViewCamera = sceneManager->addCameraSceneNode(0, vector3df(0,50,0), vector3df(0,0,0));
	
	sceneManager->setAmbientLight(video::SColorf(255.0,255.0,255.0));

	ISceneNode* selectedNode = sun.node;
	while(device->run()) {

		if(receiver.GetMouseState().LeftButtonDown) {
			position2di mousepos = receiver.GetMouseState().Position;
			line3df ray = sceneManager->getSceneCollisionManager()->getRayFromScreenCoordinates( mousepos, camera);

			vector3df intersection;
			triangle3df tri;

            for(Planet& planet : planets) {
				ITriangleSelector* wselector = sceneManager->createTriangleSelectorFromBoundingBox(planet.node);
				if (collisionManager->getCollisionPoint(ray, wselector, intersection, tri, planet.node)) {
					selectedNode = planet.node;
				}
				wselector->drop();
			}
		}

		camera->setTarget(selectedNode->getAbsolutePosition());

		skybox->setVisible(true);		
        
		driver->setViewPort(mainCameraViewPortRect);
		driver->beginScene(true, true, SColor(255,100,101,140));
		sceneManager->setActiveCamera(camera);
		sceneManager->drawAll();
		guiEnv->drawAll();

		driver->setViewPort(rect<s32>(0, 380, 200, 600));
		driver->draw2DRectangle(SColor(100,0,0,190), mainCameraViewPortRect);
		skybox->setVisible(false);		
		sceneManager->setActiveCamera(topViewCamera);
		sceneManager->drawAll();
		
		driver->endScene();
	}
	device->drop();

	return EXIT_SUCCESS;
}