Esempio n. 1
0
int main()
{
	MyIrrlichtComposition mDevice(video::EDT_SOFTWARE,dimension2d<u32>(800,600 ));

	mDevice.AddBackground("background.png");

	IAnimatedMeshSceneNode* node = mDevice.mLoadMesh(vector3df(0,10,0),vector3df(0,-90,0),vector3df(0.2,0.2,0.2),"raven.md2","raven.jpg");
	const int count=5;
	IAnimatedMeshSceneNode* plat[count+1];
	for(int i(0);i<count;++i)
		plat[i] = mDevice.mLoadMesh(vector3df(-41+i*20, -20+i*10, 0),vector3df(30,0,0),vector3df(2.5,2.5,2.5),"platform02.obj","platform00.tga");
	
	mDevice.AddCamera();
	//u32 then = mDevice()->getTimer()->getTime();
	f32 g=-0.2;

	while(mDevice()->run())
	{
		g-=0.002;
 
		// двигаем ее текущую позицию вправо или влево
		if(mDevice.receiver.IsKeyDown(irr::KEY_KEY_A)) 
			mDevice.ObjMoving(node, vector3df(0,0,-0.25));
		else if(mDevice.receiver.IsKeyDown(irr::KEY_KEY_D))
			mDevice.ObjMoving(node, vector3df(0,0,0.25));

		//считываем для выхода
		if(mDevice.receiver.IsKeyDown(irr::KEY_ESCAPE))
			return 0;
		
		//"гравитация"
		mDevice.ObjMoving(node, vector3df(0,g,0));
		//движение камеры
		mDevice.SetCamera(vector3df(0, node->getPosition().Y, 0));
		mDevice.MoveCamera(vector3df(0 , node->getPosition().Y, node->getPosition().Z + 50));

		//перенос игрока на другую сторону при вылете за пределы поля
		if(node->getPosition().X == -45)
			mDevice.ObjMoving(node, vector3df(0, 0, -90));
		else if(node->getPosition().X == 45)
			mDevice.ObjMoving(node, vector3df(0, 0, 90));

		//обработка столкновения и "прыжок"
		for(int i(0);i<count;++i)
			if(mDevice.mCollision(node,plat[i]))
				g=0.2;
		
		//выход, если слишком сильно упал
		f32 fall=-150;
		if (node->getPosition().Y>fall - 5 && node->getPosition().Y<fall + 5)
			return 0;

		//обработка сцены
		mDevice.ShowScene();
	}

	mDevice()->drop();
	
	return 0;
}
Esempio n. 2
0
void CScene::UpdateScene(vector<vector3df> otherClientPosition, ICameraSceneNode* camera)
{
	ISceneManager* smgr=device->getSceneManager();
	IVideoDriver* driver=device->getVideoDriver();

	// 测试用
	IAnimatedMesh* personMeshTest=smgr->getMesh("../../media/sydney.md2");
	IAnimatedMeshSceneNode* personNode = smgr->addAnimatedMeshSceneNode( personMeshTest );
	if (!personMeshTest)
	{
		device->drop();
		return ;
	}
	if (personNode)
	{
		personNode->setScale(vector3df(0.4f,0.4f,0.4f));
		personNode->setPosition(vector3df(0.0f,10.0f,0.0f));
		personNode->setMaterialTexture( 0, driver->getTexture("../../media/sydney.bmp") );
		personNode->setMaterialFlag(EMF_LIGHTING, false);
		personNode->getMaterial(0).Shininess=28.0f;
		personNode->getMaterial(0).NormalizeNormals=true;
		personNode->setMD2Animation ( scene::EMAT_STAND );

	}
	personMeshTest->setMaterialFlag(EMF_LIGHTING,false);

	// 显示其他客户端
	for (int i=0;i!=otherClientPosition.size();i++)
	{
		IAnimatedMesh* personMesh=smgr->getMesh("../../media/sydney.md2");
		IAnimatedMeshSceneNode* personNode = smgr->addAnimatedMeshSceneNode( personMesh );
		if (!personMesh)
		{
			device->drop();
			return ;
		}
		if (personNode && personNode->getPosition()!=camera->getPosition())
		{
//			personNode->setPosition(vector3df(10,20,0));
//			personNode->setScale(vector3df(0.5,0.5,0.5));
			personNode->setPosition(otherClientPosition[i]);
			personNode->setMaterialTexture( 0, driver->getTexture("../../media/sydney.bmp") );
			personNode->setMaterialFlag(EMF_LIGHTING, false);
			personNode->getMaterial(0).Shininess=28.0f;
			personNode->getMaterial(0).NormalizeNormals=true;
			personNode->setMD2Animation ( scene::EMAT_STAND );

		}
		personMesh->setMaterialFlag(EMF_LIGHTING,false);
	}
}
Esempio n. 3
0
int main()
{
	Input input;
	IrrlichtDevice *device = createDevice(video::EDT_DIRECT3D9, dimension2d<u32>(800, 600), 16, false, true, false, &input);
	device->setWindowCaption(L"Seas of Gold");
	IVideoDriver* driver = device->getVideoDriver();
	ISceneManager* smgr = device->getSceneManager();
	IGUIEnvironment* guienv = device->getGUIEnvironment();
	E_DRIVER_TYPE driverType = driverChoiceConsole();
	EffectHandler *effect = new EffectHandler(device, driver->getScreenSize(), false, true);
	E_FILTER_TYPE filterType = (E_FILTER_TYPE)core::clamp<u32>((u32)3 - '1', 0, 4);
	MapID currentMap;
	int skyR = 30, skyG = 30, skyB = 70;
	int timer = 0;
	SColor sky = SColor(255, skyR, skyG, skyB);
	float plPos_x = 0.0f, plPos_y = 0.0f, plPos_z = 0.0f;
	bool updateCam = true;
	bool menu1 = false;
	int state = Main;
	int frameCount = 0;
	LoadMap loadMap;
	Player player;
	Interface playerInterface(driver);
	ITriangleSelector* selector = 0;
	ISceneNodeAnimator* anim = 0;
	Vendor southVendor;
	Vendor eastVendor;
	Vendor northVendor;
	//InitializeVendors(northVendor, southVendor, eastVendor, itemD);

	//ItemDatabase* itemD = new ItemDatabase;
	ItemDatabase itemD;
	itemD.Initialize();

	//initialize player's inventory
	player.AddGold(1000);
	player.getInventory()->addItem(itemD.getItem(bronzeOre), 50);
	player.getInventory()->addItem(itemD.getItem(ironOre), 50);
	player.getInventory()->addItem(itemD.getItem(goldOre), 50);

	//initialize south vendor's inventory
	southVendor.getInventory()->addItem(itemD.getItem(bronzeOre), 100);
	southVendor.getInventory()->addItem(itemD.getItem(coalOre), 100);
	southVendor.getInventory()->addItem(itemD.getItem(supplies), 1000);

	//initialize north vendor's inventory
	northVendor.getInventory()->addItem(itemD.getItem(obsidianOre), 50);
	northVendor.getInventory()->addItem(itemD.getItem(supplies), 1000);

	//initialize south vendor's inventory
	eastVendor.getInventory()->addItem(itemD.getItem(goldOre), 100);
	eastVendor.getInventory()->addItem(itemD.getItem(ironOre), 100);
	eastVendor.getInventory()->addItem(itemD.getItem(supplies), 1000);

	//Item item(0, "bronzeOre", "Sprites/ore_Bronze.png");
	//Item item2 = item;
	//Item* item2 = itemD.getItem(3);
	//inventory.addItem(&item, 2);
	//inventory.addItem(&item, 2);
	//inventory.addItem(item2, 2);

	//int test = 0;

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

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

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

	loadMap.Load(smgr, device, selector, plyrNode, anim, driver, Map_Africa);
	currentMap = Map_Africa;
	//loadMap.setCollisions(smgr, selector, plyrNode, anim);

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

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

		plyrNode->addAnimator(anim);
	}

	ISceneCollisionManager* collMan = smgr->getSceneCollisionManager();

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

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

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

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

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

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

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

	//delete &itemD;

	int test99 = 0;


	// Make the menus
	MainMenu mainMenu(device, driver);

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

	TradeMenu tradeMenu;
	tradeMenu.Initialize(device, driver, &player, &southVendor);
	//TradeMenu tradeMenu(device, driver);
	//tradeMenu.SetPlayer(&player);
	//tradeMenu.SetVendor(&vS);
	//
	CraftingMenu craftMenu(device, driver, &player, itemD);
	//craftMenu.SetPlayer(&player);

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

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

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

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

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

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

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

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

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

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

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

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

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

			break;
		}
		case Trade:
		{

			bool out = false;
			out = tradeMenu.Update(&input, frameCount, device, currentMap);
			if (out)
				state = None;
			break;
		}
		case Main:
		{
			int out = mainMenu.Update(&input, frameCount);

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

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

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

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

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

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

		smgr->drawAll();

		playerInterface.render(driver, state);

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

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

	}

	device->drop();

	return 0;
}
void CCharacterExample::runExample()
{
    for(s32 i=0; i<KEY_KEY_CODES_COUNT; i++)
        KeyIsDown[i] = false;

    debugDraw = true;
    drawProperties = true;
    drawWireFrame = false;

    rows = 10;
	columns = 10;

    device =
        createDevice( video::EDT_OPENGL, dimension2d<u32>(640, 480), 16,
            false, false, false, this);


    device->setWindowCaption(L"irrBullet Character Example - Josiah Hartzell");

	device->getFileSystem()->addFileArchive("./media/");


    device->getSceneManager()->addLightSceneNode(0, vector3df(20, 40, -50), SColorf(1.0f, 1.0f, 1.0f), 4000.0f);


    ////////////////////////////
    // Create irrBullet World //
    ////////////////////////////
    world = createIrrBulletWorld(device, true, debugDraw);

    world->setDebugMode(EPDM_DrawAabb |
            EPDM_DrawContactPoints);

    world->setGravity(vector3df(0,-10,0));


    camera = device->getSceneManager()->addCameraSceneNodeMaya();
	camera->setPosition(vector3df(50,15,200));
	camera->bindTargetAndRotation(true);


	createGround();
	createBoxes();

	IKinematicCharacterController* character = new IKinematicCharacterController(world);

	IAnimatedMeshSceneNode* sydney = device->getSceneManager()->addAnimatedMeshSceneNode(device->getSceneManager()->getMesh("sydney.md2"));
	sydney->setScale(vector3df(0.14,0.14,0.14));
	sydney->getMaterial(0).setTexture(0, device->getVideoDriver()->getTexture("sydney.bmp"));
	sydney->setMD2Animation(scene::EMAT_STAND);


    // Set our delta time and time stamp
    u32 TimeStamp = device->getTimer()->getTime();
    u32 DeltaTime = 0;
    EMD2_ANIMATION_TYPE animation = EMAT_STAND;
    EMD2_ANIMATION_TYPE newAnimation = EMAT_RUN;
    bool jump = false;
    while(device->run())
    {
        device->getVideoDriver()->beginScene(true, true, SColor(255,100,101,140));

        DeltaTime = device->getTimer()->getTime() - TimeStamp;
		TimeStamp = device->getTimer()->getTime();


		/*sydney->setPosition(character->getWorldTransform().getTranslation()+vector3df(0,-((sydney->getBoundingBox().MaxEdge.Y-sydney->getBoundingBox().MinEdge.Y)*0.1*0.5f),0));
        vector3df dir = camera->getAbsolutePosition()-sydney->getAbsolutePosition();
        dir.normalize();
        dir.Y = 0;
        dir *= -1;

        character->setWalkDirection(dir*0.3f);*/

        if(IsKeyDown(KEY_KEY_W))
        {
            DirZ = -1.0f;
        }

        else if(IsKeyDown(KEY_KEY_S))
        {
            DirZ = 1.0f;
        }

        else
        {
            DirZ = 0.0f;
        }

        if(IsKeyDown(KEY_KEY_A))
        {
            DirX = 1.0f;
        }

        else if(IsKeyDown(KEY_KEY_D))
        {
            DirX = -1.0f;
        }

        else
        {
            DirX = 0.0f;
        }

        if(IsKeyDown(KEY_SPACE))
        {
            character->jump();
            jump = true;
        }

        if(DirZ != 0 || DirX != 0)
            newAnimation = EMAT_RUN;

        else
            newAnimation = EMAT_STAND;

        if(!character->isOnGround())
        {
            newAnimation = jump ? EMAT_JUMP:EMAT_CROUCH_STAND;
        }

        else
            jump = false;


        if(animation != newAnimation)
        {
            animation = newAnimation;
            sydney->setMD2Animation(animation);
        }


        sydney->setPosition(character->getWorldTransform().getTranslation());

        vector3df rot(0, camera->getRotation().Y-90.0f, 0);
        sydney->setRotation(rot);


        vector3df direction(DirX, 0.0f, DirZ);

        irr::core::matrix4 m;

        m.setRotationDegrees(vector3df(0, camera->getRotation().Y-180.0f, 0));

        m.transformVect(direction);

        character->setPositionIncrementPerSimulatorStep(direction*0.3f);

        camera->setTarget(sydney->getPosition());

		// Step the simulation with our delta time
        world->stepSimulation(DeltaTime*0.001f, 120);


        world->debugDrawWorld(debugDraw);

        // This call will draw the technical properties of the physics simulation
        // to the GUI environment.
        world->debugDrawProperties(true);


        device->getSceneManager()->drawAll();
        device->getGUIEnvironment()->drawAll();

        device->getVideoDriver()->endScene();
    }

    delete character;

    // We're done with the IrrBullet world, so we free the memory that it takes up.
    if(world)
        delete world;

    if(device)
        device->drop();
}
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);
Esempio n. 6
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;
}