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

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information.

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

#include "mitkConnectPointsInteractor.h"
#include <mitkLineOperation.h>
#include <mitkPositionEvent.h>
#include "mitkMesh.h"
#include <mitkDataTreeNode.h>
#include <mitkInteractionConst.h>
#include "mitkAction.h"

//how precise must the user pick the point
//default value
const int PRECISION = 5;

mitk::ConnectPointsInteractor::ConnectPointsInteractor(const char * type, DataTreeNode* dataTreeNode, int n)
:Interactor(type, dataTreeNode), m_N(n), m_CurrentCellId(0), m_Precision(PRECISION)
{
  m_LastPoint.Fill(0);
  m_SumVec.Fill(0);
}

mitk::ConnectPointsInteractor::~ConnectPointsInteractor()
{
}

void mitk::ConnectPointsInteractor::SetPrecision(unsigned int precision)
{
  m_Precision = precision;
}

//##Documentation
//## overwritten cause this class can handle it better!
float mitk::ConnectPointsInteractor::CalculateJurisdiction(StateEvent const* stateEvent) const
{
  float returnvalue = 0.0;
  //if it is a key event that can be handled in the current state, then return 0.5
  mitk::DisplayPositionEvent const  *disPosEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());

  //Key event handling:
  if (disPosEvent == NULL)
  {
    //check, if the current state has a transition waiting for that key event.
    if (this->GetCurrentState()->GetTransition(stateEvent->GetId())!=NULL)
    {
      return 0.5;
    }
    else
    {
      return 0;
    }
  }

  //on MouseMove do nothing!
  if (stateEvent->GetEvent()->GetType() == mitk::Type_MouseMove)
  {
    return 0;
  }

  //if we don't have a Point in our PointSet, then return with 0.5
  mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>(m_DataTreeNode->GetData());
  if (pointSet != NULL)
  {
    if (pointSet->GetSize()<1)
      returnvalue = 0.5;
  }

  return returnvalue;
}

bool mitk::ConnectPointsInteractor::ExecuteAction( Action* action, mitk::StateEvent const* stateEvent )
{
  bool ok = false;//for return type bool

  //checking corresponding Data; has to be a Mesh or a subclass
  mitk::Mesh* mesh = dynamic_cast<mitk::Mesh*>(m_DataTreeNode->GetData());
  if (mesh == NULL)
    return false;

  //for reading on the points, Id's etc
  mitk::PointSet::DataType *itkpointSet = mesh->GetPointSet();
  //mitk::PointSet::PointsContainer *points = itkpointSet->GetPoints();//Warning Fix: not used!

  /*Each case must watch the type of the event!*/
  switch (action->GetActionId())
  {
  case AcDONOTHING:
    ok = true;
    break;
  case AcADDPOINT:
    {
      mitk::DisplayPositionEvent const  *posEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
      if (posEvent == NULL)
        return false;

      mitk::Point3D worldPoint;
      worldPoint = posEvent->GetWorldPosition();

      int position = mesh->SearchPoint(worldPoint, m_Precision);
      if (position>=0)//found a point near enough to the given point
      {
        // if the point is the last in current cell, remove it (this has to be moved in a separate action)
        bool deleteLine=false;
        if(mesh->GetMesh()->GetCells()->Size() > 0)
        {
          Mesh::CellAutoPointer cellAutoPointer;
          ok = mesh->GetMesh()->GetCell(m_CurrentCellId, cellAutoPointer);
          if(ok)
          {
            Mesh::PointIdIterator last = cellAutoPointer->PointIdsEnd();
            --last;
            deleteLine = ((unsigned)(mesh->SearchFirstCell(position)) == m_CurrentCellId) && (*last == position);
          }
        }
        if(deleteLine)
        {
          LineOperation* doOp = new mitk::LineOperation(OpDELETELINE, m_CurrentCellId, position);
          if (m_UndoEnabled)
          {
            LineOperation* undoOp = new mitk::LineOperation(OpADDLINE, m_CurrentCellId, position);
            OperationEvent *operationEvent = new OperationEvent(mesh, doOp, undoOp);
            m_UndoController->SetOperationEvent(operationEvent);
          }
          //execute the Operation
          mesh->ExecuteOperation(doOp );
        }
        else
        {
          // add new cell if necessary
          if(mesh->GetNewCellId() == 0) //allow single line only
//allow multiple lines:          if((mesh->SearchFirstCell(position) >= 0) || ((m_CurrentCellId == 0) && (mesh->GetNewCellId() == 0)))
          {
            //get the next cellId and set m_CurrentCellId
            m_CurrentCellId = mesh->GetNewCellId();

            //now reserv a new cell in m_ItkData
            LineOperation* doOp = new mitk::LineOperation(OpNEWCELL, m_CurrentCellId);
            if (m_UndoEnabled)
            {
              LineOperation* undoOp = new mitk::LineOperation(OpDELETECELL, m_CurrentCellId);
              OperationEvent *operationEvent = new OperationEvent(mesh, doOp, undoOp);
              m_UndoController->SetOperationEvent(operationEvent);
            }
            mesh->ExecuteOperation(doOp);
          }
          // add line if point is not yet included in current cell
          if(mesh->SearchFirstCell(position) < 0)
          {
            LineOperation* doOp = new mitk::LineOperation(OpADDLINE, m_CurrentCellId, position);
            if (m_UndoEnabled)
            {
              LineOperation* undoOp = new mitk::LineOperation(OpDELETELINE, m_CurrentCellId, position);
              OperationEvent *operationEvent = new OperationEvent(mesh, doOp, undoOp);
              m_UndoController->SetOperationEvent(operationEvent);
            }
            //execute the Operation
            mesh->ExecuteOperation(doOp );
          }
        }
      }
      ok = true;
      break;
    }
  case AcREMOVEPOINT:
    {
      //mitk::DisplayPositionEvent const  *posEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
      //if (posEvent == NULL)
      //  return false;

      //mitk::Point3D worldPoint;
      //worldPoint = posEvent->GetWorldPosition();

      //int position = mesh->SearchPoint(worldPoint, m_Precision);
      //if (position>=0)//found a point near enough to the given point
      //{
      //  // if the point is in the current cell, remove it (this has to be moved in a separate action)
      //  if(mesh->SearchFirstCell(position) == m_CurrentCellId)
      //  {
      //    LineOperation* doOp = new mitk::LineOperation(OpDELETELINE, m_CurrentCellId, position);
      //  if (m_UndoEnabled)
      //  {
      //   LineOperation* undoOp = new mitk::LineOperation(OpADDLINE, m_CurrentCellId, position);
      //   OperationEvent *operationEvent = new OperationEvent(mesh, doOp, undoOp);
      //   m_UndoController->SetOperationEvent(operationEvent);
      //  }
      //  //execute the Operation
      //    mesh->ExecuteOperation(doOp );
      //  }
      //}
      ok = true;
      break;
    }
  case AcCHECKELEMENT:
    /*checking if the Point transmitted is close enough to one point. Then generate a new event with the point and let this statemaschine handle the event.*/
    {
      mitk::DisplayPositionEvent const  *posEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
      if (posEvent != NULL)
      {
        mitk::Point3D worldPoint = posEvent->GetWorldPosition();

        int position = mesh->SearchPoint(worldPoint, m_Precision);
        if (position>=0)//found a point near enough to the given point
        {
          PointSet::PointType pt = mesh->GetPoint(position);//get that point, the one meant by the user!
          mitk::Point2D displPoint;
          displPoint[0] = worldPoint[0]; displPoint[1] = worldPoint[1];
          //new Event with information YES and with the correct point
          mitk::PositionEvent const* newPosEvent = new mitk::PositionEvent(posEvent->GetSender(), Type_None, BS_NoButton, BS_NoButton, Key_none, displPoint, pt);
          mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDYES, newPosEvent);
          //call HandleEvent to leave the guard-state
          this->HandleEvent( newStateEvent );
          ok = true;
        }
        else
        {
          //new Event with information NO
          mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDNO, posEvent);
          this->HandleEvent(newStateEvent );
          ok = true;
        }
      }
      else
      {
        mitk::DisplayPositionEvent const  *disPosEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
        if (disPosEvent != NULL)
        {//2d Koordinates for 3D Interaction; return false to redo the last statechange
          mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDNO, posEvent);
          this->HandleEvent(newStateEvent );
          ok = true;
        }
      }
      break;
    }
  case AcCHECKNMINUS1://generate Events if the set will be full after the addition of the point or not.
    {
      if (m_N<0)//number of points not limited->pass on "Amount of points in Set is smaller then N-1"
      {
        mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDSTSMALERNMINUS1, stateEvent->GetEvent());
        this->HandleEvent( newStateEvent );
        ok = true;
      }
      else
      {
        if (mesh->GetSize()<(m_N-1))
          //pointset after addition won't be full
        {
          mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDSTSMALERNMINUS1, stateEvent->GetEvent());
          this->HandleEvent( newStateEvent );
          ok = true;
        }
        else //(mesh->GetSize()>=(m_N-1))
          //after the addition of a point, the container will be full
        {
          mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDSTLARGERNMINUS1, stateEvent->GetEvent());
          this->HandleEvent(newStateEvent );
          ok = true;
        }//else
      }//else
    }
    break;
  case AcCHECKEQUALS1:
    {
      if (mesh->GetSize()<=1)//the number of points in the list is 1 (or smaler)
      {
        mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDYES, stateEvent->GetEvent());
        this->HandleEvent( newStateEvent );
        ok = true;
      }
      else //more than 1 points in list, so stay in the state!
      {
        mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDNO, stateEvent->GetEvent());
        this->HandleEvent(newStateEvent );
        ok = true;
      }
    }
    break;
  default:
    return Superclass::ExecuteAction( action, stateEvent );
    //mitk::StatusBar::DisplayText("Message from mitkConnectPointsInteractor: I do not understand the Action!", 10000);
    //ok = false;
    //a false here causes the statemachine to undo its last statechange.
    //otherwise it will end up in a different state, but without done Action.
    //if a transition really has no Action, than call donothing
  }

  return ok;
}
<commit_msg>FIX: removed warning: unused var and signed unsigned mismatch<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information.

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

#include "mitkConnectPointsInteractor.h"
#include <mitkLineOperation.h>
#include <mitkPositionEvent.h>
#include "mitkMesh.h"
#include <mitkDataTreeNode.h>
#include <mitkInteractionConst.h>
#include "mitkAction.h"

//how precise must the user pick the point
//default value
const int PRECISION = 5;

mitk::ConnectPointsInteractor::ConnectPointsInteractor(const char * type, DataTreeNode* dataTreeNode, int n)
:Interactor(type, dataTreeNode), m_N(n), m_CurrentCellId(0), m_Precision(PRECISION)
{
  m_LastPoint.Fill(0);
  m_SumVec.Fill(0);
}

mitk::ConnectPointsInteractor::~ConnectPointsInteractor()
{
}

void mitk::ConnectPointsInteractor::SetPrecision(unsigned int precision)
{
  m_Precision = precision;
}

//##Documentation
//## overwritten cause this class can handle it better!
float mitk::ConnectPointsInteractor::CalculateJurisdiction(StateEvent const* stateEvent) const
{
  float returnvalue = 0.0;
  //if it is a key event that can be handled in the current state, then return 0.5
  mitk::DisplayPositionEvent const  *disPosEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());

  //Key event handling:
  if (disPosEvent == NULL)
  {
    //check, if the current state has a transition waiting for that key event.
    if (this->GetCurrentState()->GetTransition(stateEvent->GetId())!=NULL)
    {
      return 0.5;
    }
    else
    {
      return 0;
    }
  }

  //on MouseMove do nothing!
  if (stateEvent->GetEvent()->GetType() == mitk::Type_MouseMove)
  {
    return 0;
  }

  //if we don't have a Point in our PointSet, then return with 0.5
  mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>(m_DataTreeNode->GetData());
  if (pointSet != NULL)
  {
    if (pointSet->GetSize()<1)
      returnvalue = 0.5;
  }

  return returnvalue;
}

bool mitk::ConnectPointsInteractor::ExecuteAction( Action* action, mitk::StateEvent const* stateEvent )
{
  bool ok = false;//for return type bool

  //checking corresponding Data; has to be a Mesh or a subclass
  mitk::Mesh* mesh = dynamic_cast<mitk::Mesh*>(m_DataTreeNode->GetData());
  if (mesh == NULL)
    return false;

  //for reading on the points, Id's etc
  //mitk::PointSet::DataType *itkpointSet = mesh->GetPointSet();
  //mitk::PointSet::PointsContainer *points = itkpointSet->GetPoints();//Warning Fix: not used!

  /*Each case must watch the type of the event!*/
  switch (action->GetActionId())
  {
  case AcDONOTHING:
    ok = true;
    break;
  case AcADDPOINT:
    {
      mitk::DisplayPositionEvent const  *posEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
      if (posEvent == NULL)
        return false;

      mitk::Point3D worldPoint;
      worldPoint = posEvent->GetWorldPosition();

      int position = mesh->SearchPoint(worldPoint, m_Precision);
      if (position>=0)//found a point near enough to the given point
      {
        // if the point is the last in current cell, remove it (this has to be moved in a separate action)
        bool deleteLine=false;
        if(mesh->GetMesh()->GetCells()->Size() > 0)
        {
          Mesh::CellAutoPointer cellAutoPointer;
          ok = mesh->GetMesh()->GetCell(m_CurrentCellId, cellAutoPointer);
          if(ok)
          {
            Mesh::PointIdIterator last = cellAutoPointer->PointIdsEnd();
            --last;
            deleteLine = (((unsigned)(mesh->SearchFirstCell(position))) == m_CurrentCellId) && (*last == position);
          }
        }
        if(deleteLine)
        {
          LineOperation* doOp = new mitk::LineOperation(OpDELETELINE, m_CurrentCellId, position);
          if (m_UndoEnabled)
          {
            LineOperation* undoOp = new mitk::LineOperation(OpADDLINE, m_CurrentCellId, position);
            OperationEvent *operationEvent = new OperationEvent(mesh, doOp, undoOp);
            m_UndoController->SetOperationEvent(operationEvent);
          }
          //execute the Operation
          mesh->ExecuteOperation(doOp );
        }
        else
        {
          // add new cell if necessary
          if(mesh->GetNewCellId() == 0) //allow single line only
//allow multiple lines:          if((mesh->SearchFirstCell(position) >= 0) || ((m_CurrentCellId == 0) && (mesh->GetNewCellId() == 0)))
          {
            //get the next cellId and set m_CurrentCellId
            m_CurrentCellId = mesh->GetNewCellId();

            //now reserv a new cell in m_ItkData
            LineOperation* doOp = new mitk::LineOperation(OpNEWCELL, m_CurrentCellId);
            if (m_UndoEnabled)
            {
              LineOperation* undoOp = new mitk::LineOperation(OpDELETECELL, m_CurrentCellId);
              OperationEvent *operationEvent = new OperationEvent(mesh, doOp, undoOp);
              m_UndoController->SetOperationEvent(operationEvent);
            }
            mesh->ExecuteOperation(doOp);
          }
          // add line if point is not yet included in current cell
          if(mesh->SearchFirstCell(position) < 0)
          {
            LineOperation* doOp = new mitk::LineOperation(OpADDLINE, m_CurrentCellId, position);
            if (m_UndoEnabled)
            {
              LineOperation* undoOp = new mitk::LineOperation(OpDELETELINE, m_CurrentCellId, position);
              OperationEvent *operationEvent = new OperationEvent(mesh, doOp, undoOp);
              m_UndoController->SetOperationEvent(operationEvent);
            }
            //execute the Operation
            mesh->ExecuteOperation(doOp );
          }
        }
      }
      ok = true;
      break;
    }
  case AcREMOVEPOINT:
    {
      //mitk::DisplayPositionEvent const  *posEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
      //if (posEvent == NULL)
      //  return false;

      //mitk::Point3D worldPoint;
      //worldPoint = posEvent->GetWorldPosition();

      //int position = mesh->SearchPoint(worldPoint, m_Precision);
      //if (position>=0)//found a point near enough to the given point
      //{
      //  // if the point is in the current cell, remove it (this has to be moved in a separate action)
      //  if(mesh->SearchFirstCell(position) == m_CurrentCellId)
      //  {
      //    LineOperation* doOp = new mitk::LineOperation(OpDELETELINE, m_CurrentCellId, position);
      //  if (m_UndoEnabled)
      //  {
      //   LineOperation* undoOp = new mitk::LineOperation(OpADDLINE, m_CurrentCellId, position);
      //   OperationEvent *operationEvent = new OperationEvent(mesh, doOp, undoOp);
      //   m_UndoController->SetOperationEvent(operationEvent);
      //  }
      //  //execute the Operation
      //    mesh->ExecuteOperation(doOp );
      //  }
      //}
      ok = true;
      break;
    }
  case AcCHECKELEMENT:
    /*checking if the Point transmitted is close enough to one point. Then generate a new event with the point and let this statemaschine handle the event.*/
    {
      mitk::DisplayPositionEvent const  *posEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
      if (posEvent != NULL)
      {
        mitk::Point3D worldPoint = posEvent->GetWorldPosition();

        int position = mesh->SearchPoint(worldPoint, m_Precision);
        if (position>=0)//found a point near enough to the given point
        {
          PointSet::PointType pt = mesh->GetPoint(position);//get that point, the one meant by the user!
          mitk::Point2D displPoint;
          displPoint[0] = worldPoint[0]; displPoint[1] = worldPoint[1];
          //new Event with information YES and with the correct point
          mitk::PositionEvent const* newPosEvent = new mitk::PositionEvent(posEvent->GetSender(), Type_None, BS_NoButton, BS_NoButton, Key_none, displPoint, pt);
          mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDYES, newPosEvent);
          //call HandleEvent to leave the guard-state
          this->HandleEvent( newStateEvent );
          ok = true;
        }
        else
        {
          //new Event with information NO
          mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDNO, posEvent);
          this->HandleEvent(newStateEvent );
          ok = true;
        }
      }
      else
      {
        mitk::DisplayPositionEvent const  *disPosEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
        if (disPosEvent != NULL)
        {//2d Koordinates for 3D Interaction; return false to redo the last statechange
          mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDNO, posEvent);
          this->HandleEvent(newStateEvent );
          ok = true;
        }
      }
      break;
    }
  case AcCHECKNMINUS1://generate Events if the set will be full after the addition of the point or not.
    {
      if (m_N<0)//number of points not limited->pass on "Amount of points in Set is smaller then N-1"
      {
        mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDSTSMALERNMINUS1, stateEvent->GetEvent());
        this->HandleEvent( newStateEvent );
        ok = true;
      }
      else
      {
        if (mesh->GetSize()<(m_N-1))
          //pointset after addition won't be full
        {
          mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDSTSMALERNMINUS1, stateEvent->GetEvent());
          this->HandleEvent( newStateEvent );
          ok = true;
        }
        else //(mesh->GetSize()>=(m_N-1))
          //after the addition of a point, the container will be full
        {
          mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDSTLARGERNMINUS1, stateEvent->GetEvent());
          this->HandleEvent(newStateEvent );
          ok = true;
        }//else
      }//else
    }
    break;
  case AcCHECKEQUALS1:
    {
      if (mesh->GetSize()<=1)//the number of points in the list is 1 (or smaler)
      {
        mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDYES, stateEvent->GetEvent());
        this->HandleEvent( newStateEvent );
        ok = true;
      }
      else //more than 1 points in list, so stay in the state!
      {
        mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDNO, stateEvent->GetEvent());
        this->HandleEvent(newStateEvent );
        ok = true;
      }
    }
    break;
  default:
    return Superclass::ExecuteAction( action, stateEvent );
    //mitk::StatusBar::DisplayText("Message from mitkConnectPointsInteractor: I do not understand the Action!", 10000);
    //ok = false;
    //a false here causes the statemachine to undo its last statechange.
    //otherwise it will end up in a different state, but without done Action.
    //if a transition really has no Action, than call donothing
  }

  return ok;
}
<|endoftext|>


<commit_before>/*
  RGBLamp.cpp - Library for controlling RGB diodes.
  Created by Claus Lensbøl, May 19, 2013.
  For license, see LICENSE file.
*/
#include "Arduino.h"
#include "RGBLamp.h"

// Constructor - Does nothing for now (but is needed)
RGBLamp::RGBLamp() {}

void RGBLamp::create(int pin_r, int pin_g, int pin_b) {
  _pins[0]    = pin_r;
  _pins[1]    = pin_g;
  _pins[2]    = pin_b;
  _fade_start = 0;
  _fade_end   = 0;
  _fade       = false;
}

// -------- FADES START --------

// Takes fade length in millis, and direction 1 for up and -1 for down
void RGBLamp::fade(int fade_length, int fade_to[]) {
  _fade_start			= millis();
  _fade_end				= millis() + fade_length;

  for(int i = 0 ; i < 3 ; i++) {
    _fade_from[i] = _current_color[i];
    _fade_to[i]   = fade_to[i];
  }
  _fade           = true;
}

// Does the actual fading
bool RGBLamp::fade() {
  if(_fade) {

    _fade = false;

    // Test to see if we have used to much time on fading and
    // end the fading (set final color and set _fade to false).
    if(millis() >= _fade_end) {
      setColor(_fade_to);
    }
    else {
      int color[] = {0,0,0};

      for(int i = 0; i < 3 ; i++) {
        float now = ((float)millis() - _fade_start);
        float fl = (_fade_end - _fade_start);
        float fromto = (float) (_fade_from[i] - _fade_to[i]);
        float col = (now/fl) * (fromto);
        color[i] = _fade_from[i] - col;

        if (color[i] != _fade_to[i]) {
          _fade = true;
        }
      }

      setColor(color);
    }
  }

  return _fade;
}

// -------- FADES END ----------

void RGBLamp::off() {
  for(int i = 0 ; i < 3 ; i++) {
    digitalWrite(_pins[i], LOW);
  }
}

void RGBLamp::on() {
  for(int i = 0; i < 3 ; i++) {
    digitalWrite(_pins[i], HIGH);
  }
}

void RGBLamp::setColor(int color[]) {
  for(int i = 0; i < 3 ; i++) {
    _current_color[i] = color[i];
    analogWrite(_pins[i], color[i]);
  }
}

// Place things here that needs to be done with all the lamps all the time
bool RGBLamp::work() {
	return fade();
}
<commit_msg>Edit: The color pins<commit_after>/*
  RGBLamp.cpp - Library for controlling RGB diodes.
  Created by Claus Lensbøl, May 19, 2013.
  For license, see LICENSE file.
*/
#include "Arduino.h"
#include "RGBLamp.h"

// Constructor - Does nothing for now (but is needed)
RGBLamp::RGBLamp() {}

void RGBLamp::create(int pin_r, int pin_g, int pin_b) {
  _pins[0]    = pin_g;
  _pins[1]    = pin_r;
  _pins[2]    = pin_b;
  _fade_start = 0;
  _fade_end   = 0;
  _fade       = false;
}

// -------- FADES START --------

// Takes fade length in millis, and direction 1 for up and -1 for down
void RGBLamp::fade(int fade_length, int fade_to[]) {
  _fade_start			= millis();
  _fade_end				= millis() + fade_length;

  for(int i = 0 ; i < 3 ; i++) {
    _fade_from[i] = _current_color[i];
    _fade_to[i]   = fade_to[i];
  }
  _fade           = true;
}

// Does the actual fading
bool RGBLamp::fade() {
  if(_fade) {

    _fade = false;

    // Test to see if we have used to much time on fading and
    // end the fading (set final color and set _fade to false).
    if(millis() >= _fade_end) {
      setColor(_fade_to);
    }
    else {
      int color[] = {0,0,0};

      for(int i = 0; i < 3 ; i++) {
        float now = ((float)millis() - _fade_start);
        float fl = (_fade_end - _fade_start);
        float fromto = (float) (_fade_from[i] - _fade_to[i]);
        float col = (now/fl) * (fromto);
        color[i] = _fade_from[i] - col;

        if (color[i] != _fade_to[i]) {
          _fade = true;
        }
      }

      setColor(color);
    }
  }

  return _fade;
}

// -------- FADES END ----------

void RGBLamp::off() {
  for(int i = 0 ; i < 3 ; i++) {
    digitalWrite(_pins[i], LOW);
  }
}

void RGBLamp::on() {
  for(int i = 0; i < 3 ; i++) {
    digitalWrite(_pins[i], HIGH);
  }
}

void RGBLamp::setColor(int color[]) {
  for(int i = 0; i < 3 ; i++) {
    _current_color[i] = color[i];
    analogWrite(_pins[i], color[i]);
  }
}

// Place things here that needs to be done with all the lamps all the time
bool RGBLamp::work() {
	return fade();
}
<|endoftext|>


<commit_before>/**
 * @author Koen Wolters <koen.wolters@cern.ch>
 */

#include "DetectorHistogrammerTestModule.hpp"

#include <memory>
#include <string>
#include <utility>

#include <TApplication.h>
#include <TFile.h>
#include <TH2D.h>

#include "core/geometry/PixelDetectorModel.hpp"

#include "core/messenger/Messenger.hpp"
#include "core/utils/log.h"

using namespace allpix;

const std::string DetectorHistogrammerModule::name = "detector_histogrammer_test";

DetectorHistogrammerModule::DetectorHistogrammerModule(Configuration config,
                                                       Messenger* messenger,
                                                       std::shared_ptr<Detector> detector)
    : Module(detector), config_(std::move(config)), detector_(std::move(detector)), pixels_message_(nullptr) {
    // fetch deposit for single module
    messenger->bindSingle(this, &DetectorHistogrammerModule::pixels_message_);
}
DetectorHistogrammerModule::~DetectorHistogrammerModule() = default;

// histogram the deposits
void DetectorHistogrammerModule::run() {
    // check if we got any deposits
    if(pixels_message_ == nullptr) {
        LOG(WARNING) << "Detector " << detector_->getName() << " did not get any deposits... skipping!";
        return;
    }

    // get detector model
    auto model = std::dynamic_pointer_cast<PixelDetectorModel>(detector_->getModel());
    if(model == nullptr) {
        // FIXME: exception can be more appropriate here
        LOG(CRITICAL) << "Detector " << detector_->getName()
                      << " is not a PixelDetectorModel: ignored as other types are currently unsupported!";
        return;
    }

    // create root file
    std::string file_name = config_.get<std::string>("file_prefix") + "_" + detector_->getName() + ".root";
    auto file = new TFile(file_name.c_str(), "RECREATE");

    // create histogram
    std::string plot_name = "plot_" + detector_->getName();
    std::string plot_title = "Histogram for " + detector_->getName();
    auto histogram = new TH2F(plot_name.c_str(),
                              plot_title.c_str(),
                              model->getNPixelsX(),
                              0,
                              model->getNPixelsX(),
                              model->getNPixelsY(),
                              0,
                              model->getNPixelsY());

    for(auto& pixel_charge : pixels_message_->getData()) {
        auto pixel = pixel_charge.getPixel();
        auto charge = pixel_charge.getCharge();

        LOG(DEBUG) << "got " << charge << " charges on pixel (" << pixel.x() << "," << pixel.y() << ")";

        histogram->Fill(pixel.x(), pixel.y(), charge);
    }

    histogram->Write();

    file->Close();
}
<commit_msg>add test plot for cluster size<commit_after>/**
 * @author Koen Wolters <koen.wolters@cern.ch>
 */

#include "DetectorHistogrammerTestModule.hpp"

#include <memory>
#include <string>
#include <utility>

#include <TApplication.h>
#include <TFile.h>
#include <TH1I.h>
#include <TH2I.h>

#include "core/geometry/PixelDetectorModel.hpp"

#include "core/messenger/Messenger.hpp"
#include "core/utils/log.h"

using namespace allpix;

const std::string DetectorHistogrammerModule::name = "detector_histogrammer_test";

DetectorHistogrammerModule::DetectorHistogrammerModule(Configuration config,
                                                       Messenger* messenger,
                                                       std::shared_ptr<Detector> detector)
    : Module(detector), config_(std::move(config)), detector_(std::move(detector)), pixels_message_(nullptr) {
    // fetch deposit for single module
    messenger->bindSingle(this, &DetectorHistogrammerModule::pixels_message_);
}
DetectorHistogrammerModule::~DetectorHistogrammerModule() = default;

// histogram the deposits
void DetectorHistogrammerModule::run() {
    // check if we got any deposits
    if(pixels_message_ == nullptr) {
        LOG(WARNING) << "Detector " << detector_->getName() << " did not get any deposits... skipping!";
        return;
    }

    // get detector model
    auto model = std::dynamic_pointer_cast<PixelDetectorModel>(detector_->getModel());
    if(model == nullptr) {
        // FIXME: exception can be more appropriate here
        LOG(CRITICAL) << "Detector " << detector_->getName()
                      << " is not a PixelDetectorModel: ignored as other types are currently unsupported!";
        return;
    }

    // create root file
    std::string file_name = config_.get<std::string>("file_prefix") + "_" + detector_->getName() + ".root";
    auto file = new TFile(file_name.c_str(), "RECREATE");

    // create histogram
    std::string histogram_name = "histogram_" + detector_->getName();
    std::string histogram_title = "Histogram for " + detector_->getName();
    auto histogram = new TH2I(histogram_name.c_str(),
                              histogram_title.c_str(),
                              model->getNPixelsX(),
                              0,
                              model->getNPixelsX(),
                              model->getNPixelsY(),
                              0,
                              model->getNPixelsY());

    // fill histogram
    for(auto& pixel_charge : pixels_message_->getData()) {
        auto pixel = pixel_charge.getPixel();
        auto charge = pixel_charge.getCharge();

        LOG(DEBUG) << "got " << charge << " charges on pixel (" << pixel.x() << "," << pixel.y() << ")";

        histogram->Fill(pixel.x(), pixel.y(), charge);
    }
    histogram->Write();

    // create cluster size plot
    std::string cluster_size_name = "cluster_" + detector_->getName();
    std::string cluster_size_title = "Cluster size for " + detector_->getName();
    auto cluster_size = new TH1I(cluster_size_name.c_str(),
                                 cluster_size_title.c_str(),
                                 model->getNPixelsX() * model->getNPixelsY(),
                                 0,
                                 model->getNPixelsX() * model->getNPixelsY());
    cluster_size->Fill(static_cast<double>(pixels_message_->getData().size()));
    cluster_size->Write();

    // close the file
    file->Close();
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/gpu/gpu_info_collector.h"

#include <dlfcn.h>
#include <vector>

#include "app/gfx/gl/gl_bindings.h"
#include "app/gfx/gl/gl_context.h"
#include "app/gfx/gl/gl_implementation.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/string_piece.h"
#include "base/string_split.h"
#include "base/string_util.h"

namespace {

// PciDevice and PciAccess are defined to access libpci functions.  Their
// members match the corresponding structures defined by libpci in size up to
// fields we may access.  For those members we don't use, their names are
// defined as "fieldX", etc., or, left out if they are declared after the
// members we care about in libpci.

struct PciDevice {
  PciDevice* next;

  uint16 field0;
  uint8 field1;
  uint8 field2;
  uint8 field3;
  int field4;

  uint16 vendor_id;
  uint16 device_id;
  uint16 device_class;
};

struct PciAccess {
  unsigned int field0;
  int field1;
  int field2;
  char* field3;
  int field4;
  int field5;
  unsigned int field6;
  int field7;

  void (*function0)();
  void (*function1)();
  void (*function2)();

  PciDevice* device_list;
};

// Define function types.
typedef PciAccess* (*FT_pci_alloc)();
typedef void (*FT_pci_init)(PciAccess*);
typedef void (*FT_pci_cleanup)(PciAccess*);
typedef void (*FT_pci_scan_bus)(PciAccess*);
typedef void (*FT_pci_scan_bus)(PciAccess*);
typedef int (*FT_pci_fill_info)(PciDevice*, int);
typedef char* (*FT_pci_lookup_name)(PciAccess*, char*, int, int, ...);

// This includes dynamically linked library handle and functions pointers from
// libpci.
struct PciInterface {
  void* lib_handle;

  FT_pci_alloc pci_alloc;
  FT_pci_init pci_init;
  FT_pci_cleanup pci_cleanup;
  FT_pci_scan_bus pci_scan_bus;
  FT_pci_fill_info pci_fill_info;
  FT_pci_lookup_name pci_lookup_name;
};

// This dynamically opens libpci and get function pointers we need.  Return
// NULL if library fails to open or any functions can not be located.
// Returned interface (if not NULL) should be deleted in FinalizeLibPci.
PciInterface* InitializeLibPci(const char* lib_name) {
  void* handle = dlopen(lib_name, RTLD_LAZY);
  if (handle == NULL) {
    LOG(ERROR) << "Fail to dlopen libpci";
    return NULL;
  }
  PciInterface* interface = new struct PciInterface;
  interface->lib_handle = handle;
  interface->pci_alloc = reinterpret_cast<FT_pci_alloc>(
      dlsym(handle, "pci_alloc"));
  interface->pci_init = reinterpret_cast<FT_pci_init>(
      dlsym(handle, "pci_init"));
  interface->pci_cleanup = reinterpret_cast<FT_pci_cleanup>(
      dlsym(handle, "pci_cleanup"));
  interface->pci_scan_bus = reinterpret_cast<FT_pci_scan_bus>(
      dlsym(handle, "pci_scan_bus"));
  interface->pci_fill_info = reinterpret_cast<FT_pci_fill_info>(
      dlsym(handle, "pci_fill_info"));
  interface->pci_lookup_name = reinterpret_cast<FT_pci_lookup_name>(
      dlsym(handle, "pci_lookup_name"));
  if (interface->pci_alloc == NULL ||
      interface->pci_init == NULL ||
      interface->pci_cleanup == NULL ||
      interface->pci_scan_bus == NULL ||
      interface->pci_fill_info == NULL ||
      interface->pci_lookup_name == NULL) {
    LOG(ERROR) << "Missing required function(s) from libpci";
    dlclose(handle);
    delete interface;
    return NULL;
  }
  return interface;
}

// This close the dynamically opened libpci and delete the interface.
void FinalizeLibPci(PciInterface** interface) {
  DCHECK(interface && *interface && (*interface)->lib_handle);
  dlclose((*interface)->lib_handle);
  delete (*interface);
  *interface = NULL;
}

}  // namespace anonymous

namespace gpu_info_collector {

bool CollectGraphicsInfo(GPUInfo* gpu_info) {
  DCHECK(gpu_info);

  // TODO(zmo): need to consider the case where we are running on top of
  // desktop GL and GL_ARB_robustness extension is available.
  gpu_info->SetCanLoseContext(
      gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2);
  gpu_info->SetLevel(GPUInfo::kComplete);
  return CollectGraphicsInfoGL(gpu_info);
}

bool CollectPreliminaryGraphicsInfo(GPUInfo* gpu_info) {
  DCHECK(gpu_info);

  gpu_info->SetLevel(GPUInfo::kPartial);

  bool rt = true;
  if (!CollectVideoCardInfo(gpu_info))
    rt = false;

  // TODO(zmo): if vendor is ATI, consider passing /etc/ati/amdpcsdb.default
  // for driver information.

  return rt;
}

bool CollectVideoCardInfo(GPUInfo* gpu_info) {
  DCHECK(gpu_info);

  // TODO(zmo): be more flexible about library name.
  PciInterface* interface = InitializeLibPci("libpci.so.3");
  if (interface == NULL)
    return false;

  PciAccess* access = (interface->pci_alloc)();
  DCHECK(access != NULL);
  (interface->pci_init)(access);
  (interface->pci_scan_bus)(access);
  std::vector<PciDevice*> gpu_list;
  PciDevice* gpu_active = NULL;
  for (PciDevice* device = access->device_list;
       device != NULL; device = device->next) {
    (interface->pci_fill_info)(device, 33);  // Fill the IDs and class fields.
    // TODO(zmo): there might be other classes that qualify as display devices.
    if (device->device_class == 0x0300) {  // Device class is DISPLAY_VGA.
      gpu_list.push_back(device);
    }
  }
  if (gpu_list.size() == 1) {
    gpu_active = gpu_list[0];
  } else {
    // If more than one graphics card are identified, find the one that matches
    // gl VENDOR and RENDERER info.
    std::string gl_vendor_string = gpu_info->gl_vendor();
    std::string gl_renderer_string = gpu_info->gl_renderer();
    const int buffer_size = 255;
    scoped_array<char> buffer(new char[buffer_size]);
    std::vector<PciDevice*> candidates;
    for (size_t i = 0; i < gpu_list.size(); ++i) {
      PciDevice* gpu = gpu_list[i];
      // The current implementation of pci_lookup_name returns the same pointer
      // as the passed in upon success, and a different one (NULL or a pointer
      // to an error message) upon failure.
      if ((interface->pci_lookup_name)(access,
                                       buffer.get(),
                                       buffer_size,
                                       1,
                                       gpu->vendor_id) != buffer.get())
        continue;
      std::string vendor_string = buffer.get();
      const bool kCaseSensitive = false;
      if (!StartsWithASCII(gl_vendor_string, vendor_string, kCaseSensitive))
        continue;
      if ((interface->pci_lookup_name)(access,
                                       buffer.get(),
                                       buffer_size,
                                       2,
                                       gpu->vendor_id,
                                       gpu->device_id) != buffer.get())
        continue;
      std::string device_string = buffer.get();
      size_t begin = device_string.find_first_of('[');
      size_t end = device_string.find_last_of(']');
      if (begin != std::string::npos && end != std::string::npos &&
          begin < end) {
        device_string = device_string.substr(begin + 1, end - begin - 1);
      }
      if (StartsWithASCII(gl_renderer_string, device_string, kCaseSensitive)) {
        gpu_active = gpu;
        break;
      }
      // If a device's vendor matches gl VENDOR string, we want to consider the
      // possibility that libpci may not return the exact same name as gl
      // RENDERER string.
      candidates.push_back(gpu);
    }
    if (gpu_active == NULL && candidates.size() == 1)
      gpu_active = candidates[0];
  }
  if (gpu_active != NULL)
    gpu_info->SetVideoCardInfo(gpu_active->vendor_id, gpu_active->device_id);
  (interface->pci_cleanup)(access);
  FinalizeLibPci(&interface);
  return (gpu_active != NULL);
}

bool CollectDriverInfoGL(GPUInfo* gpu_info) {
  DCHECK(gpu_info);

  std::string gl_version_string = gpu_info->gl_version_string();
  std::vector<std::string> pieces;
  base::SplitStringAlongWhitespace(gl_version_string, &pieces);
  // In linux, the gl version string might be in the format of
  //   GLVersion DriverVendor DriverVersion
  if (pieces.size() < 3)
    return false;

  std::string driver_version = pieces[2];
  size_t pos = driver_version.find_first_not_of("0123456789.");
  if (pos == 0)
    return false;
  if (pos != std::string::npos)
    driver_version = driver_version.substr(0, pos);

  gpu_info->SetDriverInfo(pieces[1], driver_version, "");
  return true;
}

}  // namespace gpu_info_collector
<commit_msg>Be more flexible about PCI lib path: try both libpci.so.3 and libpci.so.  So far mostly we see if libpci.so.3, but today we received someone reporting libpci.so.<commit_after>// Copyright (c) 2006-2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/gpu/gpu_info_collector.h"

#include <dlfcn.h>
#include <vector>

#include "app/gfx/gl/gl_bindings.h"
#include "app/gfx/gl/gl_context.h"
#include "app/gfx/gl/gl_implementation.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/string_piece.h"
#include "base/string_split.h"
#include "base/string_util.h"

namespace {

// PciDevice and PciAccess are defined to access libpci functions.  Their
// members match the corresponding structures defined by libpci in size up to
// fields we may access.  For those members we don't use, their names are
// defined as "fieldX", etc., or, left out if they are declared after the
// members we care about in libpci.

struct PciDevice {
  PciDevice* next;

  uint16 field0;
  uint8 field1;
  uint8 field2;
  uint8 field3;
  int field4;

  uint16 vendor_id;
  uint16 device_id;
  uint16 device_class;
};

struct PciAccess {
  unsigned int field0;
  int field1;
  int field2;
  char* field3;
  int field4;
  int field5;
  unsigned int field6;
  int field7;

  void (*function0)();
  void (*function1)();
  void (*function2)();

  PciDevice* device_list;
};

// Define function types.
typedef PciAccess* (*FT_pci_alloc)();
typedef void (*FT_pci_init)(PciAccess*);
typedef void (*FT_pci_cleanup)(PciAccess*);
typedef void (*FT_pci_scan_bus)(PciAccess*);
typedef void (*FT_pci_scan_bus)(PciAccess*);
typedef int (*FT_pci_fill_info)(PciDevice*, int);
typedef char* (*FT_pci_lookup_name)(PciAccess*, char*, int, int, ...);

// This includes dynamically linked library handle and functions pointers from
// libpci.
struct PciInterface {
  void* lib_handle;

  FT_pci_alloc pci_alloc;
  FT_pci_init pci_init;
  FT_pci_cleanup pci_cleanup;
  FT_pci_scan_bus pci_scan_bus;
  FT_pci_fill_info pci_fill_info;
  FT_pci_lookup_name pci_lookup_name;
};

// This dynamically opens libpci and get function pointers we need.  Return
// NULL if library fails to open or any functions can not be located.
// Returned interface (if not NULL) should be deleted in FinalizeLibPci.
PciInterface* InitializeLibPci(const char* lib_name) {
  void* handle = dlopen(lib_name, RTLD_LAZY);
  if (handle == NULL) {
    LOG(INFO) << "Failed to dlopen " << lib_name;
    return NULL;
  }
  PciInterface* interface = new struct PciInterface;
  interface->lib_handle = handle;
  interface->pci_alloc = reinterpret_cast<FT_pci_alloc>(
      dlsym(handle, "pci_alloc"));
  interface->pci_init = reinterpret_cast<FT_pci_init>(
      dlsym(handle, "pci_init"));
  interface->pci_cleanup = reinterpret_cast<FT_pci_cleanup>(
      dlsym(handle, "pci_cleanup"));
  interface->pci_scan_bus = reinterpret_cast<FT_pci_scan_bus>(
      dlsym(handle, "pci_scan_bus"));
  interface->pci_fill_info = reinterpret_cast<FT_pci_fill_info>(
      dlsym(handle, "pci_fill_info"));
  interface->pci_lookup_name = reinterpret_cast<FT_pci_lookup_name>(
      dlsym(handle, "pci_lookup_name"));
  if (interface->pci_alloc == NULL ||
      interface->pci_init == NULL ||
      interface->pci_cleanup == NULL ||
      interface->pci_scan_bus == NULL ||
      interface->pci_fill_info == NULL ||
      interface->pci_lookup_name == NULL) {
    LOG(ERROR) << "Missing required function(s) from " << lib_name;
    dlclose(handle);
    delete interface;
    return NULL;
  }
  return interface;
}

// This close the dynamically opened libpci and delete the interface.
void FinalizeLibPci(PciInterface** interface) {
  DCHECK(interface && *interface && (*interface)->lib_handle);
  dlclose((*interface)->lib_handle);
  delete (*interface);
  *interface = NULL;
}

}  // namespace anonymous

namespace gpu_info_collector {

bool CollectGraphicsInfo(GPUInfo* gpu_info) {
  DCHECK(gpu_info);

  // TODO(zmo): need to consider the case where we are running on top of
  // desktop GL and GL_ARB_robustness extension is available.
  gpu_info->SetCanLoseContext(
      gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2);
  gpu_info->SetLevel(GPUInfo::kComplete);
  return CollectGraphicsInfoGL(gpu_info);
}

bool CollectPreliminaryGraphicsInfo(GPUInfo* gpu_info) {
  DCHECK(gpu_info);

  gpu_info->SetLevel(GPUInfo::kPartial);

  bool rt = true;
  if (!CollectVideoCardInfo(gpu_info))
    rt = false;

  // TODO(zmo): if vendor is ATI, consider passing /etc/ati/amdpcsdb.default
  // for driver information.

  return rt;
}

bool CollectVideoCardInfo(GPUInfo* gpu_info) {
  DCHECK(gpu_info);

  // TODO(zmo): be more flexible about library name.
  PciInterface* interface = InitializeLibPci("libpci.so.3");
  if (interface == NULL)
    interface = InitializeLibPci("libpci.so");
  if (interface == NULL) {
    LOG(ERROR) << "Failed to locate libpci";
    return false;
  }

  PciAccess* access = (interface->pci_alloc)();
  DCHECK(access != NULL);
  (interface->pci_init)(access);
  (interface->pci_scan_bus)(access);
  std::vector<PciDevice*> gpu_list;
  PciDevice* gpu_active = NULL;
  for (PciDevice* device = access->device_list;
       device != NULL; device = device->next) {
    (interface->pci_fill_info)(device, 33);  // Fill the IDs and class fields.
    // TODO(zmo): there might be other classes that qualify as display devices.
    if (device->device_class == 0x0300) {  // Device class is DISPLAY_VGA.
      gpu_list.push_back(device);
    }
  }
  if (gpu_list.size() == 1) {
    gpu_active = gpu_list[0];
  } else {
    // If more than one graphics card are identified, find the one that matches
    // gl VENDOR and RENDERER info.
    std::string gl_vendor_string = gpu_info->gl_vendor();
    std::string gl_renderer_string = gpu_info->gl_renderer();
    const int buffer_size = 255;
    scoped_array<char> buffer(new char[buffer_size]);
    std::vector<PciDevice*> candidates;
    for (size_t i = 0; i < gpu_list.size(); ++i) {
      PciDevice* gpu = gpu_list[i];
      // The current implementation of pci_lookup_name returns the same pointer
      // as the passed in upon success, and a different one (NULL or a pointer
      // to an error message) upon failure.
      if ((interface->pci_lookup_name)(access,
                                       buffer.get(),
                                       buffer_size,
                                       1,
                                       gpu->vendor_id) != buffer.get())
        continue;
      std::string vendor_string = buffer.get();
      const bool kCaseSensitive = false;
      if (!StartsWithASCII(gl_vendor_string, vendor_string, kCaseSensitive))
        continue;
      if ((interface->pci_lookup_name)(access,
                                       buffer.get(),
                                       buffer_size,
                                       2,
                                       gpu->vendor_id,
                                       gpu->device_id) != buffer.get())
        continue;
      std::string device_string = buffer.get();
      size_t begin = device_string.find_first_of('[');
      size_t end = device_string.find_last_of(']');
      if (begin != std::string::npos && end != std::string::npos &&
          begin < end) {
        device_string = device_string.substr(begin + 1, end - begin - 1);
      }
      if (StartsWithASCII(gl_renderer_string, device_string, kCaseSensitive)) {
        gpu_active = gpu;
        break;
      }
      // If a device's vendor matches gl VENDOR string, we want to consider the
      // possibility that libpci may not return the exact same name as gl
      // RENDERER string.
      candidates.push_back(gpu);
    }
    if (gpu_active == NULL && candidates.size() == 1)
      gpu_active = candidates[0];
  }
  if (gpu_active != NULL)
    gpu_info->SetVideoCardInfo(gpu_active->vendor_id, gpu_active->device_id);
  (interface->pci_cleanup)(access);
  FinalizeLibPci(&interface);
  return (gpu_active != NULL);
}

bool CollectDriverInfoGL(GPUInfo* gpu_info) {
  DCHECK(gpu_info);

  std::string gl_version_string = gpu_info->gl_version_string();
  std::vector<std::string> pieces;
  base::SplitStringAlongWhitespace(gl_version_string, &pieces);
  // In linux, the gl version string might be in the format of
  //   GLVersion DriverVendor DriverVersion
  if (pieces.size() < 3)
    return false;

  std::string driver_version = pieces[2];
  size_t pos = driver_version.find_first_not_of("0123456789.");
  if (pos == 0)
    return false;
  if (pos != std::string::npos)
    driver_version = driver_version.substr(0, pos);

  gpu_info->SetDriverInfo(pieces[1], driver_version, "");
  return true;
}

}  // namespace gpu_info_collector
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX65N/RX651 DRW2D マネージャー
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2019 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX65x/drw2d.hpp"
#include "RX65x/glcdc_def.hpp"

#include "dave_base.h"
#include "dave_videomodes.h"
#include "dave_driver.h"

#include "common/vtx.hpp"

extern "C" {
	extern void drw_int_isr(void);	// drw2d library interrupt handler
};

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  DRW2D 制御／マネージャー
		@param[in]	DRW		DRW2D 制御クラス
		@param[in]	XSIZE	X 方向ピクセルサイズ
		@param[in]	YSIZE	Y 方向ピクセルサイズ
		@param[in]	PXT		ピクセル・タイプ
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class DRW, int16_t XSIZE, int16_t YSIZE, glcdc_def::PIX_TYPE PXT>
	class drw2d_mgr {

		void*	fb_;

		d2_device*	d2_;
		d2_renderbuffer*	rb_;

		d2_color	color_;
		vtx::srect	clip_;
		uint16_t	pen_size_;
		bool		set_color_;
		bool		set_clip_;

		int32_t		last_error_;

		d2_color	clut_[256];

		static uint32_t get_mode_()
		{
			switch(PXT) {
			case glcdc_def::PIX_TYPE::RGB888:
				return d2_mode_argb8888;
			case glcdc_def::PIX_TYPE::RGB565:
				return d2_mode_rgb565;
			case glcdc_def::PIX_TYPE::CLUT8:
				return d2_mode_i8;
			case glcdc_def::PIX_TYPE::CLUT4:
				return d2_mode_i4;
			case glcdc_def::PIX_TYPE::CLUT1:
				return d2_mode_i1;
			default:
				return d2_mode_rgb565;
			}
		}

		void setup_()
		{
			auto mode = get_mode_();
			d2_framebuffer(d2_, fb_, XSIZE, XSIZE, YSIZE, mode);
			d2_selectrenderbuffer(d2_, rb_);
			if(!set_color_) {
				d2_setcolor(d2_, 0, color_);
				set_color_ = true;
			}
			if(!set_clip_) {
				d2_cliprect(d2_, clip_.org.x, clip_.org.y, clip_.size.x, clip_.size.y);
				set_clip_ = true;
			}
		}
	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクタ
			@param[in]	fb	フレームバッファポインター
		*/
		//-----------------------------------------------------------------//
		drw2d_mgr(void* fb) noexcept : fb_(fb), d2_(nullptr), rb_(nullptr),
			color_(0xffffffff), clip_(0, 0, XSIZE, YSIZE), pen_size_(4),
			set_color_(false), set_clip_(false), last_error_(D2_OK)
		{ }

		//-----------------------------------------------------------------//
		/*!
			@brief	ハードウェアーバージョンを取得
			@return ハードウェアーバージョン
		*/
		//-----------------------------------------------------------------//
		uint16_t get_version() const noexcept { return DRW::HWVER.REV(); }

		//-----------------------------------------------------------------//
		/*!
			@brief	ハードウェアー仕様の表示
		*/
		//-----------------------------------------------------------------//
		void list_info() const noexcept
		{
			utils::format("REV:             0x%03X\n") % get_version();
			utils::format("Alpha Blend:       %d\n") % static_cast<uint16_t>(DRW::HWVER.ACBLD());
			utils::format("Clomakey:          %d\n") % static_cast<uint16_t>(DRW::HWVER.COLKEY());
			utils::format("Texture CLUT:      %s\n") % (DRW::HWVER.TEXCLUT256() ? "256" : "16");
			utils::format("RLE unit:          %d\n") % static_cast<uint16_t>(DRW::HWVER.RLEUNIT());
			utils::format("Texture CLUT func: %d\n") % static_cast<uint16_t>(DRW::HWVER.TEXCLUT());
			utils::format("Pefrmance CNT:     %d\n") % static_cast<uint16_t>(DRW::HWVER.PERFCNT());
			utils::format("Texture CASH:      %d\n") % static_cast<uint16_t>(DRW::HWVER.TXCACHE());
			utils::format("FB CASH:           %d\n") % static_cast<uint16_t>(DRW::HWVER.FBCACHE());
			utils::format("Display List R:    %d\n") % static_cast<uint16_t>(DRW::HWVER.DLR());
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	開始
			@param[in]	dlis	ディスプレイリストエントリー初期化サイズ
			@param[in]	stsz	ディスプレイリストエントリーステップサイズ
			@return 成功なら「true」
		*/
		//-----------------------------------------------------------------//
		bool start(uint32_t dlis = 20, uint32_t stsz = 20) noexcept
		{
			// DRW2D power management
			power_mgr::turn(DRW::get_peripheral());

			DRW::SIZE.X = XSIZE;
			DRW::SIZE.Y = YSIZE;

			icu_mgr::install_group_task(DRW::get_irq_vec(), drw_int_isr);

			// initialization Dave2D
			d2_ = d2_opendevice(0);
			d2_inithw(d2_, 0);
			rb_ = d2_newrenderbuffer(d2_, dlis, stsz);

			clut_[0] = 0xff000000;
			clut_[1] = 0xffffffff;

			return true;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	停止
		*/
		//-----------------------------------------------------------------//
		void stop() noexcept
		{
			d2_closedevice(d2_);
			d2_ = nullptr;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	カラーの設定
			@param[in]	color	カラー
		*/
		//-----------------------------------------------------------------//
		void set_color(d2_color color) noexcept
		{
			color_ = color;
			set_color_ = false;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	クリッピング領域の設定
			@param[in]	clip	クリッピング領域
		*/
		//-----------------------------------------------------------------//
		void set_clip(const vtx::srect& clip) noexcept
		{
			clip_ = clip;
			set_clip_ = false;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	ペンサイズの設定
			@param[in]	size	ペンサイズ（ピクセル）
		*/
		//-----------------------------------------------------------------//
		void set_pen_size(uint16_t size) noexcept { pen_size_ = size; }

		//-----------------------------------------------------------------//
		/*!
			@brief	ペンサイズの取得
			@return ペンサイズ（ピクセル）
		*/
		//-----------------------------------------------------------------//
		uint16_t get_pen_size() const noexcept { return pen_size_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	DRW2D フレーム・セットアップ
		*/
		//-----------------------------------------------------------------//
		void setup_frame()
		{
			set_clip_ = false;
			setup_();
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	全クリア
			@return エラー無い場合「true」
		*/
		//-----------------------------------------------------------------//
		bool clear() noexcept
		{
			setup_();
			last_error_ = d2_clear(d2_, color_);

			d2_executerenderbuffer(d2_, rb_, 0);
			d2_flushframe(d2_);
			return last_error_ == D2_OK;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	ライン描画
			@param[in]	org		開始位置
			@param[in]	end		終端位置
			@return エラー無い場合「true」
		*/
		//-----------------------------------------------------------------//
		bool line(const vtx::spos& org, const vtx::spos& end) noexcept
		{
			setup_();
			last_error_ = d2_renderline(d2_, org.x * 16, org.y * 16, end.x * 16, end.y * 16,
				pen_size_ * 16, d2_le_exclude_none);

			d2_executerenderbuffer(d2_, rb_, 0);
			d2_flushframe(d2_);
			return last_error_ == D2_OK;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	サークル描画
			@param[in]	org		中心位置
			@param[in]	r		半径
			@param[in]	w		幅（０の場合 fill）
			@return エラー無い場合「true」
		*/
		//-----------------------------------------------------------------//
		bool circle(const vtx::spos& org, int16_t r, int16_t w = 0)
		{
			setup_();
			last_error_ = d2_rendercircle(d2_, org.x * 16, org.y * 16, r * 16, w * 16);

			d2_executerenderbuffer(d2_, rb_, 0);
			d2_flushframe(d2_);
			return last_error_ == D2_OK;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	ボックス描画
			@param[in]	org		基点
			@param[in]	size	サイズ
			@return エラー無い場合「true」
		*/
		//-----------------------------------------------------------------//
		bool box(const vtx::spos& org, const vtx::spos& size)
		{
			setup_();
			last_error_ = d2_renderbox(d2_, org.x * 16, org.y * 16, size.x * 16, size.y * 16);

			d2_executerenderbuffer(d2_, rb_, 0);
			d2_flushframe(d2_);
			return last_error_ == D2_OK;
		}

		void copy_bitmap(const vtx::spos& pos)
		{
			d2_settexclut(d2_, clut_);

			static const uint8_t src[8] = {
				0b11111111,
				0b11111101,
				0b11111001,
				0b11110001,
				0b11100001,
				0b11000001,
				0b10000001,
				0b11111111
			};

			auto mode = get_mode_();
			d2_framebuffer(d2_, fb_, XSIZE, XSIZE, YSIZE, mode);
			d2_selectrenderbuffer(d2_, rb_);
			d2_setblitsrc(d2_, (void*)src, 8, 8, 8, d2_mode_i1);
			d2_blitcopy(d2_, 8, 8,
				0, 0, 8 * 16, 8 * 16, pos.x * 16, pos.y * 16, d2_bf_usealpha);

			d2_executerenderbuffer(d2_, rb_, 0);
			d2_flushframe(d2_);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	描画フラッシュ
		*/
		//-----------------------------------------------------------------//
		void flush() noexcept { d2_flushframe(d2_); }
	};
}
<commit_msg>update: test for frame renderring<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX65N/RX651 DRW2D マネージャー
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2019 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX65x/drw2d.hpp"
#include "RX65x/glcdc_def.hpp"

#include "dave_base.h"
#include "dave_videomodes.h"
#include "dave_driver.h"

#include "common/vtx.hpp"

extern "C" {
	extern void drw_int_isr(void);	// drw2d library interrupt handler
};

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  DRW2D 制御／マネージャー
		@param[in]	GLC		グラフィックス・コントローラー・クラス
		@param[in]	DRW		DRW2D 制御クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class GLC, class DRW>
	class drw2d_mgr {

		GLC&		glc_;

		d2_device*	d2_;
		d2_renderbuffer*	rb_;

		d2_color	color_;
		vtx::srect	clip_;
		int16_t		pen_size_;
		int16_t		scale_;
		bool		set_color_;
		bool		set_clip_;

		int32_t		last_error_;

		d2_color	clut_[256];

		static uint32_t get_mode_()
		{
			switch(GLC::get_pxt()) {
			case glcdc_def::PIX_TYPE::RGB888:
				return d2_mode_argb8888;
			case glcdc_def::PIX_TYPE::RGB565:
				return d2_mode_rgb565;
			case glcdc_def::PIX_TYPE::CLUT8:
				return d2_mode_i8;
			case glcdc_def::PIX_TYPE::CLUT4:
				return d2_mode_i4;
			case glcdc_def::PIX_TYPE::CLUT1:
				return d2_mode_i1;
			default:
				return d2_mode_rgb565;
			}
		}

		void setup_()
		{
			auto mode = get_mode_();
			d2_framebuffer(d2_, glc_.get_layer2(), GLC::get_xsize(), GLC::get_xsize(), GLC::get_ysize(), mode);
//			d2_selectrenderbuffer(d2_, rb_);
			if(!set_color_) {
				d2_setcolor(d2_, 0, color_);
				set_color_ = true;
			}
			if(!set_clip_) {
				d2_cliprect(d2_, clip_.org.x, clip_.org.y, clip_.size.x, clip_.size.y);
				set_clip_ = true;
			}
		}
	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクタ
			@param[in]	glc	GLC クラスの参照
		*/
		//-----------------------------------------------------------------//
		drw2d_mgr(GLC& glc) noexcept : glc_(glc), d2_(nullptr), rb_(nullptr),
			color_(0xffffffff), clip_(0, 0, GLC::get_xsize(), GLC::get_ysize()),
			pen_size_(16), scale_(16),
			set_color_(false), set_clip_(false), last_error_(D2_OK)
		{ }

		//-----------------------------------------------------------------//
		/*!
			@brief	ハードウェアーバージョンを取得
			@return ハードウェアーバージョン
		*/
		//-----------------------------------------------------------------//
		uint16_t get_version() const noexcept { return DRW::HWVER.REV(); }

		//-----------------------------------------------------------------//
		/*!
			@brief	ハードウェアー仕様の表示
		*/
		//-----------------------------------------------------------------//
		void list_info() const noexcept
		{
			utils::format("REV:             0x%03X\n") % get_version();
			utils::format("Alpha Blend:       %d\n") % static_cast<uint16_t>(DRW::HWVER.ACBLD());
			utils::format("Clomakey:          %d\n") % static_cast<uint16_t>(DRW::HWVER.COLKEY());
			utils::format("Texture CLUT:      %s\n") % (DRW::HWVER.TEXCLUT256() ? "256" : "16");
			utils::format("RLE unit:          %d\n") % static_cast<uint16_t>(DRW::HWVER.RLEUNIT());
			utils::format("Texture CLUT func: %d\n") % static_cast<uint16_t>(DRW::HWVER.TEXCLUT());
			utils::format("Pefrmance CNT:     %d\n") % static_cast<uint16_t>(DRW::HWVER.PERFCNT());
			utils::format("Texture CASH:      %d\n") % static_cast<uint16_t>(DRW::HWVER.TXCACHE());
			utils::format("FB CASH:           %d\n") % static_cast<uint16_t>(DRW::HWVER.FBCACHE());
			utils::format("Display List R:    %d\n") % static_cast<uint16_t>(DRW::HWVER.DLR());
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	開始
			@param[in]	dlis	ディスプレイリストエントリー初期化サイズ
			@param[in]	stsz	ディスプレイリストエントリーステップサイズ
			@return 成功なら「true」
		*/
		//-----------------------------------------------------------------//
		bool start(uint32_t dlis = 20, uint32_t stsz = 20) noexcept
		{
			// DRW2D power management
			power_mgr::turn(DRW::get_peripheral());

			// initialization Dave2D
			d2_ = d2_opendevice(0);
			uint32_t init_flag = 0;
			d2_inithw(d2_, init_flag);

			icu_mgr::install_group_task(DRW::get_irq_vec(), drw_int_isr);
			icu_mgr::set_level(ICU::VECTOR::GROUPAL1, 2);

			rb_ = d2_newrenderbuffer(d2_, dlis, stsz);

			clut_[0] = 0xff000000;
			clut_[1] = 0xffffffff;

			return true;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	停止
		*/
		//-----------------------------------------------------------------//
		void stop() noexcept
		{
			d2_closedevice(d2_);
			d2_ = nullptr;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	カラーの設定
			@param[in]	color	カラー
		*/
		//-----------------------------------------------------------------//
		void set_color(d2_color color) noexcept
		{
			color_ = color;
			set_color_ = false;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	クリッピング領域の設定
			@param[in]	clip	クリッピング領域
		*/
		//-----------------------------------------------------------------//
		void set_clip(const vtx::srect& clip) noexcept
		{
			clip_ = clip;
			set_clip_ = false;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	ペンサイズの設定
			@param[in]	size	ペンサイズ（1/16 pixel）
		*/
		//-----------------------------------------------------------------//
		void set_pen_size(int16_t size) noexcept { pen_size_ = size; }

		//-----------------------------------------------------------------//
		/*!
			@brief	ペンサイズの取得
			@return ペンサイズ（1/16 pixel）
		*/
		//-----------------------------------------------------------------//
		auto get_pen_size() const noexcept { return pen_size_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	スケールの設定
			@param[in]	scale	スケール（等倍１６）
		*/
		//-----------------------------------------------------------------//
		void set_scale(int16_t scale = 16) noexcept { scale_ = scale; }

		//-----------------------------------------------------------------//
		/*!
			@brief	スケールの取得
			@return スケール（1/16 pixel）
		*/
		//-----------------------------------------------------------------//
		auto get_scale() const noexcept { return scale_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	DRW2D フレーム・セットアップ
		*/
		//-----------------------------------------------------------------//
		void setup_frame()
		{
			set_clip_ = false;
			setup_();
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	全クリア
			@return エラー無い場合「true」
		*/
		//-----------------------------------------------------------------//
		bool clear() noexcept
		{
			setup_();
			last_error_ = d2_clear(d2_, color_);

			d2_executerenderbuffer(d2_, rb_, 0);
			d2_flushframe(d2_);
			return last_error_ == D2_OK;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	ライン描画
			@param[in]	org		開始位置
			@param[in]	end		終端位置
			@return エラー無い場合「true」
		*/
		//-----------------------------------------------------------------//
		bool line(const vtx::spos& org, const vtx::spos& end) noexcept
		{
			setup_();
			last_error_ = d2_renderline(d2_, org.x * scale_, org.y * scale_,
				end.x * scale_, end.y * scale_, pen_size_, d2_le_exclude_none);

			d2_executerenderbuffer(d2_, rb_, 0);
			d2_flushframe(d2_);
			return last_error_ == D2_OK;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	サークル描画
			@param[in]	org		中心位置
			@param[in]	r		半径
			@param[in]	w		幅（０の場合 fill）
			@return エラー無い場合「true」
		*/
		//-----------------------------------------------------------------//
		bool circle(const vtx::spos& org, int16_t r, int16_t w = 0)
		{
			setup_();
			last_error_ = d2_rendercircle(d2_, org.x * scale_, org.y * scale_,
				r * scale_, w * scale_);

			d2_executerenderbuffer(d2_, rb_, 0);
			d2_flushframe(d2_);
			return last_error_ == D2_OK;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	ボックス描画
			@param[in]	org		基点
			@param[in]	size	サイズ
			@return エラー無い場合「true」
		*/
		//-----------------------------------------------------------------//
		bool box(const vtx::spos& org, const vtx::spos& size)
		{
			setup_();
			last_error_ = d2_renderbox(d2_, org.x * scale_, org.y * scale_,
				size.x * scale_, size.y * scale_);

			d2_executerenderbuffer(d2_, rb_, 0);
			d2_flushframe(d2_);
			return last_error_ == D2_OK;
		}

		void copy_bitmap(const vtx::spos& pos)
		{
			d2_settexclut(d2_, clut_);

			static const uint8_t src[8] = {
				0b11111111,
				0b11111101,
				0b11111001,
				0b11110001,
				0b11100001,
				0b11000001,
				0b10000001,
				0b11111111
			};

			auto mode = get_mode_();
			d2_framebuffer(d2_, glc_.get_layer2(), GLC::get_xsize(), GLC::get_xsize(), GLC::get_ysize(), mode);
			d2_selectrenderbuffer(d2_, rb_);
			d2_setblitsrc(d2_, (void*)src, 8, 8, 8, d2_mode_i1);
			d2_blitcopy(d2_, 8, 8,
				0, 0, 8 * 16, 8 * 16, pos.x * 16, pos.y * 16, d2_bf_usealpha);

			d2_executerenderbuffer(d2_, rb_, 0);
			d2_flushframe(d2_);
		}

		void test_frame(d2_color col, int16_t rad)
		{
			d2_startframe(d2_);
			auto xs = GLC::get_xsize();
			auto ys = GLC::get_ysize();
			d2_framebuffer(d2_, glc_.get_layer2(), xs, xs, ys, d2_mode_rgb565);
			d2_cliprect(d2_, 0, 0, xs * 16, ys * 16);
			d2_clear(d2_, 0x000000);
			d2_setcolor(d2_, 0, col);
//			d2_renderbox(d2_, 480/2*16, 272/2*16, rad*16, rad*16);
			d2_rendercircle(d2_, 480/2*16, 272/2*16, rad*16, 0);
			d2_endframe(d2_);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	描画フラッシュ
		*/
		//-----------------------------------------------------------------//
		void flush() noexcept { d2_flushframe(d2_); }
	};
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cusshow.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 03:10:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

#include "sdiocmpt.hxx"
#include "cusshow.hxx"
#include "sdpage.hxx"
#include "drawdoc.hxx"

// #90477#
#ifndef _TOOLS_TENCCVT_HXX
#include <tools/tenccvt.hxx>
#endif

using namespace ::com::sun::star;

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/
SdCustomShow::SdCustomShow(SdDrawDocument* pDrawDoc)
  : List(),
  pDoc(pDrawDoc)
{
}

/*************************************************************************
|*
|* Copy-Ctor
|*
\************************************************************************/
SdCustomShow::SdCustomShow( const SdCustomShow& rShow )
    : List( rShow )
{
    aName = rShow.GetName();
    pDoc = rShow.GetDoc();
}

SdCustomShow::SdCustomShow(SdDrawDocument* pDrawDoc, ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xShow )
  : List(),
  pDoc(pDrawDoc),
  mxUnoCustomShow( xShow )
{
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
SdCustomShow::~SdCustomShow()
{
    uno::Reference< uno::XInterface > xShow( mxUnoCustomShow );
    uno::Reference< lang::XComponent > xComponent( xShow, uno::UNO_QUERY );
    if( xComponent.is() )
        xComponent->dispose();
}

/*************************************************************************
|*
|* Inserter fuer SvStream zum Speichern
|*
\************************************************************************/
//BFS02SvStream& operator << (SvStream& rOut, const SdCustomShow& rCustomShow)
//BFS02{
//BFS02 // Letzter Parameter ist die aktuelle Versionsnummer des Codes
//BFS02 SdIOCompat aIO(rOut, STREAM_WRITE, 0);
//BFS02
//BFS02 // Name
//BFS02 // #90477# rOut.WriteByteString( rCustomShow.aName, ::GetStoreCharSet( gsl_getSystemTextEncoding() ) );
//BFS02 rOut.WriteByteString(rCustomShow.aName,
//BFS02     GetSOStoreTextEncoding(gsl_getSystemTextEncoding(), (sal_uInt16)rOut.GetVersion()));
//BFS02
//BFS02 // Anzahl Seiten
//BFS02 UINT32 nCount = rCustomShow.Count();
//BFS02 rOut << nCount;
//BFS02
//BFS02 for (UINT32 i = 0; i < nCount; i++)
//BFS02 {
//BFS02     // Seite aus Liste holen
//BFS02     SdPage* pPage = (SdPage*) rCustomShow.GetObject(i);
//BFS02
//BFS02     if (pPage)
//BFS02     {
//BFS02         // SdPage-Seitennummer
//BFS02         UINT16 nPageNum = (pPage->GetPageNum() - 1) / 2;
//BFS02         rOut << nPageNum;
//BFS02     }
//BFS02 }
//BFS02
//BFS02 return rOut;
//BFS02}

/*************************************************************************
|*
|* Extractor fuer SvStream zum Laden
|*
\************************************************************************/
//BFS02SvStream& operator >> (SvStream& rIn, SdCustomShow& rCustomShow)
//BFS02{
//BFS02 SdIOCompat aIO(rIn, STREAM_READ);
//BFS02
//BFS02 // Name
//BFS02 // #90477# rIn.ReadByteString( rCustomShow.aName, ::GetStoreCharSet( gsl_getSystemTextEncoding() ) );
//BFS02 rIn.ReadByteString(rCustomShow.aName,
//BFS02     GetSOLoadTextEncoding(gsl_getSystemTextEncoding(), (sal_uInt16)rIn.GetVersion()));
//BFS02
//BFS02 // Anzahl Seiten
//BFS02 UINT32 nCount = 0;
//BFS02 rIn >> nCount;
//BFS02
//BFS02 rCustomShow.Clear();
//BFS02
//BFS02 for (UINT32 i = 0; i < nCount; i++)
//BFS02 {
//BFS02     // Seitennummer
//BFS02     UINT16 nPageNum;
//BFS02     rIn >> nPageNum;
//BFS02
//BFS02     // Seite in Liste einfuegen
//BFS02     SdPage* pPage = (SdPage*) rCustomShow.pDoc->GetSdPage(nPageNum, PK_STANDARD);
//BFS02     rCustomShow.Insert(pPage, LIST_APPEND);
//BFS02 }
//BFS02
//BFS02 return rIn;
//BFS02}

extern uno::Reference< uno::XInterface > createUnoCustomShow( SdCustomShow* pShow );

uno::Reference< uno::XInterface > SdCustomShow::getUnoCustomShow()
{
    // try weak reference first
    uno::Reference< uno::XInterface > xShow( mxUnoCustomShow );

    if( !xShow.is() )
    {
        xShow = createUnoCustomShow( this );
    }

    return xShow;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.6.280); FILE MERGED 2006/09/01 17:36:41 kaib 1.6.280.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cusshow.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 18:13:53 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

#include "sdiocmpt.hxx"
#include "cusshow.hxx"
#include "sdpage.hxx"
#include "drawdoc.hxx"

// #90477#
#ifndef _TOOLS_TENCCVT_HXX
#include <tools/tenccvt.hxx>
#endif

using namespace ::com::sun::star;

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/
SdCustomShow::SdCustomShow(SdDrawDocument* pDrawDoc)
  : List(),
  pDoc(pDrawDoc)
{
}

/*************************************************************************
|*
|* Copy-Ctor
|*
\************************************************************************/
SdCustomShow::SdCustomShow( const SdCustomShow& rShow )
    : List( rShow )
{
    aName = rShow.GetName();
    pDoc = rShow.GetDoc();
}

SdCustomShow::SdCustomShow(SdDrawDocument* pDrawDoc, ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xShow )
  : List(),
  pDoc(pDrawDoc),
  mxUnoCustomShow( xShow )
{
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
SdCustomShow::~SdCustomShow()
{
    uno::Reference< uno::XInterface > xShow( mxUnoCustomShow );
    uno::Reference< lang::XComponent > xComponent( xShow, uno::UNO_QUERY );
    if( xComponent.is() )
        xComponent->dispose();
}

/*************************************************************************
|*
|* Inserter fuer SvStream zum Speichern
|*
\************************************************************************/
//BFS02SvStream& operator << (SvStream& rOut, const SdCustomShow& rCustomShow)
//BFS02{
//BFS02 // Letzter Parameter ist die aktuelle Versionsnummer des Codes
//BFS02 SdIOCompat aIO(rOut, STREAM_WRITE, 0);
//BFS02
//BFS02 // Name
//BFS02 // #90477# rOut.WriteByteString( rCustomShow.aName, ::GetStoreCharSet( gsl_getSystemTextEncoding() ) );
//BFS02 rOut.WriteByteString(rCustomShow.aName,
//BFS02     GetSOStoreTextEncoding(gsl_getSystemTextEncoding(), (sal_uInt16)rOut.GetVersion()));
//BFS02
//BFS02 // Anzahl Seiten
//BFS02 UINT32 nCount = rCustomShow.Count();
//BFS02 rOut << nCount;
//BFS02
//BFS02 for (UINT32 i = 0; i < nCount; i++)
//BFS02 {
//BFS02     // Seite aus Liste holen
//BFS02     SdPage* pPage = (SdPage*) rCustomShow.GetObject(i);
//BFS02
//BFS02     if (pPage)
//BFS02     {
//BFS02         // SdPage-Seitennummer
//BFS02         UINT16 nPageNum = (pPage->GetPageNum() - 1) / 2;
//BFS02         rOut << nPageNum;
//BFS02     }
//BFS02 }
//BFS02
//BFS02 return rOut;
//BFS02}

/*************************************************************************
|*
|* Extractor fuer SvStream zum Laden
|*
\************************************************************************/
//BFS02SvStream& operator >> (SvStream& rIn, SdCustomShow& rCustomShow)
//BFS02{
//BFS02 SdIOCompat aIO(rIn, STREAM_READ);
//BFS02
//BFS02 // Name
//BFS02 // #90477# rIn.ReadByteString( rCustomShow.aName, ::GetStoreCharSet( gsl_getSystemTextEncoding() ) );
//BFS02 rIn.ReadByteString(rCustomShow.aName,
//BFS02     GetSOLoadTextEncoding(gsl_getSystemTextEncoding(), (sal_uInt16)rIn.GetVersion()));
//BFS02
//BFS02 // Anzahl Seiten
//BFS02 UINT32 nCount = 0;
//BFS02 rIn >> nCount;
//BFS02
//BFS02 rCustomShow.Clear();
//BFS02
//BFS02 for (UINT32 i = 0; i < nCount; i++)
//BFS02 {
//BFS02     // Seitennummer
//BFS02     UINT16 nPageNum;
//BFS02     rIn >> nPageNum;
//BFS02
//BFS02     // Seite in Liste einfuegen
//BFS02     SdPage* pPage = (SdPage*) rCustomShow.pDoc->GetSdPage(nPageNum, PK_STANDARD);
//BFS02     rCustomShow.Insert(pPage, LIST_APPEND);
//BFS02 }
//BFS02
//BFS02 return rIn;
//BFS02}

extern uno::Reference< uno::XInterface > createUnoCustomShow( SdCustomShow* pShow );

uno::Reference< uno::XInterface > SdCustomShow::getUnoCustomShow()
{
    // try weak reference first
    uno::Reference< uno::XInterface > xShow( mxUnoCustomShow );

    if( !xShow.is() )
    {
        xShow = createUnoCustomShow( this );
    }

    return xShow;
}
<|endoftext|>


<commit_before>// File_Mpeg4_TimeCode - Info for MPEG-4 TimeCode  files
// Copyright (C) 2009-2011 MediaArea.net SARL, Info@MediaArea.net
//
// This library is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Compilation conditions
#include "MediaInfo/Setup.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_MPEG4_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Multiple/File_Mpeg4_TimeCode.h"
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Format
//***************************************************************************

//---------------------------------------------------------------------------
void File_Mpeg4_TimeCode::FileHeader_Parse()
{
    //Parsing
    int32u Position;
    while (Element_Offset<Element_Size)
        Get_B4 (Position,                                       "Position");

    //Filling
    Accept("TimeCode");

    if (FrameRate)
    {
        int64s Pos=Position;
        if (NegativeTimes)
            Pos=(int32s)Position;
        if (StreamKind==Stream_General)
        {
            //No link with a track, we do all
            Stream_Prepare(Stream_Video);
            Fill(Stream_Video, 0, Video_Delay, Pos*1000/FrameRate, 0);
            Fill(Stream_Video, 0, Video_Delay_Source, "Container");

            Stream_Prepare(Stream_Audio);
            Fill(Stream_Audio, 0, Audio_Delay, Pos*1000/FrameRate, 0);
            Fill(Stream_Video, 0, Video_Delay_Source, "Container");
        }
        else
        {
            Stream_Prepare(StreamKind);
            Fill(StreamKind, 0, Fill_Parameter(StreamKind_Last, Generic_Delay), Pos*1000/FrameRate, 0);
            Fill(StreamKind, 0, Fill_Parameter(StreamKind_Last, Generic_Delay_Source), "Container");
        }
    }

    Finish("TimeCode");
}

}

#endif //MEDIAINFO_MPEG4_YES
<commit_msg><commit_after>// File_Mpeg4_TimeCode - Info for MPEG-4 TimeCode  files
// Copyright (C) 2009-2011 MediaArea.net SARL, Info@MediaArea.net
//
// This library is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Compilation conditions
#include "MediaInfo/Setup.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_MPEG4_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Multiple/File_Mpeg4_TimeCode.h"
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Format
//***************************************************************************

//---------------------------------------------------------------------------
void File_Mpeg4_TimeCode::FileHeader_Parse()
{
    if (Element_Offset>=Element_Size)
        return;

    //Parsing
    int32u Position;
    while (Element_Offset<Element_Size)
        Get_B4 (Position,                                       "Position");

    //Filling
    Accept("TimeCode");

    if (FrameRate)
    {
        int64s Pos=Position;
        if (NegativeTimes)
            Pos=(int32s)Position;
        if (StreamKind==Stream_General)
        {
            //No link with a track, we do all
            Stream_Prepare(Stream_Video);
            Fill(Stream_Video, 0, Video_Delay, Pos*1000/FrameRate, 0);
            Fill(Stream_Video, 0, Video_Delay_Source, "Container");

            Stream_Prepare(Stream_Audio);
            Fill(Stream_Audio, 0, Audio_Delay, Pos*1000/FrameRate, 0);
            Fill(Stream_Video, 0, Video_Delay_Source, "Container");
        }
        else
        {
            Stream_Prepare(StreamKind);
            Fill(StreamKind, 0, Fill_Parameter(StreamKind_Last, Generic_Delay), Pos*1000/FrameRate, 0);
            Fill(StreamKind, 0, Fill_Parameter(StreamKind_Last, Generic_Delay_Source), "Container");
        }
    }

    Finish("TimeCode");
}

}

#endif //MEDIAINFO_MPEG4_YES
<|endoftext|>


<commit_before>#include "LARA2GUN.H"

#include "SPECIFIC.H"
#include "LARA.H"
#include "LARAFIRE.H"
#ifdef PC_VERSION
#include "GAME.H"
#else
#include "SETUP.H"
#endif
#include "DRAW.H"
#include "OBJECTS.H"
#include "EFFECTS.H"
#include "SOUND.H"

static struct PISTOL_DEF PistolTable[4] =
{
	{ LARA, 0, 0, 0, 0 },
	{ PISTOLS_ANIM, 4, 5, 0xD, 0x18 },
	{ REVOLVER_ANIM , 7, 8, 0xF, 0x1D },
	{ UZI_ANIM, 4, 5, 0xD, 0x18 }
};

void AnimatePistols(int weapon_type)
{
	UNIMPLEMENTED();
}

void PistolHandler(int weapon_type)
{
	UNIMPLEMENTED();
}

void undraw_pistol_mesh_right(int weapon_type)//44968(<), 44DCC(<) (F)
{
	WeaponObject(weapon_type);
	lara.mesh_ptrs[LM_RHAND] = meshes[objects[LARA].mesh_index + 2 * LM_RHAND];
	switch (weapon_type)
	{
	case WEAPON_PISTOLS:
		lara.holster = LARA_HOLSTERS_PISTOLS;
		break;
	case WEAPON_REVOLVER:
		lara.holster = LARA_HOLSTERS_REVOLVER;
		break;
	case WEAPON_UZI:
		lara.holster = LARA_HOLSTERS_UZIS;
		break;
	}
}

void undraw_pistol_mesh_left(int weapon_type)//448F0(<), 44D54(<) (F)
{
	if(weapon_type != WEAPON_REVOLVER)
	{
		WeaponObject(weapon_type);
		lara.mesh_ptrs[LM_LHAND] = meshes[objects[LARA].mesh_index + 2 * LM_LHAND];
		switch (weapon_type)
		{
		case WEAPON_PISTOLS:
			lara.holster = LARA_HOLSTERS_PISTOLS;
			break;
		case WEAPON_UZI:
			lara.holster = LARA_HOLSTERS_UZIS;
			break;
		}
	}
}

void draw_pistol_meshes(int weapon_type)// (F)
{
	lara.holster = LARA_HOLSTERS;
	lara.mesh_ptrs[LM_RHAND] = meshes[objects[WeaponObjectMesh(weapon_type)].mesh_index + 2 * LM_RHAND];

	if (weapon_type != WEAPON_REVOLVER)
	{
		lara.mesh_ptrs[LM_LHAND] = meshes[objects[WeaponObjectMesh(weapon_type)].mesh_index + 2 * LM_LHAND];
	}
}

void ready_pistols(int weapon_type)// (F)
{
	lara.gun_status = LG_READY;
	lara.left_arm.z_rot = 0;
	lara.left_arm.y_rot = 0;
	lara.left_arm.x_rot = 0;
	lara.right_arm.z_rot = 0;
	lara.right_arm.y_rot = 0;
	lara.right_arm.x_rot = 0;
	lara.right_arm.frame_number = 0;
	lara.left_arm.frame_number = 0;
	lara.target = 0;
	lara.right_arm.lock = 0;
	lara.left_arm.lock = 0;
	lara.right_arm.frame_base = lara.left_arm.frame_base = objects[WeaponObject(weapon_type)].frame_base;
}

void undraw_pistols(int weapon_type)//
{
	UNIMPLEMENTED();
}

void draw_pistols(int weapon_type)//443B4, 44818 (F)
{
	struct PISTOL_DEF* p = &PistolTable[lara.gun_type];//$a1
	short ani = lara.left_arm.frame_number + 1;//$s1

	//a3 = p->Draw1Anim

	//v0 = p->RecoilAnim
	if (ani < p->Draw1Anim || p->RecoilAnim - 1 < ani)
	{
		//loc_44420
		ani = p->Draw1Anim;
	}
	else
	{

		//loc_44428
		if (ani == p->Draw2Anim)
		{
			draw_pistol_meshes(weapon_type);
			//a1 = lara_item
			//a0 = 6
			//a2 = 0;
			SoundEffect(SFX_LARA_HOLSTER_DRAW, &lara_item->pos, 0);
			//s0 = &lara.right_arm.frame_base
		}//loc_44460
		else if (ani == p->RecoilAnim - 1)
		{
			ready_pistols(weapon_type);
			ani = 0;
		}
	}

	set_arm_info(&lara.right_arm, ani);
	set_arm_info(&lara.left_arm, ani);
}

void set_arm_info(struct lara_arm* arm, int frame)// (F)
{
	struct PISTOL_DEF* def = &PistolTable[lara.gun_type];
	int anim_base = objects[def->ObjectNum].anim_index;

	if (frame >= def->Draw1Anim)
	{
		if (frame >= def->Draw2Anim)
		{
			if (frame >= def->RecoilAnim)
			{
				anim_base += 3;
			}
			else
			{
				anim_base += 2;
			}
		}
		else
		{
			anim_base += 1;
		}
	}

	arm->anim_number = anim_base;
	arm->frame_number = frame;
	arm->frame_base = anims[anim_base].frame_ptr;
}<commit_msg>[Game]: Correct set_arm_info.<commit_after>#include "LARA2GUN.H"

#include "SPECIFIC.H"
#include "LARA.H"
#include "LARAFIRE.H"
#ifdef PC_VERSION
#include "GAME.H"
#else
#include "SETUP.H"
#endif
#include "DRAW.H"
#include "OBJECTS.H"
#include "EFFECTS.H"
#include "SOUND.H"

static struct PISTOL_DEF PistolTable[4] =
{
	{ LARA, 0, 0, 0, 0 },
	{ PISTOLS_ANIM, 4, 5, 0xD, 0x18 },
	{ REVOLVER_ANIM , 7, 8, 0xF, 0x1D },
	{ UZI_ANIM, 4, 5, 0xD, 0x18 }
};

void AnimatePistols(int weapon_type)
{
	UNIMPLEMENTED();
}

void PistolHandler(int weapon_type)
{
	UNIMPLEMENTED();
}

void undraw_pistol_mesh_right(int weapon_type)//44968(<), 44DCC(<) (F)
{
	WeaponObject(weapon_type);
	lara.mesh_ptrs[LM_RHAND] = meshes[objects[LARA].mesh_index + 2 * LM_RHAND];
	switch (weapon_type)
	{
	case WEAPON_PISTOLS:
		lara.holster = LARA_HOLSTERS_PISTOLS;
		break;
	case WEAPON_REVOLVER:
		lara.holster = LARA_HOLSTERS_REVOLVER;
		break;
	case WEAPON_UZI:
		lara.holster = LARA_HOLSTERS_UZIS;
		break;
	}
}

void undraw_pistol_mesh_left(int weapon_type)//448F0(<), 44D54(<) (F)
{
	if(weapon_type != WEAPON_REVOLVER)
	{
		WeaponObject(weapon_type);
		lara.mesh_ptrs[LM_LHAND] = meshes[objects[LARA].mesh_index + 2 * LM_LHAND];
		switch (weapon_type)
		{
		case WEAPON_PISTOLS:
			lara.holster = LARA_HOLSTERS_PISTOLS;
			break;
		case WEAPON_UZI:
			lara.holster = LARA_HOLSTERS_UZIS;
			break;
		}
	}
}

void draw_pistol_meshes(int weapon_type)// (F)
{
	lara.holster = LARA_HOLSTERS;
	lara.mesh_ptrs[LM_RHAND] = meshes[objects[WeaponObjectMesh(weapon_type)].mesh_index + 2 * LM_RHAND];

	if (weapon_type != WEAPON_REVOLVER)
	{
		lara.mesh_ptrs[LM_LHAND] = meshes[objects[WeaponObjectMesh(weapon_type)].mesh_index + 2 * LM_LHAND];
	}
}

void ready_pistols(int weapon_type)// (F)
{
	lara.gun_status = LG_READY;
	lara.left_arm.z_rot = 0;
	lara.left_arm.y_rot = 0;
	lara.left_arm.x_rot = 0;
	lara.right_arm.z_rot = 0;
	lara.right_arm.y_rot = 0;
	lara.right_arm.x_rot = 0;
	lara.right_arm.frame_number = 0;
	lara.left_arm.frame_number = 0;
	lara.target = 0;
	lara.right_arm.lock = 0;
	lara.left_arm.lock = 0;
	lara.right_arm.frame_base = lara.left_arm.frame_base = objects[WeaponObject(weapon_type)].frame_base;
}

void undraw_pistols(int weapon_type)//
{
	UNIMPLEMENTED();
}

void draw_pistols(int weapon_type)//443B4, 44818 (F)
{
	struct PISTOL_DEF* p = &PistolTable[lara.gun_type];//$a1
	short ani = lara.left_arm.frame_number + 1;//$s1

	//a3 = p->Draw1Anim

	//v0 = p->RecoilAnim
	if (ani < p->Draw1Anim || p->RecoilAnim - 1 < ani)
	{
		//loc_44420
		ani = p->Draw1Anim;
	}
	else
	{

		//loc_44428
		if (ani == p->Draw2Anim)
		{
			draw_pistol_meshes(weapon_type);
			//a1 = lara_item
			//a0 = 6
			//a2 = 0;
			SoundEffect(SFX_LARA_HOLSTER_DRAW, &lara_item->pos, 0);
			//s0 = &lara.right_arm.frame_base
		}//loc_44460
		else if (ani == p->RecoilAnim - 1)
		{
			ready_pistols(weapon_type);
			ani = 0;
		}
	}

	set_arm_info(&lara.right_arm, ani);
	set_arm_info(&lara.left_arm, ani);
}

void set_arm_info(struct lara_arm* arm/*a3*/, int frame/*a1*/)//44308 (F)
{
	struct PISTOL_DEF* def = &PistolTable[lara.gun_type];//$a2
	int anim_base = objects[def->ObjectNum].anim_index;//$a0

	if (def->Draw1Anim != 0)
	{
		arm->anim_number = anim_base;
		//j loc_44388
	}
	else
	{
		//loc_44358
		if (frame >= def->Draw2Anim)
		{
			if (frame >= def->RecoilAnim)
			{
				//loc_44384
				arm->anim_number = anim_base + 3;
			}
			else
			{
				//loc_44384
				arm->anim_number = anim_base + 2;
			}
		}
		else
		{
			//loc_44384
			arm->anim_number = anim_base + 1;
		}
	}

	arm->frame_number = frame;
	arm->frame_base = anims[arm->anim_number].frame_ptr;
}
<|endoftext|>