Esempio n. 1
0
void CameraToolKit::setCameraPosition( unsigned int iID, vector3df position )
{
	ICameraSceneNode *pCamera = getCamera( iID );

	if ( pCamera )
		pCamera->setPosition( position );
}
Esempio n. 2
0
int main( ) {
	// Boring stuff: set up the scene, object & camera as usual
	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"Lens Flare", rect<s32>( 10, 10, 260, 22 ), true );
	IAnimatedMeshSceneNode* node = smgr->addAnimatedMeshSceneNode( smgr->getMesh( "sydney.md2" ) );
	node->setMaterialFlag( EMF_LIGHTING, false );
	node->setMD2Animation( scene::EMAT_STAND );
	node->setMaterialTexture( 0, driver->getTexture("sydney.bmp") );
	IAnimatedMeshSceneNode* node2 = smgr->addAnimatedMeshSceneNode( smgr->getMesh( "sydney.md2" ) );
	node2->setMaterialFlag( EMF_LIGHTING, false );
	node2->setMD2Animation( scene::EMAT_STAND );
	node2->setMaterialTexture( 0, driver->getTexture("sydney.bmp") );
	node2->setPosition( vector3df( 20.0f, 0.0f, 0.0f ) );
	ICameraSceneNode* cam = smgr->addCameraSceneNode( 0, vector3df( 40.0f, 30.0f, -40.0f ), vector3df( 0.0f, 5.0f, 0.0f ) );

	ISceneNode* sun = smgr->addSphereSceneNode( 50.0f, 16 );
	sun->setPosition( vector3df( 0.0f, 50.0f, 1000.0f ) );
	sun->setMaterialFlag( EMF_LIGHTING, false );
	sun->setMaterialTexture( 0, driver->getTexture("sun.png") );
	// Interesting stuff

	// As before, we make a renderer
	IPostProc* ppRenderer = new CRendererPostProc( smgr, dimension2di( 1024, 512 ), true, true, SColor( 255u, 100u, 101u, 140u ) );
	// Now make a flare effect:
	// (render from, output size, sun scene node)
	// can also use a vector instead of a scene node - when using a scene node the position will follow node automatically
	CLensFlarePostProc* ppFlare1 = new CLensFlarePostProc( ppRenderer, dimension2di( 1024, 512 ), driver->getTexture("flare.png"), sun, 50.0f );
	CLensFlarePostProc* ppFlare2 = new CLensFlarePostProc( ppFlare1, dimension2di( 1024, 512 ), driver->getTexture("flare.png"), vector3df( -2000.0f, 50.0f, 1000.0f ) );
	ppFlare2->setQuality( PPQ_CRUDE ); // Setting the quality to crude avoids pixel checking, which is slow (expecially when more than one lens flare), so if you use >1 flare, set most of them to crude.

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

	while( device->run( ) ) {
		cam->setPosition( vector3df( -(device->getCursorControl( )->getPosition( ).X - 320.0f) * 0.1f, (device->getCursorControl( )->getPosition( ).Y - 240.0f) * 0.2f, -70.0f ) );
		driver->beginScene( false, driver->getDriverType( ) == video::EDT_DIRECT3D9 );
		ppFlare2->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 ppFlare1;
	delete ppFlare2;
	delete ppRenderer;

	// Back to boring stuff
	device->drop();
	return 0;
}
Esempio n. 3
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();
  }
}
Esempio n. 6
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; }
        }
Esempio n. 7
0
int main()
{

	

	IrrlichtDevice *device =
		createDevice(video::EDT_OPENGL, core::dimension2d<u32>(1280, 720));
	Receiver * recv = new Receiver();
	if (device == 0)
		return 1; // could not create selected driver.
	
	video::IVideoDriver* driver = device->getVideoDriver();
	 smgr = device->getSceneManager();

	device->getFileSystem()->addZipFileArchive("map-20kdm2.pk3");

	device->setEventReceiver(recv);

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

	if (mesh)
		node = smgr->addOctreeSceneNode(mesh->getMesh(0), 0, -1, 1024);

	if (node)
		node->setPosition(core::vector3df(-1350,-130,-1400));
	
	
	ICameraSceneNode * cam =  smgr->addCameraSceneNodeFPS(0,100,0.5f);
	cam->setPosition(vector3df(-20,60,-30));
	
	
	device->getCursorControl()->setVisible(false);

	bulletmgr = createBulletManager(device);
	bulletmgr->getWorld()->setGravity(vector3df(0,-10,0));
	bulletmgr->getWorld()->setTimeStep(1.0f/1000.0f);
	bulletmgr->addTrimesh(node,0);

	int xshift,yshift,zshift;
	IMeshSceneNode * Node;
	IMeshSceneNode * Node2;
	Node = smgr->addCubeSceneNode(5,0,-1,vector3df(-20,30,0));
	Node->setMaterialFlag(EMF_LIGHTING,false);
	Node->setMaterialTexture(0,driver->getTexture("sphere1.jpg"));
	box= bulletmgr->addRigidBox(Node,0);
	box->setKinematic(true);
	CIrrBPBoxBody * box2;
	for(int i=0;i<100;i++)
	{
	Node2 = smgr->addCubeSceneNode(5,0,-1,vector3df(0,50 +(i*7),0));
	//Node2->setMaterialType(EMT_TRANSPARENT_ADD_COLOR);
	Node2->setMaterialFlag(EMF_LIGHTING,false);
	Node2->setMaterialTexture(0,driver->getTexture("sphere1.jpg"));
	
	box2 = bulletmgr->addRigidBox(Node2,10);
	
	}
		
	
	const float	s=21;
	const float	h=21;
	
//	bulletmgr->getWorld()->createDebugDrawer();
//	bulletmgr->getWorld()->setDebugDrawerFlags(DBG_DrawWireframe);

	int lastFPS = -1;

	
	while(device->run())
	{
		if (device->isWindowActive())
		{
			driver->beginScene(true, true, video::SColor(255,200,200,200));
			//bulletmgr->getWorld()->stepDebugDrawer();
			bulletmgr->stepSimulation();

			smgr->drawAll();
		
			int fps = driver->getFPS();

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

				device->setWindowCaption(str.c_str());
				lastFPS = fps;
			}
			driver->endScene();
			
		}
		else
			device->yield();
	}
	/*
	In the end, delete the Irrlicht device.
*/
	delete recv;
	bulletmgr->drop();
	device->drop();
	return 0;
}
Esempio n. 8
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());
    } 
}
Esempio n. 9
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;
}
Esempio n. 10
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");
		
	
	}
Esempio n. 11
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);
}
Esempio n. 13
0
int main()
{


/*		shadowDimen = dimension2du(1024,1024);
		shadowDimen = dimension2du(2048,2048);
		shadowDimen = dimension2du(4096,4096);
		shadowDimen = dimension2du(2048,2048);
		filterType = EFT_NONE;
		filterType = EFT_4PCF;
		filterType = EFT_8PCF;
		filterType = EFT_4PCF;
*/
	dimension2du shadowDimen = dimension2du(1024,1024);
    E_FILTER_TYPE filterType = EFT_4PCF;
    filterType = EFT_NONE;
////


IrrlichtDevice* device = createDevice(EDT_OPENGL,dimension2du(800,600),32);

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

ICameraSceneNode* cam = smgr->addCameraSceneNodeFPS(0,100,.5);
cam->setPosition(vector3df(0,10,0));

// Create the effect handler, passing the device and RTT size (as a dimension2d) .
effectHandler* effect = new effectHandler(device,shadowDimen);


ITerrainSceneNode* terrain = smgr->addTerrainSceneNode("media/terrain.bmp",0,-1,vector3df(0,0,0),vector3df(0,0,0),vector3df(1,1,1),SColor(255,255,255,255),1,ETPS_33);
terrain->setMaterialTexture(0,driver->getTexture("media/terrain.jpg"));
terrain->setMaterialTexture(1, driver->getTexture("media/detailmap.jpg"));
terrain->scaleTexture(1,10);
terrain->setScale(core::vector3df(4, 0.01f, 4));
terrain->setPosition(vector3df(-120,-1.5f,-120));
terrain->setMaterialType(EMT_DETAIL_MAP);

// Make the terrain recieve a shadow with the specified filter type.
// (NOTE: 12PCF is only available in Direct3D9, all others work with OpenGL)
effect->addShadowToNode(terrain,filterType);

IAnimatedMeshSceneNode* sydney;
IAnimatedMesh* sydneymesh = smgr->getMesh("media/dwarf.x");

for(int g = 0;g < 1;g++)
{
	for(int v = 0;v < 3;v++)
	{
		sydney = smgr->addAnimatedMeshSceneNode(sydneymesh);
		sydney->setScale(vector3df(0.05f,0.05f,0.05f));
		sydney->setPosition(vector3df(g * 4,0.5f,v * 4));
		sydney->setMaterialFlag(EMF_NORMALIZE_NORMALS,true);

		sydney->setAutomaticCulling(EAC_FRUSTUM_BOX);

		sydney->setMaterialType(EMT_SOLID);

		// Add the nodes to the depth pass so that they cast a shadow.
		effect->addNodeToDepthPass(sydney);

	}
}


effect->getLightCamera()->addAnimator(smgr->createFlyCircleAnimator(sydney->getPosition() + vector3df(0,15,0),25,0.0002f));

effect->getLightCamera()->setNearValue(5);

effect->setMaxShadowDistanceFromLight(120);

smgr->addLightSceneNode(effect->getLightCamera());


MyEventReceiver receiver(cam);
device->setEventReceiver(&receiver);

// Parent a sphere to the light camera so we can see its position.
smgr->addSphereSceneNode(1,8,effect->getLightCamera())->setMaterialFlag(EMF_LIGHTING,false);



while(device->run())
{
	wchar_t tmp[255];
	swprintf(tmp,255,L"Shadow Map Demo (FPS: %d)",driver->getFPS());
	device->setWindowCaption(tmp);

	driver->beginScene(true,true,SColor(0,0,0,0));

	// Point the light camera at one of the nodes as it rotates around them.
	effect->setLightTarget(sydney->getPosition());

	// Update the effect  handler, remember to always do this BEFORE smgr->drawAll and AFTER beginscene!
	effect->update();

	smgr->drawAll();

	// If user wishes we can display the shadow map to the screen. (May not work in OpenGL)
	if(disp2d)
		driver->draw2DImage(effect->getShadowMapTexture(),position2d<s32>(0,0));

	driver->endScene();
	//	device->sleep(5);
}

device->drop();
return 0;
}
Esempio n. 14
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;
}
Esempio n. 15
0
void Mesh3DInitScene()
{
	IAnimatedMesh*				mesh;
	IAnimatedMeshSceneNode*     node;
	scene::ISceneNodeAnimator*  anim;
	scene::ISceneManager*		smgr   = IrrlichtManager::GetIrrlichtManager()->GetScene();
	IrrlichtDevice*				device = IrrlichtManager::GetIrrlichtManager()->GetDevice();
	video::IVideoDriver*		driver = IrrlichtManager::GetIrrlichtManager()->GetDriver();
	
	std::string					load_zip;
	std::string					load_data;
	std::string					reload_path;
	FileSystemZip*				pfilesystem			= NULL;
	io::IReadFile*				memfile				= NULL;
	byte*						apk_buffer			= NULL;
	byte*						buff_extract		= NULL;
	int							size				= 0;
	int							apk_size			= 0;

	if (!IrrlichtManager::GetIrrlichtManager()->GetDevice())
	{
		LogError("Error initializing Irrlicht");
		return;
	}
	
	IrrlichtManager::GetIrrlichtManager()->GetDevice()->getTimer()->setTime(0);
		
    smgr->addLightSceneNode(0, core::vector3df(-100,10,0), video::SColorf(1.0f, 1.0f, 1.0f, 1.0f), 200.0f);
    smgr->addLightSceneNode(0, core::vector3df(+100,10,0), video::SColorf(1.0f, 1.0f, 1.0f, 1.0f), 200.0f);
	
		
//////////////////////////////mesh/////////////////////////////////////////////////
	load_zip	= (GetBaseAppPath() + "game/ninja.zip").c_str();
	load_data	= "ninja.b3d";
	reload_path	= (GetBaseAppPath() + "game/ninja.b3d").c_str();
	
#ifdef ANDROID_NDK
	apk_buffer	= FileManager::GetFileManager()->Get(load_zip.c_str(), &apk_size, false, false);
	
	if( apk_buffer )
	{
		pfilesystem	= new FileSystemZip();
		pfilesystem->Init_unzMemory(apk_buffer, apk_size);
		buff_extract = pfilesystem->Get_unz(load_data, &size);

		delete apk_buffer;
		apk_buffer = NULL;
	}
#else
	pfilesystem = new FileSystemZip();
	pfilesystem->Init_unz(load_zip.c_str());
	buff_extract = pfilesystem->Get_unz(load_data.c_str(), &size);
#endif
	
	memfile = device->getFileSystem()->createMemoryReadFile(buff_extract, size, reload_path.c_str(), true);
	//new buffer copy on file->read(Buffer, size) of CXMeshFileLoader::readFileIntoMemory
	mesh	= smgr->getMesh( memfile );
	node	= smgr->addAnimatedMeshSceneNode( mesh );

	//delete buff_extract in drop() then goto ~CMemoryReadFile
	memfile->drop();
						
	if( pfilesystem )
	{
		delete pfilesystem;
		pfilesystem = NULL;
	}

//////////////////////////////texture/////////////////////////////////////////////////
	node->setMaterialTexture( 0, driver->getTexture((GetBaseAppPath()+"game/nskinbl.jpg").c_str()) );
    node->setMaterialFlag(EMF_LIGHTING, true);
    node->setMaterialFlag(EMF_NORMALIZE_NORMALS, true);
    anim = smgr->createRotationAnimator(core::vector3df(0,0.3f,0));
    node->addAnimator(anim);
    anim->drop();

	u32 alpha_val		= 90;
	u32 MaterialCount	= node->getMaterialCount();
	
	for(u32 i=0; i<MaterialCount; i++)
	{
		video::SMaterial& tex_mat	= node->getMaterial(i);
		tex_mat.MaterialType		= video::EMT_TRANSPARENT_VERTEX_ALPHA;
		//tex_mat.MaterialTypeParam	= 0.1;
		//tex_mat.MaterialTypeParam2= 0.1;
		tex_mat.AmbientColor.setAlpha(alpha_val);
		tex_mat.DiffuseColor.setAlpha(alpha_val);
		tex_mat.SpecularColor.setAlpha(alpha_val);
		tex_mat.EmissiveColor.setAlpha(alpha_val);
	}

#if	defined(_IRR_COMPILE_WITH_OGLES2_)
	for(u32 i=0; i<mesh->getMeshBufferCount(); i++)
	{
		scene::IMeshBuffer* buffer = mesh->getMeshBuffer(i);
		video::S3DVertex* vertex = (video::S3DVertex*)buffer->getVertices();
		
		for(u32 j=0; j<buffer->getVertexCount(); j++)
		{
			vertex[j].Color.setAlpha(alpha_val);
		}
	}
#endif
	
	smgr->addSkyBoxSceneNode(IrrlichtManager::GetIrrlichtManager()->GetTexture("game/irrlicht2_up.jpg"),
                             IrrlichtManager::GetIrrlichtManager()->GetTexture("game/irrlicht2_dn.jpg"),
                             IrrlichtManager::GetIrrlichtManager()->GetTexture("game/irrlicht2_lf.jpg"),
                             IrrlichtManager::GetIrrlichtManager()->GetTexture("game/irrlicht2_rt.jpg"),
                             IrrlichtManager::GetIrrlichtManager()->GetTexture("game/irrlicht2_ft.jpg"),
                             IrrlichtManager::GetIrrlichtManager()->GetTexture("game/irrlicht2_bk.jpg"));
//////////////////////////////////cam/////////////////////////////////////////////    
   	ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS(0, 100.0f, .02f, 0, 0, 0, true, 1.0f);
	//camera->addCameraSceneNode(0, vector3df(0,2,-10));
	camera->setPosition(core::vector3df(0,5,-20));
	float fov = float(GetPrimaryGLX())/ float(GetPrimaryGLY());
	camera->setAspectRatio(fov);
	camera->setFOV((120 * (float)M_PI / 360.0f));

#ifdef _IRR_COMPILE_WITH_GUI_
	EventControlComponent* receiver = new EventControlComponent();
    receiver->AddGuiButton();
	device->setEventReceiver(receiver);
#endif
}
Esempio n. 16
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;
}
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);
}
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();
}
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);
//! 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();
}
Esempio n. 21
0
Application::Application():sock(true){
	//int16_t mRCYaw = mRCPitch = mRCRoll = 0; 
	mRCThrottle = 1250; 
	mRCPitch = 1500; 
	mRCYaw = 1500; 
	mRCRoll = 1500; 
	
	mRCThrottle = 2000; 
	mRCPitch = 1000; 
	mRCYaw = 1000; 
	mRCRoll = 1000; 
	
	irrDevice = createDevice(video::EDT_OPENGL, dimension2d<u32>(640, 480), 32, false, false, false, this);
	irrGUI = irrDevice->getGUIEnvironment();
	irrTimer = irrDevice->getTimer();
	irrScene = irrDevice->getSceneManager();
	irrDriver = irrDevice->getVideoDriver();

	irrDevice->getCursorControl()->setVisible(0);

	// load a map
	irrDevice->getFileSystem()->addFileArchive("map-20kdm2.pk3");
	scene::IAnimatedMesh* mesh = irrScene->getMesh("20kdm2.bsp");
	scene::ISceneNode* node = 0;

	if (mesh)
			node = irrScene->addOctreeSceneNode(mesh->getMesh(0), 0, -1, 1024);
	if (node)
			node->setPosition(core::vector3df(-1300,-144,-1249));
        
	// Initialize bullet
	CollisionConfiguration = new btDefaultCollisionConfiguration();
	BroadPhase = new btAxisSweep3(btVector3(-1000, -1000, -1000), btVector3(1000, 1000, 1000));
	Dispatcher = new btCollisionDispatcher(CollisionConfiguration);
	Solver = new btSequentialImpulseConstraintSolver();
	World = new btDiscreteDynamicsWorld(Dispatcher, BroadPhase, Solver, CollisionConfiguration);
	World->setGravity(btVector3(0, -9.82, 0)); 

	// Add camera
	ICameraSceneNode *Camera = irrScene->addCameraSceneNodeFPS(0, 100, 0.01);
	//ICameraSceneNode *Camera = irrScene->addCameraSceneNode();
	Camera->setPosition(vector3df(0, 0, 0));
	Camera->setRotation(vector3df(45, -30, 0)); 
	//Camera->setUpVector(vector3df(0, 0, 1.0)); 
	//Camera->setTarget(vector3df(1, 0, 0));
	
	// Preload textures
	irrDriver->getTexture("ice0.jpg");
	irrDriver->getTexture("rust0.jpg");

	// Create the initial scene
	irrScene->addLightSceneNode(0, core::vector3df(2, 5, -2), SColorf(4, 4, 4, 1));
	irrScene->addLightSceneNode(0, core::vector3df(2, -5, -2), SColorf(4, 4, 4, 1));
	CreateStartScene();

	// Main loop
	TimeStamp = irrTimer->getTime(), DeltaTime = 0;

	Copter *view = new Copter(this);
	activeQuad = view;

	sock.bind("127.0.0.1", 9002); 
}
//! 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);
}
		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);
		}
Esempio n. 24
0
void Mesh3DInitScene()
{
	IAnimatedMesh*				mesh;
	IAnimatedMeshSceneNode*     node;
	scene::ISceneNodeAnimator*  anim;
	scene::ISceneManager*		smgr   = IrrlichtManager::GetIrrlichtManager()->GetScene();
	IrrlichtDevice*				device = IrrlichtManager::GetIrrlichtManager()->GetDevice();
	video::IVideoDriver*		driver = IrrlichtManager::GetIrrlichtManager()->GetDriver();
	
	std::string					load_zip;
	std::string					load_data;
	std::string					reload_path;
	FileSystemZip*				pfilesystem			= NULL;
	io::IReadFile*				memfile				= NULL;
	byte*						apk_buffer			= NULL;
	byte*						buff_extract		= NULL;
	int							size				= 0;
	int							apk_size			= 0;

	if (!IrrlichtManager::GetIrrlichtManager()->GetDevice())
	{
		LogError("Error initializing Irrlicht");
		return;
	}
	
	IrrlichtManager::GetIrrlichtManager()->GetDevice()->getTimer()->setTime(0);
		
    smgr->addLightSceneNode(0, core::vector3df(-100,10,0), video::SColorf(1.0f, 1.0f, 1.0f, 1.0f), 200.0f);
    smgr->addLightSceneNode(0, core::vector3df(+100,10,0), video::SColorf(1.0f, 1.0f, 1.0f, 1.0f), 200.0f);
	
		
//////////////////////////////mesh/////////////////////////////////////////////////
	load_zip	= (GetBaseAppPath() + "game/squirrel.zip").c_str();
	load_data	= "squirrel.x";
	reload_path	= (GetBaseAppPath() + "game/squirrel.x").c_str();
	
#ifdef ANDROID_NDK
	apk_buffer	= FileManager::GetFileManager()->Get(load_zip.c_str(), &apk_size, false, false);
	
	if( apk_buffer )
	{
		pfilesystem	= new FileSystemZip();
		pfilesystem->Init_unzMemory(apk_buffer, apk_size);
		buff_extract = pfilesystem->Get_unz(load_data, &size);

		delete apk_buffer;
		apk_buffer = NULL;
	}
#else
	pfilesystem = new FileSystemZip();
	pfilesystem->Init_unz(load_zip.c_str());
	buff_extract = pfilesystem->Get_unz(load_data.c_str(), &size);
#endif
	
	memfile = device->getFileSystem()->createMemoryReadFile(buff_extract, size, reload_path.c_str(), true);
	//new buffer copy on file->read(Buffer, size) of CXMeshFileLoader::readFileIntoMemory
	mesh	= smgr->getMesh( memfile );
	node	= smgr->addAnimatedMeshSceneNode( mesh );

	//delete buff_extract in drop() then goto ~CMemoryReadFile
	memfile->drop();
						
	if( pfilesystem )
	{
		delete pfilesystem;
		pfilesystem = NULL;
	}

//////////////////////////////texture/////////////////////////////////////////////////
	node->setMaterialTexture( 0, driver->getTexture((GetBaseAppPath()+"game/squirrel_skin.jpg").c_str()) );
    node->setMaterialFlag(EMF_LIGHTING, true);
    node->setMaterialFlag(EMF_NORMALIZE_NORMALS, true);
    anim = smgr->createRotationAnimator(core::vector3df(0,0.3f,0));
    node->addAnimator(anim);
    anim->drop();
	

//////////////////////////////////cam/////////////////////////////////////////////    
   	ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS(0, 100.0f, .02f, 0, 0, 0, true, 1.0f);
	//camera->addCameraSceneNode(0, vector3df(0,2,-10));
	camera->setPosition(core::vector3df(0,2,-10));
	float fov = float(GetPrimaryGLX())/ float(GetPrimaryGLY());
	camera->setAspectRatio(fov);
	camera->setFOV((120 * M_PI / 360.0f));

#ifdef _IRR_COMPILE_WITH_GUI_
	EventControlComponent* receiver = new EventControlComponent();
    receiver->AddGuiButton();
	device->setEventReceiver(receiver);
#endif
}