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

  Program:   Visualization Toolkit
  Module:    vtkCellArray.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

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

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

=========================================================================*/
#include "vtkCellArray.h"
#include "vtkObjectFactory.h"

vtkCxxRevisionMacro(vtkCellArray, "1.39");
vtkStandardNewMacro(vtkCellArray);

vtkCellArray::vtkCellArray()
{
  this->Ia = vtkIdTypeArray::New();
  this->NumberOfCells = 0;
  this->InsertLocation = 0;
  this->TraversalLocation = 0;
}

void vtkCellArray::DeepCopy (vtkCellArray *ca)
{
  // Do nothing on a NULL input.
  if (ca == NULL)
    {
    return;
    }

  this->Ia->DeepCopy(ca->Ia);
  this->NumberOfCells = ca->NumberOfCells;
  this->InsertLocation = 0;
  this->TraversalLocation = 0;
}

vtkCellArray::~vtkCellArray()
{
  this->Ia->Delete();
}

// Returns the size of the largest cell. The size is the number of points
// defining the cell.
int vtkCellArray::GetMaxCellSize()
{
  int i, npts=0, maxSize=0;

  for (i=0; i<this->Ia->GetMaxId(); i+=(npts+1))
    {
    if ( (npts=this->Ia->GetValue(i)) > maxSize )
      {
      maxSize = npts;
      }
    }
  return maxSize;
}

// Specify a group of cells.
void vtkCellArray::SetCells(vtkIdType ncells, vtkIdTypeArray *cells)
{
  if ( cells != this->Ia )
    {
    this->Modified();
    this->Ia->Delete();
    this->Ia = cells;
    this->Ia->Register(this);

    this->NumberOfCells = ncells;
    this->InsertLocation = cells->GetMaxId() + 1;
    this->TraversalLocation = 0;
    }
}

unsigned long vtkCellArray::GetActualMemorySize()
{
  return this->Ia->GetActualMemorySize();
}
<commit_msg>Bug in DeepCopy<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkCellArray.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

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

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

=========================================================================*/
#include "vtkCellArray.h"
#include "vtkObjectFactory.h"

vtkCxxRevisionMacro(vtkCellArray, "1.40");
vtkStandardNewMacro(vtkCellArray);

vtkCellArray::vtkCellArray()
{
  this->Ia = vtkIdTypeArray::New();
  this->NumberOfCells = 0;
  this->InsertLocation = 0;
  this->TraversalLocation = 0;
}

void vtkCellArray::DeepCopy (vtkCellArray *ca)
{
  // Do nothing on a NULL input.
  if (ca == NULL)
    {
    return;
    }

  this->Ia->DeepCopy(ca->Ia);
  this->NumberOfCells = ca->NumberOfCells;
  this->InsertLocation = ca->InsertLocation;
  this->TraversalLocation = ca->TraversalLocation;
}

vtkCellArray::~vtkCellArray()
{
  this->Ia->Delete();
}

// Returns the size of the largest cell. The size is the number of points
// defining the cell.
int vtkCellArray::GetMaxCellSize()
{
  int i, npts=0, maxSize=0;

  for (i=0; i<this->Ia->GetMaxId(); i+=(npts+1))
    {
    if ( (npts=this->Ia->GetValue(i)) > maxSize )
      {
      maxSize = npts;
      }
    }
  return maxSize;
}

// Specify a group of cells.
void vtkCellArray::SetCells(vtkIdType ncells, vtkIdTypeArray *cells)
{
  if ( cells != this->Ia )
    {
    this->Modified();
    this->Ia->Delete();
    this->Ia = cells;
    this->Ia->Register(this);

    this->NumberOfCells = ncells;
    this->InsertLocation = cells->GetMaxId() + 1;
    this->TraversalLocation = 0;
    }
}

unsigned long vtkCellArray::GetActualMemorySize()
{
  return this->Ia->GetActualMemorySize();
}
<|endoftext|>


<commit_before>//debugging level 0 = nothing
//debugging level 1 = critical errors
//debugging level 2 = errors
//debugging level 3 = status information
//debugging level 4 = extremely verbose status information
#define DEBUG 3

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/epoll.h>
#include <getopt.h>

enum {HANDLER_PROGRESSIVE, HANDLER_FLASH, HANDLER_APPLE, HANDLER_MICRO};

#define DEFAULT_PORT 80
#include "../util/server_setup.cpp"
#include "../util/http_parser.cpp"

int mainHandler(int CONN_fd){
  int handler = HANDLER_PROGRESSIVE;
  bool ready4data = false;//set to true when streaming starts
  bool inited = false;
  bool progressive_has_sent_header = false;
  int ss;
  std::string streamname;
  FLV_Pack * tag = 0;
  HTTPReader HTTP_R, HTTP_S;//HTTP Receiver en HTTP Sender.

  int retval;
  int poller = epoll_create(1);
  int sspoller = epoll_create(1);
  struct epoll_event ev;
  ev.events = EPOLLIN;
  ev.data.fd = CONN_fd;
  epoll_ctl(poller, EPOLL_CTL_ADD, CONN_fd, &ev);
  struct epoll_event events[1];

  std::string Movie = "";
  std::string Quality = "";
  int Segment = -1;
  int Fragment = -1;
  int temp;

  while (!socketError && !All_Hell_Broke_Loose){
    //only parse input if available or not yet init'ed
    retval = epoll_wait(poller, events, 1, 1);
    if ((retval > 0) || !ready4data){
      if (HTTP_R.ReadSocket(CONN_fd)){
        Movie = HTTP_R.url.substr(1);
        Movie = Movie.substr(0,Movie.find("/"));
        Quality = HTTP_R.url.substr( HTTP_R.url.find("/",1)+1 );
        Quality = Quality.substr(0, Quality.find("Seg"));
        temp = HTTP_R.url.find("Seg") + 3;
        Segment = atoi( HTTP_R.url.substr(temp,HTTP_R.url.find("-",temp)-temp).c_str());
        temp = HTTP_R.url.find("Frag") + 4;
        Fragment = atoi( HTTP_R.url.substr(temp).c_str() );
        //ERIK: we hebben nu een hele HTTP request geparsed - verwerken mag hier, door aanroepen naar
        //ERIK: bijvoorbeeld HTTP_R.GetHeader("headernaam") (voor headers) of HTTP_R.GetVar("varnaam") (voor GET/POST vars)
        //ERIK: of HTTP_R.method of HTTP_R.url of HTTP_R.protocol....
        //ERIK: zie ook ../util/http_parser.cpp - de class definitie bovenaan zou genoeg moeten zijn voor je
        //ERIK: Ik heb een handler variabele gemaakt die moet setten naar bijv HANDLER_FLASH in jouw geval.
        //ERIK: Als de handler niet is geset, is hij by default PROGRESSIVE, en daarvoor heb ik de verwerking al gecode.
        //ERIK: Je eigen handler instellen voorkomt dus dat mijn code hem handled alsof hij progressive is.
        if (handler == HANDLER_PROGRESSIVE){
          //in het geval progressive nemen we aan dat de URL de streamname is, met .flv erachter
          streamname = HTTP_R.url.substr(0, HTTP_R.url.size()-4);//strip de .flv
          for (std::string::iterator i=streamname.end()-1; i>=streamname.begin(); --i){
            if (!isalpha(*i) && !isdigit(*i)){streamname.erase(i);}else{*i=tolower(*i);}//strip nonalphanumeric
          }
          streamname = "/tmp/shared_socket_" + streamname;//dit is dan onze shared_socket
          //normaal zouden we ook een position uitlezen uit de URL, maar bij LIVE streams is dat zinloos
          ready4data = true;
        }//PROGRESSIVE handler
        printf( "URL: %s\n", HTTP_R.url.c_str());
        printf( "Movie Identifier: %s\n", Movie.c_str() );
        printf( "Quality Modifier: %s\n", Quality.c_str() );
        printf( "Segment: %d\n", Segment );
        printf( "Fragment: %d\n", Fragment );
        HTTP_R.Clean(); //maak schoon na verwerken voor eventuele volgende requests...
      }
    }
    if (ready4data){
      if (!inited){
        //we are ready, connect the socket!
        ss = DDV_OpenUnix(streamname);
        if (ss <= 0){
          #if DEBUG >= 1
          fprintf(stderr, "Could not connect to server!\n");
          #endif
          socketError = 1;
          break;
        }
        ev.events = EPOLLIN;
        ev.data.fd = ss;
        epoll_ctl(sspoller, EPOLL_CTL_ADD, ss, &ev);
        #if DEBUG >= 3
        fprintf(stderr, "Everything connected, starting to send video data...\n");
        #endif
        inited = true;
      }

      retval = epoll_wait(sspoller, events, 1, 1);
      switch (DDV_ready(ss)){
        case 0:
          socketError = true;
          #if DEBUG >= 1
          fprintf(stderr, "Source socket is disconnected.\n");
          #endif
          break;
        case -1: break;//not ready yet
        default:
          if (FLV_GetPacket(tag, ss)){//able to read a full packet?
            //ERIK: "tag" bevat nu een FLV tag (video, audio, of metadata), de header hebben we al weggelezen, np.
            //ERIK: Dit is het punt waarop je eventueel data mag/kan gaan sturen en/of parsen. Leef je uit.
            //ERIK: je kan een HTTP_S gebruiken om je HTTP request op te bouwen (via SetBody, SetHeader, etc)
            //ERIK: en dan met de .BuildResponse("200", "OK"); call een std::string met de hele response maken, klaar voor versturen
            //ERIK: Note: hergebruik echter NIET de HTTP_R die ik al heb gemaakt hierboven, want er kunnen meerdere requests binnenkomen!
            if (handler == HANDLER_PROGRESSIVE){
              if (!progressive_has_sent_header){
                HTTP_S.Clean();//troep opruimen die misschien aanwezig is...
                HTTP_S.SetHeader("Content-Type", "video/x-flv");//FLV files hebben altijd dit content-type.
                std::string tmpresp = HTTP_S.BuildResponse("200", "OK");//geen SetBody = unknown length! Dat willen we hier.
                DDV_write(tmpresp.c_str(), tmpresp.size(), CONN_fd);//schrijf de HTTP response header
                DDV_write(FLVHeader, 13, CONN_fd);//schrijf de FLV header, altijd 13 chars lang
                progressive_has_sent_header = true;
              }
              DDV_write(tag->data, tag->len, CONN_fd);//schrijf deze FLV tag onbewerkt weg
            }//PROGRESSIVE handler
          }
          break;
      }
    }
  }
  close(CONN_fd);
  if (inited) close(ss);
  #if DEBUG >= 1
  if (All_Hell_Broke_Loose){fprintf(stderr, "All Hell Broke Loose\n");}
  fprintf(stderr, "User %i disconnected.\n", CONN_fd);
  if (inited){
    fprintf(stderr, "Status was: inited\n");
  }else{
    if (ready4data){
      fprintf(stderr, "Status was: ready4data\n");
    }else{
      fprintf(stderr, "Status was: connected\n");
    }
  }
  #endif
  return 0;
}

<commit_msg>HTTP connector setting voor FLASH handler toegevoegd<commit_after>//debugging level 0 = nothing
//debugging level 1 = critical errors
//debugging level 2 = errors
//debugging level 3 = status information
//debugging level 4 = extremely verbose status information
#define DEBUG 3

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/epoll.h>
#include <getopt.h>

enum {HANDLER_PROGRESSIVE, HANDLER_FLASH, HANDLER_APPLE, HANDLER_MICRO};

#define DEFAULT_PORT 80
#include "../util/server_setup.cpp"
#include "../util/http_parser.cpp"

int mainHandler(int CONN_fd){
  int handler = HANDLER_PROGRESSIVE;
  bool ready4data = false;//set to true when streaming starts
  bool inited = false;
  bool progressive_has_sent_header = false;
  int ss;
  std::string streamname;
  FLV_Pack * tag = 0;
  HTTPReader HTTP_R, HTTP_S;//HTTP Receiver en HTTP Sender.

  int retval;
  int poller = epoll_create(1);
  int sspoller = epoll_create(1);
  struct epoll_event ev;
  ev.events = EPOLLIN;
  ev.data.fd = CONN_fd;
  epoll_ctl(poller, EPOLL_CTL_ADD, CONN_fd, &ev);
  struct epoll_event events[1];

  std::string Movie = "";
  std::string Quality = "";
  int Segment = -1;
  int Fragment = -1;
  int temp;

  while (!socketError && !All_Hell_Broke_Loose){
    //only parse input if available or not yet init'ed
    retval = epoll_wait(poller, events, 1, 1);
    if ((retval > 0) || !ready4data){
      if (HTTP_R.ReadSocket(CONN_fd)){
        if( (HTTP_R.url.find("Seg") != std::string::npos) &&
            (HTTP_R.url.find("Frag") != std::string::npos) ) {
          handler = HANDLER_FLASH;
        }
        if(handler == HANDLER_FLASH) {
          Movie = HTTP_R.url.substr(1);
          Movie = Movie.substr(0,Movie.find("/"));
          Quality = HTTP_R.url.substr( HTTP_R.url.find("/",1)+1 );
          Quality = Quality.substr(0, Quality.find("Seg"));
          temp = HTTP_R.url.find("Seg") + 3;
          Segment = atoi( HTTP_R.url.substr(temp,HTTP_R.url.find("-",temp)-temp).c_str());
          temp = HTTP_R.url.find("Frag") + 4;
          Fragment = atoi( HTTP_R.url.substr(temp).c_str() );

          printf( "URL: %s\n", HTTP_R.url.c_str());
          printf( "Movie Identifier: %s\n", Movie.c_str() );
          printf( "Quality Modifier: %s\n", Quality.c_str() );
          printf( "Segment: %d\n", Segment );
          printf( "Fragment: %d\n", Fragment );
          streamname = "/tmp/shared_socket_";
          streamname += Movie.c_str();

          ready4data = true;
        }//FLASH handler
        //ERIK: we hebben nu een hele HTTP request geparsed - verwerken mag hier, door aanroepen naar
        //ERIK: bijvoorbeeld HTTP_R.GetHeader("headernaam") (voor headers) of HTTP_R.GetVar("varnaam") (voor GET/POST vars)
        //ERIK: of HTTP_R.method of HTTP_R.url of HTTP_R.protocol....
        //ERIK: zie ook ../util/http_parser.cpp - de class definitie bovenaan zou genoeg moeten zijn voor je

        //ERIK: Ik heb een handler variabele gemaakt die moet setten naar bijv HANDLER_FLASH in jouw geval.
        //ERIK: Als de handler niet is geset, is hij by default PROGRESSIVE, en daarvoor heb ik de verwerking al gecode.
        //ERIK: Je eigen handler instellen voorkomt dus dat mijn code hem handled alsof hij progressive is.
        if (handler == HANDLER_PROGRESSIVE){
          //in het geval progressive nemen we aan dat de URL de streamname is, met .flv erachter
          streamname = HTTP_R.url.substr(0, HTTP_R.url.size()-4);//strip de .flv
          for (std::string::iterator i=streamname.end()-1; i>=streamname.begin(); --i){
            if (!isalpha(*i) && !isdigit(*i)){streamname.erase(i);}else{*i=tolower(*i);}//strip nonalphanumeric
          }
          streamname = "/tmp/shared_socket_" + streamname;//dit is dan onze shared_socket
          //normaal zouden we ook een position uitlezen uit de URL, maar bij LIVE streams is dat zinloos
          ready4data = true;
        }//PROGRESSIVE handler
        HTTP_R.Clean(); //maak schoon na verwerken voor eventuele volgende requests...
      }
    }
    if (ready4data){
      if (!inited){
        //we are ready, connect the socket!
        ss = DDV_OpenUnix(streamname);
        if (ss <= 0){
          #if DEBUG >= 1
          fprintf(stderr, "Could not connect to server!\n");
          #endif
          socketError = 1;
          break;
        }
        ev.events = EPOLLIN;
        ev.data.fd = ss;
        epoll_ctl(sspoller, EPOLL_CTL_ADD, ss, &ev);
        #if DEBUG >= 3
        fprintf(stderr, "Everything connected, starting to send video data...\n");
        #endif
        inited = true;
      }

      retval = epoll_wait(sspoller, events, 1, 1);
      switch (DDV_ready(ss)){
        case 0:
          socketError = true;
          #if DEBUG >= 1
          fprintf(stderr, "Source socket is disconnected.\n");
          #endif
          break;
        case -1: break;//not ready yet
        default:
          if (FLV_GetPacket(tag, ss)){//able to read a full packet?
            //ERIK: "tag" bevat nu een FLV tag (video, audio, of metadata), de header hebben we al weggelezen, np.
            //ERIK: Dit is het punt waarop je eventueel data mag/kan gaan sturen en/of parsen. Leef je uit.
            //ERIK: je kan een HTTP_S gebruiken om je HTTP request op te bouwen (via SetBody, SetHeader, etc)
            //ERIK: en dan met de .BuildResponse("200", "OK"); call een std::string met de hele response maken, klaar voor versturen
            //ERIK: Note: hergebruik echter NIET de HTTP_R die ik al heb gemaakt hierboven, want er kunnen meerdere requests binnenkomen!
            if (handler == HANDLER_PROGRESSIVE){
              if (!progressive_has_sent_header){
                HTTP_S.Clean();//troep opruimen die misschien aanwezig is...
                HTTP_S.SetHeader("Content-Type", "video/x-flv");//FLV files hebben altijd dit content-type.
                std::string tmpresp = HTTP_S.BuildResponse("200", "OK");//geen SetBody = unknown length! Dat willen we hier.
                DDV_write(tmpresp.c_str(), tmpresp.size(), CONN_fd);//schrijf de HTTP response header
                DDV_write(FLVHeader, 13, CONN_fd);//schrijf de FLV header, altijd 13 chars lang
                progressive_has_sent_header = true;
              }
              DDV_write(tag->data, tag->len, CONN_fd);//schrijf deze FLV tag onbewerkt weg
            }//PROGRESSIVE handler
          }
          break;
      }
    }
  }
  close(CONN_fd);
  if (inited) close(ss);
  #if DEBUG >= 1
  if (All_Hell_Broke_Loose){fprintf(stderr, "All Hell Broke Loose\n");}
  fprintf(stderr, "User %i disconnected.\n", CONN_fd);
  if (inited){
    fprintf(stderr, "Status was: inited\n");
  }else{
    if (ready4data){
      fprintf(stderr, "Status was: ready4data\n");
    }else{
      fprintf(stderr, "Status was: connected\n");
    }
  }
  #endif
  return 0;
}

<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include "BaseViewer.h"
#include "PickHandler.h"

#include <sofa/helper/Factory.inl>
#include <sofa/component/visualmodel/VisualStyle.h>
#include <sofa/core/visual/DisplayFlags.h>

namespace sofa
{
namespace gui
{

BaseViewer::BaseViewer()
    : groot(NULL)
    , currentCamera(NULL)
    , _video(false)
    , _axis(false)
    , backgroundColour(Vector3())
    , texLogo(NULL)
    , backgroundImageFile("textures/SOFA_logo.bmp")
    , ambientColour(Vector3())
    , _stereoEnabled(false)
    , _stereoMode(STEREO_AUTO)
    , _stereoShift(1.0)
    ,pick(NULL)
{
    pick = new PickHandler();
}

BaseViewer::~BaseViewer()
{
    if(texLogo)
    {
        delete texLogo;
        texLogo = NULL;
    }
}

sofa::simulation::Node* BaseViewer::getScene()
{
    return groot.get();
}
const std::string& BaseViewer::getSceneFileName()
{
    return sceneFileName;
}
void BaseViewer::setSceneFileName(const std::string &f)
{
    sceneFileName = f;
}

void BaseViewer::setScene(sofa::simulation::Node::SPtr scene, const char* filename /* = NULL */, bool /* = false */)
{
    std::string file =
        filename ? sofa::helper::system::SetDirectory::GetFileNameWithoutExtension(
                filename) : std::string();
    std::string screenshotPrefix =
        sofa::helper::system::SetDirectory::GetParentDir(
                sofa::helper::system::DataRepository.getFirstPath().c_str())
        + std::string("/share/screenshots/") + file
        + std::string("_");
    capture.setPrefix(screenshotPrefix);
#ifdef SOFA_HAVE_FFMPEG
    videoRecorder.setPrefix(screenshotPrefix);
#endif //SOFA_HAVE_FFMPEG
    sceneFileName = filename ? filename : std::string("default.scn");
    groot = scene;
    initTexturesDone = false;

    //Camera initialization
    if (groot)
    {
        groot->get(currentCamera);
        if (!currentCamera)
        {
            currentCamera = sofa::core::objectmodel::New<component::visualmodel::InteractiveCamera>();
            currentCamera->setName(core::objectmodel::Base::shortName(currentCamera.get()));
            groot->addObject(currentCamera);
            currentCamera->p_position.forceSet();
            currentCamera->p_orientation.forceSet();
            currentCamera->bwdInit();

        }
        component::visualmodel::VisualStyle::SPtr visualStyle = NULL;
        groot->get(visualStyle);
        if (!visualStyle)
        {
            visualStyle = sofa::core::objectmodel::New<component::visualmodel::VisualStyle>();
            visualStyle->setName(core::objectmodel::Base::shortName(visualStyle.get()));

            core::visual::DisplayFlags* displayFlags = visualStyle->displayFlags.beginEdit();
            displayFlags->setShowVisualModels(sofa::core::visual::tristate::true_value);
            visualStyle->displayFlags.endEdit();

            groot->addObject(visualStyle);
            visualStyle->init();
        }

        currentCamera->setBoundingBox(groot->f_bbox.getValue().minBBox(), groot->f_bbox.getValue().maxBBox());

        // init pickHandler
        pick->init(groot.get());
    }

}

void BaseViewer::setCameraMode(core::visual::VisualParams::CameraType mode)
{
    currentCamera->setCameraType(mode);
}

bool BaseViewer::ready()
{
    return true;
}

void BaseViewer::wait()
{
}

void BaseViewer::configure(sofa::component::configurationsetting::ViewerSetting* viewerConf)
{
    using namespace core::visual;
    if (viewerConf->cameraMode.getValue().getSelectedId() == VisualParams::ORTHOGRAPHIC_TYPE)
        setCameraMode(VisualParams::ORTHOGRAPHIC_TYPE);
    else
        setCameraMode(VisualParams::PERSPECTIVE_TYPE);
    if ( viewerConf->objectPickingMethod.getValue().getSelectedId() == gui::PickHandler::RAY_CASTING)
        pick->setPickingMethod( gui::PickHandler::RAY_CASTING );
    else
        pick->setPickingMethod( gui::PickHandler::SELECTION_BUFFER);
}

//Fonctions needed to take a screenshot
const std::string BaseViewer::screenshotName()
{
    return capture.findFilename().c_str();
}

void BaseViewer::setPrefix(const std::string filename)
{
    capture.setPrefix(filename);
}

void BaseViewer::screenshot(const std::string filename, int compression_level)
{
    capture.saveScreen(filename, compression_level);
}

void BaseViewer::getView(Vec3d& pos, Quat& ori) const
{
    if (!currentCamera)
        return;

    const Vec3d& camPosition = currentCamera->getPosition();
    const Quat& camOrientation = currentCamera->getOrientation();

    pos[0] = camPosition[0];
    pos[1] = camPosition[1];
    pos[2] = camPosition[2];

    ori[0] = camOrientation[0];
    ori[1] = camOrientation[1];
    ori[2] = camOrientation[2];
    ori[3] = camOrientation[3];
}

void BaseViewer::setView(const Vec3d& pos, const Quat &ori)
{
    Vec3d position;
    Quat orientation;
    for (unsigned int i=0 ; i<3 ; i++)
    {
        position[i] = pos[i];
        orientation[i] = ori[i];
    }
    orientation[3] = ori[3];

    if (currentCamera)
        currentCamera->setView(position, orientation);

    redraw();
}

void BaseViewer::moveView(const Vec3d& pos, const Quat &ori)
{
    if (!currentCamera)
        return;

    currentCamera->moveCamera(pos, ori);

    redraw();
}

void BaseViewer::newView()
{
    if (!currentCamera || !groot)
        return;

    currentCamera->setDefaultView(groot->getGravity());
}

void BaseViewer::resetView()
{
    redraw();
}

void BaseViewer::setBackgroundColour(float r, float g, float b)
{
    _background = 2;
    backgroundColour[0] = r;
    backgroundColour[1] = g;
    backgroundColour[2] = b;
}

void BaseViewer::setBackgroundImage(std::string imageFileName)
{
    _background = 0;

    if( sofa::helper::system::DataRepository.findFile(imageFileName) )
    {
        backgroundImageFile = sofa::helper::system::DataRepository.getFile(imageFileName);
        std::string extension = sofa::helper::system::SetDirectory::GetExtension(imageFileName.c_str());
        std::transform(extension.begin(),extension.end(),extension.begin(),::tolower );
        if(texLogo)
        {
            delete texLogo;
            texLogo = NULL;
        }
        helper::io::Image* image =  helper::io::Image::FactoryImage::getInstance()->createObject(extension,backgroundImageFile);
        if( !image )
        {
            helper::vector<std::string> validExtensions;
            helper::io::Image::FactoryImage::getInstance()->uniqueKeys(std::back_inserter(validExtensions));
            std::cerr << "Could not create: " << imageFileName << std::endl;
            std::cerr << "Valid extensions: " << validExtensions << std::endl;
        }
        else
        {
            texLogo = new helper::gl::Texture( image );
            texLogo->init();

        }

    }
}

std::string BaseViewer::getBackgroundImage()
{
    return backgroundImageFile;
}

PickHandler* BaseViewer::getPickHandler()
{
    return pick;
}

bool BaseViewer::unload(void)
{
    getPickHandler()->reset();
    getPickHandler()->unload();
    return true;
}

void BaseViewer::fitNodeBBox(sofa::core::objectmodel::BaseNode * node )
{
    if(!currentCamera) return;
    if( node->f_bbox.getValue().isValid() && !node->f_bbox.getValue().isFlat() )
        currentCamera->fitBoundingBox(
            node->f_bbox.getValue().minBBox(),
            node->f_bbox.getValue().maxBBox()
        );

    redraw();
}

void BaseViewer::fitObjectBBox(sofa::core::objectmodel::BaseObject * object)
{
    if(!currentCamera) return;

    if( object->f_bbox.getValue().isValid() && !object->f_bbox.getValue().isFlat() )
        currentCamera->fitBoundingBox(object->f_bbox.getValue().minBBox(),
                object->f_bbox.getValue().maxBBox());
    else
    {
        if(object->getContext()->f_bbox.getValue().isValid() && !object->getContext()->f_bbox.getValue().isFlat()  )
        {
            currentCamera->fitBoundingBox(
                object->getContext()->f_bbox.getValue().minBBox(),
                object->getContext()->f_bbox.getValue().maxBBox());
        }
    }
    redraw();
}

}
}

<commit_msg>r12787/sofa-dev : remove a warning about BaseViewer initialisation list.<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include "BaseViewer.h"
#include "PickHandler.h"

#include <sofa/helper/Factory.inl>
#include <sofa/component/visualmodel/VisualStyle.h>
#include <sofa/core/visual/DisplayFlags.h>

namespace sofa
{
namespace gui
{

BaseViewer::BaseViewer()
    : groot(NULL)
    , currentCamera(NULL)
    , _video(false)
    , _axis(false)
    , backgroundColour(Vector3())
    , texLogo(NULL)
    , backgroundImageFile("textures/SOFA_logo.bmp")
    , ambientColour(Vector3())
    , pick(NULL)
    , _stereoEnabled(false)
    , _stereoMode(STEREO_AUTO)
    , _stereoShift(1.0)
{
    pick = new PickHandler();
}

BaseViewer::~BaseViewer()
{
    if(texLogo)
    {
        delete texLogo;
        texLogo = NULL;
    }
}

sofa::simulation::Node* BaseViewer::getScene()
{
    return groot.get();
}
const std::string& BaseViewer::getSceneFileName()
{
    return sceneFileName;
}
void BaseViewer::setSceneFileName(const std::string &f)
{
    sceneFileName = f;
}

void BaseViewer::setScene(sofa::simulation::Node::SPtr scene, const char* filename /* = NULL */, bool /* = false */)
{
    std::string file =
        filename ? sofa::helper::system::SetDirectory::GetFileNameWithoutExtension(
                filename) : std::string();
    std::string screenshotPrefix =
        sofa::helper::system::SetDirectory::GetParentDir(
                sofa::helper::system::DataRepository.getFirstPath().c_str())
        + std::string("/share/screenshots/") + file
        + std::string("_");
    capture.setPrefix(screenshotPrefix);
#ifdef SOFA_HAVE_FFMPEG
    videoRecorder.setPrefix(screenshotPrefix);
#endif //SOFA_HAVE_FFMPEG
    sceneFileName = filename ? filename : std::string("default.scn");
    groot = scene;
    initTexturesDone = false;

    //Camera initialization
    if (groot)
    {
        groot->get(currentCamera);
        if (!currentCamera)
        {
            currentCamera = sofa::core::objectmodel::New<component::visualmodel::InteractiveCamera>();
            currentCamera->setName(core::objectmodel::Base::shortName(currentCamera.get()));
            groot->addObject(currentCamera);
            currentCamera->p_position.forceSet();
            currentCamera->p_orientation.forceSet();
            currentCamera->bwdInit();

        }
        component::visualmodel::VisualStyle::SPtr visualStyle = NULL;
        groot->get(visualStyle);
        if (!visualStyle)
        {
            visualStyle = sofa::core::objectmodel::New<component::visualmodel::VisualStyle>();
            visualStyle->setName(core::objectmodel::Base::shortName(visualStyle.get()));

            core::visual::DisplayFlags* displayFlags = visualStyle->displayFlags.beginEdit();
            displayFlags->setShowVisualModels(sofa::core::visual::tristate::true_value);
            visualStyle->displayFlags.endEdit();

            groot->addObject(visualStyle);
            visualStyle->init();
        }

        currentCamera->setBoundingBox(groot->f_bbox.getValue().minBBox(), groot->f_bbox.getValue().maxBBox());

        // init pickHandler
        pick->init(groot.get());
    }

}

void BaseViewer::setCameraMode(core::visual::VisualParams::CameraType mode)
{
    currentCamera->setCameraType(mode);
}

bool BaseViewer::ready()
{
    return true;
}

void BaseViewer::wait()
{
}

void BaseViewer::configure(sofa::component::configurationsetting::ViewerSetting* viewerConf)
{
    using namespace core::visual;
    if (viewerConf->cameraMode.getValue().getSelectedId() == VisualParams::ORTHOGRAPHIC_TYPE)
        setCameraMode(VisualParams::ORTHOGRAPHIC_TYPE);
    else
        setCameraMode(VisualParams::PERSPECTIVE_TYPE);
    if ( viewerConf->objectPickingMethod.getValue().getSelectedId() == gui::PickHandler::RAY_CASTING)
        pick->setPickingMethod( gui::PickHandler::RAY_CASTING );
    else
        pick->setPickingMethod( gui::PickHandler::SELECTION_BUFFER);
}

//Fonctions needed to take a screenshot
const std::string BaseViewer::screenshotName()
{
    return capture.findFilename().c_str();
}

void BaseViewer::setPrefix(const std::string filename)
{
    capture.setPrefix(filename);
}

void BaseViewer::screenshot(const std::string filename, int compression_level)
{
    capture.saveScreen(filename, compression_level);
}

void BaseViewer::getView(Vec3d& pos, Quat& ori) const
{
    if (!currentCamera)
        return;

    const Vec3d& camPosition = currentCamera->getPosition();
    const Quat& camOrientation = currentCamera->getOrientation();

    pos[0] = camPosition[0];
    pos[1] = camPosition[1];
    pos[2] = camPosition[2];

    ori[0] = camOrientation[0];
    ori[1] = camOrientation[1];
    ori[2] = camOrientation[2];
    ori[3] = camOrientation[3];
}

void BaseViewer::setView(const Vec3d& pos, const Quat &ori)
{
    Vec3d position;
    Quat orientation;
    for (unsigned int i=0 ; i<3 ; i++)
    {
        position[i] = pos[i];
        orientation[i] = ori[i];
    }
    orientation[3] = ori[3];

    if (currentCamera)
        currentCamera->setView(position, orientation);

    redraw();
}

void BaseViewer::moveView(const Vec3d& pos, const Quat &ori)
{
    if (!currentCamera)
        return;

    currentCamera->moveCamera(pos, ori);

    redraw();
}

void BaseViewer::newView()
{
    if (!currentCamera || !groot)
        return;

    currentCamera->setDefaultView(groot->getGravity());
}

void BaseViewer::resetView()
{
    redraw();
}

void BaseViewer::setBackgroundColour(float r, float g, float b)
{
    _background = 2;
    backgroundColour[0] = r;
    backgroundColour[1] = g;
    backgroundColour[2] = b;
}

void BaseViewer::setBackgroundImage(std::string imageFileName)
{
    _background = 0;

    if( sofa::helper::system::DataRepository.findFile(imageFileName) )
    {
        backgroundImageFile = sofa::helper::system::DataRepository.getFile(imageFileName);
        std::string extension = sofa::helper::system::SetDirectory::GetExtension(imageFileName.c_str());
        std::transform(extension.begin(),extension.end(),extension.begin(),::tolower );
        if(texLogo)
        {
            delete texLogo;
            texLogo = NULL;
        }
        helper::io::Image* image =  helper::io::Image::FactoryImage::getInstance()->createObject(extension,backgroundImageFile);
        if( !image )
        {
            helper::vector<std::string> validExtensions;
            helper::io::Image::FactoryImage::getInstance()->uniqueKeys(std::back_inserter(validExtensions));
            std::cerr << "Could not create: " << imageFileName << std::endl;
            std::cerr << "Valid extensions: " << validExtensions << std::endl;
        }
        else
        {
            texLogo = new helper::gl::Texture( image );
            texLogo->init();

        }

    }
}

std::string BaseViewer::getBackgroundImage()
{
    return backgroundImageFile;
}

PickHandler* BaseViewer::getPickHandler()
{
    return pick;
}

bool BaseViewer::unload(void)
{
    getPickHandler()->reset();
    getPickHandler()->unload();
    return true;
}

void BaseViewer::fitNodeBBox(sofa::core::objectmodel::BaseNode * node )
{
    if(!currentCamera) return;
    if( node->f_bbox.getValue().isValid() && !node->f_bbox.getValue().isFlat() )
        currentCamera->fitBoundingBox(
            node->f_bbox.getValue().minBBox(),
            node->f_bbox.getValue().maxBBox()
        );

    redraw();
}

void BaseViewer::fitObjectBBox(sofa::core::objectmodel::BaseObject * object)
{
    if(!currentCamera) return;

    if( object->f_bbox.getValue().isValid() && !object->f_bbox.getValue().isFlat() )
        currentCamera->fitBoundingBox(object->f_bbox.getValue().minBBox(),
                object->f_bbox.getValue().maxBBox());
    else
    {
        if(object->getContext()->f_bbox.getValue().isValid() && !object->getContext()->f_bbox.getValue().isFlat()  )
        {
            currentCamera->fitBoundingBox(
                object->getContext()->f_bbox.getValue().minBBox(),
                object->getContext()->f_bbox.getValue().maxBBox());
        }
    }
    redraw();
}

}
}

<|endoftext|>


<commit_before>/*
 * Implementation of color.h.
 */

#include "color.h"

Color::Color(int id, string name, string pathToFMIndex) {
    this->id = id;
    /// @todo initialize the FMIndex
}

Color::~Color() {
    /// @todo destruct the FMIndex
}

bool Color::isVertex(string& s) const {
    return DBGQuery::isVertex(fmIndex, s);
}

bool Color::isPrefixNeighbor(string& s, char b) const {
    return DBGQuery::isPrefixNeighbor(fmIndex, s, b);
}

bool Color::isSuffixNeighbor(string& s, char b) const {
    return DBGQuery::isSuffixNeighbor(fmIndex, s, b);
}

vector<string> Color::getSuffixNeighbors(string& s) const {
    vector<string> neighbors;
    string neighborBases = DBGQuery::getSuffixNeighbors(fmIndex, s);
    string suffix = s.substr(1, s.length() - 1);

    for(unsigned int i = 0; i < neighborBases.length(); i++) {
        string neighbor = suffix + neighborBases[i];
        neighbors.push_back(neighbor);
    }

    return neighbors;
}

vector<string> Color::getPrefixNeighbors(string& s) const {
    vector<string> neighbors;
    string neighborBases = DBGQuery::getPrefixNeighbors(fmIndex, s);
    string prefix = s.substr(0, s.length() - 1);

    for(unsigned int i = 0; i < neighborBases.length(); i++) {
        string neighbor = neighborBases[i] + prefix;
        neighbors.push_back(neighbor);
    }

    return neighbors;
}

pair<string, size_t> Color::extractSubstringAndIndex(size_t idx, size_t len) const {
    return DBGQuery::extractSubstringAndIndex(fmIndex, idx, len);
}

string Color::extractSubstring(size_t idx, size_t len) const {
    return DBGQuery::extractSubstring(fmIndex, idx, len);
}

string Color::getName() const {
    return name;
}

int Color::getID() const {
    return id;
}

FMIndex* Color::getFMIndex() const {
    return fmIndex;
}
<commit_msg>Implemented loading the FMIndex into color and setting the name.<commit_after>/*
 * Implementation of color.h.
 */

#include "color.h"

Color::Color(int id, string name, string pathToFMIndex) {
    this->id = id;
    this->name = name;
    fmIndex = new FMIndex(pathToFMIndex, 256);
}

Color::~Color() {
    delete fmIndex;
}

bool Color::isVertex(string& s) const {
    return DBGQuery::isVertex(fmIndex, s);
}

bool Color::isPrefixNeighbor(string& s, char b) const {
    return DBGQuery::isPrefixNeighbor(fmIndex, s, b);
}

bool Color::isSuffixNeighbor(string& s, char b) const {
    return DBGQuery::isSuffixNeighbor(fmIndex, s, b);
}

vector<string> Color::getSuffixNeighbors(string& s) const {
    vector<string> neighbors;
    string neighborBases = DBGQuery::getSuffixNeighbors(fmIndex, s);
    string suffix = s.substr(1, s.length() - 1);

    for(unsigned int i = 0; i < neighborBases.length(); i++) {
        string neighbor = suffix + neighborBases[i];
        neighbors.push_back(neighbor);
    }

    return neighbors;
}

vector<string> Color::getPrefixNeighbors(string& s) const {
    vector<string> neighbors;
    string neighborBases = DBGQuery::getPrefixNeighbors(fmIndex, s);
    string prefix = s.substr(0, s.length() - 1);

    for(unsigned int i = 0; i < neighborBases.length(); i++) {
        string neighbor = neighborBases[i] + prefix;
        neighbors.push_back(neighbor);
    }

    return neighbors;
}

pair<string, size_t> Color::extractSubstringAndIndex(size_t idx, size_t len) const {
    return DBGQuery::extractSubstringAndIndex(fmIndex, idx, len);
}

string Color::extractSubstring(size_t idx, size_t len) const {
    return DBGQuery::extractSubstring(fmIndex, idx, len);
}

string Color::getName() const {
    return name;
}

int Color::getID() const {
    return id;
}

FMIndex* Color::getFMIndex() const {
    return fmIndex;
}
<|endoftext|>


<commit_before>// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// ---
// Author: Sanjay Ghemawat <opensource@google.com>

#include <stdlib.h> // for getenv and strtol
#include "config.h"
#include "common.h"
#include "system-alloc.h"
#include "base/spinlock.h"

namespace tcmalloc {

// Define the maximum number of object per classe type to transfer between
// thread and central caches.
static int32 FLAGS_tcmalloc_transfer_num_objects;

static const int32 kDefaultTransferNumObjecs = 32768;

// The init function is provided to explicit initialize the variable value
// from the env. var to avoid C++ global construction that might defer its
// initialization after a malloc/new call.
static inline void InitTCMallocTransferNumObjects()
{
  if (UNLIKELY(FLAGS_tcmalloc_transfer_num_objects == 0)) {
    const char *envval = getenv("TCMALLOC_TRANSFER_NUM_OBJ");
    FLAGS_tcmalloc_transfer_num_objects = !envval ? kDefaultTransferNumObjecs :
      strtol(envval, NULL, 10);
  }
}

// Note: the following only works for "n"s that fit in 32-bits, but
// that is fine since we only use it for small sizes.
static inline int LgFloor(size_t n) {
  int log = 0;
  for (int i = 4; i >= 0; --i) {
    int shift = (1 << i);
    size_t x = n >> shift;
    if (x != 0) {
      n = x;
      log += shift;
    }
  }
  ASSERT(n == 1);
  return log;
}

int AlignmentForSize(size_t size) {
  int alignment = kAlignment;
  if (size > kMaxSize) {
    // Cap alignment at kPageSize for large sizes.
    alignment = kPageSize;
  } else if (size >= 128) {
    // Space wasted due to alignment is at most 1/8, i.e., 12.5%.
    alignment = (1 << LgFloor(size)) / 8;
  } else if (size >= kMinAlign) {
    // We need an alignment of at least 16 bytes to satisfy
    // requirements for some SSE types.
    alignment = kMinAlign;
  }
  // Maximum alignment allowed is page size alignment.
  if (alignment > kPageSize) {
    alignment = kPageSize;
  }
  CHECK_CONDITION(size < kMinAlign || alignment >= kMinAlign);
  CHECK_CONDITION((alignment & (alignment - 1)) == 0);
  return alignment;
}

int SizeMap::NumMoveSize(size_t size) {
  if (size == 0) return 0;
  // Use approx 64k transfers between thread and central caches.
  int num = static_cast<int>(64.0 * 1024.0 / size);
  if (num < 2) num = 2;

  // Avoid bringing too many objects into small object free lists.
  // If this value is too large:
  // - We waste memory with extra objects sitting in the thread caches.
  // - The central freelist holds its lock for too long while
  //   building a linked list of objects, slowing down the allocations
  //   of other threads.
  // If this value is too small:
  // - We go to the central freelist too often and we have to acquire
  //   its lock each time.
  // This value strikes a balance between the constraints above.
  if (num > FLAGS_tcmalloc_transfer_num_objects)
    num = FLAGS_tcmalloc_transfer_num_objects;

  return num;
}

// Initialize the mapping arrays
void SizeMap::Init() {
  InitTCMallocTransferNumObjects();

  // Do some sanity checking on add_amount[]/shift_amount[]/class_array[]
  if (ClassIndex(0) < 0) {
    Log(kCrash, __FILE__, __LINE__,
        "Invalid class index for size 0", ClassIndex(0));
  }
  if (ClassIndex(kMaxSize) >= sizeof(class_array_)) {
    Log(kCrash, __FILE__, __LINE__,
        "Invalid class index for kMaxSize", ClassIndex(kMaxSize));
  }

  // Compute the size classes we want to use
  int sc = 1;   // Next size class to assign
  int alignment = kAlignment;
  CHECK_CONDITION(kAlignment <= kMinAlign);
  for (size_t size = kAlignment; size <= kMaxSize; size += alignment) {
    alignment = AlignmentForSize(size);
    CHECK_CONDITION((size % alignment) == 0);

    int blocks_to_move = NumMoveSize(size) / 4;
    size_t psize = 0;
    do {
      psize += kPageSize;
      // Allocate enough pages so leftover is less than 1/8 of total.
      // This bounds wasted space to at most 12.5%.
      while ((psize % size) > (psize >> 3)) {
        psize += kPageSize;
      }
      // Continue to add pages until there are at least as many objects in
      // the span as are needed when moving objects from the central
      // freelists and spans to the thread caches.
    } while ((psize / size) < (blocks_to_move));
    const size_t my_pages = psize >> kPageShift;

    if (sc > 1 && my_pages == class_to_pages_[sc-1]) {
      // See if we can merge this into the previous class without
      // increasing the fragmentation of the previous class.
      const size_t my_objects = (my_pages << kPageShift) / size;
      const size_t prev_objects = (class_to_pages_[sc-1] << kPageShift)
                                  / class_to_size_[sc-1];
      if (my_objects == prev_objects) {
        // Adjust last class to include this size
        class_to_size_[sc-1] = size;
        continue;
      }
    }

    // Add new class
    class_to_pages_[sc] = my_pages;
    class_to_size_[sc] = size;
    sc++;
  }
  if (sc != kNumClasses) {
    Log(kCrash, __FILE__, __LINE__,
        "wrong number of size classes: (found vs. expected )", sc, kNumClasses);
  }

  // Initialize the mapping arrays
  int next_size = 0;
  for (int c = 1; c < kNumClasses; c++) {
    const int max_size_in_class = class_to_size_[c];
    for (int s = next_size; s <= max_size_in_class; s += kAlignment) {
      class_array_[ClassIndex(s)] = c;
    }
    next_size = max_size_in_class + kAlignment;
  }

  // Double-check sizes just to be safe
  for (size_t size = 0; size <= kMaxSize; size++) {
    const int sc = SizeClass(size);
    if (sc <= 0 || sc >= kNumClasses) {
      Log(kCrash, __FILE__, __LINE__,
          "Bad size class (class, size)", sc, size);
    }
    if (sc > 1 && size <= class_to_size_[sc-1]) {
      Log(kCrash, __FILE__, __LINE__,
          "Allocating unnecessarily large class (class, size)", sc, size);
    }
    const size_t s = class_to_size_[sc];
    if (size > s || s == 0) {
      Log(kCrash, __FILE__, __LINE__,
          "Bad (class, size, requested)", sc, s, size);
    }
  }

  // Initialize the num_objects_to_move array.
  for (size_t cl = 1; cl  < kNumClasses; ++cl) {
    num_objects_to_move_[cl] = NumMoveSize(ByteSizeForClass(cl));
  }
}

// Metadata allocator -- keeps stats about how many bytes allocated.
static uint64_t metadata_system_bytes_ = 0;
static const size_t kMetadataAllocChunkSize = 8*1024*1024;
static const size_t kMetadataBigAllocThreshold = kMetadataAllocChunkSize / 8;
// usually malloc uses larger alignments, but because metadata cannot
// have and fancy simd types, aligning on pointer size seems fine
static const size_t kMetadataAllignment = sizeof(void *);

static char *metadata_chunk_alloc_;
static size_t metadata_chunk_avail_;

static SpinLock metadata_alloc_lock(SpinLock::LINKER_INITIALIZED);

void* MetaDataAlloc(size_t bytes) {
  if (bytes >= kMetadataAllocChunkSize) {
    void *rv = TCMalloc_SystemAlloc(bytes,
                                    NULL, kMetadataAllignment);
    if (rv != NULL) {
      metadata_system_bytes_ += bytes;
    }
    return rv;
  }

  SpinLockHolder h(&metadata_alloc_lock);

  // the following works by essentially turning address to integer of
  // log_2 kMetadataAllignment size and negating it. I.e. negated
  // value + original value gets 0 and that's what we want modulo
  // kMetadataAllignment. Note, we negate before masking higher bits
  // off, otherwise we'd have to mask them off after negation anyways.
  intptr_t alignment = -reinterpret_cast<intptr_t>(metadata_chunk_alloc_) & (kMetadataAllignment-1);

  if (metadata_chunk_avail_ < bytes + alignment) {
    size_t real_size;
    void *ptr = TCMalloc_SystemAlloc(kMetadataAllocChunkSize,
                                     &real_size, kMetadataAllignment);
    if (ptr == NULL) {
      return NULL;
    }

    metadata_chunk_alloc_ = static_cast<char *>(ptr);
    metadata_chunk_avail_ = real_size;

    alignment = 0;
  }

  void *rv = static_cast<void *>(metadata_chunk_alloc_ + alignment);
  bytes += alignment;
  metadata_chunk_alloc_ += bytes;
  metadata_chunk_avail_ -= bytes;
  metadata_system_bytes_ += bytes;
  return rv;
}

uint64_t metadata_system_bytes() { return metadata_system_bytes_; }

}  // namespace tcmalloc
<commit_msg>skip unnecessary check during double-check SizeClass intergrity<commit_after>// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// ---
// Author: Sanjay Ghemawat <opensource@google.com>

#include <stdlib.h> // for getenv and strtol
#include "config.h"
#include "common.h"
#include "system-alloc.h"
#include "base/spinlock.h"

namespace tcmalloc {

// Define the maximum number of object per classe type to transfer between
// thread and central caches.
static int32 FLAGS_tcmalloc_transfer_num_objects;

static const int32 kDefaultTransferNumObjecs = 32768;

// The init function is provided to explicit initialize the variable value
// from the env. var to avoid C++ global construction that might defer its
// initialization after a malloc/new call.
static inline void InitTCMallocTransferNumObjects()
{
  if (UNLIKELY(FLAGS_tcmalloc_transfer_num_objects == 0)) {
    const char *envval = getenv("TCMALLOC_TRANSFER_NUM_OBJ");
    FLAGS_tcmalloc_transfer_num_objects = !envval ? kDefaultTransferNumObjecs :
      strtol(envval, NULL, 10);
  }
}

// Note: the following only works for "n"s that fit in 32-bits, but
// that is fine since we only use it for small sizes.
static inline int LgFloor(size_t n) {
  int log = 0;
  for (int i = 4; i >= 0; --i) {
    int shift = (1 << i);
    size_t x = n >> shift;
    if (x != 0) {
      n = x;
      log += shift;
    }
  }
  ASSERT(n == 1);
  return log;
}

int AlignmentForSize(size_t size) {
  int alignment = kAlignment;
  if (size > kMaxSize) {
    // Cap alignment at kPageSize for large sizes.
    alignment = kPageSize;
  } else if (size >= 128) {
    // Space wasted due to alignment is at most 1/8, i.e., 12.5%.
    alignment = (1 << LgFloor(size)) / 8;
  } else if (size >= kMinAlign) {
    // We need an alignment of at least 16 bytes to satisfy
    // requirements for some SSE types.
    alignment = kMinAlign;
  }
  // Maximum alignment allowed is page size alignment.
  if (alignment > kPageSize) {
    alignment = kPageSize;
  }
  CHECK_CONDITION(size < kMinAlign || alignment >= kMinAlign);
  CHECK_CONDITION((alignment & (alignment - 1)) == 0);
  return alignment;
}

int SizeMap::NumMoveSize(size_t size) {
  if (size == 0) return 0;
  // Use approx 64k transfers between thread and central caches.
  int num = static_cast<int>(64.0 * 1024.0 / size);
  if (num < 2) num = 2;

  // Avoid bringing too many objects into small object free lists.
  // If this value is too large:
  // - We waste memory with extra objects sitting in the thread caches.
  // - The central freelist holds its lock for too long while
  //   building a linked list of objects, slowing down the allocations
  //   of other threads.
  // If this value is too small:
  // - We go to the central freelist too often and we have to acquire
  //   its lock each time.
  // This value strikes a balance between the constraints above.
  if (num > FLAGS_tcmalloc_transfer_num_objects)
    num = FLAGS_tcmalloc_transfer_num_objects;

  return num;
}

// Initialize the mapping arrays
void SizeMap::Init() {
  InitTCMallocTransferNumObjects();

  // Do some sanity checking on add_amount[]/shift_amount[]/class_array[]
  if (ClassIndex(0) < 0) {
    Log(kCrash, __FILE__, __LINE__,
        "Invalid class index for size 0", ClassIndex(0));
  }
  if (ClassIndex(kMaxSize) >= sizeof(class_array_)) {
    Log(kCrash, __FILE__, __LINE__,
        "Invalid class index for kMaxSize", ClassIndex(kMaxSize));
  }

  // Compute the size classes we want to use
  int sc = 1;   // Next size class to assign
  int alignment = kAlignment;
  CHECK_CONDITION(kAlignment <= kMinAlign);
  for (size_t size = kAlignment; size <= kMaxSize; size += alignment) {
    alignment = AlignmentForSize(size);
    CHECK_CONDITION((size % alignment) == 0);

    int blocks_to_move = NumMoveSize(size) / 4;
    size_t psize = 0;
    do {
      psize += kPageSize;
      // Allocate enough pages so leftover is less than 1/8 of total.
      // This bounds wasted space to at most 12.5%.
      while ((psize % size) > (psize >> 3)) {
        psize += kPageSize;
      }
      // Continue to add pages until there are at least as many objects in
      // the span as are needed when moving objects from the central
      // freelists and spans to the thread caches.
    } while ((psize / size) < (blocks_to_move));
    const size_t my_pages = psize >> kPageShift;

    if (sc > 1 && my_pages == class_to_pages_[sc-1]) {
      // See if we can merge this into the previous class without
      // increasing the fragmentation of the previous class.
      const size_t my_objects = (my_pages << kPageShift) / size;
      const size_t prev_objects = (class_to_pages_[sc-1] << kPageShift)
                                  / class_to_size_[sc-1];
      if (my_objects == prev_objects) {
        // Adjust last class to include this size
        class_to_size_[sc-1] = size;
        continue;
      }
    }

    // Add new class
    class_to_pages_[sc] = my_pages;
    class_to_size_[sc] = size;
    sc++;
  }
  if (sc != kNumClasses) {
    Log(kCrash, __FILE__, __LINE__,
        "wrong number of size classes: (found vs. expected )", sc, kNumClasses);
  }

  // Initialize the mapping arrays
  int next_size = 0;
  for (int c = 1; c < kNumClasses; c++) {
    const int max_size_in_class = class_to_size_[c];
    for (int s = next_size; s <= max_size_in_class; s += kAlignment) {
      class_array_[ClassIndex(s)] = c;
    }
    next_size = max_size_in_class + kAlignment;
  }

  // Double-check sizes just to be safe
  for (size_t size = 0; size <= kMaxSize;) {
    const int sc = SizeClass(size);
    if (sc <= 0 || sc >= kNumClasses) {
      Log(kCrash, __FILE__, __LINE__,
          "Bad size class (class, size)", sc, size);
    }
    if (sc > 1 && size <= class_to_size_[sc-1]) {
      Log(kCrash, __FILE__, __LINE__,
          "Allocating unnecessarily large class (class, size)", sc, size);
    }
    const size_t s = class_to_size_[sc];
    if (size > s || s == 0) {
      Log(kCrash, __FILE__, __LINE__,
          "Bad (class, size, requested)", sc, s, size);
    }
    if (size <= kMaxSmallSize) {
      size += 8;
    } else {
      size += 128;
    }
  }

  // Initialize the num_objects_to_move array.
  for (size_t cl = 1; cl  < kNumClasses; ++cl) {
    num_objects_to_move_[cl] = NumMoveSize(ByteSizeForClass(cl));
  }
}

// Metadata allocator -- keeps stats about how many bytes allocated.
static uint64_t metadata_system_bytes_ = 0;
static const size_t kMetadataAllocChunkSize = 8*1024*1024;
static const size_t kMetadataBigAllocThreshold = kMetadataAllocChunkSize / 8;
// usually malloc uses larger alignments, but because metadata cannot
// have and fancy simd types, aligning on pointer size seems fine
static const size_t kMetadataAllignment = sizeof(void *);

static char *metadata_chunk_alloc_;
static size_t metadata_chunk_avail_;

static SpinLock metadata_alloc_lock(SpinLock::LINKER_INITIALIZED);

void* MetaDataAlloc(size_t bytes) {
  if (bytes >= kMetadataAllocChunkSize) {
    void *rv = TCMalloc_SystemAlloc(bytes,
                                    NULL, kMetadataAllignment);
    if (rv != NULL) {
      metadata_system_bytes_ += bytes;
    }
    return rv;
  }

  SpinLockHolder h(&metadata_alloc_lock);

  // the following works by essentially turning address to integer of
  // log_2 kMetadataAllignment size and negating it. I.e. negated
  // value + original value gets 0 and that's what we want modulo
  // kMetadataAllignment. Note, we negate before masking higher bits
  // off, otherwise we'd have to mask them off after negation anyways.
  intptr_t alignment = -reinterpret_cast<intptr_t>(metadata_chunk_alloc_) & (kMetadataAllignment-1);

  if (metadata_chunk_avail_ < bytes + alignment) {
    size_t real_size;
    void *ptr = TCMalloc_SystemAlloc(kMetadataAllocChunkSize,
                                     &real_size, kMetadataAllignment);
    if (ptr == NULL) {
      return NULL;
    }

    metadata_chunk_alloc_ = static_cast<char *>(ptr);
    metadata_chunk_avail_ = real_size;

    alignment = 0;
  }

  void *rv = static_cast<void *>(metadata_chunk_alloc_ + alignment);
  bytes += alignment;
  metadata_chunk_alloc_ += bytes;
  metadata_chunk_avail_ -= bytes;
  metadata_system_bytes_ += bytes;
  return rv;
}

uint64_t metadata_system_bytes() { return metadata_system_bytes_; }

}  // namespace tcmalloc
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <algorithm>
#include <unistd.h>
#include <fnord-base/UTF8.h>
#include "common.h"

namespace cm {

/**
 * mandatory params:
 *  v    -- pixel ver.  -- value: 1
 *  c    -- clickid     -- format "<uid>~<eventid>", e.g. "f97650cb~b28c61d5c"
 *  e    -- eventtype   -- format "{q,v}" (query, visit)
 *
 * params for eventtype=q (query):
 *  is   -- item ids    -- format "<setid>~<itemid>~<pos>,..."
 *
 * params for eventtype=v (visit):
 *  i    -- itemid      -- format "<setid>~<itemid>"
 *
 */
bool isReservedPixelParam(const std::string p) {
  return p == "c" || p == "e" || p == "i" || p == "is" || p == "v";
}

std::string cmHostname() {
  char hostname[128];
  gethostname(hostname, sizeof(hostname));
  hostname[127] = 0;
  return std::string(hostname);
}

Option<String> extractAttr(const Vector<String>& attrs, const String& attr) {
  auto prefix = attr + ":";

  for (const auto& a : attrs) {
    if (StringUtil::beginsWith(a, prefix)) {
      return Some(a.substr(prefix.length()));
    }
  }

  return None<String>();
}

String joinBagOfWords(const Set<String>& words) {
  Vector<String> v;

  for (const auto& w : words) {
    if (w.length() == 0) {
      continue;
    }

    v.emplace_back(w);
  }

  std::sort(v.begin(), v.end());

  return StringUtil::join(v, " ");
}

bool isQueryEligible(
    ItemEligibility eligibility,
    const cm::JoinedQuery& query) {
  switch (eligibility) {

    case ItemEligibility::DAWANDA_ALL_NOBOTS: {
      auto pgs = extractAttr(query.attrs, "pg");
      if (pgs.isEmpty()) {
        return false;
      }

      auto pg = std::stoul(pgs.get());
      return pg <= 3;
    }

    case ItemEligibility::ALL:
      return true;

  }
}

bool isItemEligible(
    ItemEligibility eligibility,
    const cm::JoinedQuery& query,
    const cm::JoinedQueryItem& item) {
  switch (eligibility) {

    case ItemEligibility::DAWANDA_ALL_NOBOTS:
      return item.position <= 40 && item.position > 0;

    case ItemEligibility::ALL:
      return true;

  }
}

}
<commit_msg>make legacy pixel lines eligible<commit_after>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <algorithm>
#include <unistd.h>
#include <fnord-base/UTF8.h>
#include "common.h"

namespace cm {

/**
 * mandatory params:
 *  v    -- pixel ver.  -- value: 1
 *  c    -- clickid     -- format "<uid>~<eventid>", e.g. "f97650cb~b28c61d5c"
 *  e    -- eventtype   -- format "{q,v}" (query, visit)
 *
 * params for eventtype=q (query):
 *  is   -- item ids    -- format "<setid>~<itemid>~<pos>,..."
 *
 * params for eventtype=v (visit):
 *  i    -- itemid      -- format "<setid>~<itemid>"
 *
 */
bool isReservedPixelParam(const std::string p) {
  return p == "c" || p == "e" || p == "i" || p == "is" || p == "v";
}

std::string cmHostname() {
  char hostname[128];
  gethostname(hostname, sizeof(hostname));
  hostname[127] = 0;
  return std::string(hostname);
}

Option<String> extractAttr(const Vector<String>& attrs, const String& attr) {
  auto prefix = attr + ":";

  for (const auto& a : attrs) {
    if (StringUtil::beginsWith(a, prefix)) {
      return Some(a.substr(prefix.length()));
    }
  }

  return None<String>();
}

String joinBagOfWords(const Set<String>& words) {
  Vector<String> v;

  for (const auto& w : words) {
    if (w.length() == 0) {
      continue;
    }

    v.emplace_back(w);
  }

  std::sort(v.begin(), v.end());

  return StringUtil::join(v, " ");
}

bool isQueryEligible(
    ItemEligibility eligibility,
    const cm::JoinedQuery& query) {
  switch (eligibility) {

    case ItemEligibility::DAWANDA_ALL_NOBOTS: {
      auto pgs = extractAttr(query.attrs, "pg");
      if (pgs.isEmpty()) {
        return return;
      } else {
        auto pg = std::stoul(pgs.get());
        return pg <= 3;
      }
    }

    case ItemEligibility::ALL:
      return true;

  }
}

bool isItemEligible(
    ItemEligibility eligibility,
    const cm::JoinedQuery& query,
    const cm::JoinedQueryItem& item) {
  switch (eligibility) {

    case ItemEligibility::DAWANDA_ALL_NOBOTS:
      return item.position <= 40 && item.position > 0;

    case ItemEligibility::ALL:
      return true;

  }
}

}
<|endoftext|>


<commit_before>#include <allegro.h>
#ifdef ALLEGRO_WINDOWS
#include <winalleg.h>
#endif

#ifndef ALLEGRO_WINDOWS
#include <signal.h>
#include <string.h>
#endif

#warning you are ugly

#include "globals.h"
#include "init.h"
#include <pthread.h>
#include "network/network.h"

#include <ostream>
#include "dumb/include/dumb.h"
#include "dumb/include/aldumb.h"
#include "loadpng/loadpng.h"
#include "util/bitmap.h"
#include "configuration.h"
#include "script/script.h"

using namespace std;

volatile int Global::speed_counter = 0;
volatile int Global::second_counter = 0;

/* the original engine was running at 90 ticks per second, but we dont
 * need to render that fast, so TICS_PER_SECOND is really fps and
 * LOGIC_MULTIPLIER will be used to adjust the speed counter to its
 * original value.
 */
static const int TICS_PER_SECOND = 40;
const double Global::LOGIC_MULTIPLIER = (double) 90 / (double) TICS_PER_SECOND;
const char * Global::shutdown_message = "Shutting down..";

pthread_mutex_t Global::loading_screen_mutex;
bool Global::done_loading = false;

const int Global::WINDOWED = GFX_AUTODETECT_WINDOWED;
const int Global::FULLSCREEN = GFX_AUTODETECT_FULLSCREEN;

void inc_speed_counter() {
	Global::speed_counter += 1;
}
END_OF_FUNCTION( inc_speed_counter );

void inc_second_counter() {
	Global::second_counter += 1;
}
END_OF_FUNCTION( inc_second_counter );

#ifndef ALLEGRO_WINDOWS
static void handleSigSegV(int i, siginfo_t * sig, void * data){
    Global::shutdown_message = "Bug! Caught a memory violation. Shutting down..";
    Bitmap::setGfxModeText();
    allegro_exit();
    /* write to a log file or something because sigsegv shouldn't
     * normally happen.
     */
    exit(0);
}
#else
#endif

/* catch a socket being closed prematurely on unix */
#ifndef ALLEGRO_WINDOWS
static void handleSigPipe( int i, siginfo_t * sig, void * data ){
}

/*
static void handleSigUsr1( int i, siginfo_t * sig, void * data ){
	pthread_exit( NULL );
}
*/
#endif

static void registerSignals(){
#ifndef ALLEGRO_WINDOWS
	struct sigaction action;
	memset( &action, 0, sizeof(struct sigaction) );
	action.sa_sigaction = handleSigPipe;
	sigaction( SIGPIPE, &action, NULL );

	memset( &action, 0, sizeof(struct sigaction) );
	action.sa_sigaction = handleSigSegV;
	sigaction( SIGSEGV, &action, NULL );

	/*
	action.sa_sigaction = handleSigUsr1;
	sigaction( SIGUSR1, &action, NULL );
	*/
#endif
}

static void say_shutdown(){
    Global::debug(0) << Global::shutdown_message << endl;
}

static void close_paintown(){
    Bitmap::setGfxModeText();
    allegro_exit();
    exit(0);
}
END_OF_FUNCTION(close_paintown)

bool Global::init( int gfx ){

	ostream & out = Global::debug( 0 );
	out << "-- BEGIN init --" << endl;
        out << "Paintown version " << Global::getVersionString() << endl;
	out << "Allegro version: " << ALLEGRO_VERSION_STR << endl;
	out <<"Allegro init: "<<allegro_init()<<endl;
	out <<"Install timer: "<<install_timer()<<endl;

	set_volume_per_voice( 0 );
	out<<"Install sound: "<<install_sound( DIGI_AUTODETECT, MIDI_NONE, "" )<<endl;

        /* png */
	loadpng_init();

        Bitmap::SCALE_X = GFX_X;
        Bitmap::SCALE_Y = GFX_Y;

        Configuration::loadConfigurations();

        const int sx = Configuration::getScreenWidth();
        const int sy = Configuration::getScreenHeight();

	out<<"Install keyboard: "<<install_keyboard()<<endl;
	out<<"Install mouse: "<<install_mouse()<<endl;
        /* 16 bit color depth */
	set_color_depth( 16 );

        /* set up the screen */
	out<<"Set gfx mode: " << Bitmap::setGraphicsMode( gfx, sx, sy ) <<endl;

	LOCK_VARIABLE( speed_counter );
	LOCK_VARIABLE( second_counter );
	LOCK_FUNCTION( (void *)inc_speed_counter );
	LOCK_FUNCTION( (void *)inc_second_counter );
        /* set up the timers */
	out<<"Install game timer: "<<install_int_ex( inc_speed_counter, BPS_TO_TIMER( TICS_PER_SECOND ) )<<endl;
	out<<"Install second timer: "<<install_int_ex( inc_second_counter, BPS_TO_TIMER( 1 ) )<<endl;
	out << "Initialize random number generator" << endl;
        /* initialize random number generator */
	srand( time( NULL ) );

        /* keep running in the background */
	set_display_switch_mode(SWITCH_BACKGROUND);

        /* close window when the X is pressed */
        LOCK_FUNCTION(close_paintown);
        set_close_button_callback(close_paintown);

        /* music */
        atexit(say_shutdown);
	atexit( &dumb_exit );
	atexit( Network::closeAll );
	dumb_register_packfiles();

	registerSignals();

	out << "Initialize network" << endl;
	Network::init();

        /* this mutex is used to show the loading screen while the game loads */
	pthread_mutex_init( &Global::loading_screen_mutex, NULL );

	out<<"-- END init --"<<endl;

	return true;
}
<commit_msg>use write directly<commit_after>#include <allegro.h>
#ifdef ALLEGRO_WINDOWS
#include <winalleg.h>
#endif

#ifndef ALLEGRO_WINDOWS
#include <signal.h>
#include <string.h>
#endif

#warning you are ugly

#include "globals.h"
#include "init.h"
#include <pthread.h>
#include "network/network.h"

#include <ostream>
#include "dumb/include/dumb.h"
#include "dumb/include/aldumb.h"
#include "loadpng/loadpng.h"
#include "util/bitmap.h"
#include "configuration.h"
#include "script/script.h"

using namespace std;

volatile int Global::speed_counter = 0;
volatile int Global::second_counter = 0;

/* the original engine was running at 90 ticks per second, but we dont
 * need to render that fast, so TICS_PER_SECOND is really fps and
 * LOGIC_MULTIPLIER will be used to adjust the speed counter to its
 * original value.
 */
static const int TICS_PER_SECOND = 40;
const double Global::LOGIC_MULTIPLIER = (double) 90 / (double) TICS_PER_SECOND;
const char * Global::shutdown_message = "Shutting down..";

pthread_mutex_t Global::loading_screen_mutex;
bool Global::done_loading = false;

const int Global::WINDOWED = GFX_AUTODETECT_WINDOWED;
const int Global::FULLSCREEN = GFX_AUTODETECT_FULLSCREEN;

void inc_speed_counter() {
	Global::speed_counter += 1;
}
END_OF_FUNCTION( inc_speed_counter );

void inc_second_counter() {
	Global::second_counter += 1;
}
END_OF_FUNCTION( inc_second_counter );

#ifndef ALLEGRO_WINDOWS
static void handleSigSegV(int i, siginfo_t * sig, void * data){
    const char * message = "Bug! Caught a memory violation. Shutting down..\n";
    write(1, message, 48);
    // Global::shutdown_message = "Bug! Caught a memory violation. Shutting down..";
    Bitmap::setGfxModeText();
    allegro_exit();
    /* write to a log file or something because sigsegv shouldn't
     * normally happen.
     */
    exit(0);
}
#else
#endif

/* catch a socket being closed prematurely on unix */
#ifndef ALLEGRO_WINDOWS
static void handleSigPipe( int i, siginfo_t * sig, void * data ){
}

/*
static void handleSigUsr1( int i, siginfo_t * sig, void * data ){
	pthread_exit( NULL );
}
*/
#endif

static void registerSignals(){
#ifndef ALLEGRO_WINDOWS
	struct sigaction action;
	memset( &action, 0, sizeof(struct sigaction) );
	action.sa_sigaction = handleSigPipe;
	sigaction( SIGPIPE, &action, NULL );

	memset( &action, 0, sizeof(struct sigaction) );
	action.sa_sigaction = handleSigSegV;
	sigaction( SIGSEGV, &action, NULL );

	/*
	action.sa_sigaction = handleSigUsr1;
	sigaction( SIGUSR1, &action, NULL );
	*/
#endif
}

static void say_shutdown(){
    Global::debug(0) << Global::shutdown_message << endl;
}

static void close_paintown(){
    Bitmap::setGfxModeText();
    allegro_exit();
    exit(0);
}
END_OF_FUNCTION(close_paintown)

bool Global::init( int gfx ){

	ostream & out = Global::debug( 0 );
	out << "-- BEGIN init --" << endl;
        out << "Paintown version " << Global::getVersionString() << endl;
	out << "Allegro version: " << ALLEGRO_VERSION_STR << endl;
	out <<"Allegro init: "<<allegro_init()<<endl;
	out <<"Install timer: "<<install_timer()<<endl;

	set_volume_per_voice( 0 );
	out<<"Install sound: "<<install_sound( DIGI_AUTODETECT, MIDI_NONE, "" )<<endl;

        /* png */
	loadpng_init();

        Bitmap::SCALE_X = GFX_X;
        Bitmap::SCALE_Y = GFX_Y;

        Configuration::loadConfigurations();

        const int sx = Configuration::getScreenWidth();
        const int sy = Configuration::getScreenHeight();

	out<<"Install keyboard: "<<install_keyboard()<<endl;
	out<<"Install mouse: "<<install_mouse()<<endl;
        /* 16 bit color depth */
	set_color_depth( 16 );

        /* set up the screen */
	out<<"Set gfx mode: " << Bitmap::setGraphicsMode( gfx, sx, sy ) <<endl;

	LOCK_VARIABLE( speed_counter );
	LOCK_VARIABLE( second_counter );
	LOCK_FUNCTION( (void *)inc_speed_counter );
	LOCK_FUNCTION( (void *)inc_second_counter );
        /* set up the timers */
	out<<"Install game timer: "<<install_int_ex( inc_speed_counter, BPS_TO_TIMER( TICS_PER_SECOND ) )<<endl;
	out<<"Install second timer: "<<install_int_ex( inc_second_counter, BPS_TO_TIMER( 1 ) )<<endl;
	out << "Initialize random number generator" << endl;
        /* initialize random number generator */
	srand( time( NULL ) );

        /* keep running in the background */
	set_display_switch_mode(SWITCH_BACKGROUND);

        /* close window when the X is pressed */
        LOCK_FUNCTION(close_paintown);
        set_close_button_callback(close_paintown);

        /* music */
	atexit( &dumb_exit );
	atexit( Network::closeAll );
	dumb_register_packfiles();

	registerSignals();

	out << "Initialize network" << endl;
	Network::init();

        /* this mutex is used to show the loading screen while the game loads */
	pthread_mutex_init( &Global::loading_screen_mutex, NULL );

	out<<"-- END init --"<<endl;

	return true;
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

//_________________________________________________________________________
// Implementation version v1 of the EMCAL particle identifier

//*-- Author: Yves Schutz (SUBATECH)
//
// --- ROOT system ---
//#include "TROOT.h"
#include "TTree.h"
#include "TBenchmark.h"
#include "TSystem.h"

  // --- Standard library ---

  // --- AliRoot header files ---
#include "AliGenerator.h"
#include "AliEMCALPIDv1.h"
#include "AliEMCALRecParticle.h"
#include "AliEMCALGetter.h"

  ClassImp( AliEMCALPIDv1)

//____________________________________________________________________________
AliEMCALPIDv1::AliEMCALPIDv1():AliEMCALPID()
{
  // default ctor

  InitParameters() ;
  fDefaultInit = kTRUE ;

}

//____________________________________________________________________________
AliEMCALPIDv1::AliEMCALPIDv1(const AliEMCALPIDv1 & pid ):AliEMCALPID(pid)
{
  // ctor
  InitParameters() ;
  Init() ;

}

//____________________________________________________________________________
AliEMCALPIDv1::AliEMCALPIDv1(const TString alirunFileName, const TString eventFolderName):AliEMCALPID(alirunFileName, eventFolderName)
{
  //ctor with the indication on where to look for the track segments

  InitParameters() ;
  Init() ;
  fDefaultInit = kFALSE ;

}

//____________________________________________________________________________
AliEMCALPIDv1::~AliEMCALPIDv1()
{
  // dtor
}

//____________________________________________________________________________
const TString AliEMCALPIDv1::BranchName() const
{

  return GetName() ;
}

//____________________________________________________________________________
Float_t  AliEMCALPIDv1::GetCalibratedEnergy(Float_t e) const
{
//      It calibrates Energy depending on the recpoint energy.
//      The energy of the reconstructed cluster is corrected with
//      the formula A + B* E  + C* E^2, whose parameters where obtained
//      through the study of the reconstructed energy distribution of
//      monoenergetic photons.

  //Float_t p[]={0.,0.,0.};
  //for (Int_t i=0; i<3; i++) p[i] = GetParameterCalibration(i);
  Float_t enerec = e ; // p[0] +  p[1]*e + p[2]*e*e;
  return enerec ;

}
//____________________________________________________________________________
TVector3 AliEMCALPIDv1::GetMomentumDirection(AliEMCALRecPoint * emc)const
{
  // Calculates the momentum direction:
  // direction is given by IP and this RecPoint

  TVector3 dir(0,0,0) ;
  TVector3 emcglobalpos ;
  // TMatrix  dummy ;

  emc->GetGlobalPosition(emcglobalpos) ;

  dir = emcglobalpos ;
  dir.SetZ( -dir.Z() ) ;   // why ?
  // dir.SetMag(1.) ; Removed to avoid warings !!!!!!!!!!!!!! TO BE REVISED

  //account correction to the position of IP
  Float_t xo,yo,zo ; //Coordinates of the origin
  gAlice->Generator()->GetOrigin(xo,yo,zo) ;
  TVector3 origin(xo,yo,zo);
  dir = dir - origin ;

  return dir ;
}

//____________________________________________________________________________
void AliEMCALPIDv1::Init()
{
  // Make all memory allocations that are not possible in default constructor
  // Add the PID task to the list of EMCAL tasks

  AliEMCALGetter * gime = AliEMCALGetter::Instance(GetTitle(), fEventFolderName.Data()) ;

  if ( !gime->PID() )
    gime->PostPID(this) ;
}

//____________________________________________________________________________
void AliEMCALPIDv1::InitParameters()
{
  // Initialize the parameters
  fRecParticlesInRun = 0 ;
  fNEvent            = 0 ;
  fRecParticlesInRun = 0 ;
}

//____________________________________________________________________________

void  AliEMCALPIDv1::Exec(Option_t * option)
{
  //Steering method

  if(strstr(option,"tim"))
    gBenchmark->Start("EMCALPID");

  if(strstr(option,"print")) {
    Print("") ;
    return ;
  }
  AliEMCALGetter * gime = AliEMCALGetter::Instance(GetTitle()) ;

  if (fLastEvent == -1)
    fLastEvent = gime->MaxEvent() - 1 ;
  else
    fLastEvent = TMath::Min(fLastEvent,gime->MaxEvent());
  Int_t nEvents   = fLastEvent - fFirstEvent + 1;

  Int_t ievent ;

  for (ievent = fFirstEvent; ievent <= fLastEvent; ievent++) {
    gime->Event(ievent,"R") ;
    MakeRecParticles() ;
    WriteRecParticles();
    if(strstr(option,"deb"))
      PrintRecParticles(option) ;
    //increment the total number of rec particles per run
    fRecParticlesInRun += gime->RecParticles()->GetEntriesFast() ;

  }
  if(strstr(option,"tim")){
    gBenchmark->Stop("EMCALPID");
    printf("Exec: took %f seconds for PID %f seconds per event",
	 gBenchmark->GetCpuTime("EMCALPID"),
	 gBenchmark->GetCpuTime("EMCALPID")/nEvents) ;
  }

  Unload();
}

//____________________________________________________________________________
void  AliEMCALPIDv1::MakeRecParticles(){

  // Makes a RecParticle out of a TrackSegment

  AliEMCALGetter * gime = AliEMCALGetter::Instance() ;
  TObjArray * aECARecPoints = gime->ECARecPoints() ;
  if ( !aECARecPoints ) {
    Fatal("MakeRecParticles", "RecPoints or TrackSegments not found !") ;
  }
  TClonesArray * recParticles  = gime->RecParticles() ;
  recParticles->Clear();

  TIter next(aECARecPoints) ;
  AliEMCALRecPoint * eca ;
  Int_t index = 0 ;
  AliEMCALRecParticle * rp ;
  while ( (eca = (AliEMCALRecPoint *)next()) ) {

    new( (*recParticles)[index] ) AliEMCALRecParticle() ;
    rp = (AliEMCALRecParticle *)recParticles->At(index) ;
    rp->SetRecPoint(index) ;
    rp->SetIndexInList(index) ;

    // Now set type (reconstructed) of the particle

    // Choose the cluster energy range

    Float_t  lambda[2] ;
    eca->GetElipsAxis(lambda) ;

    if((lambda[0]>0.01) && (lambda[1]>0.01)){
      // Looking PCA. Define and calculate the data (X),
      // introduce in the function X2P that gives the components (P).

      Float_t  spher = 0. ;
      Float_t  emaxdtotal = 0. ;

      if((lambda[0]+lambda[1])!=0)
	spher=fabs(lambda[0]-lambda[1])/(lambda[0]+lambda[1]);

      emaxdtotal=eca->GetMaximalEnergy()/eca->GetEnergy();
    }

    //    Float_t time = eca->GetTime() ;

    //Set momentum, energy and other parameters
    Float_t  encal = GetCalibratedEnergy(eca->GetEnergy());
    TVector3 dir   = GetMomentumDirection(eca) ;
    // dir.SetMag(encal) ;Removed to avoid warings !!!!!!!!!!!!!! TO BE REVISED
    rp->SetMomentum(dir.X(),dir.Y(),dir.Z(),encal) ;
    rp->SetCalcMass(0);
    rp->Name(); //If photon sets the particle pdg name to gamma
    rp->SetProductionVertex(0,0,0,0);
    rp->SetFirstMother(-1);
    rp->SetLastMother(-1);
    rp->SetFirstDaughter(-1);
    rp->SetLastDaughter(-1);
    rp->SetPolarisation(0,0,0);
    //Set the position in global coordinate system from the RecPoint
    //AliEMCALGeometry * geom = gime->EMCALGeometry() ;
    //AliEMCALTowerRecPoint  * erp = gime->ECARecPoint(rp->GetEMCALRPIndex()) ;
    TVector3 pos ;
    //geom->GetGlobal(erp, pos) ; !!!!!!!!!! to check
    rp->SetPos(pos);

    index++ ;
  }

}

//____________________________________________________________________________
void  AliEMCALPIDv1:: Print(Option_t * /*option*/) const
{
  // Print the parameters used for the particle type identification

    printf("Print: =============== AliEMCALPID1 ================") ;
    printf("Making PID\n");
    printf("    Pricipal analysis file from 0.5 to 100 %s\n", fFileName.Data() ) ;
    printf("    Name of parameters file     %s\n", fFileNamePar.Data() )  ;
}

//____________________________________________________________________________
void  AliEMCALPIDv1::Print() const
{
  // Print the parameters used for the particle type identification

    Info("Print", "=============== AliEMCALPIDv1 ================") ;
}

//____________________________________________________________________________
void AliEMCALPIDv1::PrintRecParticles(Option_t * option)
{
  // Print table of reconstructed particles

  AliEMCALGetter *gime = AliEMCALGetter::Instance() ;

  TClonesArray * recParticles = gime->RecParticles() ;

  printf("\nevent %i", gAlice->GetEvNumber());
  printf("       found %i", recParticles->GetEntriesFast());
  printf(" RecParticles\n");

  if(strstr(option,"all")) {  // printing found TS
    printf("\n  PARTICLE         Index    \n");

    Int_t index ;
    for (index = 0 ; index < recParticles->GetEntries() ; index++) {
      AliEMCALRecParticle * rp = (AliEMCALRecParticle * ) recParticles->At(index) ;
      printf("\n");
      printf(rp->Name().Data());
      printf(" %i", rp->GetIndexInList());
      printf(" %i", rp->GetType());
    }
  }
}

//____________________________________________________________________________
void AliEMCALPIDv1::Unload()
{
  // Unloads RecPoints, TrackSegments and RecParticles from the folder
  AliEMCALGetter * gime = AliEMCALGetter::Instance() ;
  gime->EmcalLoader()->UnloadRecPoints() ;
  gime->EmcalLoader()->UnloadTracks() ;
  gime->EmcalLoader()->UnloadRecParticles() ;
}

//____________________________________________________________________________
void  AliEMCALPIDv1::WriteRecParticles()
{
  // Write RecParticles array to file
  AliEMCALGetter *gime = AliEMCALGetter::Instance() ;

  TClonesArray * recParticles = gime->RecParticles() ;
  recParticles->Expand(recParticles->GetEntriesFast() ) ;
  TTree * treeP =  gime->TreeP() ;

  //First rp
  Int_t bufferSize = 32000 ;
  TBranch * rpBranch = treeP->Branch("EMCALRP",&recParticles,bufferSize);
  rpBranch->SetTitle(BranchName());

  rpBranch->Fill() ;

  gime->WriteRecParticles("OVERWRITE");
  gime->WritePID("OVERWRITE");

}

<commit_msg>The direction of z was reversed in GetMomentumDirection ... nobody remembers why.<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

//_________________________________________________________________________
// Implementation version v1 of the EMCAL particle identifier

//*-- Author: Yves Schutz (SUBATECH)
//
// --- ROOT system ---
//#include "TROOT.h"
#include "TTree.h"
#include "TBenchmark.h"
#include "TSystem.h"

  // --- Standard library ---

  // --- AliRoot header files ---
#include "AliGenerator.h"
#include "AliEMCALPIDv1.h"
#include "AliEMCALRecParticle.h"
#include "AliEMCALGetter.h"

  ClassImp( AliEMCALPIDv1)

//____________________________________________________________________________
AliEMCALPIDv1::AliEMCALPIDv1():AliEMCALPID()
{
  // default ctor

  InitParameters() ;
  fDefaultInit = kTRUE ;

}

//____________________________________________________________________________
AliEMCALPIDv1::AliEMCALPIDv1(const AliEMCALPIDv1 & pid ):AliEMCALPID(pid)
{
  // ctor
  InitParameters() ;
  Init() ;

}

//____________________________________________________________________________
AliEMCALPIDv1::AliEMCALPIDv1(const TString alirunFileName, const TString eventFolderName):AliEMCALPID(alirunFileName, eventFolderName)
{
  //ctor with the indication on where to look for the track segments

  InitParameters() ;
  Init() ;
  fDefaultInit = kFALSE ;

}

//____________________________________________________________________________
AliEMCALPIDv1::~AliEMCALPIDv1()
{
  // dtor
}

//____________________________________________________________________________
const TString AliEMCALPIDv1::BranchName() const
{

  return GetName() ;
}

//____________________________________________________________________________
Float_t  AliEMCALPIDv1::GetCalibratedEnergy(Float_t e) const
{
//      It calibrates Energy depending on the recpoint energy.
//      The energy of the reconstructed cluster is corrected with
//      the formula A + B* E  + C* E^2, whose parameters where obtained
//      through the study of the reconstructed energy distribution of
//      monoenergetic photons.

  //Float_t p[]={0.,0.,0.};
  //for (Int_t i=0; i<3; i++) p[i] = GetParameterCalibration(i);
  Float_t enerec = e ; // p[0] +  p[1]*e + p[2]*e*e;
  return enerec ;

}
//____________________________________________________________________________
TVector3 AliEMCALPIDv1::GetMomentumDirection(AliEMCALRecPoint * emc)const
{
  // Calculates the momentum direction:
  // direction is given by IP and this RecPoint

  TVector3 dir(0,0,0) ;
  TVector3 emcglobalpos ;
  // TMatrix  dummy ;

  emc->GetGlobalPosition(emcglobalpos) ;

  dir = emcglobalpos ;
  // dir.SetMag(1.) ; Removed to avoid warings !!!!!!!!!!!!!! TO BE REVISED

  //account correction to the position of IP
  Float_t xo,yo,zo ; //Coordinates of the origin
  gAlice->Generator()->GetOrigin(xo,yo,zo) ;
  TVector3 origin(xo,yo,zo);
  dir = dir - origin ;

  return dir ;
}

//____________________________________________________________________________
void AliEMCALPIDv1::Init()
{
  // Make all memory allocations that are not possible in default constructor
  // Add the PID task to the list of EMCAL tasks

  AliEMCALGetter * gime = AliEMCALGetter::Instance(GetTitle(), fEventFolderName.Data()) ;

  if ( !gime->PID() )
    gime->PostPID(this) ;
}

//____________________________________________________________________________
void AliEMCALPIDv1::InitParameters()
{
  // Initialize the parameters
  fRecParticlesInRun = 0 ;
  fNEvent            = 0 ;
  fRecParticlesInRun = 0 ;
}

//____________________________________________________________________________

void  AliEMCALPIDv1::Exec(Option_t * option)
{
  //Steering method

  if(strstr(option,"tim"))
    gBenchmark->Start("EMCALPID");

  if(strstr(option,"print")) {
    Print("") ;
    return ;
  }
  AliEMCALGetter * gime = AliEMCALGetter::Instance(GetTitle()) ;

  if (fLastEvent == -1)
    fLastEvent = gime->MaxEvent() - 1 ;
  else
    fLastEvent = TMath::Min(fLastEvent,gime->MaxEvent());
  Int_t nEvents   = fLastEvent - fFirstEvent + 1;

  Int_t ievent ;

  for (ievent = fFirstEvent; ievent <= fLastEvent; ievent++) {
    gime->Event(ievent,"R") ;
    MakeRecParticles() ;
    WriteRecParticles();
    if(strstr(option,"deb"))
      PrintRecParticles(option) ;
    //increment the total number of rec particles per run
    fRecParticlesInRun += gime->RecParticles()->GetEntriesFast() ;

  }
  if(strstr(option,"tim")){
    gBenchmark->Stop("EMCALPID");
    printf("Exec: took %f seconds for PID %f seconds per event",
	 gBenchmark->GetCpuTime("EMCALPID"),
	 gBenchmark->GetCpuTime("EMCALPID")/nEvents) ;
  }

  Unload();
}

//____________________________________________________________________________
void  AliEMCALPIDv1::MakeRecParticles(){

  // Makes a RecParticle out of a TrackSegment

  AliEMCALGetter * gime = AliEMCALGetter::Instance() ;
  TObjArray * aECARecPoints = gime->ECARecPoints() ;
  if ( !aECARecPoints ) {
    Fatal("MakeRecParticles", "RecPoints or TrackSegments not found !") ;
  }
  TClonesArray * recParticles  = gime->RecParticles() ;
  recParticles->Clear();

  TIter next(aECARecPoints) ;
  AliEMCALRecPoint * eca ;
  Int_t index = 0 ;
  AliEMCALRecParticle * rp ;
  while ( (eca = (AliEMCALRecPoint *)next()) ) {

    new( (*recParticles)[index] ) AliEMCALRecParticle() ;
    rp = (AliEMCALRecParticle *)recParticles->At(index) ;
    rp->SetRecPoint(index) ;
    rp->SetIndexInList(index) ;

    // Now set type (reconstructed) of the particle

    // Choose the cluster energy range

    Float_t  lambda[2] ;
    eca->GetElipsAxis(lambda) ;

    if((lambda[0]>0.01) && (lambda[1]>0.01)){
      // Looking PCA. Define and calculate the data (X),
      // introduce in the function X2P that gives the components (P).

      Float_t  spher = 0. ;
      Float_t  emaxdtotal = 0. ;

      if((lambda[0]+lambda[1])!=0)
	spher=fabs(lambda[0]-lambda[1])/(lambda[0]+lambda[1]);

      emaxdtotal=eca->GetMaximalEnergy()/eca->GetEnergy();
    }

    //    Float_t time = eca->GetTime() ;

    //Set momentum, energy and other parameters
    Float_t  encal = GetCalibratedEnergy(eca->GetEnergy());
    TVector3 dir   = GetMomentumDirection(eca) ;
    // dir.SetMag(encal) ;Removed to avoid warings !!!!!!!!!!!!!! TO BE REVISED
    rp->SetMomentum(dir.X(),dir.Y(),dir.Z(),encal) ;
    rp->SetCalcMass(0);
    rp->Name(); //If photon sets the particle pdg name to gamma
    rp->SetProductionVertex(0,0,0,0);
    rp->SetFirstMother(-1);
    rp->SetLastMother(-1);
    rp->SetFirstDaughter(-1);
    rp->SetLastDaughter(-1);
    rp->SetPolarisation(0,0,0);
    //Set the position in global coordinate system from the RecPoint
    //AliEMCALGeometry * geom = gime->EMCALGeometry() ;
    //AliEMCALTowerRecPoint  * erp = gime->ECARecPoint(rp->GetEMCALRPIndex()) ;
    TVector3 pos ;
    //geom->GetGlobal(erp, pos) ; !!!!!!!!!! to check
    rp->SetPos(pos);

    index++ ;
  }

}

//____________________________________________________________________________
void  AliEMCALPIDv1:: Print(Option_t * /*option*/) const
{
  // Print the parameters used for the particle type identification

    printf("Print: =============== AliEMCALPID1 ================") ;
    printf("Making PID\n");
    printf("    Pricipal analysis file from 0.5 to 100 %s\n", fFileName.Data() ) ;
    printf("    Name of parameters file     %s\n", fFileNamePar.Data() )  ;
}

//____________________________________________________________________________
void  AliEMCALPIDv1::Print() const
{
  // Print the parameters used for the particle type identification

    Info("Print", "=============== AliEMCALPIDv1 ================") ;
}

//____________________________________________________________________________
void AliEMCALPIDv1::PrintRecParticles(Option_t * option)
{
  // Print table of reconstructed particles

  AliEMCALGetter *gime = AliEMCALGetter::Instance() ;

  TClonesArray * recParticles = gime->RecParticles() ;

  printf("\nevent %i", gAlice->GetEvNumber());
  printf("       found %i", recParticles->GetEntriesFast());
  printf(" RecParticles\n");

  if(strstr(option,"all")) {  // printing found TS
    printf("\n  PARTICLE         Index    \n");

    Int_t index ;
    for (index = 0 ; index < recParticles->GetEntries() ; index++) {
      AliEMCALRecParticle * rp = (AliEMCALRecParticle * ) recParticles->At(index) ;
      printf("\n");
      printf(rp->Name().Data());
      printf(" %i", rp->GetIndexInList());
      printf(" %i", rp->GetType());
    }
  }
}

//____________________________________________________________________________
void AliEMCALPIDv1::Unload()
{
  // Unloads RecPoints, TrackSegments and RecParticles from the folder
  AliEMCALGetter * gime = AliEMCALGetter::Instance() ;
  gime->EmcalLoader()->UnloadRecPoints() ;
  gime->EmcalLoader()->UnloadTracks() ;
  gime->EmcalLoader()->UnloadRecParticles() ;
}

//____________________________________________________________________________
void  AliEMCALPIDv1::WriteRecParticles()
{
  // Write RecParticles array to file
  AliEMCALGetter *gime = AliEMCALGetter::Instance() ;

  TClonesArray * recParticles = gime->RecParticles() ;
  recParticles->Expand(recParticles->GetEntriesFast() ) ;
  TTree * treeP =  gime->TreeP() ;

  //First rp
  Int_t bufferSize = 32000 ;
  TBranch * rpBranch = treeP->Branch("EMCALRP",&recParticles,bufferSize);
  rpBranch->SetTitle(BranchName());

  rpBranch->Fill() ;

  gime->WriteRecParticles("OVERWRITE");
  gime->WritePID("OVERWRITE");

}

<|endoftext|>