<commit_before>#include <string>
#include <fstream>
#include <iostream>
#include <vector>
#include <set>
#include <cmath>

#include <getopt.h>
#include <unistd.h>
#include <time.h>

#include <tvmet/Vector.h>

#include "Node.h"
#include "EvansElastic.h"
#include "LoopShellBody.h"
#include "ProteinBody.h"
#include "ProteinLennardJones.h"
#include "MontecarloProtein.h"
#include "LoopShell.h"
#include "Model.h"
#include "Lbfgsb.h"
#include "CGfast.h"
#include "VoomMath.h"
#include "Utils/PrintingProtein.h"

using namespace voom;
using namespace std;

int main(int argc, char* argv[])
{
  // -------------------------------------------------------------------
  // Setup
  // -------------------------------------------------------------------
  time_t start, end;
  double dif;
  time(&start);

  if(argc < 2){
    cout << "Input file missing." << endl;
    return(0);
  }

  // File names
  string parameterFileName = argv[1];
  string modelName;
  string initialConf;
  int ICprovided = 0;
  double ICtol = 1.0e-5;
  string outputFileName;
  int VTKflag = 0;
  double InflationFactor = 1.0;

  // Bending
  double KC = 1.0;
  double KG =-1.0;
  double C0 = 0.0;
  int quadOrder = 1;
  // Penalty parameters
  double penaltyVolumeInit = 1.0e3;
  double penaltyAreaInit   = 1.0e3;
  double penaltyVolumeTol  = 1.0e-3;
  double penaltyAreaTol    = 1.0e-3;

  // Potential input parameters
  double PotentialSearchRF = 1.0;
  double epsilon = 1.0;
  double sigma = 1.0;
  double Rshift = 1.0;

  // Connectivity search
  double RconnSF = 1.0;

  // Monte Carlo solver parameters
  int nMCsteps = 1000;
  double T01, T02, FinalRatio;
  int CompNeighInterval;
  int MCmethod = 0;

  // Number of nodes per protein
  int NnodePr = 10;
  int PrMaxNum = 10;
  int PrintEvery = 10;

  // Reading input from file passed as argument
  ifstream inp;
  inp.open(parameterFileName.c_str(), ios::in);
  if (!inp) {
    cout << "Cannot open input file: " << parameterFileName << endl;
    return(0);
  }
  string temp;

  inp >> temp >> modelName;
  inp >> temp >> outputFileName;
  inp >> temp >> initialConf;
  inp >> temp >> ICprovided;
  inp >> temp >> ICtol;
  inp >> temp >> VTKflag;
  inp >> temp >> InflationFactor;
  inp >> temp >> KC;
  inp >> temp >> KG;
  inp >> temp >> C0;
  inp >> temp >> quadOrder;
  inp >> temp >> penaltyVolumeInit;
  inp >> temp >> penaltyAreaInit;
  inp >> temp >> penaltyVolumeTol;
  inp >> temp >> penaltyAreaTol;
  inp >> temp >> PotentialSearchRF;
  inp >> temp >> epsilon;
  inp >> temp >> sigma;
  inp >> temp >> Rshift;
  inp >> temp >> RconnSF;
  inp >> temp >> nMCsteps;
  inp >> temp >> T01;
  inp >> temp >> T02;
  inp >> temp >> FinalRatio;
  inp >> temp >> CompNeighInterval;
  inp >> temp >> MCmethod;
  inp >> temp >> NnodePr;
  inp >> temp >> PrMaxNum;
  inp >> temp >> PrintEvery;

  inp.close();

  // List input parameters
  cout << " modelName               : " << modelName         << endl
       << " outputFileName          : " << outputFileName    << endl
       << " initialConfiguration    : " << initialConf       << endl
       << " IC provided             : " << ICprovided        << endl
       << " IC tol                  : " << ICtol             << endl
       << " VTKflag                 : " << VTKflag           << endl
       << " InflationFactor         : " << InflationFactor   << endl
       << " KC                      : " << KC                << endl
       << " KG                      : " << KG                << endl
       << " C0                      : " << C0                << endl
       << " Loop Shell quadOrder    : " << quadOrder         << endl
       << " Penalty volume factor   : " << penaltyVolumeInit << endl
       << " Penalty area factor     : " << penaltyAreaInit   << endl
       << " Penalty volume tol      : " << penaltyVolumeTol  << endl
       << " Penalty area tol        : " << penaltyAreaTol    << endl
       << " Potential Search factor : " << PotentialSearchRF << endl
       << " epsilon                 : " << epsilon           << endl
       << " sigma                   : " << sigma             << endl
       << " Rshift                  : " << Rshift            << endl
       << " Rconn search radius     : " << RconnSF           << endl
       << " MC steps                : " << nMCsteps          << endl
       << " MC T01                  : " << T01               << endl
       << " MC T02                  : " << T02               << endl
       << " MC FinalRatio           : " << FinalRatio        << endl
       << " MC ComputeNeighInterval : " << CompNeighInterval << endl
       << " MC method               : " << MCmethod          << endl
       << " Number of nodes per Pr  : " << NnodePr           << endl
       << " Max number of Pr        : " << PrMaxNum          << endl
       << " Print .vtk file every   : " << PrintEvery        << endl;

  // -------------------------------------------------------------------
  // Read mesh and setup geometric model
  // -------------------------------------------------------------------
  // Read in the mesh and, if provided the initial configuration
  vector<DeformationNode<3>::Point > IC;
  unsigned NumIC = 0;
  vector<uint > ICcheck;
  if (ICprovided == 1) {
    ifstream ifsIC;
    ifsIC.open(initialConf.c_str(), ios::in);
    if (!ifsIC) {
      cout << "Cannot open input file: " << initialConf << endl;
      exit(0);
    }

    string line;
    ifsIC >> line;
    ifsIC >> NumIC;
    ICcheck.assign(NumIC, 1);
    for(uint i = 0; i < NumIC; i++) {
      uint temp = 0;
      DeformationNode<3>::Point xIC;
      if (VTKflag == 1) {
	ifsIC >> xIC(0) >> xIC(1) >> xIC(2);
      }
      else {
	ifsIC >> temp >> xIC(0) >> xIC(1) >> xIC(2); }
      IC.push_back(xIC);
    }
  } // end of ICprovided loop
  cout << "NumIC = " << IC.size() << endl;

  // Create input stream
  ifstream ifs;
  ifs.open(modelName.c_str(), ios::in);
  if (!ifs) {
    cout << "Cannot open input file: " << modelName << endl;
    exit(0);
  }

  // Create vector of nodes
  unsigned int dof = 0, npts = 0, NumDoF = 0;
  vector<NodeBase* > nodes;
  vector<DeformationNode<3>* > defNodes;

  // Input .vtk or inp files containing nodes and connectivities
  string token;
  ifs >> token;
  ifs >> npts;
  NumDoF = npts*3; // Assumed all nodes have 3 DoF
  nodes.reserve(npts);
  defNodes.reserve(npts);
  vector<ProteinNode *> Proteins;

  // read in points
  uint NextProtein = 0;
  for(uint i = 0; i < npts; i++) {
    uint NodeNum = 0;
    DeformationNode<3>::Point x;
    if (VTKflag == 1) {
      ifs >> x(0) >> x(1) >> x(2); }
    else {
      ifs >> NodeNum >> x(0) >> x(1) >> x(2); }

    NodeBase::DofIndexMap idx(3);
    for(uint j = 0; j < 3; j++) {
      idx[j] = dof++;
    }
    DeformationNode<3>* n = new DeformationNode<3>(i,idx,x);

    if (ICprovided == 1) {
      if (VTKflag == 1) {
	if (i < NumIC) {
	  ProteinNode * PrNode = new ProteinNode(n);
	  Proteins.push_back(PrNode);
	}
      }
      else {
	for (uint k = 0; k < NumIC; k++) {
	  if (tvmet::norm2(IC[k] - x) < ICtol && ICcheck[k] == 1) {
	    ProteinNode * PrNode = new ProteinNode(n);
	    Proteins.push_back(PrNode);
	    ICcheck[k] = 0;
	    break;
	  }
	}
      }
    }
    else {
      if (i == NextProtein && Proteins.size() < PrMaxNum) { // create a protein every NodePr nodes and additional conditions
	// if (x(2) > 1.0) { // just for cone example - start from proteins packed close to the tip
	ProteinNode * PrNode = new ProteinNode(n);
	Proteins.push_back(PrNode);
	NextProtein += (rand() % NnodePr) + 1;
	// }
      }
    }

    // Inflate vessel if necessary
    x *= InflationFactor;
    n->setPoint(x);
    n->resetPosition();

    nodes.push_back( n );
    defNodes.push_back( n );

  } // end of reading points

  ICcheck.clear();

  // Read in triangle connectivities
  vector< tvmet::Vector<int,3> > connectivities;
  tvmet::Vector<int,3> ct;
  uint ntri = 0, ElemNum = 0, tmp = 0;
  map<DeformationNode<3> *, vector<DeformationNode<3> *> > PossibleHosts;

  ifs >> token;
  ifs >> ntri;
  connectivities.reserve(ntri);
  for (uint i = 0; i < ntri; i++)
  {
    ifs >> ElemNum;
    ifs >> ct(0) >> ct(1) >> ct(2);
    if (VTKflag == 0) {
      ct(0) -= 1;  ct(1) -= 1;  ct(2) -= 1; }

    connectivities.push_back(ct);
  } // end of reading triangle connectivities

  // build possible hosts table
  for(uint i = 0; i < npts; i++)
  {
    set<DeformationNode<3> *> setHosts;
    for (uint j = 0; j < ntri; j++) {
      ct = connectivities[j];
      if (i == ct(0) || i == ct(1) || i == ct(2) ) {
	setHosts.insert( defNodes[ct(0)] );
	setHosts.insert( defNodes[ct(1)] );
	setHosts.insert( defNodes[ct(2)] );
      }
    }

    vector<DeformationNode<3> *> vectorHosts;
    for (set<DeformationNode<3> *>::iterator pHost = setHosts.begin();
	 pHost != setHosts.end(); pHost++) {
      vectorHosts.push_back(*pHost);
    }

    PossibleHosts[ defNodes[i] ] = vectorHosts;
  }

  cout << "Number of nodes     = " << nodes.size()          << endl
       << "Number of proteins  = " << Proteins.size()       << endl
       << "Number of elements  = " << connectivities.size() << endl;

  // Close mesh file in inp format
  ifs.close();

  // -------------------------------------------------------------------
  // Create model
  // -------------------------------------------------------------------
  // Create Loop shell body with both bending and in-plane elastic energy
  /*
  // Bending material object, to be copied when body generates new elements
  EvansElastic bodyMaterial(KC, KG, C0, 0.0, 0.0);

  // Bending body will generate a mesh of Loop Subdivision shell elements from the connectivity and nodes
  double pressure = 0.0;
  double tension  = 0.0;
  LoopShellBody<EvansElastic> * shellBody = new LoopShellBody<EvansElastic>(bodyMaterial,
									    connectivities,
									    nodes,
									    quadOrder,
									    pressure,
									    tension,
									    0.0,
									    penaltyVolumeInit,
									    penaltyAreaInit,
									    0.0,
									    noConstraint, // just at the beginning
									    noConstraint, // just at the beginning
									    noConstraint);
  // Initialize body
  // shellBody->compute(true, false, false);
  cout << "Initial shell body energy = " << shellBody->totalStrainEnergy() << endl;
  cout << "Initial shell body energy = " << shellBody->energy() << endl;
  cout << "Initial shell body volume = " << shellBody->volume() << endl;
  cout << "Initial shell body area   = " << shellBody->area()   << endl;
  cout << "Average edge length from body = " << shellBody->AverageEdgeLength() << endl << endl;
  // shellBody->checkConsistency();

  */

  // Initiliaze potential material
  ProteinLennardJones Mat(epsilon, sigma);

  // Then initialize potential body
  ProteinBody * PrBody = new ProteinBody(Proteins, &Mat, PotentialSearchRF);

  PrBody->compute(true, false, false);
  cout << "Initial protein body energy = " << PrBody->energy() << endl;

  /*
  // Create Model and solver
  Model::BodyContainer bdc;
  bdc.push_back(shellBody);
  Model model(bdc, nodes);
       // Consistency check
       // model.checkConsistency(true,false);
       // model.checkRank(model.dof()-3,true);
  */

  // Initialize printing utils
  cout << "Seraching connectivity over R = " <<  RconnSF << endl;
  PrintingProtein PrintArchaea(modelName, outputFileName+"iter", nodes, connectivities, Proteins, RconnSF);

  // Initialize Montecarlo Solver
  MontecarloProtein MCsolver(Proteins, PrBody, PossibleHosts, MCmethod, &PrintArchaea, PrintEvery, nMCsteps);
  MCsolver.SetTempSchedule(MCsolver.EXPONENTIAL, T01, T02, FinalRatio);
  MCsolver.solve(CompNeighInterval, PotentialSearchRF);

  /*
  // Print proteins positions for further processing
  for (uint i = 0; i < Proteins.size(); i++)
  {
    DeformationNode<3>::Point P =  Proteins[i]->getHostPosition();
    cout << P[0] << " " << P[1] << " " << P[2] << endl;
  }
  */

  // End of program
  time (&end);
  dif = difftime (end,start);
  cout << endl << "All done :) in " << dif  << " s" << endl;

  // -------------------------------------------------------------------
  // Clean up
  // -------------------------------------------------------------------
  // delete shellBody;
  delete PrBody;

  for (uint i = 0; i<Proteins.size(); i++)
  {
    delete Proteins[i];
  }

  for (uint i = 0; i<nodes.size(); i++)
  {
    delete nodes[i];
  }

  return (0);
}
<commit_msg>Cleaned up driver and printing util<commit_after>#include <string>
#include <fstream>
#include <iostream>
#include <vector>
#include <set>
#include <cmath>

#include <getopt.h>
#include <unistd.h>
#include <time.h>

#include <tvmet/Vector.h>

#include "VoomMath.h"
#include "Node.h"
#include "ProteinLennardJones.h"
#include "ProteinBody.h"
#include "MontecarloProtein.h"
#include "Utils/PrintingProtein.h"

using namespace voom;
using namespace std;

int main(int argc, char* argv[])
{
  // -------------------------------------------------------------------
  // Setup
  // -------------------------------------------------------------------
  time_t start, end;
  double dif;
  time(&start);

  if(argc < 2){
    cout << "Input file missing." << endl;
    return(0);
  }

  // File names
  string parameterFileName = argv[1];
  string modelName;
  string outputFileName;
  string initialConf;
  int ICprovided = 0;
  double ICtol = 1.0e-5;
  int VTKflag = 0;
  double InflationFactor = 1.0;

  // Potential input parameters
  double PotentialSearchRF = 1.0;
  double epsilon = 1.0;
  double sigma = 1.0;
  double Rshift = 1.0;

  // Connectivity search
  double RconnSF = 1.0;

  // Monte Carlo solver parameters
  int nMCsteps = 1000;
  double T01, T02, FinalRatio;
  int CompNeighInterval;
  int MCmethod = 0;
  double ResetT = -1.0;

  // Number of nodes per protein
  int NnodePr = 10;
  int PrMaxNum = 10;
  int PrintEvery = 10;

  // Other Analysis options
  int StepWise = 0;

  // Reading input from file passed as argument
  ifstream inp;
  inp.open(parameterFileName.c_str(), ios::in);
  if (!inp) {
    cout << "Cannot open input file: " << parameterFileName << endl;
    return(0);
  }
  string temp;

  inp >> temp >> modelName;
  inp >> temp >> outputFileName;
  inp >> temp >> initialConf;
  inp >> temp >> ICprovided;
  inp >> temp >> ICtol;
  inp >> temp >> VTKflag;
  inp >> temp >> InflationFactor;
  inp >> temp >> PotentialSearchRF;
  inp >> temp >> epsilon;
  inp >> temp >> sigma;
  inp >> temp >> Rshift;
  inp >> temp >> RconnSF;
  inp >> temp >> nMCsteps;
  inp >> temp >> T01;
  inp >> temp >> T02;
  inp >> temp >> FinalRatio;
  inp >> temp >> CompNeighInterval;
  inp >> temp >> MCmethod;
  inp >> temp >> ResetT;
  inp >> temp >> NnodePr;
  inp >> temp >> PrMaxNum;
  inp >> temp >> PrintEvery;
  inp >> temp >> StepWise;

  inp.close();

  // List input parameters
  cout << " modelName               : " << modelName         << endl
       << " outputFileName          : " << outputFileName    << endl
       << " initialConfiguration    : " << initialConf       << endl
       << " IC provided             : " << ICprovided        << endl
       << " IC tol                  : " << ICtol             << endl
       << " VTK flag                : " << VTKflag           << endl
       << " InflationFactor         : " << InflationFactor   << endl
       << " Potential Search factor : " << PotentialSearchRF << endl
       << " epsilon                 : " << epsilon           << endl
       << " sigma                   : " << sigma             << endl
       << " Rshift                  : " << Rshift            << endl
       << " Rconn search radius     : " << RconnSF           << endl
       << " MC steps                : " << nMCsteps          << endl
       << " MC T01                  : " << T01               << endl
       << " MC T02                  : " << T02               << endl
       << " MC FinalRatio           : " << FinalRatio        << endl
       << " MC ComputeNeighInterval : " << CompNeighInterval << endl
       << " MC method               : " << MCmethod          << endl
       << " MC reset T              : " << ResetT            << endl
       << " Number of nodes per Pr  : " << NnodePr           << endl
       << " Max number of Pr        : " << PrMaxNum          << endl
       << " Print .vtk file every   : " << PrintEvery        << endl
       << " Step wise change in T   : " << StepWise          << endl;

  // -------------------------------------------------------------------
  // Read mesh and setup geometric model
  // -------------------------------------------------------------------
  // Read in the mesh and, if provided the initial configuration
  vector<DeformationNode<3>::Point > IC;
  unsigned NumIC = 0;
  vector<uint > ICcheck;
  if (ICprovided == 1) {
    ifstream ifsIC;
    ifsIC.open(initialConf.c_str(), ios::in);
    if (!ifsIC) {
      cout << "Cannot open input file: " << initialConf << endl;
      exit(0);
    }

    string line;
    ifsIC >> line;
    ifsIC >> NumIC;
    ICcheck.assign(NumIC, 1);
    for(uint i = 0; i < NumIC; i++) {
      uint temp = 0;
      DeformationNode<3>::Point xIC;
      ifsIC >> xIC(0) >> xIC(1) >> xIC(2);
      IC.push_back(xIC);
    }
    ifsIC.close();
  } // end of ICprovided loop
  cout << "NumIC = " << IC.size() << endl;

  // Create input stream
  ifstream ifs;
  ifs.open(modelName.c_str(), ios::in);
  if (!ifs) {
    cout << "Cannot open input file: " << modelName << endl;
    exit(0);
  }

  // Create vector of nodes
  unsigned int dof = 0, npts = 0, NumDoF = 0;
  vector<NodeBase* > nodes;
  vector<DeformationNode<3>* > defNodes;

  // Input .vtk or inp files containing nodes and connectivities
  string token;
  ifs >> token;
  ifs >> npts;
  NumDoF = npts*3; // Assumed all nodes have 3 DoF
  nodes.reserve(npts);
  defNodes.reserve(npts);
  vector<ProteinNode *> Proteins;

  // read in points
  uint NextProtein = 0;
  for(uint i = 0; i < npts; i++) {
    DeformationNode<3>::Point x;
    ifs >> x(0) >> x(1) >> x(2);

    NodeBase::DofIndexMap idx(3);
    for(uint j = 0; j < 3; j++) {
      idx[j] = dof++;
    }

    // Inflate/Deflate vessel if necessary
    x *= InflationFactor;

    DeformationNode<3>* n = new DeformationNode<3>(i,idx,x);

    if (ICprovided == 1) {
      if (VTKflag == 1) {
	if (i < NumIC) {
	  ProteinNode * PrNode = new ProteinNode(n);
	  Proteins.push_back(PrNode);
	}
      }
      else if (VTKflag == 2) {
	for (uint k = 0; k < NumIC; k++) {
	  if (tvmet::norm2(IC[k] - x) < ICtol && ICcheck[k] == 1) {
	    ProteinNode * PrNode = new ProteinNode(n);
	    Proteins.push_back(PrNode);
	    ICcheck[k] = 0;
	    break;
	  }
	}
      }
    }
    else {
      if (i == NextProtein && Proteins.size() < PrMaxNum) { // create a protein every NodePr nodes and additional conditions
	// if (x(2) > 1.0) { // just for cone example - start from proteins packed close to the tip
	ProteinNode * PrNode = new ProteinNode(n);
	Proteins.push_back(PrNode);
	NextProtein += (rand() % NnodePr) + 1;
	// }
      }
    }

    nodes.push_back( n );
    defNodes.push_back( n );

  } // end of reading points

  ICcheck.clear();

  // Read in triangle connectivities
  vector< tvmet::Vector<int,3> > connectivities;
  tvmet::Vector<int,3> ct;
  uint ntri = 0, ElemNum = 0, tmp = 0;
  map<DeformationNode<3> *, vector<DeformationNode<3> *> > PossibleHosts;

  ifs >> token;
  ifs >> ntri;
  connectivities.reserve(ntri);
  for (uint i = 0; i < ntri; i++)
  {
    ifs >> ElemNum;
    ifs >> ct(0) >> ct(1) >> ct(2);
    connectivities.push_back(ct);
  } // end of reading triangle connectivities

  // build possible hosts table
  for(uint i = 0; i < npts; i++)
  {
    set<DeformationNode<3> *> setHosts;
    for (uint j = 0; j < ntri; j++) {
      ct = connectivities[j];
      if (i == ct(0) || i == ct(1) || i == ct(2) ) {
	setHosts.insert( defNodes[ct(0)] );
	setHosts.insert( defNodes[ct(1)] );
	setHosts.insert( defNodes[ct(2)] );
      }
    }

    vector<DeformationNode<3> *> vectorHosts;
    for (set<DeformationNode<3> *>::iterator pHost = setHosts.begin();
	 pHost != setHosts.end(); pHost++) {
      vectorHosts.push_back(*pHost);
    }

    PossibleHosts[ defNodes[i] ] = vectorHosts;
  }

  cout << "Number of nodes     = " << nodes.size()          << endl
       << "Number of proteins  = " << Proteins.size()       << endl
       << "Number of elements  = " << connectivities.size() << endl;

  // Close mesh file in inp format
  ifs.close();

  // Initiliaze potential material
  ProteinLennardJones Mat(epsilon, sigma);

  // Then initialize potential body
  ProteinBody * PrBody = new ProteinBody(Proteins, &Mat, PotentialSearchRF);
  PrBody->compute(true, false, false);
  cout << "Initial protein body energy = " << PrBody->energy() << endl;

  // Initialize printing utils
  cout << "Seraching connectivity over R = " <<  RconnSF << endl;
  PrintingProtein PrintArchaea(modelName, outputFileName+"iter", nodes, connectivities, Proteins, RconnSF);

  // Initialize Montecarlo Solver
  MontecarloProtein MCsolver(Proteins, PrBody, PossibleHosts, MCmethod, &PrintArchaea, ResetT, PrintEvery, nMCsteps);
  if (StepWise == 0) {
    MCsolver.SetTempSchedule(MCsolver.EXPONENTIAL, T01, T02, FinalRatio); }
  // MCsolver.SetTempSchedule(MCsolver.LINEAR, T01, T02, FinalRatio); }
  else {
    MCsolver.SetTempSchedule(MCsolver.STEPWISE, T01, T02, FinalRatio);
  }

  MCsolver.solve(CompNeighInterval, PotentialSearchRF);

  // End of program
  time (&end);
  dif = difftime (end,start);
  cout << endl << "All done :) in " << dif  << " s" << endl;

  // -------------------------------------------------------------------
  // Clean up
  // -------------------------------------------------------------------
  // delete shellBody;
  delete PrBody;

  for (uint i = 0; i<Proteins.size(); i++)
  {
    delete Proteins[i];
  }

  for (uint i = 0; i<nodes.size(); i++)
  {
    delete nodes[i];
  }

  return (0);
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "NativeBackEnd.hpp"
#include "Utils.hpp"
#include "Options.hpp"
#include "AssemblyFileWriter.hpp"
#include "Assembler.hpp"
#include "FloatPool.hpp"

//Low-level Three Address Code
#include "ltac/Compiler.hpp"
#include "ltac/PeepholeOptimizer.hpp"
#include "ltac/Printer.hpp"
#include "ltac/aggregates.hpp"
#include "ltac/prologue.hpp"
#include "ltac/stack_offsets.hpp"
#include "ltac/stack_space.hpp"
#include "ltac/register_allocator.hpp"
#include "ltac/pre_alloc_cleanup.hpp"

//Code generation
#include "asm/CodeGeneratorFactory.hpp"

using namespace eddic;

void NativeBackEnd::generate(mtac::Program& program, Platform platform){
    std::string output = configuration->option_value("output");

    //Prepare the float pool
    auto float_pool = std::make_shared<FloatPool>();

    //Allocate stack positions for aggregates that have not been allocated
    ltac::allocate_aggregates(program);

    //Generate LTAC Code
    ltac::Compiler ltacCompiler(platform, configuration);
    ltacCompiler.compile(program, float_pool);

    //Switch to LTAC Mode
    program.mode = mtac::Mode::LTAC;

    //Clean the code generated by the LTAC Compiler to ease the register allocation
    ltac::pre_alloc_cleanup(program);

    if(configuration->option_defined("ltac-pre")){
        ltac::Printer printer;
        printer.print(program);
    }

    //Init the structures and arrays
    //Must be done before register allocation to profit from it
    ltac::alloc_stack_space(program);

    //Allocate pseudo registers into hard registers
    ltac::register_allocation(program, platform);

    //Generate the prologue and epilogue of each functions
    ltac::generate_prologue_epilogue(program, configuration);

    //If specified by the configuration, replace all stack offsets using SP
    if(configuration->option_defined("fomit-frame-pointer")){
        ltac::fix_stack_offsets(program, platform);
    }

    if(configuration->option_defined("ltac-alloc")){
        ltac::Printer printer;
        printer.print(program);
    }

    if(configuration->option_defined("fpeephole-optimization")){
        ltac::optimize(program, platform);
    }

    if(configuration->option_defined("ltac") || configuration->option_defined("ltac-only")){
        ltac::Printer printer;
        printer.print(program);
    }

    if(!configuration->option_defined("ltac-only")){
        auto input_file_name = configuration->option_value("input");
        auto asm_file_name = input_file_name + ".s";
        auto object_file_name = input_file_name + ".o";

        {
            //Generate assembly from TAC
            AssemblyFileWriter writer(asm_file_name);

            as::CodeGeneratorFactory factory;
            auto generator = factory.get(platform, writer, program, program.context);

            //Generate the code from the LTAC Program
            generator->generate(get_string_pool(), float_pool);

            //writer's destructor flushes the file
        }

        //If it's necessary, assemble and link the assembly
        if(!configuration->option_defined("assembly")){
            assemble(platform, asm_file_name, object_file_name, output, configuration->option_defined("debug"), configuration->option_defined("verbose"));

            //Remove temporary files
            if(!configuration->option_defined("keep")){
                remove(asm_file_name.c_str());
            }

            remove(object_file_name.c_str());
        }
    }
}
<commit_msg>Time assembly generation and the assembler<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "NativeBackEnd.hpp"
#include "Utils.hpp"
#include "Options.hpp"
#include "AssemblyFileWriter.hpp"
#include "Assembler.hpp"
#include "FloatPool.hpp"
#include "GlobalContext.hpp"

//Low-level Three Address Code
#include "ltac/Compiler.hpp"
#include "ltac/PeepholeOptimizer.hpp"
#include "ltac/Printer.hpp"
#include "ltac/aggregates.hpp"
#include "ltac/prologue.hpp"
#include "ltac/stack_offsets.hpp"
#include "ltac/stack_space.hpp"
#include "ltac/register_allocator.hpp"
#include "ltac/pre_alloc_cleanup.hpp"

//Code generation
#include "asm/CodeGeneratorFactory.hpp"

using namespace eddic;

void NativeBackEnd::generate(mtac::Program& program, Platform platform){
    std::string output = configuration->option_value("output");

    //Prepare the float pool
    auto float_pool = std::make_shared<FloatPool>();

    //Allocate stack positions for aggregates that have not been allocated
    ltac::allocate_aggregates(program);

    //Generate LTAC Code
    ltac::Compiler ltacCompiler(platform, configuration);
    ltacCompiler.compile(program, float_pool);

    //Switch to LTAC Mode
    program.mode = mtac::Mode::LTAC;

    //Clean the code generated by the LTAC Compiler to ease the register allocation
    ltac::pre_alloc_cleanup(program);

    if(configuration->option_defined("ltac-pre")){
        ltac::Printer printer;
        printer.print(program);
    }

    //Init the structures and arrays
    //Must be done before register allocation to profit from it
    ltac::alloc_stack_space(program);

    //Allocate pseudo registers into hard registers
    ltac::register_allocation(program, platform);

    //Generate the prologue and epilogue of each functions
    ltac::generate_prologue_epilogue(program, configuration);

    //If specified by the configuration, replace all stack offsets using SP
    if(configuration->option_defined("fomit-frame-pointer")){
        ltac::fix_stack_offsets(program, platform);
    }

    if(configuration->option_defined("ltac-alloc")){
        ltac::Printer printer;
        printer.print(program);
    }

    if(configuration->option_defined("fpeephole-optimization")){
        ltac::optimize(program, platform);
    }

    if(configuration->option_defined("ltac") || configuration->option_defined("ltac-only")){
        ltac::Printer printer;
        printer.print(program);
    }

    if(!configuration->option_defined("ltac-only")){
        auto input_file_name = configuration->option_value("input");
        auto asm_file_name = input_file_name + ".s";
        auto object_file_name = input_file_name + ".o";

        {
            timing_timer timer(program.context->timing(), "assembly_generation");

            //Generate assembly from TAC
            AssemblyFileWriter writer(asm_file_name);

            as::CodeGeneratorFactory factory;
            auto generator = factory.get(platform, writer, program, program.context);

            //Generate the code from the LTAC Program
            generator->generate(get_string_pool(), float_pool);

            //writer's destructor flushes the file
        }

        //If it's necessary, assemble and link the assembly
        if(!configuration->option_defined("assembly")){
            timing_timer timer(program.context->timing(), "assemble");

            assemble(platform, asm_file_name, object_file_name, output, configuration->option_defined("debug"), configuration->option_defined("verbose"));

            //Remove temporary files
            if(!configuration->option_defined("keep")){
                remove(asm_file_name.c_str());
            }

            remove(object_file_name.c_str());
        }
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks>
 *
 * This program 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.
 *
 * This program 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 <cstdint>    // explicitly-sized integral types
#include <cstdlib>    // EXIT_SUCCESS, EXIT_FAILURE
#include <exception>  // std::exception

#include "components/command_line.hpp"
#include "spdlog/spdlog.h"
#include "config.hpp"

using add_arg = command_line::option;

int main(int argc, char *argv[])
{
    const command_line::options opts{
        add_arg("-h", "--help",      "Display this text and exit "),
        add_arg("-v", "--version",   "Print version information"),
        add_arg("-l", "--log",       "Set logging level to info"),

        /* Exclusive arguments; cannot be combined with any other arguments. */
        add_arg("-d", "--ident",     "Specify an item identification (such as DOI, URL, etc.)", "IDENT"),

        /* Main arguments; at least one of these are required. */
        /* auto main = command_line::add_group( */
        /*     "main", "necessarily inclusive arguments; at least one required" */
        /* ); */
        add_arg("-a", "--author",    "Specify authors", "AUTHOR"),
        add_arg("-t", "--title",     "Specify title", "TITLE"),
        add_arg("-s", "--serie",     "Specify serie", "SERIE"),
        add_arg("-p", "--publisher", "Specify publisher", "PUBLISHER"),

        /* Exact data arguments; all are optional. */
        add_arg("-y", "--year",      "Specify year of release", "YEAR"),
        add_arg("-L", "--language",  "Specify text language", "LANG"),
        add_arg("-e", "--edition",   "Specify item edition", "EDITION"),
        add_arg("-E", "--extension", "Specify item extension", "EXT",
                {"epub", "pdf", "djvu"}),
        add_arg("-i", "--isbn",      "Specify item ISBN", "ISBN"),
    };

    uint8_t exit_code = EXIT_SUCCESS;

    auto logger = spdlog::stdout_color_mt("logger");
    spdlog::set_pattern("%l: %v");
    spdlog::set_level(spdlog::level::err);

    try {
        /* Parse command line arguments. */
        std::string progname = argv[0];
        std::vector<std::string> args(argv + 1, argv + argc);

        cliparser::make_type cli = cliparser::make(std::move(progname), std::move(opts));
        cli->process_arguments(args);

        if (cli->has("log"))
            spdlog::set_level(spdlog::level::info);

        logger->info("the mighty eldwyrm has been summoned!");

        if (cli->has("help")) {
            cli->usage();
            return EXIT_SUCCESS;
        } else if (cli->has("version")) {
            print_build_info();
            return EXIT_SUCCESS;
        } else if (args.empty()) {
            cli->usage();
            return EXIT_FAILURE;
        }

    } catch (const std::exception &err) {
        logger->error(err.what());
        exit_code = EXIT_FAILURE;
    }

    spdlog::drop_all();
    return exit_code;
}
<commit_msg>log spd::drop_all() and main() return value<commit_after>/*
 * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks>
 *
 * This program 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.
 *
 * This program 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 <cstdint>    // explicitly-sized integral types
#include <cstdlib>    // EXIT_SUCCESS, EXIT_FAILURE
#include <exception>  // std::exception

#include "components/command_line.hpp"
#include "spdlog/spdlog.h"
#include "config.hpp"

using add_arg = command_line::option;

int main(int argc, char *argv[])
{
    const command_line::options opts{
        add_arg("-h", "--help",      "Display this text and exit "),
        add_arg("-v", "--version",   "Print version information"),
        add_arg("-l", "--log",       "Set logging level to info"),

        /* Exclusive arguments; cannot be combined with any other arguments. */
        add_arg("-d", "--ident",     "Specify an item identification (such as DOI, URL, etc.)", "IDENT"),

        /* Main arguments; at least one of these are required. */
        /* auto main = command_line::add_group( */
        /*     "main", "necessarily inclusive arguments; at least one required" */
        /* ); */
        add_arg("-a", "--author",    "Specify authors", "AUTHOR"),
        add_arg("-t", "--title",     "Specify title", "TITLE"),
        add_arg("-s", "--serie",     "Specify serie", "SERIE"),
        add_arg("-p", "--publisher", "Specify publisher", "PUBLISHER"),

        /* Exact data arguments; all are optional. */
        add_arg("-y", "--year",      "Specify year of release", "YEAR"),
        add_arg("-L", "--language",  "Specify text language", "LANG"),
        add_arg("-e", "--edition",   "Specify item edition", "EDITION"),
        add_arg("-E", "--extension", "Specify item extension", "EXT",
                {"epub", "pdf", "djvu"}),
        add_arg("-i", "--isbn",      "Specify item ISBN", "ISBN"),
    };

    uint8_t exit_code = EXIT_SUCCESS;

    auto logger = spdlog::stdout_color_mt("logger");
    spdlog::set_pattern("%l: %v");
    spdlog::set_level(spdlog::level::err);

    try {
        /* Parse command line arguments. */
        std::string progname = argv[0];
        std::vector<std::string> args(argv + 1, argv + argc);

        cliparser::make_type cli = cliparser::make(std::move(progname), std::move(opts));
        cli->process_arguments(args);

        if (cli->has("log"))
            spdlog::set_level(spdlog::level::info);

        logger->info("the mighty eldwyrm has been summoned!");

        if (cli->has("help")) {
            cli->usage();
            return EXIT_SUCCESS;
        } else if (cli->has("version")) {
            print_build_info();
            return EXIT_SUCCESS;
        } else if (args.empty()) {
            cli->usage();
            return EXIT_FAILURE;
        }

    } catch (const std::exception &err) {
        logger->error(err.what());
        exit_code = EXIT_FAILURE;
    }

    logger->info("dropping all loggers and returning exitval = {}", exit_code);
    spdlog::drop_all();
    return exit_code;
}
<|endoftext|>


<commit_before>/*****************************************************************************************
 *                                                                                *
 * OpenSpace                                                                             *
 *                                                                                *
 * Copyright (c) 2014                                                                    *
 *                                                                                *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
 * software and associated documentation files (the "Software"), to deal in the Software *
 * without restriction, including without limitation the rights to use, copy, modify,    *
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
 * permit persons to whom the Software is furnished to do so, subject to the following   *
 * conditions:                                                                           *
 *                                                                                *
 * The above copyright notice and this permission notice shall be included in all copies *
 * or substantial portions of the Software.                                              *
 *                                                                                *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
 ****************************************************************************************/

// open space includes
#include <openspace/engine/openspaceengine.h>
#include <openspace/interface/interface.h>

// sgct includes
#include <sgct.h>

sgct::Engine* _sgctEngine;
openspace::Interface* _interface;

// function pointer declarations
void mainInitFunc(void);
void mainPreSyncFunc(void);
void mainPostSyncPreDrawFunc(void);
void mainRenderFunc(void);
void mainPostDrawFunc(void);
void mainKeyboardCallback(int key, int action);
void mainMouseButtonCallback(int key, int action);
void mainMousePosCallback(double x, double y);
void mainMouseScrollCallback(double posX, double posY);
void mainEncodeFun();
void mainDecodeFun();
void mainExternalControlCallback(const char * receivedChars, int size, int clientId);

namespace {
	const std::string _loggerCat = "main";
}

int main(int argc, char** argv)
{
    // create the OpenSpace engine and get arguments for the sgct engine
    std::vector<std::string> sgctArguments;
    const bool success = openspace::OpenSpaceEngine::create(argc, argv, sgctArguments);
    if (!success)
        return EXIT_FAILURE;

    // create sgct engine c arguments
    int newArgc = static_cast<int>(sgctArguments.size());
    char** newArgv = new char*[newArgc];
    for (int i = 0; i < newArgc; ++i)
        newArgv[i] = const_cast<char*>(sgctArguments.at(i).c_str());

	LDEBUG("Creating SGCT Engine");
    _sgctEngine = new sgct::Engine(newArgc, newArgv);

    // deallocate sgct c arguments
    for (int i = 0; i < newArgc; ++i)
         delete newArgv[i];
    delete[] newArgv;

    // Bind functions
    _sgctEngine->setInitOGLFunction(mainInitFunc);
    _sgctEngine->setPreSyncFunction(mainPreSyncFunc);
    _sgctEngine->setPostSyncPreDrawFunction(mainPostSyncPreDrawFunc);
    _sgctEngine->setDrawFunction(mainRenderFunc);
    _sgctEngine->setPostDrawFunction(mainPostDrawFunc);
    _sgctEngine->setKeyboardCallbackFunction(mainKeyboardCallback);
    _sgctEngine->setMouseButtonCallbackFunction(mainMouseButtonCallback);
    _sgctEngine->setMousePosCallbackFunction(mainMousePosCallback);
    _sgctEngine->setMouseScrollCallbackFunction(mainMouseScrollCallback);
    _sgctEngine->setExternalControlCallback(mainExternalControlCallback);

    // set encode and decode functions
    // NOTE: starts synchronizing before init functions
    sgct::SharedData::instance()->setEncodeFunction(mainEncodeFun);
    sgct::SharedData::instance()->setDecodeFunction(mainDecodeFun);

    // init the interface which will handle callbacks from an external gui
	LDEBUG("Creating Interface module");
    _interface = new openspace::Interface(&OsEng);

    // try to open a window
	LDEBUG("Initialize SGCT Engine");
	const bool initSuccess = _sgctEngine->init(sgct::Engine::OpenGL_4_0_Core_Profile);
    if (!initSuccess) {
		LFATAL("Initializing failed");
        // could not open a window, deallocates and exits
        delete _sgctEngine;
        openspace::OpenSpaceEngine::destroy();
        return EXIT_FAILURE;
    }

    // Main loop
	LDEBUG("Starting rendering loop");
    _sgctEngine->render();

	LDEBUG("Destroying OpenSpaceEngine");
	openspace::OpenSpaceEngine::destroy();

    // Clean up (de-allocate)
	LDEBUG("Destroying SGCT Engine");
    delete _sgctEngine;

    // Exit program
    exit(EXIT_SUCCESS);
}

void mainExternalControlCallback(const char* receivedChars, int size, int clientId)
{
    if (_sgctEngine->isMaster())
        _interface->callback(receivedChars);
}

void mainInitFunc(void)
{
    OsEng.initialize();
    OsEng.initializeGL();
}

void mainPreSyncFunc(void)
{
    OsEng.preSynchronization();
}

void mainPostSyncPreDrawFunc(void)
{
    OsEng.postSynchronizationPreDraw();
}

void mainRenderFunc(void)
{
    OsEng.render();
}

void mainPostDrawFunc(void)
{
    OsEng.postDraw();
}

void mainKeyboardCallback(int key, int action)
{
    if (_sgctEngine->isMaster())
        OsEng.keyboardCallback(key, action);
}

void mainMouseButtonCallback(int key, int action)
{
    if (_sgctEngine->isMaster())
        OsEng.mouseButtonCallback(key, action);
}

void mainMousePosCallback(double x, double y)
{
    // TODO use float instead
    if (_sgctEngine->isMaster())
        OsEng.mousePositionCallback(static_cast<int>(x), static_cast<int>(y));
}

void mainMouseScrollCallback(double posX, double posY)
{
    // TODO use float instead
    if (_sgctEngine->isMaster())
        OsEng.mouseScrollWheelCallback(static_cast<int>(posY));
}

void mainEncodeFun()
{
    OsEng.encode();
}

void mainDecodeFun()
{
    OsEng.decode();
}
<commit_msg>Deliberately break to check email from Jenkins<commit_after>/*****************************************************************************************
 *                                                                                *
 * OpenSpace                                                                             *
 *                                                                                *
 * Copyright (c) 2014                                                                    *
 *                                                                                *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
 * software and associated documentation files (the "Software"), to deal in the Software *
 * without restriction, including without limitation the rights to use, copy, modify,    *
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
 * permit persons to whom the Software is furnished to do so, subject to the following   *
 * conditions:                                                                           *
 *                                                                                *
 * The above copyright notice and this permission notice shall be included in all copies *
 * or substantial portions of the Software.                                              *
 *                                                                                *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
 ****************************************************************************************/

// open space includes
#include <openspace/engine/openspaceengine.h>
#include <openspace/interface/interface.h>

// sgct includes
#include <sgct.h>

sgct::Engine* _sgctEngine;
openspace::Interface* _interface;

// function pointer declarations
void mainInitFunc(void);
void mainPreSyncFunc(void);
void mainPostSyncPreDrawFunc(void);
void mainRenderFunc(void);
void mainPostDrawFunc(void);
void mainKeyboardCallback(int key, int action);
void mainMouseButtonCallback(int key, int action);
void mainMousePosCallback(double x, double y);
void mainMouseScrollCallback(double posX, double posY);
void mainEncodeFun();
void mainDecodeFun();
void mainExternalControlCallback(const char * receivedChars, int size, int clientId);

namespace {
	const std::string _loggerCat = "main";
}

int main(int argc, char** argv)
{
    // create the OpenSpace engine and get arguments for the sgct engine
    std::vector<std::string> sgctArguments;
    const bool success = openspace::OpenSpaceEngine::create(argc, argv, sgctArguments);
    if (!success)
        return EXIT_FAILURE;

    // create sgct engine c arguments
    int newArgc = static_cast<int>(sgctArguments.size());
    char** newArgv = new char*[newArgc];
    for (int i = 0; i < newArgc; ++i)
        newArgv[i] = const_cast<char*>(sgctArguments.at(i).c_str());

	LDEBUG("Creating SGCT Engine");
    _sgctEngine = new sgct::Engine(newArgc, newArgv);

    // deallocate sgct c arguments
    for (int i = 0; i < newArgc; ++i)
         delete newArgv[i];
    delete[] newArgv;

    // Bind functions
    _sgctEngine->setInitOGLFunction(mainInitFunc);
    _sgctEngine->setPreSyncFunction(mainPreSyncFunc);
    _sgctEngine->setPostSyncPreDrawFunction(mainPostSyncPreDrawFunc);
    _sgctEngine->setDrawFunction(mainRenderFunc);
    _sgctEngine->setPostDrawFunction(mainPostDrawFunc);
    _sgctEngine->setKeyboardCallbackFunction(mainKeyboardCallback);
    _sgctEngine->setMouseButtonCallbackFunction(mainMouseButtonCallback);
    _sgctEngine->setMousePosCallbackFunction(mainMousePosCallback);
    _sgctEngine->setMouseScrollCallbackFunction(mainMouseScrollCallback);
    _sgctEngine->setExternalControlCallback(mainExternalControlCallback);

    // set encode and decode functions
    // NOTE: starts synchronizing before init functions
    sgct::SharedData::instance()->setEncodeFunction(mainEncodeFun);
    sgct::SharedData::instance()->setDecodeFunction(mainDecodeFun);

    // init the interface which will handle callbacks from an external gui
	LDEBUG("Creating Interface module");
    _interface = new openspace::Interface(&OsEng);

    // try to open a window
	LDEBUG("Initialize SGCT Engine");
	const bool initSuccess = _sgctEngine->init(sgct::Engine::OpenGL_4_0_Core_Profile);
    if (!initSuccess) {
		LFATAL("Initializing failed");
        // could not open a window, deallocates and exits
        delete _sgctEngine;
        openspace::OpenSpaceEngine::destroy();
        return EXIT_FAILURE;
    }

    // Main loop
	LDEBUG("Starting rendering loop");
    _sgctEngine->render();

	LDEBUG("Destroying OpenSpaceEngine");
	openspace::OpenSpaceEngine::destroy();

    // Clean up (de-allocate)
	LDEBUG("Destroying SGCT Engine");
    delete _sgctEngine;

    // Exit program
    exit(EXIT_SUCCESS);s
}

void mainExternalControlCallback(const char* receivedChars, int size, int clientId)
{
    if (_sgctEngine->isMaster())
        _interface->callback(receivedChars);
}

void mainInitFunc(void)
{
    OsEng.initialize();
    OsEng.initializeGL();
}

void mainPreSyncFunc(void)
{
    OsEng.preSynchronization();
}

void mainPostSyncPreDrawFunc(void)
{
    OsEng.postSynchronizationPreDraw();
}

void mainRenderFunc(void)
{
    OsEng.render();
}

void mainPostDrawFunc(void)
{
    OsEng.postDraw();
}

void mainKeyboardCallback(int key, int action)
{
    if (_sgctEngine->isMaster())
        OsEng.keyboardCallback(key, action);
}

void mainMouseButtonCallback(int key, int action)
{
    if (_sgctEngine->isMaster())
        OsEng.mouseButtonCallback(key, action);
}

void mainMousePosCallback(double x, double y)
{
    // TODO use float instead
    if (_sgctEngine->isMaster())
        OsEng.mousePositionCallback(static_cast<int>(x), static_cast<int>(y));
}

void mainMouseScrollCallback(double posX, double posY)
{
    // TODO use float instead
    if (_sgctEngine->isMaster())
        OsEng.mouseScrollWheelCallback(static_cast<int>(posY));
}

void mainEncodeFun()
{
    OsEng.encode();
}

void mainDecodeFun()
{
    OsEng.decode();
}
<|endoftext|>


<commit_before>#include "SDL.h"
// #include "SDL_opengl.h"
// #include <cmath>
// #include "game/world.hpp"
// #include "game/obstacle.hpp"
// #include "graphics/model.hpp"
// #include "game/player.hpp"
#include "rand.hpp"
#include "ui/menu.hpp"
#include "ui/event.hpp"
#include "graphics/video.hpp"

static const int MAX_FPS = 100;
static const int MIN_FRAMETIME = 1000 / MAX_FPS;

int main(int argc, char *argv[])
{
    if (SDL_Init(SDL_INIT_TIMER) < 0) {
        fprintf(stderr, "Could not initialize SDL Timer: %s\n",
                SDL_GetError());
        exit(1);
    }
    Video::init();
    Rand::global.seed();
    UI::Screen::setActive(new UI::Menu);

    unsigned int lastticks = SDL_GetTicks();
    while (1) {
        SDL_Event e;
        while (SDL_PollEvent(&e)) {
            if (!UI::Screen::getActive())
                goto quit;
            switch (e.type) {
            case SDL_QUIT:
                goto quit;
            case SDL_MOUSEMOTION:
            {
                SDL_MouseMotionEvent &m = e.motion;
                int x = m.x, y = Video::height - 1 - m.y;
                UI::Screen::getActive()->
                    handleEvent(UI::MouseEvent(UI::MouseMove, -1, x, y));
                break;
            }
            case SDL_MOUSEBUTTONDOWN:
            case SDL_MOUSEBUTTONUP:
            {
                SDL_MouseButtonEvent &m = e.button;
                UI::EventType t = e.type == SDL_MOUSEBUTTONDOWN ?
                    UI::MouseDown : UI::MouseUp;
                int button;
                switch (m.button) {
                case SDL_BUTTON_LEFT:
                    button = UI::ButtonLeft;
                    break;
                case SDL_BUTTON_MIDDLE:
                    button = UI::ButtonMiddle;
                    break;
                case SDL_BUTTON_RIGHT:
                    button = UI::ButtonRight;
                    break;
                default:
                    button = UI::ButtonOther + m.button - 4;
                    break;
                }
                int x = m.x, y = Video::height - 1 - m.y;
                UI::Screen::getActive()->
                    handleEvent(UI::MouseEvent(t, button, x, y));
                break;
            }
            case SDL_KEYDOWN:
            case SDL_KEYUP:
            {
                SDL_KeyboardEvent &k = e.key;
                UI::EventType t = e.type == SDL_KEYDOWN ?
                    UI::KeyDown : UI::KeyUp;
                UI::Screen::getActive()->
                    handleEvent(UI::KeyEvent(t, k.keysym.sym));
                break;
            }
            default:
                break;
            }
        }
        if (!UI::Screen::getActive())
            goto quit;
        unsigned int ticks = SDL_GetTicks(), delta = ticks - lastticks;
        if (delta < MIN_FRAMETIME) {
            SDL_Delay(MIN_FRAMETIME - delta);
            lastticks += MIN_FRAMETIME;
            ticks = SDL_GetTicks();
        } else
            lastticks = ticks;
        UI::Screen::getActive()->draw(ticks);
        Video::update();
    }

quit:
    SDL_Quit();
    return 0;
}
<commit_msg>Fixed unsigned / signed comparison warning.<commit_after>#include "SDL.h"
// #include "SDL_opengl.h"
// #include <cmath>
// #include "game/world.hpp"
// #include "game/obstacle.hpp"
// #include "graphics/model.hpp"
// #include "game/player.hpp"
#include "rand.hpp"
#include "ui/menu.hpp"
#include "ui/event.hpp"
#include "graphics/video.hpp"

static const unsigned int MAX_FPS = 100;
static const unsigned int MIN_FRAMETIME = 1000 / MAX_FPS;

int main(int argc, char *argv[])
{
    if (SDL_Init(SDL_INIT_TIMER) < 0) {
        fprintf(stderr, "Could not initialize SDL Timer: %s\n",
                SDL_GetError());
        exit(1);
    }
    Video::init();
    Rand::global.seed();
    UI::Screen::setActive(new UI::Menu);

    unsigned int lastticks = SDL_GetTicks();
    while (1) {
        SDL_Event e;
        while (SDL_PollEvent(&e)) {
            if (!UI::Screen::getActive())
                goto quit;
            switch (e.type) {
            case SDL_QUIT:
                goto quit;
            case SDL_MOUSEMOTION:
            {
                SDL_MouseMotionEvent &m = e.motion;
                int x = m.x, y = Video::height - 1 - m.y;
                UI::Screen::getActive()->
                    handleEvent(UI::MouseEvent(UI::MouseMove, -1, x, y));
                break;
            }
            case SDL_MOUSEBUTTONDOWN:
            case SDL_MOUSEBUTTONUP:
            {
                SDL_MouseButtonEvent &m = e.button;
                UI::EventType t = e.type == SDL_MOUSEBUTTONDOWN ?
                    UI::MouseDown : UI::MouseUp;
                int button;
                switch (m.button) {
                case SDL_BUTTON_LEFT:
                    button = UI::ButtonLeft;
                    break;
                case SDL_BUTTON_MIDDLE:
                    button = UI::ButtonMiddle;
                    break;
                case SDL_BUTTON_RIGHT:
                    button = UI::ButtonRight;
                    break;
                default:
                    button = UI::ButtonOther + m.button - 4;
                    break;
                }
                int x = m.x, y = Video::height - 1 - m.y;
                UI::Screen::getActive()->
                    handleEvent(UI::MouseEvent(t, button, x, y));
                break;
            }
            case SDL_KEYDOWN:
            case SDL_KEYUP:
            {
                SDL_KeyboardEvent &k = e.key;
                UI::EventType t = e.type == SDL_KEYDOWN ?
                    UI::KeyDown : UI::KeyUp;
                UI::Screen::getActive()->
                    handleEvent(UI::KeyEvent(t, k.keysym.sym));
                break;
            }
            default:
                break;
            }
        }
        if (!UI::Screen::getActive())
            goto quit;
        unsigned int ticks = SDL_GetTicks(), delta = ticks - lastticks;
        if (delta < MIN_FRAMETIME) {
            SDL_Delay(MIN_FRAMETIME - delta);
            lastticks += MIN_FRAMETIME;
            ticks = SDL_GetTicks();
        } else
            lastticks = ticks;
        UI::Screen::getActive()->draw(ticks);
        Video::update();
    }

quit:
    SDL_Quit();
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <cstdio>
#include <typeinfo>
#include <iomanip>
#include <algorithm>
#include <cctype>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/X.h>
#include <png.h>
#include <zlib.h>
#include <jpeglib.h>
#include <sys/stat.h>
#include "screenshot.h"
#include "cmdopts.h"
using namespace std;

// main() is where program execution begins.

int main(int argc, char ** argv) {
    Display * display;
    Window root;
    int width = 0;
    int height = 0;
    XWindowAttributes gwa;
    X11Screenshot screenshot;
    // options
    cmd_options opts = process_options(argc, argv);
    if (opts.verbose) {
        cout << "Options" << endl;
        cout << "width: " << opts.width << endl;
        cout << "Height: " << opts.height << endl;
        cout << "Quality: " << opts.quality << endl;
        cout << "Verbose: " << opts.verbose << endl;
        cout << "Path: " << opts.path << endl;
        cout << "Type: " << opts.type << endl;
    }

    display = XOpenDisplay(NULL);
    if (display == NULL) {
        cerr << "No display can be aquired" << endl;
        exit(1);
    }
    root = DefaultRootWindow(display);

    XGetWindowAttributes(display, root, &gwa);
    width = gwa.width;
    height = gwa.height;

    if (opts.verbose) {
        cout << "Original screen width: " << width << endl;
        cout << "Original screen height: " << height << endl;
    }

    XImage * image = XGetImage(
        display,
        root,
        0,
        0,
        width,
        height,
        AllPlanes,
        ZPixmap
    );

    if (string(opts.path).length() == 0 or (string(opts.type) == "jpg" or string(opts.type) == "png")) {
        cerr << "Invalid arguments, use --help to see details." << endl;
        exit(0);
    };

    if ((opts.width != 0 and opts.width != width) and (opts.height != 0 and opts.height != height)) {
        screenshot = X11Screenshot(image, opts.width, opts.height, "bilinear");
        if (opts.verbose) cout << "Process with resizing" << endl;
    } else {
        screenshot = X11Screenshot(image);
        if (opts.verbose) cout << "Process without resizing" << endl;
    }

    if (string(opts.type) == "png") {
        if (opts.verbose) cout << "Saving as png" << endl;
        if (screenshot.save_to_png(opts.path)) {
            if (opts.verbose) cout << "Succesfully saved to " << opts.path << endl;
        }
    }

    if (string(opts.type) == "jpg") {
        if (opts.verbose) cout << "Saving as jpg" << endl;
        if (screenshot.save_to_jpeg(opts.path, opts.quality)) {
            if (opts.verbose) cout << "Succesfully saved to " << opts.path << endl;
        }
    }

    XDestroyImage(image);
    XCloseDisplay(display);
    return 0;
}
<commit_msg>Fix check on path, Remove type check<commit_after>#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <cstdio>
#include <typeinfo>
#include <iomanip>
#include <algorithm>
#include <cctype>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/X.h>
#include <png.h>
#include <zlib.h>
#include <jpeglib.h>
#include <sys/stat.h>
#include "screenshot.h"
#include "cmdopts.h"
using namespace std;

// main() is where program execution begins.

int main(int argc, char ** argv) {
    Display * display;
    Window root;
    int width = 0;
    int height = 0;
    XWindowAttributes gwa;
    X11Screenshot screenshot;
    // options
    cmd_options opts = process_options(argc, argv);
    if (opts.verbose) {
        cout << "Options" << endl;
        cout << "width: " << opts.width << endl;
        cout << "Height: " << opts.height << endl;
        cout << "Quality: " << opts.quality << endl;
        cout << "Verbose: " << opts.verbose << endl;
        cout << "Path: " << opts.path << endl;
        cout << "Type: " << opts.type << endl;
    }

    display = XOpenDisplay(NULL);
    if (display == NULL) {
        cerr << "No display can be aquired" << endl;
        exit(1);
    }
    root = DefaultRootWindow(display);

    XGetWindowAttributes(display, root, &gwa);
    width = gwa.width;
    height = gwa.height;

    if (opts.verbose) {
        cout << "Original screen width: " << width << endl;
        cout << "Original screen height: " << height << endl;
    }

    XImage * image = XGetImage(
        display,
        root,
        0,
        0,
        width,
        height,
        AllPlanes,
        ZPixmap
    );

    if (string(opts.path).length() == 0) {
        cerr << "Invalid arguments, use --help to see details." << endl;
        exit(0);
    };

    if ((opts.width != 0 and opts.width != width) and (opts.height != 0 and opts.height != height)) {
        screenshot = X11Screenshot(image, opts.width, opts.height, "bilinear");
        if (opts.verbose) cout << "Process with resizing" << endl;
    } else {
        screenshot = X11Screenshot(image);
        if (opts.verbose) cout << "Process without resizing" << endl;
    }

    if (string(opts.type) == "png") {
        if (opts.verbose) cout << "Saving as png" << endl;
        if (screenshot.save_to_png(opts.path)) {
            if (opts.verbose) cout << "Succesfully saved to " << opts.path << endl;
        }
    }

    if (string(opts.type) == "jpg") {
        if (opts.verbose) cout << "Saving as jpg" << endl;
        if (screenshot.save_to_jpeg(opts.path, opts.quality)) {
            if (opts.verbose) cout << "Succesfully saved to " << opts.path << endl;
        }
    }

    XDestroyImage(image);
    XCloseDisplay(display);
    return 0;
}
<|endoftext|>


<commit_before>/**
 * Project
 * #    #     #     ######   ######
 * #   #     # #    #     #  #     #
 * #  #     #   #   #     #  #     #
 * ###     #     #  ######   ######
 * #  #    #######  #   #    #   #
 * #   #   #     #  #    #   #    #
 * #    #  #     #  #     #  #     #
 *
 * Copyright (c) 2014, Project KARR
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include <stdio.h>
#include <stdlib.h>

#include <GL/glut.h>
#include <vg/openvg.h>

#include <SDL2/SDL.h>
#include <SDL2/SDL_syswm.h>

#include <bgfx.h>
#include <bgfxplatform.h>

#include <nanovg.h>
#include <nanovg_gl.h>

#include <string>
#include <sstream>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

#include "ArduinoDataPacket.h"
#include "Instrument.h"
#include "SerialConnection.h"
#include "TestInput.h"
#include "Knight_Industries.C"

using namespace KARR;
using namespace std;

/* Globals */
NVGcontext *gNanoVGContext = nullptr;

/* Statics */
static const int w = 1024;
static const int h = 600;
static SDL_Window *sSdlWindow = nullptr;
static SerialConnection sArduinoConnection;
static std::vector<Instrument *> sInstruments;
static ArduinoDataPacket sDataPacket;

void handleKeyboard(unsigned char key, int x, int y) {
    if (key == 27)
	exit(0);
}

void KARRArduinoProtocol(const ArduinoDataPacket &packet) {
    if (packet.version == 7) {
	sInstruments[Instrument::IID_REVS]->update(packet.analog[0]);
	sInstruments[Instrument::IID_SPEED]->update(packet.analog[1]);
	sInstruments[Instrument::IID_FUEL_LEVEL]->update(packet.analog[2]);
	sInstruments[Instrument::IID_BOOST_LEVEL]->update(packet.analog[3]);
    }
}

void handleCommunication() {
    { /* Read data from Arduino */
	if (sArduinoConnection.isOpened()) {
	    memset(&sDataPacket, '\0', sizeof(ArduinoDataPacket));
	    if (sArduinoConnection.read((void *)&sDataPacket, sizeof(ArduinoDataPacket))) {
		// Update data
		KARRArduinoProtocol(sDataPacket);
	    }
	}
    }
}

void handleDisplay() {
    // Set view 0 default viewport.
    bgfx::setViewRect(0, 0, 0, w, h);
    // This dummy draw call is here to make sure that view 0 is cleared
    // if no other draw calls are submitted to view 0.
    bgfx::submit(0);
    // Use debug font to print information about this example.
    bgfx::dbgTextClear();
    bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/00-helloworld");
    bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Initialization and debug text.");

    nvgBeginFrame(gNanoVGContext, w, h, 1.0f);

    for (Instrument *instrument : sInstruments) {
	if (instrument)
	    instrument->draw();
    }

    nvgEndFrame(gNanoVGContext);
    // Advance to next frame. Rendering thread will be kicked to
    // process submitted rendering primitives.
    bgfx::frame();
}

int initScreen() {
    SDL_InitSubSystem(SDL_INIT_VIDEO);

    sSdlWindow = SDL_CreateWindow("karr",
	    SDL_WINDOWPOS_UNDEFINED , SDL_WINDOWPOS_UNDEFINED,
	    w , h , SDL_WINDOW_SHOWN);

    bgfx::sdlSetWindow(sSdlWindow);

    bgfx::init();
    bgfx::reset(w, h, BGFX_RESET_VSYNC);

    gNanoVGContext = nvgCreateGLES2(0);

    // Set view 0 clear state.
    bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH,
	    0x303030ff, 1.0f, 0);

    return 0;
}

void deinitScreen() {
    nvgDeleteGLES2(gNanoVGContext);

    // Shutdown bgfx.
    bgfx::shutdown();

    SDL_DestroyWindow(sSdlWindow);
    SDL_Quit();
}

void initInstruments() {
    boost::filesystem::path instrumentsXMLPath(""); // TODO get path
    boost::property_tree::ptree instrumentsTree;
    boost::property_tree::read_xml(instrumentsXMLPath.string(), instrumentsTree, boost::property_tree::xml_parser::no_comments);

    // Parse into a temp vector.
    std::vector<Instrument *> instruments;
    Instrument::ParseInstruments(instrumentsTree, instruments);

    // Determine max id for size.
    Instrument::InstrumentId maxId = Instrument::IID_UNKNOWN;
    for (Instrument *instr : instruments) {
	if (instr->getId() > maxId)
	    maxId = instr->getId();
    }

    // Populate the instruments with the parsed. May result in sparse vector.
    if (maxId > -1 && maxId < 1024) {
	sInstruments.resize(maxId + 1, nullptr);
	for (Instrument *instr : instruments) {
	    sInstruments[instr->getId()] = instr;
	}
    }
}

void deinitInstruments() {
    for (Instrument *instr : sInstruments) {
	delete instr;
    }
}

void initCommunication() {
    sArduinoConnection.open("/dev/ttyAMA0");
}

void deinitCommunication() {
    sArduinoConnection.close();
}

void cleanup() {
    deinitCommunication();

    deinitInstruments();

    deinitScreen();
}

int main(int argc, char** argv) {
    atexit(cleanup);

    SDL_Init(0);

    initScreen();

    initInstruments();

    initCommunication();

    TestInput::run();

    do {

	SDL_Event event;
	if (SDL_PollEvent(&event)) {
	    // Do something with event
	}
	handleCommunication();
	handleDisplay();
    } while (1);

    return 0;
}
<commit_msg>Assert to have a nanovg context.<commit_after>/**
 * Project
 * #    #     #     ######   ######
 * #   #     # #    #     #  #     #
 * #  #     #   #   #     #  #     #
 * ###     #     #  ######   ######
 * #  #    #######  #   #    #   #
 * #   #   #     #  #    #   #    #
 * #    #  #     #  #     #  #     #
 *
 * Copyright (c) 2014, Project KARR
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include <stdio.h>
#include <stdlib.h>

#include <GL/glut.h>
#include <vg/openvg.h>

#include <SDL2/SDL.h>
#include <SDL2/SDL_syswm.h>

#include <bgfx.h>
#include <bgfxplatform.h>

#include <nanovg.h>
#include <nanovg_gl.h>

#include <string>
#include <sstream>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

#include "ArduinoDataPacket.h"
#include "Instrument.h"
#include "SerialConnection.h"
#include "TestInput.h"
#include "Knight_Industries.C"

using namespace KARR;
using namespace std;

/* Globals */
NVGcontext *gNanoVGContext = nullptr;

/* Statics */
static const int w = 1024;
static const int h = 600;
static SDL_Window *sSdlWindow = nullptr;
static SerialConnection sArduinoConnection;
static std::vector<Instrument *> sInstruments;
static ArduinoDataPacket sDataPacket;

void handleKeyboard(unsigned char key, int x, int y) {
    if (key == 27)
	exit(0);
}

void KARRArduinoProtocol(const ArduinoDataPacket &packet) {
    if (packet.version == 7) {
	sInstruments[Instrument::IID_REVS]->update(packet.analog[0]);
	sInstruments[Instrument::IID_SPEED]->update(packet.analog[1]);
	sInstruments[Instrument::IID_FUEL_LEVEL]->update(packet.analog[2]);
	sInstruments[Instrument::IID_BOOST_LEVEL]->update(packet.analog[3]);
    }
}

void handleCommunication() {
    { /* Read data from Arduino */
	if (sArduinoConnection.isOpened()) {
	    memset(&sDataPacket, '\0', sizeof(ArduinoDataPacket));
	    if (sArduinoConnection.read((void *)&sDataPacket, sizeof(ArduinoDataPacket))) {
		// Update data
		KARRArduinoProtocol(sDataPacket);
	    }
	}
    }
}

void handleDisplay() {
    // Set view 0 default viewport.
    bgfx::setViewRect(0, 0, 0, w, h);
    // This dummy draw call is here to make sure that view 0 is cleared
    // if no other draw calls are submitted to view 0.
    bgfx::submit(0);
    // Use debug font to print information about this example.
    bgfx::dbgTextClear();
    bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/00-helloworld");
    bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Initialization and debug text.");

    nvgBeginFrame(gNanoVGContext, w, h, 1.0f);

    for (Instrument *instrument : sInstruments) {
	if (instrument)
	    instrument->draw();
    }

    nvgEndFrame(gNanoVGContext);
    // Advance to next frame. Rendering thread will be kicked to
    // process submitted rendering primitives.
    bgfx::frame();
}

int initScreen() {
    SDL_InitSubSystem(SDL_INIT_VIDEO);

    sSdlWindow = SDL_CreateWindow("karr",
	    SDL_WINDOWPOS_UNDEFINED , SDL_WINDOWPOS_UNDEFINED,
	    w , h , SDL_WINDOW_SHOWN);

    bgfx::sdlSetWindow(sSdlWindow);

    bgfx::init();
    bgfx::reset(w, h, BGFX_RESET_VSYNC);

    gNanoVGContext = nvgCreateGLES2(0);
    assert(gNanoVGContext);

    // Set view 0 clear state.
    bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH,
	    0x303030ff, 1.0f, 0);

    return 0;
}

void deinitScreen() {
    nvgDeleteGLES2(gNanoVGContext);

    // Shutdown bgfx.
    bgfx::shutdown();

    SDL_DestroyWindow(sSdlWindow);
    SDL_Quit();
}

void initInstruments() {
    boost::filesystem::path instrumentsXMLPath(""); // TODO get path
    boost::property_tree::ptree instrumentsTree;
    boost::property_tree::read_xml(instrumentsXMLPath.string(), instrumentsTree, boost::property_tree::xml_parser::no_comments);

    // Parse into a temp vector.
    std::vector<Instrument *> instruments;
    Instrument::ParseInstruments(instrumentsTree, instruments);

    // Determine max id for size.
    Instrument::InstrumentId maxId = Instrument::IID_UNKNOWN;
    for (Instrument *instr : instruments) {
	if (instr->getId() > maxId)
	    maxId = instr->getId();
    }

    // Populate the instruments with the parsed. May result in sparse vector.
    if (maxId > -1 && maxId < 1024) {
	sInstruments.resize(maxId + 1, nullptr);
	for (Instrument *instr : instruments) {
	    sInstruments[instr->getId()] = instr;
	}
    }
}

void deinitInstruments() {
    for (Instrument *instr : sInstruments) {
	delete instr;
    }
}

void initCommunication() {
    sArduinoConnection.open("/dev/ttyAMA0");
}

void deinitCommunication() {
    sArduinoConnection.close();
}

void cleanup() {
    deinitCommunication();

    deinitInstruments();

    deinitScreen();
}

int main(int argc, char** argv) {
    atexit(cleanup);

    SDL_Init(0);

    initScreen();

    initInstruments();

    initCommunication();

    TestInput::run();

    do {

	SDL_Event event;
	if (SDL_PollEvent(&event)) {
	    // Do something with event
	}
	handleCommunication();
	handleDisplay();
    } while (1);

    return 0;
}
<|endoftext|>


<commit_before>#include <QCoreApplication>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Configuration conf;
    qDebug() << conf.getUserAgent();
    return a.exec();
}

<commit_msg>delete main in src<commit_after><|endoftext|>


<commit_before>/*! \file main.cpp
 *  \brief Program to run the grid code. */

#ifdef MPI_CHOLLA
#include <mpi.h>
#include "mpi_routines.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "global.h"
#include "grid3D.h"
#include "io.h"
#include "error_handling.h"

int main(int argc, char *argv[])
{
  // timing variables
  double start_total, stop_total, start_step, stop_step;
  #ifdef CPU_TIME
  double stop_init, init_min, init_max, init_avg;
  double start_bound, stop_bound, bound_min, bound_max, bound_avg;
  double start_hydro, stop_hydro, hydro_min, hydro_max, hydro_avg;
  double init, bound, hydro;
  init = bound = hydro = 0;
  #endif //CPU_TIME

  // start the total time
  start_total = get_time();

  /* Initialize MPI communication */
  #ifdef MPI_CHOLLA
  InitializeChollaMPI(&argc, &argv);
  #endif /*MPI_CHOLLA*/

  Real dti = 0; // inverse time step, 1.0 / dt

  // input parameter variables
  char *param_file;
  struct parameters P;
  int nfile = 0; // number of output files
  Real outtime = 0; // current output time

  // read in command line arguments
  if (argc != 2)
  {
    chprintf("usage: %s <parameter_file>\n", argv[0]);
    chexit(-1);
  } else {
    param_file = argv[1];
  }

  // create the grid
  Grid3D G;

  // read in the parameters
  parse_params (param_file, &P);
  // and output to screen
  chprintf ("Parameter values:  nx = %d, ny = %d, nz = %d, tout = %f, init = %s, boundaries = %d %d %d %d %d %d\n",
    P.nx, P.ny, P.nz, P.tout, P.init, P.xl_bcnd, P.xu_bcnd, P.yl_bcnd, P.yu_bcnd, P.zl_bcnd, P.zu_bcnd);
  if (strcmp(P.init, "Read_Grid") == 0  ) chprintf ("Input directory:  %s\n", P.indir);
  chprintf ("Output directory:  %s\n", P.outdir);

  //Create a Log file to output run-time messages
  Create_Log_File(P);

  // initialize the grid
  G.Initialize(&P);
  chprintf("Local number of grid cells: %d %d %d %d\n", G.H.nx_real, G.H.ny_real, G.H.nz_real, G.H.n_cells);

  char *message = (char*)malloc(50 * sizeof(char));
  sprintf(message, "Initializing Simulation" );
  Write_Message_To_Log_File( message );

  // Set initial conditions and calculate first dt
  chprintf("Setting initial conditions...\n");
  G.Set_Initial_Conditions(P);
  chprintf("Initial conditions set.\n");
  // set main variables for Read_Grid initial conditions
  if (strcmp(P.init, "Read_Grid") == 0) {
    dti = C_cfl / G.H.dt;
    outtime += G.H.t;
    nfile = P.nfile;
  }

  #ifdef DE
  chprintf("\nUsing Dual Energy Formalism:\n eta_1: %0.3f   eta_2: %0.4f\n", DE_ETA_1, DE_ETA_2 );
  sprintf(message, " eta_1: %0.3f   eta_2: %0.3f  ", DE_ETA_1, DE_ETA_2 );
  Write_Message_To_Log_File( message );
  #endif

  #ifdef CPU_TIME
  G.Timer.Initialize();
  #endif

  #ifdef GRAVITY
  G.Initialize_Gravity(&P);
  #endif

  #ifdef PARTICLES
  G.Initialize_Particles(&P);
  #endif

  #ifdef COSMOLOGY
  G.Initialize_Cosmology(&P);
  #endif

  #ifdef COOLING_GRACKLE
  G.Initialize_Grackle(&P);
  #endif

  #ifdef ANALYSIS
  G.Initialize_Analysis_Module(&P);
  if ( G.Analysis.Output_Now ) G.Compute_and_Output_Analysis(&P);
  #endif

  #ifdef GRAVITY
  // Get the gravitaional potential for the first timestep
  G.Compute_Gravitational_Potential( &P);
  #endif

  // Set boundary conditions (assign appropriate values to ghost cells) for hydro and potential
  chprintf("Setting boundary conditions...\n");
  G.Set_Boundary_Conditions_Grid(P);
  chprintf("Boundary conditions set.\n");

  #ifdef GRAVITY_ANALYTIC_COMP
  // add analytic component to gravity potential.
  G.Add_Analytic_Potential(&P);
  #endif

  #ifdef PARTICLES
  // Get the particles acceleration for the first timestep
  G.Get_Particles_Acceleration();
  #endif

  chprintf("Dimensions of each cell: dx = %f dy = %f dz = %f\n", G.H.dx, G.H.dy, G.H.dz);
  chprintf("Ratio of specific heats gamma = %f\n",gama);
  chprintf("Nstep = %d  Timestep = %f  Simulation time = %f\n", G.H.n_step, G.H.dt, G.H.t);

  #ifdef OUTPUT
  if (strcmp(P.init, "Read_Grid") != 0 || G.H.Output_Now ) {
    // write the initial conditions to file
    chprintf("Writing initial conditions to file...\n");
    #ifdef HYDRO_GPU
    cudaMemcpy(G.C.density, G.C.device,
             G.H.n_fields*G.H.n_cells*sizeof(Real), cudaMemcpyDeviceToHost);
    #endif
    WriteData(G, P, nfile);
  }
  // add one to the output file count
  nfile++;
  #endif //OUTPUT
  // increment the next output time
  outtime += P.outstep;

  #ifdef CPU_TIME
  stop_init = get_time();
  init = stop_init - start_total;
  #ifdef MPI_CHOLLA
  init_min = ReduceRealMin(init);
  init_max = ReduceRealMax(init);
  init_avg = ReduceRealAvg(init);
  chprintf("Init  min: %9.4f  max: %9.4f  avg: %9.4f\n", init_min, init_max, init_avg);
  #else
  printf("Init %9.4f\n", init);
  #endif //MPI_CHOLLA
  #endif //CPU_TIME

  // Evolve the grid, one timestep at a time
  chprintf("Starting calculations.\n");
  sprintf(message, "Starting calculations." );
  Write_Message_To_Log_File( message );
  while (G.H.t < P.tout)
  {
    // get the start time
    start_step = get_time();

    // calculate the timestep
    G.set_dt(dti);

    if (G.H.t + G.H.dt > outtime) G.H.dt = outtime - G.H.t;

    #ifdef PARTICLES
    //Advance the particles KDK( first step ): Velocities are updated by 0.5*dt and positions are updated by dt
    G.Advance_Particles( 1 );
    //Transfer the particles that moved outside the local domain
    G.Transfer_Particles_Boundaries(P);
    #endif

    // Advance the grid by one timestep
    dti = G.Update_Hydro_Grid();

    // update the simulation time ( t += dt )
    G.Update_Time();

    #ifdef GRAVITY
    //Compute Gravitational potential for next step
    G.Compute_Gravitational_Potential( &P);
    #endif

    // add one to the timestep count
    G.H.n_step++;

    //Set the Grid boundary conditions for next time step
    G.Set_Boundary_Conditions_Grid(P);

    #ifdef GRAVITY_ANALYTIC_COMP
    // add analytic component to gravity potential.
    G.Add_Analytic_Potential(&P);
    #endif

    #ifdef PARTICLES
    ///Advance the particles KDK( second step ): Velocities are updated by 0.5*dt using the Accelerations at the new positions
    G.Advance_Particles( 2 );
    #endif

    #ifdef PARTICLE_AGE
    //G.Cluster_Feedback();
    #endif

    #ifdef CPU_TIME
    G.Timer.Print_Times();
    #endif

    // get the time to compute the total timestep
    stop_step = get_time();
    stop_total = get_time();
    G.H.t_wall = stop_total-start_total;
    #ifdef MPI_CHOLLA
    G.H.t_wall = ReduceRealMax(G.H.t_wall);
    #endif
    chprintf("n_step: %d   sim time: %10.7f   sim timestep: %7.4e  timestep time = %9.3f ms   total time = %9.4f s\n\n",
      G.H.n_step, G.H.t, G.H.dt, (stop_step-start_step)*1000, G.H.t_wall);

    #ifdef OUTPUT_ALWAYS
    G.H.Output_Now = true;
    #endif

    #ifdef ANALYSIS
    if ( G.Analysis.Output_Now ) G.Compute_and_Output_Analysis(&P);
    #endif

    // if ( P.n_steps_output > 0 && G.H.n_step % P.n_steps_output == 0) G.H.Output_Now = true;

    if (G.H.t == outtime || G.H.Output_Now )
    {
      #ifdef OUTPUT
      /*output the grid data*/
      #ifdef HYDRO_GPU
      cudaMemcpy(G.C.density, G.C.device,
                 G.H.n_fields*G.H.n_cells*sizeof(Real), cudaMemcpyDeviceToHost);
      #endif
      WriteData(G, P, nfile);
      // add one to the output file count
      nfile++;
      #endif //OUTPUT
      // update to the next output time
      outtime += P.outstep;
    }

    #ifdef CPU_TIME
    G.Timer.n_steps += 1;
    #endif

    #ifdef N_STEPS_LIMIT
    // Exit the loop when reached the limit number of steps (optional)
    if ( G.H.n_step == N_STEPS_LIMIT) {
      #ifdef HYDRO_GPU
      cudaMemcpy(G.C.density, G.C.device,
                 G.H.n_fields*G.H.n_cells*sizeof(Real), cudaMemcpyDeviceToHost);
      #endif
      WriteData(G, P, nfile);
      #endif //COSMOLOGY
      break;
    }
    #endif

    #ifdef COSMOLOGY
    // Exit the loop when reached the last scale_factor output
    if ( G.Cosmo.exit_now ) {
      chprintf( "\nReached Last Cosmological Output: Ending Simulation\n");
      break;
    }
    #endif

  } /*end loop over timesteps*/

  #ifdef CPU_TIME
  // Print timing statistics
  G.Timer.Get_Average_Times();
  G.Timer.Print_Average_Times( P );
  #endif

  sprintf(message, "Simulation completed successfully." );
  Write_Message_To_Log_File( message );

  // free the grid
  G.Reset();

  #ifdef MPI_CHOLLA
  MPI_Finalize();
  #endif /*MPI_CHOLLA*/

  return 0;

}
<commit_msg>fixed extra #endif<commit_after>/*! \file main.cpp
 *  \brief Program to run the grid code. */

#ifdef MPI_CHOLLA
#include <mpi.h>
#include "mpi_routines.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "global.h"
#include "grid3D.h"
#include "io.h"
#include "error_handling.h"

int main(int argc, char *argv[])
{
  // timing variables
  double start_total, stop_total, start_step, stop_step;
  #ifdef CPU_TIME
  double stop_init, init_min, init_max, init_avg;
  double start_bound, stop_bound, bound_min, bound_max, bound_avg;
  double start_hydro, stop_hydro, hydro_min, hydro_max, hydro_avg;
  double init, bound, hydro;
  init = bound = hydro = 0;
  #endif //CPU_TIME

  // start the total time
  start_total = get_time();

  /* Initialize MPI communication */
  #ifdef MPI_CHOLLA
  InitializeChollaMPI(&argc, &argv);
  #endif /*MPI_CHOLLA*/

  Real dti = 0; // inverse time step, 1.0 / dt

  // input parameter variables
  char *param_file;
  struct parameters P;
  int nfile = 0; // number of output files
  Real outtime = 0; // current output time

  // read in command line arguments
  if (argc != 2)
  {
    chprintf("usage: %s <parameter_file>\n", argv[0]);
    chexit(-1);
  } else {
    param_file = argv[1];
  }

  // create the grid
  Grid3D G;

  // read in the parameters
  parse_params (param_file, &P);
  // and output to screen
  chprintf ("Parameter values:  nx = %d, ny = %d, nz = %d, tout = %f, init = %s, boundaries = %d %d %d %d %d %d\n",
    P.nx, P.ny, P.nz, P.tout, P.init, P.xl_bcnd, P.xu_bcnd, P.yl_bcnd, P.yu_bcnd, P.zl_bcnd, P.zu_bcnd);
  if (strcmp(P.init, "Read_Grid") == 0  ) chprintf ("Input directory:  %s\n", P.indir);
  chprintf ("Output directory:  %s\n", P.outdir);

  //Create a Log file to output run-time messages
  Create_Log_File(P);

  // initialize the grid
  G.Initialize(&P);
  chprintf("Local number of grid cells: %d %d %d %d\n", G.H.nx_real, G.H.ny_real, G.H.nz_real, G.H.n_cells);

  char *message = (char*)malloc(50 * sizeof(char));
  sprintf(message, "Initializing Simulation" );
  Write_Message_To_Log_File( message );

  // Set initial conditions and calculate first dt
  chprintf("Setting initial conditions...\n");
  G.Set_Initial_Conditions(P);
  chprintf("Initial conditions set.\n");
  // set main variables for Read_Grid initial conditions
  if (strcmp(P.init, "Read_Grid") == 0) {
    dti = C_cfl / G.H.dt;
    outtime += G.H.t;
    nfile = P.nfile;
  }

  #ifdef DE
  chprintf("\nUsing Dual Energy Formalism:\n eta_1: %0.3f   eta_2: %0.4f\n", DE_ETA_1, DE_ETA_2 );
  sprintf(message, " eta_1: %0.3f   eta_2: %0.3f  ", DE_ETA_1, DE_ETA_2 );
  Write_Message_To_Log_File( message );
  #endif

  #ifdef CPU_TIME
  G.Timer.Initialize();
  #endif

  #ifdef GRAVITY
  G.Initialize_Gravity(&P);
  #endif

  #ifdef PARTICLES
  G.Initialize_Particles(&P);
  #endif

  #ifdef COSMOLOGY
  G.Initialize_Cosmology(&P);
  #endif

  #ifdef COOLING_GRACKLE
  G.Initialize_Grackle(&P);
  #endif

  #ifdef ANALYSIS
  G.Initialize_Analysis_Module(&P);
  if ( G.Analysis.Output_Now ) G.Compute_and_Output_Analysis(&P);
  #endif

  #ifdef GRAVITY
  // Get the gravitaional potential for the first timestep
  G.Compute_Gravitational_Potential( &P);
  #endif

  // Set boundary conditions (assign appropriate values to ghost cells) for hydro and potential
  chprintf("Setting boundary conditions...\n");
  G.Set_Boundary_Conditions_Grid(P);
  chprintf("Boundary conditions set.\n");

  #ifdef GRAVITY_ANALYTIC_COMP
  // add analytic component to gravity potential.
  G.Add_Analytic_Potential(&P);
  #endif

  #ifdef PARTICLES
  // Get the particles acceleration for the first timestep
  G.Get_Particles_Acceleration();
  #endif

  chprintf("Dimensions of each cell: dx = %f dy = %f dz = %f\n", G.H.dx, G.H.dy, G.H.dz);
  chprintf("Ratio of specific heats gamma = %f\n",gama);
  chprintf("Nstep = %d  Timestep = %f  Simulation time = %f\n", G.H.n_step, G.H.dt, G.H.t);

  #ifdef OUTPUT
  if (strcmp(P.init, "Read_Grid") != 0 || G.H.Output_Now ) {
    // write the initial conditions to file
    chprintf("Writing initial conditions to file...\n");
    #ifdef HYDRO_GPU
    cudaMemcpy(G.C.density, G.C.device,
             G.H.n_fields*G.H.n_cells*sizeof(Real), cudaMemcpyDeviceToHost);
    #endif
    WriteData(G, P, nfile);
  }
  // add one to the output file count
  nfile++;
  #endif //OUTPUT
  // increment the next output time
  outtime += P.outstep;

  #ifdef CPU_TIME
  stop_init = get_time();
  init = stop_init - start_total;
  #ifdef MPI_CHOLLA
  init_min = ReduceRealMin(init);
  init_max = ReduceRealMax(init);
  init_avg = ReduceRealAvg(init);
  chprintf("Init  min: %9.4f  max: %9.4f  avg: %9.4f\n", init_min, init_max, init_avg);
  #else
  printf("Init %9.4f\n", init);
  #endif //MPI_CHOLLA
  #endif //CPU_TIME

  // Evolve the grid, one timestep at a time
  chprintf("Starting calculations.\n");
  sprintf(message, "Starting calculations." );
  Write_Message_To_Log_File( message );
  while (G.H.t < P.tout)
  {
    // get the start time
    start_step = get_time();

    // calculate the timestep
    G.set_dt(dti);

    if (G.H.t + G.H.dt > outtime) G.H.dt = outtime - G.H.t;

    #ifdef PARTICLES
    //Advance the particles KDK( first step ): Velocities are updated by 0.5*dt and positions are updated by dt
    G.Advance_Particles( 1 );
    //Transfer the particles that moved outside the local domain
    G.Transfer_Particles_Boundaries(P);
    #endif

    // Advance the grid by one timestep
    dti = G.Update_Hydro_Grid();

    // update the simulation time ( t += dt )
    G.Update_Time();

    #ifdef GRAVITY
    //Compute Gravitational potential for next step
    G.Compute_Gravitational_Potential( &P);
    #endif

    // add one to the timestep count
    G.H.n_step++;

    //Set the Grid boundary conditions for next time step
    G.Set_Boundary_Conditions_Grid(P);

    #ifdef GRAVITY_ANALYTIC_COMP
    // add analytic component to gravity potential.
    G.Add_Analytic_Potential(&P);
    #endif

    #ifdef PARTICLES
    ///Advance the particles KDK( second step ): Velocities are updated by 0.5*dt using the Accelerations at the new positions
    G.Advance_Particles( 2 );
    #endif

    #ifdef PARTICLE_AGE
    //G.Cluster_Feedback();
    #endif

    #ifdef CPU_TIME
    G.Timer.Print_Times();
    #endif

    // get the time to compute the total timestep
    stop_step = get_time();
    stop_total = get_time();
    G.H.t_wall = stop_total-start_total;
    #ifdef MPI_CHOLLA
    G.H.t_wall = ReduceRealMax(G.H.t_wall);
    #endif
    chprintf("n_step: %d   sim time: %10.7f   sim timestep: %7.4e  timestep time = %9.3f ms   total time = %9.4f s\n\n",
      G.H.n_step, G.H.t, G.H.dt, (stop_step-start_step)*1000, G.H.t_wall);

    #ifdef OUTPUT_ALWAYS
    G.H.Output_Now = true;
    #endif

    #ifdef ANALYSIS
    if ( G.Analysis.Output_Now ) G.Compute_and_Output_Analysis(&P);
    #endif

    // if ( P.n_steps_output > 0 && G.H.n_step % P.n_steps_output == 0) G.H.Output_Now = true;

    if (G.H.t == outtime || G.H.Output_Now )
    {
      #ifdef OUTPUT
      /*output the grid data*/
      #ifdef HYDRO_GPU
      cudaMemcpy(G.C.density, G.C.device,
                 G.H.n_fields*G.H.n_cells*sizeof(Real), cudaMemcpyDeviceToHost);
      #endif
      WriteData(G, P, nfile);
      // add one to the output file count
      nfile++;
      #endif //OUTPUT
      // update to the next output time
      outtime += P.outstep;
    }

    #ifdef CPU_TIME
    G.Timer.n_steps += 1;
    #endif

    #ifdef N_STEPS_LIMIT
    // Exit the loop when reached the limit number of steps (optional)
    if ( G.H.n_step == N_STEPS_LIMIT) {
      #ifdef HYDRO_GPU
      cudaMemcpy(G.C.density, G.C.device,
                 G.H.n_fields*G.H.n_cells*sizeof(Real), cudaMemcpyDeviceToHost);
      #endif
      WriteData(G, P, nfile);
      break;
    }
    #endif

    #ifdef COSMOLOGY
    // Exit the loop when reached the last scale_factor output
    if ( G.Cosmo.exit_now ) {
      chprintf( "\nReached Last Cosmological Output: Ending Simulation\n");
      break;
    }
    #endif

  } /*end loop over timesteps*/

  #ifdef CPU_TIME
  // Print timing statistics
  G.Timer.Get_Average_Times();
  G.Timer.Print_Average_Times( P );
  #endif

  sprintf(message, "Simulation completed successfully." );
  Write_Message_To_Log_File( message );

  // free the grid
  G.Reset();

  #ifdef MPI_CHOLLA
  MPI_Finalize();
  #endif /*MPI_CHOLLA*/

  return 0;

}
<|endoftext|>