<commit_before>// Author: B. Sahlmueller
// Analysis task for neutral pions (into two gammas), and for direct photons by subtraction method

AliAnalysisTask *AddTaskEMCALPi0Gamma(const UInt_t triggermask = AliVEvent::kMB,
                                      Bool_t mcmode = 0,
                                      Bool_t addsig = 0,
                                      Bool_t issys = 0,
                                      const char geoname[] = "EMCAL_COMPLETEV1",
                                      Bool_t qf = 0,
                                      Double_t asym1 = 0.3,
                                      Double_t asym2 = 0.7,
                                      Double_t minE = 0.4,
                                      Double_t minecc = -10,
                                      Int_t ncells = 2,
                                      Bool_t bunfold = 0,
                                      Double_t cutm02 = 100,
                                      Double_t cutchi2 = -1,
                                      Bool_t dotrmsmpl = 0,
                                      Bool_t doManualRecal = 0,
                                     Int_t dataPeriod = 0,
                                      Double_t centMin = 0,
                                      Double_t centMax = 100,
                                      const char cent[] = "V0M",
                                      Bool_t doCalibRun = 0,
                                      Bool_t doManualBadmap = 0,
                                      TString badMapName = "defaultTender")
{

  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskPi0Gamma", "No analysis manager to connect to.");
    return NULL;
  }

  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskPi0Gamma", "This task requires an input event handler");
    return NULL;
  }

  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();

  if(bunfold){
    AliAnalysisTaskEMCALClusterize * clusterize = new AliAnalysisTaskEMCALClusterize("EMCALClusterize");
    clusterize->SetOCDBPath("local://$ALICE_ROOT/OCDB");
    //  clusterize->SetAODBranchName("newEMCALClusters"); //Make sure you use this same name to recover the list during the analysis.
    //  clusterize->FillAODFile(kTRUE); //if true aod.root file filled, in any case list of clusters is accessible after in the event analysis.
    clusterize->JustUnfold(kTRUE); // if TRUE, do just unfolding, do not recluster cells
    //  clusterize->SetImportGeometryFromFile(kTRUE,"$ALICE_ROOT/OADB/EMCAL/geometry_2011.root"); // change only in case 2010 to geometry_2010.root
    //  clusterize->SwitchOnLoadOwnGeometryMatrices();
    //////Set the parameters used in standard reconstruction

    AliEMCALRecParam * params = clusterize->GetRecParam();
    params->SetClusterizerFlag( AliEMCALRecParam ::kClusterizerv1); //Select the clusterization algorithm this or kClusterizerv1, kClusterizerNxN
    params->SetClusteringThreshold(0.5); // 100 MeV
    params->SetMinECut(0.15); //10 MeV , no effect
    params->SetUnfold(kTRUE); //Do the unfolding or not like in the standard reconstruction
    params->SetW0(4.3);
    mgr->AddTask(clusterize);

    mgr->ConnectInput (clusterize, 0, cinput);  //connect input
  }

  // settings

  TString pathToBadMap;

  if (badMapName !="defaultTender") {
    gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/b/bsahlmul/%s.root .",badMapName.Data()));
    pathToBadMap = Form("%s/",gSystem->pwd());
    pathToBadMap += badMapName;
    pathToBadMap += ".root";
  }

  // Create the task and configure it.
  //===========================================================================
  AliAnalysisTaskEMCALPi0Gamma* task = new  AliAnalysisTaskEMCALPi0Gamma("Pi0GammaTask");
  task->SelectCollisionCandidates(triggermask);
  task->SetUseQualFlag(qf);
  task->SetAsymMax1(asym1);
  task->SetAsymMax2(asym2);
  task->SetMinClusEnergy(minE);
  task->SetMinEcc(minecc);
  task->SetNminCells(ncells);
  task->SetGeoName(geoname);
  task->SetMcMode(mcmode);
  task->SetAddedSignal(addsig);
  task->SetFillNtuple(0);
  task->SetM02Cut(cutm02);
  task->SetMinEcc(cutchi2);
  task->SetTrackMatchSimple(dotrmsmpl);
  task->SetDoManualRecal(doManualRecal);
  task->SetDoCalibRun(doCalibRun);
  task->SetDataPeriod(dataPeriod);
  task->SetCentrality(cent);
  task->SetCentralityRange(centMin,centMax);
  task->SetManualBadMap(doManualBadmap);

  if(doManualBadmap) {
    if (badMapName == "defaultTender")
      AliWarning("Cannot apply default tender bad map in task, now applying empty bad map. Specify own bad map to fix it.");
    else {
      TFile *fBadMap = TFile::Open(pathToBadMap.Data());

      if(fBadMap->IsOpen()){
        printf("\n\n...Adding bad channel map (MANUALY) \n") ;
        gROOT->cd();
        Char_t key[55] ;
        sprintf(key,"hresult") ;
        TH1D * h = (TH1D*)fBadMap->Get(key) ;
        if(h)
          task->SetBadMap(h) ;
        fBadMap->Close() ;
      }
    }
  }

  mgr->AddTask(task);

  char name[256];

  sprintf(name,"histosPi0Gamma%s","MB");
  if(triggermask == AliVEvent::kINT7){
    sprintf(name,"histosPi0Gamma%s","INT7");
  }
  if(triggermask == AliVEvent::kEMC1){
    sprintf(name,"histosPi0Gamma%s","EMC1");
  }
  if(triggermask == AliVEvent::kEMC7){
    sprintf(name,"histosPi0Gamma%s","EMC7");
  }

  if(issys){
    strcat(name,"sys");
  }

  char ccentmin[10];
  char ccentmax[10];
  sprintf(ccentmin,"_%.0f",centMin);
  sprintf(ccentmax,"_%.0f",centMax);

  strcat(name,ccentmin);
  strcat(name,ccentmax);

  //RequestMemory(task,320*1024); // request 0.5GB memory for task

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(name,
							    TList::Class(),AliAnalysisManager::kOutputContainer,
							    Form("%s", AliAnalysisManager::GetCommonFileName()));
							    //							    "_pi0gamma.root");

  mgr->ConnectInput  (task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput (task, 1, coutput1 );

  return task;

}
<commit_msg>changed warning<commit_after>// Author: B. Sahlmueller
// Analysis task for neutral pions (into two gammas), and for direct photons by subtraction method

AliAnalysisTask *AddTaskEMCALPi0Gamma(const UInt_t triggermask = AliVEvent::kMB,
                                      Bool_t mcmode = 0,
                                      Bool_t addsig = 0,
                                      Bool_t issys = 0,
                                      const char geoname[] = "EMCAL_COMPLETEV1",
                                      Bool_t qf = 0,
                                      Double_t asym1 = 0.3,
                                      Double_t asym2 = 0.7,
                                      Double_t minE = 0.4,
                                      Double_t minecc = -10,
                                      Int_t ncells = 2,
                                      Bool_t bunfold = 0,
                                      Double_t cutm02 = 100,
                                      Double_t cutchi2 = -1,
                                      Bool_t dotrmsmpl = 0,
                                      Bool_t doManualRecal = 0,
                                     Int_t dataPeriod = 0,
                                      Double_t centMin = 0,
                                      Double_t centMax = 100,
                                      const char cent[] = "V0M",
                                      Bool_t doCalibRun = 0,
                                      Bool_t doManualBadmap = 0,
                                      TString badMapName = "defaultTender")
{

  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskPi0Gamma", "No analysis manager to connect to.");
    return NULL;
  }

  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskPi0Gamma", "This task requires an input event handler");
    return NULL;
  }

  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();

  if(bunfold){
    AliAnalysisTaskEMCALClusterize * clusterize = new AliAnalysisTaskEMCALClusterize("EMCALClusterize");
    clusterize->SetOCDBPath("local://$ALICE_ROOT/OCDB");
    //  clusterize->SetAODBranchName("newEMCALClusters"); //Make sure you use this same name to recover the list during the analysis.
    //  clusterize->FillAODFile(kTRUE); //if true aod.root file filled, in any case list of clusters is accessible after in the event analysis.
    clusterize->JustUnfold(kTRUE); // if TRUE, do just unfolding, do not recluster cells
    //  clusterize->SetImportGeometryFromFile(kTRUE,"$ALICE_ROOT/OADB/EMCAL/geometry_2011.root"); // change only in case 2010 to geometry_2010.root
    //  clusterize->SwitchOnLoadOwnGeometryMatrices();
    //////Set the parameters used in standard reconstruction

    AliEMCALRecParam * params = clusterize->GetRecParam();
    params->SetClusterizerFlag( AliEMCALRecParam ::kClusterizerv1); //Select the clusterization algorithm this or kClusterizerv1, kClusterizerNxN
    params->SetClusteringThreshold(0.5); // 100 MeV
    params->SetMinECut(0.15); //10 MeV , no effect
    params->SetUnfold(kTRUE); //Do the unfolding or not like in the standard reconstruction
    params->SetW0(4.3);
    mgr->AddTask(clusterize);

    mgr->ConnectInput (clusterize, 0, cinput);  //connect input
  }

  // settings

  TString pathToBadMap;

  if (badMapName !="defaultTender") {
    gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/b/bsahlmul/%s.root .",badMapName.Data()));
    pathToBadMap = Form("%s/",gSystem->pwd());
    pathToBadMap += badMapName;
    pathToBadMap += ".root";
  }

  // Create the task and configure it.
  //===========================================================================
  AliAnalysisTaskEMCALPi0Gamma* task = new  AliAnalysisTaskEMCALPi0Gamma("Pi0GammaTask");
  task->SelectCollisionCandidates(triggermask);
  task->SetUseQualFlag(qf);
  task->SetAsymMax1(asym1);
  task->SetAsymMax2(asym2);
  task->SetMinClusEnergy(minE);
  task->SetMinEcc(minecc);
  task->SetNminCells(ncells);
  task->SetGeoName(geoname);
  task->SetMcMode(mcmode);
  task->SetAddedSignal(addsig);
  task->SetFillNtuple(0);
  task->SetM02Cut(cutm02);
  task->SetMinEcc(cutchi2);
  task->SetTrackMatchSimple(dotrmsmpl);
  task->SetDoManualRecal(doManualRecal);
  task->SetDoCalibRun(doCalibRun);
  task->SetDataPeriod(dataPeriod);
  task->SetCentrality(cent);
  task->SetCentralityRange(centMin,centMax);
  task->SetManualBadMap(doManualBadmap);

  if(doManualBadmap) {
    if (badMapName == "defaultTender")
      cout << "Cannot apply default tender bad map in task, now applying empty bad map. Specify own bad map to fix it." << endl;
    else {
      TFile *fBadMap = TFile::Open(pathToBadMap.Data());

      if(fBadMap->IsOpen()){
        printf("\n\n...Adding bad channel map (MANUALY) \n") ;
        gROOT->cd();
        Char_t key[55] ;
        sprintf(key,"hresult") ;
        TH1D * h = (TH1D*)fBadMap->Get(key) ;
        if(h)
          task->SetBadMap(h) ;
        fBadMap->Close() ;
      }
    }
  }

  mgr->AddTask(task);

  char name[256];

  sprintf(name,"histosPi0Gamma%s","MB");
  if(triggermask == AliVEvent::kINT7){
    sprintf(name,"histosPi0Gamma%s","INT7");
  }
  if(triggermask == AliVEvent::kEMC1){
    sprintf(name,"histosPi0Gamma%s","EMC1");
  }
  if(triggermask == AliVEvent::kEMC7){
    sprintf(name,"histosPi0Gamma%s","EMC7");
  }

  if(issys){
    strcat(name,"sys");
  }

  char ccentmin[10];
  char ccentmax[10];
  sprintf(ccentmin,"_%.0f",centMin);
  sprintf(ccentmax,"_%.0f",centMax);

  strcat(name,ccentmin);
  strcat(name,ccentmax);

  //RequestMemory(task,320*1024); // request 0.5GB memory for task

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(name,
							    TList::Class(),AliAnalysisManager::kOutputContainer,
							    Form("%s", AliAnalysisManager::GetCommonFileName()));
							    //							    "_pi0gamma.root");

  mgr->ConnectInput  (task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput (task, 1, coutput1 );

  return task;

}
<|endoftext|>


<commit_before>#include "ControlSystem.hpp"
#include <DeferredTaskSystem.hpp>
#include <TimeWorldComponent.hpp>
#include <InputWorldComponent.hpp>

#include "MovementComponent.hpp"
#include "CollisionComponent.hpp"
#include "TankComponent.hpp"

using namespace Poly;

void ControlSystem::ControlSystemPhase(World* world)
{

	GameManagerComponent* gameManager = nullptr;
	double time = world->GetWorldComponent<TimeWorldComponent>()->GetGameplayTime();
	double deltaTime = TimeSystem::GetTimerDeltaTime(world, Poly::eEngineTimer::GAMEPLAY);
	for (auto componentTuple : world->IterateComponents<GameManagerComponent>())
	{
		gameManager = std::get<GameManagerComponent*>(componentTuple);
	}
	for (auto componentTuple : world->IterateComponents<PlayerControllerComponent>())
	{
		PlayerControllerComponent* player = std::get<PlayerControllerComponent*>(componentTuple);
		Vector move(0, 0, 0);
		if (world->GetWorldComponent<InputWorldComponent>()->IsPressed(player->GetLeftKey()))
			move -= Vector::UNIT_X;
		else if (world->GetWorldComponent<InputWorldComponent>()->IsPressed(player->GetRightKey()))
			move += Vector::UNIT_X;

		if (move.Length() > 0)
		{
			move.Normalize();
			move *= player->GetMovementSpeed();
			move *= deltaTime;
			TransformComponent* player_transform = player->GetSibling<TransformComponent>();
			Vector prev_location = player_transform->GetLocalTranslation();
			if (Abs(prev_location.X + move.X) <= player->GetMaxAbsXPosition())
				player_transform->SetLocalTranslation(prev_location + move);
		}
		if (world->GetWorldComponent<InputWorldComponent>()->IsPressed(player->GetShootKey()) && (world->GetWorldComponent<TimeWorldComponent>()->GetGameplayTime() - player->GetLastShoot() >= player->GetShootInterval()))
		{
			Vector pos = player->GetSibling<TransformComponent>()->GetLocalTranslation();

			SpawnBullet(gameManager, world, pos, Vector(0.0f, 0.0f, -1.0f), player->GetBulletSpeed());
			player->SetLastShoot(world->GetWorldComponent<TimeWorldComponent>()->GetGameplayTime());
		}
	}

	for (auto tuple : world->IterateComponents<Invaders::MovementSystem::MovementComponent, Invaders::TankComponent>())
	{
		Invaders::MovementSystem::MovementComponent* transform = std::get<Invaders::MovementSystem::MovementComponent*>(tuple);
		Invaders::TankComponent* tank = std::get<Invaders::TankComponent*>(tuple);

		if (tank->MovedDistance > 100)
		{
			Invaders::MovementSystem::SetLinearVelocity(world, transform->GetOwnerID(), -Invaders::MovementSystem::GetLinearVelocity(world, transform->GetOwnerID()));
			tank->MovedDistance = 0;
		}

		tank->MovedDistance += std::fabs(Invaders::MovementSystem::GetLinearVelocity(world, transform->GetOwnerID()).X * deltaTime);

	}

	for (auto componentTuple : world->IterateComponents<Invaders::TankComponent, TransformComponent>())
	{
		TransformComponent* transform = std::get<TransformComponent*>(componentTuple);
		Invaders::TankComponent* tank = std::get<Invaders::TankComponent*>(componentTuple);
		TransformComponent* transformTurret = world->GetComponent<TransformComponent>(tank->Turret);

		if (tank->NextRotTime < time)
		{
			tank->NextRotTime = time + 5.0f;
			tank->Degree *= -1;
		}
		Quaternion rotaton(Vector::UNIT_Y, tank->Degree * deltaTime);
		rotaton *= transformTurret->GetLocalRotation();
		transformTurret->SetLocalRotation(rotaton);

	}

	for (auto componentTuple : world->IterateComponents<BulletComponent, TransformComponent>())
	{
		BulletComponent* bullet = std::get<BulletComponent*>(componentTuple);
		TransformComponent* transform = std::get<TransformComponent*>(componentTuple);
		if (time < bullet->GetSpawnTme() + bullet->GetLifeTme())
		{
			Vector move = bullet->GetDirection();
			move *= bullet->GetMovementSpeed();
			move *= TimeSystem::GetTimerDeltaTime(world, Poly::eEngineTimer::GAMEPLAY);
			transform->SetLocalTranslation(transform->GetLocalTranslation() + move);
			bullet->GetCollisionBox().SetPosition(transform->GetLocalTranslation() + move);
		}
		else
		{
			if (!gameManager->GetDeadGameEntities()->Contains(bullet->GetOwnerID()))
				gameManager->GetDeadGameEntities()->PushBack(bullet->GetOwnerID());
		}
	}

	Invaders::CollisionSystem::CollisionComponent* collider;

	for (auto tuple : world->IterateComponents<Invaders::CollisionSystem::CollisionComponent>())
	{
		collider = std::get<Invaders::CollisionSystem::CollisionComponent*>(tuple);
		if (collider->IsColliding())
		{
			gameManager->SetKillCount(gameManager->GetKillCount() + 1);
			DeferredTaskSystem::DestroyEntity(world, collider->GetOwnerID());
		}
	}

	if (world->GetWorldComponent<InputWorldComponent>()->IsReleased(gameManager->GetQuitKey()))
	{
		//quit game
	}

	CleanUpEnitites(gameManager, world);
}

void ControlSystem::SpawnBullet(GameManagerComponent* gameManager, World* world, Vector pos, Vector direction, float speed)
{
	auto bullet = DeferredTaskSystem::SpawnEntityImmediate(world);

	DeferredTaskSystem::AddComponentImmediate<Poly::TransformComponent>(world, bullet);
	DeferredTaskSystem::AddComponentImmediate<Poly::MeshRenderingComponent>(world, bullet, "Models/bullet/lowpolybullet.obj");
	DeferredTaskSystem::AddComponentImmediate<Invaders::CollisionSystem::CollisionComponent>(world, bullet,  Vector(0, 0, 0), Vector(2.0f,2.0f,2.0f));

	if (direction.Length() > 0)
		direction.Normalize();
	DeferredTaskSystem::AddComponentImmediate<BulletComponent>(world, bullet, speed, direction,
		AABox(world->GetComponent<Poly::TransformComponent>(bullet)->GetLocalTranslation(), Vector(2.0f,2.0f,2.0f)), world->GetWorldComponent<TimeWorldComponent>()->GetGameplayTime());
	Poly::TransformComponent* transform = world->GetComponent<Poly::TransformComponent>(bullet);
	transform->SetLocalScale(Vector(0.25f, 0.25f, 0.25f));
	transform->SetLocalRotation(Quaternion(Vector::UNIT_Y, 180_deg));
	transform->SetLocalTranslation(pos);
	gConsole.LogInfo("Spawning Bullet!");
}
void ControlSystem::CleanUpEnitites(GameManagerComponent* gameManager, World* world)
{
	for (Poly::UniqueID ent : *(gameManager->GetDeadGameEntities()))
	{
		DeferredTaskSystem::DestroyEntity(world, ent);
	}
	gameManager->GetDeadGameEntities()->Clear();
}<commit_msg>Doubled kill count fixed.<commit_after>#include "ControlSystem.hpp"
#include <DeferredTaskSystem.hpp>
#include <TimeWorldComponent.hpp>
#include <InputWorldComponent.hpp>

#include "MovementComponent.hpp"
#include "CollisionComponent.hpp"
#include "TankComponent.hpp"

using namespace Poly;

void ControlSystem::ControlSystemPhase(World* world)
{

	GameManagerComponent* gameManager = nullptr;
	double time = world->GetWorldComponent<TimeWorldComponent>()->GetGameplayTime();
	double deltaTime = TimeSystem::GetTimerDeltaTime(world, Poly::eEngineTimer::GAMEPLAY);
	for (auto componentTuple : world->IterateComponents<GameManagerComponent>())
	{
		gameManager = std::get<GameManagerComponent*>(componentTuple);
	}
	for (auto componentTuple : world->IterateComponents<PlayerControllerComponent>())
	{
		PlayerControllerComponent* player = std::get<PlayerControllerComponent*>(componentTuple);
		Vector move(0, 0, 0);
		if (world->GetWorldComponent<InputWorldComponent>()->IsPressed(player->GetLeftKey()))
			move -= Vector::UNIT_X;
		else if (world->GetWorldComponent<InputWorldComponent>()->IsPressed(player->GetRightKey()))
			move += Vector::UNIT_X;

		if (move.Length() > 0)
		{
			move.Normalize();
			move *= player->GetMovementSpeed();
			move *= deltaTime;
			TransformComponent* player_transform = player->GetSibling<TransformComponent>();
			Vector prev_location = player_transform->GetLocalTranslation();
			if (Abs(prev_location.X + move.X) <= player->GetMaxAbsXPosition())
				player_transform->SetLocalTranslation(prev_location + move);
		}
		if (world->GetWorldComponent<InputWorldComponent>()->IsPressed(player->GetShootKey()) && (world->GetWorldComponent<TimeWorldComponent>()->GetGameplayTime() - player->GetLastShoot() >= player->GetShootInterval()))
		{
			Vector pos = player->GetSibling<TransformComponent>()->GetLocalTranslation();

			SpawnBullet(gameManager, world, pos, Vector(0.0f, 0.0f, -1.0f), player->GetBulletSpeed());
			player->SetLastShoot(world->GetWorldComponent<TimeWorldComponent>()->GetGameplayTime());
		}
	}

	for (auto tuple : world->IterateComponents<Invaders::MovementSystem::MovementComponent, Invaders::TankComponent>())
	{
		Invaders::MovementSystem::MovementComponent* transform = std::get<Invaders::MovementSystem::MovementComponent*>(tuple);
		Invaders::TankComponent* tank = std::get<Invaders::TankComponent*>(tuple);

		if (tank->MovedDistance > 100)
		{
			Invaders::MovementSystem::SetLinearVelocity(world, transform->GetOwnerID(), -Invaders::MovementSystem::GetLinearVelocity(world, transform->GetOwnerID()));
			tank->MovedDistance = 0;
		}

		tank->MovedDistance += std::fabs(Invaders::MovementSystem::GetLinearVelocity(world, transform->GetOwnerID()).X * deltaTime);

	}

	for (auto componentTuple : world->IterateComponents<Invaders::TankComponent, TransformComponent>())
	{
		TransformComponent* transform = std::get<TransformComponent*>(componentTuple);
		Invaders::TankComponent* tank = std::get<Invaders::TankComponent*>(componentTuple);
		TransformComponent* transformTurret = world->GetComponent<TransformComponent>(tank->Turret);

		if (tank->NextRotTime < time)
		{
			tank->NextRotTime = time + 5.0f;
			tank->Degree *= -1;
		}
		Quaternion rotaton(Vector::UNIT_Y, tank->Degree * deltaTime);
		rotaton *= transformTurret->GetLocalRotation();
		transformTurret->SetLocalRotation(rotaton);

	}

	for (auto componentTuple : world->IterateComponents<BulletComponent, TransformComponent>())
	{
		BulletComponent* bullet = std::get<BulletComponent*>(componentTuple);
		TransformComponent* transform = std::get<TransformComponent*>(componentTuple);
		if (time < bullet->GetSpawnTme() + bullet->GetLifeTme())
		{
			Vector move = bullet->GetDirection();
			move *= bullet->GetMovementSpeed();
			move *= TimeSystem::GetTimerDeltaTime(world, Poly::eEngineTimer::GAMEPLAY);
			transform->SetLocalTranslation(transform->GetLocalTranslation() + move);
			bullet->GetCollisionBox().SetPosition(transform->GetLocalTranslation() + move);
		}
		else
		{
			if (!gameManager->GetDeadGameEntities()->Contains(bullet->GetOwnerID()))
				gameManager->GetDeadGameEntities()->PushBack(bullet->GetOwnerID());
		}
	}

	Invaders::CollisionSystem::CollisionComponent* collider;

	for (auto tuple : world->IterateComponents<Invaders::CollisionSystem::CollisionComponent>())
	{
		collider = std::get<Invaders::CollisionSystem::CollisionComponent*>(tuple);
		if (collider->IsColliding())
		{
			if(collider->GetSibling<Invaders::TankComponent>() != nullptr)
				gameManager->SetKillCount(gameManager->GetKillCount() + 1);
			DeferredTaskSystem::DestroyEntity(world, collider->GetOwnerID());
		}
	}

	if (world->GetWorldComponent<InputWorldComponent>()->IsReleased(gameManager->GetQuitKey()))
	{
		//quit game
	}

	CleanUpEnitites(gameManager, world);
}

void ControlSystem::SpawnBullet(GameManagerComponent* gameManager, World* world, Vector pos, Vector direction, float speed)
{
	auto bullet = DeferredTaskSystem::SpawnEntityImmediate(world);

	DeferredTaskSystem::AddComponentImmediate<Poly::TransformComponent>(world, bullet);
	DeferredTaskSystem::AddComponentImmediate<Poly::MeshRenderingComponent>(world, bullet, "Models/bullet/lowpolybullet.obj");
	DeferredTaskSystem::AddComponentImmediate<Invaders::CollisionSystem::CollisionComponent>(world, bullet,  Vector(0, 0, 0), Vector(2.0f,2.0f,2.0f));

	if (direction.Length() > 0)
		direction.Normalize();
	DeferredTaskSystem::AddComponentImmediate<BulletComponent>(world, bullet, speed, direction,
		AABox(world->GetComponent<Poly::TransformComponent>(bullet)->GetLocalTranslation(), Vector(2.0f,2.0f,2.0f)), world->GetWorldComponent<TimeWorldComponent>()->GetGameplayTime());
	Poly::TransformComponent* transform = world->GetComponent<Poly::TransformComponent>(bullet);
	transform->SetLocalScale(Vector(0.25f, 0.25f, 0.25f));
	transform->SetLocalRotation(Quaternion(Vector::UNIT_Y, 180_deg));
	transform->SetLocalTranslation(pos);
	gConsole.LogInfo("Spawning Bullet!");
}
void ControlSystem::CleanUpEnitites(GameManagerComponent* gameManager, World* world)
{
	for (Poly::UniqueID ent : *(gameManager->GetDeadGameEntities()))
	{
		DeferredTaskSystem::DestroyEntity(world, ent);
	}
	gameManager->GetDeadGameEntities()->Clear();
}<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <string>

#include "ThreadSafeMessaging.h"

using namespace std;

class TestMessenger : public ThreadSafeMessaging
{
public:
	TestMessenger()
	{
		m_messaging = NULL;
	}

	TestMessenger( ThreadSafeMessaging* p_messaging )
	{
		m_messaging = p_messaging;
	}

	~TestMessenger()
	{
	}

	void sendMessage( string p_message )
	{
		m_messaging->putMessage( new ProcessMessage(
			MessageType::TEXT, m_messaging, p_message ) );
	}

private:
	ThreadSafeMessaging* m_messaging;

};

TEST(ThreadSafeMessaging, PutMessage)
{
	ThreadSafeMessaging* A = new TestMessenger();

	TestMessenger* B = new TestMessenger(A);
	string hej = "hej";
	B->sendMessage( hej );

}<commit_msg>Written one test for ThreadSafeMessaging and it passes.<commit_after>#include <gtest/gtest.h>
#include <string>

#include "ThreadSafeMessaging.h"

using namespace std;

class TestMessenger : public ThreadSafeMessaging
{
public:
	TestMessenger()
	{
		m_messaging = NULL;
	}

	TestMessenger( ThreadSafeMessaging* p_messaging )
	{
		m_messaging = p_messaging;
	}

	~TestMessenger()
	{
	}

	void sendMessage( string p_message )
	{
		m_messaging->putMessage( new ProcessMessage(
			MessageType::TEXT, m_messaging, p_message ) );
	}

	string getMessage()
	{
		ProcessMessage* message = popMessage();

		string outMessage = message->message;

		delete message;

		return outMessage;
	}

private:
	ThreadSafeMessaging* m_messaging;

};

TEST(ThreadSafeMessaging, PutMessage)
{
	ThreadSafeMessaging* A = new TestMessenger();

	TestMessenger* B = new TestMessenger(A);
	string hej = "hej";
	B->sendMessage( hej );

	EXPECT_STREQ( hej.c_str(), static_cast<TestMessenger*>(A)->getMessage().c_str() );
}<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org

Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com>
Copyright (c) 2000-2009 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreGLESPixelFormat.h"

#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreBitwise.h"

namespace Ogre  {
    GLenum GLESPixelUtil::getGLOriginFormat(PixelFormat mFormat)
    {
        switch (mFormat)
        {
            case PF_A8:
                return GL_ALPHA;

            case PF_L8:
            case PF_L16:
            case PF_FLOAT16_R:
            case PF_FLOAT32_R:
                return GL_LUMINANCE;

            case PF_BYTE_LA:
            case PF_SHORT_GR:
            case PF_FLOAT16_GR:
            case PF_FLOAT32_GR:
                return GL_LUMINANCE_ALPHA;

            // PVRTC compressed formats
#if GL_IMG_texture_compression_pvrtc
            case PF_PVRTC_RGB2:
                return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
            case PF_PVRTC_RGB4:
                return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
            case PF_PVRTC_RGBA2:
                return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
            case PF_PVRTC_RGBA4:
                return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
#endif
            case PF_R5G6B5:
            case PF_B5G6R5:
                return GL_RGB;

            case PF_A1R5G5B5:
                return GL_BGRA;
            case PF_A4R4G4B4:
            case PF_X8R8G8B8:
            case PF_A8R8G8B8:
            case PF_B8G8R8A8:
            case PF_X8B8G8R8:
            case PF_A8B8G8R8:
                return GL_RGBA;

#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
            // Formats are in native endian, so R8G8B8 on little endian is
            // BGR, on big endian it is RGB.
            case PF_R8G8B8:
                return GL_RGB;
            case PF_B8G8R8:
                return 0;
#else
            case PF_R8G8B8:
                return GL_RGB;
            case PF_B8G8R8:
                return 0;
#endif
            case PF_DXT1:
            case PF_DXT3:
            case PF_DXT5:
            case PF_R3G3B2:
            case PF_A2R10G10B10:
            case PF_A2B10G10R10:
            case PF_SHORT_RGB:
            case PF_FLOAT16_RGB:
            case PF_FLOAT32_RGB:
            case PF_FLOAT16_RGBA:
            case PF_FLOAT32_RGBA:
            case PF_SHORT_RGBA:
            default:
                return 0;
        }
    }

    GLenum GLESPixelUtil::getGLOriginDataType(PixelFormat mFormat)
    {
        switch (mFormat)
        {
            case PF_A8:
            case PF_L8:
            case PF_L16:
            case PF_R8G8B8:
            case PF_B8G8R8:
            case PF_BYTE_LA:
                return GL_UNSIGNED_BYTE;
            case PF_R5G6B5:
            case PF_B5G6R5:
                return GL_UNSIGNED_SHORT_5_6_5;
            case PF_A4R4G4B4:
				return GL_UNSIGNED_SHORT_4_4_4_4;
            case PF_A1R5G5B5:
                return GL_UNSIGNED_SHORT_5_5_5_1;

#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
            case PF_X8B8G8R8:
            case PF_A8B8G8R8:
                return GL_UNSIGNED_INT_8_8_8_8_REV;
            case PF_X8R8G8B8:
            case PF_A8R8G8B8:
                return GL_UNSIGNED_INT_8_8_8_8_REV;
            case PF_B8G8R8A8:
                return GL_UNSIGNED_BYTE;
            case PF_R8G8B8A8:
                return GL_UNSIGNED_BYTE;
#else
            case PF_X8B8G8R8:
            case PF_A8B8G8R8:
            case PF_X8R8G8B8:
            case PF_A8R8G8B8:
            case PF_B8G8R8A8:
            case PF_R8G8B8A8:
                return GL_UNSIGNED_BYTE;
#endif
            case PF_DXT1:
            case PF_DXT3:
            case PF_DXT5:
            case PF_R3G3B2:
            case PF_A2R10G10B10:
            case PF_A2B10G10R10:
            case PF_FLOAT16_RGB:
            case PF_FLOAT16_RGBA:
            case PF_FLOAT32_R:
            case PF_FLOAT32_GR:
            case PF_FLOAT32_RGB:
            case PF_FLOAT32_RGBA:
            case PF_SHORT_RGBA:
            case PF_SHORT_RGB:
            case PF_SHORT_GR:
                // TODO not supported
            default:
                return 0;
        }
    }

    GLenum GLESPixelUtil::getGLInternalFormat(PixelFormat fmt, bool hwGamma)
    {
        switch (fmt)
        {
            case PF_L8:
            case PF_L16:
                return GL_LUMINANCE;

            case PF_A8:
                return GL_ALPHA;

            case PF_BYTE_LA:
                return GL_LUMINANCE_ALPHA;

#if GL_IMG_texture_compression_pvrtc
            case PF_PVRTC_RGB2:
                return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
            case PF_PVRTC_RGB4:
                return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
            case PF_PVRTC_RGBA2:
                return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
            case PF_PVRTC_RGBA4:
                return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
#endif

            case PF_X8B8G8R8:
            case PF_X8R8G8B8:
            case PF_A8R8G8B8:
            case PF_B8G8R8A8:
            case PF_A1R5G5B5:
            case PF_A4R4G4B4:
                return GL_RGBA;
            case PF_R5G6B5:
            case PF_B5G6R5:
            case PF_R8G8B8:
            case PF_B8G8R8:
                return GL_RGB;
            case PF_A4L4:
            case PF_R3G3B2:
            case PF_A2R10G10B10:
            case PF_A2B10G10R10:
            case PF_DXT1:
            case PF_DXT3:
            case PF_DXT5:
            case PF_FLOAT16_R:
            case PF_FLOAT16_RGB:
            case PF_FLOAT16_GR:
            case PF_FLOAT16_RGBA:
            case PF_FLOAT32_R:
            case PF_FLOAT32_GR:
            case PF_FLOAT32_RGB:
            case PF_FLOAT32_RGBA:
            case PF_SHORT_RGBA:
            case PF_SHORT_RGB:
            case PF_SHORT_GR:
            default:
                return 0;
        }
    }

    GLenum GLESPixelUtil::getClosestGLInternalFormat(PixelFormat mFormat,
                                                   bool hwGamma)
    {
        GLenum format = getGLInternalFormat(mFormat, hwGamma);
        if (format == 0)
        {
            if (hwGamma)
            {
                // TODO not supported
                return 0;
            }
            else
            {
                return GL_RGBA;
            }
        }
        else
        {
            return format;
        }
    }

    PixelFormat GLESPixelUtil::getClosestOGREFormat(GLenum fmt, GLenum dataType)
    {
        switch (fmt)
        {
#if GL_IMG_texture_compression_pvrtc
            case GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG:
                return PF_PVRTC_RGB2;
            case GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:
                return PF_PVRTC_RGBA2;
            case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:
                return PF_PVRTC_RGB4;
            case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:
                return PF_PVRTC_RGBA4;
#endif
            case GL_LUMINANCE:
                return PF_L8;
            case GL_ALPHA:
                return PF_A8;
            case GL_LUMINANCE_ALPHA:
                return PF_BYTE_LA;

            case GL_RGB:
                switch(dataType)
                {
                    case GL_UNSIGNED_SHORT_5_6_5:
                        return PF_B5G6R5;
                    default:
                        return PF_R8G8B8;
                };
            case GL_RGBA:
                switch(dataType)
                {
                    case GL_UNSIGNED_SHORT_5_5_5_1:
                        return PF_A1R5G5B5;
                    case GL_UNSIGNED_SHORT_4_4_4_4:
                        return PF_A4R4G4B4;
                    default:
#if (OGRE_PLATFORM == OGRE_PLATFORM_IPHONE)
                        // seems that in iPhone we need this value to get the right color
                        return PF_A8R8G8B8;
#else
                        return PF_X8B8G8R8;
#endif
                }
#ifdef GL_BGRA
            case GL_BGRA:
                return PF_A8B8G8R8;
#endif

            default:
                //TODO: not supported
                return PF_A8R8G8B8;
        };
    }

    size_t GLESPixelUtil::getMaxMipmaps(size_t width, size_t height, size_t depth,
                                      PixelFormat format)
    {
        size_t count = 0;

        do {
            if (width > 1)
            {
                width = width / 2;
            }
            if (height > 1)
            {
                height = height / 2;
            }
            if (depth > 1)
            {
                depth = depth / 2;
            }
            /*
            NOT needed, compressed formats will have mipmaps up to 1x1
            if(PixelUtil::isValidExtent(width, height, depth, format))
                count ++;
            else
                break;
            */
            count++;
        } while (!(width == 1 && height == 1 && depth == 1));

        return count;
    }

    size_t GLESPixelUtil::optionalPO2(size_t value)
    {
        const RenderSystemCapabilities *caps =
            Root::getSingleton().getRenderSystem()->getCapabilities();

        if (caps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES))
        {
            return value;
        }
        else
        {
            return Bitwise::firstPO2From((uint32)value);
        }
    }

    void GLESPixelUtil::convertToGLformat(const PixelBox &src, const PixelBox &dst)
    {
        // Always need to convert PF_A4R4G4B4, GL expects the colors to be in the
        // reverse order
        if (dst.format == PF_A4R4G4B4)
        {
            // Convert PF_A4R4G4B4 -> PF_B4G4R4A4
            // Reverse pixel order
            uint16 *srcptr = static_cast<uint16*>(src.data)
			+ (src.left + src.top * src.rowPitch + src.front * src.slicePitch);
            uint16 *dstptr = static_cast<uint16*>(dst.data)
			+ (dst.left + dst.top * dst.rowPitch + dst.front * dst.slicePitch);
            const size_t srcSliceSkip = src.getSliceSkip();
            const size_t dstSliceSkip = dst.getSliceSkip();
            const size_t k = src.right - src.left;
            for(size_t z=src.front; z<src.back; z++)
            {
                for(size_t y=src.top; y<src.bottom; y++)
                {
                    for(size_t x=0; x<k; x++)
                    {
                        dstptr[x] = ((srcptr[x]&0x000F)<<12) |  // B
                                    ((srcptr[x]&0x00F0)<<4) |   // G
                                    ((srcptr[x]&0x0F00)>>4) |   // R
                                    ((srcptr[x]&0xF000)>>12);   // A
                    }
                    srcptr += src.rowPitch;
                    dstptr += dst.rowPitch;
                }
                srcptr += srcSliceSkip;
                dstptr += dstSliceSkip;
            }
        }
    }
}
<commit_msg>GLES: Use the correct GL type for BGRA textures<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org

Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com>
Copyright (c) 2000-2009 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreGLESPixelFormat.h"

#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreBitwise.h"

namespace Ogre  {
    GLenum GLESPixelUtil::getGLOriginFormat(PixelFormat mFormat)
    {
        switch (mFormat)
        {
            case PF_A8:
                return GL_ALPHA;

            case PF_L8:
            case PF_L16:
            case PF_FLOAT16_R:
            case PF_FLOAT32_R:
                return GL_LUMINANCE;

            case PF_BYTE_LA:
            case PF_SHORT_GR:
            case PF_FLOAT16_GR:
            case PF_FLOAT32_GR:
                return GL_LUMINANCE_ALPHA;

            // PVRTC compressed formats
#if GL_IMG_texture_compression_pvrtc
            case PF_PVRTC_RGB2:
                return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
            case PF_PVRTC_RGB4:
                return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
            case PF_PVRTC_RGBA2:
                return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
            case PF_PVRTC_RGBA4:
                return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
#endif
            case PF_R5G6B5:
            case PF_B5G6R5:
                return GL_RGB;

            case PF_A1R5G5B5:
            case PF_B8G8R8A8:
                return GL_BGRA;
            case PF_A4R4G4B4:
            case PF_X8R8G8B8:
            case PF_A8R8G8B8:
            case PF_X8B8G8R8:
            case PF_A8B8G8R8:
                return GL_RGBA;

#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
            // Formats are in native endian, so R8G8B8 on little endian is
            // BGR, on big endian it is RGB.
            case PF_R8G8B8:
                return GL_RGB;
            case PF_B8G8R8:
                return 0;
#else
            case PF_R8G8B8:
                return GL_RGB;
            case PF_B8G8R8:
                return 0;
#endif
            case PF_DXT1:
            case PF_DXT3:
            case PF_DXT5:
            case PF_R3G3B2:
            case PF_A2R10G10B10:
            case PF_A2B10G10R10:
            case PF_SHORT_RGB:
            case PF_FLOAT16_RGB:
            case PF_FLOAT32_RGB:
            case PF_FLOAT16_RGBA:
            case PF_FLOAT32_RGBA:
            case PF_SHORT_RGBA:
            default:
                return 0;
        }
    }

    GLenum GLESPixelUtil::getGLOriginDataType(PixelFormat mFormat)
    {
        switch (mFormat)
        {
            case PF_A8:
            case PF_L8:
            case PF_L16:
            case PF_R8G8B8:
            case PF_B8G8R8:
            case PF_BYTE_LA:
                return GL_UNSIGNED_BYTE;
            case PF_R5G6B5:
            case PF_B5G6R5:
                return GL_UNSIGNED_SHORT_5_6_5;
            case PF_A4R4G4B4:
				return GL_UNSIGNED_SHORT_4_4_4_4;
            case PF_A1R5G5B5:
                return GL_UNSIGNED_SHORT_5_5_5_1;

#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
            case PF_X8B8G8R8:
            case PF_A8B8G8R8:
                return GL_UNSIGNED_INT_8_8_8_8_REV;
            case PF_X8R8G8B8:
            case PF_A8R8G8B8:
                return GL_UNSIGNED_INT_8_8_8_8_REV;
            case PF_B8G8R8A8:
                return GL_UNSIGNED_BYTE;
            case PF_R8G8B8A8:
                return GL_UNSIGNED_BYTE;
#else
            case PF_X8B8G8R8:
            case PF_A8B8G8R8:
            case PF_X8R8G8B8:
            case PF_A8R8G8B8:
            case PF_B8G8R8A8:
            case PF_R8G8B8A8:
                return GL_UNSIGNED_BYTE;
#endif
            case PF_DXT1:
            case PF_DXT3:
            case PF_DXT5:
            case PF_R3G3B2:
            case PF_A2R10G10B10:
            case PF_A2B10G10R10:
            case PF_FLOAT16_RGB:
            case PF_FLOAT16_RGBA:
            case PF_FLOAT32_R:
            case PF_FLOAT32_GR:
            case PF_FLOAT32_RGB:
            case PF_FLOAT32_RGBA:
            case PF_SHORT_RGBA:
            case PF_SHORT_RGB:
            case PF_SHORT_GR:
                // TODO not supported
            default:
                return 0;
        }
    }

    GLenum GLESPixelUtil::getGLInternalFormat(PixelFormat fmt, bool hwGamma)
    {
        switch (fmt)
        {
            case PF_L8:
            case PF_L16:
                return GL_LUMINANCE;

            case PF_A8:
                return GL_ALPHA;

            case PF_BYTE_LA:
                return GL_LUMINANCE_ALPHA;

#if GL_IMG_texture_compression_pvrtc
            case PF_PVRTC_RGB2:
                return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
            case PF_PVRTC_RGB4:
                return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
            case PF_PVRTC_RGBA2:
                return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
            case PF_PVRTC_RGBA4:
                return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
#endif

            case PF_B8G8R8A8:
                return GL_BGRA;
            case PF_X8B8G8R8:
            case PF_X8R8G8B8:
            case PF_A8R8G8B8:
            case PF_A1R5G5B5:
            case PF_A4R4G4B4:
                return GL_RGBA;
            case PF_R5G6B5:
            case PF_B5G6R5:
            case PF_R8G8B8:
            case PF_B8G8R8:
                return GL_RGB;
            case PF_A4L4:
            case PF_R3G3B2:
            case PF_A2R10G10B10:
            case PF_A2B10G10R10:
            case PF_DXT1:
            case PF_DXT3:
            case PF_DXT5:
            case PF_FLOAT16_R:
            case PF_FLOAT16_RGB:
            case PF_FLOAT16_GR:
            case PF_FLOAT16_RGBA:
            case PF_FLOAT32_R:
            case PF_FLOAT32_GR:
            case PF_FLOAT32_RGB:
            case PF_FLOAT32_RGBA:
            case PF_SHORT_RGBA:
            case PF_SHORT_RGB:
            case PF_SHORT_GR:
            default:
                return 0;
        }
    }

    GLenum GLESPixelUtil::getClosestGLInternalFormat(PixelFormat mFormat,
                                                   bool hwGamma)
    {
        GLenum format = getGLInternalFormat(mFormat, hwGamma);
        if (format == 0)
        {
            if (hwGamma)
            {
                // TODO not supported
                return 0;
            }
            else
            {
                return GL_RGBA;
            }
        }
        else
        {
            return format;
        }
    }

    PixelFormat GLESPixelUtil::getClosestOGREFormat(GLenum fmt, GLenum dataType)
    {
        switch (fmt)
        {
#if GL_IMG_texture_compression_pvrtc
            case GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG:
                return PF_PVRTC_RGB2;
            case GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:
                return PF_PVRTC_RGBA2;
            case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:
                return PF_PVRTC_RGB4;
            case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:
                return PF_PVRTC_RGBA4;
#endif
            case GL_LUMINANCE:
                return PF_L8;
            case GL_ALPHA:
                return PF_A8;
            case GL_LUMINANCE_ALPHA:
                return PF_BYTE_LA;

            case GL_RGB:
                switch(dataType)
                {
                    case GL_UNSIGNED_SHORT_5_6_5:
                        return PF_B5G6R5;
                    default:
                        return PF_R8G8B8;
                };
            case GL_RGBA:
                switch(dataType)
                {
                    case GL_UNSIGNED_SHORT_5_5_5_1:
                        return PF_A1R5G5B5;
                    case GL_UNSIGNED_SHORT_4_4_4_4:
                        return PF_A4R4G4B4;
                    default:
#if (OGRE_PLATFORM == OGRE_PLATFORM_IPHONE)
                        // seems that in iPhone we need this value to get the right color
                        return PF_A8R8G8B8;
#else
                        return PF_X8B8G8R8;
#endif
                }
#ifdef GL_BGRA
            case GL_BGRA:
                return PF_A8B8G8R8;
#endif

            default:
                //TODO: not supported
                return PF_A8R8G8B8;
        };
    }

    size_t GLESPixelUtil::getMaxMipmaps(size_t width, size_t height, size_t depth,
                                      PixelFormat format)
    {
        size_t count = 0;

        do {
            if (width > 1)
            {
                width = width / 2;
            }
            if (height > 1)
            {
                height = height / 2;
            }
            if (depth > 1)
            {
                depth = depth / 2;
            }
            /*
            NOT needed, compressed formats will have mipmaps up to 1x1
            if(PixelUtil::isValidExtent(width, height, depth, format))
                count ++;
            else
                break;
            */
            count++;
        } while (!(width == 1 && height == 1 && depth == 1));

        return count;
    }

    size_t GLESPixelUtil::optionalPO2(size_t value)
    {
        const RenderSystemCapabilities *caps =
            Root::getSingleton().getRenderSystem()->getCapabilities();

        if (caps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES))
        {
            return value;
        }
        else
        {
            return Bitwise::firstPO2From((uint32)value);
        }
    }

    void GLESPixelUtil::convertToGLformat(const PixelBox &src, const PixelBox &dst)
    {
        // Always need to convert PF_A4R4G4B4, GL expects the colors to be in the
        // reverse order
        if (dst.format == PF_A4R4G4B4)
        {
            // Convert PF_A4R4G4B4 -> PF_B4G4R4A4
            // Reverse pixel order
            uint16 *srcptr = static_cast<uint16*>(src.data)
			+ (src.left + src.top * src.rowPitch + src.front * src.slicePitch);
            uint16 *dstptr = static_cast<uint16*>(dst.data)
			+ (dst.left + dst.top * dst.rowPitch + dst.front * dst.slicePitch);
            const size_t srcSliceSkip = src.getSliceSkip();
            const size_t dstSliceSkip = dst.getSliceSkip();
            const size_t k = src.right - src.left;
            for(size_t z=src.front; z<src.back; z++)
            {
                for(size_t y=src.top; y<src.bottom; y++)
                {
                    for(size_t x=0; x<k; x++)
                    {
                        dstptr[x] = ((srcptr[x]&0x000F)<<12) |  // B
                                    ((srcptr[x]&0x00F0)<<4) |   // G
                                    ((srcptr[x]&0x0F00)>>4) |   // R
                                    ((srcptr[x]&0xF000)>>12);   // A
                    }
                    srcptr += src.rowPitch;
                    dstptr += dst.rowPitch;
                }
                srcptr += srcSliceSkip;
                dstptr += dstSliceSkip;
            }
        }
    }
}
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com>
Copyright (c) 2000-2009 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreRoot.h"

#include "OgreGLES2Prerequisites.h"
#include "OgreGLES2RenderSystem.h"

#include "OgreEGLSupport.h"
#include "OgreEGLWindow.h"
#include "OgreEGLRenderTexture.h"

namespace Ogre {

    EGLSupport::EGLSupport()
        : mGLDisplay(0),
          mNativeDisplay(0),
	  mRandr(false)
    {
    }

    EGLSupport::~EGLSupport()
    {
    }

    void EGLSupport::addConfig(void)
    {
        ConfigOption optFullScreen;
        ConfigOption optVideoMode;
        ConfigOption optDisplayFrequency;
        ConfigOption optFSAA;
        ConfigOption optRTTMode;

        optFullScreen.name = "Full Screen";
        optFullScreen.immutable = false;

        optVideoMode.name = "Video Mode";
        optVideoMode.immutable = false;

        optDisplayFrequency.name = "Display Frequency";
        optDisplayFrequency.immutable = false;

        optFSAA.name = "FSAA";
        optFSAA.immutable = false;

        optRTTMode.name = "RTT Preferred Mode";
        optRTTMode.immutable = false;

        optFullScreen.possibleValues.push_back("No");
        optFullScreen.possibleValues.push_back("Yes");

        optFullScreen.currentValue = optFullScreen.possibleValues[1];

        VideoModes::const_iterator value = mVideoModes.begin();
        VideoModes::const_iterator end = mVideoModes.end();

        for (; value != end; value++)
        {
            String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4);
            optVideoMode.possibleValues.push_back(mode);
        }
        removeDuplicates(optVideoMode.possibleValues);

        optVideoMode.currentValue = StringConverter::toString(mCurrentMode.first.first,4) + " x " + StringConverter::toString(mCurrentMode.first.second,4);

        refreshConfig();
        if (!mSampleLevels.empty())
        {
            StringVector::const_iterator value = mSampleLevels.begin();
            StringVector::const_iterator end = mSampleLevels.end();

            for (; value != end; value++)
            {
                optFSAA.possibleValues.push_back(*value);
            }

            optFSAA.currentValue = optFSAA.possibleValues[0];
        }

        optRTTMode.possibleValues.push_back("Copy");
        optRTTMode.currentValue = optRTTMode.possibleValues[0];

        mOptions[optFullScreen.name] = optFullScreen;
        mOptions[optVideoMode.name] = optVideoMode;
        mOptions[optDisplayFrequency.name] = optDisplayFrequency;
        mOptions[optFSAA.name] = optFSAA;
        mOptions[optRTTMode.name] = optRTTMode;

        refreshConfig();
    }

    void EGLSupport::refreshConfig(void)
    {
        ConfigOptionMap::iterator optVideoMode = mOptions.find("Video Mode");
        ConfigOptionMap::iterator optDisplayFrequency = mOptions.find("Display Frequency");

        if (optVideoMode != mOptions.end() && optDisplayFrequency != mOptions.end())
        {
            optDisplayFrequency->second.possibleValues.clear();

            VideoModes::const_iterator value = mVideoModes.begin();
            VideoModes::const_iterator end = mVideoModes.end();

            for (; value != end; value++)
            {
                String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4);

                if (mode == optVideoMode->second.currentValue)
                {
                    String frequency = StringConverter::toString(value->second) + " MHz";

                    optDisplayFrequency->second.possibleValues.push_back(frequency);
                }
            }

            if (!optDisplayFrequency->second.possibleValues.empty())
            {
                optDisplayFrequency->second.currentValue = optDisplayFrequency->second.possibleValues[0];
            }
            else
            {
                optVideoMode->second.currentValue = StringConverter::toString(mVideoModes[0].first.first,4) + " x " + StringConverter::toString(mVideoModes[0].first.second,4);
                optDisplayFrequency->second.currentValue = StringConverter::toString(mVideoModes[0].second) + " MHz";
            }
        }
    }

    void EGLSupport::setConfigOption(const String &name, const String &value)
    {
        GLES2Support::setConfigOption(name, value);
        if (name == "Video Mode")
        {
            refreshConfig();
        }
    }

    String EGLSupport::validateConfig(void)
    {
        // TODO
        return StringUtil::BLANK;
    }

    EGLDisplay EGLSupport::getGLDisplay(void)
    {
        EGLint major = 0, minor = 0;

        mGLDisplay = eglGetDisplay(mNativeDisplay);
        EGL_CHECK_ERROR

        if(mGLDisplay == EGL_NO_DISPLAY)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Couldn`t open EGLDisplay " + getDisplayName(),
                        "EGLSupport::getGLDisplay");
        }

        if (eglInitialize(mGLDisplay, &major, &minor) == EGL_FALSE)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Couldn`t initialize EGLDisplay ",
                        "EGLSupport::getGLDisplay");
        }
        EGL_CHECK_ERROR
        return mGLDisplay;
    }

    String EGLSupport::getDisplayName(void)
    {
		return "todo";
    }

    EGLConfig* EGLSupport::chooseGLConfig(const GLint *attribList, GLint *nElements)
    {
        EGLConfig *configs;

        if (eglChooseConfig(mGLDisplay, attribList, NULL, 0, nElements) == EGL_FALSE)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Failed to choose config",
                        __FUNCTION__);

            *nElements = 0;
            return 0;
        }
        EGL_CHECK_ERROR
        configs = (EGLConfig*) malloc(*nElements * sizeof(EGLConfig));
        if (eglChooseConfig(mGLDisplay, attribList, configs, *nElements, nElements) == EGL_FALSE)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Failed to choose config",
                        __FUNCTION__);

            *nElements = 0;
            free(configs);
            return 0;
        }
        EGL_CHECK_ERROR
        return configs;
    }

    EGLBoolean EGLSupport::getGLConfigAttrib(EGLConfig glConfig, GLint attribute, GLint *value)
    {
        EGLBoolean status;

        status = eglGetConfigAttrib(mGLDisplay, glConfig, attribute, value);
        EGL_CHECK_ERROR
        return status;
    }

    void* EGLSupport::getProcAddress(const Ogre::String& name)
    {
        return (void*)eglGetProcAddress((const char*) name.c_str());
    }

    ::EGLConfig EGLSupport::getGLConfigFromContext(::EGLContext context)
    {
        ::EGLConfig glConfig = 0;

        if (eglQueryContext(mGLDisplay, context, EGL_CONFIG_ID, (EGLint *) &glConfig) == EGL_FALSE)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Fail to get config from context",
                        __FUNCTION__);
            return 0;
        }
        EGL_CHECK_ERROR
        return glConfig;
    }

    ::EGLConfig EGLSupport::getGLConfigFromDrawable(::EGLSurface drawable,
                                                    unsigned int *w, unsigned int *h)
    {
        ::EGLConfig glConfig = 0;

        if (eglQuerySurface(mGLDisplay, drawable, EGL_CONFIG_ID, (EGLint *) &glConfig) == EGL_FALSE)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Fail to get config from drawable",
                        __FUNCTION__);
            return 0;
        }
        EGL_CHECK_ERROR
        eglQuerySurface(mGLDisplay, drawable, EGL_WIDTH, (EGLint *) w);
        EGL_CHECK_ERROR
        eglQuerySurface(mGLDisplay, drawable, EGL_HEIGHT, (EGLint *) h);
        EGL_CHECK_ERROR
        return glConfig;
    }

    //------------------------------------------------------------------------
    // A helper class for the implementation of selectFBConfig
    //------------------------------------------------------------------------
    class GLConfigAttribs
    {
        public:
            GLConfigAttribs(const int* attribs)
            {
                fields[EGL_CONFIG_CAVEAT] = EGL_NONE;

                for (int i = 0; attribs[2*i] != EGL_NONE; i++)
                {
                    fields[attribs[2*i]] = attribs[2*i+1];
                }
            }

            void load(EGLSupport* const glSupport, EGLConfig glConfig)
            {
                std::map<int,int>::iterator it;

                for (it = fields.begin(); it != fields.end(); it++)
                {
                    it->second = EGL_NONE;

                    glSupport->getGLConfigAttrib(glConfig, it->first, &it->second);
                }
            }

            bool operator>(GLConfigAttribs& alternative)
            {
                // Caveats are best avoided, but might be needed for anti-aliasing
                if (fields[EGL_CONFIG_CAVEAT] != alternative.fields[EGL_CONFIG_CAVEAT])
                {
                    if (fields[EGL_CONFIG_CAVEAT] == EGL_SLOW_CONFIG)
                    {
                        return false;
                    }

                    if (fields.find(EGL_SAMPLES) != fields.end() &&
                        fields[EGL_SAMPLES] < alternative.fields[EGL_SAMPLES])
                    {
                        return false;
                    }
                }

                std::map<int,int>::iterator it;

                for (it = fields.begin(); it != fields.end(); it++)
                {
                    if (it->first != EGL_CONFIG_CAVEAT &&
                        fields[it->first] > alternative.fields[it->first])
                    {
                        return true;
                    }
                }

                return false;
            }

            std::map<int,int> fields;
    };

    ::EGLConfig EGLSupport::selectGLConfig(const int* minAttribs, const int *maxAttribs)
    {
        EGLConfig *glConfigs;
        EGLConfig glConfig = 0;
        int config, nConfigs = 0;

        glConfigs = chooseGLConfig(minAttribs, &nConfigs);

        if (!nConfigs)
        {
            return 0;
        }

        glConfig = glConfigs[0];

        if (maxAttribs)
        {
            GLConfigAttribs maximum(maxAttribs);
            GLConfigAttribs best(maxAttribs);
            GLConfigAttribs candidate(maxAttribs);

            best.load(this, glConfig);

            for (config = 1; config < nConfigs; config++)
            {
                candidate.load(this, glConfigs[config]);

                if (candidate > maximum)
                {
                    continue;
                }

                if (candidate > best)
                {
                    glConfig = glConfigs[config];

                    best.load(this, glConfig);
                }
            }
        }

        free(glConfigs);
        return glConfig;
    }

    void EGLSupport::switchMode(void)
    {
        return switchMode(mOriginalMode.first.first,
                          mOriginalMode.first.second, mOriginalMode.second);
    }

    RenderWindow* EGLSupport::createWindow(bool autoCreateWindow,
                                           GLES2RenderSystem* renderSystem,
                                           const String& windowTitle)
    {
        RenderWindow *window = 0;

        if (autoCreateWindow)
        {
            ConfigOptionMap::iterator opt;
            ConfigOptionMap::iterator end = mOptions.end();
            NameValuePairList miscParams;

            bool fullscreen = false;
            uint w = 640, h = 480;

            if ((opt = mOptions.find("Full Screen")) != end)
            {
                fullscreen = (opt->second.currentValue == "Yes");
            }

            if ((opt = mOptions.find("Display Frequency")) != end)
            {
                miscParams["displayFrequency"] = opt->second.currentValue;
            }

            if ((opt = mOptions.find("Video Mode")) != end)
            {
                String val = opt->second.currentValue;
                String::size_type pos = val.find('x');

                if (pos != String::npos)
                {
                    w = StringConverter::parseUnsignedInt(val.substr(0, pos));
                    h = StringConverter::parseUnsignedInt(val.substr(pos + 1));
                }
            }

            if ((opt = mOptions.find("FSAA")) != end)
            {
                miscParams["FSAA"] = opt->second.currentValue;
            }

            window = renderSystem->_createRenderWindow(windowTitle, w, h, fullscreen, &miscParams);
        }

        return window;
    }

    ::EGLContext EGLSupport::createNewContext(EGLDisplay eglDisplay,
					      ::EGLConfig glconfig,
                                              ::EGLContext shareList) const
    {
        EGLint contextAttrs[] = {
            EGL_CONTEXT_CLIENT_VERSION, 2,
            EGL_NONE, EGL_NONE
        };
	::EGLContext context = ((::EGLContext) 0);
	if (eglDisplay == ((EGLDisplay) 0))
	{
		context = eglCreateContext(mGLDisplay, glconfig, shareList, contextAttrs);
        EGL_CHECK_ERROR
	}
	else
	{
		context = eglCreateContext(eglDisplay, glconfig, 0, contextAttrs);
        EGL_CHECK_ERROR
	}

	if (context == ((::EGLContext) 0))
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Fail to create New context",
                        __FUNCTION__);
            return 0;
        }

        return context;
    }

    void EGLSupport::start()
    {
    }

    void EGLSupport::stop()
    {
    }

    void EGLSupport::setGLDisplay( EGLDisplay val )
    {
        mGLDisplay = val;
    }
}
<commit_msg>GLES2: When running on Linux, use FBO's for RTT's by default.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com>
Copyright (c) 2000-2009 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreRoot.h"

#include "OgreGLES2Prerequisites.h"
#include "OgreGLES2RenderSystem.h"

#include "OgreEGLSupport.h"
#include "OgreEGLWindow.h"
#include "OgreEGLRenderTexture.h"

namespace Ogre {

    EGLSupport::EGLSupport()
        : mGLDisplay(0),
          mNativeDisplay(0),
	  mRandr(false)
    {
    }

    EGLSupport::~EGLSupport()
    {
    }

    void EGLSupport::addConfig(void)
    {
        ConfigOption optFullScreen;
        ConfigOption optVideoMode;
        ConfigOption optDisplayFrequency;
        ConfigOption optFSAA;
        ConfigOption optRTTMode;

        optFullScreen.name = "Full Screen";
        optFullScreen.immutable = false;

        optVideoMode.name = "Video Mode";
        optVideoMode.immutable = false;

        optDisplayFrequency.name = "Display Frequency";
        optDisplayFrequency.immutable = false;

        optFSAA.name = "FSAA";
        optFSAA.immutable = false;

        optRTTMode.name = "RTT Preferred Mode";
        optRTTMode.possibleValues.push_back("FBO");
        optRTTMode.possibleValues.push_back("Copy");
        optRTTMode.currentValue = "FBO";
        optRTTMode.immutable = false;

        optFullScreen.possibleValues.push_back("No");
        optFullScreen.possibleValues.push_back("Yes");

        optFullScreen.currentValue = optFullScreen.possibleValues[1];

        VideoModes::const_iterator value = mVideoModes.begin();
        VideoModes::const_iterator end = mVideoModes.end();

        for (; value != end; value++)
        {
            String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4);
            optVideoMode.possibleValues.push_back(mode);
        }
        removeDuplicates(optVideoMode.possibleValues);

        optVideoMode.currentValue = StringConverter::toString(mCurrentMode.first.first,4) + " x " + StringConverter::toString(mCurrentMode.first.second,4);

        refreshConfig();
        if (!mSampleLevels.empty())
        {
            StringVector::const_iterator value = mSampleLevels.begin();
            StringVector::const_iterator end = mSampleLevels.end();

            for (; value != end; value++)
            {
                optFSAA.possibleValues.push_back(*value);
            }

            optFSAA.currentValue = optFSAA.possibleValues[0];
        }

        optRTTMode.currentValue = optRTTMode.possibleValues[0];

        mOptions[optFullScreen.name] = optFullScreen;
        mOptions[optVideoMode.name] = optVideoMode;
        mOptions[optDisplayFrequency.name] = optDisplayFrequency;
        mOptions[optFSAA.name] = optFSAA;
        mOptions[optRTTMode.name] = optRTTMode;

        refreshConfig();
    }

    void EGLSupport::refreshConfig(void)
    {
        ConfigOptionMap::iterator optVideoMode = mOptions.find("Video Mode");
        ConfigOptionMap::iterator optDisplayFrequency = mOptions.find("Display Frequency");

        if (optVideoMode != mOptions.end() && optDisplayFrequency != mOptions.end())
        {
            optDisplayFrequency->second.possibleValues.clear();

            VideoModes::const_iterator value = mVideoModes.begin();
            VideoModes::const_iterator end = mVideoModes.end();

            for (; value != end; value++)
            {
                String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4);

                if (mode == optVideoMode->second.currentValue)
                {
                    String frequency = StringConverter::toString(value->second) + " MHz";

                    optDisplayFrequency->second.possibleValues.push_back(frequency);
                }
            }

            if (!optDisplayFrequency->second.possibleValues.empty())
            {
                optDisplayFrequency->second.currentValue = optDisplayFrequency->second.possibleValues[0];
            }
            else
            {
                optVideoMode->second.currentValue = StringConverter::toString(mVideoModes[0].first.first,4) + " x " + StringConverter::toString(mVideoModes[0].first.second,4);
                optDisplayFrequency->second.currentValue = StringConverter::toString(mVideoModes[0].second) + " MHz";
            }
        }
    }

    void EGLSupport::setConfigOption(const String &name, const String &value)
    {
        GLES2Support::setConfigOption(name, value);
        if (name == "Video Mode")
        {
            refreshConfig();
        }
    }

    String EGLSupport::validateConfig(void)
    {
        // TODO
        return StringUtil::BLANK;
    }

    EGLDisplay EGLSupport::getGLDisplay(void)
    {
        EGLint major = 0, minor = 0;

        mGLDisplay = eglGetDisplay(mNativeDisplay);
        EGL_CHECK_ERROR

        if(mGLDisplay == EGL_NO_DISPLAY)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Couldn`t open EGLDisplay " + getDisplayName(),
                        "EGLSupport::getGLDisplay");
        }

        if (eglInitialize(mGLDisplay, &major, &minor) == EGL_FALSE)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Couldn`t initialize EGLDisplay ",
                        "EGLSupport::getGLDisplay");
        }
        EGL_CHECK_ERROR
        return mGLDisplay;
    }

    String EGLSupport::getDisplayName(void)
    {
		return "todo";
    }

    EGLConfig* EGLSupport::chooseGLConfig(const GLint *attribList, GLint *nElements)
    {
        EGLConfig *configs;

        if (eglChooseConfig(mGLDisplay, attribList, NULL, 0, nElements) == EGL_FALSE)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Failed to choose config",
                        __FUNCTION__);

            *nElements = 0;
            return 0;
        }
        EGL_CHECK_ERROR
        configs = (EGLConfig*) malloc(*nElements * sizeof(EGLConfig));
        if (eglChooseConfig(mGLDisplay, attribList, configs, *nElements, nElements) == EGL_FALSE)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Failed to choose config",
                        __FUNCTION__);

            *nElements = 0;
            free(configs);
            return 0;
        }
        EGL_CHECK_ERROR
        return configs;
    }

    EGLBoolean EGLSupport::getGLConfigAttrib(EGLConfig glConfig, GLint attribute, GLint *value)
    {
        EGLBoolean status;

        status = eglGetConfigAttrib(mGLDisplay, glConfig, attribute, value);
        EGL_CHECK_ERROR
        return status;
    }

    void* EGLSupport::getProcAddress(const Ogre::String& name)
    {
        return (void*)eglGetProcAddress((const char*) name.c_str());
    }

    ::EGLConfig EGLSupport::getGLConfigFromContext(::EGLContext context)
    {
        ::EGLConfig glConfig = 0;

        if (eglQueryContext(mGLDisplay, context, EGL_CONFIG_ID, (EGLint *) &glConfig) == EGL_FALSE)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Fail to get config from context",
                        __FUNCTION__);
            return 0;
        }
        EGL_CHECK_ERROR
        return glConfig;
    }

    ::EGLConfig EGLSupport::getGLConfigFromDrawable(::EGLSurface drawable,
                                                    unsigned int *w, unsigned int *h)
    {
        ::EGLConfig glConfig = 0;

        if (eglQuerySurface(mGLDisplay, drawable, EGL_CONFIG_ID, (EGLint *) &glConfig) == EGL_FALSE)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Fail to get config from drawable",
                        __FUNCTION__);
            return 0;
        }
        EGL_CHECK_ERROR
        eglQuerySurface(mGLDisplay, drawable, EGL_WIDTH, (EGLint *) w);
        EGL_CHECK_ERROR
        eglQuerySurface(mGLDisplay, drawable, EGL_HEIGHT, (EGLint *) h);
        EGL_CHECK_ERROR
        return glConfig;
    }

    //------------------------------------------------------------------------
    // A helper class for the implementation of selectFBConfig
    //------------------------------------------------------------------------
    class GLConfigAttribs
    {
        public:
            GLConfigAttribs(const int* attribs)
            {
                fields[EGL_CONFIG_CAVEAT] = EGL_NONE;

                for (int i = 0; attribs[2*i] != EGL_NONE; i++)
                {
                    fields[attribs[2*i]] = attribs[2*i+1];
                }
            }

            void load(EGLSupport* const glSupport, EGLConfig glConfig)
            {
                std::map<int,int>::iterator it;

                for (it = fields.begin(); it != fields.end(); it++)
                {
                    it->second = EGL_NONE;

                    glSupport->getGLConfigAttrib(glConfig, it->first, &it->second);
                }
            }

            bool operator>(GLConfigAttribs& alternative)
            {
                // Caveats are best avoided, but might be needed for anti-aliasing
                if (fields[EGL_CONFIG_CAVEAT] != alternative.fields[EGL_CONFIG_CAVEAT])
                {
                    if (fields[EGL_CONFIG_CAVEAT] == EGL_SLOW_CONFIG)
                    {
                        return false;
                    }

                    if (fields.find(EGL_SAMPLES) != fields.end() &&
                        fields[EGL_SAMPLES] < alternative.fields[EGL_SAMPLES])
                    {
                        return false;
                    }
                }

                std::map<int,int>::iterator it;

                for (it = fields.begin(); it != fields.end(); it++)
                {
                    if (it->first != EGL_CONFIG_CAVEAT &&
                        fields[it->first] > alternative.fields[it->first])
                    {
                        return true;
                    }
                }

                return false;
            }

            std::map<int,int> fields;
    };

    ::EGLConfig EGLSupport::selectGLConfig(const int* minAttribs, const int *maxAttribs)
    {
        EGLConfig *glConfigs;
        EGLConfig glConfig = 0;
        int config, nConfigs = 0;

        glConfigs = chooseGLConfig(minAttribs, &nConfigs);

        if (!nConfigs)
        {
            return 0;
        }

        glConfig = glConfigs[0];

        if (maxAttribs)
        {
            GLConfigAttribs maximum(maxAttribs);
            GLConfigAttribs best(maxAttribs);
            GLConfigAttribs candidate(maxAttribs);

            best.load(this, glConfig);

            for (config = 1; config < nConfigs; config++)
            {
                candidate.load(this, glConfigs[config]);

                if (candidate > maximum)
                {
                    continue;
                }

                if (candidate > best)
                {
                    glConfig = glConfigs[config];

                    best.load(this, glConfig);
                }
            }
        }

        free(glConfigs);
        return glConfig;
    }

    void EGLSupport::switchMode(void)
    {
        return switchMode(mOriginalMode.first.first,
                          mOriginalMode.first.second, mOriginalMode.second);
    }

    RenderWindow* EGLSupport::createWindow(bool autoCreateWindow,
                                           GLES2RenderSystem* renderSystem,
                                           const String& windowTitle)
    {
        RenderWindow *window = 0;

        if (autoCreateWindow)
        {
            ConfigOptionMap::iterator opt;
            ConfigOptionMap::iterator end = mOptions.end();
            NameValuePairList miscParams;

            bool fullscreen = false;
            uint w = 640, h = 480;

            if ((opt = mOptions.find("Full Screen")) != end)
            {
                fullscreen = (opt->second.currentValue == "Yes");
            }

            if ((opt = mOptions.find("Display Frequency")) != end)
            {
                miscParams["displayFrequency"] = opt->second.currentValue;
            }

            if ((opt = mOptions.find("Video Mode")) != end)
            {
                String val = opt->second.currentValue;
                String::size_type pos = val.find('x');

                if (pos != String::npos)
                {
                    w = StringConverter::parseUnsignedInt(val.substr(0, pos));
                    h = StringConverter::parseUnsignedInt(val.substr(pos + 1));
                }
            }

            if ((opt = mOptions.find("FSAA")) != end)
            {
                miscParams["FSAA"] = opt->second.currentValue;
            }

            window = renderSystem->_createRenderWindow(windowTitle, w, h, fullscreen, &miscParams);
        }

        return window;
    }

    ::EGLContext EGLSupport::createNewContext(EGLDisplay eglDisplay,
					      ::EGLConfig glconfig,
                                              ::EGLContext shareList) const
    {
        EGLint contextAttrs[] = {
            EGL_CONTEXT_CLIENT_VERSION, 2,
            EGL_NONE, EGL_NONE
        };
	::EGLContext context = ((::EGLContext) 0);
	if (eglDisplay == ((EGLDisplay) 0))
	{
		context = eglCreateContext(mGLDisplay, glconfig, shareList, contextAttrs);
        EGL_CHECK_ERROR
	}
	else
	{
		context = eglCreateContext(eglDisplay, glconfig, 0, contextAttrs);
        EGL_CHECK_ERROR
	}

	if (context == ((::EGLContext) 0))
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Fail to create New context",
                        __FUNCTION__);
            return 0;
        }

        return context;
    }

    void EGLSupport::start()
    {
    }

    void EGLSupport::stop()
    {
    }

    void EGLSupport::setGLDisplay( EGLDisplay val )
    {
        mGLDisplay = val;
    }
}
<|endoftext|>


<commit_before>#include "GLBlaat/GL.h"

#include "SliceViewer.h"
#include "SliceViewer.moc"

#include <NQVTK/Interactors/SliceViewInteractor.h>

#include <NQVTK/Math/Vector3.h>

#include <NQVTK/Rendering/SliceRenderer.h>

namespace VFE
{
	// ------------------------------------------------------------------------
	SliceViewer::SliceViewer(QWidget *parent) : NQVTKWidget(parent)
	{
		NQVTK::SliceRenderer *renderer = new NQVTK::SliceRenderer();
		renderer->SetPlane(
			NQVTK::Vector3(-10.0, -10.0, 5.0),
			NQVTK::Vector3(20.0, 0.0, 0.0),
			NQVTK::Vector3(0.0, 20.0, 0.0));
		SetRenderer(renderer);
		SetInteractor(new NQVTK::SliceViewInteractor(renderer));
	}

	// ------------------------------------------------------------------------
	SliceViewer::~SliceViewer()
	{
	}

    // ------------------------------------------------------------------------
	void SliceViewer::initializeGL()
	{
		NQVTK::SliceRenderer *renderer =
			dynamic_cast<NQVTK::SliceRenderer*>(GetRenderer());
		if (!renderer->CreateDefaultShader())
		{
			qDebug("Could not create slice viewer shader!");
		}

		Superclass::initializeGL();
	}
}
<commit_msg>Really fixed slice viewer initialization this time.<commit_after>#include "GLBlaat/GL.h"

#include "SliceViewer.h"
#include "SliceViewer.moc"

#include <NQVTK/Interactors/SliceViewInteractor.h>

#include <NQVTK/Math/Vector3.h>

#include <NQVTK/Rendering/SliceRenderer.h>

namespace VFE
{
	// ------------------------------------------------------------------------
	SliceViewer::SliceViewer(QWidget *parent) : NQVTKWidget(parent)
	{
		NQVTK::SliceRenderer *renderer = new NQVTK::SliceRenderer();
		renderer->SetPlane(
			NQVTK::Vector3(-10.0, -10.0, 5.0),
			NQVTK::Vector3(20.0, 0.0, 0.0),
			NQVTK::Vector3(0.0, 20.0, 0.0));
		SetRenderer(renderer);
		SetInteractor(new NQVTK::SliceViewInteractor(renderer));

		// TODO: create interactor and use crosshair for point selection
		toggleCrosshair(true);
		connect(this, SIGNAL(cursorPosChanged(double, double)),
			this, SLOT(setCrosshairPos(double, double)));
	}

	// ------------------------------------------------------------------------
	SliceViewer::~SliceViewer()
	{
	}

    // ------------------------------------------------------------------------
	void SliceViewer::initializeGL()
	{
		Superclass::initializeGL();

		NQVTK::SliceRenderer *renderer =
			dynamic_cast<NQVTK::SliceRenderer*>(GetRenderer());
		if (!renderer->CreateDefaultShader())
		{
			qDebug("Could not create slice viewer shader!");
		}
	}
}
<|endoftext|>