<commit_before>#include "SteamWebAPI.h"

std::string SteamWebAPI::getMatchHistory(std::string numMatches){
	std::string url = std::string("https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/V001/?format=XML");
	url.append(std::string("&key=").append(API_KEY));
	url.append(std::string("&account_id=").append(ACCOUNT_ID));
	url.append(std::string("&matches_requested=").append(numMatches));
	return getSteamXML(url, "DOTARAIN-MatchHistory.xml");
}

std::string SteamWebAPI::getMatchDetails(std::string matchID){
	std::string url = std::string("https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?format=XML");
	url.append(std::string("&key=").append(API_KEY));
	url.append(std::string("&match_id=").append(matchID));
	return getSteamXML(url, "DOTARAIN-MatchDetails");
}

std::string SteamWebAPI::getHeroes(){
	std::string url = std::string("https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?format=XML");
	url.append(std::string("&key=").append(API_KEY));
	url.append("&language=en_us");
	return getSteamXML(url, "DOTARAIN-Heroes.xml");
}

/*Returns full path to file.
TODO: Check if the file is older than 5-10 minutes, if not just return file path
*/
std::string SteamWebAPI::getSteamXML(std::string URL, std::string filename){
	std::string path = std::string("C:\\Windows\\Temp\\").append(filename);

	HANDLE file = CreateFile(s2ws(path).c_str(),(GENERIC_READ | GENERIC_WRITE), 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

	//checking to see if the file is still relatively new, new meaning ~10 minutes here
	//TODO: break this into another function
	if(pastThreshold(file)){
		CloseHandle(file);
		return path;
	}

	HINTERNET hOpen = InternetOpen(L"DotaRain", NULL, NULL, NULL, NULL);
	HINTERNET hURL = InternetOpenUrl(hOpen, s2ws(URL).c_str(), NULL, NULL, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, NULL);

	DWORD dwBytesRead =0;
	DWORD dwBytesWritten = 0;
	do {
		char* lpBuffer = new char[2000];
		ZeroMemory(lpBuffer, 2000);
		InternetReadFile(hURL, (LPVOID)lpBuffer, 2000, &dwBytesRead);
		WriteFile(file, (LPVOID)lpBuffer, dwBytesRead, &dwBytesWritten, NULL);
		delete[] lpBuffer;
		lpBuffer = NULL;
	} while (dwBytesRead);

	InternetCloseHandle(hURL);
	InternetCloseHandle(hOpen);
	CloseHandle(file);
	return path;
}

bool SteamWebAPI::pastThreshold(HANDLE file){
	FILETIME modTime;
	SYSTEMTIME modSysTime;
	GetFileTime(file, 0, 0, &modTime);
	FileTimeToSystemTime(&modTime, &modSysTime);

	SYSTEMTIME currentTime;
	GetSystemTime(&currentTime);

	if(currentTime.wDay > modSysTime.wDay)
		return false;

	else if(currentTime.wHour == modSysTime.wHour && currentTime.wMinute-modSysTime.wMinute < threshhold)
		return false;

	else if(currentTime.wHour > modSysTime.wHour && (currentTime.wMinute-60)+(modSysTime.wMinute) < threshhold)
		return false;

	return true;
}<commit_msg>fixed bug in threshhold function<commit_after>#include "SteamWebAPI.h"

std::string SteamWebAPI::getMatchHistory(std::string numMatches){
	std::string url = std::string("https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/V001/?format=XML");
	url.append(std::string("&key=").append(API_KEY));
	url.append(std::string("&account_id=").append(ACCOUNT_ID));
	url.append(std::string("&matches_requested=").append(numMatches));
	return getSteamXML(url, "DOTARAIN-MatchHistory.xml");
}

std::string SteamWebAPI::getMatchDetails(std::string matchID){
	std::string url = std::string("https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?format=XML");
	url.append(std::string("&key=").append(API_KEY));
	url.append(std::string("&match_id=").append(matchID));
	return getSteamXML(url, "DOTARAIN-MatchDetails");
}

std::string SteamWebAPI::getHeroes(){
	std::string url = std::string("https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?format=XML");
	url.append(std::string("&key=").append(API_KEY));
	url.append("&language=en_us");
	return getSteamXML(url, "DOTARAIN-Heroes.xml");
}

/*Returns full path to file.
TODO: Check if the file is older than 5-10 minutes, if not just return file path
*/
std::string SteamWebAPI::getSteamXML(std::string URL, std::string filename){
	std::string path = std::string("C:\\Windows\\Temp\\").append(filename);

	HANDLE file = CreateFile(s2ws(path).c_str(),(GENERIC_READ | GENERIC_WRITE), 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

	//checking to see if the file is still relatively new, new meaning ~10 minutes here
	//TODO: break this into another function
	if(!pastThreshold(file)){
		std::cout << "No need to create new file" << std::endl;
		CloseHandle(file);
		return path;
	}
	std::cout << "Creating new file" << std::endl;

	HINTERNET hOpen = InternetOpen(L"DotaRain", NULL, NULL, NULL, NULL);
	HINTERNET hURL = InternetOpenUrl(hOpen, s2ws(URL).c_str(), NULL, NULL, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, NULL);

	DWORD dwBytesRead =0;
	DWORD dwBytesWritten = 0;
	do {
		char* lpBuffer = new char[2000];
		ZeroMemory(lpBuffer, 2000);
		InternetReadFile(hURL, (LPVOID)lpBuffer, 2000, &dwBytesRead);
		WriteFile(file, (LPVOID)lpBuffer, dwBytesRead, &dwBytesWritten, NULL);
		delete[] lpBuffer;
		lpBuffer = NULL;
	} while (dwBytesRead);

	InternetCloseHandle(hURL);
	InternetCloseHandle(hOpen);
	CloseHandle(file);
	return path;
}

bool SteamWebAPI::pastThreshold(HANDLE file){
	FILETIME modTime;
	SYSTEMTIME modSysTime;
	GetFileTime(file, 0, 0, &modTime);
	FileTimeToSystemTime(&modTime, &modSysTime);

	SYSTEMTIME currentTime;
	GetSystemTime(&currentTime);

	if(currentTime.wDay > modSysTime.wDay)
		return false;

	else if(currentTime.wHour == modSysTime.wHour && currentTime.wMinute-modSysTime.wMinute < threshhold)
		return false;

	else if(currentTime.wHour > modSysTime.wHour && (currentTime.wMinute)+(60-modSysTime.wMinute) < threshhold)
		return false;

	return true;
}<|endoftext|>


<commit_before>/*
 * cclive Copyright (C) 2009 Toni Gundogdu. This file is part of cclive.
 *
 * cclive is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * cclive is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <string>
#include <vector>

#include "except.h"
#include "video.h"
#include "util.h"
#include "singleton.h"
#include "curl.h"
#include "hosthandler.h"

const bool
LiveleakHandler::isHost(std::string url) {
    props.setHost   ("lleak");
    props.setDomain ("liveleak.com");
    return Util::toLower(url).find(props.getDomain())
        != std::string::npos;
}

void
LiveleakHandler::parseId() {
    const char *begin = "token=";
    const char *end   = "&";

    props.setId( Util::subStr(pageContent, begin, end) );
}

void
LiveleakHandler::parseLink() {
    const char *cpathBegin = "'config','";
    const char *cpathEnd   = "'";

    std::string confPath =
        Util::subStr(pageContent, cpathBegin, cpathEnd);

    curlmgr.unescape(confPath);

    std::string config =
        curlmgr.fetchToMem(confPath, "config");

    const char *plBegin = "<file>";
    const char *plEnd   = "</file>";

    std::string plPath =
        Util::subStr(config, plBegin, plEnd);

    curlmgr.unescape(plPath);

    std::string playlist =
        curlmgr.fetchToMem(plPath, "playlist");

    const char *linkBegin = "<location>";
    const char *linkEnd   = "</location>";

    props.setLink( Util::subStr(playlist, linkBegin, linkEnd) );
}
<commit_msg>Fix: liveleak id parsing.<commit_after>/*
 * cclive Copyright (C) 2009 Toni Gundogdu. This file is part of cclive.
 *
 * cclive is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * cclive is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <string>
#include <vector>

#include "except.h"
#include "video.h"
#include "util.h"
#include "singleton.h"
#include "curl.h"
#include "hosthandler.h"

const bool
LiveleakHandler::isHost(std::string url) {
    props.setHost   ("lleak");
    props.setDomain ("liveleak.com");
    return Util::toLower(url).find(props.getDomain())
        != std::string::npos;
}

void
LiveleakHandler::parseId() {
    const char *begin = "token=";
    const char *end   = "'";

    props.setId( Util::subStr(pageContent, begin, end) );
}

void
LiveleakHandler::parseLink() {
    const char *cpathBegin = "'config','";
    const char *cpathEnd   = "'";

    std::string confPath =
        Util::subStr(pageContent, cpathBegin, cpathEnd);

    curlmgr.unescape(confPath);

    std::string config =
        curlmgr.fetchToMem(confPath, "config");

    const char *plBegin = "<file>";
    const char *plEnd   = "</file>";

    std::string plPath =
        Util::subStr(config, plBegin, plEnd);

    curlmgr.unescape(plPath);

    std::string playlist =
        curlmgr.fetchToMem(plPath, "playlist");

    const char *linkBegin = "<location>";
    const char *linkEnd   = "</location>";

    props.setLink( Util::subStr(playlist, linkBegin, linkEnd) );
}
<|endoftext|>


<commit_before>/// \file AddTaskEMCALPi0Calibration.C
/// \brief Configuration of task AliAnalysisTaskEMCALPi0CalibSelection.
///
/// Configuration of task AliAnalysisTaskEMCALPi0CalibSelection, which fills invariant mass
/// histograms for each of the EMCal channels. It has to be executed in several iterations.
///
/// The parameters for the analysis are:
/// \param calibPath : TString with full path and name of file with calibration factors from previous iteration.
/// \param trigger   : TString, event that triggered must contain this string.
/// \param recalE    : Bool, recalibrate EMCal energy
/// \param recalT    : Bool, recalibrate EMCal time
/// \param rmBad     : Bool, remove bad channels
/// \param nonLin    : Bool, correct cluster non linearity
/// \param simu      : Bool, simulation or data.
/// \param outputFile: TString with name of output file (AnalysisResults.root).
///
/// \author : Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>, (LPSC-CNRS)
///

AliAnalysisTaskEMCALPi0CalibSelection * AddTaskEMCALPi0Calibration(TString calibPath = "", // "alienpath/RecalibrationFactors.root"
                                                                   TString trigger   ="CEMC7",
                                                                   Bool_t  recalE    = kFALSE,
                                                                   Bool_t  recalT    = kFALSE,
                                                                   Bool_t  rmBad     = kFALSE,
                                                                   Bool_t  nonlin    = kTRUE,
                                                                   Bool_t  simu      = kFALSE,
                                                                   TString outputFile = "") // AnalysisResults.root

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

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
  {
    ::Error("AddTaskEMCALPi0Calibration", "This task requires an input event handler");
    return NULL;
  }

  // Create containers for input/output
  AliAnalysisDataContainer *cinput1  = mgr->GetCommonInputContainer();

  AliAnalysisTaskEMCALPi0CalibSelection * pi0calib = new AliAnalysisTaskEMCALPi0CalibSelection ("EMCALPi0Calibration");
  //pi0calib->SetDebugLevel(10);
  //pi0calib->UseFilteredEventAsInput();
  pi0calib->SetClusterMinEnergy(0.3);
  pi0calib->SetClusterMaxEnergy(10.);
  pi0calib->SetClusterLambda0Cuts(0.1,0.5);

  pi0calib->SetAsymmetryCut(1.);
  pi0calib->SetClusterMinNCells(1);
  pi0calib->SetNCellsGroup(0);
  pi0calib->SwitchOnSameSM();

  // Timing cuts
  pi0calib->SetPairDTimeCut(100);   //  20 ns in Run1
  pi0calib->SetClusterMinTime(300); // 560 ns in Run1
  pi0calib->SetClusterMaxTime(800); // 610 ns in Run1

  pi0calib->SetTriggerName(trigger);

  // Cluster recalculation, Reco Utils configuration

  AliEMCALRecoUtils * reco = pi0calib->GetEMCALRecoUtils();

  gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/EMCAL/macros/ConfigureEMCALRecoUtils.C");

  ConfigureEMCALRecoUtils(reco,
                          simu,
                          kTRUE, // exotic
                          nonlin,
                          recalE,
                          rmBad,
                          recalT);

  reco->SetNumberOfCellsFromEMCALBorder(0); // Do not remove clusters in borders!

  // recalibrate energy and do corrections because of Temperature corrections
  pi0calib->SwitchOnClusterCorrection();
  reco->SwitchOnRecalibration();
  reco->SwitchOnRunDepCorrection();

  //reco->Print("");

  //---------------------
  // Geometry alignment
  //---------------------

  pi0calib->SetGeometryName("EMCAL_COMPLETE12SMV1_DCAL_8SM");

  pi0calib->SwitchOnLoadOwnGeometryMatrices();

  //---------------------
  // Pass recalibration factors
  // Do it here or inside the task
  // If previous pass not available (first) avoid recalculate clusters
  //---------------------

  pi0calib->SetCalibrationFilePath(calibPath);
  pi0calib->InitEnergyCalibrationFactors();

  if(calibPath == "")
  {
    if(recalE)
    {
      printf("Get the calibration file from AddTask!!!\n");

      TFile * calibFile = TFile::Open("RecalibrationFactors.root");
      if(!calibFile)
      {
        printf("File %d not found!\n",calibPath.Data());
        return;
      }

      for(Int_t ism = 0; ism < 20; ism++)
      {
        TH2F * h = (TH2F*)calibFile->Get(Form("EMCALRecalFactors_SM%d",ism));

        if(h) reco->SetEMCALChannelRecalibrationFactors(ism,h);
        else  printf("Null histogram with calibration factors for SM%d, 1 will be used in the full SM\n",ism);
      }
    }
    else
    {
      // First iteration, just fill histograms, switch off recalculation
      reco->SwitchOffRecalibration();
      reco->SwitchOffRunDepCorrection(); // Careful!!!, activate when T corrections are available.
      pi0calib->SwitchOffLoadOwnGeometryMatrices();
      pi0calib->SwitchOffRecalculatePosition();
      printf("Pi0 Calibration: Do not recalculate the clusters! First iteration. \n");
    }
  }

  pi0calib->PrintInfo();

  mgr->AddTask(pi0calib);

  if(outputFile.Length()==0) outputFile = AliAnalysisManager::GetCommonFileName();

  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput = mgr->CreateContainer(Form("Pi0Calibration_Trig%s",trigger.Data()),
                                                           TList::Class(), AliAnalysisManager::kOutputContainer,
                                                           outputFile.Data());

//  AliAnalysisDataContainer *cout_cuts = mgr->CreateContainer(Form("ParamsPi0Calibration_Trig%s",trigger.Data()),
//                                                             TList::Class(), AliAnalysisManager::kOutputContainer,
//                                                             "AnalysisParameters.root");

  mgr->AddTask(pi0calib);

  mgr->ConnectInput  (pi0calib, 0, cinput1);
  mgr->ConnectOutput (pi0calib, 1, coutput);
//  mgr->ConnectOutput (pi0calib, 2, cout_cuts);

  return pi0calib;
}
<commit_msg>simplify the logic on the loading of the calibration parameters<commit_after>/// \file AddTaskEMCALPi0Calibration.C
/// \brief Configuration of task AliAnalysisTaskEMCALPi0CalibSelection.
///
/// Configuration of task AliAnalysisTaskEMCALPi0CalibSelection, which fills invariant mass
/// histograms for each of the EMCal channels. It has to be executed in several iterations.
///
/// The parameters for the analysis are:
/// \param calibPath : TString with full path and name of file with calibration factors from previous iteration.
/// \param trigger   : TString, event that triggered must contain this string.
/// \param recalE    : Bool, recalibrate EMCal energy
/// \param recalT    : Bool, recalibrate EMCal time
/// \param rmBad     : Bool, remove bad channels
/// \param nonLin    : Bool, correct cluster non linearity
/// \param simu      : Bool, simulation or data.
/// \param outputFile: TString with name of output file (AnalysisResults.root).
///
/// \author : Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>, (LPSC-CNRS)
///

AliAnalysisTaskEMCALPi0CalibSelection * AddTaskEMCALPi0Calibration(TString calibPath = "", // "alienpath/RecalibrationFactors.root"
                                                                   TString trigger   ="CEMC7",
                                                                   Bool_t  recalE    = kFALSE,
                                                                   Bool_t  recalT    = kFALSE,
                                                                   Bool_t  rmBad     = kFALSE,
                                                                   Bool_t  nonlin    = kTRUE,
                                                                   Bool_t  simu      = kFALSE,
                                                                   TString outputFile = "") // AnalysisResults.root

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

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
  {
    ::Error("AddTaskEMCALPi0Calibration", "This task requires an input event handler");
    return NULL;
  }

  // Create containers for input/output
  AliAnalysisDataContainer *cinput1  = mgr->GetCommonInputContainer();

  AliAnalysisTaskEMCALPi0CalibSelection * pi0calib = new AliAnalysisTaskEMCALPi0CalibSelection ("EMCALPi0Calibration");
  //pi0calib->SetDebugLevel(10);
  //pi0calib->UseFilteredEventAsInput();
  pi0calib->SetClusterMinEnergy(0.3);
  pi0calib->SetClusterMaxEnergy(10.);
  pi0calib->SetClusterLambda0Cuts(0.1,0.5);

  pi0calib->SetAsymmetryCut(1.);
  pi0calib->SetClusterMinNCells(1);
  pi0calib->SetNCellsGroup(0);
  pi0calib->SwitchOnSameSM();

  // Timing cuts
  pi0calib->SetPairDTimeCut(100);   //  20 ns in Run1
  pi0calib->SetClusterMinTime(300); // 560 ns in Run1
  pi0calib->SetClusterMaxTime(800); // 610 ns in Run1

  pi0calib->SetTriggerName(trigger);

  // Cluster recalculation, Reco Utils configuration

  AliEMCALRecoUtils * reco = pi0calib->GetEMCALRecoUtils();

  gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/EMCAL/macros/ConfigureEMCALRecoUtils.C");

  ConfigureEMCALRecoUtils(reco,
                          simu,
                          kTRUE, // exotic
                          nonlin,
                          recalE,
                          rmBad,
                          recalT);

  reco->SetNumberOfCellsFromEMCALBorder(0); // Do not remove clusters in borders!

  // recalibrate energy and do corrections because of Temperature corrections
  pi0calib->SwitchOnClusterCorrection();
  reco->SwitchOnRecalibration();
  reco->SwitchOnRunDepCorrection();

  //reco->Print("");

  //---------------------
  // Geometry alignment
  //---------------------

  pi0calib->SetGeometryName("EMCAL_COMPLETE12SMV1_DCAL_8SM");

  pi0calib->SwitchOnLoadOwnGeometryMatrices();

  //---------------------
  // Pass recalibration factors
  // Do it here or inside the task
  // If previous pass not available (first) avoid recalculate clusters
  //---------------------

  pi0calib->SetCalibrationFilePath(calibPath);

  if(calibPath != "" && recalE)
  {
    printf("AddTaskEMCALPi0Calibration - Get the energy calibration factors from: \n %s \n",calibPath.Data());
    pi0calib->InitEnergyCalibrationFactors();
  }

  if(!recalE)
  {
    // Do not calibrate anything
    // First iteration, just fill histograms, switch off recalculation
    reco->SwitchOffRecalibration();
    reco->SwitchOffRunDepCorrection(); // Careful!!!, activate when T corrections are available.
    pi0calib->SwitchOffLoadOwnGeometryMatrices();
    pi0calib->SwitchOffRecalculatePosition();
    printf("AddTaskEMCALPi0Calibration - Pi0 Calibration: Do not recalculate the clusters! First iteration. \n");
    // check if time is corrected in case of calibration available!!!
  }

  pi0calib->PrintInfo();

  mgr->AddTask(pi0calib);

  if(outputFile.Length()==0) outputFile = AliAnalysisManager::GetCommonFileName();

  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput = mgr->CreateContainer(Form("Pi0Calibration_Trig%s",trigger.Data()),
                                                           TList::Class(), AliAnalysisManager::kOutputContainer,
                                                           outputFile.Data());

//  AliAnalysisDataContainer *cout_cuts = mgr->CreateContainer(Form("ParamsPi0Calibration_Trig%s",trigger.Data()),
//                                                             TList::Class(), AliAnalysisManager::kOutputContainer,
//                                                             "AnalysisParameters.root");

  mgr->AddTask(pi0calib);

  mgr->ConnectInput  (pi0calib, 0, cinput1);
  mgr->ConnectOutput (pi0calib, 1, coutput);
//  mgr->ConnectOutput (pi0calib, 2, cout_cuts);

  return pi0calib;
}
<|endoftext|>


<commit_before>#include "Python.h"
#include "orbit_mpi.hh"

#include <iostream>

//modules headers
#include "wrap_orbit_mpi.hh"
#include "wrap_bunch.hh"
#include "wrap_utils.hh"
#include "wrap_teapotbase.hh"
#include "wrap_trackerrk4.hh"
#include "wrap_spacecharge.hh"
#include "wrap_linacmodule.hh"
#include "wrap_collimator.hh"
#include "wrap_foil.hh"
#include "wrap_rfcavities.hh"
#include "wrap_aperture.hh"

/**
 * The main function that will initialize the MPI and will
 * call the python interpreter: Py_Main(argc,argv).
 */
int main (int argc, char **argv)
{

  //   for(int i = 0; i < argc; i++){
  //     std::cout<<"before i="<<i<<" arg="<<argv[i]<<std::endl;
  //   }

  ORBIT_MPI_Init(&argc,&argv);

  //   for(int i = 0; i < argc; i++){
  //     std::cout<<"after i="<<i<<" arg="<<argv[i]<<std::endl;
  //   }

  //int rank = 0;
  //int size = 0;
  //ORBIT_MPI_Comm_rank(MPI_COMM_WORLD,&rank);
  //ORBIT_MPI_Comm_size(MPI_COMM_WORLD,&size);
  //std::cout<<"rank="<< rank <<" size="<< size <<std::endl;

  //we need this to initialize the extra ORBIT modules
  Py_Initialize();

  //ORBIT module initializations
  wrap_orbit_mpi::initorbit_mpi();
  wrap_orbit_bunch::initbunch();
  wrap_orbit_utils::initutils();
  wrap_teapotbase::initteapotbase();
  wrap_linac::initlinac();
  wrap_collimator::initcollimator();
  wrap_aperture::initaperture();
  wrap_foil::initfoil();
  wrap_rfcavities::initrfcavities();

  //Runge-Kutta tracker package
  inittrackerrk4();

  //space-charge package
  initspacecharge();

  //the python interpreter
  //It will call Py_Initialize() again, but there is no harm
  Py_Main(argc,argv);

  //std::cout << "MPI - stopped" << std::endl;
  ORBIT_MPI_Finalize();

  return 0;

}
<commit_msg>Added field tracker<commit_after>#include "Python.h"
#include "orbit_mpi.hh"

#include <iostream>

//modules headers
#include "wrap_orbit_mpi.hh"
#include "wrap_bunch.hh"
#include "wrap_utils.hh"
#include "wrap_teapotbase.hh"
#include "wrap_trackerrk4.hh"
#include "wrap_spacecharge.hh"
#include "wrap_linacmodule.hh"
#include "wrap_collimator.hh"
#include "wrap_foil.hh"
#include "wrap_rfcavities.hh"
#include "wrap_aperture.hh"
#include "wrap_fieldtracker.hh"

/**
 * The main function that will initialize the MPI and will
 * call the python interpreter: Py_Main(argc,argv).
 */
int main (int argc, char **argv)
{

  //   for(int i = 0; i < argc; i++){
  //     std::cout<<"before i="<<i<<" arg="<<argv[i]<<std::endl;
  //   }

  ORBIT_MPI_Init(&argc,&argv);

  //   for(int i = 0; i < argc; i++){
  //     std::cout<<"after i="<<i<<" arg="<<argv[i]<<std::endl;
  //   }

  //int rank = 0;
  //int size = 0;
  //ORBIT_MPI_Comm_rank(MPI_COMM_WORLD,&rank);
  //ORBIT_MPI_Comm_size(MPI_COMM_WORLD,&size);
  //std::cout<<"rank="<< rank <<" size="<< size <<std::endl;

  //we need this to initialize the extra ORBIT modules
  Py_Initialize();

  //ORBIT module initializations
  wrap_orbit_mpi::initorbit_mpi();
  wrap_orbit_bunch::initbunch();
  wrap_orbit_utils::initutils();
  wrap_teapotbase::initteapotbase();
  wrap_linac::initlinac();
  wrap_collimator::initcollimator();
  wrap_aperture::initaperture();
  wrap_foil::initfoil();
  wrap_rfcavities::initrfcavities();
  wrap_fieldtracker::initfieldtracker();

  //Runge-Kutta tracker package
  inittrackerrk4();

  //space-charge package
  initspacecharge();

  //the python interpreter
  //It will call Py_Initialize() again, but there is no harm
  Py_Main(argc,argv);

  //std::cout << "MPI - stopped" << std::endl;
  ORBIT_MPI_Finalize();

  return 0;

}
<|endoftext|>


<commit_before>/* Copyright (C) The LinBox group
 * ========LICENCE========
 * This file is part of the library LinBox.
 *
 * LinBox is free software: you can redistribute it and/or modify
 * it under the terms of the  GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * ========LICENCE========
 */

/**\file examples/dixondenseelim.C
 @example examples/dixondenseelim.C
 @author Jean-Guillaume.Dumas@univ-grenoble-alpes.fr
 * \brief Dixon System Solving Lifting using dense LU
 * \ingroup examples
 */
#include <iostream>
#include <omp.h>
#include "linbox/matrix/dense-matrix.h"
#include "linbox/solutions/solve.h"
#include "linbox/util/matrix-stream.h"
#include "linbox/solutions/methods.h"

using namespace LinBox;
typedef Givaro::ZRing<Givaro::Integer> Ints;
typedef DenseVector<Ints> ZVector;

struct FixPrime {
    typedef Givaro::Integer Prime_Type;
    const Prime_Type _myprime;
    FixPrime(const Givaro::Integer& i) : _myprime(i) {}
    inline FixPrime &operator ++ () { return *this; }
    const Prime_Type &operator * () const { return randomPrime(); }
    const Prime_Type & randomPrime() const { return _myprime; }
    void setBits(uint64_t bits) {}
    template<class _ModField> void setBitsField() { }
};

int main (int argc, char **argv) {
        // Usage
    if (argc < 2 || argc > 4) {
        std::cerr << "Usage: solve <matrix-file-in-supported-format> [<dense-vector-file>]" << std::endl;
        return 0;
    }

        // File
    std::ifstream input (argv[1]);
    if (!input) { std::cerr << "Error opening matrix file " << argv[1] << std::endl; return -1; }

    std::ifstream invect;
    bool createB = false;
    if (argc == 2) {
        createB = true;
    }
    if (argc == 3) {
        invect.open (argv[2], std::ifstream::in);
        if (!invect) {
            createB = true;
        } else {
            createB = false;
        }
    }

        // Read Integral matrix from File
    Ints ZZ;
    MatrixStream< Ints > ms( ZZ, input );
    DenseMatrix<Ints> A (ms);
    Ints::Element d;
    std::cout << "A is " << A.rowdim() << " by " << A.coldim() << std::endl;

    {
            // Print Matrix

            // Matrix Market
            // std::cout << "A is " << A << std::endl;

            // Maple
        if ( (A.rowdim() < 100) && (A.coldim() < 100) )
            A.write(std::cout << "Pretty A is ", Tag::FileFormat::Maple) << std::endl;
    }

        // Vectors
    ZVector X(ZZ, A.coldim()),B(ZZ, A.rowdim());

    if (createB) {
        std::cerr << "Creating a random {-1,1} vector " << std::endl;
        srand48( BaseTimer::seed() );
        for(ZVector::iterator it=B.begin();
            it != B.end(); ++it)
            if (drand48() <0.5)
                *it = -1;
            else
                *it = 1;
    } else {
        for(ZVector::iterator it=B.begin();
            it != B.end(); ++it)
            invect >> *it;
    }

    {
            // Print RHS

        std::cout << "B is [";
        for(auto it:B) ZZ.write(std::cout, it) << " ";
        std::cout << "]" << std::endl;
    }

    std::cout << "B is " << B.size() << "x1" << std::endl;

    Timer chrono;

        // BlasElimination
    Method::DenseElimination M;
    M.singularity = Singularity::NonSingular;

        //====================================================
        // BEGIN Replacement solve with fixed prime
    Method::Dixon m(M);
    typedef Givaro::Modular<double> Field;
		// 0.7213475205 is an upper approximation of 1/(2log(2))
    size_t bitsize((size_t)( 26-(int)ceil(log((double)A.rowdim())*0.7213475205)));
    Givaro::Integer randomPrime( *(PrimeIterator<>(bitsize)) );

    FixPrime fixedprime( randomPrime );
    DixonSolver<Ints, Field, FixPrime, Method::DenseElimination> rsolve(A.field(), fixedprime);
    std::cout << "Using: " << *fixedprime << " as the fixed p-adic." << std::endl;

    chrono.start();
    rsolve.solveNonsingular(X, d, A, B, false,(int)m.trialsBeforeFailure);

        // END Replacement solve with fixed prime
        //====================================================
//     solve (X, d, A, B, M);
    chrono.stop();

    std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl;

    {
            // Solution size

        std::cout<<"Reduced solution: \n";
        size_t maxbits=0;
        for (size_t i=0;i<A.coldim();++i){
            maxbits=(maxbits > X[i].bitsize() ? maxbits: X[i].bitsize());
        }
        std::cout<<" numerators of size   "<<maxbits<<" bits" << std::endl
                 <<" denominators hold over "<<d.bitsize()<<" bits\n";
    }

    {
			// Check Solution

        VectorDomain<Ints> VD(ZZ);
        MatrixDomain<Ints> MD(ZZ);
        ZVector LHS(ZZ, A.rowdim()), RHS(ZZ, B);
            // check that Ax = d.b
        MD.vectorMul(LHS, A, X);
        VD.mulin(RHS, d);
        if (VD.areEqual(LHS, RHS))
            std::cout << "Ax=b : Yes" << std::endl;
        else
            std::cout << "Ax=b : No" << std::endl;
    }

    {
            // Print Solution

        std::cout << "(DenseElimination) Solution is [";
        for(auto it:X) ZZ.write(std::cout, it) << " ";
        std::cout << "] / ";
        ZZ.write(std::cout, d)<< std::endl;
    }

    return 0;
}

// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<commit_msg>upd text<commit_after>/* Copyright (C) The LinBox group
 * ========LICENCE========
 * This file is part of the library LinBox.
 *
 * LinBox is free software: you can redistribute it and/or modify
 * it under the terms of the  GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * ========LICENCE========
 */

/**\file examples/dixondenseelim.C
 @example examples/dixondenseelim.C
 @author Jean-Guillaume.Dumas@univ-grenoble-alpes.fr
 * \brief Dixon System Solving Lifting using dense LU
 * \ingroup examples
 */
#include <iostream>
#include <omp.h>
#include "linbox/matrix/dense-matrix.h"
#include "linbox/solutions/solve.h"
#include "linbox/util/matrix-stream.h"
#include "linbox/solutions/methods.h"

using namespace LinBox;
typedef Givaro::ZRing<Givaro::Integer> Ints;
typedef DenseVector<Ints> ZVector;

struct FixPrime {
    typedef Givaro::Integer Prime_Type;
    const Prime_Type _myprime;
    FixPrime(const Givaro::Integer& i) : _myprime(i) {}
    inline FixPrime &operator ++ () { return *this; }
    const Prime_Type &operator * () const { return randomPrime(); }
    const Prime_Type & randomPrime() const { return _myprime; }
    void setBits(uint64_t bits) {}
    template<class _ModField> void setBitsField() { }
};

int main (int argc, char **argv) {
        // Usage
    if (argc < 2 || argc > 4) {
        std::cerr << "Usage: solve <matrix-file-in-supported-format> [<dense-vector-file>]" << std::endl;
        return 0;
    }

        // File
    std::ifstream input (argv[1]);
    if (!input) { std::cerr << "Error opening matrix file " << argv[1] << std::endl; return -1; }

    std::ifstream invect;
    bool createB = false;
    if (argc == 2) {
        createB = true;
    }
    if (argc == 3) {
        invect.open (argv[2], std::ifstream::in);
        if (!invect) {
            createB = true;
        } else {
            createB = false;
        }
    }

        // Read Integral matrix from File
    Ints ZZ;
    MatrixStream< Ints > ms( ZZ, input );
    DenseMatrix<Ints> A (ms);
    Ints::Element d;
    std::cout << "A is " << A.rowdim() << " by " << A.coldim() << std::endl;

    {
            // Print Matrix

            // Matrix Market
            // std::cout << "A is " << A << std::endl;

            // Maple
        if ( (A.rowdim() < 100) && (A.coldim() < 100) )
            A.write(std::cout << "Pretty A is ", Tag::FileFormat::Maple) << std::endl;
    }

        // Vectors
    ZVector X(ZZ, A.coldim()),B(ZZ, A.rowdim());

    if (createB) {
        std::cerr << "Creating a random {-1,1} vector " << std::endl;
        srand48( BaseTimer::seed() );
        for(ZVector::iterator it=B.begin();
            it != B.end(); ++it)
            if (drand48() <0.5)
                *it = -1;
            else
                *it = 1;
    } else {
        for(ZVector::iterator it=B.begin();
            it != B.end(); ++it)
            invect >> *it;
    }

    {
            // Print RHS

        std::cout << "B is [";
        for(auto it:B) ZZ.write(std::cout, it) << " ";
        std::cout << "]" << std::endl;
    }

    std::cout << "B is " << B.size() << "x1" << std::endl;

    Timer chrono;

        // BlasElimination
    Method::DenseElimination M;
    M.singularity = Singularity::NonSingular;

        //====================================================
        // BEGIN Replacement solve with fixed prime
    Method::Dixon m(M);
    typedef Givaro::Modular<double> Field;
		// 0.7213475205 is an upper approximation of 1/(2log(2))
    size_t bitsize((size_t)( 26-(int)ceil(log((double)A.rowdim())*0.7213475205)));
    Givaro::Integer randomPrime( *(PrimeIterator<>(bitsize)) );

    FixPrime fixedprime( randomPrime );
    DixonSolver<Ints, Field, FixPrime, Method::DenseElimination> rsolve(A.field(), fixedprime);
    std::cout << "Using: " << *fixedprime << " as the fixed p-adic." << std::endl;

    chrono.start();
    rsolve.solveNonsingular(X, d, A, B, false,(int)m.trialsBeforeFailure);

        // END Replacement solve with fixed prime
        //====================================================
//     solve (X, d, A, B, M);
    chrono.stop();

    std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl;

    {
            // Solution size

        std::cout<<"Reduced solution: \n";
        size_t maxbits=0;
        for (size_t i=0;i<A.coldim();++i){
            maxbits=(maxbits > X[i].bitsize() ? maxbits: X[i].bitsize());
        }
        std::cout<<" numerators of size   "<<maxbits<<" bits" << std::endl
                 <<" denominators hold over "<<d.bitsize()<<" bits\n";
    }

    {
			// Check Solution

        VectorDomain<Ints> VD(ZZ);
        MatrixDomain<Ints> MD(ZZ);
        ZVector LHS(ZZ, A.rowdim()), RHS(ZZ, B);
            // check that Ax = d.b
        MD.vectorMul(LHS, A, X);
        VD.mulin(RHS, d);
        if (VD.areEqual(LHS, RHS))
            std::cout << "Ax=d.b : Yes" << std::endl;
        else
            std::cout << "Ax=d.b : No" << std::endl;
    }

    {
            // Print Solution

        std::cout << "(DenseElimination) Solution is [";
        for(auto it:X) ZZ.write(std::cout, it) << " ";
        std::cout << "] / ";
        ZZ.write(std::cout, d)<< std::endl;
    }

    return 0;
}

// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<|endoftext|>


<commit_before>
#include "polyimport.h"
#include "PolyPolygon.h"
#include "OSBasics.h"

using namespace Polycode;

const struct aiScene* scene = NULL;
bool hasWeights = false;
vector<aiBone*> bones;
unsigned int numBones = 0;

unsigned int addBone(aiBone *bone) {
	for(int i=0; i < bones.size(); i++) {
		if(bones[i]->mName == bone->mName)
			return i;
	}
	bones.push_back(bone);
	return bones.size()-1;
}

void addToMesh(Polycode::Mesh *tmesh, const struct aiScene *sc, const struct aiNode* nd, bool swapZY) {
	int i;
	unsigned int n = 0, t;
	// draw all meshes assigned to this node

	for (; n < nd->mNumMeshes; ++n) {
		const struct aiMesh* mesh = scene->mMeshes[nd->mMeshes[n]];
		printf("Importing mesh:%s\n", mesh->mName.data);

		//apply_material(sc->mMaterials[mesh->mMaterialIndex]);

		for (t = 0; t < mesh->mNumFaces; ++t) {
			const struct aiFace* face = &mesh->mFaces[t];
			Polycode::Polygon *poly = new Polycode::Polygon();

			for(i = 0; i < face->mNumIndices; i++) {
				Vertex *vertex = new Vertex();

				int index = face->mIndices[i];
				if(mesh->mColors[0] != NULL) {
					vertex->vertexColor.setColorRGBA(mesh->mColors[0][index].r, mesh->mColors[0][index].g, mesh->mColors[0][index].b, mesh->mColors[0][index].a);
				}

				if(mesh->mNormals != NULL)  {
					if(swapZY)
						vertex->setNormal(mesh->mNormals[index].x, mesh->mNormals[index].z, -mesh->mNormals[index].y);
					else
						vertex->setNormal(mesh->mNormals[index].x, mesh->mNormals[index].y, mesh->mNormals[index].z);
				}

				if(mesh->HasTextureCoords(0))
				{
					vertex->setTexCoord(mesh->mTextureCoords[0][index].x, mesh->mTextureCoords[0][index].y);
				}

				for( unsigned int a = 0; a < mesh->mNumBones; a++) {
					aiBone* bone = mesh->mBones[a];
					unsigned int boneIndex = addBone(bone);

					for( unsigned int b = 0; b < bone->mNumWeights; b++) {
						if(bone->mWeights[b].mVertexId == index) {
							vertex->addBoneAssignment(boneIndex, bone->mWeights[b].mWeight);
							hasWeights = true;
						}
					}
				}

				if(swapZY)
					vertex->set(mesh->mVertices[index].x, mesh->mVertices[index].z, -mesh->mVertices[index].y);
				else
					vertex->set(mesh->mVertices[index].x, mesh->mVertices[index].y, mesh->mVertices[index].z);
				poly->addVertex(vertex);
			}
			tmesh->addPolygon(poly);
		}
	}

	// draw all children
	for (n = 0; n < nd->mNumChildren; ++n) {
		addToMesh(tmesh, sc, nd->mChildren[n], swapZY);
	}
}

int getBoneID(aiString name) {
	for(int i=0; i  < bones.size(); i++) {
		if(bones[i]->mName == name) {
			return i;
		}
	}
	return 666;
}

void addToISkeleton(ISkeleton *skel, IBone *parent, const struct aiScene *sc, const struct aiNode* nd) {
	IBone *bone = new IBone();
	bone->parent = parent;
	bone->name = nd->mName;
	bone->t = nd->mTransformation;

	for(int i=0; i < bones.size(); i++) {
		if(bones[i]->mName == bone->name) {
			bone->bindMatrix = bones[i]->mOffsetMatrix;
		}
	}

	for (int n = 0; n < nd->mNumChildren; ++n) {
		addToISkeleton(skel, bone, sc, nd->mChildren[n]);
	}
	skel->addIBone(bone, getBoneID(bone->name));
}

int exportToFile(const char *fileName, bool swapZY) {
	String fileNameMesh = String(fileName)+".mesh";
	OSFILE *outFile = OSBasics::open(fileNameMesh.c_str(), "wb");
	Polycode::Mesh *mesh = new Polycode::Mesh(Mesh::TRI_MESH);
	addToMesh(mesh, scene, scene->mRootNode, swapZY);
	mesh->saveToFile(outFile);
	OSBasics::close(outFile);

	if(hasWeights) {
		printf("Mesh has weights, exporting skeleton...\n");
		String fileNameSkel = String(fileName)+".skeleton";
		ISkeleton *skeleton = new ISkeleton();

		for (int n = 0; n < scene->mRootNode->mNumChildren; ++n) {
			if(scene->mRootNode->mChildren[n]->mNumChildren > 0) {
				addToISkeleton(skeleton, NULL, scene, scene->mRootNode->mChildren[n]);
			}
		}

		if(scene->HasAnimations()) {
			printf("Importing animations...\n");
			for(int i=0; i < scene->mNumAnimations;i++) {
				aiAnimation *a = scene->mAnimations[i];
				printf("Importing '%s' (%d tracks)\n", a->mName.data, a->mNumChannels);

				IAnimation *anim = new IAnimation();
				anim->tps = a->mTicksPerSecond;
				anim->name = a->mName.data;
				anim->numTracks = a->mNumChannels;
				anim->length = a->mDuration/a->mTicksPerSecond;

				for(int c=0; c < a->mNumChannels; c++) {
					aiNodeAnim *nodeAnim = a->mChannels[c];

					ITrack *track = new ITrack();
					track->nodeAnim = nodeAnim;
					anim->tracks.push_back(track);
				}

				skeleton->addAnimation(anim);

			}
		} else {
			printf("No animations in file...\n");
		}

		skeleton->saveToFile(fileName, swapZY);
	} else {
		printf("No weight data, skipping skeleton export...\n");
	}

	delete mesh;
	return 1;
}

int main(int argc, char **argv) {

	printf("Polycode import tool v0.8.2\n");

	if(argc != 4) {
		printf("\n\nInvalid arguments!\n");
		printf("usage: polyimport <source_file> <output_file> (Swap Z/Y:<true>/<false>) \n\n");
		return 0;
	}

	struct aiLogStream stream;
	stream = aiGetPredefinedLogStream(aiDefaultLogStream_STDOUT,NULL);
	aiAttachLogStream(&stream);

	printf("Loading %s...\n", argv[1]);
	scene = aiImportFile(argv[1],aiProcessPreset_TargetRealtime_Quality);

	exportToFile(argv[2], strcmp(argv[3], "true") == 0);

	aiReleaseImport(scene);
	return 1;
}
<commit_msg>Fix for polyimport on Linux<commit_after>
#include "polyimport.h"
#include "PolyPolygon.h"
#include "OSBasics.h"

using namespace Polycode;

const struct aiScene* scene = NULL;
bool hasWeights = false;
vector<aiBone*> bones;
unsigned int numBones = 0;

unsigned int addBone(aiBone *bone) {
	for(int i=0; i < bones.size(); i++) {
		if(bones[i]->mName == bone->mName)
			return i;
	}
	bones.push_back(bone);
	return bones.size()-1;
}

void addToMesh(Polycode::Mesh *tmesh, const struct aiScene *sc, const struct aiNode* nd, bool swapZY) {
	int i;
	unsigned int n = 0, t;
	// draw all meshes assigned to this node

	for (; n < nd->mNumMeshes; ++n) {
		const struct aiMesh* mesh = scene->mMeshes[nd->mMeshes[n]];
		printf("Importing mesh:%s\n", mesh->mName.data);

		//apply_material(sc->mMaterials[mesh->mMaterialIndex]);

		for (t = 0; t < mesh->mNumFaces; ++t) {
			const struct aiFace* face = &mesh->mFaces[t];
			Polycode::Polygon *poly = new Polycode::Polygon();

			for(i = 0; i < face->mNumIndices; i++) {
				Vertex *vertex = new Vertex();

				int index = face->mIndices[i];
				if(mesh->mColors[0] != NULL) {
					vertex->vertexColor.setColorRGBA(mesh->mColors[0][index].r, mesh->mColors[0][index].g, mesh->mColors[0][index].b, mesh->mColors[0][index].a);
				}

				if(mesh->mNormals != NULL)  {
					if(swapZY)
						vertex->setNormal(mesh->mNormals[index].x, mesh->mNormals[index].z, -mesh->mNormals[index].y);
					else
						vertex->setNormal(mesh->mNormals[index].x, mesh->mNormals[index].y, mesh->mNormals[index].z);
				}

				if(mesh->HasTextureCoords(0))
				{
					vertex->setTexCoord(mesh->mTextureCoords[0][index].x, mesh->mTextureCoords[0][index].y);
				}

				for( unsigned int a = 0; a < mesh->mNumBones; a++) {
					aiBone* bone = mesh->mBones[a];
					unsigned int boneIndex = addBone(bone);

					for( unsigned int b = 0; b < bone->mNumWeights; b++) {
						if(bone->mWeights[b].mVertexId == index) {
							vertex->addBoneAssignment(boneIndex, bone->mWeights[b].mWeight);
							hasWeights = true;
						}
					}
				}

				if(swapZY)
					vertex->set(mesh->mVertices[index].x, mesh->mVertices[index].z, -mesh->mVertices[index].y);
				else
					vertex->set(mesh->mVertices[index].x, mesh->mVertices[index].y, mesh->mVertices[index].z);
				poly->addVertex(vertex);
			}
			tmesh->addPolygon(poly);
		}
	}

	// draw all children
	for (n = 0; n < nd->mNumChildren; ++n) {
		addToMesh(tmesh, sc, nd->mChildren[n], swapZY);
	}
}

int getBoneID(aiString name) {
	for(int i=0; i  < bones.size(); i++) {
		if(bones[i]->mName == name) {
			return i;
		}
	}
	return 666;
}

void addToISkeleton(ISkeleton *skel, IBone *parent, const struct aiScene *sc, const struct aiNode* nd) {
	IBone *bone = new IBone();
	bone->parent = parent;
	bone->name = nd->mName;
	bone->t = nd->mTransformation;

	for(int i=0; i < bones.size(); i++) {
		if(bones[i]->mName == bone->name) {
			bone->bindMatrix = bones[i]->mOffsetMatrix;
		}
	}

	for (int n = 0; n < nd->mNumChildren; ++n) {
		addToISkeleton(skel, bone, sc, nd->mChildren[n]);
	}
	skel->addIBone(bone, getBoneID(bone->name));
}

int exportToFile(const char *fileName, bool swapZY) {
	String fileNameMesh = String(fileName)+".mesh";
	OSFILE *outFile = OSBasics::open(fileNameMesh.c_str(), "wb");
	Polycode::Mesh *mesh = new Polycode::Mesh(Mesh::TRI_MESH);
	addToMesh(mesh, scene, scene->mRootNode, swapZY);
	mesh->saveToFile(outFile);
	OSBasics::close(outFile);

	if(hasWeights) {
		printf("Mesh has weights, exporting skeleton...\n");
		String fileNameSkel = String(fileName)+".skeleton";
		ISkeleton *skeleton = new ISkeleton();

		for (int n = 0; n < scene->mRootNode->mNumChildren; ++n) {
			if(scene->mRootNode->mChildren[n]->mNumChildren > 0) {
				addToISkeleton(skeleton, NULL, scene, scene->mRootNode->mChildren[n]);
			}
		}

		if(scene->HasAnimations()) {
			printf("Importing animations...\n");
			for(int i=0; i < scene->mNumAnimations;i++) {
				aiAnimation *a = scene->mAnimations[i];
				printf("Importing '%s' (%d tracks)\n", a->mName.data, a->mNumChannels);

				IAnimation *anim = new IAnimation();
				anim->tps = a->mTicksPerSecond;
				anim->name = a->mName.data;
				anim->numTracks = a->mNumChannels;
				anim->length = a->mDuration/a->mTicksPerSecond;

				for(int c=0; c < a->mNumChannels; c++) {
					aiNodeAnim *nodeAnim = a->mChannels[c];

					ITrack *track = new ITrack();
					track->nodeAnim = nodeAnim;
					anim->tracks.push_back(track);
				}

				skeleton->addAnimation(anim);

			}
		} else {
			printf("No animations in file...\n");
		}

		skeleton->saveToFile(fileName, swapZY);
	} else {
		printf("No weight data, skipping skeleton export...\n");
	}

	delete mesh;
	return 1;
}

int main(int argc, char **argv) {

	printf("Polycode import tool v0.8.2\n");

	if(argc != 4) {
		printf("\n\nInvalid arguments!\n");
		printf("usage: polyimport <source_file> <output_file> (Swap Z/Y:<true>/<false>) \n\n");
		return 0;
	}

	PHYSFS_init(argv[0]);
	struct aiLogStream stream;
	stream = aiGetPredefinedLogStream(aiDefaultLogStream_STDOUT,NULL);
	aiAttachLogStream(&stream);

	printf("Loading %s...\n", argv[1]);
	scene = aiImportFile(argv[1],aiProcessPreset_TargetRealtime_Quality);

	exportToFile(argv[2], strcmp(argv[3], "true") == 0);

	aiReleaseImport(scene);
	return 1;
}
<|endoftext|>


<commit_before>//
//  CRT.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 19/07/2015.
//  Copyright © 2015 Thomas Harte. All rights reserved.
//

#include "CRT.hpp"
#include <stdarg.h>

static const int bufferWidth = 512;
static const int bufferHeight = 512;

using namespace Outputs;

CRT::CRT(int cycles_per_line, int height_of_display, int number_of_buffers, ...)
{
	static const int syncCapacityLineChargeThreshold = 3;
	static const int millisecondsHorizontalRetraceTime = 16;
	static const int scanlinesVerticalRetraceTime = 26;

	// store fundamental display configuration properties
	_height_of_display = height_of_display;
	_cycles_per_line = cycles_per_line;

	// generate timing values implied by the given arbuments
	_hsync_error_window = cycles_per_line >> 5;

	_sync_capacitor_charge_threshold = syncCapacityLineChargeThreshold * cycles_per_line;
	_horizontal_retrace_time = (millisecondsHorizontalRetraceTime * cycles_per_line) >> 6;
	_vertical_retrace_time = scanlinesVerticalRetraceTime * cycles_per_line;

	_scanSpeed.x = 1.0f / (float)cycles_per_line;
	_scanSpeed.y = 1.0f / (float)height_of_display;
	_retraceSpeed.x = 1.0f / (float)_horizontal_retrace_time;
	_retraceSpeed.y = 1.0f / (float)_vertical_retrace_time;

	// generate buffers for signal storage as requested — format is
	// number of buffers, size of buffer 1, size of buffer 2...
	_numberOfBuffers = number_of_buffers;
	_bufferSizes = new int[_numberOfBuffers];
	_buffers = new uint8_t *[_numberOfBuffers];

	va_list va;
	va_start(va, number_of_buffers);
	for(int c = 0; c < _numberOfBuffers; c++)
	{
		_bufferSizes[c] = va_arg(va, int);
		_buffers[c] = new uint8_t[bufferHeight * bufferWidth * _bufferSizes[c]];
	}
	va_end(va);

	// reset pointer into output buffers
	_write_allocation_pointer = 0;

	// reset the run buffer pointer
	_run_pointer = 0;

	// reset raster position
	_rasterPosition.x = _rasterPosition.y = 0.0f;

	// reset flywheel sync
	_expected_next_hsync = cycles_per_line;
	_horizontal_counter = 0;

	// reset the vertical charge capacitor
	_sync_capacitor_charge_level = 0;

	// start off not in horizontal sync, not receiving a sync signal
	_is_receiving_sync = false;
	_is_in_hsync = false;
	_vretrace_counter = 0;
}

CRT::~CRT()
{
	delete[] _bufferSizes;
	for(int c = 0; c < _numberOfBuffers; c++)
	{
		delete[] _buffers[c];
	}
	delete[] _buffers;
}

#pragma mark - Sync loop

CRT::SyncEvent CRT::advance_to_next_sync_event(bool hsync_is_requested, bool vsync_is_charging, int cycles_to_run_for, int *cycles_advanced)
{
	// do we recognise this hsync, thereby adjusting time expectations?
	if ((_horizontal_counter < _hsync_error_window || _horizontal_counter >= _expected_next_hsync - _hsync_error_window) && hsync_is_requested) {
		_did_detect_hsync = true;

		int time_now = (_horizontal_counter < _hsync_error_window) ? _expected_next_hsync + _horizontal_counter : _horizontal_counter;
		_expected_next_hsync = (_expected_next_hsync + time_now) >> 1;
//		printf("to %d for %d\n", _expected_next_hsync, time_now);
	}

	SyncEvent proposedEvent = SyncEvent::None;
	int proposedSyncTime = cycles_to_run_for;

	// have we overrun the maximum permitted number of horizontal syncs for this frame?
	if (!_vretrace_counter)
	{
		float raster_distance = _scanSpeed.y * (float)proposedSyncTime;
		if(_rasterPosition.y < 1.02f && _rasterPosition.y + raster_distance >= 1.02f) {
			proposedSyncTime = (int)(1.02f - _rasterPosition.y) / _scanSpeed.y;
			proposedEvent = SyncEvent::StartVSync;
		}
	}

	// will we end an ongoing hsync?
	if (_horizontal_counter < _horizontal_retrace_time && _horizontal_counter+proposedSyncTime >= _horizontal_retrace_time) {
		proposedSyncTime = _horizontal_retrace_time - _horizontal_counter;
		proposedEvent = SyncEvent::EndHSync;
	}

	// will we start an hsync?
	if (_horizontal_counter + proposedSyncTime >= _expected_next_hsync) {
		proposedSyncTime = _expected_next_hsync - _horizontal_counter;
		proposedEvent = SyncEvent::StartHSync;
	}

	// will an acceptable vertical sync be triggered?
	if (vsync_is_charging && !_vretrace_counter) {
		 if (_sync_capacitor_charge_level < _sync_capacitor_charge_threshold && _sync_capacitor_charge_level + proposedSyncTime >= _sync_capacitor_charge_threshold) {
			proposedSyncTime = _sync_capacitor_charge_threshold - _sync_capacitor_charge_level;
			proposedEvent = SyncEvent::StartVSync;
		 }
	}

	// will an ongoing vertical sync end?
	if (_vretrace_counter > 0) {
		if (_vretrace_counter < proposedSyncTime) {
			proposedSyncTime = _vretrace_counter;
			proposedEvent = SyncEvent::EndVSync;
		}
	}

	*cycles_advanced = proposedSyncTime;
	return proposedEvent;
}

void CRT::advance_cycles(int number_of_cycles, bool hsync_requested, const bool vsync_charging, const CRTRun::Type type, const char *data_type)
{
	// this is safe to keep locally because it accumulates over this run of cycles only
	int buffer_offset = 0;

	while(number_of_cycles) {

		// get the next sync event and its timing; hsync request is instantaneous (being edge triggered) so
		// set it to false for the next run through this loop (if any)
		int next_run_length;
		SyncEvent next_event = advance_to_next_sync_event(hsync_requested, vsync_charging, number_of_cycles, &next_run_length);
		hsync_requested = false;

		// get a run from the allocated list, allocating more if we're about to overrun
		if(_run_pointer >= _all_runs.size())
		{
			_all_runs.resize((_all_runs.size() * 2)+1);
		}

		CRTRun *nextRun = &_all_runs[_run_pointer];
		_run_pointer++;

		// set the type, initial raster position and type of this run
		nextRun->type = type;
		nextRun->start_point.dst_x = _rasterPosition.x;
		nextRun->start_point.dst_y = _rasterPosition.y;
		nextRun->data_type = data_type;

		// if this is a data or level run then store a starting data position
		if(type == CRTRun::Type::Data || type == CRTRun::Type::Level)
		{
			nextRun->start_point.src_x = (_write_target_pointer + buffer_offset) & (bufferWidth - 1);
			nextRun->start_point.src_y = (_write_target_pointer + buffer_offset) / bufferWidth;
		}

		// advance the raster position as dictated by current sync status
		if (_is_in_hsync)
			_rasterPosition.x = std::max(0.0f, _rasterPosition.x - (float)number_of_cycles * _retraceSpeed.x);
		else
			_rasterPosition.x = std::min(1.0f, _rasterPosition.x + (float)number_of_cycles * _scanSpeed.x);

		if (_vretrace_counter > 0)
			_rasterPosition.y = std::max(0.0f, _rasterPosition.y - (float)number_of_cycles * _retraceSpeed.y);
		else
			_rasterPosition.y = std::min(1.0f, _rasterPosition.y + (float)number_of_cycles * _scanSpeed.y);

		// store the final raster position
		nextRun->end_point.dst_x = _rasterPosition.x;
		nextRun->end_point.dst_y = _rasterPosition.y;

		// if this is a data run then advance the buffer pointer
		if(type == CRTRun::Type::Data)
		{
			buffer_offset += next_run_length;
		}

		// if this is a data or level run then store the end point
		if(type == CRTRun::Type::Data || type == CRTRun::Type::Level)
		{
			nextRun->end_point.src_x = (_write_target_pointer + buffer_offset) & (bufferWidth - 1);
			nextRun->end_point.src_y = (_write_target_pointer + buffer_offset) / bufferWidth;
		}

		// decrement the number of cycles left to run for and increment the
		// horizontal counter appropriately
		number_of_cycles -= next_run_length;
		_horizontal_counter += next_run_length;

		// either charge or deplete the vertical retrace capacitor (making sure it stops at 0)
		if (vsync_charging)
			_sync_capacitor_charge_level += next_run_length;
		else
			_sync_capacitor_charge_level = std::max(_sync_capacitor_charge_level - next_run_length, 0);

		// decrement the vertical retrace counter, making sure it stops at 0
		_vretrace_counter = std::max(_vretrace_counter - next_run_length, 0);

		// react to the incoming event...
		switch(next_event) {

			// start of hsync: zero the scanline counter, note that we're now in
			// horizontal sync, increment the lines-in-this-frame counter
			case SyncEvent::StartHSync:
				_horizontal_counter = 0;
				_is_in_hsync = true;
			break;

			// end of horizontal sync: update the flywheel's velocity, note that we're no longer
			// in horizontal sync
			case SyncEvent::EndHSync:
				if (!_did_detect_hsync) {
					_expected_next_hsync = (_expected_next_hsync + (_hsync_error_window >> 1) + _cycles_per_line) >> 1;
				}
				_did_detect_hsync = false;
				_is_in_hsync = false;
			break;

			// start of vertical sync: reset the lines-in-this-frame counter,
			// load the retrace counter with the amount of time it'll take to retrace
			case SyncEvent::StartVSync:
				_vretrace_counter = _vertical_retrace_time;
			break;

			// end of vertical sync: tell the delegate that we finished vertical sync,
			// releasing all runs back into the common pool
			case SyncEvent::EndVSync:
				if(_delegate != nullptr)
					_delegate->crt_did_start_vertical_retrace_with_runs(&_all_runs[0], _run_pointer);
				_run_pointer = 0;
			break;

			default:		break;
		}
	}
}

#pragma mark - delegate

void CRT::set_delegate(CRTDelegate *delegate)
{
	_delegate = delegate;
}

#pragma mark - stream feeding methods

/*
	These all merely channel into advance_cycles, supplying appropriate arguments
*/
void CRT::output_sync(int number_of_cycles)
{
	bool _hsync_requested = !_is_receiving_sync;	// ensure this really is edge triggered; someone calling output_sync twice in succession shouldn't trigger it twice
	_is_receiving_sync = true;
	advance_cycles(number_of_cycles, _hsync_requested, true, CRTRun::Type::Sync, nullptr);
}

void CRT::output_blank(int number_of_cycles)
{
	_is_receiving_sync = false;
	advance_cycles(number_of_cycles, false, false, CRTRun::Type::Blank, nullptr);
}

void CRT::output_level(int number_of_cycles, const char *type)
{
	_is_receiving_sync = false;
	advance_cycles(number_of_cycles, false, false, CRTRun::Type::Level, type);
}

void CRT::output_data(int number_of_cycles, const char *type)
{
	_is_receiving_sync = false;
	advance_cycles(number_of_cycles, false, false, CRTRun::Type::Data, type);
}

#pragma mark - Buffer supply

void CRT::allocate_write_area(int required_length)
{
	int xPos = _write_allocation_pointer & (bufferWidth - 1);
	if (xPos + required_length > bufferWidth)
	{
		_write_allocation_pointer &= ~(bufferWidth - 1);
		_write_allocation_pointer = (_write_allocation_pointer + bufferWidth) & ((bufferHeight-1) * bufferWidth);
	}

	_write_target_pointer = _write_allocation_pointer;
	_write_allocation_pointer += required_length;
}

uint8_t *CRT::get_write_target_for_buffer(int buffer)
{
	return &_buffers[buffer][_write_target_pointer * _bufferSizes[buffer]];
}
<commit_msg>Fix one: vertical scan speed was failing to allow for the number of cycles in a line.<commit_after>//
//  CRT.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 19/07/2015.
//  Copyright © 2015 Thomas Harte. All rights reserved.
//

#include "CRT.hpp"
#include <stdarg.h>

static const int bufferWidth = 512;
static const int bufferHeight = 512;

using namespace Outputs;

CRT::CRT(int cycles_per_line, int height_of_display, int number_of_buffers, ...)
{
	static const int syncCapacityLineChargeThreshold = 3;
	static const int millisecondsHorizontalRetraceTime = 16;
	static const int scanlinesVerticalRetraceTime = 26;

	// store fundamental display configuration properties
	_height_of_display = height_of_display;
	_cycles_per_line = cycles_per_line;

	// generate timing values implied by the given arbuments
	_hsync_error_window = cycles_per_line >> 5;

	_sync_capacitor_charge_threshold = syncCapacityLineChargeThreshold * cycles_per_line;
	_horizontal_retrace_time = (millisecondsHorizontalRetraceTime * cycles_per_line) >> 6;
	_vertical_retrace_time = scanlinesVerticalRetraceTime * cycles_per_line;

	_scanSpeed.x = 1.0f / (float)cycles_per_line;
	_scanSpeed.y = 1.0f / (float)(height_of_display * cycles_per_line);
	_retraceSpeed.x = 1.0f / (float)_horizontal_retrace_time;
	_retraceSpeed.y = 1.0f / (float)_vertical_retrace_time;

	// generate buffers for signal storage as requested — format is
	// number of buffers, size of buffer 1, size of buffer 2...
	_numberOfBuffers = number_of_buffers;
	_bufferSizes = new int[_numberOfBuffers];
	_buffers = new uint8_t *[_numberOfBuffers];

	va_list va;
	va_start(va, number_of_buffers);
	for(int c = 0; c < _numberOfBuffers; c++)
	{
		_bufferSizes[c] = va_arg(va, int);
		_buffers[c] = new uint8_t[bufferHeight * bufferWidth * _bufferSizes[c]];
	}
	va_end(va);

	// reset pointer into output buffers
	_write_allocation_pointer = 0;

	// reset the run buffer pointer
	_run_pointer = 0;

	// reset raster position
	_rasterPosition.x = _rasterPosition.y = 0.0f;

	// reset flywheel sync
	_expected_next_hsync = cycles_per_line;
	_horizontal_counter = 0;

	// reset the vertical charge capacitor
	_sync_capacitor_charge_level = 0;

	// start off not in horizontal sync, not receiving a sync signal
	_is_receiving_sync = false;
	_is_in_hsync = false;
	_vretrace_counter = 0;
}

CRT::~CRT()
{
	delete[] _bufferSizes;
	for(int c = 0; c < _numberOfBuffers; c++)
	{
		delete[] _buffers[c];
	}
	delete[] _buffers;
}

#pragma mark - Sync loop

CRT::SyncEvent CRT::advance_to_next_sync_event(bool hsync_is_requested, bool vsync_is_charging, int cycles_to_run_for, int *cycles_advanced)
{
	// do we recognise this hsync, thereby adjusting time expectations?
	if ((_horizontal_counter < _hsync_error_window || _horizontal_counter >= _expected_next_hsync - _hsync_error_window) && hsync_is_requested) {
		_did_detect_hsync = true;

		int time_now = (_horizontal_counter < _hsync_error_window) ? _expected_next_hsync + _horizontal_counter : _horizontal_counter;
		_expected_next_hsync = (_expected_next_hsync + time_now) >> 1;
//		printf("to %d for %d\n", _expected_next_hsync, time_now);
	}

	SyncEvent proposedEvent = SyncEvent::None;
	int proposedSyncTime = cycles_to_run_for;

	// have we overrun the maximum permitted number of horizontal syncs for this frame?
	if (!_vretrace_counter)
	{
		float raster_distance = _scanSpeed.y * (float)proposedSyncTime;
		if(_rasterPosition.y < 1.02f && _rasterPosition.y + raster_distance >= 1.02f) {
			proposedSyncTime = (int)(1.02f - _rasterPosition.y) / _scanSpeed.y;
			proposedEvent = SyncEvent::StartVSync;
		}
	}

	// will we end an ongoing hsync?
	if (_horizontal_counter < _horizontal_retrace_time && _horizontal_counter+proposedSyncTime >= _horizontal_retrace_time) {
		proposedSyncTime = _horizontal_retrace_time - _horizontal_counter;
		proposedEvent = SyncEvent::EndHSync;
	}

	// will we start an hsync?
	if (_horizontal_counter + proposedSyncTime >= _expected_next_hsync) {
		proposedSyncTime = _expected_next_hsync - _horizontal_counter;
		proposedEvent = SyncEvent::StartHSync;
	}

	// will an acceptable vertical sync be triggered?
	if (vsync_is_charging && !_vretrace_counter) {
		 if (_sync_capacitor_charge_level < _sync_capacitor_charge_threshold && _sync_capacitor_charge_level + proposedSyncTime >= _sync_capacitor_charge_threshold) {
			proposedSyncTime = _sync_capacitor_charge_threshold - _sync_capacitor_charge_level;
			proposedEvent = SyncEvent::StartVSync;
		 }
	}

	// will an ongoing vertical sync end?
	if (_vretrace_counter > 0) {
		if (_vretrace_counter < proposedSyncTime) {
			proposedSyncTime = _vretrace_counter;
			proposedEvent = SyncEvent::EndVSync;
		}
	}

	*cycles_advanced = proposedSyncTime;
	return proposedEvent;
}

void CRT::advance_cycles(int number_of_cycles, bool hsync_requested, const bool vsync_charging, const CRTRun::Type type, const char *data_type)
{
	// this is safe to keep locally because it accumulates over this run of cycles only
	int buffer_offset = 0;

	while(number_of_cycles) {

		// get the next sync event and its timing; hsync request is instantaneous (being edge triggered) so
		// set it to false for the next run through this loop (if any)
		int next_run_length;
		SyncEvent next_event = advance_to_next_sync_event(hsync_requested, vsync_charging, number_of_cycles, &next_run_length);
		hsync_requested = false;

		// get a run from the allocated list, allocating more if we're about to overrun
		if(_run_pointer >= _all_runs.size())
		{
			_all_runs.resize((_all_runs.size() * 2)+1);
		}

		CRTRun *nextRun = &_all_runs[_run_pointer];
		_run_pointer++;

		// set the type, initial raster position and type of this run
		nextRun->type = type;
		nextRun->start_point.dst_x = _rasterPosition.x;
		nextRun->start_point.dst_y = _rasterPosition.y;
		nextRun->data_type = data_type;

		// if this is a data or level run then store a starting data position
		if(type == CRTRun::Type::Data || type == CRTRun::Type::Level)
		{
			nextRun->start_point.src_x = (_write_target_pointer + buffer_offset) & (bufferWidth - 1);
			nextRun->start_point.src_y = (_write_target_pointer + buffer_offset) / bufferWidth;
		}

		// advance the raster position as dictated by current sync status
		if (_is_in_hsync)
			_rasterPosition.x = std::max(0.0f, _rasterPosition.x - (float)number_of_cycles * _retraceSpeed.x);
		else
			_rasterPosition.x = std::min(1.0f, _rasterPosition.x + (float)number_of_cycles * _scanSpeed.x);

		if (_vretrace_counter > 0)
			_rasterPosition.y = std::max(0.0f, _rasterPosition.y - (float)number_of_cycles * _retraceSpeed.y);
		else
			_rasterPosition.y = std::min(1.0f, _rasterPosition.y + (float)number_of_cycles * _scanSpeed.y);

		// store the final raster position
		nextRun->end_point.dst_x = _rasterPosition.x;
		nextRun->end_point.dst_y = _rasterPosition.y;

		// if this is a data run then advance the buffer pointer
		if(type == CRTRun::Type::Data)
		{
			buffer_offset += next_run_length;
		}

		// if this is a data or level run then store the end point
		if(type == CRTRun::Type::Data || type == CRTRun::Type::Level)
		{
			nextRun->end_point.src_x = (_write_target_pointer + buffer_offset) & (bufferWidth - 1);
			nextRun->end_point.src_y = (_write_target_pointer + buffer_offset) / bufferWidth;
		}

		// decrement the number of cycles left to run for and increment the
		// horizontal counter appropriately
		number_of_cycles -= next_run_length;
		_horizontal_counter += next_run_length;

		// either charge or deplete the vertical retrace capacitor (making sure it stops at 0)
		if (vsync_charging)
			_sync_capacitor_charge_level += next_run_length;
		else
			_sync_capacitor_charge_level = std::max(_sync_capacitor_charge_level - next_run_length, 0);

		// decrement the vertical retrace counter, making sure it stops at 0
		_vretrace_counter = std::max(_vretrace_counter - next_run_length, 0);

		// react to the incoming event...
		switch(next_event) {

			// start of hsync: zero the scanline counter, note that we're now in
			// horizontal sync, increment the lines-in-this-frame counter
			case SyncEvent::StartHSync:
				_horizontal_counter = 0;
				_is_in_hsync = true;
			break;

			// end of horizontal sync: update the flywheel's velocity, note that we're no longer
			// in horizontal sync
			case SyncEvent::EndHSync:
				if (!_did_detect_hsync) {
					_expected_next_hsync = (_expected_next_hsync + (_hsync_error_window >> 1) + _cycles_per_line) >> 1;
				}
				_did_detect_hsync = false;
				_is_in_hsync = false;
			break;

			// start of vertical sync: reset the lines-in-this-frame counter,
			// load the retrace counter with the amount of time it'll take to retrace
			case SyncEvent::StartVSync:
				_vretrace_counter = _vertical_retrace_time;
			break;

			// end of vertical sync: tell the delegate that we finished vertical sync,
			// releasing all runs back into the common pool
			case SyncEvent::EndVSync:
				if(_delegate != nullptr)
					_delegate->crt_did_start_vertical_retrace_with_runs(&_all_runs[0], _run_pointer);
				_run_pointer = 0;
			break;

			default:		break;
		}
	}
}

#pragma mark - delegate

void CRT::set_delegate(CRTDelegate *delegate)
{
	_delegate = delegate;
}

#pragma mark - stream feeding methods

/*
	These all merely channel into advance_cycles, supplying appropriate arguments
*/
void CRT::output_sync(int number_of_cycles)
{
	bool _hsync_requested = !_is_receiving_sync;	// ensure this really is edge triggered; someone calling output_sync twice in succession shouldn't trigger it twice
	_is_receiving_sync = true;
	advance_cycles(number_of_cycles, _hsync_requested, true, CRTRun::Type::Sync, nullptr);
}

void CRT::output_blank(int number_of_cycles)
{
	_is_receiving_sync = false;
	advance_cycles(number_of_cycles, false, false, CRTRun::Type::Blank, nullptr);
}

void CRT::output_level(int number_of_cycles, const char *type)
{
	_is_receiving_sync = false;
	advance_cycles(number_of_cycles, false, false, CRTRun::Type::Level, type);
}

void CRT::output_data(int number_of_cycles, const char *type)
{
	_is_receiving_sync = false;
	advance_cycles(number_of_cycles, false, false, CRTRun::Type::Data, type);
}

#pragma mark - Buffer supply

void CRT::allocate_write_area(int required_length)
{
	int xPos = _write_allocation_pointer & (bufferWidth - 1);
	if (xPos + required_length > bufferWidth)
	{
		_write_allocation_pointer &= ~(bufferWidth - 1);
		_write_allocation_pointer = (_write_allocation_pointer + bufferWidth) & ((bufferHeight-1) * bufferWidth);
	}

	_write_target_pointer = _write_allocation_pointer;
	_write_allocation_pointer += required_length;
}

uint8_t *CRT::get_write_target_for_buffer(int buffer)
{
	return &_buffers[buffer][_write_target_pointer * _bufferSizes[buffer]];
}
<|endoftext|>


<commit_before>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <arrayfire.h>
#include <af/exception.h>
#include <iostream>

using namespace af;

int main(int argc, char *argv[])
{
    try {
        int device = argc > 1 ? atoi(argv[1]) : 0;
        af::setDevice(device);
        af::info();

        printf("\ncreate a 5-by-3 matrix of random floats on the GPU\n");
        array A = randu(5,3, f32);
        af_print(A);

        printf("element-wise arithmetic\n");
        array B = sin(A) + 1.5;
        af_print(B);

        printf("Fourier transform the result\n");
        array C = fft(B);
        af_print(C);

        printf("grab last row\n");
        array c = C.row(end);
        af_print(c);

        printf("zero out every other column\n");
        B(span, seq(0, end, 2)) = 0;
        printf("negate the first three elements of second column\n");
        B(seq(0, 2), 1) = B(seq(0, 2), 1) * -1;
        af_print(B);

        printf("create 2-by-3 matrix from host data\n");
        float d[] = { 1, 2, 3, 4, 5, 6 };
        array D(2, 3, d, af::afHost);
        af_print(D);

        printf("copy last column onto first\n");
        D.col(0) = D.col(end);
        af_print(D);

        // Sort A
        printf("sort A and print sorted array and corresponding indices\n");
        array E, F;
        sort(E, F, A);
        af_print(E);
        af_print(F);

    } catch (af::exception& e) {
        fprintf(stderr, "%s\n", e.what());
        throw;
    }

    #ifdef WIN32 // pause in Windows
    if (!(argc == 2 && argv[1][0] == '-')) {
        printf("hit [enter]...");
        fflush(stdout);
        getchar();
    }
    #endif
    return 0;
}
<commit_msg>Reorganizing helloworld.cpp<commit_after>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <arrayfire.h>
#include <cstdio>

using namespace af;

int main(int argc, char *argv[])
{
    try {

        // Select a device and display arrayfire info
        int device = argc > 1 ? atoi(argv[1]) : 0;
        af::setDevice(device);
        af::info();

        printf("Create a 5-by-3 matrix of random floats on the GPU\n");
        array A = randu(5,3, f32);
        af_print(A);

        printf("Element-wise arithmetic\n");
        array B = sin(A) + 1.5;
        af_print(B);

        printf("Negate the first three elements of second column\n");
        B(seq(0, 2), 1) = B(seq(0, 2), 1) * -1;
        af_print(B);

        printf("Fourier transform the result\n");
        array C = fft(B);
        af_print(C);

        printf("Grab last row\n");
        array c = C.row(end);
        af_print(c);

        printf("Create 2-by-3 matrix from host data\n");
        float d[] = { 1, 2, 3, 4, 5, 6 };
        array D(2, 3, d, af::afHost);
        af_print(D);

        printf("Copy last column onto first\n");
        D.col(0) = D.col(end);
        af_print(D);

        // Sort A
        printf("Sort A and print sorted array and corresponding indices\n");
        array vals, inds;
        sort(vals, inds, A);
        af_print(vals);
        af_print(inds);

    } catch (af::exception& e) {
        fprintf(stderr, "%s\n", e.what());
        throw;
    }

    #ifdef WIN32 // pause in Windows
    if (!(argc == 2 && argv[1][0] == '-')) {
        printf("hit [enter]...");
        fflush(stdout);
        getchar();
    }
    #endif
    return 0;
}
<|endoftext|>


<commit_before>/* bid_request_endpoint_test.cc
   Eric Robert, 9 May 2013
   Copyright (c) 2013 Datacratic Inc.  All rights reserved.

   Tool to test a bid request endpoint.
*/

#include <memory>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>

#include "rtbkit/core/router/router.h"
#include "rtbkit/core/agent_configuration/agent_configuration_service.h"
#include "rtbkit/core/banker/null_banker.h"
#include "rtbkit/plugins/bidding_agent/bidding_agent_cluster.h"
#include "rtbkit/testing/test_agent.h"
#include "rtbkit/soa/service/message_loop.h"
#include "jml/utils/file_functions.h"

using namespace Datacratic;
using namespace RTBKIT;
using namespace std ;

static Json::Value loadJsonFromFile(const std::string & filename) {
    ML::File_Read_Buffer buf(filename);
    return Json::parse(std::string(buf.start(), buf.end()));
}

string tid()
{
    ostringstream oss ;
    oss << "0x" << hex <<  this_thread::get_id();
    return oss.str();
}

int main(int argc, char ** argv)
{
    using namespace boost::program_options;

    int recordCount = 1000;
    std::string recordFile;
    std::string exchangeConfigurationFile = "rtbkit/examples/router-config.json";

    options_description endpoint_options("Bid request endpoint options");
    endpoint_options.add_options()
    ("record-request,r", value<std::string>(&recordFile),
     "filename prefix to record incoming bid request")
    ("record-count,n", value<int>(&recordCount),
     "number of bid request recorded by file")
    ("exchange-configuration,x", value<std::string>(&exchangeConfigurationFile),
     "configuration file with exchange data");

    options_description all_opt;
    all_opt
    .add(endpoint_options);
    all_opt.add_options()
    ("help,h", "print this message");

    variables_map vm;
    store(command_line_parser(argc, argv)
          .options(all_opt)
          .run(),
          vm);
    notify(vm);

    if(vm.count("help")) {
        std::cerr << all_opt << std::endl;
        exit(1);
    }

    std::shared_ptr<ServiceProxies> proxies(new ServiceProxies());

    // The agent config service lets the router know how our agent is
    // configured
    AgentConfigurationService agentConfig(proxies, "config");
    agentConfig.unsafeDisableMonitor();
    agentConfig.init();
    agentConfig.bindTcp();
    agentConfig.start();

    // We need a router for our exchange connector to work
    Router router(proxies, "router");
    router.unsafeDisableMonitor();
    router.init();

    // Set a null banker that blindly approves all bids so that we can
    // bid.
    router.setBanker(std::make_shared<NullBanker>(true));

    // Start the router up
    router.bindTcp();
    router.start();

    // Configure exchange connectors
    Json::Value exchangeConfiguration = loadJsonFromFile(exchangeConfigurationFile);
    for(auto & exchange : exchangeConfiguration) {
        router.startExchange(exchange);
    }

    router.forAllExchanges([&](std::shared_ptr<ExchangeConnector> const & item) {
        item->enableUntil(Date::positiveInfinity());
        if(!recordFile.empty()) {
            std::string filename = item->exchangeName() + "-" + recordFile;
            item->startRequestLogging(filename, recordCount);
        }
    });

    RTBKIT::AgentConfig config;
    config.maxInFlight = 20000;
    config.creatives.push_back(RTBKIT::Creative::sampleLB);
    config.creatives.push_back(RTBKIT::Creative::sampleWS);
    config.creatives.push_back(RTBKIT::Creative::sampleBB);

    // create a router proxy and start it.
    BiddingAgentCluster cluster (proxies, "BAC");
    cluster.start ();

    // create/start/configure 1st agent
    auto bob = make_shared<TestAgent>(proxies, "BOB") ;
    bob->onBidRequest = [&] (
                            double timestamp,
                            const Id & id,
                            std::shared_ptr<BidRequest> br,
                            Bids bids,
                            double timeLeftMs,
                            const Json::Value & augmentations,
                            const WinCostModel & wcm)
    {
        Bid& bid = bids[0];
        bid.bid(bid.availableCreatives[0], USD_CPM(1.234));
        bob->doBid(id, bids, Json::Value(), wcm);
        ML::atomic_inc(bob->numBidRequests);
        cerr << bob->serviceName() << "(" << tid() << ") bid count=" << bob->numBidRequests << endl;
    };

    // create/start/configure 2nd agent
    auto alice = make_shared<TestAgent>(proxies, "ALICE") ;
    alice->onBidRequest = [&] (
                              double timestamp,
                              const Id & id,
                              std::shared_ptr<BidRequest> br,
                              Bids bids,
                              double timeLeftMs,
                              const Json::Value & augmentations,
                              const WinCostModel & wcm)
    {
        Bid& bid = bids[0];
        bid.bid(bid.availableCreatives[0], USD_CPM(1.233));
        alice->doBid(id, bids, Json::Value(), wcm);
        ML::atomic_inc(bob->numBidRequests);
        cerr << alice->serviceName() << "(" << tid() << ") bid count=" << alice->numBidRequests << endl;
    };

    // join agents to our cluster
    // joined agents will be added as source to
    // our the cluster's poll loop;
    cluster.join (bob);
    cluster.join (alice);

    // for each agent A in cluster, will call A.init()
    cluster.init();

    // will start polling in a dedicated thread
    cluster.start ();

    config.account = {"testCampaign", "bobStrategy"};
    cluster[bob]->doConfig(config);

    config.account = {"testCampaign", "aliceStrategy"};
    cluster[alice]->doConfig(config);

    for(;;)
    {
        ML::sleep(10.0);

        std::cerr << "----------[ REPORT ]----------" << std::endl;
        proxies->events->dump(std::cerr);
    }
}

<commit_msg>do not start twice the cluster<commit_after>/* bid_request_endpoint_test.cc
   Eric Robert, 9 May 2013
   Copyright (c) 2013 Datacratic Inc.  All rights reserved.

   Tool to test a bid request endpoint.
*/

#include <memory>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>

#include "rtbkit/core/router/router.h"
#include "rtbkit/core/agent_configuration/agent_configuration_service.h"
#include "rtbkit/core/banker/null_banker.h"
#include "rtbkit/plugins/bidding_agent/bidding_agent_cluster.h"
#include "rtbkit/testing/test_agent.h"
#include "rtbkit/soa/service/message_loop.h"
#include "jml/utils/file_functions.h"

using namespace Datacratic;
using namespace RTBKIT;
using namespace std ;

static Json::Value loadJsonFromFile(const std::string & filename) {
    ML::File_Read_Buffer buf(filename);
    return Json::parse(std::string(buf.start(), buf.end()));
}

string tid()
{
    ostringstream oss ;
    oss << "0x" << hex <<  this_thread::get_id();
    return oss.str();
}

int main(int argc, char ** argv)
{
    using namespace boost::program_options;

    int recordCount = 1000;
    std::string recordFile;
    std::string exchangeConfigurationFile = "rtbkit/examples/router-config.json";

    options_description endpoint_options("Bid request endpoint options");
    endpoint_options.add_options()
    ("record-request,r", value<std::string>(&recordFile),
     "filename prefix to record incoming bid request")
    ("record-count,n", value<int>(&recordCount),
     "number of bid request recorded by file")
    ("exchange-configuration,x", value<std::string>(&exchangeConfigurationFile),
     "configuration file with exchange data");

    options_description all_opt;
    all_opt
    .add(endpoint_options);
    all_opt.add_options()
    ("help,h", "print this message");

    variables_map vm;
    store(command_line_parser(argc, argv)
          .options(all_opt)
          .run(),
          vm);
    notify(vm);

    if(vm.count("help")) {
        std::cerr << all_opt << std::endl;
        exit(1);
    }

    std::shared_ptr<ServiceProxies> proxies(new ServiceProxies());

    // The agent config service lets the router know how our agent is
    // configured
    AgentConfigurationService agentConfig(proxies, "config");
    agentConfig.unsafeDisableMonitor();
    agentConfig.init();
    agentConfig.bindTcp();
    agentConfig.start();

    // We need a router for our exchange connector to work
    Router router(proxies, "router");
    router.unsafeDisableMonitor();
    router.init();

    // Set a null banker that blindly approves all bids so that we can
    // bid.
    router.setBanker(std::make_shared<NullBanker>(true));

    // Start the router up
    router.bindTcp();
    router.start();

    // Configure exchange connectors
    Json::Value exchangeConfiguration = loadJsonFromFile(exchangeConfigurationFile);
    for(auto & exchange : exchangeConfiguration) {
        router.startExchange(exchange);
    }

    router.forAllExchanges([&](std::shared_ptr<ExchangeConnector> const & item) {
        item->enableUntil(Date::positiveInfinity());
        if(!recordFile.empty()) {
            std::string filename = item->exchangeName() + "-" + recordFile;
            item->startRequestLogging(filename, recordCount);
        }
    });

    RTBKIT::AgentConfig config;
    config.maxInFlight = 20000;
    config.creatives.push_back(RTBKIT::Creative::sampleLB);
    config.creatives.push_back(RTBKIT::Creative::sampleWS);
    config.creatives.push_back(RTBKIT::Creative::sampleBB);

    // create a router proxy and start it.
    // will start polling in a dedicated thread
    BiddingAgentCluster cluster (proxies, "BAC");
    cluster.start ();

    // create/start/configure 1st agent
    auto bob = make_shared<TestAgent>(proxies, "BOB") ;
    bob->onBidRequest = [&] (
                            double timestamp,
                            const Id & id,
                            std::shared_ptr<BidRequest> br,
                            Bids bids,
                            double timeLeftMs,
                            const Json::Value & augmentations,
                            const WinCostModel & wcm)
    {
        Bid& bid = bids[0];
        bid.bid(bid.availableCreatives[0], USD_CPM(1.234));
        bob->doBid(id, bids, Json::Value(), wcm);
        ML::atomic_inc(bob->numBidRequests);
        cerr << bob->serviceName() << "(" << tid() << ") bid count=" << bob->numBidRequests << endl;
    };

    // create/start/configure 2nd agent
    auto alice = make_shared<TestAgent>(proxies, "ALICE") ;
    alice->onBidRequest = [&] (
                              double timestamp,
                              const Id & id,
                              std::shared_ptr<BidRequest> br,
                              Bids bids,
                              double timeLeftMs,
                              const Json::Value & augmentations,
                              const WinCostModel & wcm)
    {
        Bid& bid = bids[0];
        bid.bid(bid.availableCreatives[0], USD_CPM(1.233));
        alice->doBid(id, bids, Json::Value(), wcm);
        ML::atomic_inc(bob->numBidRequests);
        cerr << alice->serviceName() << "(" << tid() << ") bid count=" << alice->numBidRequests << endl;
    };

    // join agents to our cluster
    // joined agents will be added as source to
    // our the cluster's poll loop;
    cluster.join (bob);
    cluster.join (alice);

    // for each agent A in cluster, will call A.init()
    cluster.init();

    config.account = {"testCampaign", "bobStrategy"};
    cluster[bob]->doConfig(config);

    config.account = {"testCampaign", "aliceStrategy"};
    cluster[alice]->doConfig(config);

    for(;;)
    {
        ML::sleep(10.0);

        std::cerr << "----------[ REPORT ]----------" << std::endl;
        proxies->events->dump(std::cerr);
    }
}

<|endoftext|>


<commit_before>/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include <TPieSlice.h>

#include <Riostream.h>
#include <TError.h>
#include <TROOT.h>
#include <TVirtualPad.h>
#include <TArc.h>
#include <TMath.h>
#include <TStyle.h>
#include <TLatex.h>
#include <TPaveText.h>
#include <TH1.h>

ClassImp(TPieSlice)

//______________________________________________________________________________
//
// A slice of a piechart, see the TPie class.
//
// This class describe the property of single
//

//______________________________________________________________________________
TPieSlice::TPieSlice() : TNamed(), TAttFill(), TAttLine()
{
   // This is the default constructor, used to create the standard.

   fPie = 0;
   fValue = 1;
   fRadiusOffset = 0;
   fIsActive = kFALSE;
}

//______________________________________________________________________________
TPieSlice::TPieSlice(const char *name, const char *title,
                     TPie *pie, Double_t val) :
                     TNamed(name, title), TAttFill(), TAttLine()
{
   // This constructor create a slice with a particular value.

   fPie = pie;
   fValue = val;
   fRadiusOffset = 0;
   fIsActive = kFALSE;
}

//______________________________________________________________________________
Int_t TPieSlice::DistancetoPrimitive(Int_t /*px*/, Int_t /*py*/)
{
   // Eval if the mouse is over the area associated with this slice.

   Int_t dist = 9999;

   if (fIsActive) {
      dist = 0;
      fIsActive = kFALSE;
      gPad->SetCursor(kCross);
   }

   return dist;
}

//______________________________________________________________________________
Double_t TPieSlice::GetRadiusOffset()
{
   // return the value of the offset in radial direction for this slice.

   return fRadiusOffset;
}

//______________________________________________________________________________
Double_t TPieSlice::GetValue()
{
   // Return the value of this slice.

   return fValue;
}

//______________________________________________________________________________
void TPieSlice::SavePrimitive(ostream &/*out*/, Option_t * /*opts*/)
{
   // Do nothing.
}

//______________________________________________________________________________
void TPieSlice::SetRadiusOffset(Double_t val)
{
   // Set the radial offset of this slice.

   fRadiusOffset = val;
   if (fRadiusOffset<.0) fRadiusOffset = .0;
}

//______________________________________________________________________________
void TPieSlice::SetValue(Double_t val)
{
   // Set the value for this slice.
   // Negative values are changed with its absolute value.

   fValue = val;
   if (fValue<.0) {
      Warning("SetValue","Invalid negative value. Absolute value taken");
      fValue *= -1;
   }

   fPie->MakeSlices(kTRUE);
}
<commit_msg>- From Guido Volpi: Change the cursor shape to point on a slice (Hand instead of Cross)<commit_after>/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include <TPieSlice.h>

#include <Riostream.h>
#include <TError.h>
#include <TROOT.h>
#include <TVirtualPad.h>
#include <TArc.h>
#include <TMath.h>
#include <TStyle.h>
#include <TLatex.h>
#include <TPaveText.h>
#include <TH1.h>

ClassImp(TPieSlice)

//______________________________________________________________________________
//
// A slice of a piechart, see the TPie class.
//
// This class describe the property of single
//

//______________________________________________________________________________
TPieSlice::TPieSlice() : TNamed(), TAttFill(), TAttLine()
{
   // This is the default constructor, used to create the standard.

   fPie = 0;
   fValue = 1;
   fRadiusOffset = 0;
   fIsActive = kFALSE;
}

//______________________________________________________________________________
TPieSlice::TPieSlice(const char *name, const char *title,
                     TPie *pie, Double_t val) :
                     TNamed(name, title), TAttFill(), TAttLine()
{
   // This constructor create a slice with a particular value.

   fPie = pie;
   fValue = val;
   fRadiusOffset = 0;
   fIsActive = kFALSE;
}

//______________________________________________________________________________
Int_t TPieSlice::DistancetoPrimitive(Int_t /*px*/, Int_t /*py*/)
{
   // Eval if the mouse is over the area associated with this slice.

   Int_t dist = 9999;

   if (fIsActive) {
      dist = 0;
      fIsActive = kFALSE;
      gPad->SetCursor(kHand);
   }

   return dist;
}

//______________________________________________________________________________
Double_t TPieSlice::GetRadiusOffset()
{
   // return the value of the offset in radial direction for this slice.

   return fRadiusOffset;
}

//______________________________________________________________________________
Double_t TPieSlice::GetValue()
{
   // Return the value of this slice.

   return fValue;
}

//______________________________________________________________________________
void TPieSlice::SavePrimitive(ostream &/*out*/, Option_t * /*opts*/)
{
   // Do nothing.
}

//______________________________________________________________________________
void TPieSlice::SetRadiusOffset(Double_t val)
{
   // Set the radial offset of this slice.

   fRadiusOffset = val;
   if (fRadiusOffset<.0) fRadiusOffset = .0;
}

//______________________________________________________________________________
void TPieSlice::SetValue(Double_t val)
{
   // Set the value for this slice.
   // Negative values are changed with its absolute value.

   fValue = val;
   if (fValue<.0) {
      Warning("SetValue","Invalid negative value. Absolute value taken");
      fValue *= -1;
   }

   fPie->MakeSlices(kTRUE);
}
<|endoftext|>