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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkContourModelGLMapper2D.h"
#include "mitkBaseRenderer.h"
#include "mitkPlaneGeometry.h"
#include "mitkColorProperty.h"
#include "mitkProperties.h"
#include "mitkContourModel.h"
#include "mitkContourModelSubDivisionFilter.h"
#include <vtkLinearTransform.h>

#include "mitkGL.h"

mitk::ContourModelGLMapper2D::ContourModelGLMapper2D()
{
}

mitk::ContourModelGLMapper2D::~ContourModelGLMapper2D()
{
}

void mitk::ContourModelGLMapper2D::Paint(mitk::BaseRenderer * renderer)
{
  BaseLocalStorage *ls = m_LSH.GetLocalStorage(renderer);

  bool visible = true;
  GetDataNode()->GetVisibility(visible, renderer, "visible");

  if ( !visible ) return;

  bool updateNeccesary=true;

  int timestep = renderer->GetTimeStep();

  mitk::ContourModel::Pointer input =  const_cast<mitk::ContourModel*>(this->GetInput());
  mitk::ContourModel::Pointer renderingContour = input;

  bool subdivision = false;
  this->GetDataNode()->GetBoolProperty( "subdivision curve", subdivision, renderer );
  if (subdivision)
  {

    mitk::ContourModel::Pointer subdivContour = mitk::ContourModel::New();

    mitk::ContourModelSubDivisionFilter::Pointer subdivFilter = mitk::ContourModelSubDivisionFilter::New();

    subdivFilter->SetInput(input);
    subdivFilter->Update();

    subdivContour = subdivFilter->GetOutput();

    if(subdivContour->GetNumberOfVertices() == 0 )
    {
      subdivContour = input;
    }

    renderingContour = subdivContour;
  }

  renderingContour->UpdateOutputInformation();

  if( renderingContour->GetMTime() < ls->GetLastGenerateDataTime() )
    updateNeccesary = false;

  if(renderingContour->GetNumberOfVertices(timestep) < 1)
    updateNeccesary = false;

  if (updateNeccesary)
  {
    // ok, das ist aus GenerateData kopiert
    mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry();
    assert(displayGeometry.IsNotNull());

    //apply color and opacity read from the PropertyList
    ApplyProperties(renderer);

    bool isEditing = false;
    GetDataNode()->GetBoolProperty("contour.editing", isEditing);

    mitk::ColorProperty::Pointer colorprop;

    if (isEditing)
        colorprop = dynamic_cast<mitk::ColorProperty*>(GetDataNode()->GetProperty("contour.editing.color", renderer));
    else
        colorprop = dynamic_cast<mitk::ColorProperty*>(GetDataNode()->GetProperty("contour.color", renderer));

    if(colorprop)
    {
      //set the color of the contour
      double red = colorprop->GetColor().GetRed();
      double green = colorprop->GetColor().GetGreen();
      double blue = colorprop->GetColor().GetBlue();
      glColor4f(red,green,blue,0.5);
    }

    mitk::ColorProperty::Pointer selectedcolor = dynamic_cast<mitk::ColorProperty*>(GetDataNode()->GetProperty("points.color", renderer));
    if(!selectedcolor)
    {
      selectedcolor = mitk::ColorProperty::New(1.0,0.0,0.1);
    }

    vtkLinearTransform* transform = GetDataNode()->GetVtkTransform();

    //    ContourModel::OutputType point;
    mitk::Point3D point;

    mitk::Point3D p, projected_p;
    float vtkp[3];
    float lineWidth = 3.0;

    bool isHovering = false;
    this->GetDataNode()->GetBoolProperty("contour.hovering", isHovering);

    if (isHovering)
        this->GetDataNode()->GetFloatProperty("contour.hovering.width", lineWidth);
    else
        this->GetDataNode()->GetFloatProperty("contour.width", lineWidth);

    bool drawit=false;

    mitk::ContourModel::VertexIterator pointsIt = renderingContour->IteratorBegin(timestep);

    Point2D pt2d;       // projected_p in display coordinates
    Point2D lastPt2d;

    while ( pointsIt != renderingContour->IteratorEnd(timestep) )
    {
      lastPt2d = pt2d;

      point = (*pointsIt)->Coordinates;

      itk2vtk(point, vtkp);
      transform->TransformPoint(vtkp, vtkp);
      vtk2itk(vtkp,p);

      displayGeometry->Project(p, projected_p);

      displayGeometry->Map(projected_p, pt2d);
      displayGeometry->WorldToDisplay(pt2d, pt2d);

      Vector3D diff=p-projected_p;
      ScalarType scalardiff = diff.GetNorm();

      //draw lines
      bool projectmode=false;
      GetDataNode()->GetVisibility(projectmode, renderer, "contour.project-onto-plane");

      if(projectmode)
      {
        drawit=true;
      }
      else if(scalardiff<0.25)
      {
        drawit=true;
      }

      if(drawit)
      {
        //lastPt2d is not valid in first step
        if( !(pointsIt == renderingContour->IteratorBegin(timestep)) )
        {
          glLineWidth(lineWidth);
          glBegin (GL_LINES);
          glVertex2f(pt2d[0], pt2d[1]);
          glVertex2f(lastPt2d[0], lastPt2d[1]);
          glEnd();
        }

        //draw active points
        if ((*pointsIt)->IsControlPoint)
        {
          float pointsize = 4;
          Point2D  tmp;

          Vector2D horz,vert;
          horz[1]=0;
          vert[0]=0;
          horz[0]=pointsize;
          vert[1]=pointsize;
          glColor3f(selectedcolor->GetColor().GetRed(), selectedcolor->GetColor().GetBlue(), selectedcolor->GetColor().GetGreen());
          glLineWidth(1);
          //a rectangle around the point with the selected color
          glBegin (GL_LINE_LOOP);
          tmp=pt2d-horz;      glVertex2fv(&tmp[0]);
          tmp=pt2d+vert;      glVertex2fv(&tmp[0]);
          tmp=pt2d+horz;      glVertex2fv(&tmp[0]);
          tmp=pt2d-vert;      glVertex2fv(&tmp[0]);
          glEnd();
          glLineWidth(1);
          //the actual point in the specified color to see the usual color of the point
          glColor3f(colorprop->GetColor().GetRed(),colorprop->GetColor().GetGreen(),colorprop->GetColor().GetBlue());
          glPointSize(1);
          glBegin (GL_POINTS);
          tmp=pt2d;             glVertex2fv(&tmp[0]);
          glEnd ();
        }
      }

      pointsIt++;
    }//end while iterate over controlpoints

    // make sure the line is set back to default value
    glLineWidth(1);

    //close contour if necessary
    if(renderingContour->IsClosed(timestep) && drawit)
    {
      lastPt2d = pt2d;
      point = renderingContour->GetVertexAt(0,timestep)->Coordinates;
      itk2vtk(point, vtkp);
      transform->TransformPoint(vtkp, vtkp);
      vtk2itk(vtkp,p);
      displayGeometry->Project(p, projected_p);
      displayGeometry->Map(projected_p, pt2d);
      displayGeometry->WorldToDisplay(pt2d, pt2d);

      glBegin (GL_LINES);
      glVertex2f(lastPt2d[0], lastPt2d[1]);
      glVertex2f( pt2d[0], pt2d[1] );
      glEnd();
    }

    //draw selected vertex if exists
    if(renderingContour->GetSelectedVertex())
    {
      //transform selected vertex
      point = renderingContour->GetSelectedVertex()->Coordinates;

      itk2vtk(point, vtkp);
      transform->TransformPoint(vtkp, vtkp);
      vtk2itk(vtkp,p);

      displayGeometry->Project(p, projected_p);

      displayGeometry->Map(projected_p, pt2d);
      displayGeometry->WorldToDisplay(pt2d, pt2d);

      Vector3D diff=p-projected_p;
      ScalarType scalardiff = diff.GetNorm();
      //----------------------------------

      //draw point if close to plane
      if(scalardiff<0.25)
      {

        float pointsize = 3.2;
        Point2D  tmp;
        glColor3f(0.0, 1.0, 0.0);
        glLineWidth(1);
        //a diamond around the point
        glBegin (GL_LINE_LOOP);
        //begin from upper left corner and paint clockwise
        tmp[0]=pt2d[0]-pointsize;    tmp[1]=pt2d[1]+pointsize;    glVertex2fv(&tmp[0]);
        tmp[0]=pt2d[0]+pointsize;    tmp[1]=pt2d[1]+pointsize;    glVertex2fv(&tmp[0]);
        tmp[0]=pt2d[0]+pointsize;    tmp[1]=pt2d[1]-pointsize;    glVertex2fv(&tmp[0]);
        tmp[0]=pt2d[0]-pointsize;    tmp[1]=pt2d[1]-pointsize;    glVertex2fv(&tmp[0]);
        glEnd ();
      }
      //------------------------------------
    }
  }
}

const mitk::ContourModel* mitk::ContourModelGLMapper2D::GetInput(void)
{
  return static_cast<const mitk::ContourModel * > ( GetDataNode()->GetData() );
}

void mitk::ContourModelGLMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{
  node->AddProperty( "contour.color", ColorProperty::New(0.9, 1.0, 0.1), renderer, overwrite );
  node->AddProperty( "contour.editing", mitk::BoolProperty::New( false ), renderer, overwrite );
  node->AddProperty( "contour.editing.color", ColorProperty::New(0.1, 0.9, 0.1), renderer, overwrite );
  node->AddProperty( "points.color", ColorProperty::New(1.0, 0.0, 0.1), renderer, overwrite );
  node->AddProperty( "contour.width", mitk::FloatProperty::New( 1.0 ), renderer, overwrite );
  node->AddProperty( "contour.hovering.width", mitk::FloatProperty::New( 3.0 ), renderer, overwrite );
  node->AddProperty( "contour.hovering", mitk::BoolProperty::New( false ), renderer, overwrite );

  node->AddProperty( "subdivision curve", mitk::BoolProperty::New( false ), renderer, overwrite );
  node->AddProperty( "contour.project-onto-plane", mitk::BoolProperty::New( false ), renderer, overwrite );

  Superclass::SetDefaultProperties(node, renderer, overwrite);
}
<commit_msg>- fixed closing contour. - set a bigger box for selected vertex<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkContourModelGLMapper2D.h"
#include "mitkBaseRenderer.h"
#include "mitkPlaneGeometry.h"
#include "mitkColorProperty.h"
#include "mitkProperties.h"
#include "mitkContourModel.h"
#include "mitkContourModelSubDivisionFilter.h"
#include <vtkLinearTransform.h>

#include "mitkGL.h"

mitk::ContourModelGLMapper2D::ContourModelGLMapper2D()
{
}

mitk::ContourModelGLMapper2D::~ContourModelGLMapper2D()
{
}

void mitk::ContourModelGLMapper2D::Paint(mitk::BaseRenderer * renderer)
{
  BaseLocalStorage *ls = m_LSH.GetLocalStorage(renderer);

  bool visible = true;
  GetDataNode()->GetVisibility(visible, renderer, "visible");

  if ( !visible ) return;

  bool updateNeccesary=true;

  int timestep = renderer->GetTimeStep();

  mitk::ContourModel::Pointer input =  const_cast<mitk::ContourModel*>(this->GetInput());
  mitk::ContourModel::Pointer renderingContour = input;

  bool subdivision = false;
  this->GetDataNode()->GetBoolProperty( "subdivision curve", subdivision, renderer );
  if (subdivision)
  {

    mitk::ContourModel::Pointer subdivContour = mitk::ContourModel::New();

    mitk::ContourModelSubDivisionFilter::Pointer subdivFilter = mitk::ContourModelSubDivisionFilter::New();

    subdivFilter->SetInput(input);
    subdivFilter->Update();

    subdivContour = subdivFilter->GetOutput();

    if(subdivContour->GetNumberOfVertices() == 0 )
    {
      subdivContour = input;
    }

    renderingContour = subdivContour;
  }

  renderingContour->UpdateOutputInformation();

  if( renderingContour->GetMTime() < ls->GetLastGenerateDataTime() )
    updateNeccesary = false;

  if(renderingContour->GetNumberOfVertices(timestep) < 1)
    updateNeccesary = false;

  if (updateNeccesary)
  {
    // ok, das ist aus GenerateData kopiert
    mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry();
    assert(displayGeometry.IsNotNull());

    //apply color and opacity read from the PropertyList
    ApplyProperties(renderer);

    bool isEditing = false;
    GetDataNode()->GetBoolProperty("contour.editing", isEditing);

    mitk::ColorProperty::Pointer colorprop;

    if (isEditing)
        colorprop = dynamic_cast<mitk::ColorProperty*>(GetDataNode()->GetProperty("contour.editing.color", renderer));
    else
        colorprop = dynamic_cast<mitk::ColorProperty*>(GetDataNode()->GetProperty("contour.color", renderer));

    if(colorprop)
    {
      //set the color of the contour
      double red = colorprop->GetColor().GetRed();
      double green = colorprop->GetColor().GetGreen();
      double blue = colorprop->GetColor().GetBlue();
      glColor4f(red,green,blue,0.5);
    }

    mitk::ColorProperty::Pointer selectedcolor = dynamic_cast<mitk::ColorProperty*>(GetDataNode()->GetProperty("points.color", renderer));
    if(!selectedcolor)
    {
      selectedcolor = mitk::ColorProperty::New(1.0,0.0,0.1);
    }

    vtkLinearTransform* transform = GetDataNode()->GetVtkTransform();

    //    ContourModel::OutputType point;
    mitk::Point3D point;

    mitk::Point3D p, projected_p;
    float vtkp[3];
    float lineWidth = 3.0;

    bool isHovering = false;
    this->GetDataNode()->GetBoolProperty("contour.hovering", isHovering);

    if (isHovering)
        this->GetDataNode()->GetFloatProperty("contour.hovering.width", lineWidth);
    else
        this->GetDataNode()->GetFloatProperty("contour.width", lineWidth);

    bool drawit=false;

    mitk::ContourModel::VertexIterator pointsIt = renderingContour->IteratorBegin(timestep);

    Point2D pt2d;       // projected_p in display coordinates
    Point2D lastPt2d;

    while ( pointsIt != renderingContour->IteratorEnd(timestep) )
    {
      lastPt2d = pt2d;

      point = (*pointsIt)->Coordinates;

      itk2vtk(point, vtkp);
      transform->TransformPoint(vtkp, vtkp);
      vtk2itk(vtkp,p);

      displayGeometry->Project(p, projected_p);

      displayGeometry->Map(projected_p, pt2d);
      displayGeometry->WorldToDisplay(pt2d, pt2d);

      Vector3D diff=p-projected_p;
      ScalarType scalardiff = diff.GetNorm();

      //draw lines
      bool projectmode=false;
      GetDataNode()->GetVisibility(projectmode, renderer, "contour.project-onto-plane");

      if(projectmode)
      {
        drawit=true;
      }
      else if(scalardiff<0.25)
      {
        drawit=true;
      }

      if(drawit)
      {
        //lastPt2d is not valid in first step
        if( !(pointsIt == renderingContour->IteratorBegin(timestep)) )
        {
          glLineWidth(lineWidth);
          glBegin (GL_LINES);
          glVertex2f(pt2d[0], pt2d[1]);
          glVertex2f(lastPt2d[0], lastPt2d[1]);
          glEnd();
          glLineWidth(1);
        }

        //draw active points
        if ((*pointsIt)->IsControlPoint)
        {
          float pointsize = 4;
          Point2D  tmp;

          Vector2D horz,vert;
          horz[1]=0;
          vert[0]=0;
          horz[0]=pointsize;
          vert[1]=pointsize;
          glColor3f(selectedcolor->GetColor().GetRed(), selectedcolor->GetColor().GetBlue(), selectedcolor->GetColor().GetGreen());
          glLineWidth(1);
          //a rectangle around the point with the selected color
          glBegin (GL_LINE_LOOP);
          tmp=pt2d-horz;      glVertex2fv(&tmp[0]);
          tmp=pt2d+vert;      glVertex2fv(&tmp[0]);
          tmp=pt2d+horz;      glVertex2fv(&tmp[0]);
          tmp=pt2d-vert;      glVertex2fv(&tmp[0]);
          glEnd();
          glLineWidth(1);
          //the actual point in the specified color to see the usual color of the point
          glColor3f(colorprop->GetColor().GetRed(),colorprop->GetColor().GetGreen(),colorprop->GetColor().GetBlue());
          glPointSize(1);
          glBegin (GL_POINTS);
          tmp=pt2d;             glVertex2fv(&tmp[0]);
          glEnd ();
        }
      }

      pointsIt++;
    }//end while iterate over controlpoints

    //close contour if necessary
    if(renderingContour->IsClosed(timestep) && drawit)
    {
      lastPt2d = pt2d;
      point = renderingContour->GetVertexAt(0,timestep)->Coordinates;
      itk2vtk(point, vtkp);
      transform->TransformPoint(vtkp, vtkp);
      vtk2itk(vtkp,p);
      displayGeometry->Project(p, projected_p);
      displayGeometry->Map(projected_p, pt2d);
      displayGeometry->WorldToDisplay(pt2d, pt2d);

      glLineWidth(lineWidth);
      glBegin (GL_LINES);
      glVertex2f(lastPt2d[0], lastPt2d[1]);
      glVertex2f( pt2d[0], pt2d[1] );
      glEnd();
      glLineWidth(1);
    }

    //draw selected vertex if exists
    if(renderingContour->GetSelectedVertex())
    {
      //transform selected vertex
      point = renderingContour->GetSelectedVertex()->Coordinates;

      itk2vtk(point, vtkp);
      transform->TransformPoint(vtkp, vtkp);
      vtk2itk(vtkp,p);

      displayGeometry->Project(p, projected_p);

      displayGeometry->Map(projected_p, pt2d);
      displayGeometry->WorldToDisplay(pt2d, pt2d);

      Vector3D diff=p-projected_p;
      ScalarType scalardiff = diff.GetNorm();
      //----------------------------------

      //draw point if close to plane
      if(scalardiff<0.25)
      {

        float pointsize = 5;
        Point2D  tmp;
        glColor3f(0.0, 1.0, 0.0);
        glLineWidth(1);
        //a diamond around the point
        glBegin (GL_LINE_LOOP);
        //begin from upper left corner and paint clockwise
        tmp[0]=pt2d[0]-pointsize;    tmp[1]=pt2d[1]+pointsize;    glVertex2fv(&tmp[0]);
        tmp[0]=pt2d[0]+pointsize;    tmp[1]=pt2d[1]+pointsize;    glVertex2fv(&tmp[0]);
        tmp[0]=pt2d[0]+pointsize;    tmp[1]=pt2d[1]-pointsize;    glVertex2fv(&tmp[0]);
        tmp[0]=pt2d[0]-pointsize;    tmp[1]=pt2d[1]-pointsize;    glVertex2fv(&tmp[0]);
        glEnd ();
      }
      //------------------------------------
    }
  }
}

const mitk::ContourModel* mitk::ContourModelGLMapper2D::GetInput(void)
{
  return static_cast<const mitk::ContourModel * > ( GetDataNode()->GetData() );
}

void mitk::ContourModelGLMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{
  node->AddProperty( "contour.color", ColorProperty::New(0.9, 1.0, 0.1), renderer, overwrite );
  node->AddProperty( "contour.editing", mitk::BoolProperty::New( false ), renderer, overwrite );
  node->AddProperty( "contour.editing.color", ColorProperty::New(0.1, 0.9, 0.1), renderer, overwrite );
  node->AddProperty( "points.color", ColorProperty::New(1.0, 0.0, 0.1), renderer, overwrite );
  node->AddProperty( "contour.width", mitk::FloatProperty::New( 1.0 ), renderer, overwrite );
  node->AddProperty( "contour.hovering.width", mitk::FloatProperty::New( 3.0 ), renderer, overwrite );
  node->AddProperty( "contour.hovering", mitk::BoolProperty::New( false ), renderer, overwrite );

  node->AddProperty( "subdivision curve", mitk::BoolProperty::New( false ), renderer, overwrite );
  node->AddProperty( "contour.project-onto-plane", mitk::BoolProperty::New( false ), renderer, overwrite );

  Superclass::SetDefaultProperties(node, renderer, overwrite);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <time.h>
#include <sys/time.h>
#include <string>

//#define FUNCTION_TIME(x) gmtime(x)
#define FUNCTION_TIME(x) localtime(x)

using namespace std;

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

     time_t ltime;
     //int timestamp = 1246962445;
     int timestamp = 10;
     struct tm *Tm;

/* time: Get the current time (number of seconds from the epoch) from the system clock. Stores that value in timer. If timer is null, the value is not stored, but it is still returned by the function. */

     ltime=time(NULL);
     cout << "ltime --> " << ltime << endl;

/* localtime: Convert a time_t time value to a tm structure as local time. This structure is statically allocated and shared by gmtime, localtime and ctime functions. Each time one of these functions is called the content of the structure is overwritten. */

     Tm=localtime(&ltime);
     //Tm=localtime((const time_t*) &timestamp);
     cout << endl << Tm->tm_wday << " " << Tm->tm_mday << "/" << Tm->tm_mon+1 << "/" << Tm->tm_year+1900 << " ";
     cout << Tm->tm_hour << ":" << Tm->tm_min << ":" << Tm->tm_sec << endl;

     Tm=gmtime((const time_t*) &timestamp);
     cout << endl << Tm->tm_wday << " " << Tm->tm_mday << "/" << Tm->tm_mon+1 << "/" << Tm->tm_year+1900 << " ";
     cout << Tm->tm_hour << ":" << Tm->tm_min << ":" << Tm->tm_sec << endl;

/*     printf("[%d] %d %d %d, %d:%d:%d",
         Tm->tm_wday, // Mon - Sun
         Tm->tm_mday,
         Tm->tm_mon+1,
         Tm->tm_year+1900,
         Tm->tm_hour,
         Tm->tm_min,
         Tm->tm_sec);  */

    struct timeval detail_time;
    gettimeofday(&detail_time,NULL);
    printf("%d %d",
    detail_time.tv_usec /1000,  /* milliseconds */
    detail_time.tv_usec); /* microseconds */

}
<commit_msg>fix core dump<commit_after>#include <iostream>
#include <time.h>
#include <sys/time.h>
#include <string>

//#define FUNCTION_TIME(x) gmtime(x)
#define FUNCTION_TIME(x) localtime(x)

using namespace std;

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

     time_t ltime;
     //int timestamp = 1246962445;
     const time_t timestamp = 10;
     struct tm *Tm;

/* time: Get the current time (number of seconds from the epoch) from the system clock. Stores that value in timer. If timer is null, the value is not stored, but it is still returned by the function. */

     ltime=time(NULL);
     cout << "ltime --> " << ltime << endl;

/* localtime: Convert a time_t time value to a tm structure as local time. This structure is statically allocated and shared by gmtime, localtime and ctime functions. Each time one of these functions is called the content of the structure is overwritten. */

     Tm=localtime(&ltime);
     //Tm=localtime((const time_t*) &timestamp);
     cout << endl << Tm->tm_wday << " " << Tm->tm_mday << "/" << Tm->tm_mon+1 << "/" << Tm->tm_year+1900 << " ";
     cout << Tm->tm_hour << ":" << Tm->tm_min << ":" << Tm->tm_sec << endl;

     Tm=gmtime(&timestamp);
     cout << endl << Tm->tm_wday << " " << Tm->tm_mday << "/" << Tm->tm_mon+1 << "/" << Tm->tm_year+1900 << " ";
     cout << Tm->tm_hour << ":" << Tm->tm_min << ":" << Tm->tm_sec << endl;

/*     printf("[%d] %d %d %d, %d:%d:%d",
         Tm->tm_wday, // Mon - Sun
         Tm->tm_mday,
         Tm->tm_mon+1,
         Tm->tm_year+1900,
         Tm->tm_hour,
         Tm->tm_min,
         Tm->tm_sec);  */

    struct timeval detail_time;
    gettimeofday(&detail_time,NULL);
    printf("%li %li \n",
    detail_time.tv_usec /1000,  /* milliseconds */
    detail_time.tv_usec); /* microseconds */

}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <string.h>
#include <math.h>
#include "norad.h"
#include "norad_in.h"

/* Example code to add BSTAR data using Ted Molczan's method.  It just
   reads in TLEs,  computes BSTAR if possible,  then writes out the
   resulting modified TLE.

   Add the '-v' (verbose) switch,  and it also writes out the orbital
   period and perigee/apogee distances.  Eventually,  I'll probably
   set it up to dump other data that are not immediately obvious
   just by looking at the TLEs... */

int main( const int argc, const char **argv)
{
   FILE *ifile;
   const char *filename;
   char line1[100], line2[100];
   int i, verbose = 0;
   const char *norad = NULL, *intl = NULL;
   bool legend_shown = false;

   for( i = 2; i < argc; i++)
      if( argv[i][0] == '-')
         switch( argv[i][1])
            {
            case 'v':
               verbose = 1;
               break;
            case 'n':
               norad = argv[i] + 2;
               if( !*norad && i < argc - 1)
                  norad = argv[++i];
               printf( "Looking for NORAD %s\n", norad);
               break;
            case 'i':
               intl = argv[i] + 2;
               if( !*intl && i < argc - 1)
                  intl = argv[++i];
               printf( "Looking for international ID %s\n", intl);
               break;
            default:
               printf( "'%s': unrecognized option\n", argv[i]);
               return( -1);
               break;
            }
   filename = (argc == 1 ? "all_tle.txt" : argv[1]);
   ifile = fopen( filename, "rb");
   if( !ifile)
      {
      fprintf( stderr, "Couldn't open '%s': ", filename);
      perror( "");
      return( -1);
      }
   while( fgets( line1, sizeof( line1), ifile))
      if( *line1 == '1' && (!norad || !memcmp( line1 + 2, norad, 5))
                        && (!intl || !memcmp( line1 + 9, intl, 5))
                  && fgets( line2, sizeof( line2), ifile) && *line2 == '2')
         {
         tle_t tle;

         if( parse_elements( line1, line2, &tle) >= 0)
            {
            char obuff[200];
            double params[N_SGP4_PARAMS], c2;

            if( verbose && !legend_shown)
               {
               legend_shown = true;
               printf(
  "1 NoradU COSPAR   Epoch.epoch     dn/dt/2  d2n/dt2/6 BSTAR    T El# C\n"
  "2 NoradU Inclina RAAscNode Eccent  ArgPeri MeanAno  MeanMotion Rev# C\n");

               }
            SGP4_init( params, &tle);
            c2 = params[0];
            if( c2 && tle.xno)
               tle.bstar = tle.xndt2o / (tle.xno * c2 * 1.5);
            write_elements_in_tle_format( obuff, &tle);
            printf( "%s", obuff);
            if( verbose)
               {
               const double a1 = pow(xke / tle.xno, two_thirds);  /* in Earth radii */

               printf( "   Perigee: %.4f km\n",
                    (a1 * (1. - tle.eo) - 1.) * earth_radius_in_km);
               printf( "   Apogee: %.4f km\n",
                    (a1 * (1. + tle.eo) - 1.) * earth_radius_in_km);
               printf( "   Orbital period: %.4f min\n",
                    2. * pi / tle.xno);
               printf( "   Epoch: JD %.5f\n", tle.epoch);
               }
            }
         }
      else if( !norad && !intl)
         printf( "%s", line1);
   fclose( ifile);
   return( 0);
}
<commit_msg>Display the 'line 0' (object name,  sometimes brightness and size) data<commit_after>#include <stdio.h>
#include <string.h>
#include <math.h>
#include "norad.h"
#include "norad_in.h"

/* Example code to add BSTAR data using Ted Molczan's method.  It just
   reads in TLEs,  computes BSTAR if possible,  then writes out the
   resulting modified TLE.

   Add the '-v' (verbose) switch,  and it also writes out the orbital
   period and perigee/apogee distances.  Eventually,  I'll probably
   set it up to dump other data that are not immediately obvious
   just by looking at the TLEs... */

int main( const int argc, const char **argv)
{
   FILE *ifile;
   const char *filename;
   char line0[100], line1[100], line2[100];
   int i, verbose = 0;
   const char *norad = NULL, *intl = NULL;
   bool legend_shown = false;

   for( i = 2; i < argc; i++)
      if( argv[i][0] == '-')
         switch( argv[i][1])
            {
            case 'v':
               verbose = 1;
               break;
            case 'n':
               norad = argv[i] + 2;
               if( !*norad && i < argc - 1)
                  norad = argv[++i];
               printf( "Looking for NORAD %s\n", norad);
               break;
            case 'i':
               intl = argv[i] + 2;
               if( !*intl && i < argc - 1)
                  intl = argv[++i];
               printf( "Looking for international ID %s\n", intl);
               break;
            default:
               printf( "'%s': unrecognized option\n", argv[i]);
               return( -1);
               break;
            }
   filename = (argc == 1 ? "all_tle.txt" : argv[1]);
   ifile = fopen( filename, "rb");
   if( !ifile)
      {
      fprintf( stderr, "Couldn't open '%s': ", filename);
      perror( "");
      return( -1);
      }
   if( !fgets( line0, sizeof( line0), ifile)
            || !fgets( line1, sizeof( line1), ifile))
      perror( "Couldn't read from input file");
   while( fgets( line2, sizeof( line2), ifile))
      {
      if( *line1 == '1' && (!norad || !memcmp( line1 + 2, norad, 5))
                        && (!intl || !memcmp( line1 + 9, intl, 5))
                   && *line2 == '2')
         {
         tle_t tle;

         if( parse_elements( line1, line2, &tle) >= 0)
            {
            char obuff[200];
            double params[N_SGP4_PARAMS], c2;

            if( verbose && !legend_shown)
               {
               legend_shown = true;
               printf(
  "1 NoradU COSPAR   Epoch.epoch     dn/dt/2  d2n/dt2/6 BSTAR    T El# C\n"
  "2 NoradU Inclina RAAscNode Eccent  ArgPeri MeanAno  MeanMotion Rev# C\n");

               }
            SGP4_init( params, &tle);
            c2 = params[0];
            if( c2 && tle.xno)
               tle.bstar = tle.xndt2o / (tle.xno * c2 * 1.5);
            write_elements_in_tle_format( obuff, &tle);
            if( strlen( line0) < 60)
               printf( "%s", line0);
            printf( "%s", obuff);
            if( verbose)
               {
               const double a1 = pow(xke / tle.xno, two_thirds);  /* in Earth radii */

               printf( "   Perigee: %.4f km\n",
                    (a1 * (1. - tle.eo) - 1.) * earth_radius_in_km);
               printf( "   Apogee: %.4f km\n",
                    (a1 * (1. + tle.eo) - 1.) * earth_radius_in_km);
               printf( "   Orbital period: %.4f min\n",
                    2. * pi / tle.xno);
               printf( "   Epoch: JD %.5f\n", tle.epoch);
               }
            }
         }
      strcpy( line0, line1);
      strcpy( line1, line2);
      }
   fclose( ifile);
   return( 0);
}
<|endoftext|>


<commit_before>// @(#)root/reflex:$Name:  $:$Id: ScopeName.cxx,v 1.9 2006/03/13 15:49:51 roiser Exp $
// Author: Stefan Roiser 2004

// Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.

#ifndef REFLEX_BUILD
#define REFLEX_BUILD
#endif

#include "Reflex/ScopeName.h"

#include "Reflex/Scope.h"
#include "Reflex/ScopeBase.h"

#include "Reflex/Tools.h"

#include "stl_hash.h"
#include <vector>

//-------------------------------------------------------------------------------
typedef __gnu_cxx::hash_map < const char *, ROOT::Reflex::ScopeName * > Name2Scope_t;
typedef std::vector< ROOT::Reflex::Scope > ScopeVec_t;

//-------------------------------------------------------------------------------
static Name2Scope_t & sScopes() {
//-------------------------------------------------------------------------------
   static Name2Scope_t m;
   return m;
}

//-------------------------------------------------------------------------------
static ScopeVec_t & sScopeVec() {
//-------------------------------------------------------------------------------
   static ScopeVec_t m;
   return m;
}

//-------------------------------------------------------------------------------
ROOT::Reflex::ScopeName::ScopeName( const char * name,
                                    ScopeBase * scopeBase )
   : fName(name),
     fScopeBase(scopeBase) {
//-------------------------------------------------------------------------------
   sScopes() [ fName.c_str() ] = this;
   sScopeVec().push_back(Scope(this));
   //---Build recursively the declaring scopeNames
   if( fName != "@N@I@R@V@A@N@A@" ) {
      std::string decl_name = Tools::GetScopeName(fName);
      if ( ! Scope::ByName( decl_name ).Id() )  new ScopeName( decl_name.c_str(), 0 );
   }
}

//-------------------------------------------------------------------------------
ROOT::Reflex::ScopeName::~ScopeName() {
//-------------------------------------------------------------------------------
}

//-------------------------------------------------------------------------------
ROOT::Reflex::Scope ROOT::Reflex::ScopeName::ByName( const std::string & name ) {
//-------------------------------------------------------------------------------
   size_t pos =  name.substr(0,2) == "::" ?  2 : 0;
   Name2Scope_t::iterator it = sScopes().find(name.substr(pos).c_str());
   if (it != sScopes().end() ) return Scope( it->second );
   else                        return Scope();
}

//-------------------------------------------------------------------------------
ROOT::Reflex::Scope ROOT::Reflex::ScopeName::ThisScope() const {
//-------------------------------------------------------------------------------
   return Scope( this );
}

//-------------------------------------------------------------------------------
ROOT::Reflex::Scope ROOT::Reflex::ScopeName::ScopeAt( size_t nth ) {
//-------------------------------------------------------------------------------
   if ( nth < sScopeVec().size()) return sScopeVec()[nth];
   return Scope();
}

//-------------------------------------------------------------------------------
size_t ROOT::Reflex::ScopeName::ScopeSize() {
//-------------------------------------------------------------------------------
   return sScopeVec().size();
}

//-------------------------------------------------------------------------------
ROOT::Reflex::Scope_Iterator ROOT::Reflex::ScopeName::Scope_Begin() {
//-------------------------------------------------------------------------------
   return sScopeVec().begin();
}

//-------------------------------------------------------------------------------
ROOT::Reflex::Scope_Iterator ROOT::Reflex::ScopeName::Scope_End() {
//-------------------------------------------------------------------------------
   return sScopeVec().end();
}

//-------------------------------------------------------------------------------
ROOT::Reflex::Reverse_Scope_Iterator ROOT::Reflex::ScopeName::Scope_RBegin() {
//-------------------------------------------------------------------------------
   return sScopeVec().rbegin();
}

//-------------------------------------------------------------------------------
ROOT::Reflex::Reverse_Scope_Iterator ROOT::Reflex::ScopeName::Scope_REnd() {
//-------------------------------------------------------------------------------
   return sScopeVec().rend();
}

<commit_msg>Ugly hack to workaround typedefs to Scopes. This has to be undone ASAP.<commit_after>// @(#)root/reflex:$Name:  $:$Id: ScopeName.cxx,v 1.10 2006/03/20 09:46:18 roiser Exp $
// Author: Stefan Roiser 2004

// Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.

#ifndef REFLEX_BUILD
#define REFLEX_BUILD
#endif

#include "Reflex/ScopeName.h"

#include "Reflex/Scope.h"
#include "Reflex/ScopeBase.h"

#include "Reflex/Tools.h"

#include "stl_hash.h"
#include <vector>

//-------------------------------------------------------------------------------
typedef __gnu_cxx::hash_map < const char *, ROOT::Reflex::ScopeName * > Name2Scope_t;
typedef std::vector< ROOT::Reflex::Scope > ScopeVec_t;

//-------------------------------------------------------------------------------
static Name2Scope_t & sScopes() {
//-------------------------------------------------------------------------------
   static Name2Scope_t m;
   return m;
}

//-------------------------------------------------------------------------------
static ScopeVec_t & sScopeVec() {
//-------------------------------------------------------------------------------
   static ScopeVec_t m;
   return m;
}

//-------------------------------------------------------------------------------
ROOT::Reflex::ScopeName::ScopeName( const char * name,
                                    ScopeBase * scopeBase )
   : fName(name),
     fScopeBase(scopeBase) {
//-------------------------------------------------------------------------------
   sScopes() [ fName.c_str() ] = this;
   sScopeVec().push_back(Scope(this));
   //---Build recursively the declaring scopeNames
   if( fName != "@N@I@R@V@A@N@A@" ) {
      std::string decl_name = Tools::GetScopeName(fName);
      if ( ! Scope::ByName( decl_name ).Id() )  new ScopeName( decl_name.c_str(), 0 );
   }
}

//-------------------------------------------------------------------------------
ROOT::Reflex::ScopeName::~ScopeName() {
//-------------------------------------------------------------------------------
}

//-------------------------------------------------------------------------------
ROOT::Reflex::Scope ROOT::Reflex::ScopeName::ByName( const std::string & name ) {
//-------------------------------------------------------------------------------
   size_t pos =  name.substr(0,2) == "::" ?  2 : 0;
   Name2Scope_t::iterator it = sScopes().find(name.substr(pos).c_str());
   if (it != sScopes().end() ) return Scope( it->second );
   //else                        return Scope();
   // HERE STARTS AN UGLY HACK WHICH HAS TO BE UNDONE ASAP
   Type t = Type::ByName("name");
   if ( t && t.IsTypedef()) {
      while ( t.IsTypedef()) t = t.ToType();
      if ( t.IsClass() || t.IsEnum() || t.IsUnion() ) return (Scope)t;
   }
   return Scope();
   // END OF UGLY HACK
}

//-------------------------------------------------------------------------------
ROOT::Reflex::Scope ROOT::Reflex::ScopeName::ThisScope() const {
//-------------------------------------------------------------------------------
   return Scope( this );
}

//-------------------------------------------------------------------------------
ROOT::Reflex::Scope ROOT::Reflex::ScopeName::ScopeAt( size_t nth ) {
//-------------------------------------------------------------------------------
   if ( nth < sScopeVec().size()) return sScopeVec()[nth];
   return Scope();
}

//-------------------------------------------------------------------------------
size_t ROOT::Reflex::ScopeName::ScopeSize() {
//-------------------------------------------------------------------------------
   return sScopeVec().size();
}

//-------------------------------------------------------------------------------
ROOT::Reflex::Scope_Iterator ROOT::Reflex::ScopeName::Scope_Begin() {
//-------------------------------------------------------------------------------
   return sScopeVec().begin();
}

//-------------------------------------------------------------------------------
ROOT::Reflex::Scope_Iterator ROOT::Reflex::ScopeName::Scope_End() {
//-------------------------------------------------------------------------------
   return sScopeVec().end();
}

//-------------------------------------------------------------------------------
ROOT::Reflex::Reverse_Scope_Iterator ROOT::Reflex::ScopeName::Scope_RBegin() {
//-------------------------------------------------------------------------------
   return sScopeVec().rbegin();
}

//-------------------------------------------------------------------------------
ROOT::Reflex::Reverse_Scope_Iterator ROOT::Reflex::ScopeName::Scope_REnd() {
//-------------------------------------------------------------------------------
   return sScopeVec().rend();
}

<|endoftext|>


<commit_before>#include "tree.h"

Tree::Tree() {
    root = NULL;
}

// Copies a tree
Tree::Tree(const Tree &tree){
    // If we are not empty clear then rebuild
    if(root!=NULL)
        this->clear();
    this->build(tree.commands);
    this->commands = tree.commands;
}

// Assignment operator
Tree & Tree::operator= (const Tree& tree){
    // If we are not empty clear then rebuild
    if(root!=NULL)
        this->clear();
    this->build(tree.commands);
    this->commands = tree.commands;
    return *this;
}

// Returns whether the tree is empty
bool Tree::isEmpty() {
    if (root == NULL) return true;
    return false;
}

void Tree::build(std::vector< std::vector<std::string> > vIn) {
    if ((vIn.size() % 2) != 0) {
        root = new Command(vIn.at(0));
        if (vIn.size() > 1) {
            int i = 1;
            while (i < (((int) vIn.size()) - 1)) {
                if (vIn.at(i).at(0) == "&") {
                   root = new And_Connector(root, new Command(vIn.at(i + 1)));
                }
                else if (vIn.at(i).at(0) == "|") {
                    root = new Or_Connector(root, new Command(vIn.at(i + 1)));
                }
                else if (vIn.at(i).at(0) == ";") {
                    root = new Semicolon_Connector(root, new Command(vIn.at(i + 1)));
                }
                i += 2;
            }
        }
    }
}

// Empty the tree
void Tree::clear(){
  if (root != NULL) {
        delete root;
        root = NULL; // Point it to NULL so we don't get garbage accessing it later
    }
}

// Executes the tree commands
int Tree::execute(){
    return root->execute();
}
<commit_msg>updated Tree's build to create exit_commands<commit_after>#include "tree.h"

Tree::Tree() {
    root = NULL;
}

// Copies a tree
Tree::Tree(const Tree &tree){
    // If we are not empty clear then rebuild
    if(root!=NULL)
        this->clear();
    this->build(tree.commands);
    this->commands = tree.commands;
}

// Assignment operator
Tree & Tree::operator= (const Tree& tree){
    // If we are not empty clear then rebuild
    if(root!=NULL)
        this->clear();
    this->build(tree.commands);
    this->commands = tree.commands;
    return *this;
}

// Returns whether the tree is empty
bool Tree::isEmpty() {
    if (root == NULL) return true;
    return false;
}

void Tree::build(std::vector< std::vector<std::string> > vIn) {
    if ((vIn.size() % 2) != 0) {
        root = new Command(vIn.at(0));
        if (vIn.size() > 1) {
            int i = 1;
            Base* command;
            while (i < (((int) vIn.size()) - 1)) {
                if (vIn.at(i + 1).at(0) == "exit") {
                    command = new Exit_Command();
                }
                else {
                    command = new Command(vIn.at(i + 1));
                }
                if (vIn.at(i).at(0) == "&") {
                   root = new And_Connector(root, command);
                }
                else if (vIn.at(i).at(0) == "|") {
                    root = new Or_Connector(root, command);
                }
                else if (vIn.at(i).at(0) == ";") {
                    root = new Semicolon_Connector(root, command);
                }
                i += 2;
            }
        }
    }
}

// Empty the tree
void Tree::clear(){
  if (root != NULL) {
        delete root;
        root = NULL; // Point it to NULL so we don't get garbage accessing it later
    }
}

// Executes the tree commands
int Tree::execute(){
    return root->execute();
}
<|endoftext|>


<commit_before>/**
 * @file GameInfo.cpp
 *
 * @author Mellmann, Heinrich
 * @breief the game information in RoboCup
 */

#include <iostream>
#include "GameData.h"

using namespace naoth;
using namespace std;

GameData::GameData()
  :
    valid(false),
    playersPerTeam(0),

    competitionPhase(roundrobin),
    competitionType(competition_normal),
    gamePhase(normal),
    gameState(unknown_game_state),
    setPlay(set_none),

    firstHalf(true),
    kickingTeam(0),
    dropInTeam(0),
    dropInTime(0),
    secsRemaining(0),
    secondaryTime(0),
    // HACK: for more info see declaration
    newPlayerNumber(0)
{
}

#define RETURN_VALUE_TO_STR(v) case v: return #v

std::string GameData::toString(TeamColor value)
{
  switch (value)
  {
    RETURN_VALUE_TO_STR(blue);
    RETURN_VALUE_TO_STR(red);
    RETURN_VALUE_TO_STR(yellow);
    RETURN_VALUE_TO_STR(black);
    RETURN_VALUE_TO_STR(white);
    RETURN_VALUE_TO_STR(green);
    RETURN_VALUE_TO_STR(orange);
    RETURN_VALUE_TO_STR(purple);
    RETURN_VALUE_TO_STR(brown);
    RETURN_VALUE_TO_STR(gray);
    RETURN_VALUE_TO_STR(unknown_team_color);
  }

  ASSERT(false);
  return "invalid TeamColor";
}

std::string GameData::toString(CompetitionPhase value)
{
  switch (value)
  {
    RETURN_VALUE_TO_STR(roundrobin);
    RETURN_VALUE_TO_STR(playoff);
  }

  ASSERT(false);
  return "invalid CompetitionPhase";
}

std::string GameData::toString(CompetitionType value)
{
  switch (value)
  {
    RETURN_VALUE_TO_STR(competition_normal);
    RETURN_VALUE_TO_STR(competition_mixed);
    RETURN_VALUE_TO_STR(competition_penalty);
  }

  ASSERT(false);
  return "invalid CompetitionType";
}

std::string GameData::toString(GamePhase value)
{
  switch (value)
  {
    RETURN_VALUE_TO_STR(normal);
    RETURN_VALUE_TO_STR(penaltyshoot);
    RETURN_VALUE_TO_STR(overtime);
    RETURN_VALUE_TO_STR(timeout);
  }

  ASSERT(false);
  return "invalid SecondaryGameState";
}

std::string GameData::toString(GameState value)
{
  switch (value)
  {
    RETURN_VALUE_TO_STR(initial);
    RETURN_VALUE_TO_STR(ready);
    RETURN_VALUE_TO_STR(set);
    RETURN_VALUE_TO_STR(playing);
    RETURN_VALUE_TO_STR(finished);
    RETURN_VALUE_TO_STR(unknown_game_state);
  }

  ASSERT(false);
  return "invalid GameState";
}

std::string GameData::toString(SetPlay value)
{
  switch (value)
  {
    RETURN_VALUE_TO_STR(set_none);
    RETURN_VALUE_TO_STR(goal_free_kick);
    RETURN_VALUE_TO_STR(pushing_free_kick);
  }

  ASSERT(false);
  return "invalid SetPlay";
}

std::string GameData::toString(Penalty value)
{
  switch (value)
  {
    RETURN_VALUE_TO_STR(penalty_none);
    RETURN_VALUE_TO_STR(illegal_ball_contact);
    RETURN_VALUE_TO_STR(player_pushing);
    RETURN_VALUE_TO_STR(illegal_motion_in_set);
    RETURN_VALUE_TO_STR(inactive_player);
    RETURN_VALUE_TO_STR(illegal_defender);
    RETURN_VALUE_TO_STR(leaving_the_field);
    RETURN_VALUE_TO_STR(kick_off_goal);
    RETURN_VALUE_TO_STR(request_for_pickup);
    RETURN_VALUE_TO_STR(local_game_stuck);
    RETURN_VALUE_TO_STR(substitute);
    RETURN_VALUE_TO_STR(manual);
  }

  ASSERT(false);
  return "invalid Penalty";
}

#define RETURN_STING_TO_VALUE(value, str) if(toString(value) == str) return value

GameData::TeamColor GameData::teamColorFromString(const std::string& str)
{
  RETURN_STING_TO_VALUE(blue, str);
  RETURN_STING_TO_VALUE(red, str);
  RETURN_STING_TO_VALUE(yellow, str);
  RETURN_STING_TO_VALUE(black, str);

  return unknown_team_color;
}

GameData::GameState GameData::gameStateFromString(const std::string& str)
{
  RETURN_STING_TO_VALUE(initial, str);
  RETURN_STING_TO_VALUE(ready, str);
  RETURN_STING_TO_VALUE(set, str);
  RETURN_STING_TO_VALUE(playing, str);
  RETURN_STING_TO_VALUE(finished, str);

  return unknown_game_state;
}

void GameData::parseFrom(const spl::RoboCupGameControlData& data, int teamNumber)
{
  playersPerTeam    = data.playersPerTeam;

  competitionType   = (CompetitionType) data.competitionType;
  competitionPhase  = (CompetitionPhase) data.competitionPhase;
  gamePhase         = (GamePhase) data.gamePhase;
  gameState         = (GameState) data.state;
  setPlay           = (SetPlay) data.setPlay;

  firstHalf       = data.firstHalf == 1;
  kickingTeam     = data.kickingTeam;

  dropInTeam      = data.dropInTeam;

  // ACHTUNG: casting to signed values - game time can be negative (!)
  dropInTime      = (int16_t)data.dropInTime;
  secsRemaining   = (int16_t)data.secsRemaining;
  secondaryTime   = (int16_t)data.secondaryTime;

  // team info
  if(data.teams[0].teamNumber == teamNumber) {
    parseTeamInfo(ownTeam, data.teams[0]);
    parseTeamInfo(oppTeam, data.teams[1]);
  } else if(data.teams[1].teamNumber == teamNumber) {
    parseTeamInfo(ownTeam, data.teams[1]);
    parseTeamInfo(oppTeam, data.teams[0]);
  } else {
    ASSERT(false);
  }
}

void GameData::parseTeamInfo(TeamInfo& teamInfoDst, const spl::TeamInfo& teamInfoSrc) const
{
  teamInfoDst.penaltyShot = teamInfoSrc.penaltyShot;
  teamInfoDst.score = teamInfoSrc.score;
  teamInfoDst.teamColor = (TeamColor)teamInfoSrc.teamColor;
  teamInfoDst.teamNumber = teamInfoSrc.teamNumber;

  teamInfoDst.players.resize(playersPerTeam);
  for(int i = 0; i < playersPerTeam; i++) {
    teamInfoDst.players[i].penalty = (Penalty)teamInfoSrc.players[i].penalty;

    // ACHTUNG: casting to signed values - time can be negative (!)
    teamInfoDst.players[i].secsTillUnpenalised = (int8_t)teamInfoSrc.players[i].secsTillUnpenalised;
  }
}

void GameData::print(ostream& stream) const
{
  stream << "playersPerTeam = " << playersPerTeam << std::endl;

  stream << "competitionPhase = " << toString(competitionPhase) << std::endl;
  stream << "competitionType = "  << toString(competitionType) << std::endl;
  stream << "gamePhase = "        << toString(gamePhase) << std::endl;
  stream << "gameState = "        << toString(gameState) << std::endl;
  stream << "setPlay = "          << toString(setPlay) << std::endl;

  stream << "firstHalf = "      << firstHalf << std::endl;
  stream << "kickingTeam = "    << kickingTeam << std::endl;
  stream << "dropInTeam = "     << dropInTeam << std::endl;
  stream << "dropInTime = "     << dropInTime << std::endl;
  stream << "secsRemaining = "  << secsRemaining << std::endl;
  stream << "secondaryTime = "  << secondaryTime << std::endl;

  stream << std::endl;
  stream << "Own Team:" << std::endl;
  stream << " |- number = " << ownTeam.teamNumber << std::endl;
  stream << " |- color = " << toString(ownTeam.teamColor) << std::endl;
  stream << " |- score = " << ownTeam.score << std::endl;
  stream << " |- penaltyShot = " << ownTeam.penaltyShot << std::endl;
  stream << " |- players (penalty, time until unpenalize in s):" << std::endl;
  for(size_t i = 0; i < ownTeam.players.size(); ++i) {
    stream << "      |- " << (i+1) << ": " << toString(ownTeam.players[i].penalty) << " - " << ownTeam.players[i].secsTillUnpenalised << std::endl;
  }

  stream << std::endl;
  stream << "Opp Team:" << std::endl;
  stream << " |- number = " << oppTeam.teamNumber << std::endl;
  stream << " |- color = " << toString(oppTeam.teamColor) << std::endl;
  stream << " |- score = " << oppTeam.score << std::endl;
  stream << " |- penaltyShot = " << oppTeam.penaltyShot << std::endl;
  stream << " |- players (penalty, time until unpenalize in s):" << std::endl;
  for(size_t i = 0; i < oppTeam.players.size(); ++i) {
    stream << "      |- " << (i+1) << ": " << toString(oppTeam.players[i].penalty) << " - " << oppTeam.players[i].secsTillUnpenalised << std::endl;
  }
}

std::string GameReturnData::toString(Message value)
{
  switch (value)
  {
    RETURN_VALUE_TO_STR(manual_penalise);
    RETURN_VALUE_TO_STR(manual_unpenalise);
    RETURN_VALUE_TO_STR(alive);
  }

  ASSERT(false);
  return "invalide Message";
}

<commit_msg>bugfix: added all team colors to conversion function<commit_after>/**
 * @file GameInfo.cpp
 *
 * @author Mellmann, Heinrich
 * @breief the game information in RoboCup
 */

#include <iostream>
#include "GameData.h"

using namespace naoth;
using namespace std;

GameData::GameData()
  :
    valid(false),
    playersPerTeam(0),

    competitionPhase(roundrobin),
    competitionType(competition_normal),
    gamePhase(normal),
    gameState(unknown_game_state),
    setPlay(set_none),

    firstHalf(true),
    kickingTeam(0),
    dropInTeam(0),
    dropInTime(0),
    secsRemaining(0),
    secondaryTime(0),
    // HACK: for more info see declaration
    newPlayerNumber(0)
{
}

#define RETURN_VALUE_TO_STR(v) case v: return #v

std::string GameData::toString(TeamColor value)
{
  switch (value)
  {
    RETURN_VALUE_TO_STR(blue);
    RETURN_VALUE_TO_STR(red);
    RETURN_VALUE_TO_STR(yellow);
    RETURN_VALUE_TO_STR(black);
    RETURN_VALUE_TO_STR(white);
    RETURN_VALUE_TO_STR(green);
    RETURN_VALUE_TO_STR(orange);
    RETURN_VALUE_TO_STR(purple);
    RETURN_VALUE_TO_STR(brown);
    RETURN_VALUE_TO_STR(gray);
    RETURN_VALUE_TO_STR(unknown_team_color);
  }

  ASSERT(false);
  return "invalid TeamColor";
}

std::string GameData::toString(CompetitionPhase value)
{
  switch (value)
  {
    RETURN_VALUE_TO_STR(roundrobin);
    RETURN_VALUE_TO_STR(playoff);
  }

  ASSERT(false);
  return "invalid CompetitionPhase";
}

std::string GameData::toString(CompetitionType value)
{
  switch (value)
  {
    RETURN_VALUE_TO_STR(competition_normal);
    RETURN_VALUE_TO_STR(competition_mixed);
    RETURN_VALUE_TO_STR(competition_penalty);
  }

  ASSERT(false);
  return "invalid CompetitionType";
}

std::string GameData::toString(GamePhase value)
{
  switch (value)
  {
    RETURN_VALUE_TO_STR(normal);
    RETURN_VALUE_TO_STR(penaltyshoot);
    RETURN_VALUE_TO_STR(overtime);
    RETURN_VALUE_TO_STR(timeout);
  }

  ASSERT(false);
  return "invalid SecondaryGameState";
}

std::string GameData::toString(GameState value)
{
  switch (value)
  {
    RETURN_VALUE_TO_STR(initial);
    RETURN_VALUE_TO_STR(ready);
    RETURN_VALUE_TO_STR(set);
    RETURN_VALUE_TO_STR(playing);
    RETURN_VALUE_TO_STR(finished);
    RETURN_VALUE_TO_STR(unknown_game_state);
  }

  ASSERT(false);
  return "invalid GameState";
}

std::string GameData::toString(SetPlay value)
{
  switch (value)
  {
    RETURN_VALUE_TO_STR(set_none);
    RETURN_VALUE_TO_STR(goal_free_kick);
    RETURN_VALUE_TO_STR(pushing_free_kick);
  }

  ASSERT(false);
  return "invalid SetPlay";
}

std::string GameData::toString(Penalty value)
{
  switch (value)
  {
    RETURN_VALUE_TO_STR(penalty_none);
    RETURN_VALUE_TO_STR(illegal_ball_contact);
    RETURN_VALUE_TO_STR(player_pushing);
    RETURN_VALUE_TO_STR(illegal_motion_in_set);
    RETURN_VALUE_TO_STR(inactive_player);
    RETURN_VALUE_TO_STR(illegal_defender);
    RETURN_VALUE_TO_STR(leaving_the_field);
    RETURN_VALUE_TO_STR(kick_off_goal);
    RETURN_VALUE_TO_STR(request_for_pickup);
    RETURN_VALUE_TO_STR(local_game_stuck);
    RETURN_VALUE_TO_STR(substitute);
    RETURN_VALUE_TO_STR(manual);
  }

  ASSERT(false);
  return "invalid Penalty";
}

#define RETURN_STING_TO_VALUE(value, str) if(toString(value) == str) return value

GameData::TeamColor GameData::teamColorFromString(const std::string& str)
{
  RETURN_STING_TO_VALUE(blue, str);
  RETURN_STING_TO_VALUE(red, str);
  RETURN_STING_TO_VALUE(yellow, str);
  RETURN_STING_TO_VALUE(black, str);
  RETURN_STING_TO_VALUE(white, str);
  RETURN_STING_TO_VALUE(green, str);
  RETURN_STING_TO_VALUE(orange, str);
  RETURN_STING_TO_VALUE(purple, str);
  RETURN_STING_TO_VALUE(brown, str);
  RETURN_STING_TO_VALUE(gray, str);

  return unknown_team_color;
}

GameData::GameState GameData::gameStateFromString(const std::string& str)
{
  RETURN_STING_TO_VALUE(initial, str);
  RETURN_STING_TO_VALUE(ready, str);
  RETURN_STING_TO_VALUE(set, str);
  RETURN_STING_TO_VALUE(playing, str);
  RETURN_STING_TO_VALUE(finished, str);

  return unknown_game_state;
}

void GameData::parseFrom(const spl::RoboCupGameControlData& data, int teamNumber)
{
  playersPerTeam    = data.playersPerTeam;

  competitionType   = (CompetitionType) data.competitionType;
  competitionPhase  = (CompetitionPhase) data.competitionPhase;
  gamePhase         = (GamePhase) data.gamePhase;
  gameState         = (GameState) data.state;
  setPlay           = (SetPlay) data.setPlay;

  firstHalf       = data.firstHalf == 1;
  kickingTeam     = data.kickingTeam;

  dropInTeam      = data.dropInTeam;

  // ACHTUNG: casting to signed values - game time can be negative (!)
  dropInTime      = (int16_t)data.dropInTime;
  secsRemaining   = (int16_t)data.secsRemaining;
  secondaryTime   = (int16_t)data.secondaryTime;

  // team info
  if(data.teams[0].teamNumber == teamNumber) {
    parseTeamInfo(ownTeam, data.teams[0]);
    parseTeamInfo(oppTeam, data.teams[1]);
  } else if(data.teams[1].teamNumber == teamNumber) {
    parseTeamInfo(ownTeam, data.teams[1]);
    parseTeamInfo(oppTeam, data.teams[0]);
  } else {
    ASSERT(false);
  }
}

void GameData::parseTeamInfo(TeamInfo& teamInfoDst, const spl::TeamInfo& teamInfoSrc) const
{
  teamInfoDst.penaltyShot = teamInfoSrc.penaltyShot;
  teamInfoDst.score = teamInfoSrc.score;
  teamInfoDst.teamColor = (TeamColor)teamInfoSrc.teamColor;
  teamInfoDst.teamNumber = teamInfoSrc.teamNumber;

  teamInfoDst.players.resize(playersPerTeam);
  for(int i = 0; i < playersPerTeam; i++) {
    teamInfoDst.players[i].penalty = (Penalty)teamInfoSrc.players[i].penalty;

    // ACHTUNG: casting to signed values - time can be negative (!)
    teamInfoDst.players[i].secsTillUnpenalised = (int8_t)teamInfoSrc.players[i].secsTillUnpenalised;
  }
}

void GameData::print(ostream& stream) const
{
  stream << "playersPerTeam = " << playersPerTeam << std::endl;

  stream << "competitionPhase = " << toString(competitionPhase) << std::endl;
  stream << "competitionType = "  << toString(competitionType) << std::endl;
  stream << "gamePhase = "        << toString(gamePhase) << std::endl;
  stream << "gameState = "        << toString(gameState) << std::endl;
  stream << "setPlay = "          << toString(setPlay) << std::endl;

  stream << "firstHalf = "      << firstHalf << std::endl;
  stream << "kickingTeam = "    << kickingTeam << std::endl;
  stream << "dropInTeam = "     << dropInTeam << std::endl;
  stream << "dropInTime = "     << dropInTime << std::endl;
  stream << "secsRemaining = "  << secsRemaining << std::endl;
  stream << "secondaryTime = "  << secondaryTime << std::endl;

  stream << std::endl;
  stream << "Own Team:" << std::endl;
  stream << " |- number = " << ownTeam.teamNumber << std::endl;
  stream << " |- color = " << toString(ownTeam.teamColor) << std::endl;
  stream << " |- score = " << ownTeam.score << std::endl;
  stream << " |- penaltyShot = " << ownTeam.penaltyShot << std::endl;
  stream << " |- players (penalty, time until unpenalize in s):" << std::endl;
  for(size_t i = 0; i < ownTeam.players.size(); ++i) {
    stream << "      |- " << (i+1) << ": " << toString(ownTeam.players[i].penalty) << " - " << ownTeam.players[i].secsTillUnpenalised << std::endl;
  }

  stream << std::endl;
  stream << "Opp Team:" << std::endl;
  stream << " |- number = " << oppTeam.teamNumber << std::endl;
  stream << " |- color = " << toString(oppTeam.teamColor) << std::endl;
  stream << " |- score = " << oppTeam.score << std::endl;
  stream << " |- penaltyShot = " << oppTeam.penaltyShot << std::endl;
  stream << " |- players (penalty, time until unpenalize in s):" << std::endl;
  for(size_t i = 0; i < oppTeam.players.size(); ++i) {
    stream << "      |- " << (i+1) << ": " << toString(oppTeam.players[i].penalty) << " - " << oppTeam.players[i].secsTillUnpenalised << std::endl;
  }
}

std::string GameReturnData::toString(Message value)
{
  switch (value)
  {
    RETURN_VALUE_TO_STR(manual_penalise);
    RETURN_VALUE_TO_STR(manual_unpenalise);
    RETURN_VALUE_TO_STR(alive);
  }

  ASSERT(false);
  return "invalide Message";
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: salvd.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2004-11-26 20:45:01 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <salunx.h>

#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALDISP_HXX
#include <saldisp.hxx>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALGDI_H
#include <salgdi.h>
#endif
#ifndef _SV_SALVD_H
#include <salvd.h>
#endif

// -=-= SalInstance =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
SalVirtualDevice* X11SalInstance::CreateVirtualDevice( SalGraphics* pGraphics,
                                                       long nDX, long nDY,
                                                       USHORT nBitCount, const SystemGraphicsData *pData )
{
    X11SalVirtualDevice *pVDev = new X11SalVirtualDevice();
    if( !nBitCount && pGraphics )
        nBitCount = pGraphics->GetBitCount();
    if( !pVDev->Init( GetSalData()->GetDisplay(), nDX, nDY, nBitCount ) )
    {
        delete pVDev;
        return NULL;
    }

    pVDev->InitGraphics( pVDev );
    return pVDev;
}

void X11SalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice )
{
    delete pDevice;
}

// -=-= SalGraphicsData =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void X11SalGraphics::Init( X11SalVirtualDevice *pDevice )
{
    SalDisplay *pDisplay  = pDevice->GetDisplay();

    int nVisualDepth = pDisplay->GetColormap().GetVisual()->GetDepth();
    int nDeviceDepth = pDevice->GetDepth();

    if( nDeviceDepth == nVisualDepth )
        m_pColormap = &pDisplay->GetColormap();
    else
    if( nDeviceDepth == 1 )
        m_pDeleteColormap = m_pColormap = new SalColormap();

    hDrawable_   = pDevice->GetDrawable();
    m_pVDev      = pDevice;
    m_pFrame     = NULL;

    bWindow_     = pDisplay->IsDisplay();
    bVirDev_     = TRUE;

    nPenPixel_   = GetPixel( nPenColor_ );
    nTextPixel_  = GetPixel( nTextColor_ );
    nBrushPixel_ = GetPixel( nBrushColor_ );
}

// -=-= SalVirDevData / SalVirtualDevice -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
BOOL X11SalVirtualDevice::Init( SalDisplay *pDisplay,
                                long nDX, long nDY,
                                USHORT nBitCount )
{
    pDisplay_               = pDisplay;
    pGraphics_              = new X11SalGraphics();
    pGraphics_->SetLayout( 0 ); // by default no! mirroring for VirtualDevices, can be enabled with EnableRTL()
    nDX_                    = nDX;
    nDY_                    = nDY;
    nDepth_                 = nBitCount;

    hDrawable_              = XCreatePixmap( GetXDisplay(),
                                     pDisplay_->GetDrawable(),
                                     nDX_, nDY_,
                                     GetDepth() );

    pGraphics_->Init( this );

    return hDrawable_ != None ? TRUE : FALSE;
}

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
X11SalVirtualDevice::X11SalVirtualDevice()
{
    pDisplay_               = (SalDisplay*)ILLEGAL_POINTER;
    pGraphics_              = NULL;
    hDrawable_              = None;
    nDX_                    = 0;
    nDY_                    = 0;
    nDepth_                 = 0;
    bGraphics_              = FALSE;
}

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
X11SalVirtualDevice::~X11SalVirtualDevice()
{
    if( pGraphics_ )
        delete pGraphics_;

    if( GetDrawable() )
        XFreePixmap( GetXDisplay(), GetDrawable() );
}

SalGraphics* X11SalVirtualDevice::GetGraphics()
{
    if( bGraphics_ )
        return NULL;

    if( pGraphics_ )
        bGraphics_ = TRUE;

    return pGraphics_;
}

void X11SalVirtualDevice::ReleaseGraphics( SalGraphics* )
{ bGraphics_ = FALSE; }

BOOL X11SalVirtualDevice::SetSize( long nDX, long nDY )
{
    if( !nDX ) nDX = 1;
    if( !nDY ) nDY = 1;

    Pixmap h = XCreatePixmap( GetXDisplay(),
                              pDisplay_->GetDrawable(),
                              nDX, nDY, nDepth_ );

    if( !h )
    {
        if( !GetDrawable() )
        {
            hDrawable_ = XCreatePixmap( GetXDisplay(),
                                        pDisplay_->GetDrawable(),
                                        1, 1, nDepth_ );
            nDX_ = 1;
            nDY_ = 1;
        }
        return FALSE;
    }

    if( GetDrawable() )
        XFreePixmap( GetXDisplay(), GetDrawable() );
    hDrawable_ = h;

    nDX_ = nDX;
    nDY_ = nDY;

    if( pGraphics_ )
        InitGraphics( this );

    return TRUE;
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.9.290); FILE MERGED 2005/09/05 14:45:45 rt 1.9.290.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: salvd.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 13:08:36 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <salunx.h>

#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALDISP_HXX
#include <saldisp.hxx>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALGDI_H
#include <salgdi.h>
#endif
#ifndef _SV_SALVD_H
#include <salvd.h>
#endif

// -=-= SalInstance =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
SalVirtualDevice* X11SalInstance::CreateVirtualDevice( SalGraphics* pGraphics,
                                                       long nDX, long nDY,
                                                       USHORT nBitCount, const SystemGraphicsData *pData )
{
    X11SalVirtualDevice *pVDev = new X11SalVirtualDevice();
    if( !nBitCount && pGraphics )
        nBitCount = pGraphics->GetBitCount();
    if( !pVDev->Init( GetSalData()->GetDisplay(), nDX, nDY, nBitCount ) )
    {
        delete pVDev;
        return NULL;
    }

    pVDev->InitGraphics( pVDev );
    return pVDev;
}

void X11SalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice )
{
    delete pDevice;
}

// -=-= SalGraphicsData =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void X11SalGraphics::Init( X11SalVirtualDevice *pDevice )
{
    SalDisplay *pDisplay  = pDevice->GetDisplay();

    int nVisualDepth = pDisplay->GetColormap().GetVisual()->GetDepth();
    int nDeviceDepth = pDevice->GetDepth();

    if( nDeviceDepth == nVisualDepth )
        m_pColormap = &pDisplay->GetColormap();
    else
    if( nDeviceDepth == 1 )
        m_pDeleteColormap = m_pColormap = new SalColormap();

    hDrawable_   = pDevice->GetDrawable();
    m_pVDev      = pDevice;
    m_pFrame     = NULL;

    bWindow_     = pDisplay->IsDisplay();
    bVirDev_     = TRUE;

    nPenPixel_   = GetPixel( nPenColor_ );
    nTextPixel_  = GetPixel( nTextColor_ );
    nBrushPixel_ = GetPixel( nBrushColor_ );
}

// -=-= SalVirDevData / SalVirtualDevice -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
BOOL X11SalVirtualDevice::Init( SalDisplay *pDisplay,
                                long nDX, long nDY,
                                USHORT nBitCount )
{
    pDisplay_               = pDisplay;
    pGraphics_              = new X11SalGraphics();
    pGraphics_->SetLayout( 0 ); // by default no! mirroring for VirtualDevices, can be enabled with EnableRTL()
    nDX_                    = nDX;
    nDY_                    = nDY;
    nDepth_                 = nBitCount;

    hDrawable_              = XCreatePixmap( GetXDisplay(),
                                     pDisplay_->GetDrawable(),
                                     nDX_, nDY_,
                                     GetDepth() );

    pGraphics_->Init( this );

    return hDrawable_ != None ? TRUE : FALSE;
}

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
X11SalVirtualDevice::X11SalVirtualDevice()
{
    pDisplay_               = (SalDisplay*)ILLEGAL_POINTER;
    pGraphics_              = NULL;
    hDrawable_              = None;
    nDX_                    = 0;
    nDY_                    = 0;
    nDepth_                 = 0;
    bGraphics_              = FALSE;
}

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
X11SalVirtualDevice::~X11SalVirtualDevice()
{
    if( pGraphics_ )
        delete pGraphics_;

    if( GetDrawable() )
        XFreePixmap( GetXDisplay(), GetDrawable() );
}

SalGraphics* X11SalVirtualDevice::GetGraphics()
{
    if( bGraphics_ )
        return NULL;

    if( pGraphics_ )
        bGraphics_ = TRUE;

    return pGraphics_;
}

void X11SalVirtualDevice::ReleaseGraphics( SalGraphics* )
{ bGraphics_ = FALSE; }

BOOL X11SalVirtualDevice::SetSize( long nDX, long nDY )
{
    if( !nDX ) nDX = 1;
    if( !nDY ) nDY = 1;

    Pixmap h = XCreatePixmap( GetXDisplay(),
                              pDisplay_->GetDrawable(),
                              nDX, nDY, nDepth_ );

    if( !h )
    {
        if( !GetDrawable() )
        {
            hDrawable_ = XCreatePixmap( GetXDisplay(),
                                        pDisplay_->GetDrawable(),
                                        1, 1, nDepth_ );
            nDX_ = 1;
            nDY_ = 1;
        }
        return FALSE;
    }

    if( GetDrawable() )
        XFreePixmap( GetXDisplay(), GetDrawable() );
    hDrawable_ = h;

    nDX_ = nDX;
    nDY_ = nDY;

    if( pGraphics_ )
        InitGraphics( this );

    return TRUE;
}

<|endoftext|>


<commit_before>/* type.cpp                                 -*- C++ -*-
   Rémi Attab (remi.attab@gmail.com), 24 Mar 2014
   FreeBSD-style copyright and disclaimer apply

   Type implementation.
*/

#include "reflect.h"

#include <algorithm>
#include <sstream>

namespace reflect {

/******************************************************************************/
/* TYPE                                                                       */
/******************************************************************************/

void
Type::
addTrait(std::string trait)
{
    traits_.emplace(std::move(trait));
}

bool
Type::
is(const std::string& trait) const
{
    return traits_.count(trait);
}

std::vector<std::string>
Type::
traits() const
{
    return { traits_.begin(), traits_.end() };
}

void
Type::
addFunctionTrait(const std::string& fn, std::string trait)
{
    fnTraits_[fn].emplace(std::move(trait));
}

bool
Type::
functionIs(const std::string& fn, const std::string& trait) const
{
    auto it = fnTraits_.find(fn);
    if (it != fnTraits_.end())
        return it->second.count(trait);

    return parent_ ? parent_->functionIs(fn, trait) : false;
}

bool
Type::
fieldIs(const std::string& field, const std::string& trait) const
{
    return functionIs(field, trait);
}

std::vector<std::string>
Type::
functionTraits(const std::string& fn) const
{
    auto it = fnTraits_.find(fn);
    if (it != fnTraits_.end())
        return { it->second.begin(), it->second.end() };

    return parent_ ? parent_->functionTraits(fn) : std::vector<std::string>();
}

std::vector<std::string>
Type::
fieldTraits(const std::string& field) const
{
    return functionTraits(field);
}

bool
Type::
isChildOf(const Type* other) const
{
    return this == other
        || (parent_ && parent_->isChildOf(other));
}

bool
Type::
isParentOf(const Type* other) const
{
    return other->isChildOf(this);
}

bool
Type::
hasConverter(const Type* other) const
{
    return hasField("operator " + other->id() + "()");
}

const Function&
Type::
converter(const Type* other) const
{
    auto& fns = field("operator " + other->id() + "()");

    if (fns.size() > 1) {
        reflectError("<%s> has too many converters for <%s>",
                id_, other->id());
    }

    return fns[0];
}

bool
Type::
isCopiable() const
{
    if (!hasField(id_)) return false;

    auto& fns = field(id_);
    return fns.test(
            Argument(this, RefType::Copy, false),
            { Argument(this, RefType::Copy, false) });
}

bool
Type::
isMovable() const
{
    if (!hasField(id_)) return false;

    auto& fns = field(id_);
    return fns.test(
            Argument(this, RefType::Copy, false),
            { Argument(this, RefType::RValue, false) });
}

void
Type::
functions(std::vector<std::string>& result) const
{
    result.reserve(result.size() + fns_.size());
    for (const auto& f : fns_)
        result.push_back(f.first);

    if (parent_) parent_->functions(result);
}

std::vector<std::string>
Type::
functions() const
{
    std::vector<std::string> result;
    functions(result);

    std::sort(result.begin(), result.end());
    result.erase(std::unique(result.begin(), result.end()), result.end());

    return result;
}

bool
Type::
hasFunction(const std::string& function) const
{
    if (fns_.find(function) != fns_.end()) return true;
    return parent_ ? parent_->hasFunction(function) : false;
}

const Overloads&
Type::
function(const std::string& function) const
{
    auto it = fns_.find(function);
    if (it != fns_.end()) return it->second;

    if (!parent_)
        reflectError("<%s> doesn't have a function <%s>", id_, function);

    return parent_->function(function);
}

void
Type::
fields(std::vector<std::string>& result) const
{
    result.reserve(result.size() + fns_.size());
    for (const auto& f : fns_) {
        if (!f.second.isField()) continue;
        result.push_back(f.first);
    }

    if (parent_) parent_->fields(result);
}

std::vector<std::string>
Type::
fields() const
{
    std::vector<std::string> result;
    fields(result);

    std::sort(result.begin(), result.end());
    result.erase(std::unique(result.begin(), result.end()), result.end());

    return result;
}

bool
Type::
hasField(const std::string& field) const
{
    auto it = fns_.find(field);
    if (it != fns_.end() && it->second.isField()) return true;
    return parent_ ? parent_->hasField(field) : false;
}

const Overloads&
Type::
field(const std::string& field) const
{
    auto it = fns_.find(field);
    if (it != fns_.end() && it->second.isField()) return it->second;

    if (!parent_)
        reflectError("<%s> doesn't have a field <%s>", id_, field);

    return parent_->field(field);
}

const Type*
Type::
fieldType(const std::string& field) const
{
    auto& f = this->field(field);
    return f.fieldType();
}

std::string
Type::
print(size_t indent) const
{
    enum { PadInc = 4 };

    std::stringstream ss;
    std::string pad0(indent, ' ');

    indent += PadInc;
    std::string pad1(indent, ' ');

    ss << pad0 << "struct " << id_ << "\n";
    ss << pad0 << "{\n";

    if (parent_) ss << parent_->print(indent) << "\n";

    for (const auto& field : fns_) {
        ss << pad1 << field.first << ":\n";
        ss << field.second.print(indent + PadInc);
    }

    ss << pad0 << "}\n";

    return ss.str();
}

} // reflect
<commit_msg>Traits are now printed in Type.<commit_after>/* type.cpp                                 -*- C++ -*-
   Rémi Attab (remi.attab@gmail.com), 24 Mar 2014
   FreeBSD-style copyright and disclaimer apply

   Type implementation.
*/

#include "reflect.h"

#include <algorithm>
#include <sstream>

namespace reflect {

/******************************************************************************/
/* TYPE                                                                       */
/******************************************************************************/

void
Type::
addTrait(std::string trait)
{
    traits_.emplace(std::move(trait));
}

bool
Type::
is(const std::string& trait) const
{
    return traits_.count(trait);
}

std::vector<std::string>
Type::
traits() const
{
    return { traits_.begin(), traits_.end() };
}

void
Type::
addFunctionTrait(const std::string& fn, std::string trait)
{
    fnTraits_[fn].emplace(std::move(trait));
}

bool
Type::
functionIs(const std::string& fn, const std::string& trait) const
{
    auto it = fnTraits_.find(fn);
    if (it != fnTraits_.end())
        return it->second.count(trait);

    return parent_ ? parent_->functionIs(fn, trait) : false;
}

bool
Type::
fieldIs(const std::string& field, const std::string& trait) const
{
    return functionIs(field, trait);
}

std::vector<std::string>
Type::
functionTraits(const std::string& fn) const
{
    auto it = fnTraits_.find(fn);
    if (it != fnTraits_.end())
        return { it->second.begin(), it->second.end() };

    return parent_ ? parent_->functionTraits(fn) : std::vector<std::string>();
}

std::vector<std::string>
Type::
fieldTraits(const std::string& field) const
{
    return functionTraits(field);
}

bool
Type::
isChildOf(const Type* other) const
{
    return this == other
        || (parent_ && parent_->isChildOf(other));
}

bool
Type::
isParentOf(const Type* other) const
{
    return other->isChildOf(this);
}

bool
Type::
hasConverter(const Type* other) const
{
    return hasField("operator " + other->id() + "()");
}

const Function&
Type::
converter(const Type* other) const
{
    auto& fns = field("operator " + other->id() + "()");

    if (fns.size() > 1) {
        reflectError("<%s> has too many converters for <%s>",
                id_, other->id());
    }

    return fns[0];
}

bool
Type::
isCopiable() const
{
    if (!hasField(id_)) return false;

    auto& fns = field(id_);
    return fns.test(
            Argument(this, RefType::Copy, false),
            { Argument(this, RefType::Copy, false) });
}

bool
Type::
isMovable() const
{
    if (!hasField(id_)) return false;

    auto& fns = field(id_);
    return fns.test(
            Argument(this, RefType::Copy, false),
            { Argument(this, RefType::RValue, false) });
}

void
Type::
functions(std::vector<std::string>& result) const
{
    result.reserve(result.size() + fns_.size());
    for (const auto& f : fns_)
        result.push_back(f.first);

    if (parent_) parent_->functions(result);
}

std::vector<std::string>
Type::
functions() const
{
    std::vector<std::string> result;
    functions(result);

    std::sort(result.begin(), result.end());
    result.erase(std::unique(result.begin(), result.end()), result.end());

    return result;
}

bool
Type::
hasFunction(const std::string& function) const
{
    if (fns_.find(function) != fns_.end()) return true;
    return parent_ ? parent_->hasFunction(function) : false;
}

const Overloads&
Type::
function(const std::string& function) const
{
    auto it = fns_.find(function);
    if (it != fns_.end()) return it->second;

    if (!parent_)
        reflectError("<%s> doesn't have a function <%s>", id_, function);

    return parent_->function(function);
}

void
Type::
fields(std::vector<std::string>& result) const
{
    result.reserve(result.size() + fns_.size());
    for (const auto& f : fns_) {
        if (!f.second.isField()) continue;
        result.push_back(f.first);
    }

    if (parent_) parent_->fields(result);
}

std::vector<std::string>
Type::
fields() const
{
    std::vector<std::string> result;
    fields(result);

    std::sort(result.begin(), result.end());
    result.erase(std::unique(result.begin(), result.end()), result.end());

    return result;
}

bool
Type::
hasField(const std::string& field) const
{
    auto it = fns_.find(field);
    if (it != fns_.end() && it->second.isField()) return true;
    return parent_ ? parent_->hasField(field) : false;
}

const Overloads&
Type::
field(const std::string& field) const
{
    auto it = fns_.find(field);
    if (it != fns_.end() && it->second.isField()) return it->second;

    if (!parent_)
        reflectError("<%s> doesn't have a field <%s>", id_, field);

    return parent_->field(field);
}

const Type*
Type::
fieldType(const std::string& field) const
{
    auto& f = this->field(field);
    return f.fieldType();
}

namespace {

void printTraits(
        std::stringstream& ss, const std::unordered_set<std::string>& traits)
{
    ss<< "traits: [ ";
    for (auto& trait : traits) ss << trait << " ";
    ss << "]\n";
}

} // namespace anonymous

std::string
Type::
print(size_t indent) const
{
    enum { PadInc = 4 };

    std::stringstream ss;
    std::string pad0(indent, ' ');

    indent += PadInc;
    std::string pad1(indent, ' ');
    std::string pad2(indent + PadInc, ' ');

    ss << pad0 << "struct " << id_ << "\n";
    ss << pad0 << "{\n";

    if (parent_) ss << parent_->print(indent) << "\n";

    if (!traits_.empty()) {
        ss << pad1; printTraits(ss, traits_);
    }

    for (auto& field : fns_) {
        ss << pad1 << field.first << ":\n";

        auto it = fnTraits_.find(field.first);
        if (it != fnTraits_.end()) {
            ss << pad2; printTraits(ss, it->second);
        }

        ss << field.second.print(indent + PadInc);
    }

    ss << pad0 << "}\n";

    return ss.str();
}

} // reflect
<|endoftext|>


<commit_before>// $Id$
//
// Task to filter Esd tracks and propagate to Emcal surface.
//
// Author: C.Loizides

#include "AliEmcalEsdTrackFilterTask.h"
#include <TClonesArray.h>
#include <TRandom3.h>
#include <TGeoGlobalMagField.h>
#include <AliAnalysisManager.h>
#include <AliEMCALRecoUtils.h>
#include <AliESDEvent.h>
#include <AliESDtrackCuts.h>
#include <AliMagF.h>
#include <AliTrackerBase.h>

ClassImp(AliEmcalEsdTrackFilterTask)

//________________________________________________________________________
AliEmcalEsdTrackFilterTask::AliEmcalEsdTrackFilterTask() :
  AliAnalysisTaskSE("AliEmcalEsdTrackFilterTask"),
  fEsdTrackCuts(0),
  fDoSpdVtxCon(0),
  fHybridTrackCuts(0),
  fTracksName(),
  fIncludeNoITS(kTRUE),
  fDoPropagation(kFALSE),
  fDist(440),
  fTrackEfficiency(1),
  fEsdEv(0),
  fTracks(0)
{
  // Constructor.
}

//________________________________________________________________________
AliEmcalEsdTrackFilterTask::AliEmcalEsdTrackFilterTask(const char *name) :
  AliAnalysisTaskSE(name),
  fEsdTrackCuts(0),
  fDoSpdVtxCon(0),
  fHybridTrackCuts(0),
  fTracksName("EsdTracksOut"),
  fIncludeNoITS(kTRUE),
  fDoPropagation(kFALSE),
  fDist(440),
  fTrackEfficiency(1),
  fEsdEv(0),
  fTracks(0)
{
  // Constructor.

  if (!name)
    return;

  SetName(name);

  fBranchNames = "ESD:AliESDHeader.,AliESDRun.,SPDVertex.,Tracks";
}

//________________________________________________________________________
AliEmcalEsdTrackFilterTask::~AliEmcalEsdTrackFilterTask()
{
  //Destructor

  delete fEsdTrackCuts;
}

//________________________________________________________________________
void AliEmcalEsdTrackFilterTask::UserCreateOutputObjects()
{
  // Create histograms.

  fTracks = new TClonesArray("AliESDtrack");
  fTracks->SetName(fTracksName);

  if (fDoSpdVtxCon) {
    if (!fEsdTrackCuts) {
      AliInfo("No track cuts given, creating default (standard only TPC) cuts");
      fEsdTrackCuts = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
      fEsdTrackCuts->SetPtRange(0.15,1e3);
    }
  } else {
    AliWarning("No track cuts given, but maybe this is indeed intended?");
  }
}

//________________________________________________________________________
void AliEmcalEsdTrackFilterTask::UserExec(Option_t *)
{
  // Main loop, called for each event.

  fEsdEv = dynamic_cast<AliESDEvent*>(InputEvent());
  if (!fEsdEv) {
    AliError("Task works only on ESD events, returning");
    return;
  }

  AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
  if (!am) {
    AliError("Manager zero, returning");
    return;
  }

  // add tracks to event if not yet there
  fTracks->Delete();
  if (!(InputEvent()->FindListObject(fTracksName)))
    InputEvent()->AddObject(fTracks);

  if (!fHybridTrackCuts) { // constrain TPC tracks to SPD vertex if fDoSpdVtxCon==kTRUE
    am->LoadBranch("AliESDRun.");
    am->LoadBranch("AliESDHeader.");
    am->LoadBranch("Tracks");

    if (fDoSpdVtxCon) {
      if (!TGeoGlobalMagField::Instance()->GetField()) { // construct field map
        fEsdEv->InitMagneticField();
      }
      am->LoadBranch("SPDVertex.");
      const AliESDVertex *vtxSPD = fEsdEv->GetPrimaryVertexSPD();
      if (!vtxSPD) {
        AliError("No SPD vertex, returning");
        return;
      }
      Int_t ntr = fEsdEv->GetNumberOfTracks();
      for (Int_t i=0, ntrnew=0; i<ntr; ++i) {
        AliESDtrack *etrack = fEsdEv->GetTrack(i);
        if (!etrack)
          continue;

	if (fTrackEfficiency < 1) {
	  Double_t r = gRandom->Rndm();
	  if (fTrackEfficiency < r)
	    continue;
	}

        if (!fEsdTrackCuts->AcceptTrack(etrack))
          continue;

        AliESDtrack *ntrack = AliESDtrackCuts::GetTPCOnlyTrack(fEsdEv,etrack->GetID());
        if (!ntrack)
          continue;
        if (ntrack->Pt()<=0) {
          delete ntrack;
          continue;
        }
        Double_t bfield[3] = {0,0,0};
        ntrack->GetBxByBz(bfield);
        AliExternalTrackParam exParam;
        Bool_t relate = ntrack->RelateToVertexBxByBz(vtxSPD,bfield,kVeryBig,&exParam);
        if (!relate) {
          delete ntrack;
          continue;
        }
        // set the constraint parameters to the track
        ntrack->Set(exParam.GetX(),exParam.GetAlpha(),exParam.GetParameter(),exParam.GetCovariance());
        if (ntrack->Pt()<=0) {
          delete ntrack;
          continue;
        }
	if (fDoPropagation)
	  AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(ntrack,fDist);
        new ((*fTracks)[ntrnew++]) AliESDtrack(*ntrack);
        delete ntrack;
      }
    } else { /* no spd vtx constraint */
      Int_t ntr = fEsdEv->GetNumberOfTracks();
      for (Int_t i=0, ntrnew=0; i<ntr; ++i) {
        AliESDtrack *etrack = fEsdEv->GetTrack(i);
        if (!etrack)
          continue;
	if (fTrackEfficiency < 1) {
	  Double_t r = gRandom->Rndm();
	  if (fTrackEfficiency < r)
	    continue;
	}
	if ((fEsdTrackCuts!=0) && !fEsdTrackCuts->AcceptTrack(etrack))
          continue;
        AliESDtrack *ntrack = new ((*fTracks)[ntrnew++]) AliESDtrack(*etrack);
	if (fDoPropagation)
	  AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(ntrack,fDist);
      }
    }

  } else { // use hybrid track cuts

    am->LoadBranch("Tracks");
    Int_t ntr = fEsdEv->GetNumberOfTracks();
    for (Int_t i=0, ntrnew=0; i<ntr; ++i) {
      AliESDtrack *etrack = fEsdEv->GetTrack(i);
      if (!etrack)
	continue;

      if (fTrackEfficiency < 1) {
	Double_t r = gRandom->Rndm();
	if (fTrackEfficiency < r)
	  continue;
      }

      if (fEsdTrackCuts->AcceptTrack(etrack)) {
        AliESDtrack *newTrack = new ((*fTracks)[ntrnew]) AliESDtrack(*etrack);
	if (fDoPropagation)
	  AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(newTrack,fDist);
        newTrack->SetBit(BIT(22),0);
        newTrack->SetBit(BIT(23),0);
        ++ntrnew;
      } else if (fHybridTrackCuts->AcceptTrack(etrack)) {
	if (!etrack->GetConstrainedParam())
	  continue;
	UInt_t status = etrack->GetStatus();
	if (!fIncludeNoITS && ((status&AliESDtrack::kITSrefit)==0))
	  continue;
	AliESDtrack *newTrack = new ((*fTracks)[ntrnew]) AliESDtrack(*etrack);
	if (fDoPropagation)
	  AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(newTrack,fDist);
	const AliExternalTrackParam* constrainParam = etrack->GetConstrainedParam();
	newTrack->Set(constrainParam->GetX(),
		      constrainParam->GetAlpha(),
		      constrainParam->GetParameter(),
		      constrainParam->GetCovariance());
	if ((status&AliESDtrack::kITSrefit)==0) {
	  newTrack->SetBit(BIT(22),0); //type 2
	  newTrack->SetBit(BIT(23),1);
	} else {
	  newTrack->SetBit(BIT(22),1); //type 1
	  newTrack->SetBit(BIT(23),0);
	}
	++ntrnew;
      }
    }
  }
}
<commit_msg>random track rejection (tracking efficiency studies) only after all cuts have been applied<commit_after>// $Id$
//
// Task to filter Esd tracks and propagate to Emcal surface.
//
// Author: C.Loizides

#include "AliEmcalEsdTrackFilterTask.h"
#include <TClonesArray.h>
#include <TRandom3.h>
#include <TGeoGlobalMagField.h>
#include <AliAnalysisManager.h>
#include <AliEMCALRecoUtils.h>
#include <AliESDEvent.h>
#include <AliESDtrackCuts.h>
#include <AliMagF.h>
#include <AliTrackerBase.h>

ClassImp(AliEmcalEsdTrackFilterTask)

//________________________________________________________________________
AliEmcalEsdTrackFilterTask::AliEmcalEsdTrackFilterTask() :
  AliAnalysisTaskSE("AliEmcalEsdTrackFilterTask"),
  fEsdTrackCuts(0),
  fDoSpdVtxCon(0),
  fHybridTrackCuts(0),
  fTracksName(),
  fIncludeNoITS(kTRUE),
  fDoPropagation(kFALSE),
  fDist(440),
  fTrackEfficiency(1),
  fEsdEv(0),
  fTracks(0)
{
  // Constructor.
}

//________________________________________________________________________
AliEmcalEsdTrackFilterTask::AliEmcalEsdTrackFilterTask(const char *name) :
  AliAnalysisTaskSE(name),
  fEsdTrackCuts(0),
  fDoSpdVtxCon(0),
  fHybridTrackCuts(0),
  fTracksName("EsdTracksOut"),
  fIncludeNoITS(kTRUE),
  fDoPropagation(kFALSE),
  fDist(440),
  fTrackEfficiency(1),
  fEsdEv(0),
  fTracks(0)
{
  // Constructor.

  if (!name)
    return;

  SetName(name);

  fBranchNames = "ESD:AliESDHeader.,AliESDRun.,SPDVertex.,Tracks";
}

//________________________________________________________________________
AliEmcalEsdTrackFilterTask::~AliEmcalEsdTrackFilterTask()
{
  //Destructor

  delete fEsdTrackCuts;
}

//________________________________________________________________________
void AliEmcalEsdTrackFilterTask::UserCreateOutputObjects()
{
  // Create histograms.

  fTracks = new TClonesArray("AliESDtrack");
  fTracks->SetName(fTracksName);

  if (fDoSpdVtxCon) {
    if (!fEsdTrackCuts) {
      AliInfo("No track cuts given, creating default (standard only TPC) cuts");
      fEsdTrackCuts = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
      fEsdTrackCuts->SetPtRange(0.15,1e3);
    }
  } else {
    AliWarning("No track cuts given, but maybe this is indeed intended?");
  }
}

//________________________________________________________________________
void AliEmcalEsdTrackFilterTask::UserExec(Option_t *)
{
  // Main loop, called for each event.

  fEsdEv = dynamic_cast<AliESDEvent*>(InputEvent());
  if (!fEsdEv) {
    AliError("Task works only on ESD events, returning");
    return;
  }

  AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
  if (!am) {
    AliError("Manager zero, returning");
    return;
  }

  // add tracks to event if not yet there
  fTracks->Delete();
  if (!(InputEvent()->FindListObject(fTracksName)))
    InputEvent()->AddObject(fTracks);

  if (!fHybridTrackCuts) { // constrain TPC tracks to SPD vertex if fDoSpdVtxCon==kTRUE
    am->LoadBranch("AliESDRun.");
    am->LoadBranch("AliESDHeader.");
    am->LoadBranch("Tracks");

    if (fDoSpdVtxCon) {
      if (!TGeoGlobalMagField::Instance()->GetField()) { // construct field map
        fEsdEv->InitMagneticField();
      }
      am->LoadBranch("SPDVertex.");
      const AliESDVertex *vtxSPD = fEsdEv->GetPrimaryVertexSPD();
      if (!vtxSPD) {
        AliError("No SPD vertex, returning");
        return;
      }
      Int_t ntr = fEsdEv->GetNumberOfTracks();
      for (Int_t i=0, ntrnew=0; i<ntr; ++i) {
        AliESDtrack *etrack = fEsdEv->GetTrack(i);
        if (!etrack)
          continue;

        if (!fEsdTrackCuts->AcceptTrack(etrack))
          continue;

        AliESDtrack *ntrack = AliESDtrackCuts::GetTPCOnlyTrack(fEsdEv,etrack->GetID());
        if (!ntrack)
          continue;
        if (ntrack->Pt()<=0) {
          delete ntrack;
          continue;
        }
        Double_t bfield[3] = {0,0,0};
        ntrack->GetBxByBz(bfield);
        AliExternalTrackParam exParam;
        Bool_t relate = ntrack->RelateToVertexBxByBz(vtxSPD,bfield,kVeryBig,&exParam);
        if (!relate) {
          delete ntrack;
          continue;
        }
        // set the constraint parameters to the track
        ntrack->Set(exParam.GetX(),exParam.GetAlpha(),exParam.GetParameter(),exParam.GetCovariance());
        if (ntrack->Pt()<=0) {
          delete ntrack;
          continue;
        }

	if (fTrackEfficiency < 1) {
	  Double_t r = gRandom->Rndm();
	  if (fTrackEfficiency < r)
	    continue;
	}

	if (fDoPropagation)
	  AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(ntrack,fDist);
        new ((*fTracks)[ntrnew++]) AliESDtrack(*ntrack);
        delete ntrack;
      }
    } else { /* no spd vtx constraint */
      Int_t ntr = fEsdEv->GetNumberOfTracks();
      for (Int_t i=0, ntrnew=0; i<ntr; ++i) {
        AliESDtrack *etrack = fEsdEv->GetTrack(i);
        if (!etrack)
          continue;

	if ((fEsdTrackCuts!=0) && !fEsdTrackCuts->AcceptTrack(etrack))
          continue;

	if (fTrackEfficiency < 1) {
	  Double_t r = gRandom->Rndm();
	  if (fTrackEfficiency < r)
	    continue;
	}

        AliESDtrack *ntrack = new ((*fTracks)[ntrnew++]) AliESDtrack(*etrack);
	if (fDoPropagation)
	  AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(ntrack,fDist);
      }
    }

  } else { // use hybrid track cuts

    am->LoadBranch("Tracks");
    Int_t ntr = fEsdEv->GetNumberOfTracks();
    for (Int_t i=0, ntrnew=0; i<ntr; ++i) {
      AliESDtrack *etrack = fEsdEv->GetTrack(i);
      if (!etrack)
	continue;

      if (fEsdTrackCuts->AcceptTrack(etrack)) {
        AliESDtrack *newTrack = new ((*fTracks)[ntrnew]) AliESDtrack(*etrack);
	if (fDoPropagation)
	  AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(newTrack,fDist);
        newTrack->SetBit(BIT(22),0);
        newTrack->SetBit(BIT(23),0);
        ++ntrnew;
      } else if (fHybridTrackCuts->AcceptTrack(etrack)) {
	if (!etrack->GetConstrainedParam())
	  continue;
	UInt_t status = etrack->GetStatus();
	if (!fIncludeNoITS && ((status&AliESDtrack::kITSrefit)==0))
	  continue;

	if (fTrackEfficiency < 1) {
	  Double_t r = gRandom->Rndm();
	  if (fTrackEfficiency < r)
	    continue;
	}

	AliESDtrack *newTrack = new ((*fTracks)[ntrnew]) AliESDtrack(*etrack);
	if (fDoPropagation)
	  AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(newTrack,fDist);
	const AliExternalTrackParam* constrainParam = etrack->GetConstrainedParam();
	newTrack->Set(constrainParam->GetX(),
		      constrainParam->GetAlpha(),
		      constrainParam->GetParameter(),
		      constrainParam->GetCovariance());
	if ((status&AliESDtrack::kITSrefit)==0) {
	  newTrack->SetBit(BIT(22),0); //type 2
	  newTrack->SetBit(BIT(23),1);
	} else {
	  newTrack->SetBit(BIT(22),1); //type 1
	  newTrack->SetBit(BIT(23),0);
	}
	++ntrnew;
      }
    }
  }
}
<|endoftext|>


<commit_before>#include "type_name.h"

int main()
{
    const volatile char abc[1][2][3]{};
    std::cout << type_name<decltype(abc)>() << std::endl;
}
<commit_msg>Remove main.C - missed with rename to main.cpp<commit_after><|endoftext|>