<commit_before>#include "Hymn.hpp"

#include "Util/FileSystem.hpp"
#include "Manager/Managers.hpp"
#include "Manager/RenderManager.hpp"
#include "Manager/PhysicsManager.hpp"
#include "Manager/ParticleManager.hpp"
#include "Manager/ScriptManager.hpp"
#include "Manager/SoundManager.hpp"
#include "Manager/DebugDrawingManager.hpp"
#include "Manager/ResourceManager.hpp"
#include "DefaultAlbedo.png.hpp"
#include "DefaultNormal.png.hpp"
#include "DefaultMetallic.png.hpp"
#include "DefaultRoughness.png.hpp"
#include "Geometry/Model.hpp"
#include <Video/Texture/Texture2D.hpp>
#include "Texture/TextureAsset.hpp"
#include "Input/Input.hpp"
#include "Script/ScriptFile.hpp"
#include "Util/Json.hpp"
#include <fstream>
#include "Util/Profiling.hpp"

#include "Entity/Entity.hpp"
#include "Component/Animation.hpp"

using namespace std;

ActiveHymn::ActiveHymn() {
    defaultAlbedo = new TextureAsset();
    defaultAlbedo->GetTexture()->Load(DEFAULTALBEDO_PNG, DEFAULTALBEDO_PNG_LENGTH, true);
    defaultNormal = new TextureAsset();
    defaultNormal->GetTexture()->Load(DEFAULTNORMAL_PNG, DEFAULTNORMAL_PNG_LENGTH, false);
    defaultMetallic= new TextureAsset();
    defaultMetallic->GetTexture()->Load(DEFAULTMETALLIC_PNG, DEFAULTMETALLIC_PNG_LENGTH, false);
    defaultRoughness = new TextureAsset();
    defaultRoughness->GetTexture()->Load(DEFAULTROUGHNESS_PNG, DEFAULTROUGHNESS_PNG_LENGTH, false);

    Clear();
}

ActiveHymn& ActiveHymn::GetInstance() {
    static ActiveHymn ActiveHymn;

    return ActiveHymn;
}

void ActiveHymn::Clear() {
    path = "";
    world.Clear();

    entityNumber = 1U;

    filterSettings.color = false;
    filterSettings.fog = false;
    filterSettings.fogDensity = 0.001f;
    filterSettings.fxaa = true;
    filterSettings.glow = true;
    filterSettings.glowBlurAmount = 1;

    for (ScriptFile* script : scripts) {
        Managers().resourceManager->FreeScriptFile(script);
    }
    scripts.clear();
    scriptNumber = 0U;
}

const string& ActiveHymn::GetPath() const {
    return path;
}

void ActiveHymn::SetPath(const string& path) {
    this->path = path;
    FileSystem::CreateDirectory(path.c_str());
    FileSystem::CreateDirectory((path + FileSystem::DELIMITER + "Models").c_str());
    FileSystem::CreateDirectory((path + FileSystem::DELIMITER + "Scenes").c_str());
    FileSystem::CreateDirectory((path + FileSystem::DELIMITER + "Scripts").c_str());
    FileSystem::CreateDirectory((path + FileSystem::DELIMITER + "Sounds").c_str());
    FileSystem::CreateDirectory((path + FileSystem::DELIMITER + "Textures").c_str());
}

void ActiveHymn::Save() const {
    // Save to file.
    ofstream file(path + FileSystem::DELIMITER + "Hymn.json");
    file << ToJson();
    file.close();
}

void ActiveHymn::Load(const string& path) {
    Clear();
    this->path = path;

    // Load Json document from file.
    Json::Value root;
    ifstream file(path + FileSystem::DELIMITER + "Hymn.json");
    file >> root;
    file.close();

    FromJson(root);
}

Json::Value ActiveHymn::ToJson() const {
    Json::Value root;

    Json::Value inputNode;
    inputNode.append(Input::GetInstance().Save());
    root["input"] = inputNode;

    // Filter settings.
    Json::Value filtersNode;
    filtersNode["color"] = filterSettings.color;
    filtersNode["colorColor"] = Json::SaveVec3(filterSettings.colorColor);
    filtersNode["fog"] = filterSettings.fog;
    filtersNode["fogDensity"] = filterSettings.fogDensity;
    filtersNode["fogColor"] = Json::SaveVec3(filterSettings.fogColor);
    filtersNode["fxaa"] = filterSettings.fxaa;
    filtersNode["glow"] = filterSettings.glow;
    filtersNode["glowBlurAmount"] = filterSettings.glowBlurAmount;
    root["filters"] = filtersNode;

    // Save scripts.
    Json::Value scriptNode;
    for (ScriptFile* script : scripts) {
        scriptNode.append(script->name);
    }
    root["scripts"] = scriptNode;

    return root;
}

void ActiveHymn::FromJson(Json::Value root) {
    const Json::Value inputNode = root["input"];
    Input::GetInstance().Load(inputNode[0]);

    // Load filter settings.
    Json::Value filtersNode = root["filters"];
    filterSettings.color = filtersNode["color"].asBool();
    filterSettings.colorColor = Json::LoadVec3(filtersNode["colorColor"]);
    filterSettings.fog = filtersNode["fog"].asBool();
    filterSettings.fogDensity = filtersNode["fogDensity"].asFloat();
    filterSettings.fogColor = Json::LoadVec3(filtersNode["fogColor"]);
    filterSettings.fxaa = filtersNode["fxaa"].asBool();
    filterSettings.glow = filtersNode["glow"].asBool();
    filterSettings.glowBlurAmount = filtersNode["glowBlurAmount"].asInt();

    // Load scripts.
    const Json::Value scriptNode = root["scripts"];
    for (unsigned int i = 0; i < scriptNode.size(); ++i) {
        scripts.push_back(Managers().resourceManager->CreateScriptFile(scriptNode[i].asString()));
    }
    scriptNumber = scripts.size();
}

void ActiveHymn::Update(float deltaTime) {
    { PROFILE("Run scripts.");
        Managers().scriptManager->Update(world, deltaTime);
    }

    { PROFILE("Update physics");
        Managers().physicsManager->Update(deltaTime);
    }

    { PROFILE("Update animations");
        for (Entity* entity : world.GetEntities()) {
            if (entity->IsKilled() || !entity->enabled)
                continue;

            Component::Animation* anim = entity->GetComponent<Component::Animation>();
            if (anim != nullptr) {
                Geometry::Model* model = anim->riggedModel;
                /// @todo Fix animations.
            }
        }
    }

    { PROFILE("Update particles");
        Managers().particleManager->Update(world, deltaTime);
    }

    { PROFILE("Update sounds");
        Managers().soundManager->Update();
    }

    { PROFILE("Update debug drawing");
        Managers().debugDrawingManager->Update(deltaTime);
    }

    { PROFILE("Synchronize transforms");
        Managers().physicsManager->UpdateEntityTransforms();
    }

    { PROFILE("Clear killed entities/components");
        world.ClearKilled();
    }
}

void ActiveHymn::Render(Entity* camera, bool soundSources, bool particleEmitters, bool lightSources, bool cameras) {
    { PROFILE("Render world");
        Managers().renderManager->Render(world, camera);
    }

    if (soundSources || particleEmitters || lightSources || cameras) {
        { PROFILE("Render editor entities");
            Managers().renderManager->RenderEditorEntities(world, camera, soundSources, particleEmitters, lightSources, cameras);
        }
    }

    { PROFILE("Render debug entities");
        CreateGrid(glm::vec2(20.0f, 20.0f));
        Managers().debugDrawingManager->Render(camera);
    }
}

void ActiveHymn::CreateGrid(glm::vec2 gridWidthDepth)
{
    float xStart = -gridWidthDepth.x / 2;
    float xEnd = gridWidthDepth.x / 2;
    float zStart = -gridWidthDepth.y / 2;
    float zEnd = gridWidthDepth.y / 2;

    for (int i = 0; i < 21; i++)
    {
        Managers().debugDrawingManager->AddLine(glm::vec3(xStart, 0.0f, -gridWidthDepth.y/2), glm::vec3(xStart, 0.0f, zEnd), glm::vec3(0.4f, 0.1f, 0.5f), 3.0f);
        Managers().debugDrawingManager->AddLine(glm::vec3(-gridWidthDepth.x/2, 0.0f, zStart), glm::vec3(xEnd, 0.0f, zStart), glm::vec3(0.2f, 0.1f, 0.7f), 3.0f);
        xStart += (gridWidthDepth.x / 2) / 10;
        zStart += (gridWidthDepth.y / 2) / 10;
    }
}

ActiveHymn& Hymn() {
    return ActiveHymn::GetInstance();
}
<commit_msg>create grid<commit_after>#include "Hymn.hpp"

#include "Util/FileSystem.hpp"
#include "Manager/Managers.hpp"
#include "Manager/RenderManager.hpp"
#include "Manager/PhysicsManager.hpp"
#include "Manager/ParticleManager.hpp"
#include "Manager/ScriptManager.hpp"
#include "Manager/SoundManager.hpp"
#include "Manager/DebugDrawingManager.hpp"
#include "Manager/ResourceManager.hpp"
#include "DefaultAlbedo.png.hpp"
#include "DefaultNormal.png.hpp"
#include "DefaultMetallic.png.hpp"
#include "DefaultRoughness.png.hpp"
#include "Geometry/Model.hpp"
#include <Video/Texture/Texture2D.hpp>
#include "Texture/TextureAsset.hpp"
#include "Input/Input.hpp"
#include "Script/ScriptFile.hpp"
#include "Util/Json.hpp"
#include <fstream>
#include "Util/Profiling.hpp"

#include "Entity/Entity.hpp"
#include "Component/Animation.hpp"

using namespace std;

ActiveHymn::ActiveHymn() {
    defaultAlbedo = new TextureAsset();
    defaultAlbedo->GetTexture()->Load(DEFAULTALBEDO_PNG, DEFAULTALBEDO_PNG_LENGTH, true);
    defaultNormal = new TextureAsset();
    defaultNormal->GetTexture()->Load(DEFAULTNORMAL_PNG, DEFAULTNORMAL_PNG_LENGTH, false);
    defaultMetallic= new TextureAsset();
    defaultMetallic->GetTexture()->Load(DEFAULTMETALLIC_PNG, DEFAULTMETALLIC_PNG_LENGTH, false);
    defaultRoughness = new TextureAsset();
    defaultRoughness->GetTexture()->Load(DEFAULTROUGHNESS_PNG, DEFAULTROUGHNESS_PNG_LENGTH, false);

    Clear();
}

ActiveHymn& ActiveHymn::GetInstance() {
    static ActiveHymn ActiveHymn;

    return ActiveHymn;
}

void ActiveHymn::Clear() {
    path = "";
    world.Clear();

    entityNumber = 1U;

    filterSettings.color = false;
    filterSettings.fog = false;
    filterSettings.fogDensity = 0.001f;
    filterSettings.fxaa = true;
    filterSettings.glow = true;
    filterSettings.glowBlurAmount = 1;

    for (ScriptFile* script : scripts) {
        Managers().resourceManager->FreeScriptFile(script);
    }
    scripts.clear();
    scriptNumber = 0U;
}

const string& ActiveHymn::GetPath() const {
    return path;
}

void ActiveHymn::SetPath(const string& path) {
    this->path = path;
    FileSystem::CreateDirectory(path.c_str());
    FileSystem::CreateDirectory((path + FileSystem::DELIMITER + "Models").c_str());
    FileSystem::CreateDirectory((path + FileSystem::DELIMITER + "Scenes").c_str());
    FileSystem::CreateDirectory((path + FileSystem::DELIMITER + "Scripts").c_str());
    FileSystem::CreateDirectory((path + FileSystem::DELIMITER + "Sounds").c_str());
    FileSystem::CreateDirectory((path + FileSystem::DELIMITER + "Textures").c_str());
}

void ActiveHymn::Save() const {
    // Save to file.
    ofstream file(path + FileSystem::DELIMITER + "Hymn.json");
    file << ToJson();
    file.close();
}

void ActiveHymn::Load(const string& path) {
    Clear();
    this->path = path;

    // Load Json document from file.
    Json::Value root;
    ifstream file(path + FileSystem::DELIMITER + "Hymn.json");
    file >> root;
    file.close();

    FromJson(root);
}

Json::Value ActiveHymn::ToJson() const {
    Json::Value root;

    Json::Value inputNode;
    inputNode.append(Input::GetInstance().Save());
    root["input"] = inputNode;

    // Filter settings.
    Json::Value filtersNode;
    filtersNode["color"] = filterSettings.color;
    filtersNode["colorColor"] = Json::SaveVec3(filterSettings.colorColor);
    filtersNode["fog"] = filterSettings.fog;
    filtersNode["fogDensity"] = filterSettings.fogDensity;
    filtersNode["fogColor"] = Json::SaveVec3(filterSettings.fogColor);
    filtersNode["fxaa"] = filterSettings.fxaa;
    filtersNode["glow"] = filterSettings.glow;
    filtersNode["glowBlurAmount"] = filterSettings.glowBlurAmount;
    root["filters"] = filtersNode;

    // Save scripts.
    Json::Value scriptNode;
    for (ScriptFile* script : scripts) {
        scriptNode.append(script->name);
    }
    root["scripts"] = scriptNode;

    return root;
}

void ActiveHymn::FromJson(Json::Value root) {
    const Json::Value inputNode = root["input"];
    Input::GetInstance().Load(inputNode[0]);

    // Load filter settings.
    Json::Value filtersNode = root["filters"];
    filterSettings.color = filtersNode["color"].asBool();
    filterSettings.colorColor = Json::LoadVec3(filtersNode["colorColor"]);
    filterSettings.fog = filtersNode["fog"].asBool();
    filterSettings.fogDensity = filtersNode["fogDensity"].asFloat();
    filterSettings.fogColor = Json::LoadVec3(filtersNode["fogColor"]);
    filterSettings.fxaa = filtersNode["fxaa"].asBool();
    filterSettings.glow = filtersNode["glow"].asBool();
    filterSettings.glowBlurAmount = filtersNode["glowBlurAmount"].asInt();

    // Load scripts.
    const Json::Value scriptNode = root["scripts"];
    for (unsigned int i = 0; i < scriptNode.size(); ++i) {
        scripts.push_back(Managers().resourceManager->CreateScriptFile(scriptNode[i].asString()));
    }
    scriptNumber = scripts.size();
}

void ActiveHymn::Update(float deltaTime) {
    { PROFILE("Run scripts.");
        Managers().scriptManager->Update(world, deltaTime);
    }

    { PROFILE("Update physics");
        Managers().physicsManager->Update(deltaTime);
    }

    { PROFILE("Update animations");
        for (Entity* entity : world.GetEntities()) {
            if (entity->IsKilled() || !entity->enabled)
                continue;

            Component::Animation* anim = entity->GetComponent<Component::Animation>();
            if (anim != nullptr) {
                Geometry::Model* model = anim->riggedModel;
                /// @todo Fix animations.
            }
        }
    }

    { PROFILE("Update particles");
        Managers().particleManager->Update(world, deltaTime);
    }

    { PROFILE("Update sounds");
        Managers().soundManager->Update();
    }

    { PROFILE("Update debug drawing");
        Managers().debugDrawingManager->Update(deltaTime);
    }

    { PROFILE("Synchronize transforms");
        Managers().physicsManager->UpdateEntityTransforms();
    }

    { PROFILE("Clear killed entities/components");
        world.ClearKilled();
    }
}

void ActiveHymn::Render(Entity* camera, bool soundSources, bool particleEmitters, bool lightSources, bool cameras) {
    { PROFILE("Render world");
        Managers().renderManager->Render(world, camera);
    }

    if (soundSources || particleEmitters || lightSources || cameras) {
        { PROFILE("Render editor entities");
            Managers().renderManager->RenderEditorEntities(world, camera, soundSources, particleEmitters, lightSources, cameras);
        }
    }

    { PROFILE("Render debug entities");
        CreateGrid(glm::vec2(70.0f, 70.0f));
        Managers().debugDrawingManager->Render(camera);
    }
}

void ActiveHymn::CreateGrid(glm::vec2 gridWidthDepth)
{
    float xStart = -gridWidthDepth.x / 2;
    float xEnd = gridWidthDepth.x / 2;
    float zStart = -gridWidthDepth.y / 2;
    float zEnd = gridWidthDepth.y / 2;

    for (int i = 0; i < 21; i++)
    {
        Managers().debugDrawingManager->AddLine(glm::vec3(xStart, 0.0f, -gridWidthDepth.y/2), glm::vec3(xStart, 0.0f, zEnd), glm::vec3(0.1f, 0.1f, 0.5f), 3.0f);
        Managers().debugDrawingManager->AddLine(glm::vec3(-gridWidthDepth.x/2, 0.0f, zStart), glm::vec3(xEnd, 0.0f, zStart), glm::vec3(0.5f, 0.1f, 0.1f), 3.0f);
        xStart += (gridWidthDepth.x / 2) / 10;
        zStart += (gridWidthDepth.y / 2) / 10;
    }
}

ActiveHymn& Hymn() {
    return ActiveHymn::GetInstance();
}
<|endoftext|>


<commit_before>#include "AliAnalysisTaskJetQ.h"

AliAnalysisTaskJetQ::AliAnalysisTaskJetQ():
 AliAnalysisTaskSE(),
 fAOD(0),
 fMCEvent(0),
 fPoolMgr(0),
 fPoolTrackArray(0),
 fTriggerType(AliVEvent::kINT7),
 fOutList(0),
 fCentAxis(0),
 fVzAxis(0),
 fPtAxis(0),
 fNormCounter(0),
 fCorrPlot(0),
 fMixCorrPlot(0),
 fNtriggers(0),
 fPtAssocMin(2.),
 fPtAssocMax(2.5),
 fPtTriggMin(6.),
 fPtTriggMax(8.)
{}
//_____________________________________________________________________________
AliAnalysisTaskJetQ::AliAnalysisTaskJetQ(const char* name):
 AliAnalysisTaskSE(name),
 fAOD(0),
 fMCEvent(0),
 fPoolMgr(0),
 fPoolTrackArray(0),
 fTriggerType(AliVEvent::kINT7),
 fOutList(0),
 fCentAxis(0),
 fVzAxis(0),
 fPtAxis(0),
 fNormCounter(0),
 fCorrPlot(0),
 fMixCorrPlot(0),
 fNtriggers(0),
 fPtAssocMin(2.),
 fPtAssocMax(2.5),
 fPtTriggMin(6.),
 fPtTriggMax(8.)
{
    DefineOutput(1, TList::Class());
}
//_____________________________________________________________________________
AliAnalysisTaskJetQ::~AliAnalysisTaskJetQ()
{
  delete fPoolTrackArray;
}
//_____________________________________________________________________________
void AliAnalysisTaskJetQ::UserCreateOutputObjects()
{
    OpenFile(1);
    //Setting up variables
    if(fCentBins.size()<2) {
      Double_t tempCentBins[] = {0,100};
      SetCentralityBins(1,tempCentBins);
    };
    if(fVzBins.size()<2) {
      Double_t vzs[]   = {-10.,10.};
      SetVtxZBins(1,vzs);
    };
    if(fPtBins.size()<2) {
      Double_t ptbs[] = {2.,2.5};
      SetPtBins(1,ptbs);
    };
    fPtAssocMin = fPtAxis->GetBinLowEdge(1);
    fPtAssocMax = fPtAxis->GetBinUpEdge(fPtAxis->GetNbins());
    fPtDif = fPtBins.size()>2; //if only one pT bin, then assoc is not pt-dif. and use TH2 instead of TH3
    if(!fEvMixPars[0]) SetEventMixingCapacity(30,5000,10,10);
    //Setting up the pool manager
    // Double_t cents[] = {0.,50.,70.};
    fPoolMgr = new AliEventPoolManager(fEvMixPars[0], fEvMixPars[1], fCentBins.size()-1, fCentBins.data(), fVzBins.size()-1, fVzBins.data());
      //fNCentBins,fCentBins.data(), fNzVtxBins, fzVtxBins.data());
    if (!fPoolMgr) { AliError("Event Pool manager not created!"); return; }
    fPoolMgr->SetTargetValues(fEvMixPars[1], fEvMixPars[2]*0.01, fEvMixPars[3]);
    fPoolTrackArray = new TObjArray();
    fPoolTrackArray->SetOwner(kTRUE);
    // creating output lists
    fOutList = new TList();
    fOutList->SetOwner(kTRUE);
    TH1D *vtzBefore = new TH1D("vtzBefore","vtzBefore",20,-10,10);
    TH1D *vtzAfter  = new TH1D("vtzAfter","vtzAfter",20,-10,10);
    fNormCounter    = new TH2D("NormCounter","NormCounter; multi/cent; index",fCentBins.size()-1, fCentBins.data(), 4, -0.5, 3.5);
    fOutList->Add(vtzBefore);
    fOutList->Add(vtzAfter);
    fOutList->Add(fNormCounter);
    //Setting up correlation plots
    fCorrPlot    = new TH1**[fCentAxis->GetNbins()];
    fMixCorrPlot = new TH1**[fCentAxis->GetNbins()];
    fNtriggers   = new TH1*[fCentAxis->GetNbins()];
    for(Int_t iCent=0;iCent<fCentAxis->GetNbins();iCent++) {
      fCorrPlot[iCent] = new TH1*[fPtAxis->GetNbins()];
      fMixCorrPlot[iCent] = new TH1*[fPtAxis->GetNbins()];
      for(Int_t iPt=0;iPt<fPtAxis->GetNbins();iPt++) {
        fCorrPlot[iCent][iPt]       = new TH3D(Form("fCorr_Cent%i_Pt%i",iCent,iPt),Form("fCorr_Cent%i_Pt%i; #Delta#phi (rad); #Delta#eta; z_{vtx}",iCent,iPt),100,-C_PI_HALF,C_PI_TH,200, -1.6, 1.6,fVzBins.size()-1,-10,10);
        fMixCorrPlot[iCent][iPt]    = new TH3D(Form("fMixCorr_Cent%i_Pt%i",iCent,iPt),Form("fMixCorr_Cent%i_Pt%i; #Delta#phi (rad); #Delta#eta; z_{vtx}",iCent,iPt),100,-C_PI_HALF,C_PI_TH,200, -1.6, 1.6,fVzBins.size()-1,-10,10);
        fCorrPlot[iCent][iPt]->GetZaxis()->Set(fVzBins.size()-1,fVzBins.data());
        fMixCorrPlot[iCent][iPt]->GetZaxis()->Set(fVzBins.size()-1,fVzBins.data());
        fOutList->Add(fCorrPlot[iCent][iPt]);
        fOutList->Add(fMixCorrPlot[iCent][iPt]);
      };
      fNtriggers[iCent]    = new TH1D(Form("fNtriggers_Cent%i",iCent),Form("fNtriggers_Cent%i; v_{z}; dN_{trig}/dv_{z}",iCent),fVzBins.size()-1,-10,10);
      fNtriggers[iCent]->GetZaxis()->Set(fVzBins.size()-1,fVzBins.data());
      fOutList->Add(fNtriggers[iCent]);

    };
    PostData(1, fOutList);
}
//_____________________________________________________________________________
void AliAnalysisTaskJetQ::UserExec(Option_t *)
{
  Bool_t fIsMC = kFALSE;
  fAOD = dynamic_cast<AliAODEvent*>(InputEvent());
  if(!fAOD) return;
  if(fIsMC) {
    fMCEvent = dynamic_cast<AliMCEvent *>(MCEvent());
    if (!fMCEvent) return;
  }
  Double_t vz = fAOD->GetPrimaryVertex()->GetZ();
  AliMultSelection *lMultSel = (AliMultSelection*)fInputEvent->FindListObject("MultSelection");
  Double_t l_Cent = lMultSel->GetMultiplicityPercentile("V0M");
  if(!CheckTrigger(l_Cent)) return;
  Double_t vtxXYZ[] = {0.,0.,0.};
  if(!AcceptAOD(fAOD, vtxXYZ)) return;
  // Double_t vz = fAOD->GetPrimaryVertex()->GetZ();
  ((TH1D*)fOutList->At(0))->Fill(vz);
  Int_t ind = FindGivenPt(fPtTriggMin,fPtTriggMax);
  if(ind<0) return;
  Int_t i_Cent = fCentAxis->FindBin(l_Cent);
  Int_t i_vz   = fVzAxis->FindBin(vz);
  if(!i_Cent || i_Cent>fCentAxis->GetNbins()) return; //out of centrality/vz range
  if(!i_vz || i_vz>fVzAxis->GetNbins()) return; //out of centrality/vz range
  ((TH1D*)fOutList->At(1))->Fill(vz);

  fNormCounter->Fill(l_Cent,0); //Number of triggers
  Int_t nPairs = FillCorrelations(ind,i_Cent,vz);
  AliEventPool *pool = fPoolMgr->GetEventPool(i_Cent-1, i_vz-1);
  if(!pool) { printf("Could not find the event pool!\n"); return; };
  // printf("Current numbe of events in pool: %i\n",pool->GetCurrentNEvents());
  if(pool->IsReady()) { Int_t nMixPairs = FillMixedEvent(ind, pool, i_Cent, vz);  };
  pool->UpdatePool((TObjArray*)fPoolTrackArray->Clone());
  fPoolTrackArray->Clear();
  PostData(1, fOutList);
}
//_____________________________________________________________________________
void AliAnalysisTaskJetQ::Terminate(Option_t *)
{}
//_____________________________________________________________________________

Bool_t AliAnalysisTaskJetQ::CheckTrigger(Double_t l_Cent) {
  UInt_t fSelMask = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected();
  //Apparently, MB trigger can also mark special triggers, leaving depleted regions in multi. To avoid this, pass true, if MB has been triggered.
  //This would fail if spec. triggers would also flag MB trigger, which seems to NOT be the case.
  if(!(fTriggerType&fSelMask)) { return kFALSE; }; //printf("Returning from the generic check\n");
  if(fSelMask&(fTriggerType&(AliVEvent::kINT7+AliVEvent::kMB))) {return kTRUE; }; //printf("Passed by MB trigger!\n");
  if((fSelMask&fTriggerType&AliVEvent::kCentral) && l_Cent>10) {return kFALSE; }; //printf("Returnning from kCent case\n");
  if((fSelMask&fTriggerType&AliVEvent::kSemiCentral) && (l_Cent<30 || l_Cent>50)) {return kFALSE; }; //printf("Returning from kSC case\n");
  return kTRUE;
}
Bool_t AliAnalysisTaskJetQ::AcceptAOD(AliAODEvent *inEv, Double_t *lvtxXYZ) {
  if(!fEventCuts.AcceptEvent(inEv)) return 0;
  const AliAODVertex* vtx = dynamic_cast<const AliAODVertex*>(inEv->GetPrimaryVertex());
  if(!vtx || vtx->GetNContributors() < 1)
    return kFALSE;
  const AliAODVertex* vtxSPD = dynamic_cast<const AliAODVertex*>(inEv->GetPrimaryVertexSPD());
  Double_t dMaxResol = 0.25; // suggested from DPG
  Double_t cov[6] = {0};
  vtxSPD->GetCovarianceMatrix(cov);
  Double_t zRes = TMath::Sqrt(cov[5]);
  if ( vtxSPD->IsFromVertexerZ() && (zRes > dMaxResol)) return kFALSE;
  const Double_t aodVtxZ = vtx->GetZ();
  if(TMath::Abs(aodVtxZ) > 10)
    return kFALSE;
  vtx->GetXYZ(lvtxXYZ);
  return kTRUE;
};
Int_t AliAnalysisTaskJetQ::FindGivenPt(const Double_t &ptMin, const Double_t &ptMax) {
  Int_t ind=-1;
  AliAODTrack *lTrack;
  Double_t lPtMax=0;
  Double_t lPtCur=0;
  for(Int_t i=0;i<fAOD->GetNumberOfTracks();i++) {
    lTrack = (AliAODTrack*)fAOD->GetTrack(i);
    if(!lTrack->TestFilterBit(768)) continue;
    lPtCur = lTrack->Pt();
    if(lPtCur > ptMin && lPtCur < ptMax && lPtCur > lPtMax) { lPtMax=lPtCur; ind=i;  };
  };
  return ind;
}
Int_t AliAnalysisTaskJetQ::FillCorrelations(Int_t &triggerIndex, Int_t &centVal, Double_t &vzValue) {
  Int_t nPairs=0;
  AliAODTrack *lTrack;
  AliAODTrack *lTriggerTrack = (AliAODTrack*)fAOD->GetTrack(triggerIndex);
  Double_t l_TrEta = lTriggerTrack->Eta();
  Double_t l_TrPhi = lTriggerTrack->Phi();
  Int_t centBin = centVal-1;
  fNtriggers[centBin]->Fill(vzValue);
  //Fetch pT trigger & make sure we are not in the same pT bin below
  lTrack = (AliAODTrack*)fAOD->GetTrack(triggerIndex);
  Int_t trigBin = fPtAxis->FindBin(lTrack->Pt());
  for(Int_t i=0;i<fAOD->GetNumberOfTracks();i++) {
    lTrack = (AliAODTrack*)fAOD->GetTrack(i);
    if(!lTrack->TestFilterBit(768)) continue;
    Int_t ptInd = fPtAxis->FindBin(lTrack->Pt());
    if(!ptInd || ptInd>fPtAxis->GetNbins() || ptInd == trigBin) continue;
    ptInd--;
    Double_t d_Eta = l_TrEta-lTrack->Eta();
    Double_t d_Phi = l_TrPhi-lTrack->Phi();
    fixPhi(d_Phi);
    // printf("Attempting to fill a track with %f %f %f (%s)\n",d_Phi,d_Eta,lPt,fPtDif);
    fill3DHist(fCorrPlot[centBin][ptInd],d_Phi,d_Eta,vzValue);
    nPairs++;
    fPoolTrackArray->Add(new AliBasicParticle(lTrack->Eta(),lTrack->Phi(),lTrack->Pt(), lTrack->Charge()));
  };
  return nPairs;
};
Int_t AliAnalysisTaskJetQ::FillMixedEvent(Int_t &triggerIndex, AliEventPool *l_pool, Int_t &centVal, Double_t &vzValue) {
  Int_t nPairs=0;
  AliAODTrack *lTrack;
  AliAODTrack *lTriggerTrack = (AliAODTrack*)fAOD->GetTrack(triggerIndex);
  Double_t l_TrEta = lTriggerTrack->Eta();
  Double_t l_TrPhi = lTriggerTrack->Phi();
  Double_t l_AsEta;
  Double_t l_AsPhi;
  Double_t l_AsPt;
  TObjArray *mixTracks;
  Int_t centInd = centVal-1;
  //Fetch pT trigger & make sure we are not in the same pT bin below
  lTrack = (AliAODTrack*)fAOD->GetTrack(triggerIndex);
  Int_t trigBin = fPtAxis->FindBin(lTrack->Pt());
  for(Int_t i=0;i<l_pool->GetCurrentNEvents();i++) {
    mixTracks = l_pool->GetEvent(i);
    TObjArrayIter *myIt = new TObjArrayIter(mixTracks);
    while(AliBasicParticle *rTr = (AliBasicParticle*)myIt->Next()) {
      Int_t ptInd = fPtAxis->FindBin(rTr->Pt());
      if(!ptInd || ptInd>fPtAxis->GetNbins() || ptInd==trigBin) continue;
      ptInd-=1;
      l_AsEta = l_TrEta - rTr->Eta();
      l_AsPhi = l_TrPhi - rTr->Phi();
      fixPhi(l_AsPhi);
      fill3DHist(fMixCorrPlot[centInd][ptInd],l_AsPhi,l_AsEta,vzValue);
      nPairs++;
    };
  };
  return nPairs;
};
<commit_msg>AnalysisTaskJetQ: adding to extra TH1Ds to store pt and centrlity bins for further convenience<commit_after>#include "AliAnalysisTaskJetQ.h"

AliAnalysisTaskJetQ::AliAnalysisTaskJetQ():
 AliAnalysisTaskSE(),
 fAOD(0),
 fMCEvent(0),
 fPoolMgr(0),
 fPoolTrackArray(0),
 fTriggerType(AliVEvent::kINT7),
 fOutList(0),
 fCentAxis(0),
 fVzAxis(0),
 fPtAxis(0),
 fNormCounter(0),
 fCorrPlot(0),
 fMixCorrPlot(0),
 fNtriggers(0),
 fPtAssocMin(2.),
 fPtAssocMax(2.5),
 fPtTriggMin(6.),
 fPtTriggMax(8.)
{}
//_____________________________________________________________________________
AliAnalysisTaskJetQ::AliAnalysisTaskJetQ(const char* name):
 AliAnalysisTaskSE(name),
 fAOD(0),
 fMCEvent(0),
 fPoolMgr(0),
 fPoolTrackArray(0),
 fTriggerType(AliVEvent::kINT7),
 fOutList(0),
 fCentAxis(0),
 fVzAxis(0),
 fPtAxis(0),
 fNormCounter(0),
 fCorrPlot(0),
 fMixCorrPlot(0),
 fNtriggers(0),
 fPtAssocMin(2.),
 fPtAssocMax(2.5),
 fPtTriggMin(6.),
 fPtTriggMax(8.)
{
    DefineOutput(1, TList::Class());
}
//_____________________________________________________________________________
AliAnalysisTaskJetQ::~AliAnalysisTaskJetQ()
{
  delete fPoolTrackArray;
}
//_____________________________________________________________________________
void AliAnalysisTaskJetQ::UserCreateOutputObjects()
{
    OpenFile(1);
    //Setting up variables
    if(fCentBins.size()<2) {
      Double_t tempCentBins[] = {0,100};
      SetCentralityBins(1,tempCentBins);
    };
    if(fVzBins.size()<2) {
      Double_t vzs[]   = {-10.,10.};
      SetVtxZBins(1,vzs);
    };
    if(fPtBins.size()<2) {
      Double_t ptbs[] = {2.,2.5};
      SetPtBins(1,ptbs);
    };
    fPtAssocMin = fPtAxis->GetBinLowEdge(1);
    fPtAssocMax = fPtAxis->GetBinUpEdge(fPtAxis->GetNbins());
    fPtDif = fPtBins.size()>2; //if only one pT bin, then assoc is not pt-dif. and use TH2 instead of TH3
    if(!fEvMixPars[0]) SetEventMixingCapacity(30,5000,10,10);
    //Setting up the pool manager
    // Double_t cents[] = {0.,50.,70.};
    fPoolMgr = new AliEventPoolManager(fEvMixPars[0], fEvMixPars[1], fCentBins.size()-1, fCentBins.data(), fVzBins.size()-1, fVzBins.data());
      //fNCentBins,fCentBins.data(), fNzVtxBins, fzVtxBins.data());
    if (!fPoolMgr) { AliError("Event Pool manager not created!"); return; }
    fPoolMgr->SetTargetValues(fEvMixPars[1], fEvMixPars[2]*0.01, fEvMixPars[3]);
    fPoolTrackArray = new TObjArray();
    fPoolTrackArray->SetOwner(kTRUE);
    // creating output lists
    fOutList = new TList();
    fOutList->SetOwner(kTRUE);
    TH1 *l_ptBins = new TH1D("ptBins","ptBins",fPtBins.size()-1,fPtBins.data());
    TH1 *l_centBins = new TH1D("centBins","centBins",fCentBins.size()-1,fCentBins.data());
    TH1D *vtzBefore = new TH1D("vtzBefore","vtzBefore",20,-10,10);
    TH1D *vtzAfter  = new TH1D("vtzAfter","vtzAfter",20,-10,10);
    fNormCounter    = new TH2D("NormCounter","NormCounter; multi/cent; index",fCentBins.size()-1, fCentBins.data(), 4, -0.5, 3.5);
    fOutList->Add(vtzBefore);
    fOutList->Add(vtzAfter);
    fOutList->Add(fNormCounter);
    fOutList->Add(l_ptBins);
    fOutList->Add(l_centBins);
    //Setting up correlation plots
    fCorrPlot    = new TH1**[fCentAxis->GetNbins()];
    fMixCorrPlot = new TH1**[fCentAxis->GetNbins()];
    fNtriggers   = new TH1*[fCentAxis->GetNbins()];
    for(Int_t iCent=0;iCent<fCentAxis->GetNbins();iCent++) {
      fCorrPlot[iCent] = new TH1*[fPtAxis->GetNbins()];
      fMixCorrPlot[iCent] = new TH1*[fPtAxis->GetNbins()];
      for(Int_t iPt=0;iPt<fPtAxis->GetNbins();iPt++) {
        fCorrPlot[iCent][iPt]       = new TH3D(Form("fCorr_Cent%i_Pt%i",iCent,iPt),Form("fCorr_Cent%i_Pt%i; #Delta#phi (rad); #Delta#eta; z_{vtx}",iCent,iPt),100,-C_PI_HALF,C_PI_TH,200, -1.6, 1.6,fVzBins.size()-1,-10,10);
        fMixCorrPlot[iCent][iPt]    = new TH3D(Form("fMixCorr_Cent%i_Pt%i",iCent,iPt),Form("fMixCorr_Cent%i_Pt%i; #Delta#phi (rad); #Delta#eta; z_{vtx}",iCent,iPt),100,-C_PI_HALF,C_PI_TH,200, -1.6, 1.6,fVzBins.size()-1,-10,10);
        fCorrPlot[iCent][iPt]->GetZaxis()->Set(fVzBins.size()-1,fVzBins.data());
        fMixCorrPlot[iCent][iPt]->GetZaxis()->Set(fVzBins.size()-1,fVzBins.data());
        fOutList->Add(fCorrPlot[iCent][iPt]);
        fOutList->Add(fMixCorrPlot[iCent][iPt]);
      };
      fNtriggers[iCent]    = new TH1D(Form("fNtriggers_Cent%i",iCent),Form("fNtriggers_Cent%i; v_{z}; dN_{trig}/dv_{z}",iCent),fVzBins.size()-1,-10,10);
      fNtriggers[iCent]->GetZaxis()->Set(fVzBins.size()-1,fVzBins.data());
      fOutList->Add(fNtriggers[iCent]);

    };
    PostData(1, fOutList);
}
//_____________________________________________________________________________
void AliAnalysisTaskJetQ::UserExec(Option_t *)
{
  Bool_t fIsMC = kFALSE;
  fAOD = dynamic_cast<AliAODEvent*>(InputEvent());
  if(!fAOD) return;
  if(fIsMC) {
    fMCEvent = dynamic_cast<AliMCEvent *>(MCEvent());
    if (!fMCEvent) return;
  }
  Double_t vz = fAOD->GetPrimaryVertex()->GetZ();
  AliMultSelection *lMultSel = (AliMultSelection*)fInputEvent->FindListObject("MultSelection");
  Double_t l_Cent = lMultSel->GetMultiplicityPercentile("V0M");
  if(!CheckTrigger(l_Cent)) return;
  Double_t vtxXYZ[] = {0.,0.,0.};
  if(!AcceptAOD(fAOD, vtxXYZ)) return;
  // Double_t vz = fAOD->GetPrimaryVertex()->GetZ();
  ((TH1D*)fOutList->At(0))->Fill(vz);
  Int_t ind = FindGivenPt(fPtTriggMin,fPtTriggMax);
  if(ind<0) return;
  Int_t i_Cent = fCentAxis->FindBin(l_Cent);
  Int_t i_vz   = fVzAxis->FindBin(vz);
  if(!i_Cent || i_Cent>fCentAxis->GetNbins()) return; //out of centrality/vz range
  if(!i_vz || i_vz>fVzAxis->GetNbins()) return; //out of centrality/vz range
  ((TH1D*)fOutList->At(1))->Fill(vz);

  fNormCounter->Fill(l_Cent,0); //Number of triggers
  Int_t nPairs = FillCorrelations(ind,i_Cent,vz);
  AliEventPool *pool = fPoolMgr->GetEventPool(i_Cent-1, i_vz-1);
  if(!pool) { printf("Could not find the event pool!\n"); return; };
  // printf("Current numbe of events in pool: %i\n",pool->GetCurrentNEvents());
  if(pool->IsReady()) { Int_t nMixPairs = FillMixedEvent(ind, pool, i_Cent, vz);  };
  pool->UpdatePool((TObjArray*)fPoolTrackArray->Clone());
  fPoolTrackArray->Clear();
  PostData(1, fOutList);
}
//_____________________________________________________________________________
void AliAnalysisTaskJetQ::Terminate(Option_t *)
{}
//_____________________________________________________________________________

Bool_t AliAnalysisTaskJetQ::CheckTrigger(Double_t l_Cent) {
  UInt_t fSelMask = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected();
  //Apparently, MB trigger can also mark special triggers, leaving depleted regions in multi. To avoid this, pass true, if MB has been triggered.
  //This would fail if spec. triggers would also flag MB trigger, which seems to NOT be the case.
  if(!(fTriggerType&fSelMask)) { return kFALSE; }; //printf("Returning from the generic check\n");
  if(fSelMask&(fTriggerType&(AliVEvent::kINT7+AliVEvent::kMB))) {return kTRUE; }; //printf("Passed by MB trigger!\n");
  if((fSelMask&fTriggerType&AliVEvent::kCentral) && l_Cent>10) {return kFALSE; }; //printf("Returnning from kCent case\n");
  if((fSelMask&fTriggerType&AliVEvent::kSemiCentral) && (l_Cent<30 || l_Cent>50)) {return kFALSE; }; //printf("Returning from kSC case\n");
  return kTRUE;
}
Bool_t AliAnalysisTaskJetQ::AcceptAOD(AliAODEvent *inEv, Double_t *lvtxXYZ) {
  if(!fEventCuts.AcceptEvent(inEv)) return 0;
  const AliAODVertex* vtx = dynamic_cast<const AliAODVertex*>(inEv->GetPrimaryVertex());
  if(!vtx || vtx->GetNContributors() < 1)
    return kFALSE;
  const AliAODVertex* vtxSPD = dynamic_cast<const AliAODVertex*>(inEv->GetPrimaryVertexSPD());
  Double_t dMaxResol = 0.25; // suggested from DPG
  Double_t cov[6] = {0};
  vtxSPD->GetCovarianceMatrix(cov);
  Double_t zRes = TMath::Sqrt(cov[5]);
  if ( vtxSPD->IsFromVertexerZ() && (zRes > dMaxResol)) return kFALSE;
  const Double_t aodVtxZ = vtx->GetZ();
  if(TMath::Abs(aodVtxZ) > 10)
    return kFALSE;
  vtx->GetXYZ(lvtxXYZ);
  return kTRUE;
};
Int_t AliAnalysisTaskJetQ::FindGivenPt(const Double_t &ptMin, const Double_t &ptMax) {
  Int_t ind=-1;
  AliAODTrack *lTrack;
  Double_t lPtMax=0;
  Double_t lPtCur=0;
  for(Int_t i=0;i<fAOD->GetNumberOfTracks();i++) {
    lTrack = (AliAODTrack*)fAOD->GetTrack(i);
    if(!lTrack->TestFilterBit(768)) continue;
    lPtCur = lTrack->Pt();
    if(lPtCur > ptMin && lPtCur < ptMax && lPtCur > lPtMax) { lPtMax=lPtCur; ind=i;  };
  };
  return ind;
}
Int_t AliAnalysisTaskJetQ::FillCorrelations(Int_t &triggerIndex, Int_t &centVal, Double_t &vzValue) {
  Int_t nPairs=0;
  AliAODTrack *lTrack;
  AliAODTrack *lTriggerTrack = (AliAODTrack*)fAOD->GetTrack(triggerIndex);
  Double_t l_TrEta = lTriggerTrack->Eta();
  Double_t l_TrPhi = lTriggerTrack->Phi();
  Int_t centBin = centVal-1;
  fNtriggers[centBin]->Fill(vzValue);
  //Fetch pT trigger & make sure we are not in the same pT bin below
  lTrack = (AliAODTrack*)fAOD->GetTrack(triggerIndex);
  Int_t trigBin = fPtAxis->FindBin(lTrack->Pt());
  for(Int_t i=0;i<fAOD->GetNumberOfTracks();i++) {
    lTrack = (AliAODTrack*)fAOD->GetTrack(i);
    if(!lTrack->TestFilterBit(768)) continue;
    Int_t ptInd = fPtAxis->FindBin(lTrack->Pt());
    if(!ptInd || ptInd>fPtAxis->GetNbins() || ptInd == trigBin) continue;
    ptInd--;
    Double_t d_Eta = l_TrEta-lTrack->Eta();
    Double_t d_Phi = l_TrPhi-lTrack->Phi();
    fixPhi(d_Phi);
    // printf("Attempting to fill a track with %f %f %f (%s)\n",d_Phi,d_Eta,lPt,fPtDif);
    fill3DHist(fCorrPlot[centBin][ptInd],d_Phi,d_Eta,vzValue);
    nPairs++;
    fPoolTrackArray->Add(new AliBasicParticle(lTrack->Eta(),lTrack->Phi(),lTrack->Pt(), lTrack->Charge()));
  };
  return nPairs;
};
Int_t AliAnalysisTaskJetQ::FillMixedEvent(Int_t &triggerIndex, AliEventPool *l_pool, Int_t &centVal, Double_t &vzValue) {
  Int_t nPairs=0;
  AliAODTrack *lTrack;
  AliAODTrack *lTriggerTrack = (AliAODTrack*)fAOD->GetTrack(triggerIndex);
  Double_t l_TrEta = lTriggerTrack->Eta();
  Double_t l_TrPhi = lTriggerTrack->Phi();
  Double_t l_AsEta;
  Double_t l_AsPhi;
  Double_t l_AsPt;
  TObjArray *mixTracks;
  Int_t centInd = centVal-1;
  //Fetch pT trigger & make sure we are not in the same pT bin below
  lTrack = (AliAODTrack*)fAOD->GetTrack(triggerIndex);
  Int_t trigBin = fPtAxis->FindBin(lTrack->Pt());
  for(Int_t i=0;i<l_pool->GetCurrentNEvents();i++) {
    mixTracks = l_pool->GetEvent(i);
    TObjArrayIter *myIt = new TObjArrayIter(mixTracks);
    while(AliBasicParticle *rTr = (AliBasicParticle*)myIt->Next()) {
      Int_t ptInd = fPtAxis->FindBin(rTr->Pt());
      if(!ptInd || ptInd>fPtAxis->GetNbins() || ptInd==trigBin) continue;
      ptInd-=1;
      l_AsEta = l_TrEta - rTr->Eta();
      l_AsPhi = l_TrPhi - rTr->Phi();
      fixPhi(l_AsPhi);
      fill3DHist(fMixCorrPlot[centInd][ptInd],l_AsPhi,l_AsEta,vzValue);
      nPairs++;
    };
  };
  return nPairs;
};
<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "MenuManager.h"
#include "Common/AnchorLayoutManager.h"
#include "UiProxyWidget.h"
#include "ActionNode.h"
#include "GroupNode.h"

#include <QSequentialAnimationGroup>
#include <QPropertyAnimation>
#include <QTimer>
#include <QUuid>
#include <QDebug>

#include "MemoryLeakCheck.h"

namespace CoreUi
{
    QString MenuManager::defaultItemIcon = "./data/ui/images/menus/edbutton_MATWIZ_normal.png";
    QString MenuManager::defaultGroupIcon = "./data/ui/images/menus/edbutton_WRLDTOOLS_icon.png";

    MenuManager::MenuManager(QObject *parent, CoreUi::AnchorLayoutManager *layout_manager) :
            QObject(parent),
            layout_manager_(layout_manager),
            last_clicked_node_(0),
            next_move_animations_(0),
            last_resize_animations_(0),
            ongoing_animations_(false),
            root_collapsing_(false)
    {
        // Create the root menu
        root_menu_ = new GroupNode(true, "RootNode", "", -20, 5);
        category_map_["Root"] = root_menu_;
        layout_manager_->AddCornerAnchor(root_menu_, Qt::TopLeftCorner, Qt::TopLeftCorner);
        connect(root_menu_, SIGNAL(NodeGroupClicked(GroupNode*, QParallelAnimationGroup*, QParallelAnimationGroup*)),
                SLOT(GroupNodeClicked(GroupNode*, QParallelAnimationGroup *, QParallelAnimationGroup *)));
    }

    MenuManager::~MenuManager()
    {
        SAFE_DELETE(root_menu_);
    }

    void MenuManager::AddMenuGroup(const QString &name, const QString &icon, qreal hgap, qreal vgap)
    {
        ///\todo Remove this hack at some point.
        QString hack_icon;
        QString base_url = "./data/ui/images/menus/";
        if (name == "Server Tools")
            hack_icon = base_url + "edbutton_SRVRTOOLS_icon.png";
        else if (name == "World Tools")
            hack_icon = base_url + "edbutton_WRLDTOOLS_icon.png";
        else
            hack_icon = defaultGroupIcon;

        GroupNode *group_node = new GroupNode(false, name, hack_icon, hgap, vgap);
        root_menu_->AddChildNode(group_node);
        category_map_[name] = group_node;
        layout_manager_->AddItemToScene(group_node);

        connect(group_node, SIGNAL(NodeGroupClicked(GroupNode*, QParallelAnimationGroup*, QParallelAnimationGroup*)),
                SLOT(GroupNodeClicked(GroupNode*, QParallelAnimationGroup *, QParallelAnimationGroup *)));

        Sort();
    }

    void MenuManager::AddMenuItem(QGraphicsProxyWidget *widget, const QString &name, const QString &category, const QString &icon)
    {
        ActionNode *child_node = new ActionNode(name, icon);
        ///\todo hack protection for menu crashing when root having more than 5 items.
        /// Remove when Qt 4.7 supposedly fixes this.
        if ((category.isEmpty() || category == "Root") && root_menu_->ChildCount() >= 5)
        {
            category_map_["World Tools"]->AddChildNode(child_node);
        }
        else if (category.isEmpty())
        {
            category_map_["Root"]->AddChildNode(child_node);
        }
        else if (category_map_.contains(category))
        {
            category_map_[category]->AddChildNode(child_node);
        }
        else
        {
            AddMenuGroup(category);
            category_map_[category]->AddChildNode(child_node);
        }

        controller_map_[child_node->GetID()] = widget;
        connect(child_node, SIGNAL(ActionButtonClicked(const QUuid&)), SLOT(ActionNodeClicked(const QUuid&)));
        layout_manager_->AddItemToScene(child_node);

        Sort();
    }

    void MenuManager::RemoveMenuItem(QGraphicsProxyWidget *controlled_widget)
    {
        QUuid remove_id = controller_map_.key(controlled_widget);
        if (remove_id.isNull())
            return;
/*
        MenuNode *recovered_node = 0;
        if (category_map_.contains(category))
            recovered_node =  category_map_[category]->RemoveChildNode(remove_id);
        else
            return;
*/
        MenuNode *recovered_node = 0;
        QMapIterator<QString, GroupNode*> it(category_map_);
        while(it.hasNext())
        {
            recovered_node = it.next().value()->RemoveChildNode(remove_id);
            if (recovered_node)
                break;
        }

        if (recovered_node)
        {
            controller_map_.remove(remove_id);
            disconnect(recovered_node, SIGNAL(ActionButtonClicked(const QUuid&)), this, SLOT(ActionNodeClicked(const QUuid&)));
            layout_manager_->RemoveItemFromScene(recovered_node);
        }

        Sort();
    }

    void MenuManager::ActionNodeClicked(const QUuid &id)
    {
        if (!controller_map_.contains(id))
            return;

        QGraphicsProxyWidget *controlled_widget = controller_map_[id];
        if (!controlled_widget)
            return;

        UiProxyWidget *naali_proxy = dynamic_cast<UiProxyWidget *>(controlled_widget);
        if (!naali_proxy)
        {
            if (!controlled_widget->isVisible())
                controlled_widget->show();
            else
                controlled_widget->hide();
        }
        else
        {
            if (!naali_proxy->isVisible())
                naali_proxy->show();
            else
                naali_proxy->AnimatedHide();
        }
    }

    void MenuManager::GroupNodeClicked(GroupNode *node, QParallelAnimationGroup *move_animations, QParallelAnimationGroup *size_animations)
    {
        if (ongoing_animations_)
            return;

        QSequentialAnimationGroup *revert_group = new QSequentialAnimationGroup(this);
        QSequentialAnimationGroup *sequential_move_animations_ = new QSequentialAnimationGroup(this);
        sequential_move_animations_->setDirection(QAbstractAnimation::Backward);

        // Make a sequential animation of currently expanding nodes
        // Only revert into the same tree depth as the clicked item
        int click_tree_depth = node->GetTreeDepth();
        foreach (GroupNode *node, expanded_nodes_)
        {
            if (node->GetTreeDepth() >= click_tree_depth && node->IsExpanded())
            {
                QParallelAnimationGroup *node_move_anim = node->GetMoveAnimations();
                sequential_move_animations_->addAnimation(node_move_anim);
                expanded_nodes_.removeOne(node);
            }
        }
        revert_group->addAnimation(sequential_move_animations_);
        if (last_resize_animations_)
            revert_group->addAnimation(last_resize_animations_);

        // New animations
        next_move_animations_ = move_animations;
        last_resize_animations_ = size_animations;
        expanded_nodes_.append(node);

        connect(move_animations, SIGNAL( finished() ), size_animations, SLOT( start() ));
        connect(size_animations, SIGNAL( finished() ), SLOT( AdjustTreeOpacity() ));
        // Normal item, we are expanding now, hook up move animations after revert is done
        if (!node->IsExpanded())
        {
            connect(revert_group, SIGNAL(finished()), SLOT(RevertAnimationsFinished()));
        }
        // Clicked item is root, and its collapsing
        else if (!node->parent())
        {
            connect(revert_group, SIGNAL(finished()), SLOT(RevertAnimationsFinished()));
            root_collapsing_ = true;
            expanded_nodes_.clear();
            expanded_nodes_.append(node);
        }
        // Else its a normal item collapsing, lets remove it from tracking map of expanded items
        else
        {
            expanded_nodes_.removeOne(node);
            last_resize_animations_ = 0;

            GroupNode* group_node = dynamic_cast<GroupNode*>(node->parent());
            if (group_node)
            {
                group_node->AdjustNode(QAbstractAnimation::Forward);
                last_resize_animations_ = group_node->GetResizeAnimations();
            }
        }

        revert_group->setDirection(QAbstractAnimation::Backward);
        revert_group->start();
        ongoing_animations_ = true;
    }

    void MenuManager::RevertAnimationsFinished()
    {
        if (root_collapsing_)
        {
            next_move_animations_ = 0;
            last_resize_animations_ = 0;
            root_collapsing_ = false;
            ongoing_animations_ = false;
            expanded_nodes_.at(0)->GetMoveAnimations()->stop();
            expanded_nodes_.at(0)->GetResizeAnimations()->stop();
            expanded_nodes_.clear();
        }

        if (next_move_animations_)
        {
            connect(next_move_animations_, SIGNAL( finished() ), SLOT( MoveAnimationsFinished() ));
            next_move_animations_->start();
        }
    }

    void MenuManager::MoveAnimationsFinished()
    {
        ongoing_animations_ = false;
    }

    void MenuManager::AdjustTreeOpacity()
    {
        if (expanded_nodes_.count() <= 1)
            return;

        GroupNode *process_layer = expanded_nodes_.last();
        int depth = process_layer->GetTreeDepth();
        bool level_found = false;

        process_layer = root_menu_;
        while (!level_found)
        {
            foreach(MenuNode *node, process_layer->GetChildNodeList())
            {
                if (node->GetTreeDepth() == depth)
                {
                    node->setOpacity(0.65);
                    level_found = true;
                }
                else if (dynamic_cast<GroupNode*>(node))
                {
                    process_layer = dynamic_cast<GroupNode*>(node);
                    break;
                }

                if (dynamic_cast<GroupNode*>(node) && dynamic_cast<GroupNode*>(node)->IsExpanded())
                    node->setOpacity(1);
            }
        }
    }

    void MenuManager::Sort()
    {
        root_menu_->Sort();
        layout_manager_->GetScene()->update();
    }
}
<commit_msg>compile fix<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "MenuManager.h"
#include "Common/AnchorLayoutManager.h"
#include "UiProxyWidget.h"
#include "ActionNode.h"
#include "GroupNode.h"

#include <QSequentialAnimationGroup>
#include <QPropertyAnimation>
#include <QTimer>
#include <QUuid>
#include <QDebug>
#include <QGraphicsScene>

#include "MemoryLeakCheck.h"

namespace CoreUi
{
    QString MenuManager::defaultItemIcon = "./data/ui/images/menus/edbutton_MATWIZ_normal.png";
    QString MenuManager::defaultGroupIcon = "./data/ui/images/menus/edbutton_WRLDTOOLS_icon.png";

    MenuManager::MenuManager(QObject *parent, CoreUi::AnchorLayoutManager *layout_manager) :
            QObject(parent),
            layout_manager_(layout_manager),
            last_clicked_node_(0),
            next_move_animations_(0),
            last_resize_animations_(0),
            ongoing_animations_(false),
            root_collapsing_(false)
    {
        // Create the root menu
        root_menu_ = new GroupNode(true, "RootNode", "", -20, 5);
        category_map_["Root"] = root_menu_;
        layout_manager_->AddCornerAnchor(root_menu_, Qt::TopLeftCorner, Qt::TopLeftCorner);
        connect(root_menu_, SIGNAL(NodeGroupClicked(GroupNode*, QParallelAnimationGroup*, QParallelAnimationGroup*)),
                SLOT(GroupNodeClicked(GroupNode*, QParallelAnimationGroup *, QParallelAnimationGroup *)));
    }

    MenuManager::~MenuManager()
    {
        SAFE_DELETE(root_menu_);
    }

    void MenuManager::AddMenuGroup(const QString &name, const QString &icon, qreal hgap, qreal vgap)
    {
        ///\todo Remove this hack at some point.
        QString hack_icon;
        QString base_url = "./data/ui/images/menus/";
        if (name == "Server Tools")
            hack_icon = base_url + "edbutton_SRVRTOOLS_icon.png";
        else if (name == "World Tools")
            hack_icon = base_url + "edbutton_WRLDTOOLS_icon.png";
        else
            hack_icon = defaultGroupIcon;

        GroupNode *group_node = new GroupNode(false, name, hack_icon, hgap, vgap);
        root_menu_->AddChildNode(group_node);
        category_map_[name] = group_node;
        layout_manager_->AddItemToScene(group_node);

        connect(group_node, SIGNAL(NodeGroupClicked(GroupNode*, QParallelAnimationGroup*, QParallelAnimationGroup*)),
                SLOT(GroupNodeClicked(GroupNode*, QParallelAnimationGroup *, QParallelAnimationGroup *)));

        Sort();
    }

    void MenuManager::AddMenuItem(QGraphicsProxyWidget *widget, const QString &name, const QString &category, const QString &icon)
    {
        ActionNode *child_node = new ActionNode(name, icon);
        ///\todo hack protection for menu crashing when root having more than 5 items.
        /// Remove when Qt 4.7 supposedly fixes this.
        if ((category.isEmpty() || category == "Root") && root_menu_->ChildCount() >= 5)
        {
            category_map_["World Tools"]->AddChildNode(child_node);
        }
        else if (category.isEmpty())
        {
            category_map_["Root"]->AddChildNode(child_node);
        }
        else if (category_map_.contains(category))
        {
            category_map_[category]->AddChildNode(child_node);
        }
        else
        {
            AddMenuGroup(category);
            category_map_[category]->AddChildNode(child_node);
        }

        controller_map_[child_node->GetID()] = widget;
        connect(child_node, SIGNAL(ActionButtonClicked(const QUuid&)), SLOT(ActionNodeClicked(const QUuid&)));
        layout_manager_->AddItemToScene(child_node);

        Sort();
    }

    void MenuManager::RemoveMenuItem(QGraphicsProxyWidget *controlled_widget)
    {
        QUuid remove_id = controller_map_.key(controlled_widget);
        if (remove_id.isNull())
            return;
/*
        MenuNode *recovered_node = 0;
        if (category_map_.contains(category))
            recovered_node =  category_map_[category]->RemoveChildNode(remove_id);
        else
            return;
*/
        MenuNode *recovered_node = 0;
        QMapIterator<QString, GroupNode*> it(category_map_);
        while(it.hasNext())
        {
            recovered_node = it.next().value()->RemoveChildNode(remove_id);
            if (recovered_node)
                break;
        }

        if (recovered_node)
        {
            controller_map_.remove(remove_id);
            disconnect(recovered_node, SIGNAL(ActionButtonClicked(const QUuid&)), this, SLOT(ActionNodeClicked(const QUuid&)));
            layout_manager_->RemoveItemFromScene(recovered_node);
        }

        Sort();
    }

    void MenuManager::ActionNodeClicked(const QUuid &id)
    {
        if (!controller_map_.contains(id))
            return;

        QGraphicsProxyWidget *controlled_widget = controller_map_[id];
        if (!controlled_widget)
            return;

        UiProxyWidget *naali_proxy = dynamic_cast<UiProxyWidget *>(controlled_widget);
        if (!naali_proxy)
        {
            if (!controlled_widget->isVisible())
                controlled_widget->show();
            else
                controlled_widget->hide();
        }
        else
        {
            if (!naali_proxy->isVisible())
                naali_proxy->show();
            else
                naali_proxy->AnimatedHide();
        }
    }

    void MenuManager::GroupNodeClicked(GroupNode *node, QParallelAnimationGroup *move_animations, QParallelAnimationGroup *size_animations)
    {
        if (ongoing_animations_)
            return;

        QSequentialAnimationGroup *revert_group = new QSequentialAnimationGroup(this);
        QSequentialAnimationGroup *sequential_move_animations_ = new QSequentialAnimationGroup(this);
        sequential_move_animations_->setDirection(QAbstractAnimation::Backward);

        // Make a sequential animation of currently expanding nodes
        // Only revert into the same tree depth as the clicked item
        int click_tree_depth = node->GetTreeDepth();
        foreach (GroupNode *node, expanded_nodes_)
        {
            if (node->GetTreeDepth() >= click_tree_depth && node->IsExpanded())
            {
                QParallelAnimationGroup *node_move_anim = node->GetMoveAnimations();
                sequential_move_animations_->addAnimation(node_move_anim);
                expanded_nodes_.removeOne(node);
            }
        }
        revert_group->addAnimation(sequential_move_animations_);
        if (last_resize_animations_)
            revert_group->addAnimation(last_resize_animations_);

        // New animations
        next_move_animations_ = move_animations;
        last_resize_animations_ = size_animations;
        expanded_nodes_.append(node);

        connect(move_animations, SIGNAL( finished() ), size_animations, SLOT( start() ));
        connect(size_animations, SIGNAL( finished() ), SLOT( AdjustTreeOpacity() ));
        // Normal item, we are expanding now, hook up move animations after revert is done
        if (!node->IsExpanded())
        {
            connect(revert_group, SIGNAL(finished()), SLOT(RevertAnimationsFinished()));
        }
        // Clicked item is root, and its collapsing
        else if (!node->parent())
        {
            connect(revert_group, SIGNAL(finished()), SLOT(RevertAnimationsFinished()));
            root_collapsing_ = true;
            expanded_nodes_.clear();
            expanded_nodes_.append(node);
        }
        // Else its a normal item collapsing, lets remove it from tracking map of expanded items
        else
        {
            expanded_nodes_.removeOne(node);
            last_resize_animations_ = 0;

            GroupNode* group_node = dynamic_cast<GroupNode*>(node->parent());
            if (group_node)
            {
                group_node->AdjustNode(QAbstractAnimation::Forward);
                last_resize_animations_ = group_node->GetResizeAnimations();
            }
        }

        revert_group->setDirection(QAbstractAnimation::Backward);
        revert_group->start();
        ongoing_animations_ = true;
    }

    void MenuManager::RevertAnimationsFinished()
    {
        if (root_collapsing_)
        {
            next_move_animations_ = 0;
            last_resize_animations_ = 0;
            root_collapsing_ = false;
            ongoing_animations_ = false;
            expanded_nodes_.at(0)->GetMoveAnimations()->stop();
            expanded_nodes_.at(0)->GetResizeAnimations()->stop();
            expanded_nodes_.clear();
        }

        if (next_move_animations_)
        {
            connect(next_move_animations_, SIGNAL( finished() ), SLOT( MoveAnimationsFinished() ));
            next_move_animations_->start();
        }
    }

    void MenuManager::MoveAnimationsFinished()
    {
        ongoing_animations_ = false;
    }

    void MenuManager::AdjustTreeOpacity()
    {
        if (expanded_nodes_.count() <= 1)
            return;

        GroupNode *process_layer = expanded_nodes_.last();
        int depth = process_layer->GetTreeDepth();
        bool level_found = false;

        process_layer = root_menu_;
        while (!level_found)
        {
            foreach(MenuNode *node, process_layer->GetChildNodeList())
            {
                if (node->GetTreeDepth() == depth)
                {
                    node->setOpacity(0.65);
                    level_found = true;
                }
                else if (dynamic_cast<GroupNode*>(node))
                {
                    process_layer = dynamic_cast<GroupNode*>(node);
                    break;
                }

                if (dynamic_cast<GroupNode*>(node) && dynamic_cast<GroupNode*>(node)->IsExpanded())
                    node->setOpacity(1);
            }
        }
    }

    void MenuManager::Sort()
    {
        root_menu_->Sort();
        layout_manager_->GetScene()->update();
    }
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkHashSource.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include <vtksys/stl/string>
#include <vtksys/ios/fstream>
#include <vtksys/ios/iostream>
#include <vtksys/MD5.h>
#include <vtksys/SystemTools.hxx>
#include <vtksys/RegularExpression.hxx>

static vtksys_stl::string HashMD5(vtksys_ios::istream& in)
{
  char hash[33];
  vtksysMD5* hasher = vtksysMD5_New();
  vtksysMD5_Initialize(hasher);

  vtksys::RegularExpression key("\\$(Revision|Date|RCSfile):[^$]*\\$");

  vtksys_stl::string line;
  while(vtksys::SystemTools::GetLineFromStream(in, line))
    {
    // Remove CVS key values from the line (simulate -kk).
    while(key.find(line))
      {
      vtksys_stl::string tmp = line.substr(0, key.start());
      tmp += "$";
      tmp += key.match(1);
      tmp += "$";
      tmp += line.substr(key.end());
      line = tmp;
      }

    // Append the line and a newline.
    vtksysMD5_Append(hasher, (unsigned char const*)line.c_str(), -1);
    vtksysMD5_Append(hasher, (unsigned char const*)"\n", 1);
    }

  vtksysMD5_FinalizeHex(hasher, hash);
  vtksysMD5_Delete(hasher);
  hash[32] = 0;
  return vtksys_stl::string(hash);
}

int main(int argc, char *argv[])
{
  if(argc < 3)
    {
    vtksys_ios::cerr << "Usage: vtkHashSource input.cxx name\n";
    return 1;
    }
  const char* inFile = argv[1];
  const char* name = argv[2];

  vtksys_ios::ifstream fin(inFile);
  if(!fin)
    {
    vtksys_ios::cerr << "Unable to read \"" << inFile << "\"\n";
    return 1;
    }

  vtksys_stl::string md5 = HashMD5(fin);

  vtksys_ios::cout
    << "#ifndef " << name << "\n"
    << "# define " << name << " \"" << md5 << "\"\n"
    << "#endif\n";

  return 0;
}
<commit_msg>ENH: Teach vtkHashSource to create an output file<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkHashSource.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include <vtksys/stl/string>
#include <vtksys/ios/fstream>
#include <vtksys/ios/iostream>
#include <vtksys/MD5.h>
#include <vtksys/SystemTools.hxx>
#include <vtksys/RegularExpression.hxx>

static vtksys_stl::string HashMD5(vtksys_ios::istream& in)
{
  char hash[33];
  vtksysMD5* hasher = vtksysMD5_New();
  vtksysMD5_Initialize(hasher);

  vtksys::RegularExpression key("\\$(Revision|Date|RCSfile):[^$]*\\$");

  vtksys_stl::string line;
  while(vtksys::SystemTools::GetLineFromStream(in, line))
    {
    // Remove CVS key values from the line (simulate -kk).
    while(key.find(line))
      {
      vtksys_stl::string tmp = line.substr(0, key.start());
      tmp += "$";
      tmp += key.match(1);
      tmp += "$";
      tmp += line.substr(key.end());
      line = tmp;
      }

    // Append the line and a newline.
    vtksysMD5_Append(hasher, (unsigned char const*)line.c_str(), -1);
    vtksysMD5_Append(hasher, (unsigned char const*)"\n", 1);
    }

  vtksysMD5_FinalizeHex(hasher, hash);
  vtksysMD5_Delete(hasher);
  hash[32] = 0;
  return vtksys_stl::string(hash);
}

int main(int argc, char *argv[])
{
  if(argc < 3)
    {
    vtksys_ios::cerr << "Usage: vtkHashSource input.cxx name [output.h]\n";
    return 1;
    }
  const char* inFile = argv[1];
  const char* name = argv[2];
  const char* outFile = argc > 3? argv[3] : 0;

  vtksys_ios::ifstream fin(inFile);
  if(!fin)
    {
    vtksys_ios::cerr << "Unable to read \"" << inFile << "\"\n";
    return 1;
    }

  vtksys_stl::string md5 = HashMD5(fin);

  vtksys_ios::ofstream fout;
  if(outFile)
    {
    fout.open(outFile);
    if(!fout)
      {
      vtksys_ios::cerr << "Unable to write \"" << outFile << "\"\n";
      return 1;
      }
    }

  vtksys_ios::ostream& out = fout.is_open()? fout : vtksys_ios::cout;
  out
    << "#ifndef " << name << "\n"
    << "# define " << name << " \"" << md5 << "\"\n"
    << "#endif\n";

  return 0;
}
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- *
 *                    OpenSim:  testREADME.cpp                                *
 * -------------------------------------------------------------------------- *
 * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
 * See http://opensim.stanford.edu and the NOTICE file for more information.  *
 * OpenSim is developed at Stanford University and supported by the US        *
 * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
 * through the Warrior Web program.                                           *
 *                                                                            *
 * Copyright (c) 2005-2014 Stanford University and the Authors                *
 * Author(s): Chris Dembia                                                    *
 *                                                                            *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License. You may obtain a  *
 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0.         *
 *                                                                            *
 * Unless required by applicable law or agreed to in writing, software        *
 * distributed under the License is distributed on an "AS IS" BASIS,          *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 * -------------------------------------------------------------------------- */

/* Whenever you change this test:
 * 1. Copy the new code over to the README.md, uncommenting setUseVisualizer
 * and removing getchar().
 *
 * If your changes would cause the gif to change substantially:
 * 1. Uncomment setUseVisualizer and getchar(), and run the test.
 * 2. When the visualizer pops up, click View -> Save Movie.
 * 3. cd into testREADME_1 and run the following commands (on Linux):
 *      $ convert 'Frame*.png[400x470+200+100]' \( +clone -set delay 100 \)
 *          +swap +delete opensim_double_pendulum_muscle_1.gif
 *      $ gifsicle --crop-transparency --optimize=O3 --colors=32 --delay 5 <
 *          opensim_double_pendulum_muscle_1.gif >
 *          opensim_double_pendulum_muscle.gif
 */

#include <OpenSim/OpenSim.h>
using namespace SimTK;
using namespace OpenSim; using OpenSim::Body;
int main() {
    Model model; // TODO model.setUseVisualizer(true);
    // Two links, with mass of 1 kg, center of mass at the
    // origin of the body's frame, and moments/products of inertia of zero.
    OpenSim::Body* link1 = new OpenSim::Body("humerus", 1, Vec3(0), Inertia(0));
    OpenSim::Body* link2 = new OpenSim::Body("radius", 1, Vec3(0), Inertia(0));

    // Joints that connect the bodies together.
    PinJoint* joint1 = new PinJoint("shoulder",
            // Parent body, location in parent, orientation in parent.
            model.getGroundBody(), Vec3(0), Vec3(0),
            // Child body, location in child, orientation in child.
            *link1, Vec3(0, 1, 0), Vec3(0));
    PinJoint* joint2 = new PinJoint("elbow",
            *link1, Vec3(0), Vec3(0), *link2, Vec3(0, 1, 0), Vec3(0));

    // Add an actuator that crosses the elbow, and a joint stop.
    Millard2012EquilibriumMuscle* muscle = new
        Millard2012EquilibriumMuscle("biceps", 200, 0.6, 0.55, 0);
    muscle->addNewPathPoint("point1", *link1, Vec3(0, 0.8, 0));
    muscle->addNewPathPoint("point2", *link2, Vec3(0, 0.7, 0));

    // A controller that specifies the excitation of the biceps muscle.
    PrescribedController* brain = new PrescribedController();
    brain->addActuator(*muscle);
    // Muscle excitation is 0.3 for the first 0.5 seconds, and 1.0 thereafter.
    brain->prescribeControlForActuator("biceps",
            new StepFunction(0.5, 3, 0.3, 1));

    // Add bodies and joints to the model.
    model.addBody(link1); model.addBody(link2);
    model.addJoint(joint1); model.addJoint(joint2);
    model.addForce(muscle);
    model.addController(brain);

    // Configure the model.
    State& state = model.initSystem();
    // Fix shoulder joint, flex elbow joint.
    model.updCoordinateSet()[0].setLocked(state, true);
    model.updCoordinateSet()[1].setValue(state, 0.5 * Pi);
    model.equilibrateMuscles(state);

    // Add display geometry.
    model.updMatterSubsystem().setShowDefaultGeometry(true);
    Visualizer& viz = model.updVisualizer().updSimbodyVisualizer();
    viz.setBackgroundColor(Vec3(1, 1, 1));
    // Ellipsoids: 0.5 m radius along y axis, centered 0.5 m up along y axis.
    DecorativeEllipsoid geom(Vec3(0.1, 0.5, 0.1)); Vec3 center(0, 0.5, 0);
    viz.addDecoration(link1->getIndex(), Transform(center), geom);
    viz.addDecoration(link2->getIndex(), Transform(center), geom);

    // Simulate.
    RungeKuttaMersonIntegrator integrator(model.getSystem());
    Manager manager(model, integrator);
    manager.setInitialTime(0); manager.setFinalTime(10.0);
    // TODO getchar();
    manager.integrate(state);
};
<commit_msg>Enable visualizer in testREADME.<commit_after>/* -------------------------------------------------------------------------- *
 *                    OpenSim:  testREADME.cpp                                *
 * -------------------------------------------------------------------------- *
 * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
 * See http://opensim.stanford.edu and the NOTICE file for more information.  *
 * OpenSim is developed at Stanford University and supported by the US        *
 * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
 * through the Warrior Web program.                                           *
 *                                                                            *
 * Copyright (c) 2005-2014 Stanford University and the Authors                *
 * Author(s): Chris Dembia                                                    *
 *                                                                            *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License. You may obtain a  *
 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0.         *
 *                                                                            *
 * Unless required by applicable law or agreed to in writing, software        *
 * distributed under the License is distributed on an "AS IS" BASIS,          *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 * -------------------------------------------------------------------------- */

/* Whenever you change this test:
 * 1. Copy the new code over to the README.md, removing getchar().
 *
 * If your changes would cause the gif to change substantially:
 * 1. Uncomment getchar(), and run the test.
 * 2. When the visualizer pops up, click View -> Save Movie.
 * 3. cd into testREADME_1 and run the following commands (on Linux):
 *      $ convert 'Frame*.png[400x470+200+100]' \( +clone -set delay 100 \)
 *          +swap +delete opensim_double_pendulum_muscle_1.gif
 *      $ gifsicle --crop-transparency --optimize=O3 --colors=32 --delay 5 <
 *          opensim_double_pendulum_muscle_1.gif >
 *          opensim_double_pendulum_muscle.gif
 */

#include <OpenSim/OpenSim.h>
using namespace SimTK;
using namespace OpenSim; using OpenSim::Body;
int main() {
    Model model; model.setUseVisualizer(true);
    // Two links, with mass of 1 kg, center of mass at the
    // origin of the body's frame, and moments/products of inertia of zero.
    OpenSim::Body* link1 = new OpenSim::Body("humerus", 1, Vec3(0), Inertia(0));
    OpenSim::Body* link2 = new OpenSim::Body("radius", 1, Vec3(0), Inertia(0));

    // Joints that connect the bodies together.
    PinJoint* joint1 = new PinJoint("shoulder",
            // Parent body, location in parent, orientation in parent.
            model.getGroundBody(), Vec3(0), Vec3(0),
            // Child body, location in child, orientation in child.
            *link1, Vec3(0, 1, 0), Vec3(0));
    PinJoint* joint2 = new PinJoint("elbow",
            *link1, Vec3(0), Vec3(0), *link2, Vec3(0, 1, 0), Vec3(0));

    // Add an actuator that crosses the elbow, and a joint stop.
    Millard2012EquilibriumMuscle* muscle = new
        Millard2012EquilibriumMuscle("biceps", 200, 0.6, 0.55, 0);
    muscle->addNewPathPoint("point1", *link1, Vec3(0, 0.8, 0));
    muscle->addNewPathPoint("point2", *link2, Vec3(0, 0.7, 0));

    // A controller that specifies the excitation of the biceps muscle.
    PrescribedController* brain = new PrescribedController();
    brain->addActuator(*muscle);
    // Muscle excitation is 0.3 for the first 0.5 seconds, and 1.0 thereafter.
    brain->prescribeControlForActuator("biceps",
            new StepFunction(0.5, 3, 0.3, 1));

    // Add bodies and joints to the model.
    model.addBody(link1); model.addBody(link2);
    model.addJoint(joint1); model.addJoint(joint2);
    model.addForce(muscle);
    model.addController(brain);

    // Configure the model.
    State& state = model.initSystem();
    // Fix shoulder joint, flex elbow joint.
    model.updCoordinateSet()[0].setLocked(state, true);
    model.updCoordinateSet()[1].setValue(state, 0.5 * Pi);
    model.equilibrateMuscles(state);

    // Add display geometry.
    model.updMatterSubsystem().setShowDefaultGeometry(true);
    Visualizer& viz = model.updVisualizer().updSimbodyVisualizer();
    viz.setBackgroundColor(Vec3(1, 1, 1));
    // Ellipsoids: 0.5 m radius along y axis, centered 0.5 m up along y axis.
    DecorativeEllipsoid geom(Vec3(0.1, 0.5, 0.1)); Vec3 center(0, 0.5, 0);
    viz.addDecoration(link1->getIndex(), Transform(center), geom);
    viz.addDecoration(link2->getIndex(), Transform(center), geom);

    // Simulate.
    RungeKuttaMersonIntegrator integrator(model.getSystem());
    Manager manager(model, integrator);
    manager.setInitialTime(0); manager.setFinalTime(10.0);
    // TODO getchar();
    manager.integrate(state);
};
<|endoftext|>


<commit_before><commit_msg>Fix call to slightly oddball interface of krb5_free_addresses()  #6992 #7578<commit_after><|endoftext|>


<commit_before>#include <Indie.h>

#include "GameManager.h"
#include "menu/PauseMenu.h"
#include "menu/Player.h"
#include "power/Power.h"
#include "power/Sneeze.h"

#define DEATH_VELOCITY 120

namespace Symp {

GameManager::GameManager(const char *title, int width, int height, int bpp, bool vsync, bool fs, bool dBuffer) {
	IndieLib::init(IND_DEBUG_MODE);
	m_pWindow = new Window();
	m_pRender = new Render();
	m_pWindow->setWindow(m_pRender->init(title, width, height, bpp, vsync, fs, dBuffer));
	//m_pRender->toggleFullScreen();
	m_pWindow->setCursor(true);

	InputManager::getInstance();
	InputManager::initRender(m_pRender);

	m_pParser = new Parser("../assets/data.xml");

	m_pLevelManager = nullptr;
	m_bIsMenu = false;
	switchToMenu();
}

GameManager::~GameManager() {
	IndieLib::end();
	if(m_pRender->isFullScreen()) {
		m_pRender->toggleFullScreen();
	}
	delete m_pWindow;
	delete m_pRender;
	InputManager::removeInstance();
	MenuManager::removeInstance();
}

void GameManager::clear() {
	EntityManager::getInstance()->deleteAllEntities();
	delete m_pLevelManager;
	MenuManager::removeInstance();
	m_bIsMenu = false;
	EntityManager::removeInstance();
	m_pLevelManager = NULL;
}

void GameManager::startMainLoop(){
	//If the user didn't closed the window or didn't clicked a "quit" button, then update
	while (!MenuManager::getInstance()->isAboutToQuit() && !InputManager::getInstance()->quit())
	{
		InputManager::getInstance()->update();
 		if(m_bIsInGame) {
			updateGame();
		}
		else {
			updateMenu();
		}
	}
}

void GameManager::updateGame() {

	/******************/
	/*   Move Dino    */
	/******************/

	PhysicalEntity* pDino = EntityManager::getInstance()->getPhysicalDino();
    std::vector<SoundEntity*> sDinoArray = EntityManager::getInstance()->getSoundDino();

	float forceFactor = 10.f;
	float impulse = pDino->getMass() * forceFactor;

	// Left
	if (InputManager::getInstance()->isKeyPressed(IND_KEYLEFT) && !pDino->isContactingLeft()) {
		// Physics
		pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(-impulse, 0.f), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
		// Render : flip to the left all render entities
		for(size_t i = 0; i < EntityManager::getInstance()->getRenderDino().size(); ++i) {
			if(EntityManager::getInstance()->getRenderDino().at(i) != NULL)
				EntityManager::getInstance()->getRenderDino().at(i)->flipHorizontaly(true);
		}
		EntityManager::getInstance()->updateDinoRender(DinoAction::Walk);
	}
	// Right
	if (InputManager::getInstance()->isKeyPressed(IND_KEYRIGHT) && !pDino->isContactingRight()) {
		// Physics
		pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(impulse, 0.f), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
		// Render : flip to the right all render entities
		for(size_t i = 0; i < EntityManager::getInstance()->getRenderDino().size(); ++i) {
			if(EntityManager::getInstance()->getRenderDino().at(i) != NULL)
				EntityManager::getInstance()->getRenderDino().at(i)->flipHorizontaly(false);
		}
		EntityManager::getInstance()->updateDinoRender(DinoAction::Walk);
	}
	// Up
	if (InputManager::getInstance()->isKeyPressed(IND_KEYUP) && pDino->getNumContacts() > 0 && pDino->isContactingBelow()) {
		// Physics
		float force = impulse / (1/60.0); //f = mv/t
	    pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(pDino->getLinearVelocity().x, -force), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
	    // Sound
		SoundManager::getInstance()->play(sDinoArray[DinoAction::Jump]->getIndexSound());
	}
	if (InputManager::getInstance()->isKeyPressed(IND_KEYDOWN)) {
		// Physics
		pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(0.f, impulse), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
	}
	// No movements
	else {
		// if no power
		if(EntityManager::getInstance()->getCurrentDinoAction() != DinoAction::Sneezing
			&& EntityManager::getInstance()->getCurrentDinoAction() != DinoAction::Die)
			EntityManager::getInstance()->updateDinoRender(DinoAction::Stop);
	}

	/***********/
	/*  Death  */
	/***********/

	// std::cout << "Velocity : " << pDino->getLinearVelocity().x << " - " << pDino->getLinearVelocity().y << std::endl;
	// if(pDino->getLinearVelocity().y >= DEATH_VELOCITY) {
	// 	std::cout << "Tou est mort ! ;) " << std::endl;
	// 	EntityManager::getInstance()->killDino(DinoAction::Die);

	// 	loadLevel(MenuManager::getInstance()->getLevelToLoad().c_str());

	// }

	/****************************/
	/*  Camera zoom (for debug) */
	/****************************/

	if (InputManager::getInstance()->isKeyPressed(IND_S)){
		float newZoom = m_pRender->getZoom()+0.005;
		m_pRender->setZoom(newZoom);
	}
	else if (InputManager::getInstance()->isKeyPressed(IND_Q)){
		float newZoom = m_pRender->getZoom()-0.005;
		m_pRender->setZoom(newZoom);
	}
	else if (InputManager::getInstance()->isKeyPressed(IND_D)){
		m_pRender->setZoom(1);
	}

	/********************/
	/* Camera movements */
	/********************/

	m_pRender->setCamera();
	m_pRender->setCameraPosition(pDino->getPosition().x, pDino->getPosition().y);

	/********************/
	/*  Update entities */
	/********************/

	EntityManager::getInstance()->updateEntities();

	/********************/
	/*     Powers       */
	/********************/

	EntityManager::getInstance()->executePowers();

	/********************/
	/*  Manage render   */
	/********************/

	m_pRender->clearViewPort(60, 60, 60);
	m_pRender->beginScene();
		EntityManager::getInstance()->renderEntities();
		//test hitbox
		debugPhysicalEntities();
		//debugRenderEntities();
	m_pRender->endScene();

	/********************/
	/*      Pause       */
	/********************/

	if (InputManager::getInstance()->onKeyPress(IND_ESCAPE)) {
		switchToMenu();
	}

	/***********************/
	/*  Detect level exit  */
	/***********************/

	float exitX = EntityManager::getInstance()->getExitCoordinates()[0];
	float exitY = EntityManager::getInstance()->getExitCoordinates()[1];

	if(abs(exitX - pDino->getPosition().x) < 10 && abs(exitY - pDino->getPosition().y) < 10) {
		fprintf(stderr, "You finished this level !\n");
	}
}

void GameManager::updateMenu() {
	//Forward inputs

	//The following offsets are necessary to the mouse pointer to click on the pause menu
	//because it's not the same coordinate space
	int offsetX = 0;
	int offsetY = 0;
	if(MenuManager::getInstance()->isDisplayingPauseState()){
		PhysicalEntity* pDino = EntityManager::getInstance()->getPhysicalDino();
		offsetX = pDino->getPosition().x - m_pWindow->getIND_Window()->getWidth()*0.5;
		offsetY = pDino->getPosition().y - m_pWindow->getIND_Window()->getHeight()*0.5;
	}

	if (InputManager::getInstance()->onKeyPress(IND_KEYDOWN)){
		MenuManager::getInstance()->handleKeyPressed("KEYDOWN");
	}
	else if (InputManager::getInstance()->onKeyPress(IND_KEYUP)){
		MenuManager::getInstance()->handleKeyPressed("KEYUP");
	}
	else if (InputManager::getInstance()->isMouseMotion()){
		// Mouse hover
		MenuManager::getInstance()->handleMouseHover(InputManager::getInstance()->getMouseX()+offsetX, InputManager::getInstance()->getMouseY()+offsetY);
	}
	else if(InputManager::getInstance()->onMouseButtonPress(IND_MBUTTON_LEFT)){
		// Clic
		MenuManager::getInstance()->handleMouseClic(InputManager::getInstance()->getMouseX()+offsetX, InputManager::getInstance()->getMouseY()+offsetY);
	}
	else if (InputManager::getInstance()->onKeyPress(IND_ESCAPE) && MenuManager::getInstance()->isDisplayingPauseState()){
		// Hidding the Pause menu
		MenuManager::getInstance()->setLevelChoosen(false);
		m_bIsInGame = true;
	}

	// The PauseMenu need not to refresh the window in order to displayed upon the game view
	if(!MenuManager::getInstance()->isDisplayingPauseState()){
		m_pRender->clearViewPort(60, 60, 60);
	}
	// Otherwise, all the menus needs to refresh the window
	m_pRender->beginScene();
		MenuManager::getInstance()->renderEntities();
	m_pRender->endScene();

	//manage camera
	m_pRender->setCamera();
	//Manage user decisions
	if(MenuManager::getInstance()->isLevelChoosen()){
		// If the game part needs to be launch
		switchToGame();
		MenuManager::getInstance()->clear();
	}else if (MenuManager::getInstance()->isGoingBackToMenu() && MenuManager::getInstance()->isDisplayingPauseState()){
		// If the user wants to go back to the main menu from the pause menu
		m_pRender->setCameraPosition(m_pWindow->getIND_Window()->getWidth()*0.5, m_pWindow->getIND_Window()->getHeight()*0.5);
		clear();
		switchToMenu();
	}
}

void GameManager::switchToGame() {

	// Reset the menuManager attribut
	MenuManager::getInstance()->setLevelChoosen(false);

	if (m_pLevelManager == NULL) {
		EntityManager::getInstance()->initRender(m_pRender);
		//If no game have been created before then create a new one (from the main menu)
		m_pLevelManager = new LevelManager();
		loadLevel(MenuManager::getInstance()->getLevelToLoad().c_str());
	 	m_bIsInGame = true;
	}
	else {
		m_bIsInGame = true;
	}
}

void GameManager::switchToMenu() {

	//If the MenuManager doesn't exists, means at the first launch or when the user quit the game, then create it.
	if (m_bIsMenu == false) {

		// Retrive data from the player data file
		std::pair<Player*, std::vector<Player*>> playerData = m_pParser->loadPlayerData();

		// Start the menus
		MenuManager::getInstance();
		MenuManager::init(m_pRender, playerData);
		m_bIsMenu = true;

 		// Manage Camera
		m_pRender->setCamera();
 		m_pRender->setCameraPosition(m_pWindow->getIND_Window()->getWidth()*0.5, m_pWindow->getIND_Window()->getHeight()*0.5);

 	}
 	else {
 		// Pause menu
 		std::vector<RenderEntity*> pDinos = EntityManager::getInstance()->getRenderDino();
 		PauseMenu* pPauseMenu = new PauseMenu(MenuManager::getInstance(), pDinos[0]->getPosX(), pDinos[0]	->getPosY());
 		MenuManager::getInstance()->setState(pPauseMenu);
 	}

 	m_bIsInGame = false;
}

void GameManager::loadLevel(const char* mapFile) {
	EntityManager::getInstance()->deleteAllEntities();
	m_pLevelManager->loadLevel(mapFile);
}

void GameManager::debugPhysicalEntities() {
	for (unsigned int idEntity = 0; idEntity < EntityManager::getInstance()->getPhysicalEntityArray().size(); ++idEntity) {
		PhysicalEntity* pEntity = EntityManager::getInstance()->getPhysicalEntityArray()[idEntity];
		if(pEntity != NULL) {
			b2Vec2 topleft;
			topleft.x = pEntity->getPosition().x - pEntity->getWidth()/2;
			topleft.y = pEntity->getPosition().y + pEntity->getHeight()/2;
			b2Vec2 botright;
			botright.x = pEntity->getPosition().x + pEntity->getWidth()/2;
			botright.y = pEntity->getPosition().y - pEntity->getHeight()/2;
			//draw the hitbox in red
			m_pRender->getIND_Render()->blitRectangle(topleft.x, topleft.y, botright.x, botright.y, 255, 0, 0, 255);
			//draw the position
			m_pRender->getIND_Render()->blitRectangle(pEntity->getPosition().x-5, pEntity->getPosition().y+5, pEntity->getPosition().x+5, pEntity->getPosition().y-5, 255, 0, 255, 255);
		}
	}
}

void GameManager::debugRenderEntities() {
	for (unsigned int idEntity = 0; idEntity < EntityManager::getInstance()->getRenderEntityArray().size(); ++idEntity) {
		std::vector<RenderEntity*> entityArray = EntityManager::getInstance()->getRenderEntityArray()[idEntity];
		if(entityArray.size() > 0) {
			for (unsigned int indexEntity = 0; indexEntity < entityArray.size(); ++indexEntity) {
				RenderEntity* rEntity = entityArray[indexEntity];
				b2Vec2 topleft;
				topleft.x = rEntity->getPosX() - rEntity->getWidth()/2;
				topleft.y = rEntity->getPosY() + rEntity->getHeight()/2;
				b2Vec2 botright;
				botright.x = rEntity->getPosX() + rEntity->getWidth()/2;
				botright.y = rEntity->getPosY() - rEntity->getHeight()/2;
				//draw the size in green
				m_pRender->getIND_Render()->blitRectangle(topleft.x, topleft.y, botright.x, botright.y, 0, 255, 0, 255);
				//draw the position
				m_pRender->getIND_Render()->blitRectangle(rEntity->getPosX()-5, rEntity->getPosY()+5, rEntity->getPosX()+5, rEntity->getPosY()-5, 0, 255, 255, 255);
			}
		}
	}
}

}
<commit_msg>fix animation bug<commit_after>#include <Indie.h>

#include "GameManager.h"
#include "menu/PauseMenu.h"
#include "menu/Player.h"
#include "power/Power.h"
#include "power/Sneeze.h"

#define DEATH_VELOCITY 120

namespace Symp {

GameManager::GameManager(const char *title, int width, int height, int bpp, bool vsync, bool fs, bool dBuffer) {
	IndieLib::init(IND_DEBUG_MODE);
	m_pWindow = new Window();
	m_pRender = new Render();
	m_pWindow->setWindow(m_pRender->init(title, width, height, bpp, vsync, fs, dBuffer));
	//m_pRender->toggleFullScreen();
	m_pWindow->setCursor(true);

	InputManager::getInstance();
	InputManager::initRender(m_pRender);

	m_pParser = new Parser("../assets/data.xml");

	m_pLevelManager = nullptr;
	m_bIsMenu = false;
	switchToMenu();
}

GameManager::~GameManager() {
	IndieLib::end();
	if(m_pRender->isFullScreen()) {
		m_pRender->toggleFullScreen();
	}
	delete m_pWindow;
	delete m_pRender;
	InputManager::removeInstance();
	MenuManager::removeInstance();
}

void GameManager::clear() {
	EntityManager::getInstance()->deleteAllEntities();
	delete m_pLevelManager;
	MenuManager::removeInstance();
	m_bIsMenu = false;
	EntityManager::removeInstance();
	m_pLevelManager = NULL;
}

void GameManager::startMainLoop(){
	//If the user didn't closed the window or didn't clicked a "quit" button, then update
	while (!MenuManager::getInstance()->isAboutToQuit() && !InputManager::getInstance()->quit())
	{
		InputManager::getInstance()->update();
 		if(m_bIsInGame) {
			updateGame();
		}
		else {
			updateMenu();
		}
	}
}

void GameManager::updateGame() {

	/******************/
	/*   Move Dino    */
	/******************/

	PhysicalEntity* pDino = EntityManager::getInstance()->getPhysicalDino();
    std::vector<SoundEntity*> sDinoArray = EntityManager::getInstance()->getSoundDino();

	float forceFactor = 10.f;
	float impulse = pDino->getMass() * forceFactor;

	// Left
	if (InputManager::getInstance()->isKeyPressed(IND_KEYLEFT) && !pDino->isContactingLeft()) {
		// Physics
		pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(-impulse, 0.f), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
		// Render : flip to the left all render entities
		for(size_t i = 0; i < EntityManager::getInstance()->getRenderDino().size(); ++i) {
			if(EntityManager::getInstance()->getRenderDino().at(i) != NULL)
				EntityManager::getInstance()->getRenderDino().at(i)->flipHorizontaly(true);
		}
		EntityManager::getInstance()->updateDinoRender(DinoAction::Walk);
	}
	// Right
	if (InputManager::getInstance()->isKeyPressed(IND_KEYRIGHT) && !pDino->isContactingRight()) {
		// Physics
		pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(impulse, 0.f), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
		// Render : flip to the right all render entities
		for(size_t i = 0; i < EntityManager::getInstance()->getRenderDino().size(); ++i) {
			if(EntityManager::getInstance()->getRenderDino().at(i) != NULL)
				EntityManager::getInstance()->getRenderDino().at(i)->flipHorizontaly(false);
		}
		EntityManager::getInstance()->updateDinoRender(DinoAction::Walk);
	}
	// Up
	if (InputManager::getInstance()->isKeyPressed(IND_KEYUP) && pDino->getNumContacts() > 0 && pDino->isContactingBelow()) {
		// Physics
		float force = impulse / (1/60.0); //f = mv/t
	    pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(pDino->getLinearVelocity().x, -force), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
	    // Sound
		SoundManager::getInstance()->play(sDinoArray[DinoAction::Jump]->getIndexSound());
	}
	if (InputManager::getInstance()->isKeyPressed(IND_KEYDOWN)) {
		// Physics
		pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(0.f, impulse), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
	}

	// If no movements
	if(EntityManager::getInstance()->getPhysicalDino()->getLinearVelocity().x == 0) {
		EntityManager::getInstance()->updateDinoRender(DinoAction::Stop);
	}

	/***********/
	/*  Death  */
	/***********/

	// std::cout << "Velocity : " << pDino->getLinearVelocity().x << " - " << pDino->getLinearVelocity().y << std::endl;
	// if(pDino->getLinearVelocity().y >= DEATH_VELOCITY) {
	// 	std::cout << "Tou est mort ! ;) " << std::endl;
	// 	EntityManager::getInstance()->killDino(DinoAction::Die);

	// 	loadLevel(MenuManager::getInstance()->getLevelToLoad().c_str());

	// }

	/****************************/
	/*  Camera zoom (for debug) */
	/****************************/

	if (InputManager::getInstance()->isKeyPressed(IND_S)){
		float newZoom = m_pRender->getZoom()+0.005;
		m_pRender->setZoom(newZoom);
	}
	else if (InputManager::getInstance()->isKeyPressed(IND_Q)){
		float newZoom = m_pRender->getZoom()-0.005;
		m_pRender->setZoom(newZoom);
	}
	else if (InputManager::getInstance()->isKeyPressed(IND_D)){
		m_pRender->setZoom(1);
	}

	/********************/
	/* Camera movements */
	/********************/

	m_pRender->setCamera();
	m_pRender->setCameraPosition(pDino->getPosition().x, pDino->getPosition().y);

	/********************/
	/*  Update entities */
	/********************/

	EntityManager::getInstance()->updateEntities();

	/********************/
	/*     Powers       */
	/********************/

	EntityManager::getInstance()->executePowers();

	/********************/
	/*  Manage render   */
	/********************/

	m_pRender->clearViewPort(60, 60, 60);
	m_pRender->beginScene();
		EntityManager::getInstance()->renderEntities();
		//test hitbox
		debugPhysicalEntities();
		//debugRenderEntities();
	m_pRender->endScene();

	/********************/
	/*      Pause       */
	/********************/

	if (InputManager::getInstance()->onKeyPress(IND_ESCAPE)) {
		switchToMenu();
	}

	/***********************/
	/*  Detect level exit  */
	/***********************/

	float exitX = EntityManager::getInstance()->getExitCoordinates()[0];
	float exitY = EntityManager::getInstance()->getExitCoordinates()[1];

	if(abs(exitX - pDino->getPosition().x) < 10 && abs(exitY - pDino->getPosition().y) < 10) {
		fprintf(stderr, "You finished this level !\n");
	}
}

void GameManager::updateMenu() {
	//Forward inputs

	//The following offsets are necessary to the mouse pointer to click on the pause menu
	//because it's not the same coordinate space
	int offsetX = 0;
	int offsetY = 0;
	if(MenuManager::getInstance()->isDisplayingPauseState()){
		PhysicalEntity* pDino = EntityManager::getInstance()->getPhysicalDino();
		offsetX = pDino->getPosition().x - m_pWindow->getIND_Window()->getWidth()*0.5;
		offsetY = pDino->getPosition().y - m_pWindow->getIND_Window()->getHeight()*0.5;
	}

	if (InputManager::getInstance()->onKeyPress(IND_KEYDOWN)){
		MenuManager::getInstance()->handleKeyPressed("KEYDOWN");
	}
	else if (InputManager::getInstance()->onKeyPress(IND_KEYUP)){
		MenuManager::getInstance()->handleKeyPressed("KEYUP");
	}
	else if (InputManager::getInstance()->isMouseMotion()){
		// Mouse hover
		MenuManager::getInstance()->handleMouseHover(InputManager::getInstance()->getMouseX()+offsetX, InputManager::getInstance()->getMouseY()+offsetY);
	}
	else if(InputManager::getInstance()->onMouseButtonPress(IND_MBUTTON_LEFT)){
		// Clic
		MenuManager::getInstance()->handleMouseClic(InputManager::getInstance()->getMouseX()+offsetX, InputManager::getInstance()->getMouseY()+offsetY);
	}
	else if (InputManager::getInstance()->onKeyPress(IND_ESCAPE) && MenuManager::getInstance()->isDisplayingPauseState()){
		// Hidding the Pause menu
		MenuManager::getInstance()->setLevelChoosen(false);
		m_bIsInGame = true;
	}

	// The PauseMenu need not to refresh the window in order to displayed upon the game view
	if(!MenuManager::getInstance()->isDisplayingPauseState()){
		m_pRender->clearViewPort(60, 60, 60);
	}
	// Otherwise, all the menus needs to refresh the window
	m_pRender->beginScene();
		MenuManager::getInstance()->renderEntities();
	m_pRender->endScene();

	//manage camera
	m_pRender->setCamera();
	//Manage user decisions
	if(MenuManager::getInstance()->isLevelChoosen()){
		// If the game part needs to be launch
		switchToGame();
		MenuManager::getInstance()->clear();
	}else if (MenuManager::getInstance()->isGoingBackToMenu() && MenuManager::getInstance()->isDisplayingPauseState()){
		// If the user wants to go back to the main menu from the pause menu
		m_pRender->setCameraPosition(m_pWindow->getIND_Window()->getWidth()*0.5, m_pWindow->getIND_Window()->getHeight()*0.5);
		clear();
		switchToMenu();
	}
}

void GameManager::switchToGame() {

	// Reset the menuManager attribut
	MenuManager::getInstance()->setLevelChoosen(false);

	if (m_pLevelManager == NULL) {
		EntityManager::getInstance()->initRender(m_pRender);
		//If no game have been created before then create a new one (from the main menu)
		m_pLevelManager = new LevelManager();
		loadLevel(MenuManager::getInstance()->getLevelToLoad().c_str());
	 	m_bIsInGame = true;
	}
	else {
		m_bIsInGame = true;
	}
}

void GameManager::switchToMenu() {

	//If the MenuManager doesn't exists, means at the first launch or when the user quit the game, then create it.
	if (m_bIsMenu == false) {

		// Retrive data from the player data file
		std::pair<Player*, std::vector<Player*>> playerData = m_pParser->loadPlayerData();

		// Start the menus
		MenuManager::getInstance();
		MenuManager::init(m_pRender, playerData);
		m_bIsMenu = true;

 		// Manage Camera
		m_pRender->setCamera();
 		m_pRender->setCameraPosition(m_pWindow->getIND_Window()->getWidth()*0.5, m_pWindow->getIND_Window()->getHeight()*0.5);

 	}
 	else {
 		// Pause menu
 		std::vector<RenderEntity*> pDinos = EntityManager::getInstance()->getRenderDino();
 		PauseMenu* pPauseMenu = new PauseMenu(MenuManager::getInstance(), pDinos[0]->getPosX(), pDinos[0]	->getPosY());
 		MenuManager::getInstance()->setState(pPauseMenu);
 	}

 	m_bIsInGame = false;
}

void GameManager::loadLevel(const char* mapFile) {
	EntityManager::getInstance()->deleteAllEntities();
	m_pLevelManager->loadLevel(mapFile);
}

void GameManager::debugPhysicalEntities() {
	for (unsigned int idEntity = 0; idEntity < EntityManager::getInstance()->getPhysicalEntityArray().size(); ++idEntity) {
		PhysicalEntity* pEntity = EntityManager::getInstance()->getPhysicalEntityArray()[idEntity];
		if(pEntity != NULL) {
			b2Vec2 topleft;
			topleft.x = pEntity->getPosition().x - pEntity->getWidth()/2;
			topleft.y = pEntity->getPosition().y + pEntity->getHeight()/2;
			b2Vec2 botright;
			botright.x = pEntity->getPosition().x + pEntity->getWidth()/2;
			botright.y = pEntity->getPosition().y - pEntity->getHeight()/2;
			//draw the hitbox in red
			m_pRender->getIND_Render()->blitRectangle(topleft.x, topleft.y, botright.x, botright.y, 255, 0, 0, 255);
			//draw the position
			m_pRender->getIND_Render()->blitRectangle(pEntity->getPosition().x-5, pEntity->getPosition().y+5, pEntity->getPosition().x+5, pEntity->getPosition().y-5, 255, 0, 255, 255);
		}
	}
}

void GameManager::debugRenderEntities() {
	for (unsigned int idEntity = 0; idEntity < EntityManager::getInstance()->getRenderEntityArray().size(); ++idEntity) {
		std::vector<RenderEntity*> entityArray = EntityManager::getInstance()->getRenderEntityArray()[idEntity];
		if(entityArray.size() > 0) {
			for (unsigned int indexEntity = 0; indexEntity < entityArray.size(); ++indexEntity) {
				RenderEntity* rEntity = entityArray[indexEntity];
				b2Vec2 topleft;
				topleft.x = rEntity->getPosX() - rEntity->getWidth()/2;
				topleft.y = rEntity->getPosY() + rEntity->getHeight()/2;
				b2Vec2 botright;
				botright.x = rEntity->getPosX() + rEntity->getWidth()/2;
				botright.y = rEntity->getPosY() - rEntity->getHeight()/2;
				//draw the size in green
				m_pRender->getIND_Render()->blitRectangle(topleft.x, topleft.y, botright.x, botright.y, 0, 255, 0, 255);
				//draw the position
				m_pRender->getIND_Render()->blitRectangle(rEntity->getPosX()-5, rEntity->getPosY()+5, rEntity->getPosX()+5, rEntity->getPosY()-5, 0, 255, 255, 255);
			}
		}
	}
}

}
<|endoftext|>


<commit_before>#pragma once

#include <pqrs/osx/iokit_hid_device_open_checker.hpp>

namespace krbn {
namespace iokit_hid_device_open_checker_utility {
inline void run_checker(void) {
  auto global_wait = pqrs::make_thread_wait();

  std::vector<pqrs::cf::cf_ptr<CFDictionaryRef>> matching_dictionaries{
      pqrs::osx::iokit_hid_manager::make_matching_dictionary(
          pqrs::osx::iokit_hid_usage_page_generic_desktop,
          pqrs::osx::iokit_hid_usage_generic_desktop_keyboard),

      pqrs::osx::iokit_hid_manager::make_matching_dictionary(
          pqrs::osx::iokit_hid_usage_page_generic_desktop,
          pqrs::osx::iokit_hid_usage_generic_desktop_mouse),

      pqrs::osx::iokit_hid_manager::make_matching_dictionary(
          pqrs::osx::iokit_hid_usage_page_generic_desktop,
          pqrs::osx::iokit_hid_usage_generic_desktop_pointer),
  };

  auto checker = std::make_unique<pqrs::osx::iokit_hid_device_open_checker>(pqrs::dispatcher::extra::get_shared_dispatcher(),
                                                                            matching_dictionaries);

  checker->device_open_permitted.connect([&] {
    global_wait->notify();
  });

  checker->device_open_forbidden.connect([&] {
    global_wait->notify();
  });

  checker->async_start();

  global_wait->wait_notice();
}
} // namespace iokit_hid_device_open_checker_utility
} // namespace krbn
<commit_msg>return bool @ iokit_hid_device_open_checker_utility::run_checker<commit_after>#pragma once

#include <pqrs/osx/iokit_hid_device_open_checker.hpp>

namespace krbn {
namespace iokit_hid_device_open_checker_utility {
inline bool run_checker(void) {
  bool result = true;

  auto global_wait = pqrs::make_thread_wait();

  std::vector<pqrs::cf::cf_ptr<CFDictionaryRef>> matching_dictionaries{
      pqrs::osx::iokit_hid_manager::make_matching_dictionary(
          pqrs::osx::iokit_hid_usage_page_generic_desktop,
          pqrs::osx::iokit_hid_usage_generic_desktop_keyboard),

      pqrs::osx::iokit_hid_manager::make_matching_dictionary(
          pqrs::osx::iokit_hid_usage_page_generic_desktop,
          pqrs::osx::iokit_hid_usage_generic_desktop_mouse),

      pqrs::osx::iokit_hid_manager::make_matching_dictionary(
          pqrs::osx::iokit_hid_usage_page_generic_desktop,
          pqrs::osx::iokit_hid_usage_generic_desktop_pointer),
  };

  auto checker = std::make_unique<pqrs::osx::iokit_hid_device_open_checker>(pqrs::dispatcher::extra::get_shared_dispatcher(),
                                                                            matching_dictionaries);

  checker->device_open_permitted.connect([&] {
    result = true;
    global_wait->notify();
  });

  checker->device_open_forbidden.connect([&] {
    result = false;
    global_wait->notify();
  });

  checker->async_start();

  global_wait->wait_notice();

  return result;
}
} // namespace iokit_hid_device_open_checker_utility
} // namespace krbn
<|endoftext|>