<commit_before>/******************************************************************************
* Controller_Functions.cpp
*
* Contains the marchPID() and depth_controller functions
******************************************************************************/
#include "Mapper.h"

/******************************************************************************
* float marchPID()
*
* Takes in readings from the IMU and returns a value between -1 and 1 (-100% -
* +100%) that the port and starboard thrusters should run at
******************************************************************************/

float marchPID(pid_data_t PID, float input)
{
	float err = input - PID.setpoint;

	if(PID.period > 0 && err > PID.period/2)
	{
		err -= period;
	}

	// Calculating errors
	PID.perr = err;
	PID.derr = (err - PID.old)/(PID.dt);
	PID.ierr += PID.dt * (err);

	//Check for integrator saturation
	if(PID.ierr > PID.isat)
	{
		PID.ierr = PID.isat;
	}

	if(PID.ierr < -PID.isat)
	{
		PID.ierr = - PID.isat;
	}
	//Calculate motor output
	PID.output =	 PID.kp * PID.perr
						+ PID.ki * PID.ierr
						+ PID.kd * PID.derr;
	//Check for output saturation
	if(PID.output > PID.sat)
	{
		PID.output = PID.sat;
	}

	if(PID.output < -PID.sat)
	{
		PID.output = -PID.sat;
	}
	// set current input to be the old input //
	PID.old = err;

	return PID.output;
}

/******************************************************************************
 * int initialize_motors(int channels[3], float freq)
 *
 * Initializes the PWM board and the ESCs that run the motors
******************************************************************************/
int initialize_motors(int channels[3], float freq)
{
	// setup PCA9685 PWM board //
	int fd = pca9685Setup(PIN_BASE, PCA9685_ADDR, HERTZ);
	if (fd < 0)
	{
		printf("Error in setup\n");
		return fd;
	}

	// reset all PCA9685 PWM board output //
	pca9685PWMReset(fd);

	// set motor outputs to 0 to initialize ESCs //
	for( int i = 0; i < 3; i++ )
	{
		set_motor(i, 0);
	}
	return fd;
}

/******************************************************************************
 * float set_motor(int motornum, float percent)
 *
 * Takes in a value from -1 to 1 (-100 to +100%) and sets the motor
 * outputs accordingly
******************************************************************************/
float set_motor(int motornum, float percent)
{
	// Define characteristics of PWM pulse, microseconds
	float amplitude	 = PWM_HIGH_LIMIT - PWM_ZERO_VALUE;

	// Saturation limits
	if( percent >	 1.0) percent =	 1.0;
	if( percent < -1.0) percent = -1.0;

	// Deadzone check
	if( (percent < MOTOR_DEADZONE) && (percent > -MOTOR_DEADZONE) ) percent = 0.0;

	// Calculate corresponding pwm output value
	int motoroutput = percent * amplitude + PWM_ZERO_VALUE;

	// Spin those motors
	pwmWrite(motornum + PIN_BASE, motoroutput);

	#ifdef DEBUG
	// Print what we told the motor to spin at.
	printf("Set motor %d to %d \n", motornum, motoroutput);
	#endif

	return percent;
}
<commit_msg>PID to pid, like nice people<commit_after>/******************************************************************************
* Controller_Functions.cpp
*
* Contains the marchPID() and depth_controller functions
******************************************************************************/
#include "Mapper.h"

/******************************************************************************
* float marchPID()
*
* Takes in readings from the IMU and returns a value between -1 and 1 (-100% -
* +100%) that the port and starboard thrusters should run at
******************************************************************************/

float marchPID(pid_data_t pid, float input)
{
	float err = input - pid.setpoint;

	if(pid.period > 0 && err > pid.period/2)
	{
		err -= pid.period;
	}

	// Calculating errors
	pid.perr = err;
	pid.derr = (err - pid.old)/(pid.dt);
	pid.ierr += pid.dt * (err);

	//Check for integrator saturation
	if(pid.ierr > pid.isat)
	{
		pid.ierr = pid.isat;
	}

	if(pid.ierr < -pid.isat)
	{
		pid.ierr = - pid.isat;
	}
	//Calculate motor output
	pid.output =	 pid.kp * pid.perr
						+ pid.ki * pid.ierr
						+ pid.kd * pid.derr;
	//Check for output saturation
	if(pid.output > pid.sat)
	{
		pid.output = pid.sat;
	}

	if(pid.output < -pid.sat)
	{
		pid.output = -pid.sat;
	}
	// set current input to be the old input //
	pid.old = err;

	return pid.output;
}

/******************************************************************************
 * int initialize_motors(int channels[3], float freq)
 *
 * Initializes the PWM board and the ESCs that run the motors
******************************************************************************/
int initialize_motors(int channels[3], float freq)
{
	// setup PCA9685 PWM board //
	int fd = pca9685Setup(PIN_BASE, PCA9685_ADDR, HERTZ);
	if (fd < 0)
	{
		printf("Error in setup\n");
		return fd;
	}

	// reset all PCA9685 PWM board output //
	pca9685PWMReset(fd);

	// set motor outputs to 0 to initialize ESCs //
	for( int i = 0; i < 3; i++ )
	{
		set_motor(i, 0);
	}
	return fd;
}

/******************************************************************************
 * float set_motor(int motornum, float percent)
 *
 * Takes in a value from -1 to 1 (-100 to +100%) and sets the motor
 * outputs accordingly
******************************************************************************/
float set_motor(int motornum, float percent)
{
	// Define characteristics of PWM pulse, microseconds
	float amplitude	 = PWM_HIGH_LIMIT - PWM_ZERO_VALUE;

	// Saturation limits
	if( percent >	 1.0) percent =	 1.0;
	if( percent < -1.0) percent = -1.0;

	// Deadzone check
	if( (percent < MOTOR_DEADZONE) && (percent > -MOTOR_DEADZONE) ) percent = 0.0;

	// Calculate corresponding pwm output value
	int motoroutput = percent * amplitude + PWM_ZERO_VALUE;

	// Spin those motors
	pwmWrite(motornum + PIN_BASE, motoroutput);

	#ifdef DEBUG
	// Print what we told the motor to spin at.
	printf("Set motor %d to %d \n", motornum, motoroutput);
	#endif

	return percent;
}
<|endoftext|>


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

#include "CEGUI/SchemeManager.h"
#include "CEGUI/GUIContext.h"
#include "CEGUI/WindowManager.h"
#include "CEGUI/FontManager.h"
#include "CEGUI/Window.h"
#include "CEGUI/widgets/DefaultWindow.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/BitmapImage.h"
#include "CEGUI/ImageManager.h"
#include "CEGUI/svg/SVGDataManager.h"
#include "CEGUI/svg/SVGImage.h"
#include "CEGUI/svg/SVGData.h"
#include "CEGUI/svg/SVGBasicShape.h"

#include "glm/glm.hpp"

#include <iostream>

using namespace CEGUI;
using namespace glm;

/*************************************************************************
    Constructor.
*************************************************************************/
CustomShapesDrawing::CustomShapesDrawing()
    : d_FPSMaxGraphValue(1)
    , d_FPSGraphSamplesCount(30)
{
    // Initialising the FPS values
    for(unsigned int i = 0; i < d_FPSGraphSamplesCount; ++i)
        d_lastFPSValues.push_front(0);
}

/*************************************************************************
    Sample specific initialisation goes here.
*************************************************************************/
bool CustomShapesDrawing::initialise(CEGUI::GUIContext* guiContext)
{
    d_usedFiles = CEGUI::String(__FILE__);

    //CEGUI setup
    SchemeManager::getSingleton().createFromFile("WindowsLook.scheme");
    SchemeManager::getSingleton().createFromFile("Generic.scheme");
    guiContext->getMouseCursor().setDefaultImage("WindowsLook/MouseArrow");
    WindowManager& winMgr = WindowManager::getSingleton();

    // Create a DefaultWindow called 'Root'.
    d_root = (DefaultWindow*)winMgr.createWindow("DefaultWindow", "Root");

    // load font and setup default if not loaded via scheme
    Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font");
    // Set default font for the gui context
    guiContext->setDefaultFont(&defaultFont);

    // Set the root window as root of our GUI Context
    guiContext->setRootWindow(d_root);

    CEGUI::Renderer* renderer = CEGUI::System::getSingleton().getRenderer();

    // GeometryBuffer used for drawing in this demo
    d_FPSGraphGeometry = &renderer->createGeometryBufferColoured(renderer->createRenderMaterial(DS_SOLID));
    // Size and position have to be set
    positionFPSGraphGeometry();
    updateFPSGraphGeometry();

    // Create an SVGImage using the ImageManager
    CEGUI::ImageManager& imageManager = CEGUI::ImageManager::getSingleton();
    SVGImage& fpsSVGImage = static_cast<SVGImage&>(imageManager.create(CEGUI::String("SVGImage"), "FPSGraphSVG"));
    // Create an SVGData object
    CEGUI::SVGDataManager& svgDataManager = CEGUI::SVGDataManager::getSingleton();
    SVGData& fpsSVGData = svgDataManager.create(CEGUI::String("FPSGraphCustomShape"));
    //Fill in line points
    SVGPolyline* polyLine = new SVGPolyline(); //TODO maybe create a creation function for this
    polyLine->d_points.push_back(glm::vec2(20.0f, 20.0f));
    polyLine->d_points.push_back(glm::vec2(40.0f, 20.0f));
    polyLine->d_points.push_back(glm::vec2(20.0f, 40.0f));
    polyLine->d_points.push_back(glm::vec2(60.0f, 60.0f));
    polyLine->d_points.push_back(glm::vec2(110.0f, 60.0f));
    fpsSVGData.addShape(polyLine);
    // ...and set the pointer to the SVGData for the SVGImage
    fpsSVGImage.setSVGData(&fpsSVGData);

    Window* fpsSVGFrameWindow = winMgr.createWindow("WindowsLook/FrameWindow");
    d_root->addChild(fpsSVGFrameWindow);
    Window* fpsSVGImageWindow = winMgr.createWindow("Generic/Image");
    fpsSVGFrameWindow->addChild(fpsSVGImageWindow);
    fpsSVGImageWindow->setProperty("Image", "FPSGraphSVG");

    // clearing this queue actually makes sure it's created(!)
    guiContext->clearGeometry(CEGUI::RQ_OVERLAY);

    // subscribe handler to render overlay items
    guiContext->subscribeEvent(CEGUI::RenderingSurface::EventRenderQueueStarted,
        CEGUI::Event::Subscriber(&CustomShapesDrawing::drawFPSGraphOverlay,
        this));

    // return true so that the samples framework knows that initialisation was a
    // success, and that it should now run the sample.
    return true;
}

/*************************************************************************
    Cleans up resources allocated in the initialiseSample call.
*************************************************************************/
void CustomShapesDrawing::positionFPSGraphGeometry()
{
    CEGUI::Renderer* renderer = CEGUI::System::getSingleton().getRenderer();
    const CEGUI::Rectf scrn(CEGUI::Vector2f(0, 0), renderer->getDisplaySize());

    d_FPSGraphGeometry->setClippingRegion(scrn);
    d_FPSGraphGeometry->setTranslation(
        CEGUI::Vector3f(250.0f, 250.f, 0.0f));
}

/*************************************************************************
    Triggers the drawing of our FPS graph after everything else was rendered
*************************************************************************/
bool CustomShapesDrawing::drawFPSGraphOverlay(const CEGUI::EventArgs& args)
{
    if (static_cast<const CEGUI::RenderQueueEventArgs&>(args).queueID != CEGUI::RQ_OVERLAY)
        return false;

    // draw FPS value
    d_FPSGraphGeometry->draw();

    return true;
}

/*************************************************************************
    Update the FPS graph geometry when necessary
*************************************************************************/
void CustomShapesDrawing::update(float timeSinceLastUpdate)
{
    updateFPS(timeSinceLastUpdate);
    positionFPSGraphGeometry();
}

void CustomShapesDrawing::updateFPS(const float elapsed)
{
    // another frame
    ++d_FPSFrames;

    // Add FPS count if a second has passed
    if ((d_FPSElapsed += elapsed) >= 1.0f)
    {
        d_FPSMaxGraphValue = std::max(d_FPSMaxGraphValue, d_FPSFrames);
        d_FPSGraphGeometry->reset();

        d_lastFPSValues.pop_front();
        d_lastFPSValues.push_back(d_FPSFrames);
        updateFPSGraphGeometry();

        // reset counter state
        d_FPSFrames = 0;
        float modValue = 1.f;
        d_FPSElapsed = std::modf(d_FPSElapsed, &modValue);
    }
}

/*************************************************************************
    Cleans up resources allocated in the initialiseSample call.
*************************************************************************/
void CustomShapesDrawing::deinitialise()
{
}

/*************************************************************************
    Update the geometry used for the FPS graph
*************************************************************************/
void CustomShapesDrawing::updateFPSGraphGeometry()
{
    static const float maxHeight = 100.0f;
    static const float sampleDisplaySpacing = 7.0f;
    static const float lineWidth = 1.f;
    static const CEGUI::Colour lineColour = CEGUI::Colour(0.0f, 1.0f, 0.0f);

    d_FPSGraphGeometry->reset();

    std::vector<glm::vec2> linePositions;

    for(unsigned int i = 0; i < d_FPSGraphSamplesCount; ++i)
    {
        float currentOffset = i * sampleDisplaySpacing;

        float scale = static_cast<float>(d_lastFPSValues.at(i)) / d_FPSMaxGraphValue;
        float pointHeight = maxHeight - scale * maxHeight;

        glm::vec2 currentPosition(currentOffset, pointHeight);
        linePositions.push_back(currentPosition);
    }

    drawLineStrip(linePositions, lineWidth, lineColour);
}

void CustomShapesDrawing::drawLineStrip(std::vector<glm::vec2> &linePositions, const float lineWidth, const CEGUI::Colour lineColour)
{
    unsigned int size = linePositions.size();
    for (unsigned int j = 1; j < size; ++j)
    {
        const glm::vec2& prevPos = linePositions.at(j - 1);
        const glm::vec2& currentPos = linePositions.at(j);

        // Normalize and tilt the 2D direction vector by 90 to get the vector pointing in the offset direction
        glm::vec2 offsetVector = currentPos - prevPos;
        offsetVector = glm::normalize(offsetVector);
        offsetVector = glm::vec2(offsetVector.y, -offsetVector.x) * 0.5f;

        CEGUI::ColouredVertex linePositionVertex;
        glm::vec2 vertexPosition;
        linePositionVertex.colour_val = lineColour;

        linePositionVertex.position = glm::vec3(prevPos - offsetVector, 0.0f);
        d_FPSGraphGeometry->appendVertex(linePositionVertex);

        linePositionVertex.position = glm::vec3(currentPos - offsetVector, 0.0f);
        d_FPSGraphGeometry->appendVertex(linePositionVertex);

        linePositionVertex.position = glm::vec3(currentPos + offsetVector, 0.0f);
        d_FPSGraphGeometry->appendVertex(linePositionVertex);

        linePositionVertex.position = glm::vec3(currentPos + offsetVector, 0.0f);
        d_FPSGraphGeometry->appendVertex(linePositionVertex);

        linePositionVertex.position = glm::vec3(prevPos - offsetVector, 0.0f);
        d_FPSGraphGeometry->appendVertex(linePositionVertex);

        linePositionVertex.position = glm::vec3(prevPos + offsetVector, 0.0f);
        d_FPSGraphGeometry->appendVertex(linePositionVertex);
    }
}

/*************************************************************************
    Define the module function that returns an instance of the sample
*************************************************************************/
extern "C" SAMPLE_EXPORT Sample& getSampleInstance()
{
    static CustomShapesDrawing sample;
    return sample;
}<commit_msg>MOD: Adapting demo for changed functions and adding rect<commit_after>/***********************************************************************
    filename:   CustomShapesDrawing.cpp
    created:    16/7/2013
    author:     Lukas E Meindl
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CustomShapesDrawing.h"

#include "CEGUI/SchemeManager.h"
#include "CEGUI/GUIContext.h"
#include "CEGUI/WindowManager.h"
#include "CEGUI/FontManager.h"
#include "CEGUI/Window.h"
#include "CEGUI/widgets/DefaultWindow.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/BitmapImage.h"
#include "CEGUI/ImageManager.h"
#include "CEGUI/svg/SVGDataManager.h"
#include "CEGUI/svg/SVGImage.h"
#include "CEGUI/svg/SVGData.h"
#include "CEGUI/svg/SVGBasicShape.h"

#include "glm/glm.hpp"

#include <iostream>

using namespace CEGUI;
using namespace glm;

/*************************************************************************
    Constructor.
*************************************************************************/
CustomShapesDrawing::CustomShapesDrawing()
    : d_FPSMaxGraphValue(1)
    , d_FPSGraphSamplesCount(30)
{
    // Initialising the FPS values
    for(unsigned int i = 0; i < d_FPSGraphSamplesCount; ++i)
        d_lastFPSValues.push_front(0);
}

/*************************************************************************
    Sample specific initialisation goes here.
*************************************************************************/
bool CustomShapesDrawing::initialise(CEGUI::GUIContext* guiContext)
{
    d_usedFiles = CEGUI::String(__FILE__);

    //CEGUI setup
    SchemeManager::getSingleton().createFromFile("WindowsLook.scheme");
    SchemeManager::getSingleton().createFromFile("Generic.scheme");
    guiContext->getMouseCursor().setDefaultImage("WindowsLook/MouseArrow");
    WindowManager& winMgr = WindowManager::getSingleton();

    // Create a DefaultWindow called 'Root'.
    d_root = (DefaultWindow*)winMgr.createWindow("DefaultWindow", "Root");

    // load font and setup default if not loaded via scheme
    Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font");
    // Set default font for the gui context
    guiContext->setDefaultFont(&defaultFont);

    // Set the root window as root of our GUI Context
    guiContext->setRootWindow(d_root);

    CEGUI::Renderer* renderer = CEGUI::System::getSingleton().getRenderer();

    // GeometryBuffer used for drawing in this demo
    d_FPSGraphGeometry = &renderer->createGeometryBufferColoured(renderer->createRenderMaterial(DS_SOLID));
    // Size and position have to be set
    positionFPSGraphGeometry();
    updateFPSGraphGeometry();

    // Create an SVGImage using the ImageManager
    CEGUI::ImageManager& imageManager = CEGUI::ImageManager::getSingleton();
    SVGImage& fpsSVGImage = static_cast<SVGImage&>(imageManager.create(CEGUI::String("SVGImage"), "FPSGraphSVG"));
    // Create an SVGData object
    CEGUI::SVGDataManager& svgDataManager = CEGUI::SVGDataManager::getSingleton();
    SVGData& fpsSVGData = svgDataManager.create(CEGUI::String("FPSGraphCustomShape"));
    //Fill in line points
    SVGPolyline* polyLine = new SVGPolyline(); //TODO maybe create a creation function for this
    polyLine->d_points.push_back(glm::vec2(20.0f, 20.0f));
    polyLine->d_points.push_back(glm::vec2(40.0f, 20.0f));
    polyLine->d_points.push_back(glm::vec2(20.0f, 40.0f));
    polyLine->d_points.push_back(glm::vec2(160.0f, 60.0f));
    polyLine->d_points.push_back(glm::vec2(210.0f, 60.0f));
    fpsSVGData.addShape(*polyLine);

    SVGRect* svg_rect = new SVGRect(120.f, 10.f, 15.f, 20.f);
    svg_rect->d_shapeStyle.d_fill.d_colour = CEGUI::Colour(0.f, 0.3f, 0.3f, 1.f);
    fpsSVGData.addShape(*svg_rect);

    //Set the desired size of the SVGData
    fpsSVGData.setWidth(215.f);
    fpsSVGData.setHeight(65.f);

    // Set the pointer to the SVGData for the SVGImage
    fpsSVGImage.setSVGData(&fpsSVGData);
    const Rectf rect(Vector2f(0.0f, 0.0f), CEGUI::Sizef(fpsSVGData.getWidth(), fpsSVGData.getHeight()));
    fpsSVGImage.setImageArea(rect);

    Window* fpsSVGFrameWindow = winMgr.createWindow("WindowsLook/FrameWindow");
    d_root->addChild(fpsSVGFrameWindow);
    Window* fpsSVGImageWindow = winMgr.createWindow("Generic/Image");
    fpsSVGImageWindow->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(1.0f)));
    fpsSVGFrameWindow->addChild(fpsSVGImageWindow);
    fpsSVGImageWindow->setProperty("Image", "FPSGraphSVG");

    // clearing this queue actually makes sure it's created(!)
    guiContext->clearGeometry(CEGUI::RQ_OVERLAY);

    // subscribe handler to render overlay items
    guiContext->subscribeEvent(CEGUI::RenderingSurface::EventRenderQueueStarted,
        CEGUI::Event::Subscriber(&CustomShapesDrawing::drawFPSGraphOverlay,
        this));

    // return true so that the samples framework knows that initialisation was a
    // success, and that it should now run the sample.
    return true;
}

/*************************************************************************
    Cleans up resources allocated in the initialiseSample call.
*************************************************************************/
void CustomShapesDrawing::positionFPSGraphGeometry()
{
    CEGUI::Renderer* renderer = CEGUI::System::getSingleton().getRenderer();
    const CEGUI::Rectf scrn(CEGUI::Vector2f(0, 0), renderer->getDisplaySize());

    d_FPSGraphGeometry->setClippingRegion(scrn);
    d_FPSGraphGeometry->setTranslation(
        CEGUI::Vector3f(250.0f, 250.f, 0.0f));
}

/*************************************************************************
    Triggers the drawing of our FPS graph after everything else was rendered
*************************************************************************/
bool CustomShapesDrawing::drawFPSGraphOverlay(const CEGUI::EventArgs& args)
{
    if (static_cast<const CEGUI::RenderQueueEventArgs&>(args).queueID != CEGUI::RQ_OVERLAY)
        return false;

    // draw FPS value
    d_FPSGraphGeometry->draw();

    return true;
}

/*************************************************************************
    Update the FPS graph geometry when necessary
*************************************************************************/
void CustomShapesDrawing::update(float timeSinceLastUpdate)
{
    updateFPS(timeSinceLastUpdate);
    positionFPSGraphGeometry();
}

void CustomShapesDrawing::updateFPS(const float elapsed)
{
    // another frame
    ++d_FPSFrames;

    // Add FPS count if a second has passed
    if ((d_FPSElapsed += elapsed) >= 1.0f)
    {
        d_FPSMaxGraphValue = std::max(d_FPSMaxGraphValue, d_FPSFrames);
        d_FPSGraphGeometry->reset();

        d_lastFPSValues.pop_front();
        d_lastFPSValues.push_back(d_FPSFrames);
        updateFPSGraphGeometry();

        // reset counter state
        d_FPSFrames = 0;
        float modValue = 1.f;
        d_FPSElapsed = std::modf(d_FPSElapsed, &modValue);
    }
}

/*************************************************************************
    Cleans up resources allocated in the initialiseSample call.
*************************************************************************/
void CustomShapesDrawing::deinitialise()
{
}

/*************************************************************************
    Update the geometry used for the FPS graph
*************************************************************************/
void CustomShapesDrawing::updateFPSGraphGeometry()
{
    static const float maxHeight = 100.0f;
    static const float sampleDisplaySpacing = 7.0f;
    static const float lineWidth = 1.f;
    static const CEGUI::Colour lineColour = CEGUI::Colour(0.0f, 1.0f, 0.0f);

    d_FPSGraphGeometry->reset();

    std::vector<glm::vec2> linePositions;

    for(unsigned int i = 0; i < d_FPSGraphSamplesCount; ++i)
    {
        float currentOffset = i * sampleDisplaySpacing;

        float scale = static_cast<float>(d_lastFPSValues.at(i)) / d_FPSMaxGraphValue;
        float pointHeight = maxHeight - scale * maxHeight;

        glm::vec2 currentPosition(currentOffset, pointHeight);
        linePositions.push_back(currentPosition);
    }

    drawLineStrip(linePositions, lineWidth, lineColour);
}

void CustomShapesDrawing::drawLineStrip(std::vector<glm::vec2> &linePositions, const float lineWidth, const CEGUI::Colour lineColour)
{
    unsigned int size = linePositions.size();
    for (unsigned int j = 1; j < size; ++j)
    {
        const glm::vec2& prevPos = linePositions.at(j - 1);
        const glm::vec2& currentPos = linePositions.at(j);

        // Normalize and tilt the 2D direction vector by 90 to get the vector pointing in the offset direction
        glm::vec2 offsetVector = currentPos - prevPos;
        offsetVector = glm::normalize(offsetVector);
        offsetVector = glm::vec2(offsetVector.y, -offsetVector.x) * 0.5f;

        CEGUI::ColouredVertex linePositionVertex;
        glm::vec2 vertexPosition;
        linePositionVertex.colour_val = lineColour;

        linePositionVertex.position = glm::vec3(prevPos - offsetVector, 0.0f);
        d_FPSGraphGeometry->appendVertex(linePositionVertex);

        linePositionVertex.position = glm::vec3(currentPos - offsetVector, 0.0f);
        d_FPSGraphGeometry->appendVertex(linePositionVertex);

        linePositionVertex.position = glm::vec3(currentPos + offsetVector, 0.0f);
        d_FPSGraphGeometry->appendVertex(linePositionVertex);

        linePositionVertex.position = glm::vec3(currentPos + offsetVector, 0.0f);
        d_FPSGraphGeometry->appendVertex(linePositionVertex);

        linePositionVertex.position = glm::vec3(prevPos - offsetVector, 0.0f);
        d_FPSGraphGeometry->appendVertex(linePositionVertex);

        linePositionVertex.position = glm::vec3(prevPos + offsetVector, 0.0f);
        d_FPSGraphGeometry->appendVertex(linePositionVertex);
    }
}

/*************************************************************************
    Define the module function that returns an instance of the sample
*************************************************************************/
extern "C" SAMPLE_EXPORT Sample& getSampleInstance()
{
    static CustomShapesDrawing sample;
    return sample;
}<|endoftext|>


<commit_before>
inline Exception::Exception( const std::string& message ) :
    std::runtime_error( message )
{}
<commit_msg>Just for consistency.<commit_after>
inline C3::Exception::Exception( const std::string& message ) :
    std::runtime_error( message )
{}
<|endoftext|>


<commit_before>#ifndef LIBBITCOIN_VERSION_HPP
#define LIBBITCOIN_VERSION_HPP

// Caution, this is the only libbitcoin header that is guarenteed
// to change with every libbitcoin release, including this header
// will cause a recompile every time a new libbitcoin version is
// released.
//
// LIBBITCOIN_VERSION % 100 is the patch level
// LIBBITCOIN_VERSION / 100 % 1000 is the minor version
// LIBBITCOIN_VERSION / 100000 is the major version

#define LIBBITCOIN_VERSION 100300

// LIBBITCOIN_LIB_VERSION is defined to be the same as LIBBITCOIN_VERSION
// but as a *string* in the form "x.y[.z]" where x is the major version
// number, y is the minor version number, and z is the patch level if not 0.
// This is used for the user agent string during the connection handshake.

#define LIBBITCOIN_LIB_VERSION "1.3.0"

#endif

<commit_msg>incorrect version number in version.hpp - corrected it.<commit_after>#ifndef LIBBITCOIN_VERSION_HPP
#define LIBBITCOIN_VERSION_HPP

// Caution, this is the only libbitcoin header that is guarenteed
// to change with every libbitcoin release, including this header
// will cause a recompile every time a new libbitcoin version is
// released.
//
// LIBBITCOIN_VERSION % 100 is the patch level
// LIBBITCOIN_VERSION / 100 % 1000 is the minor version
// LIBBITCOIN_VERSION / 100000 is the major version

#define LIBBITCOIN_VERSION 100400

// LIBBITCOIN_LIB_VERSION is defined to be the same as LIBBITCOIN_VERSION
// but as a *string* in the form "x.y[.z]" where x is the major version
// number, y is the minor version number, and z is the patch level if not 0.
// This is used for the user agent string during the connection handshake.

#define LIBBITCOIN_LIB_VERSION "1.4.0"

#endif

<|endoftext|>


<commit_before>/* Copyright 2013 Edwin van Leeuwen.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#ifndef BSON_STREAM_H
#define BSON_STREAM_H
#include<map>
#include "bson/bson.h"

template<class T>
void operator>>( const mongo::BSONElement &bel, T &t ) {
	bel.Val( t );
}

template<class T>
void operator>>( const mongo::BSONObj &bobj, T &t ) {
	// If we have a object we probably want to pipe the object as a whole into
	// class T. To do that we first turn it into an element (containing an sub object)
	// and then pipe that to our class T. I could not find a simple way of turning an
	// object into an element, so we'll wrap it up and then when we unwrap it we get
	// an element back
	mongo::BSONObjBuilder bbuild;
	bbuild << "a" << bobj;
	bbuild.obj()["a"] >> t;
}

void operator>>( const mongo::BSONElement &bel, double &t );
inline void operator>>( const mongo::BSONElement &bel, double &t ) {
	t = bel.Number();
}

template<class T>
void operator>>( const mongo::BSONElement &bel, std::vector<T> &v ) {
	v.clear();
	auto barr = bel.Array();
	for ( auto & bson_el : barr ) {
		// This will only work if T has an empty constructor T()
		// I am not aware of a more general way of doing this though
		T el;
		bson_el >> el;
		v.push_back( el );
	}
}

template<class T>
void operator>>( const mongo::BSONElement &bel, std::list<T> &v ) {
	v.clear();
	auto barr = bel.Array();
	for ( auto & bson_el : barr ) {
		// This will only work if T has an empty constructor T()
		// I am not aware of a more general way of doing this though
		T el;
		bson_el >> el;
		v.push_back( el );
	}
}

template<class T>
void operator>>( const mongo::BSONElement &bel, std::set<T> &v ) {
	v.clear();
	auto barr = bel.Array();
	for ( auto & bson_el : barr ) {
		// This will only work if T has an empty constructor T()
		// I am not aware of a more general way of doing this though
		T el;
		bson_el >> el;
		v.insert( el );
	}
}

template<class K, class V>
void operator>>( const mongo::BSONObj &bobj, std::map<K,V> &map ) {
	map.clear();
	for ( mongo::BSONObj::iterator i = bobj.begin(); i.more(); ) {
		mongo::BSONElement el = i.next();
		V value;
		el >> value;
		map[el.fieldName()] = value;
	}
}

namespace mongo {
	class BSONEmitter;

	class BSONValueEmitter {
		public:
			BSONValueEmitter( BSONEmitter *pEmitter );

			template<class T>
				BSONEmitter &append( const T &t );

			BSONEmitter &append( const double &t );
			BSONEmitter &append( const long long &t );
			BSONEmitter &append( const bool &t );
			BSONEmitter &append( const int &t );
			BSONEmitter &append( const std::string &t );
			BSONEmitter &append( const BSONArray &t );
			BSONEmitter &append( const BSONObj &t );

			BSONEmitter *pEmitter;
			BSONObjBuilderValueStream builder;
	};

	/**
	 * \brief Define an emitter for BSONObjects
	 *
	 * Behaviour is partly based on BSONObjBuilder, but different enough that
	 * we need a separate class
	 */
	class BSONEmitter {
		public:
			BSONEmitter() : builder( new BSONObjBuilder() ), v_emitter( this ) {}
			BSONEmitter( BSONObjBuilder *builder )
				: builder( builder ), v_emitter( this )
			{}

			BSONObj obj() {
				auto bobj = builder->obj();
				// This invalidates builder any way, so we can delete it
				delete builder;
				return bobj;
			}

			BSONValueEmitter &append( const std::string &name ) {
				v_emitter.builder.endField( name.c_str() );
				return v_emitter;
			}

			BSONValueEmitter &append( const char *name ) {
				v_emitter.builder.endField( name );
				return v_emitter;
			}

			BSONObjBuilder *builder;
			BSONValueEmitter v_emitter;
	};

	inline BSONValueEmitter::BSONValueEmitter( BSONEmitter *pEmitter )
		: pEmitter( pEmitter ), builder( pEmitter->builder ) {
		}

	template<class T>
		BSONEmitter &BSONValueEmitter::append( const T &t ) {
			mongo::BSONEmitter b;
			b << t;
			return this->append( b.obj() );
		}

	inline BSONEmitter &BSONValueEmitter::append( const double &t ) {
		pEmitter->builder = &(builder << t);
		return (*pEmitter);
	}

	inline BSONEmitter &BSONValueEmitter::append( const long long &t ) {
		pEmitter->builder = &(builder << t);
		return (*pEmitter);
	}

	inline BSONEmitter &BSONValueEmitter::append( const bool &t ) {
		pEmitter->builder = &(builder << t);
		return (*pEmitter);
	}

	inline BSONEmitter &BSONValueEmitter::append( const int &t ) {
		pEmitter->builder = &(builder << t);
		return (*pEmitter);
	}

	inline BSONEmitter &BSONValueEmitter::append( const std::string &t ) {
		pEmitter->builder = &(builder << t);
		return (*pEmitter);
	}

	inline BSONEmitter &BSONValueEmitter::append( const BSONArray &t ) {
		pEmitter->builder = &(builder << t);
		return (*pEmitter);
	}

	inline BSONEmitter &BSONValueEmitter::append( const BSONObj &t ) {
		pEmitter->builder = &(builder << t);
		return (*pEmitter);
	}

	class BSONArrayEmitter {
		public:
			BSONArrayEmitter() {}

			template<class T>
				BSONArrayEmitter &append( const T &t ) {
					mongo::BSONEmitter b;
					b << t;
					builder.append( b.obj() );
					return *this;
				}

			BSONArrayEmitter &append(	const double &t ) {
				builder.append( t );
				return *this;
			}

			BSONArrayEmitter &append(	const long long &t ) {
				builder.append( t );
				return *this;
			}

			BSONArrayEmitter &append(	const bool &t ) {
				builder.append( t );
				return *this;
			}

			BSONArrayEmitter &append(	const int &t ) {
				builder.append( t );
				return *this;
			}

			BSONArrayEmitter &append(	const std::string &t ) {
				builder.append( t );
				return *this;
			}

			BSONArray arr() {
				return builder.arr();
			}

			BSONArrayBuilder builder;
	};

	template<class K, class V>
		BSONEmitter &operator<<( BSONEmitter &wrap,
				const std::pair<K,V> &t ) {
			wrap.append( t.first ).append( t.second );
			return wrap;
		}

	template<class K, class V>
		BSONEmitter &operator<<( BSONEmitter &wrap,
				const std::map<K,V> &t ) {
			for (auto & pair : t)
				wrap << pair;
			return wrap;
		}

};

template<class T>
mongo::BSONValueEmitter &operator<<( mongo::BSONEmitter &emitter, const T &t ) {
	return emitter.append( t );
}

/*//! Add map easily to an emitter, map keys become keys in the resulting BSONObj
template<class K, class V>
mongo::BSONEmitter &operator<<( mongo::BSONEmitter &emitter, const std::map<K,V> &map ) {
	(*emitter.builder) << map;
	return emitter;
}*/

template<class T>
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &emitter, const T &t ) {
	return emitter.append( t );
}

template<class T>
mongo::BSONArrayEmitter &operator<<( mongo::BSONArrayEmitter &barr,
		const T &t ) {
	return barr.append( t );
}

template<class T>
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &bbuild,
		const std::vector<T> &vt ) {
	mongo::BSONArrayEmitter b;
	for ( const T &el : vt ) {
		b << el;
	}
	return bbuild.append( b.arr() );
}

template<class T>
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &bbuild,
		const std::set<T> &vt ) {
	mongo::BSONArrayEmitter b;
	for ( const T &el : vt ) {
		b << el;
	}
	return bbuild.append( b.arr() );
}

template<class T>
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &bbuild,
		const std::list<T> &vt ) {
	mongo::BSONArrayEmitter b;
	for ( const T &el : vt ) {
		b << el;
	}
	return bbuild.append( b.arr() );
}

#endif
<commit_msg>Move operator overloading into it the mongo namespace<commit_after>/* Copyright 2013 Edwin van Leeuwen.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#ifndef BSON_STREAM_H
#define BSON_STREAM_H
#include<map>
#include "bson/bson.h"

namespace mongo {

template<class T>
void operator>>( const mongo::BSONElement &bel, T &t ) {
	bel.Val( t );
}

template<class T>
void operator>>( const mongo::BSONObj &bobj, T &t ) {
	// If we have a object we probably want to pipe the object as a whole into
	// class T. To do that we first turn it into an element (containing an sub object)
	// and then pipe that to our class T. I could not find a simple way of turning an
	// object into an element, so we'll wrap it up and then when we unwrap it we get
	// an element back
	mongo::BSONObjBuilder bbuild;
	bbuild << "a" << bobj;
	bbuild.obj()["a"] >> t;
}

void operator>>( const mongo::BSONElement &bel, double &t );
inline void operator>>( const mongo::BSONElement &bel, double &t ) {
	t = bel.Number();
}

template<class T>
void operator>>( const mongo::BSONElement &bel, std::vector<T> &v ) {
	v.clear();
	auto barr = bel.Array();
	for ( auto & bson_el : barr ) {
		// This will only work if T has an empty constructor T()
		// I am not aware of a more general way of doing this though
		T el;
		bson_el >> el;
		v.push_back( el );
	}
}

template<class T>
void operator>>( const mongo::BSONElement &bel, std::list<T> &v ) {
	v.clear();
	auto barr = bel.Array();
	for ( auto & bson_el : barr ) {
		// This will only work if T has an empty constructor T()
		// I am not aware of a more general way of doing this though
		T el;
		bson_el >> el;
		v.push_back( el );
	}
}

template<class T>
void operator>>( const mongo::BSONElement &bel, std::set<T> &v ) {
	v.clear();
	auto barr = bel.Array();
	for ( auto & bson_el : barr ) {
		// This will only work if T has an empty constructor T()
		// I am not aware of a more general way of doing this though
		T el;
		bson_el >> el;
		v.insert( el );
	}
}

template<class K, class V>
void operator>>( const mongo::BSONObj &bobj, std::map<K,V> &map ) {
	map.clear();
	for ( mongo::BSONObj::iterator i = bobj.begin(); i.more(); ) {
		mongo::BSONElement el = i.next();
		V value;
		el >> value;
		map[el.fieldName()] = value;
	}
}

	class BSONEmitter;

	class BSONValueEmitter {
		public:
			BSONValueEmitter( BSONEmitter *pEmitter );

			template<class T>
				BSONEmitter &append( const T &t );

			BSONEmitter &append( const double &t );
			BSONEmitter &append( const long long &t );
			BSONEmitter &append( const bool &t );
			BSONEmitter &append( const int &t );
			BSONEmitter &append( const std::string &t );
			BSONEmitter &append( const BSONArray &t );
			BSONEmitter &append( const BSONObj &t );

			BSONEmitter *pEmitter;
			BSONObjBuilderValueStream builder;
	};

	/**
	 * \brief Define an emitter for BSONObjects
	 *
	 * Behaviour is partly based on BSONObjBuilder, but different enough that
	 * we need a separate class
	 */
	class BSONEmitter {
		public:
			BSONEmitter() : builder( new BSONObjBuilder() ), v_emitter( this ) {}
			BSONEmitter( BSONObjBuilder *builder )
				: builder( builder ), v_emitter( this )
			{}

			BSONObj obj() {
				auto bobj = builder->obj();
				// This invalidates builder any way, so we can delete it
				delete builder;
				return bobj;
			}

			BSONValueEmitter &append( const std::string &name ) {
				v_emitter.builder.endField( name.c_str() );
				return v_emitter;
			}

			BSONValueEmitter &append( const char *name ) {
				v_emitter.builder.endField( name );
				return v_emitter;
			}

			BSONObjBuilder *builder;
			BSONValueEmitter v_emitter;
	};

	inline BSONValueEmitter::BSONValueEmitter( BSONEmitter *pEmitter )
		: pEmitter( pEmitter ), builder( pEmitter->builder ) {
		}

	template<class T>
		BSONEmitter &BSONValueEmitter::append( const T &t ) {
			mongo::BSONEmitter b;
			b << t;
			return this->append( b.obj() );
		}

	inline BSONEmitter &BSONValueEmitter::append( const double &t ) {
		pEmitter->builder = &(builder << t);
		return (*pEmitter);
	}

	inline BSONEmitter &BSONValueEmitter::append( const long long &t ) {
		pEmitter->builder = &(builder << t);
		return (*pEmitter);
	}

	inline BSONEmitter &BSONValueEmitter::append( const bool &t ) {
		pEmitter->builder = &(builder << t);
		return (*pEmitter);
	}

	inline BSONEmitter &BSONValueEmitter::append( const int &t ) {
		pEmitter->builder = &(builder << t);
		return (*pEmitter);
	}

	inline BSONEmitter &BSONValueEmitter::append( const std::string &t ) {
		pEmitter->builder = &(builder << t);
		return (*pEmitter);
	}

	inline BSONEmitter &BSONValueEmitter::append( const BSONArray &t ) {
		pEmitter->builder = &(builder << t);
		return (*pEmitter);
	}

	inline BSONEmitter &BSONValueEmitter::append( const BSONObj &t ) {
		pEmitter->builder = &(builder << t);
		return (*pEmitter);
	}

	class BSONArrayEmitter {
		public:
			BSONArrayEmitter() {}

			template<class T>
				BSONArrayEmitter &append( const T &t ) {
					mongo::BSONEmitter b;
					b << t;
					builder.append( b.obj() );
					return *this;
				}

			BSONArrayEmitter &append(	const double &t ) {
				builder.append( t );
				return *this;
			}

			BSONArrayEmitter &append(	const long long &t ) {
				builder.append( t );
				return *this;
			}

			BSONArrayEmitter &append(	const bool &t ) {
				builder.append( t );
				return *this;
			}

			BSONArrayEmitter &append(	const int &t ) {
				builder.append( t );
				return *this;
			}

			BSONArrayEmitter &append(	const std::string &t ) {
				builder.append( t );
				return *this;
			}

			BSONArray arr() {
				return builder.arr();
			}

			BSONArrayBuilder builder;
	};

	template<class K, class V>
		BSONEmitter &operator<<( BSONEmitter &wrap,
				const std::pair<K,V> &t ) {
			wrap.append( t.first ).append( t.second );
			return wrap;
		}

	template<class K, class V>
		BSONEmitter &operator<<( BSONEmitter &wrap,
				const std::map<K,V> &t ) {
			for (auto & pair : t)
				wrap << pair;
			return wrap;
		}

template<class T>
mongo::BSONValueEmitter &operator<<( mongo::BSONEmitter &emitter, const T &t ) {
	return emitter.append( t );
}

/*//! Add map easily to an emitter, map keys become keys in the resulting BSONObj
template<class K, class V>
mongo::BSONEmitter &operator<<( mongo::BSONEmitter &emitter, const std::map<K,V> &map ) {
	(*emitter.builder) << map;
	return emitter;
}*/

template<class T>
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &emitter, const T &t ) {
	return emitter.append( t );
}

template<class T>
mongo::BSONArrayEmitter &operator<<( mongo::BSONArrayEmitter &barr,
		const T &t ) {
	return barr.append( t );
}

template<class T>
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &bbuild,
		const std::vector<T> &vt ) {
	mongo::BSONArrayEmitter b;
	for ( const T &el : vt ) {
		b << el;
	}
	return bbuild.append( b.arr() );
}

template<class T>
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &bbuild,
		const std::set<T> &vt ) {
	mongo::BSONArrayEmitter b;
	for ( const T &el : vt ) {
		b << el;
	}
	return bbuild.append( b.arr() );
}

template<class T>
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &bbuild,
		const std::list<T> &vt ) {
	mongo::BSONArrayEmitter b;
	for ( const T &el : vt ) {
		b << el;
	}
	return bbuild.append( b.arr() );
}
};

#endif
<|endoftext|>


<commit_before>/* Copyright 2013 Edwin van Leeuwen.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#ifndef BSON_STREAM_H
#define BSON_STREAM_H

#include "bson/bson.h"

template<class T>
void operator>>( const mongo::BSONElement &bel, T &t ) {
	bel.Val( t );
}

void operator>>( const mongo::BSONElement &bel, double &t ) {
	t = bel.Number();
}

template<class T>
void operator>>( const mongo::BSONElement &bel, std::vector<T> &v ) {
	auto barr = bel.Array();
	for ( auto bson_el : barr ) {
		// This will only work if T has an empty constructor T()
		// I am not aware of a more general way of doing this though
		T el;
		bson_el >> el;
		v.push_back( el );
	}
}

template<class T>
void operator>>( const mongo::BSONElement &bel, std::list<T> &v ) {
	auto barr = bel.Array();
	for ( auto bson_el : barr ) {
		// This will only work if T has an empty constructor T()
		// I am not aware of a more general way of doing this though
		T el;
		bson_el >> el;
		v.push_back( el );
	}
}

template<class T>
void operator>>( const mongo::BSONElement &bel, std::set<T> &v ) {
	auto barr = bel.Array();
	for ( auto bson_el : barr ) {
		// This will only work if T has an empty constructor T()
		// I am not aware of a more general way of doing this though
		T el;
		bson_el >> el;
		v.insert( el );
	}
}

template<class K, class V>
void operator>>( const mongo::BSONObj &bobj, std::map<K,V> &map ) {
	for ( mongo::BSONObj::iterator i = bobj.begin(); i.more(); ) {
		mongo::BSONElement el = i.next();
		V value;
		el >> value;
		map[el.fieldName()] = value;
	}
}

/**
 * Stream in
 *
 * YAML works as follows:
 Emitter out;
 out << Emitter::Key << "name";
 out << Emitter::Value << "Ryan Braun";
 out << Emitter::Key << "position";
 out << Emitter::Value << "LF";
 BSONobj bobj = out.obj();

 I guess we should start with just building on BSONBuilder, which requires that
 a value could be any object, which then needs to be turned into a BSONElement, so
 one first needs to support <<( BSONElement &bel, T &t )

 It depends a bit on how BSONObjBuilder works if just adding my own classes
 to <<(BSONElement &bel, myclass &c ) will be enough,
 or do we need to use <<(BSONObjBuilder, myclass). If the second then it will be
 cleaner to add <<(BSONObjBuilder, T) which in turn calls <<(BSONElement, T)
 */

namespace mongo {
	class BSONEmitter;

	class BSONValueEmitter {
		public:
			BSONValueEmitter( BSONEmitter *pEmitter );

			template<class T>
				BSONEmitter &append( const T &t );

			BSONEmitter *pEmitter;
			BSONObjBuilderValueStream builder;
	};

	/**
	 * \brief Define an emitter for BSONObjects
	 *
	 * Behaviour is partly based on BSONObjBuilder, but different enough that
	 * we need a separate class
	 */
	class BSONEmitter {
		public:
			BSONEmitter() : builder( new BSONObjBuilder() ), v_emitter( this ) {}
			BSONEmitter( BSONObjBuilder *builder )
				: builder( builder ), v_emitter( this )
			{}

			BSONObj obj() {
				auto bobj = builder->obj();
				// This invalidates builder any way, so we can delete it
				delete builder;
				return bobj;
			}

			BSONValueEmitter &append( const std::string &name ) {
				v_emitter.builder.endField( name.c_str() );
				return v_emitter;
			}

			BSONValueEmitter &append( const char *name ) {
				v_emitter.builder.endField( name );
				return v_emitter;
			}

			BSONObjBuilder *builder;
			BSONValueEmitter v_emitter;
	};

	BSONValueEmitter::BSONValueEmitter( BSONEmitter *pEmitter )
		: pEmitter( pEmitter ), builder( pEmitter->builder ) {
		}

	template<class T>
		BSONEmitter &BSONValueEmitter::append( const T &t ) {
			//pEmitter->builder->append( t );
			pEmitter->builder = &(builder << t);
			return (*pEmitter);
		}

	class BSONArrayEmitter {
		public:
			BSONArrayEmitter() {}

			template<class T>
			BSONArrayEmitter &append( const T &t) {
				builder.append( t );
				return *this;
			}

			BSONArray arr() {
				return builder.arr();
			}

			BSONArrayBuilder builder;
	};

};
// Would prefer to define these as friend, but not possible due to
// BSONValueEmitter not being define at that point in the header file
template<class T>
mongo::BSONValueEmitter &operator<<( mongo::BSONEmitter &emitter, const T &t ) {
	return emitter.append( t );
}

//! For normal classes we need to convert them to an BSONObj first
//
//Below we override all the normal types
template<class T>
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &emitter, const T &t ) {
	mongo::BSONObjBuilder b;
	b << t;
	return emitter.append( b.obj() );
}

/**
 * \brief Override for standard types (as opposed to classes/objects)
 */
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &emitter, const double &t ) {
	return emitter.append( t );
}

mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &emitter, const long long &t ) {
	return emitter.append( t );
}

mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &emitter, const bool &t ) {
	return emitter.append( t );
}

mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &emitter, const int &t ) {
	return emitter.append( t );
}

mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &emitter, const std::string &t ) {
	return emitter.append( t );
}

/*
template<class K, class V>
mongo::BSONObjBuilder &operator<<( mongo::BSONObjBuilder &bbuild,
		const std::pair<K,V> &pair ) {
	bbuild << pair.first << pair.second;
	return bbuild;
}

template<class K, class V>
mongo::BSONObjBuilder &operator<<( mongo::BSONObjBuilder &bbuild,
		const std::map<K,V> &map ) {
	for ( auto pair : map ) {
		bbuild << pair;
	}
	return bbuild;
}

mongo::BSONObjBuilder &operator<<(
				mongo::BSONObjBuilderValueStream &bbuild, const double d ) {
	return bbuild << d;
}

template<class T>
mongo::BSONObjBuilder &operator<<(
				mongo::BSONObjBuilderValueStream &bbuild, const T &t ) {
	mongo::BSONObjBuilder bob;
	bob << t;
	return bbuild << bob.obj();
}

template<class K, class V>
mongo::BSONObjBuilder &operator<<( mongo::BSONObjBuilderValueStream &bbuild,
		const std::map<K,V> &map ) {
	mongo::BSONObjBuilder b;
	for ( auto pair : map )
		b << pair.first << pair.second;
	return bbuild << b.obj();
}

mongo::BSONObjBuilder &operator<<( mongo::BSONObjBuilderValueStream &bbuild,
		const std::vector<double> &vt ) {
	mongo::BSONArrayBuilder b;
	for ( auto el : vt ) {
		b << el;
	}
	return bbuild << b.arr();
}*/

//template<class T>
template<class T>
mongo::BSONArrayEmitter &operator<<( mongo::BSONArrayEmitter &barr,
		const T &t ) {
	mongo::BSONObjBuilder b;
	b << t;
	return barr.append( b.obj() );
}

mongo::BSONArrayEmitter &operator<<( mongo::BSONArrayEmitter &barr,
		const double &t ) {
	return barr.append( t );
}

mongo::BSONArrayEmitter &operator<<( mongo::BSONArrayEmitter &barr,
		const long long &t ) {
	return barr.append( t );
}

mongo::BSONArrayEmitter &operator<<( mongo::BSONArrayEmitter &barr,
		const bool &t ) {
	return barr.append( t );
}

mongo::BSONArrayEmitter &operator<<( mongo::BSONArrayEmitter &barr,
		const int &t ) {
	return barr.append( t );
}

mongo::BSONArrayEmitter &operator<<( mongo::BSONArrayEmitter &barr,
		const std::string &t ) {
	return barr.append( t );
}

template<class T>
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &bbuild,
		const std::vector<T> &vt ) {
	mongo::BSONArrayEmitter b;
	for ( T el : vt ) {
		b << el;
	}
	return bbuild.append( b.arr() );
}

template<class T>
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &bbuild,
		const std::set<T> &vt ) {
	mongo::BSONArrayEmitter b;
	for ( T el : vt ) {
		b << el;
	}
	return bbuild.append( b.arr() );
}

template<class T>
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &bbuild,
		const std::list<T> &vt ) {
	mongo::BSONArrayEmitter b;
	for ( T el : vt ) {
		b << el;
	}
	return bbuild.append( b.arr() );
}

#endif
<commit_msg>Loop by reference where possible<commit_after>/* Copyright 2013 Edwin van Leeuwen.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#ifndef BSON_STREAM_H
#define BSON_STREAM_H

#include "bson/bson.h"

template<class T>
void operator>>( const mongo::BSONElement &bel, T &t ) {
	bel.Val( t );
}

void operator>>( const mongo::BSONElement &bel, double &t ) {
	t = bel.Number();
}

template<class T>
void operator>>( const mongo::BSONElement &bel, std::vector<T> &v ) {
	auto barr = bel.Array();
	for ( auto & bson_el : barr ) {
		// This will only work if T has an empty constructor T()
		// I am not aware of a more general way of doing this though
		T el;
		bson_el >> el;
		v.push_back( el );
	}
}

template<class T>
void operator>>( const mongo::BSONElement &bel, std::list<T> &v ) {
	auto barr = bel.Array();
	for ( auto & bson_el : barr ) {
		// This will only work if T has an empty constructor T()
		// I am not aware of a more general way of doing this though
		T el;
		bson_el >> el;
		v.push_back( el );
	}
}

template<class T>
void operator>>( const mongo::BSONElement &bel, std::set<T> &v ) {
	auto barr = bel.Array();
	for ( auto & bson_el : barr ) {
		// This will only work if T has an empty constructor T()
		// I am not aware of a more general way of doing this though
		T el;
		bson_el >> el;
		v.insert( el );
	}
}

template<class K, class V>
void operator>>( const mongo::BSONObj &bobj, std::map<K,V> &map ) {
	for ( mongo::BSONObj::iterator i = bobj.begin(); i.more(); ) {
		mongo::BSONElement el = i.next();
		V value;
		el >> value;
		map[el.fieldName()] = value;
	}
}

/**
 * Stream in
 *
 * YAML works as follows:
 Emitter out;
 out << Emitter::Key << "name";
 out << Emitter::Value << "Ryan Braun";
 out << Emitter::Key << "position";
 out << Emitter::Value << "LF";
 BSONobj bobj = out.obj();

 I guess we should start with just building on BSONBuilder, which requires that
 a value could be any object, which then needs to be turned into a BSONElement, so
 one first needs to support <<( BSONElement &bel, T &t )

 It depends a bit on how BSONObjBuilder works if just adding my own classes
 to <<(BSONElement &bel, myclass &c ) will be enough,
 or do we need to use <<(BSONObjBuilder, myclass). If the second then it will be
 cleaner to add <<(BSONObjBuilder, T) which in turn calls <<(BSONElement, T)
 */

namespace mongo {
	class BSONEmitter;

	class BSONValueEmitter {
		public:
			BSONValueEmitter( BSONEmitter *pEmitter );

			template<class T>
				BSONEmitter &append( const T &t );

			BSONEmitter *pEmitter;
			BSONObjBuilderValueStream builder;
	};

	/**
	 * \brief Define an emitter for BSONObjects
	 *
	 * Behaviour is partly based on BSONObjBuilder, but different enough that
	 * we need a separate class
	 */
	class BSONEmitter {
		public:
			BSONEmitter() : builder( new BSONObjBuilder() ), v_emitter( this ) {}
			BSONEmitter( BSONObjBuilder *builder )
				: builder( builder ), v_emitter( this )
			{}

			BSONObj obj() {
				auto bobj = builder->obj();
				// This invalidates builder any way, so we can delete it
				delete builder;
				return bobj;
			}

			BSONValueEmitter &append( const std::string &name ) {
				v_emitter.builder.endField( name.c_str() );
				return v_emitter;
			}

			BSONValueEmitter &append( const char *name ) {
				v_emitter.builder.endField( name );
				return v_emitter;
			}

			BSONObjBuilder *builder;
			BSONValueEmitter v_emitter;
	};

	BSONValueEmitter::BSONValueEmitter( BSONEmitter *pEmitter )
		: pEmitter( pEmitter ), builder( pEmitter->builder ) {
		}

	template<class T>
		BSONEmitter &BSONValueEmitter::append( const T &t ) {
			//pEmitter->builder->append( t );
			pEmitter->builder = &(builder << t);
			return (*pEmitter);
		}

	class BSONArrayEmitter {
		public:
			BSONArrayEmitter() {}

			template<class T>
			BSONArrayEmitter &append( const T &t) {
				builder.append( t );
				return *this;
			}

			BSONArray arr() {
				return builder.arr();
			}

			BSONArrayBuilder builder;
	};

};
// Would prefer to define these as friend, but not possible due to
// BSONValueEmitter not being define at that point in the header file
template<class T>
mongo::BSONValueEmitter &operator<<( mongo::BSONEmitter &emitter, const T &t ) {
	return emitter.append( t );
}

//! For normal classes we need to convert them to an BSONObj first
//
//Below we override all the normal types
template<class T>
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &emitter, const T &t ) {
	mongo::BSONObjBuilder b;
	b << t;
	return emitter.append( b.obj() );
}

/**
 * \brief Override for standard types (as opposed to classes/objects)
 */
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &emitter, const double &t ) {
	return emitter.append( t );
}

mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &emitter, const long long &t ) {
	return emitter.append( t );
}

mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &emitter, const bool &t ) {
	return emitter.append( t );
}

mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &emitter, const int &t ) {
	return emitter.append( t );
}

mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &emitter, const std::string &t ) {
	return emitter.append( t );
}

/*
template<class K, class V>
mongo::BSONObjBuilder &operator<<( mongo::BSONObjBuilder &bbuild,
		const std::pair<K,V> &pair ) {
	bbuild << pair.first << pair.second;
	return bbuild;
}

template<class K, class V>
mongo::BSONObjBuilder &operator<<( mongo::BSONObjBuilder &bbuild,
		const std::map<K,V> &map ) {
	for ( auto pair : map ) {
		bbuild << pair;
	}
	return bbuild;
}

mongo::BSONObjBuilder &operator<<(
				mongo::BSONObjBuilderValueStream &bbuild, const double d ) {
	return bbuild << d;
}

template<class T>
mongo::BSONObjBuilder &operator<<(
				mongo::BSONObjBuilderValueStream &bbuild, const T &t ) {
	mongo::BSONObjBuilder bob;
	bob << t;
	return bbuild << bob.obj();
}

template<class K, class V>
mongo::BSONObjBuilder &operator<<( mongo::BSONObjBuilderValueStream &bbuild,
		const std::map<K,V> &map ) {
	mongo::BSONObjBuilder b;
	for ( auto pair : map )
		b << pair.first << pair.second;
	return bbuild << b.obj();
}

mongo::BSONObjBuilder &operator<<( mongo::BSONObjBuilderValueStream &bbuild,
		const std::vector<double> &vt ) {
	mongo::BSONArrayBuilder b;
	for ( auto el : vt ) {
		b << el;
	}
	return bbuild << b.arr();
}*/

//template<class T>
template<class T>
mongo::BSONArrayEmitter &operator<<( mongo::BSONArrayEmitter &barr,
		const T &t ) {
	mongo::BSONObjBuilder b;
	b << t;
	return barr.append( b.obj() );
}

mongo::BSONArrayEmitter &operator<<( mongo::BSONArrayEmitter &barr,
		const double &t ) {
	return barr.append( t );
}

mongo::BSONArrayEmitter &operator<<( mongo::BSONArrayEmitter &barr,
		const long long &t ) {
	return barr.append( t );
}

mongo::BSONArrayEmitter &operator<<( mongo::BSONArrayEmitter &barr,
		const bool &t ) {
	return barr.append( t );
}

mongo::BSONArrayEmitter &operator<<( mongo::BSONArrayEmitter &barr,
		const int &t ) {
	return barr.append( t );
}

mongo::BSONArrayEmitter &operator<<( mongo::BSONArrayEmitter &barr,
		const std::string &t ) {
	return barr.append( t );
}

template<class T>
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &bbuild,
		const std::vector<T> &vt ) {
	mongo::BSONArrayEmitter b;
	for ( const T &el : vt ) {
		b << el;
	}
	return bbuild.append( b.arr() );
}

template<class T>
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &bbuild,
		const std::set<T> &vt ) {
	mongo::BSONArrayEmitter b;
	for ( const T &el : vt ) {
		b << el;
	}
	return bbuild.append( b.arr() );
}

template<class T>
mongo::BSONEmitter &operator<<( mongo::BSONValueEmitter &bbuild,
		const std::list<T> &vt ) {
	mongo::BSONArrayEmitter b;
	for ( const T &el : vt ) {
		b << el;
	}
	return bbuild.append( b.arr() );
}

#endif
<|endoftext|>


<commit_before>// $Id$

//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project        *
//* ALICE Experiment at CERN, All rights reserved.                         *
//*                                                                        *
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
//*                  for The ALICE HLT Project.                            *
//*                                                                        *
//* Permission to use, copy, modify and distribute this software and its   *
//* documentation strictly for non-commercial purposes is hereby granted   *
//* without fee, provided that the above copyright notice appears in all   *
//* copies and that both the copyright notice and this permission notice   *
//* appear in the supporting documentation. The authors make no claims     *
//* about the suitability of this software for any purpose. It is          *
//* provided "as is" without express or implied warranty.                  *
//**************************************************************************

/** @file   AliHLTGlobalAgent.cxx
    @author Matthias Richter
    @date
    @brief  Agent of the libAliHLTGlobal library
*/

#include <cassert>
#include "AliHLTGlobalAgent.h"
#include "AliHLTConfigurationHandler.h"
#include "TObjString.h"
#include "TObjArray.h"
#include "AliHLTGlobalFlatEsdTestComponent.h"

// header files of library components
#include "AliHLTGlobalTrackMergerComponent.h"
#include "AliHLTGlobalCompareFlatComponent.h"
#include "AliHLTGlobalEsdToFlatConverterComponent.h"
#include "AliHLTGlobalFlatEsdConverterComponent.h"
#include "AliHLTGlobalEsdConverterComponent.h"
#include "AliHLTGlobalVertexerComponent.h"
#include "AliHLTGlobalOfflineVertexerComponent.h"
#include "AliHLTV0HistoComponent.h"
#include "AliHLTdNdPtAnalysisComponent.h"
#include "AliHLTdNdPtAnalysisMergerComponent.h"
#include "AliHLTGlobalVertexerHistoComponent.h"
#include "AliHLTGlobalHistoComponent.h"
#include "AliHLTGlobalHistoCollector.h"
#include "AliHLTGlobalDCSPublisherComponent.h"
#include "AliHLTMultiplicityCorrelationsComponent.h"
#include "AliHLTPrimaryVertexFinderComponent.h"
#include "AliHLTV0FinderComponent.h"
#include "AliHLTESDAnaManagerComponent.h"
#include "AliHLTFlatAnaManagerComponent.h"
#include "AliHLTTPCCalibManagerComponent.h"

// header file for preprocessor plugin
#include "AliHLTGlobalPreprocessor.h"

#define TESTING
#define NOCOMPRESS

/** global instance for agent registration */
AliHLTGlobalAgent gAliHLTGlobalAgent;

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTGlobalAgent)

AliHLTGlobalAgent::AliHLTGlobalAgent()
  :
  AliHLTModuleAgent("Global")
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}

AliHLTGlobalAgent::~AliHLTGlobalAgent()
{
  // see header file for class documentation
}

int AliHLTGlobalAgent::RegisterComponents(AliHLTComponentHandler* pHandler) const
{
  // see header file for class documentation
  assert(pHandler);
  if (!pHandler) return -EINVAL;
#ifdef TESTING
  pHandler->AddComponent(new AliHLTGlobalEsdToFlatConverterComponent);
  pHandler->AddComponent(new AliHLTGlobalCompareFlatComponent);
  pHandler->AddComponent(new AliHLTGlobalFlatEsdTestComponent);
#endif
  pHandler->AddComponent(new AliHLTGlobalTrackMergerComponent);
  pHandler->AddComponent(new AliHLTGlobalFlatEsdConverterComponent);
  pHandler->AddComponent(new AliHLTGlobalEsdConverterComponent);
  pHandler->AddComponent(new AliHLTGlobalVertexerComponent);
  pHandler->AddComponent(new AliHLTGlobalOfflineVertexerComponent);
  pHandler->AddComponent(new AliHLTGlobalVertexerHistoComponent);
  pHandler->AddComponent(new AliHLTGlobalHistoComponent);
  pHandler->AddComponent(new AliHLTV0HistoComponent );
  //pHandler->AddComponent(new AliHLTdNdPtAnalysisComponent );
  //pHandler->AddComponent(new AliHLTdNdPtAnalysisMergerComponent );
  pHandler->AddComponent(new AliHLTMultiplicityCorrelationsComponent );
  pHandler->AddComponent(new AliHLTPrimaryVertexFinderComponent);
  pHandler->AddComponent(new AliHLTV0FinderComponent);
  pHandler->AddComponent(new AliHLTGlobalHistoCollector );
  pHandler->AddComponent(new AliHLTGlobalDCSPublisherComponent );
  pHandler->AddComponent(new AliHLTESDAnaManagerComponent);
  pHandler->AddComponent(new AliHLTFlatAnaManagerComponent);
  pHandler->AddComponent(new AliHLTTPCCalibManagerComponent);
  return 0;
}

int AliHLTGlobalAgent::CreateConfigurations(AliHLTConfigurationHandler* pHandler,
					    AliRawReader* /*rawReader*/,
					    AliRunLoader* /*runloader*/) const
{
  // see header file for class documentation
  if (!pHandler) return -EINVAL;
  TObjArray* pTokens=NULL;

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // global vertexer component
  //
  // define the inputs
  TString vertexerInputs="TPC-globalmerger ITS-tracker";

  // check for the availibility
  pTokens=vertexerInputs.Tokenize(" ");
  vertexerInputs="";
  if (pTokens) {
    for (int n=0; n<pTokens->GetEntriesFast(); n++) {
      TString module=((TObjString*)pTokens->At(n))->GetString();
      if (pHandler->FindConfiguration(module.Data())) {
	vertexerInputs+=module;
	vertexerInputs+=" ";
      }
    }
    delete pTokens;
    pTokens=NULL;
  }
  cout<<endl<<"\n\nConfiguring inputs to global HLT Vertexer: %s\n\n"<<vertexerInputs.Data()<<endl<<endl;
  if (!vertexerInputs.IsNull()) {
    HLTInfo("\n\nConfiguring inputs to global HLT Vertexer: %s\n\n", vertexerInputs.Data());
    pHandler->CreateConfiguration("GLOBAL-vertexer","GlobalVertexer",vertexerInputs,"");
  } else {
    HLTWarning("\n\nNo inputs to global HLT Vertexer found\n\n");
  }

  /////////////////////////////////////////////////////////////////////////////////////
  //
  // assembly of the global ESD

  // define the inputs to the global ESD
  TString esdInputs="TPC-globalmerger TPC-mcTrackMarker ITS-tracker TPC-ClusterTransformation GLOBAL-vertexer ITS-SPD-vertexer TPC-dEdx VZERO-RECO ITS-SAPtracker";

  // check for the availibility
  pTokens=esdInputs.Tokenize(" ");
  esdInputs="";
  if (pTokens) {
    for (int n=0; n<pTokens->GetEntriesFast(); n++) {
      TString module=((TObjString*)pTokens->At(n))->GetString();
      if (pHandler->FindConfiguration(module.Data())) {
	esdInputs+=module;
	esdInputs+=" ";
      }
    }
    delete pTokens;
    pTokens=NULL;
  }

  if (esdInputs.Length()>0) {
    esdInputs+=" TPC-ClusterTransformation";
    HLTInfo("Configuring inputs to global HLT ESD: %s", esdInputs.Data());
  } else {
    HLTWarning("No inputs to global HLT ESD found");
  }
#ifdef NOCOMPRESS
  pHandler->CreateConfiguration("GLOBAL-flat-esd-converter", "GlobalFlatEsdConverter", esdInputs.Data(), "-object-compression=0");
  pHandler->CreateConfiguration("GLOBAL-esd-converter", "GlobalEsdConverter", esdInputs.Data(), "-object-compression=0");
#endif

#ifndef NOCOMPRESS
  pHandler->CreateConfiguration("GLOBAL-flat-esd-converter", "GlobalFlatEsdConverter", esdInputs.Data(), "");
  pHandler->CreateConfiguration("GLOBAL-esd-converter", "GlobalEsdConverter", esdInputs.Data(), "");
#endif

#ifdef TESTING
  pHandler->CreateConfiguration("GLOBAL-flat-esd-test", "GlobalFlatEsdTest", "GLOBAL-esd-converter GLOBAL-flat-esd-converter", "");
  pHandler->CreateConfiguration("esd-to-flat-conversion", "GlobalEsdToFlatConverter", "GLOBAL-esd-converter", "");
  pHandler->CreateConfiguration("compare-flat", "GlobalCompareFlat", "GLOBAL-flat-esd-converter esd-to-flat-conversion", "");
#endif

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // global histograms
  //
  TString vertexhistoInput="GLOBAL-vertexer ITS-SPD-vertexer";

  // check for the availibility
  pTokens=vertexhistoInput.Tokenize(" ");
  vertexhistoInput="";
  if (pTokens) {
    for (int n=0; n<pTokens->GetEntriesFast(); n++) {
      TString module=((TObjString*)pTokens->At(n))->GetString();
      if (pHandler->FindConfiguration(module.Data())) {
	vertexhistoInput+=module;
	vertexhistoInput+=" ";
      }
    }
    delete pTokens;
    pTokens=NULL;
  }

  if (!vertexhistoInput.IsNull()) {
    HLTInfo("Configuring inputs to global HLT Vertex histogram component: %s", vertexhistoInput.Data());
    pHandler->CreateConfiguration("GLOBAL-vertexhisto","GlobalVertexerHisto", vertexhistoInput.Data(),"");
  } else {
    HLTWarning("No inputs to global HLT Vertex histogram component found");
  }

  //pHandler->CreateConfiguration("GLOBAL-dNdPtAnalysis", "dNdPtAnalysis", "GLOBAL-esd-converter", "");

  pHandler->CreateConfiguration("GLOBAL-MultCorr", "MultiplicityCorrelations", "GLOBAL-esd-converter", "");

  return 0;
}

const char* AliHLTGlobalAgent::GetReconstructionChains(AliRawReader* /*rawReader*/,
						    AliRunLoader* runloader) const
{
  // see header file for class documentation
  if (runloader) {
    // reconstruction chains for AliRoot simulation
    // Note: run loader is only available while running embedded into
    // AliRoot simulation
    return "GLOBAL-esd-converter";
  }
  return NULL;
}

const char* AliHLTGlobalAgent::GetRequiredComponentLibraries() const
{
  // see header file for class documentation

  return "";
}

int AliHLTGlobalAgent::GetHandlerDescription(AliHLTComponentDataType /*dt*/,
					     AliHLTUInt32_t /*spec*/,
					     AliHLTOUTHandlerDesc& /*desc*/) const
{
  // see header file for class documentation

  return 0;
}

AliHLTOUTHandler* AliHLTGlobalAgent::GetOutputHandler(AliHLTComponentDataType /*dt*/,
						      AliHLTUInt32_t /*spec*/)
{
  // see header file for class documentation

  return NULL;
}

int AliHLTGlobalAgent::DeleteOutputHandler(AliHLTOUTHandler* pInstance)
{
  // see header file for class documentation
  if (pInstance==NULL) return -EINVAL;

  return 0;
}

AliHLTModulePreprocessor* AliHLTGlobalAgent::GetPreprocessor()
{
  // create the preprocessor plugin
  return new AliHLTGlobalPreprocessor;
}
<commit_msg>more cleanup<commit_after>// $Id$

//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project        *
//* ALICE Experiment at CERN, All rights reserved.                         *
//*                                                                        *
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
//*                  for The ALICE HLT Project.                            *
//*                                                                        *
//* Permission to use, copy, modify and distribute this software and its   *
//* documentation strictly for non-commercial purposes is hereby granted   *
//* without fee, provided that the above copyright notice appears in all   *
//* copies and that both the copyright notice and this permission notice   *
//* appear in the supporting documentation. The authors make no claims     *
//* about the suitability of this software for any purpose. It is          *
//* provided "as is" without express or implied warranty.                  *
//**************************************************************************

/** @file   AliHLTGlobalAgent.cxx
    @author Matthias Richter
    @date
    @brief  Agent of the libAliHLTGlobal library
*/

#include <cassert>
#include "AliHLTGlobalAgent.h"
#include "AliHLTConfigurationHandler.h"
#include "TObjString.h"
#include "TObjArray.h"
#include "AliHLTGlobalFlatEsdTestComponent.h"

// header files of library components
#include "AliHLTGlobalTrackMergerComponent.h"
#include "AliHLTGlobalCompareFlatComponent.h"
#include "AliHLTGlobalEsdToFlatConverterComponent.h"
#include "AliHLTGlobalFlatEsdConverterComponent.h"
#include "AliHLTGlobalEsdConverterComponent.h"
#include "AliHLTGlobalVertexerComponent.h"
#include "AliHLTGlobalOfflineVertexerComponent.h"
#include "AliHLTV0HistoComponent.h"
#include "AliHLTdNdPtAnalysisComponent.h"
#include "AliHLTdNdPtAnalysisMergerComponent.h"
#include "AliHLTGlobalVertexerHistoComponent.h"
#include "AliHLTGlobalHistoComponent.h"
#include "AliHLTGlobalHistoCollector.h"
#include "AliHLTGlobalDCSPublisherComponent.h"
#include "AliHLTMultiplicityCorrelationsComponent.h"
#include "AliHLTPrimaryVertexFinderComponent.h"
#include "AliHLTV0FinderComponent.h"
#include "AliHLTESDAnaManagerComponent.h"
#include "AliHLTFlatAnaManagerComponent.h"
#include "AliHLTTPCCalibManagerComponent.h"

// header file for preprocessor plugin
#include "AliHLTGlobalPreprocessor.h"

#define NOCOMPRESS

/** global instance for agent registration */
AliHLTGlobalAgent gAliHLTGlobalAgent;

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTGlobalAgent)

AliHLTGlobalAgent::AliHLTGlobalAgent()
  :
  AliHLTModuleAgent("Global")
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}

AliHLTGlobalAgent::~AliHLTGlobalAgent()
{
  // see header file for class documentation
}

int AliHLTGlobalAgent::RegisterComponents(AliHLTComponentHandler* pHandler) const
{
  // see header file for class documentation
  assert(pHandler);
  if (!pHandler) return -EINVAL;
  pHandler->AddComponent(new AliHLTGlobalEsdToFlatConverterComponent);
  pHandler->AddComponent(new AliHLTGlobalCompareFlatComponent);
  pHandler->AddComponent(new AliHLTGlobalFlatEsdTestComponent);
  pHandler->AddComponent(new AliHLTGlobalTrackMergerComponent);
  pHandler->AddComponent(new AliHLTGlobalFlatEsdConverterComponent);
  pHandler->AddComponent(new AliHLTGlobalEsdConverterComponent);
  pHandler->AddComponent(new AliHLTGlobalVertexerComponent);
  pHandler->AddComponent(new AliHLTGlobalOfflineVertexerComponent);
  pHandler->AddComponent(new AliHLTGlobalVertexerHistoComponent);
  pHandler->AddComponent(new AliHLTGlobalHistoComponent);
  pHandler->AddComponent(new AliHLTV0HistoComponent );
  //pHandler->AddComponent(new AliHLTdNdPtAnalysisComponent );
  //pHandler->AddComponent(new AliHLTdNdPtAnalysisMergerComponent );
  pHandler->AddComponent(new AliHLTMultiplicityCorrelationsComponent );
  pHandler->AddComponent(new AliHLTPrimaryVertexFinderComponent);
  pHandler->AddComponent(new AliHLTV0FinderComponent);
  pHandler->AddComponent(new AliHLTGlobalHistoCollector );
  pHandler->AddComponent(new AliHLTGlobalDCSPublisherComponent );
  pHandler->AddComponent(new AliHLTESDAnaManagerComponent);
  pHandler->AddComponent(new AliHLTFlatAnaManagerComponent);
  pHandler->AddComponent(new AliHLTTPCCalibManagerComponent);
  return 0;
}

int AliHLTGlobalAgent::CreateConfigurations(AliHLTConfigurationHandler* pHandler,
					    AliRawReader* /*rawReader*/,
					    AliRunLoader* /*runloader*/) const
{
  // see header file for class documentation
  if (!pHandler) return -EINVAL;
  TObjArray* pTokens=NULL;

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // global vertexer component
  //
  // define the inputs
  TString vertexerInputs="TPC-globalmerger ITS-tracker";

  // check for the availibility
  pTokens=vertexerInputs.Tokenize(" ");
  vertexerInputs="";
  if (pTokens) {
    for (int n=0; n<pTokens->GetEntriesFast(); n++) {
      TString module=((TObjString*)pTokens->At(n))->GetString();
      if (pHandler->FindConfiguration(module.Data())) {
	vertexerInputs+=module;
	vertexerInputs+=" ";
      }
    }
    delete pTokens;
    pTokens=NULL;
  }
  cout<<endl<<"\n\nConfiguring inputs to global HLT Vertexer: %s\n\n"<<vertexerInputs.Data()<<endl<<endl;
  if (!vertexerInputs.IsNull()) {
    HLTInfo("\n\nConfiguring inputs to global HLT Vertexer: %s\n\n", vertexerInputs.Data());
    pHandler->CreateConfiguration("GLOBAL-vertexer","GlobalVertexer",vertexerInputs,"");
  } else {
    HLTWarning("\n\nNo inputs to global HLT Vertexer found\n\n");
  }

  /////////////////////////////////////////////////////////////////////////////////////
  //
  // assembly of the global ESD

  // define the inputs to the global ESD
  TString esdInputs="TPC-globalmerger TPC-mcTrackMarker ITS-tracker TPC-ClusterTransformation GLOBAL-vertexer ITS-SPD-vertexer TPC-dEdx VZERO-RECO ITS-SAPtracker";

  // check for the availibility
  pTokens=esdInputs.Tokenize(" ");
  esdInputs="";
  if (pTokens) {
    for (int n=0; n<pTokens->GetEntriesFast(); n++) {
      TString module=((TObjString*)pTokens->At(n))->GetString();
      if (pHandler->FindConfiguration(module.Data())) {
	esdInputs+=module;
	esdInputs+=" ";
      }
    }
    delete pTokens;
    pTokens=NULL;
  }

  if (esdInputs.Length()>0) {
    esdInputs+=" TPC-ClusterTransformation";
    HLTInfo("Configuring inputs to global HLT ESD: %s", esdInputs.Data());
  } else {
    HLTWarning("No inputs to global HLT ESD found");
  }
#ifdef NOCOMPRESS
  pHandler->CreateConfiguration("GLOBAL-flat-esd-converter", "GlobalFlatEsdConverter", esdInputs.Data(), "-object-compression=0");
  pHandler->CreateConfiguration("GLOBAL-esd-converter", "GlobalEsdConverter", esdInputs.Data(), "-object-compression=0");
#endif

#ifndef NOCOMPRESS
  pHandler->CreateConfiguration("GLOBAL-flat-esd-converter", "GlobalFlatEsdConverter", esdInputs.Data(), "");
  pHandler->CreateConfiguration("GLOBAL-esd-converter", "GlobalEsdConverter", esdInputs.Data(), "");
#endif
  pHandler->CreateConfiguration("GLOBAL-flat-esd-test", "GlobalFlatEsdTest", "GLOBAL-esd-converter GLOBAL-flat-esd-converter", "");
  pHandler->CreateConfiguration("esd-to-flat-conversion", "GlobalEsdToFlatConverter", "GLOBAL-esd-converter", "");
  pHandler->CreateConfiguration("compare-flat", "GlobalCompareFlat", "GLOBAL-flat-esd-converter esd-to-flat-conversion", "");

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // global histograms
  //
  TString vertexhistoInput="GLOBAL-vertexer ITS-SPD-vertexer";

  // check for the availibility
  pTokens=vertexhistoInput.Tokenize(" ");
  vertexhistoInput="";
  if (pTokens) {
    for (int n=0; n<pTokens->GetEntriesFast(); n++) {
      TString module=((TObjString*)pTokens->At(n))->GetString();
      if (pHandler->FindConfiguration(module.Data())) {
	vertexhistoInput+=module;
	vertexhistoInput+=" ";
      }
    }
    delete pTokens;
    pTokens=NULL;
  }

  if (!vertexhistoInput.IsNull()) {
    HLTInfo("Configuring inputs to global HLT Vertex histogram component: %s", vertexhistoInput.Data());
    pHandler->CreateConfiguration("GLOBAL-vertexhisto","GlobalVertexerHisto", vertexhistoInput.Data(),"");
  } else {
    HLTWarning("No inputs to global HLT Vertex histogram component found");
  }

  //pHandler->CreateConfiguration("GLOBAL-dNdPtAnalysis", "dNdPtAnalysis", "GLOBAL-esd-converter", "");

  pHandler->CreateConfiguration("GLOBAL-MultCorr", "MultiplicityCorrelations", "GLOBAL-esd-converter", "");

  return 0;
}

const char* AliHLTGlobalAgent::GetReconstructionChains(AliRawReader* /*rawReader*/,
						    AliRunLoader* runloader) const
{
  // see header file for class documentation
  if (runloader) {
    // reconstruction chains for AliRoot simulation
    // Note: run loader is only available while running embedded into
    // AliRoot simulation
    return "GLOBAL-esd-converter";
  }
  return NULL;
}

const char* AliHLTGlobalAgent::GetRequiredComponentLibraries() const
{
  // see header file for class documentation

  return "";
}

int AliHLTGlobalAgent::GetHandlerDescription(AliHLTComponentDataType /*dt*/,
					     AliHLTUInt32_t /*spec*/,
					     AliHLTOUTHandlerDesc& /*desc*/) const
{
  // see header file for class documentation

  return 0;
}

AliHLTOUTHandler* AliHLTGlobalAgent::GetOutputHandler(AliHLTComponentDataType /*dt*/,
						      AliHLTUInt32_t /*spec*/)
{
  // see header file for class documentation

  return NULL;
}

int AliHLTGlobalAgent::DeleteOutputHandler(AliHLTOUTHandler* pInstance)
{
  // see header file for class documentation
  if (pInstance==NULL) return -EINVAL;

  return 0;
}

AliHLTModulePreprocessor* AliHLTGlobalAgent::GetPreprocessor()
{
  // create the preprocessor plugin
  return new AliHLTGlobalPreprocessor;
}
<|endoftext|>