<commit_before>/***********************************************************************
    filename:   CEGUIOgreGeometryBuffer.cpp
    created:    Tue Feb 17 2009
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2013 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 "CEGUI/RendererModules/Ogre/GeometryBuffer.h"
#include "CEGUI/RendererModules/Ogre/Texture.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/RenderEffect.h"

#include <OgreRenderSystem.h>
#include <OgreQuaternion.h>
#include <OgreHardwareBufferManager.h>

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
static const Ogre::LayerBlendModeEx S_colourBlendMode =
{
    Ogre::LBT_COLOUR,
    Ogre::LBX_MODULATE,
    Ogre::LBS_TEXTURE,
    Ogre::LBS_DIFFUSE
};

//----------------------------------------------------------------------------//
static const Ogre::LayerBlendModeEx S_alphaBlendMode =
{
    Ogre::LBT_ALPHA,
    Ogre::LBX_MODULATE,
    Ogre::LBS_TEXTURE,
    Ogre::LBS_DIFFUSE
};

//----------------------------------------------------------------------------//
static const Ogre::TextureUnitState::UVWAddressingMode S_textureAddressMode =
{
    Ogre::TextureUnitState::TAM_CLAMP,
    Ogre::TextureUnitState::TAM_CLAMP,
    Ogre::TextureUnitState::TAM_CLAMP
};

//----------------------------------------------------------------------------//
// Helper to allocate a vertex buffer and initialse a Ogre::RenderOperation
static void initialiseRenderOp(Ogre::RenderOperation& rop,
                               Ogre::HardwareVertexBufferSharedPtr& vb,
                               size_t count)
{
    using namespace Ogre;

    // basic initialisation of render op
    rop.vertexData = OGRE_NEW VertexData();
    rop.operationType = RenderOperation::OT_TRIANGLE_LIST;
    rop.useIndexes = false;

    // setup vertex declaration for format we will use
    VertexDeclaration* vd = rop.vertexData->vertexDeclaration;
    size_t vd_offset = 0;
    vd->addElement(0, vd_offset, VET_FLOAT3, VES_POSITION);
    vd_offset += VertexElement::getTypeSize(VET_FLOAT3);
    vd->addElement(0, vd_offset, VET_COLOUR, VES_DIFFUSE);
    vd_offset += VertexElement::getTypeSize(VET_COLOUR);
    vd->addElement(0, vd_offset, VET_FLOAT2, VES_TEXTURE_COORDINATES);

    // create hardware vertex buffer
    vb = HardwareBufferManager::getSingleton().createVertexBuffer(
            vd->getVertexSize(0), count,
            HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE,
            false);

    // bind vertex buffer
    rop.vertexData->vertexBufferBinding->setBinding(0, vb);
}

//----------------------------------------------------------------------------//
// Helper to cleanup what initialiseRenderOp did.
static void cleanupRenderOp(Ogre::RenderOperation& rop,
                            Ogre::HardwareVertexBufferSharedPtr& vb)
{
    OGRE_DELETE rop.vertexData;
    rop.vertexData = 0;
    vb.setNull();
}

//----------------------------------------------------------------------------//
OgreGeometryBuffer::OgreGeometryBuffer(OgreRenderer& owner,
                                       Ogre::RenderSystem& rs) :
    d_owner(owner),
    d_renderSystem(rs),
    d_activeTexture(0),
    d_clipRect(0, 0, 0, 0),
    d_clippingActive(true),
    d_translation(0, 0, 0),
    d_rotation(Quaternion::IDENTITY),
    d_pivot(0, 0, 0),
    d_effect(0),
    d_texelOffset(rs.getHorizontalTexelOffset(), rs.getVerticalTexelOffset()),
    d_matrixValid(false),
    d_sync(false)
{
    initialiseRenderOp(d_renderOp, d_hwBuffer, 64);
}

//----------------------------------------------------------------------------//
OgreGeometryBuffer::~OgreGeometryBuffer()
{
    cleanupRenderOp(d_renderOp, d_hwBuffer);
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::draw() const
{
    if (!d_sync)
        syncHardwareBuffer();

    d_owner.setWorldMatrix(getMatrix());
    d_owner.setupRenderingBlendMode(d_blendMode);
    d_owner.updateShaderParams();

    const int pass_count = d_effect ? d_effect->getPassCount() : 1;
    for (int pass = 0; pass < pass_count; ++pass)
    {
        // set up RenderEffect
        if (d_effect)
            d_effect->performPreRenderFunctions(pass);

        // draw the batches
        size_t pos = 0;
        BatchList::const_iterator i = d_batches.begin();
        for ( ; i != d_batches.end(); ++i)
        {
            // Set up clipping for this buffer
            d_renderSystem.setScissorTest(
                i->clip, d_clipRect.left(), d_clipRect.top(),
                         d_clipRect.right(), d_clipRect.bottom());

            d_renderOp.vertexData->vertexStart = pos;
            d_renderOp.vertexData->vertexCount = i->vertexCount;
            d_renderSystem._setTexture(0, true, i->texture);
            initialiseTextureStates();
            d_renderSystem._render(d_renderOp);
            pos += i->vertexCount;
        }
    }

    // clean up RenderEffect
    if (d_effect)
        d_effect->performPostRenderFunctions();
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::setTranslation(const Vector3f& v)
{
    d_translation = v;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::setRotation(const Quaternion& r)
{
    d_rotation = r;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::setPivot(const Vector3f& p)
{
    d_pivot = p;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::setClippingRegion(const Rectf& region)
{
    d_clipRect.top(ceguimax(0.0f, region.top()));
    d_clipRect.bottom(ceguimax(0.0f, region.bottom()));
    d_clipRect.left(ceguimax(0.0f, region.left()));
    d_clipRect.right(ceguimax(0.0f, region.right()));
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::appendVertex(const Vertex& vertex)
{
    appendGeometry(&vertex, 1);
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::appendGeometry(const Vertex* const vbuff,
                                        uint vertex_count)
{
    // see if we should start a new batch
    Ogre::TexturePtr t;
    if (d_activeTexture)
        t = d_activeTexture->getOgreTexture();

    if (d_batches.empty() ||
        d_batches.back().texture != t ||
        d_batches.back().clip != d_clippingActive)
    {
        const BatchInfo batch = {t, 0, d_clippingActive};
        d_batches.push_back(batch);
    }

    // update size of current batch
    d_batches.back().vertexCount += vertex_count;

    // buffer these vertices
    OgreVertex v;
    for (uint i = 0; i < vertex_count; ++i)
    {
        const Vertex& vs = vbuff[i];
        // convert from CEGUI::Vertex to something directly usable by Ogre.
        v.x       = vs.position.d_x + d_texelOffset.d_x;
        v.y       = vs.position.d_y + d_texelOffset.d_y;
        v.z       = vs.position.d_z;
        v.diffuse = colourToOgre(vs.colour_val);
        v.u       = vs.tex_coords.d_x;
        v.v       = vs.tex_coords.d_y;

        d_vertices.push_back(v);
    }

    d_sync = false;
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::setActiveTexture(Texture* texture)
{
    d_activeTexture = static_cast<OgreTexture*>(texture);
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::reset()
{
    d_vertices.clear();
    d_batches.clear();
    d_activeTexture = 0;
    d_sync = false;
}

//----------------------------------------------------------------------------//
Texture* OgreGeometryBuffer::getActiveTexture() const
{
    return d_activeTexture;
}

//----------------------------------------------------------------------------//
uint OgreGeometryBuffer::getVertexCount() const
{
    return d_vertices.size();
}

//----------------------------------------------------------------------------//
uint OgreGeometryBuffer::getBatchCount() const
{
    return d_batches.size();
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::setRenderEffect(RenderEffect* effect)
{
    d_effect = effect;
}

//----------------------------------------------------------------------------//
RenderEffect* OgreGeometryBuffer::getRenderEffect()
{
    return d_effect;
}

//----------------------------------------------------------------------------//
Ogre::RGBA OgreGeometryBuffer::colourToOgre(const Colour& col) const
{
    Ogre::ColourValue ocv(col.getRed(),
                          col.getGreen(),
                          col.getBlue(),
                          col.getAlpha());

    uint32 final;
    d_renderSystem.convertColourValue(ocv, &final);

    return final;
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::updateMatrix() const
{
    // translation to position geometry and offset to pivot point
    Ogre::Matrix4 trans;
    trans.makeTrans(d_translation.d_x + d_pivot.d_x,
                    d_translation.d_y + d_pivot.d_y,
                    d_translation.d_z + d_pivot.d_z);

    // rotation
    Ogre::Matrix4 rot(Ogre::Quaternion(
        d_rotation.d_w, d_rotation.d_x, d_rotation.d_y, d_rotation.d_z));

    // translation to remove rotation pivot offset
    Ogre::Matrix4 inv_pivot_trans;
    inv_pivot_trans.makeTrans(-d_pivot.d_x, -d_pivot.d_y, -d_pivot.d_z);

    // calculate final matrix
    d_matrix = trans * rot * inv_pivot_trans;

    d_matrixValid = true;
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::syncHardwareBuffer() const
{
    // Reallocate h/w buffer as requied
    size_t size = d_hwBuffer->getNumVertices();
    const size_t required_size = d_vertices.size();
    if(size < required_size)
    {
        // calculate new size to use
        while(size < required_size)
            size *= 2;

        // Reallocate the buffer
        cleanupRenderOp(d_renderOp, d_hwBuffer);
        initialiseRenderOp(d_renderOp, d_hwBuffer, size);
    }

    // copy vertex data into hw buffer
    if (required_size > 0)
    {
        std::memcpy(d_hwBuffer->lock(Ogre::HardwareVertexBuffer::HBL_DISCARD),
                    &d_vertices[0], sizeof(OgreVertex) * d_vertices.size());

        d_hwBuffer->unlock();
    }

    d_sync = true;
}

//----------------------------------------------------------------------------//
const Ogre::Matrix4& OgreGeometryBuffer::getMatrix() const
{
    if (!d_matrixValid)
        updateMatrix();

    return d_matrix;
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::initialiseTextureStates() const
{
    using namespace Ogre;
    d_renderSystem._setTextureCoordCalculation(0, TEXCALC_NONE);
    d_renderSystem._setTextureCoordSet(0, 0);
    d_renderSystem._setTextureUnitFiltering(0, FO_LINEAR, FO_LINEAR, FO_POINT);
    d_renderSystem._setTextureAddressingMode(0, S_textureAddressMode);
    d_renderSystem._setTextureMatrix(0, Matrix4::IDENTITY);
    d_renderSystem._setAlphaRejectSettings(CMPF_ALWAYS_PASS, 0, false);
    d_renderSystem._setTextureBlendMode(0, S_colourBlendMode);
    d_renderSystem._setTextureBlendMode(0, S_alphaBlendMode);
    d_renderSystem._disableTextureUnitsFrom(1);
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::setClippingActive(const bool active)
{
    d_clippingActive = active;
}

//----------------------------------------------------------------------------//
bool OgreGeometryBuffer::isClippingActive() const
{
    return d_clippingActive;
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<commit_msg>Complete initialization of Ogre::LayerBlendModeEx objects.<commit_after>/***********************************************************************
    filename:   CEGUIOgreGeometryBuffer.cpp
    created:    Tue Feb 17 2009
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2013 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 "CEGUI/RendererModules/Ogre/GeometryBuffer.h"
#include "CEGUI/RendererModules/Ogre/Texture.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/RenderEffect.h"

#include <OgreRenderSystem.h>
#include <OgreQuaternion.h>
#include <OgreHardwareBufferManager.h>

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
static const Ogre::LayerBlendModeEx S_colourBlendMode =
{
    Ogre::LBT_COLOUR,
    Ogre::LBX_MODULATE,
    Ogre::LBS_TEXTURE,
    Ogre::LBS_DIFFUSE,
    Ogre::ColourValue(0, 0, 0, 0),
    Ogre::ColourValue(0, 0, 0, 0),
    0, 0, 0
};

//----------------------------------------------------------------------------//
static const Ogre::LayerBlendModeEx S_alphaBlendMode =
{
    Ogre::LBT_ALPHA,
    Ogre::LBX_MODULATE,
    Ogre::LBS_TEXTURE,
    Ogre::LBS_DIFFUSE,
    Ogre::ColourValue(0, 0, 0, 0),
    Ogre::ColourValue(0, 0, 0, 0),
    0, 0, 0
};

//----------------------------------------------------------------------------//
static const Ogre::TextureUnitState::UVWAddressingMode S_textureAddressMode =
{
    Ogre::TextureUnitState::TAM_CLAMP,
    Ogre::TextureUnitState::TAM_CLAMP,
    Ogre::TextureUnitState::TAM_CLAMP
};

//----------------------------------------------------------------------------//
// Helper to allocate a vertex buffer and initialse a Ogre::RenderOperation
static void initialiseRenderOp(Ogre::RenderOperation& rop,
                               Ogre::HardwareVertexBufferSharedPtr& vb,
                               size_t count)
{
    using namespace Ogre;

    // basic initialisation of render op
    rop.vertexData = OGRE_NEW VertexData();
    rop.operationType = RenderOperation::OT_TRIANGLE_LIST;
    rop.useIndexes = false;

    // setup vertex declaration for format we will use
    VertexDeclaration* vd = rop.vertexData->vertexDeclaration;
    size_t vd_offset = 0;
    vd->addElement(0, vd_offset, VET_FLOAT3, VES_POSITION);
    vd_offset += VertexElement::getTypeSize(VET_FLOAT3);
    vd->addElement(0, vd_offset, VET_COLOUR, VES_DIFFUSE);
    vd_offset += VertexElement::getTypeSize(VET_COLOUR);
    vd->addElement(0, vd_offset, VET_FLOAT2, VES_TEXTURE_COORDINATES);

    // create hardware vertex buffer
    vb = HardwareBufferManager::getSingleton().createVertexBuffer(
            vd->getVertexSize(0), count,
            HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE,
            false);

    // bind vertex buffer
    rop.vertexData->vertexBufferBinding->setBinding(0, vb);
}

//----------------------------------------------------------------------------//
// Helper to cleanup what initialiseRenderOp did.
static void cleanupRenderOp(Ogre::RenderOperation& rop,
                            Ogre::HardwareVertexBufferSharedPtr& vb)
{
    OGRE_DELETE rop.vertexData;
    rop.vertexData = 0;
    vb.setNull();
}

//----------------------------------------------------------------------------//
OgreGeometryBuffer::OgreGeometryBuffer(OgreRenderer& owner,
                                       Ogre::RenderSystem& rs) :
    d_owner(owner),
    d_renderSystem(rs),
    d_activeTexture(0),
    d_clipRect(0, 0, 0, 0),
    d_clippingActive(true),
    d_translation(0, 0, 0),
    d_rotation(Quaternion::IDENTITY),
    d_pivot(0, 0, 0),
    d_effect(0),
    d_texelOffset(rs.getHorizontalTexelOffset(), rs.getVerticalTexelOffset()),
    d_matrixValid(false),
    d_sync(false)
{
    initialiseRenderOp(d_renderOp, d_hwBuffer, 64);
}

//----------------------------------------------------------------------------//
OgreGeometryBuffer::~OgreGeometryBuffer()
{
    cleanupRenderOp(d_renderOp, d_hwBuffer);
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::draw() const
{
    if (!d_sync)
        syncHardwareBuffer();

    d_owner.setWorldMatrix(getMatrix());
    d_owner.setupRenderingBlendMode(d_blendMode);
    d_owner.updateShaderParams();

    const int pass_count = d_effect ? d_effect->getPassCount() : 1;
    for (int pass = 0; pass < pass_count; ++pass)
    {
        // set up RenderEffect
        if (d_effect)
            d_effect->performPreRenderFunctions(pass);

        // draw the batches
        size_t pos = 0;
        BatchList::const_iterator i = d_batches.begin();
        for ( ; i != d_batches.end(); ++i)
        {
            // Set up clipping for this buffer
            d_renderSystem.setScissorTest(
                i->clip, d_clipRect.left(), d_clipRect.top(),
                         d_clipRect.right(), d_clipRect.bottom());

            d_renderOp.vertexData->vertexStart = pos;
            d_renderOp.vertexData->vertexCount = i->vertexCount;
            d_renderSystem._setTexture(0, true, i->texture);
            initialiseTextureStates();
            d_renderSystem._render(d_renderOp);
            pos += i->vertexCount;
        }
    }

    // clean up RenderEffect
    if (d_effect)
        d_effect->performPostRenderFunctions();
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::setTranslation(const Vector3f& v)
{
    d_translation = v;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::setRotation(const Quaternion& r)
{
    d_rotation = r;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::setPivot(const Vector3f& p)
{
    d_pivot = p;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::setClippingRegion(const Rectf& region)
{
    d_clipRect.top(ceguimax(0.0f, region.top()));
    d_clipRect.bottom(ceguimax(0.0f, region.bottom()));
    d_clipRect.left(ceguimax(0.0f, region.left()));
    d_clipRect.right(ceguimax(0.0f, region.right()));
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::appendVertex(const Vertex& vertex)
{
    appendGeometry(&vertex, 1);
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::appendGeometry(const Vertex* const vbuff,
                                        uint vertex_count)
{
    // see if we should start a new batch
    Ogre::TexturePtr t;
    if (d_activeTexture)
        t = d_activeTexture->getOgreTexture();

    if (d_batches.empty() ||
        d_batches.back().texture != t ||
        d_batches.back().clip != d_clippingActive)
    {
        const BatchInfo batch = {t, 0, d_clippingActive};
        d_batches.push_back(batch);
    }

    // update size of current batch
    d_batches.back().vertexCount += vertex_count;

    // buffer these vertices
    OgreVertex v;
    for (uint i = 0; i < vertex_count; ++i)
    {
        const Vertex& vs = vbuff[i];
        // convert from CEGUI::Vertex to something directly usable by Ogre.
        v.x       = vs.position.d_x + d_texelOffset.d_x;
        v.y       = vs.position.d_y + d_texelOffset.d_y;
        v.z       = vs.position.d_z;
        v.diffuse = colourToOgre(vs.colour_val);
        v.u       = vs.tex_coords.d_x;
        v.v       = vs.tex_coords.d_y;

        d_vertices.push_back(v);
    }

    d_sync = false;
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::setActiveTexture(Texture* texture)
{
    d_activeTexture = static_cast<OgreTexture*>(texture);
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::reset()
{
    d_vertices.clear();
    d_batches.clear();
    d_activeTexture = 0;
    d_sync = false;
}

//----------------------------------------------------------------------------//
Texture* OgreGeometryBuffer::getActiveTexture() const
{
    return d_activeTexture;
}

//----------------------------------------------------------------------------//
uint OgreGeometryBuffer::getVertexCount() const
{
    return d_vertices.size();
}

//----------------------------------------------------------------------------//
uint OgreGeometryBuffer::getBatchCount() const
{
    return d_batches.size();
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::setRenderEffect(RenderEffect* effect)
{
    d_effect = effect;
}

//----------------------------------------------------------------------------//
RenderEffect* OgreGeometryBuffer::getRenderEffect()
{
    return d_effect;
}

//----------------------------------------------------------------------------//
Ogre::RGBA OgreGeometryBuffer::colourToOgre(const Colour& col) const
{
    Ogre::ColourValue ocv(col.getRed(),
                          col.getGreen(),
                          col.getBlue(),
                          col.getAlpha());

    uint32 final;
    d_renderSystem.convertColourValue(ocv, &final);

    return final;
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::updateMatrix() const
{
    // translation to position geometry and offset to pivot point
    Ogre::Matrix4 trans;
    trans.makeTrans(d_translation.d_x + d_pivot.d_x,
                    d_translation.d_y + d_pivot.d_y,
                    d_translation.d_z + d_pivot.d_z);

    // rotation
    Ogre::Matrix4 rot(Ogre::Quaternion(
        d_rotation.d_w, d_rotation.d_x, d_rotation.d_y, d_rotation.d_z));

    // translation to remove rotation pivot offset
    Ogre::Matrix4 inv_pivot_trans;
    inv_pivot_trans.makeTrans(-d_pivot.d_x, -d_pivot.d_y, -d_pivot.d_z);

    // calculate final matrix
    d_matrix = trans * rot * inv_pivot_trans;

    d_matrixValid = true;
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::syncHardwareBuffer() const
{
    // Reallocate h/w buffer as requied
    size_t size = d_hwBuffer->getNumVertices();
    const size_t required_size = d_vertices.size();
    if(size < required_size)
    {
        // calculate new size to use
        while(size < required_size)
            size *= 2;

        // Reallocate the buffer
        cleanupRenderOp(d_renderOp, d_hwBuffer);
        initialiseRenderOp(d_renderOp, d_hwBuffer, size);
    }

    // copy vertex data into hw buffer
    if (required_size > 0)
    {
        std::memcpy(d_hwBuffer->lock(Ogre::HardwareVertexBuffer::HBL_DISCARD),
                    &d_vertices[0], sizeof(OgreVertex) * d_vertices.size());

        d_hwBuffer->unlock();
    }

    d_sync = true;
}

//----------------------------------------------------------------------------//
const Ogre::Matrix4& OgreGeometryBuffer::getMatrix() const
{
    if (!d_matrixValid)
        updateMatrix();

    return d_matrix;
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::initialiseTextureStates() const
{
    using namespace Ogre;
    d_renderSystem._setTextureCoordCalculation(0, TEXCALC_NONE);
    d_renderSystem._setTextureCoordSet(0, 0);
    d_renderSystem._setTextureUnitFiltering(0, FO_LINEAR, FO_LINEAR, FO_POINT);
    d_renderSystem._setTextureAddressingMode(0, S_textureAddressMode);
    d_renderSystem._setTextureMatrix(0, Matrix4::IDENTITY);
    d_renderSystem._setAlphaRejectSettings(CMPF_ALWAYS_PASS, 0, false);
    d_renderSystem._setTextureBlendMode(0, S_colourBlendMode);
    d_renderSystem._setTextureBlendMode(0, S_alphaBlendMode);
    d_renderSystem._disableTextureUnitsFrom(1);
}

//----------------------------------------------------------------------------//
void OgreGeometryBuffer::setClippingActive(const bool active)
{
    d_clippingActive = active;
}

//----------------------------------------------------------------------------//
bool OgreGeometryBuffer::isClippingActive() const
{
    return d_clippingActive;
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>// Copyright (c) 2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

/* Example file for this grammar:

a = 3
  b = 4
    d = 5
  c = 6
d = 1
foo
  bar
    baz = 42

*/

#include <iostream>
#include <numeric>

#include <tao/pegtl.hpp>

#include <tao/pegtl/contrib/integer.hpp>

namespace pegtl = tao::TAO_PEGTL_NAMESPACE;

namespace example
{
   // clang-format off

   struct s : pegtl::star< pegtl::blank > {};
   struct eq : pegtl::one< '=' > {};
   struct key : pegtl::plus< pegtl::alpha > {};
   struct value : pegtl::plus< pegtl::digit > {};
   struct indent : pegtl::star< pegtl::one< ' ' > > {};

   struct assignment : pegtl::if_must< eq, s, value > {};

   struct line : pegtl::must< indent, key, s, pegtl::opt< assignment >, pegtl::eolf > {};

   struct grammar : pegtl::until< pegtl::eof, line > {};

   // clang-format on

   struct entry
   {
      unsigned i;
      std::string k;
   };

   struct state
   {
      unsigned indent;
      unsigned converted;
      std::vector< entry > stack;
      std::map< std::string, unsigned > result;
   };

   template< typename Rule >
   struct action
      : pegtl::nothing< Rule >
   {
   };

   template<>
   struct action< indent >
   {
      template< typename Input >
      static void apply( const Input& in, state& is )
      {
         is.indent = in.size();
      }
   };

   template<>
   struct action< key >
   {
      template< typename Input >
      static void apply( const Input& in, state& is )
      {
         while( ( !is.stack.empty() ) && ( is.stack.back().i >= is.indent ) ) {
            is.stack.pop_back();
         }
         is.stack.emplace_back( entry{ is.indent, in.string() } );
      }
   };

   template<>
   struct action< value >
      : public pegtl::integer::unsigned_action
   {
   };

   std::string join( const std::vector< entry >& v, const char s = '.' )
   {
      return std::accumulate( v.begin(), v.end(), entry{ 0, "" }, [=]( const entry& l, const entry& r ) { return entry{ 0, l.k + s + r.k }; } ).k.substr( 1 );
   }

   template<>
   struct action< assignment >
   {
      static void apply0( state& is )
      {
         is.result[ join( is.stack ) ] = is.converted;
      }
   };

}  // namespace example

int main( int argc, char** argv )
{
   for( int i = 1; i < argc; ++i ) {
      pegtl::file_input<> in( argv[ i ] );
      example::state is;
      pegtl::parse< example::grammar, example::action >( in, is );
      for( const auto& j : is.result ) {
         std::cout << j.first << " = " << j.second << std::endl;
      }
   }
   return 0;
}
<commit_msg>Fix clang-tidy warning<commit_after>// Copyright (c) 2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

/* Example file for this grammar:

a = 3
  b = 4
    d = 5
  c = 6
d = 1
foo
  bar
    baz = 42

*/

#include <iostream>
#include <numeric>

#include <tao/pegtl.hpp>

#include <tao/pegtl/contrib/integer.hpp>

namespace pegtl = tao::TAO_PEGTL_NAMESPACE;

namespace example
{
   // clang-format off

   struct s : pegtl::star< pegtl::blank > {};
   struct eq : pegtl::one< '=' > {};
   struct key : pegtl::plus< pegtl::alpha > {};
   struct value : pegtl::plus< pegtl::digit > {};
   struct indent : pegtl::star< pegtl::one< ' ' > > {};

   struct assignment : pegtl::if_must< eq, s, value > {};

   struct line : pegtl::must< indent, key, s, pegtl::opt< assignment >, pegtl::eolf > {};

   struct grammar : pegtl::until< pegtl::eof, line > {};

   // clang-format on

   struct entry
   {
      unsigned i;
      std::string k;
   };

   struct state
   {
      unsigned indent = 0;
      unsigned converted = 0;
      std::vector< entry > stack;
      std::map< std::string, unsigned > result;
   };

   template< typename Rule >
   struct action
      : pegtl::nothing< Rule >
   {
   };

   template<>
   struct action< indent >
   {
      template< typename Input >
      static void apply( const Input& in, state& is )
      {
         is.indent = in.size();
      }
   };

   template<>
   struct action< key >
   {
      template< typename Input >
      static void apply( const Input& in, state& is )
      {
         while( ( !is.stack.empty() ) && ( is.stack.back().i >= is.indent ) ) {
            is.stack.pop_back();
         }
         is.stack.emplace_back( entry{ is.indent, in.string() } );
      }
   };

   template<>
   struct action< value >
      : public pegtl::integer::unsigned_action
   {
   };

   std::string join( const std::vector< entry >& v, const char s = '.' )
   {
      return std::accumulate( v.begin(), v.end(), entry{ 0, "" }, [=]( const entry& l, const entry& r ) { return entry{ 0, l.k + s + r.k }; } ).k.substr( 1 );
   }

   template<>
   struct action< assignment >
   {
      static void apply0( state& is )
      {
         is.result[ join( is.stack ) ] = is.converted;
      }
   };

}  // namespace example

int main( int argc, char** argv )
{
   for( int i = 1; i < argc; ++i ) {
      pegtl::file_input<> in( argv[ i ] );
      example::state is;
      pegtl::parse< example::grammar, example::action >( in, is );
      for( const auto& j : is.result ) {
         std::cout << j.first << " = " << j.second << std::endl;
      }
   }
   return 0;
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    TestRRandomTableSource.cxx

-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------

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

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

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

#include <vtkRCalculatorFilter.h>
#include <vtkSmartPointer.h>
#include <vtkRRandomTableSource.h>
#include <vtkDescriptiveStatistics.h>
#include <vtkTable.h>
#include <vtkVariant.h>

#include <vtksys/ios/iostream>
#include <vtksys/ios/sstream>
#include <vtksys/stl/stdexcept>

namespace
{

#define test_expression(expression) \
{ \
  if(!(expression)) \
    { \
    vtksys_ios::ostringstream buffer; \
    buffer << "Expression failed at line " << __LINE__ << ": " << #expression; \
    throw vtkstd::runtime_error(buffer.str()); \
    } \
}

bool doubleEquals(double left, double right, double epsilon) {
  return (fabs(left - right) < epsilon);
}

}

int TestRRandomTableSource(int vtkNotUsed(argc), char *vtkNotUsed(argv)[])
{
  try
    {
    double mean_nd = 5.0;
    double sd_nd = 2.5;
    double lambda_pd = 3.0;
    double k_csd = 3.0;
    double lb_ud = 5.0;
    double ub_ud = 100.0;
    double nt_bd = 100;
    double ps_bd = 0.2;
    vtkRRandomTableSource* rts = vtkRRandomTableSource::New();
    vtkDescriptiveStatistics* dsf = vtkDescriptiveStatistics::New();
    rts->SetNumberOfRows(100000);
    rts->SetStatisticalDistributionForColumn(vtkRRandomTableSource::NORMAL,mean_nd,sd_nd,0.0,"Normal",0);
    rts->SetStatisticalDistributionForColumn(vtkRRandomTableSource::POISSON,lambda_pd,0.0,0.0,"Poisson",1);
    rts->SetStatisticalDistributionForColumn(vtkRRandomTableSource::CHISQUARE,k_csd,0.0,0.0,"Chi-Square",2);
    rts->SetStatisticalDistributionForColumn(vtkRRandomTableSource::UNIF,lb_ud,ub_ud,0.0,"Uniform",3);
    rts->SetStatisticalDistributionForColumn(vtkRRandomTableSource::BINOMIAL,nt_bd,ps_bd,0.0,"Binomial",4);
    dsf->SetInputConnection(rts->GetOutputPort());
    dsf->AddColumn("Normal");
    dsf->AddColumn("Poisson");
    dsf->AddColumn("Chi-Square");
    dsf->AddColumn("Uniform");
    dsf->AddColumn("Binomial");
    dsf->SetLearnOption( true );
    dsf->SetDeriveOption( true );
    dsf->Update();
    vtkTable* outputMeta = dsf->GetOutput( vtkStatisticsAlgorithm::OUTPUT_MODEL );

    for ( vtkIdType r = 0; r < outputMeta->GetNumberOfRows(); ++ r )
      {
      if(!strcmp(outputMeta->GetValueByName(r, "Variable").ToString(),"Normal"))
        {
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Mean").ToDouble(),mean_nd,1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Standard Deviation").ToDouble(),sd_nd,1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g1 Skewness").ToDouble(),0.0,1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g2 Kurtosis").ToDouble(),0.0,1.0));
        }
      else if(!strcmp(outputMeta->GetValueByName(r, "Variable").ToString(),"Poisson"))
        {
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Mean").ToDouble(),lambda_pd,1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Standard Deviation").ToDouble(),sqrt(lambda_pd),1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g1 Skewness").ToDouble(),1.0/sqrt(lambda_pd),1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g2 Kurtosis").ToDouble(),1.0/lambda_pd,1.0));
        }
      else if(!strcmp(outputMeta->GetValueByName(r, "Variable").ToString(),"Chi-Square"))
        {
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Mean").ToDouble(),k_csd,1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Standard Deviation").ToDouble(),sqrt(2.0*k_csd),1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g1 Skewness").ToDouble(),sqrt(8.0/k_csd),1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g2 Kurtosis").ToDouble(),12.0/k_csd,2.0));
        }
      else if(!strcmp(outputMeta->GetValueByName(r, "Variable").ToString(),"Uniform"))
        {
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Mean").ToDouble(),0.5*(lb_ud+ub_ud),1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Standard Deviation").ToDouble(),sqrt((1.0/12.0)*pow((ub_ud-lb_ud),2)),1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g1 Skewness").ToDouble(),0.0,1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g2 Kurtosis").ToDouble(),-(6.0/5.0),1.0));
        }
      else if(!strcmp(outputMeta->GetValueByName(r, "Variable").ToString(),"Binomial"))
        {
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Mean").ToDouble(),nt_bd*ps_bd,1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Standard Deviation").ToDouble(),sqrt(nt_bd*ps_bd*(1.0 - ps_bd)),1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g1 Skewness").ToDouble(),(1.0 - 2.0*ps_bd)/sqrt(nt_bd*ps_bd*(1.0 - ps_bd)),1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g2 Kurtosis").ToDouble(),(1.0 - 6.0*ps_bd*(1.0 - ps_bd))/(nt_bd*ps_bd*(1.0 - ps_bd)),1.0));
        }
      }

    dsf->Delete();
    rts->Delete();
    return 0;
    }
  catch(exception& e)
    {
    cerr << e.what() << endl;
    return 1;
    }
}

<commit_msg>COMP: more missing namespaces<commit_after>/*=========================================================================

Program:   Visualization Toolkit
Module:    TestRRandomTableSource.cxx

-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------

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

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

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

#include <vtkRCalculatorFilter.h>
#include <vtkSmartPointer.h>
#include <vtkRRandomTableSource.h>
#include <vtkDescriptiveStatistics.h>
#include <vtkTable.h>
#include <vtkVariant.h>

#include <vtksys/ios/iostream>
#include <vtksys/ios/sstream>
#include <vtksys/stl/stdexcept>

namespace
{

#define test_expression(expression)                                     \
  {                                                                     \
    if(!(expression))                                                   \
      {                                                                 \
      vtksys_ios::ostringstream buffer;                                 \
      buffer << "Expression failed at line " << __LINE__ << ": " << #expression; \
      throw vtkstd::runtime_error(buffer.str());                        \
      }                                                                 \
  }

  bool doubleEquals(double left, double right, double epsilon) {
    return (fabs(left - right) < epsilon);
  }

}

int TestRRandomTableSource(int vtkNotUsed(argc), char *vtkNotUsed(argv)[])
{
  try
    {
    double mean_nd = 5.0;
    double sd_nd = 2.5;
    double lambda_pd = 3.0;
    double k_csd = 3.0;
    double lb_ud = 5.0;
    double ub_ud = 100.0;
    double nt_bd = 100;
    double ps_bd = 0.2;
    vtkRRandomTableSource* rts = vtkRRandomTableSource::New();
    vtkDescriptiveStatistics* dsf = vtkDescriptiveStatistics::New();
    rts->SetNumberOfRows(100000);
    rts->SetStatisticalDistributionForColumn(vtkRRandomTableSource::NORMAL,mean_nd,sd_nd,0.0,"Normal",0);
    rts->SetStatisticalDistributionForColumn(vtkRRandomTableSource::POISSON,lambda_pd,0.0,0.0,"Poisson",1);
    rts->SetStatisticalDistributionForColumn(vtkRRandomTableSource::CHISQUARE,k_csd,0.0,0.0,"Chi-Square",2);
    rts->SetStatisticalDistributionForColumn(vtkRRandomTableSource::UNIF,lb_ud,ub_ud,0.0,"Uniform",3);
    rts->SetStatisticalDistributionForColumn(vtkRRandomTableSource::BINOMIAL,nt_bd,ps_bd,0.0,"Binomial",4);
    dsf->SetInputConnection(rts->GetOutputPort());
    dsf->AddColumn("Normal");
    dsf->AddColumn("Poisson");
    dsf->AddColumn("Chi-Square");
    dsf->AddColumn("Uniform");
    dsf->AddColumn("Binomial");
    dsf->SetLearnOption( true );
    dsf->SetDeriveOption( true );
    dsf->Update();
    vtkTable* outputMeta = dsf->GetOutput( vtkStatisticsAlgorithm::OUTPUT_MODEL );

    for ( vtkIdType r = 0; r < outputMeta->GetNumberOfRows(); ++ r )
      {
      if(!strcmp(outputMeta->GetValueByName(r, "Variable").ToString(),"Normal"))
        {
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Mean").ToDouble(),mean_nd,1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Standard Deviation").ToDouble(),sd_nd,1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g1 Skewness").ToDouble(),0.0,1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g2 Kurtosis").ToDouble(),0.0,1.0));
        }
      else if(!strcmp(outputMeta->GetValueByName(r, "Variable").ToString(),"Poisson"))
        {
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Mean").ToDouble(),lambda_pd,1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Standard Deviation").ToDouble(),sqrt(lambda_pd),1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g1 Skewness").ToDouble(),1.0/sqrt(lambda_pd),1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g2 Kurtosis").ToDouble(),1.0/lambda_pd,1.0));
        }
      else if(!strcmp(outputMeta->GetValueByName(r, "Variable").ToString(),"Chi-Square"))
        {
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Mean").ToDouble(),k_csd,1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Standard Deviation").ToDouble(),sqrt(2.0*k_csd),1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g1 Skewness").ToDouble(),sqrt(8.0/k_csd),1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g2 Kurtosis").ToDouble(),12.0/k_csd,2.0));
        }
      else if(!strcmp(outputMeta->GetValueByName(r, "Variable").ToString(),"Uniform"))
        {
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Mean").ToDouble(),0.5*(lb_ud+ub_ud),1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Standard Deviation").ToDouble(),sqrt((1.0/12.0)*pow((ub_ud-lb_ud),2)),1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g1 Skewness").ToDouble(),0.0,1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g2 Kurtosis").ToDouble(),-(6.0/5.0),1.0));
        }
      else if(!strcmp(outputMeta->GetValueByName(r, "Variable").ToString(),"Binomial"))
        {
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Mean").ToDouble(),nt_bd*ps_bd,1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"Standard Deviation").ToDouble(),sqrt(nt_bd*ps_bd*(1.0 - ps_bd)),1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g1 Skewness").ToDouble(),(1.0 - 2.0*ps_bd)/sqrt(nt_bd*ps_bd*(1.0 - ps_bd)),1.0));
        test_expression(doubleEquals(outputMeta->GetValueByName(r,"g2 Kurtosis").ToDouble(),(1.0 - 6.0*ps_bd*(1.0 - ps_bd))/(nt_bd*ps_bd*(1.0 - ps_bd)),1.0));
        }
      }

    dsf->Delete();
    rts->Delete();
    return 0;
    }

  catch( vtkstd::exception& e )
    {
    cerr << e.what()
         << "\n";
    return 1;
    }
}

<|endoftext|>


<commit_before>#include "stdafx.h"
#include "TDB_API.h"

#include "TDB_API_helper.h"

#include "win32.util/Singleton.h"
#include "kdb+.util/util.h"
#include "kdb+.util/K_ptr.h"
#include "kdb+.util/type_convert.h"
#include "Wind.util/FieldMapper.h"

namespace TDB {
	namespace traits {

		// Traits to assist symbolic retrieval of tick data fields from TDBDefine_OrderQueue.
		struct OrderQueue : public Wind::mapper::Fields<::TDBDefine_OrderQueue> {
			typedef Singleton<OrderQueue> accessor_map;
			typedef ::TDBDefine_OrderQueue tdb_result_type;

			OrderQueue() : Wind::mapper::Fields<tdb_result_type>() { registerAllFields(); }

			typedef Wind::accessor::SymbolAccessor<tdb_result_type, char[32]> SymbolAccessor;
			typedef Wind::accessor::DateAccessor<tdb_result_type> DateAccessor;
			typedef Wind::accessor::TimeAccessor<tdb_result_type> TimeAccessor;
			typedef Wind::accessor::IntAccessor<tdb_result_type, C> SideAccessor;
			typedef Wind::accessor::IntAccessor<tdb_result_type, I> IntAccessor;
			typedef Wind::accessor::CharAccessor<tdb_result_type> CharAccessor;
			typedef Wind::accessor::FloatAccessor<tdb_result_type, int> FloatAccessor;
			template <typename FieldT>
			using FloatsAccessor = Wind::accessor::VarFloatsAccessor<tdb_result_type, FieldT>;

			// Data fields -- always keep in sync with TDBDefine_OrderQueue
			void registerAllFields() {
				// ô(AG1312.SHF)
				addField("WindCode", new SymbolAccessor(&tdb_result_type::chWindCode));
				// (ag1312)
				addField("Code", new SymbolAccessor(&tdb_result_type::chCode));
				// ڣȻգʽYYMMDD
				addField("Date", new DateAccessor(&tdb_result_type::nDate));
				// ʱ䣨HHMMSSmmm94500000 ʾ 94500000
				addField("Time", new TimeAccessor(&tdb_result_type::nTime));
				// ('B':Bid 'A' : Ask)
				addField("Side", new SideAccessor(&tdb_result_type::nSide));
				// ɽ۸
				addField("Price", new FloatAccessor(&tdb_result_type::nPrice, .0001));
				//
				addField("OrderCount", new IntAccessor(&tdb_result_type::nOrderItems));
				// ϸ
				addField("Sizes", new FloatsAccessor<int[50]>(&tdb_result_type::nABVolume, &tdb_result_type::nABItems));
			}
		};

	}//namespace TDB::traits
}//namespace TDB

TDB_API K K_DECL TDB_orderQueue_fields(K _) {
	return TDB::traits::OrderQueue::accessor_map::getInstance()->getFields();
}

TDB_API K K_DECL TDB_orderQueue(K h, K windCode, K indicators, K begin, K end) {
	::THANDLE tdb = NULL;
	std::vector<TDB::traits::OrderQueue::field_accessor const*> indis;
	::TDBDefine_ReqOrderQueue req = { 0 };
	try {
		TDB::parseTdbHandle(h, tdb);
		TDB::parseIndicators<TDB::traits::OrderQueue>(indicators, indis);
		TDB::parseTdbReq(windCode, begin, end, req);
	}
	catch (std::string const& error) {
		return q::error2q(error);
	}

	return TDB::runQuery<TDB::traits::OrderQueue, ::TDBDefine_ReqOrderQueue>(tdb, req, indis, &::TDB_GetOrderQueue);
}<commit_msg>reenabled orderQueue<commit_after>#include "stdafx.h"
#include "TDB_API.h"

#include "TDB_API_helper.h"

#include "win32.util/Singleton.h"
#include "kdb+.util/util.h"
#include "kdb+.util/K_ptr.h"
#include "kdb+.util/type_convert.h"
#include "Wind.util/FieldMapper.h"

namespace TDB {
	namespace traits {

		// Traits to assist symbolic retrieval of tick data fields from TDBDefine_OrderQueue.
		struct OrderQueue : public Wind::mapper::Fields<::TDBDefine_OrderQueue> {
			typedef Singleton<OrderQueue> accessor_map;
			typedef ::TDBDefine_OrderQueue tdb_result_type;

			OrderQueue() : Wind::mapper::Fields<tdb_result_type>() { registerAllFields(); }

			typedef Wind::accessor::SymbolAccessor<tdb_result_type, char[32]> SymbolAccessor;
			typedef Wind::accessor::DateAccessor<tdb_result_type> DateAccessor;
			typedef Wind::accessor::TimeAccessor<tdb_result_type> TimeAccessor;
			typedef Wind::accessor::IntAccessor<tdb_result_type, C> SideAccessor;
			typedef Wind::accessor::IntAccessor<tdb_result_type, I> IntAccessor;
			typedef Wind::accessor::CharAccessor<tdb_result_type> CharAccessor;
			typedef Wind::accessor::FloatAccessor<tdb_result_type, int> FloatAccessor;
			template <typename FieldT>
			using FloatsAccessor = Wind::accessor::VarFloatsAccessor<tdb_result_type, FieldT>;

			// Data fields -- always keep in sync with TDBDefine_OrderQueue
			void registerAllFields() {
				// ô(AG1312.SHF)
				addField("WindCode", new SymbolAccessor(&tdb_result_type::chWindCode));
				// (ag1312)
				addField("Code", new SymbolAccessor(&tdb_result_type::chCode));
				// ڣȻգʽYYMMDD
				addField("Date", new DateAccessor(&tdb_result_type::nDate));
				// ʱ䣨HHMMSSmmm94500000 ʾ 94500000
				addField("Time", new TimeAccessor(&tdb_result_type::nTime));
				// ('B':Bid 'A' : Ask)
				addField("Side", new SideAccessor(&tdb_result_type::nSide));
				// ɽ۸
				addField("Price", new FloatAccessor(&tdb_result_type::nPrice, .0001));
				//
				addField("OrderCount", new IntAccessor(&tdb_result_type::nOrderItems));
				// ϸ
				addField("Sizes", new FloatsAccessor<int[50]>(&tdb_result_type::nABVolume, &tdb_result_type::nABItems));
			}
		};

	}//namespace TDB::traits
}//namespace TDB

TDB_API K K_DECL TDB_orderQueue_fields(K _) {
	return TDB::traits::OrderQueue::accessor_map::getInstance()->getFields();
}

TDB_API K K_DECL TDB_orderQueue(K h, K windCode, K indicators, K date, K begin, K end) {
	::THANDLE tdb = NULL;
	std::vector<TDB::traits::OrderQueue::field_accessor const*> indis;
	::TDBDefine_ReqOrderQueue req = { 0 };
	try {
		TDB::parseTdbHandle(h, tdb);
		TDB::parseIndicators<TDB::traits::OrderQueue>(indicators, indis);
		TDB::parseTdbReq(windCode, date, begin, end, req);
	}
	catch (std::string const& error) {
		return q::error2q(error);
	}

	return TDB::runQuery<TDB::traits::OrderQueue, ::TDBDefine_ReqOrderQueue>(tdb, req, indis, &::TDB_GetOrderQueue);
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014, Veelion Chong

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

#include <iostream>
#include <Python.h>
#include "farmhash.h"
#include "python-farmhash.h"

using namespace NAMESPACE_FOR_HASH_FUNCTIONS;

static PyObject *
py_farmhash_Hash32(PyObject *self, PyObject *args)
{
    PyObject *result;
    const char *s;
    size_t len;

    if (!PyArg_ParseTuple(args, "s", &s))
        return NULL;

    len = strlen(s);
    uint32_t h = Hash32(s, len);
    result = Py_BuildValue("I", h);

    return result;
}

static PyObject *
py_farmhash_Hash32WithSeed(PyObject *self, PyObject *args)
{
    PyObject *result;
    const char *s;
    size_t len;
    uint32_t seed;

    if (!PyArg_ParseTuple(args, "sI", &s, &seed))
        return NULL;

    len = strlen(s);
    uint32_t h = Hash32WithSeed(s, len, seed);
    result = Py_BuildValue("I", h);

    return result;
}

static PyObject *
py_farmhash_Hash64(PyObject *self, PyObject *args)
{
    PyObject *result;
    const char *s;
    size_t len;

    if (!PyArg_ParseTuple(args, "s", &s))
        return NULL;
    len = strlen(s);

    len = strlen(s);
    uint64_t h = Hash64(s, len);
# if __WORDSIZE == 64
    const char* int_param = "k";
# else
    const char* int_param = "K";
#endif
    result = Py_BuildValue(int_param, h);

    return result;
}

static PyObject *
py_farmhash_Hash64WithSeed(PyObject *self, PyObject *args)
{
    PyObject *result;
    const char *s;
    size_t len;
    uint64_t seed;

    if (!PyArg_ParseTuple(args, "sK", &s, &seed))
        return NULL;

    len = strlen(s);
    uint64_t h = Hash64WithSeed(s, len, seed);
# if __WORDSIZE == 64
    const char* int_param = "k";
# else
    const char* int_param = "K";
#endif
    result = Py_BuildValue(int_param, h);

    return result;
}

static PyObject *
py_farmhash_Hash128(PyObject *self, PyObject *args)
{
    PyObject *result;
    const char *s;
    size_t len;

    if (!PyArg_ParseTuple(args, "s", &s))
        return NULL;

    len = strlen(s);
    uint128_t h = Hash128(s, len);
    uint64_t low64 = Uint128Low64(h);
    uint64_t high64 = Uint128High64(h);
    result = Py_BuildValue("(KK)", low64, high64);

    return result;
}

static PyObject *
py_farmhash_Hash128WithSeed(PyObject *self, PyObject *args)
{
    PyObject *result;
    const char *s;
    size_t len;
    uint64_t seedlow64;
    uint64_t seedhigh64;

    if (!PyArg_ParseTuple(args, "sKK", &s, &seedlow64, &seedhigh64))
        return NULL;

    //std::cout << "seed low64:" << seedlow64 << std::endl;
    //std::cout << "seed high64:" << seedhigh64 << std::endl;
    len = strlen(s);
    uint128_t seed = Uint128(seedlow64, seedhigh64);
    uint128_t h = Hash128WithSeed(s, len, seed);
    uint64_t low64 = Uint128Low64(h);
    uint64_t high64 = Uint128High64(h);
    result = Py_BuildValue("(KK)", low64, high64);

    return result;
}

static PyMethodDef FarmHashMethods[] = {
    {"hash32",  py_farmhash_Hash32, METH_VARARGS, HASH32_DOCSTRING},
    {"hash32withseed",  py_farmhash_Hash32WithSeed, METH_VARARGS, HASH32WITHSEED_DOCSTRING},
    {"hash64",  py_farmhash_Hash64, METH_VARARGS, HASH64_DOCSTRING},
    {"hash64withseed",  py_farmhash_Hash64WithSeed, METH_VARARGS, HASH64WITHSEED_DOCSTRING},
    {"hash128",  py_farmhash_Hash128, METH_VARARGS, HASH128_DOCSTRING},
    {"hash128withseed",  py_farmhash_Hash128WithSeed, METH_VARARGS, HASH128WITHSEED_DOCSTRING},
    {NULL, NULL, 0, NULL}
};

struct module_state {
    PyObject *error;
};

#if PY_MAJOR_VERSION >= 3
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
#else
#define GETSTATE(m) (&_state)
static struct module_state _state;
#endif

#if PY_MAJOR_VERSION >= 3

static int myextension_traverse(PyObject *m, visitproc visit, void *arg) {
    Py_VISIT(GETSTATE(m)->error);
    return 0;
}

static int myextension_clear(PyObject *m) {
    Py_CLEAR(GETSTATE(m)->error);
    return 0;
}

static struct PyModuleDef moduledef = {
        PyModuleDef_HEAD_INIT,
        "farmhash",
        NULL,
        sizeof(struct module_state),
        FarmHashMethods,
        NULL,
        myextension_traverse,
        myextension_clear,
        NULL
};

#define INITERROR return NULL

PyObject *
PyInit_farmhash(void)

#else
#define INITERROR return

void
initfarmhash(void)
#endif
{
#if PY_MAJOR_VERSION >= 3
    PyObject *module = PyModule_Create(&moduledef);
#else
    PyObject *module = Py_InitModule("farmhash", FarmHashMethods);
#endif
    struct module_state *st = NULL;

    if (module == NULL)
        INITERROR;
    st = GETSTATE(module);

    st->error = PyErr_NewException("farmhash.Error", NULL, NULL);
    if (st->error == NULL) {
        Py_DECREF(module);
        INITERROR;
    }

#if PY_MAJOR_VERSION >= 3
    return module;
#endif
}
<commit_msg>Python 3.4 compatability<commit_after>/*
 * Copyright (c) 2014, Veelion Chong

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

#include <iostream>
#include <Python.h>
#include "farmhash.h"
#include "python-farmhash.h"

using namespace NAMESPACE_FOR_HASH_FUNCTIONS;

static PyObject *
py_farmhash_Hash32(PyObject *self, PyObject *args)
{
    PyObject *result;
    const char *s;
    size_t len;

    if (!PyArg_ParseTuple(args, "s", &s))
        return NULL;

    len = strlen(s);
    uint32_t h = Hash32(s, len);
    result = Py_BuildValue("I", h);

    return result;
}

static PyObject *
py_farmhash_Hash32WithSeed(PyObject *self, PyObject *args)
{
    PyObject *result;
    const char *s;
    size_t len;
    uint32_t seed;

    if (!PyArg_ParseTuple(args, "sI", &s, &seed))
        return NULL;

    len = strlen(s);
    uint32_t h = Hash32WithSeed(s, len, seed);
    result = Py_BuildValue("I", h);

    return result;
}

static PyObject *
py_farmhash_Hash64(PyObject *self, PyObject *args)
{
    PyObject *result;
    const char *s;
    size_t len;

    if (!PyArg_ParseTuple(args, "s", &s))
        return NULL;
    len = strlen(s);

    len = strlen(s);
    uint64_t h = Hash64(s, len);
# if __WORDSIZE == 64
    const char* int_param = "k";
# else
    const char* int_param = "K";
#endif
    result = Py_BuildValue(int_param, h);

    return result;
}

static PyObject *
py_farmhash_Hash64WithSeed(PyObject *self, PyObject *args)
{
    PyObject *result;
    const char *s;
    size_t len;
    uint64_t seed;

    if (!PyArg_ParseTuple(args, "sK", &s, &seed))
        return NULL;

    len = strlen(s);
    uint64_t h = Hash64WithSeed(s, len, seed);
# if __WORDSIZE == 64
    const char* int_param = "k";
# else
    const char* int_param = "K";
#endif
    result = Py_BuildValue(int_param, h);

    return result;
}

static PyObject *
py_farmhash_Hash128(PyObject *self, PyObject *args)
{
    PyObject *result;
    const char *s;
    size_t len;

    if (!PyArg_ParseTuple(args, "s", &s))
        return NULL;

    len = strlen(s);
    uint128_t h = Hash128(s, len);
    uint64_t low64 = Uint128Low64(h);
    uint64_t high64 = Uint128High64(h);
    result = Py_BuildValue("(KK)", low64, high64);

    return result;
}

static PyObject *
py_farmhash_Hash128WithSeed(PyObject *self, PyObject *args)
{
    PyObject *result;
    const char *s;
    size_t len;
    uint64_t seedlow64;
    uint64_t seedhigh64;

    if (!PyArg_ParseTuple(args, "sKK", &s, &seedlow64, &seedhigh64))
        return NULL;

    //std::cout << "seed low64:" << seedlow64 << std::endl;
    //std::cout << "seed high64:" << seedhigh64 << std::endl;
    len = strlen(s);
    uint128_t seed = Uint128(seedlow64, seedhigh64);
    uint128_t h = Hash128WithSeed(s, len, seed);
    uint64_t low64 = Uint128Low64(h);
    uint64_t high64 = Uint128High64(h);
    result = Py_BuildValue("(KK)", low64, high64);

    return result;
}

static PyMethodDef FarmHashMethods[] = {
    {"hash32",  py_farmhash_Hash32, METH_VARARGS, HASH32_DOCSTRING},
    {"hash32withseed",  py_farmhash_Hash32WithSeed, METH_VARARGS, HASH32WITHSEED_DOCSTRING},
    {"hash64",  py_farmhash_Hash64, METH_VARARGS, HASH64_DOCSTRING},
    {"hash64withseed",  py_farmhash_Hash64WithSeed, METH_VARARGS, HASH64WITHSEED_DOCSTRING},
    {"hash128",  py_farmhash_Hash128, METH_VARARGS, HASH128_DOCSTRING},
    {"hash128withseed",  py_farmhash_Hash128WithSeed, METH_VARARGS, HASH128WITHSEED_DOCSTRING},
    {NULL, NULL, 0, NULL}
};

struct module_state {
    PyObject *error;
};

#if PY_MAJOR_VERSION >= 3
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
#else
#define GETSTATE(m) (&_state)
static struct module_state _state;
#endif

#if PY_MAJOR_VERSION >= 3

static int myextension_traverse(PyObject *m, visitproc visit, void *arg) {
    Py_VISIT(GETSTATE(m)->error);
    return 0;
}

static int myextension_clear(PyObject *m) {
    Py_CLEAR(GETSTATE(m)->error);
    return 0;
}

static struct PyModuleDef moduledef = {
        PyModuleDef_HEAD_INIT,
        "farmhash",
        NULL,
        sizeof(struct module_state),
        FarmHashMethods,
        NULL,
        myextension_traverse,
        myextension_clear,
        NULL
};

#define INITERROR return NULL

extern "C" PyObject *
PyInit_farmhash(void)

#else
#define INITERROR return

void
initfarmhash(void)
#endif
{
#if PY_MAJOR_VERSION >= 3
    PyObject *module = PyModule_Create(&moduledef);
#else
    PyObject *module = Py_InitModule("farmhash", FarmHashMethods);
#endif
    struct module_state *st = NULL;

    if (module == NULL)
        INITERROR;
    st = GETSTATE(module);

    st->error = PyErr_NewException("farmhash.Error", NULL, NULL);
    if (st->error == NULL) {
        Py_DECREF(module);
        INITERROR;
    }

#if PY_MAJOR_VERSION >= 3
    return module;
#endif
}
<|endoftext|>


<commit_before>// $Id$
/*
 * Example macro to run locally an analysis task for comparing the offline
 * with the HLT esd tree.
 *
 * The output is a root file containing the histograms defined in the
 * analysis task. There is one output file per detector.
 *
 * Usage:
 *

 *   aliroot -b -q -l compare_HLT_offline_local.C'("phos")' 2>&1 | tee task.log
 *   aliroot -b -q -l compare_HLT_offline_local.C'("phos tpc")' 2>&1 | tee task.log
 *   aliroot -b -q -l compare_HLT_offline_local.C 2>&1 | tee task.log
 *

 *
 * If no argument is specified, ALL detector tasks are run.
 *
 * @ingroup alihlt_tpc
 * @author zbyin@mail.ccnu.edu.cn, Kalliopi.Kanaki@ift.uib.no
 */

void compare_HLT_offline_local(const char* detectorTask="all"){

  TStopwatch timer;
  timer.Start();

  gSystem->Load("libTree.so");
  gSystem->Load("libGeom.so");
  gSystem->Load("libVMC.so");
  gSystem->Load("libPhysics.so");

  //----------- Loading the required libraries ---------//

  gSystem->Load("libSTEERBase.so");
  gSystem->Load("libESD.so");
  gSystem->Load("libAOD.so");
  gSystem->Load("libANALYSIS.so");
  gSystem->Load("libANALYSISalice.so");
  gSystem->Load("libHLTbase.so");
  gROOT->ProcessLine(".include $ALICE_ROOT/include");

  Bool_t bAll=kFALSE, bTPC=kFALSE, bPHOS=kFALSE, bITS=kFALSE, bGLOBAL=kFALSE;

  TString allArgs = detectorTask;
  TString argument;

  TObjArray *pTokens = allArgs.Tokenize(" ");
  if(pTokens){
     for(int i=0; i<pTokens->GetEntries(); i++){
         argument=((TObjString*)pTokens->At(i))->GetString();
         if(argument.IsNull()) continue;

         if(argument.CompareTo("tpc", TString::kIgnoreCase)==0){
	    bTPC = kTRUE;
	    continue;
         }
         if(argument.CompareTo("phos", TString::kIgnoreCase)==0){
  	    bPHOS = kTRUE;
	    continue;
         }
	 if(argument.CompareTo("its", TString::kIgnoreCase)==0){
  	    bITS = kTRUE;
	    continue;
         }
	 if(argument.CompareTo("global", TString::kIgnoreCase)==0){
  	    bGLOBAL = kTRUE;
	    continue;
         }
	 if(argument.CompareTo("all",TString::kIgnoreCase)==0){
	    bTPC    = kTRUE;
	    bPHOS   = kTRUE;
	    bITS    = kTRUE;
	    bGLOBAL = kTRUE;
	    bAll    = kTRUE;
	    continue;
         }
         else break;
    }
  }

  //-------------- Compile the analysis tasks ---------- //
  if(bTPC)    gROOT->LoadMacro("AliAnalysisTaskHLTTPC.cxx+");
  if(bPHOS)   gROOT->LoadMacro("AliAnalysisTaskHLTPHOS.cxx+");
  if(bITS)    gROOT->LoadMacro("AliAnalysisTaskHLTITS.cxx+");
  if(bGLOBAL) gROOT->LoadMacro("AliAnalysisTaskHLT.cxx+");

  AliTagAnalysis *TagAna = new AliTagAnalysis("ESD");
  //TagAna->ChainLocalTags("../Tags");

//   AliRunTagCuts *runCuts = new AliRunTagCuts();
//   AliLHCTagCuts *lhcCuts = new AliLHCTagCuts();
//   AliDetectorTagCuts *detCuts = new AliDetectorTagCuts();
//   AliEventTagCuts *evCuts = new AliEventTagCuts();
//   evCuts->SetMultiplicityRange(11,12);

  TChain *chain = 0x0;
  //chain = TagAna->QueryTags(runCuts,lhcCuts,detCuts,evCuts);
  chain = new TChain("esdTree");

  //gROOT->LoadMacro("$ALICE_ROOT/PWG0/CreateESDChain.C");
  //chain = CreateESDChain("esd_run84254.txt", 2);

  //chain->Add("/afs/.alihlt.cern.ch/public/rec/79876/AliESDs.root");
  //chain->Add("/opt/HLT-public/rec/83683/rec/09000083683000.10/AliESDs.root");

  //chain->Add("/opt/HLT-public/rec/82762/ESDs/pass1/09000082762002.10/AliESDs.root");
  //chain->Add("/opt/HLT-public/rec/82762/ESDs/pass1/09000082762004.10/AliESDs.root");
  //chain->Add("/opt/HLT-public/rec/82762/ESDs/pass1/09000082762005.10/AliESDs.root");
  //chain->Add("/opt/HLT-public/rec/82762/ESDs/pass1/09000082762006.10/AliESDs.root");

  //chain->Add("/opt/HLT-public/rec/84254/alien/09000084254009.200/AliESDs.root");
  //chain->Add("/opt/HLT-public/rec/84254/alien/09000084254009.40/AliESDs.root");
  //chain->Add("/opt/HLT-public/rec/84254/alien/09000084254009.10/AliESDs.root");

  chain->Add("~/7TeV/115322/10000115322040.110/AliESDs.root");
  //chain->SetBranchStatus("*Calo*",0);

  //-------- Make the analysis manager ---------------//

  AliAnalysisManager *mgr  = new AliAnalysisManager("TestManager");
  AliESDInputHandler *esdH = new AliESDInputHandler;
  esdH->SetReadHLT();
  mgr->SetInputEventHandler(esdH);
  mgr->SetNSysInfo(1000);

  //-------------- define the tasks ------------//

  if(bTPC){
     AliAnalysisTaskHLTTPC *taskTPC = new AliAnalysisTaskHLTTPC("offhlt_comparison_TPC");
     mgr->AddTask(taskTPC);
     AliAnalysisDataContainer *coutput1 =  mgr->CreateContainer("tpc_histograms", TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-TPC-comparison.root");
     mgr->ConnectInput(taskTPC,0,mgr->GetCommonInputContainer());
     //mgr->ConnectOutput (taskTPC, 0, mgr->GetCommonOutputContainer());
     mgr->ConnectOutput(taskTPC,1,coutput1);
  }

  if(bPHOS){
     AliAnalysisTaskHLTPHOS *taskPHOS = new AliAnalysisTaskHLTPHOS("offhlt_comparison_PHOS");
     mgr->AddTask(taskPHOS);
     AliAnalysisDataContainer *coutput2 =  mgr->CreateContainer("phos_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-PHOS-comparison.root");
     mgr->ConnectInput(taskPHOS,0,mgr->GetCommonInputContainer());
     mgr->ConnectOutput(taskPHOS,1,coutput2);
  }

  if(bITS){
     AliAnalysisTaskHLTITS *taskITS = new AliAnalysisTaskHLTITS("offhlt_comparison_ITS");
     mgr->AddTask(taskITS);
     AliAnalysisDataContainer *coutput3 =  mgr->CreateContainer("its_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-ITS-comparison.root");
     mgr->ConnectInput(taskITS,0,mgr->GetCommonInputContainer());
     mgr->ConnectOutput(taskITS,1,coutput3);
  }

  if(bGLOBAL){
     AliAnalysisTaskHLT *taskGLOBAL = new AliAnalysisTaskHLT("offhlt_comparison_GLOBAL");
     mgr->AddTask(taskGLOBAL);
     AliAnalysisDataContainer *coutput4 =  mgr->CreateContainer("global_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-GLOBAL-comparison.root");
     mgr->ConnectInput(taskGLOBAL,0,mgr->GetCommonInputContainer());
     mgr->ConnectOutput(taskGLOBAL,1,coutput4);
  }

  if (!mgr->InitAnalysis()) return;
  mgr->PrintStatus();
  mgr->StartAnalysis("local",chain);

  timer.Stop();
  timer.Print();
}
<commit_msg>- cleaned up macro for local running<commit_after>// $Id$
/*
 * Example macro to run locally an analysis task for comparing the offline
 * with the HLT esd tree.
 *
 * The output is a root file containing the histograms defined in the
 * analysis task. There is one output file per detector.
 *
 * Usage:
 *

 *   aliroot -b -q -l compare_HLT_offline_local.C'("phos")' 2>&1 | tee task.log
 *   aliroot -b -q -l compare_HLT_offline_local.C'("phos tpc global")' 2>&1 | tee task.log
 *   aliroot -b -q -l compare_HLT_offline_local.C 2>&1 | tee task.log
 *

 *
 * If no argument is specified, ALL detector tasks are run.
 *
 * @ingroup alihlt_tpc
 * @author zbyin@mail.ccnu.edu.cn, Kalliopi.Kanaki@ift.uib.no
 */

void compare_HLT_offline_local(const char* detectorTask="all"){

  TStopwatch timer;
  timer.Start();

  gSystem->Load("libTree.so");
  gSystem->Load("libGeom.so");
  gSystem->Load("libVMC.so");
  gSystem->Load("libPhysics.so");

  //----------- Loading the required libraries ---------//

  gSystem->Load("libSTEERBase.so");
  gSystem->Load("libESD.so");
  gSystem->Load("libAOD.so");
  gSystem->Load("libANALYSIS.so");
  gSystem->Load("libANALYSISalice.so");
  gSystem->Load("libHLTbase.so");
  gROOT->ProcessLine(".include $ALICE_ROOT/include");

  Bool_t bAll=kFALSE, bTPC=kFALSE, bPHOS=kFALSE, bITS=kFALSE, bGLOBAL=kFALSE;

  TString allArgs = detectorTask;
  TString argument;

  TObjArray *pTokens = allArgs.Tokenize(" ");
  if(pTokens){
     for(int i=0; i<pTokens->GetEntries(); i++){
         argument=((TObjString*)pTokens->At(i))->GetString();
         if(argument.IsNull()) continue;

         if(argument.CompareTo("tpc", TString::kIgnoreCase)==0){
	    bTPC = kTRUE;
	    continue;
         }
         if(argument.CompareTo("phos", TString::kIgnoreCase)==0){
  	    bPHOS = kTRUE;
	    continue;
         }
	 if(argument.CompareTo("its", TString::kIgnoreCase)==0){
  	    bITS = kTRUE;
	    continue;
         }
	 if(argument.CompareTo("global", TString::kIgnoreCase)==0){
  	    bGLOBAL = kTRUE;
	    continue;
         }
	 if(argument.CompareTo("all",TString::kIgnoreCase)==0){
	    bTPC    = kTRUE;
	    bPHOS   = kTRUE;
	    bITS    = kTRUE;
	    bGLOBAL = kTRUE;
	    bAll    = kTRUE;
	    continue;
         }
         else break;
    }
  }

  //-------------- Compile the analysis tasks ---------- //
  if(bTPC)    gROOT->LoadMacro("AliAnalysisTaskHLTTPC.cxx+");
  if(bPHOS)   gROOT->LoadMacro("AliAnalysisTaskHLTPHOS.cxx+");
  if(bITS)    gROOT->LoadMacro("AliAnalysisTaskHLTITS.cxx+");
  if(bGLOBAL) gROOT->LoadMacro("AliAnalysisTaskHLT.cxx+");

  TChain *chain = new TChain("esdTree");
  chain->Add("~/7TeV/115322/10000115322040.110/AliESDs.root");
  //chain->Add("...");

  //-------- Make the analysis manager ---------------//

  AliAnalysisManager *mgr  = new AliAnalysisManager("TestManager");
  AliESDInputHandler *esdH = new AliESDInputHandler;
  esdH->SetReadHLT();
  mgr->SetInputEventHandler(esdH);
  mgr->SetNSysInfo(1000);

  //-------------- define the tasks ------------//

  if(bTPC){
     AliAnalysisTaskHLTTPC *taskTPC = new AliAnalysisTaskHLTTPC("offhlt_comparison_TPC");
     mgr->AddTask(taskTPC);
     AliAnalysisDataContainer *coutput1 =  mgr->CreateContainer("tpc_histograms", TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-TPC-comparison.root");
     mgr->ConnectInput(taskTPC,0,mgr->GetCommonInputContainer());
     mgr->ConnectOutput(taskTPC,1,coutput1);
  }

  if(bPHOS){
     AliAnalysisTaskHLTPHOS *taskPHOS = new AliAnalysisTaskHLTPHOS("offhlt_comparison_PHOS");
     mgr->AddTask(taskPHOS);
     AliAnalysisDataContainer *coutput2 =  mgr->CreateContainer("phos_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-PHOS-comparison.root");
     mgr->ConnectInput(taskPHOS,0,mgr->GetCommonInputContainer());
     mgr->ConnectOutput(taskPHOS,1,coutput2);
  }

  if(bITS){
     AliAnalysisTaskHLTITS *taskITS = new AliAnalysisTaskHLTITS("offhlt_comparison_ITS");
     mgr->AddTask(taskITS);
     AliAnalysisDataContainer *coutput3 =  mgr->CreateContainer("its_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-ITS-comparison.root");
     mgr->ConnectInput(taskITS,0,mgr->GetCommonInputContainer());
     mgr->ConnectOutput(taskITS,1,coutput3);
  }

  if(bGLOBAL){
     AliAnalysisTaskHLT *taskGLOBAL = new AliAnalysisTaskHLT("offhlt_comparison_GLOBAL");
     mgr->AddTask(taskGLOBAL);
     AliAnalysisDataContainer *coutput4 =  mgr->CreateContainer("global_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-GLOBAL-comparison.root");
     mgr->ConnectInput(taskGLOBAL,0,mgr->GetCommonInputContainer());
     mgr->ConnectOutput(taskGLOBAL,1,coutput4);
  }

  if (!mgr->InitAnalysis()) return;
  mgr->PrintStatus();
  mgr->StartAnalysis("local",chain);

  timer.Stop();
  timer.Print();
}
<|endoftext|>


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

/*
  // Load libraries
  gSystem->Load("libANALYSIS");
  gSystem->Load("libTPCcalib");

  .x ~/NimStyle.C
  gSystem->Load("libANALYSIS");
  gSystem->Load("libTPCcalib");

  TFile f("CalibObjects.root");
  AliTPCcalibTrigger *calibTrigger = (AliTPCcalibTrigger *)f->Get("TPCCalib")->FindObject("calibTrigger");

  gSystem->AddIncludePath("-I$ALICE_ROOT/TPC/macros");
  gROOT->LoadMacro("$ALICE_ROOT/TPC/macros/AliXRDPROOFtoolkit.cxx+")
  AliXRDPROOFtoolkit tool;
  TChain * chainTrack = tool.MakeChain("trigger.txt","Track",0,10200);
  chainTrack->Lookup();
  TChain * chainEvent = tool.MakeChain("trigger.txt","Event",0,10200);
  chainEvent->Lookup();

*/

#include "Riostream.h"
#include "TChain.h"
#include "TTree.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TH3F.h"
#include "THnSparse.h"
#include "TList.h"
#include "TMath.h"
#include "TCanvas.h"
#include "TFile.h"
#include "TF1.h"
#include "TVectorD.h"
#include "TProfile.h"
#include "TGraphErrors.h"
#include "TCanvas.h"

#include "AliTPCclusterMI.h"
#include "AliTPCseed.h"
#include "AliESDVertex.h"
#include "AliESDEvent.h"
#include "AliESDfriend.h"
#include "AliESDInputHandler.h"
#include "AliAnalysisManager.h"

#include "AliTracker.h"
#include "AliMagF.h"
#include "AliTPCCalROC.h"

#include "AliLog.h"

#include "AliTPCcalibTrigger.h"

#include "TTreeStream.h"
#include "AliTPCTracklet.h"
#include "TTimeStamp.h"
#include "AliTPCcalibDB.h"
#include "AliTPCcalibLaser.h"
#include "AliDCSSensorArray.h"
#include "AliDCSSensor.h"

ClassImp(AliTPCcalibTrigger)

AliTPCcalibTrigger::AliTPCcalibTrigger():
  AliTPCcalibBase("calibTrigger","calibTrigger"),
  fHisMap(0)
{

}

AliTPCcalibTrigger::AliTPCcalibTrigger(const char * name, const char * title):
  AliTPCcalibBase(name,title),
  fHisMap(0)
{
  //
  //
  //
  fHisMap = new TMap;
}

Long64_t AliTPCcalibTrigger::Merge(TCollection *li) {
  //
  // Merge histograms
  //
  TIterator* iter = li->MakeIterator();
  AliTPCcalibTrigger* cal = 0;

  while ((cal = (AliTPCcalibTrigger*)iter->Next())) {
    if (!cal->InheritsFrom(AliTPCcalibTrigger::Class())) {
      Error("Merge","Attempt to add object of class %s to a %s", cal->ClassName(), this->ClassName());
      return -1;
    }
    TMap * addMap=(cal->fHisMap);
    if(!addMap) return 0;
    TIterator* iterator = addMap->MakeIterator();
    iterator->Reset();
    //    TPair* addPair=0;
    TObject *object=0;
    //
    while((object=iterator->Next())){
      THnSparse* his1 = dynamic_cast<THnSparseF*>(cal->fHisMap->GetValue(object->GetName()));
      if (!his1) continue;
      his1->Print();
      THnSparse* his0 = dynamic_cast<THnSparseF*>(fHisMap->GetValue(object->GetName()));

      if(!his0){
        his0=MakeHisto(object->GetName());
        fHisMap->Add(new TObjString(object->GetName()),his0);
      }
      his0->Add(his1);
    }
  }
  return 0;
}

void AliTPCcalibTrigger::Process(AliESDEvent *event){
  //
  //
  //
  if (!event) return;
  const TString &trigger = event->GetFiredTriggerClasses();
  TTreeSRedirector * cstream =  GetDebugStreamer();
  //
  TObjString str(event->GetFiredTriggerClasses());
  Bool_t hasPIXEL=HasPIXEL(&str);
  Bool_t hasTRD=HasTRD(&str);
  Bool_t hasTOF=HasTOF(&str);
  Bool_t hasACORDE=HasACORDE(&str);
  //
  if (!GetHisto(trigger.Data())){
    AddHisto(trigger.Data(),MakeHisto(trigger.Data()));
  }
  if (!GetHisto("all")){
    AddHisto("all",MakeHisto("all"));
  }

  THnSparse *histoAll = GetHisto("all");
  THnSparse *histo = GetHisto(trigger.Data());
  Double_t xcont[9]={0,0,0,0,0,0,0,0,0};

  Int_t ntracks = event->GetNumberOfTracks();
  xcont[0] = ntracks;
  xcont[8] = 1;
  //
  // GetLongest track
  //
  AliESDtrack * longest=0;
  Int_t nclmax=0;
  for (Int_t itrack=0; itrack<ntracks; itrack++){
    AliESDtrack *track=event->GetTrack(itrack);
    if (!track) continue;
    if (track->GetTPCNcls()<=nclmax) continue;
    nclmax = track->GetTPCNcls();
    longest= track;
  }
  xcont[1]  =nclmax;
  histoAll->Fill(xcont);
  histo->Fill(xcont);
  if (cstream) {
    (*cstream) << "Event" <<
      "run="<<fRun<<
      "time="<<fTime<<
      "pixel="<<hasPIXEL<<
      "trd="<<hasTRD<<
      "tof="<<hasTOF<<
      "acorde="<<hasACORDE<<
      "ntracks="<<ntracks<<
      "\n";
  }
  //
  xcont[8] = -1.;
  for (Int_t itrack=0; itrack<ntracks; itrack++){
    AliESDtrack *track=event->GetTrack(itrack);
    if (!track) continue;
    Float_t dca[2];
    Double_t pxyz[3];
    track->GetDZ(0.,0.,0.,event->GetMagneticField(),dca);
    Bool_t status = track->GetPxPyPz(pxyz);
    Double_t alpha = TMath::ATan2(pxyz[1],pxyz[0]);
    xcont[1]=track->GetTPCNcls();
    xcont[2]=dca[0];
    xcont[3]=dca[1];
    xcont[4]=alpha;
    xcont[5]=track->GetParameter()[3];
    xcont[6]=track->Pt();
    xcont[7]=track->GetTPCsignal();
    histoAll->Fill(xcont);
    histo->Fill(xcont);
    //
    //
    if (cstream) {
      Double_t mpt = track->GetParameter()[4];
      (*cstream) << "Track" <<
	"run="<<fRun<<
	"time="<<fTime<<
	"status="<<status<<
	"ntracks="<<ntracks<<
	"pixel="<<hasPIXEL<<
	"trd="<<hasTRD<<
	"tof="<<hasTOF<<
	"acorde="<<hasACORDE<<
	"ncl="<<xcont[1]<<
	"dcaR="<<xcont[2]<<
	"dcaZ="<<xcont[3]<<
	"alpha="<<xcont[4]<<
	"theta="<<xcont[5]<<
	"pt="<<xcont[6]<<
	"dEdx="<<xcont[7]<<
	"mpt="<<mpt<<
	"\n";
    }
  }
}

THnSparse *AliTPCcalibTrigger::MakeHisto(const char* trigger){
  //
  // Make event/track histograms
  // trigger histo
  //
  //                 ntracks  nclMax dcaR dcaZ alpha   theta pt dEdx ev
  Int_t    bins[9] = {50,     40,    20,  20,  18,     25,   25, 25, 2 };
  //Int_t    bins[9] = {50*   20*    25*  25*  18*     25*   25* 25 };
  Double_t xmin[9] = {0.,     0,      0,  -250,   -3.14, -1.5,  0, 0, -1.};
  Double_t xmax[9] = {50,     160,  150,  250, 3.14,  1.5,   100, 100, 1.};
  TString  axisName[9]={
    "ntracks",
    "ncl",
    "dcaR",
    "dcaZ",
    "alpha",
    "theta",
    "pt",
    "dEdx",
    "ev"
  };
  TString  axisTitle[9]={
    "Number of tracks",
    "N_{cl}",
    "dca_{R} (cm)",
    "dca_{z} (cm)",
    "alpha (mrad)",
    "theta",
    "p_{t} (GeV/c)",
    "dEdx (a.u.)",
    "ev"
  };

  THnSparse *sparse = new THnSparseF(Form("his_%s",trigger), Form("his_%s",trigger), 9, bins, xmin, xmax);
  for (Int_t iaxis=0; iaxis<9; iaxis++){
    sparse->GetAxis(iaxis)->SetName(axisName[iaxis]);
    sparse->GetAxis(iaxis)->SetTitle(axisTitle[iaxis]);
  }
  return sparse;
}

THnSparse * AliTPCcalibTrigger::GetHisto(const char *trigger) {
  //
  // return histogram for given class
  if (!fHisMap) fHisMap=new TMap;
  return (THnSparse*) fHisMap->GetValue(trigger);
}

void   AliTPCcalibTrigger::AddHisto(const char *trigger, THnSparse *his) {
  if (!GetHisto(trigger)) {
    TObjString *pstr = new TObjString(trigger);
    fHisMap->Add(pstr,his);
  }
}

TTree * AliTPCcalibTrigger::MakeTree(const char * fname){
  //
  //
  //
  TTreeSRedirector * sred = new TTreeSRedirector(fname);
  TTreeStream &pcstream = (*sred)<<"Trigger";
  //
  //
  TIterator* iterator = fHisMap->MakeIterator();
  TObject * object=0;
  //
  while((object=iterator->Next())){
    MakeTree(pcstream, object->GetName());
  }
  delete sred;
  TFile *f = new TFile(fname);
  TTree *tree = (TTree*)f->Get("Trigger");
  return tree;
}

void AliTPCcalibTrigger::MakeTree(TTreeStream &pcstream, const char *tname){
  //
  //  TTreeSRedirector * sred = new TTreeSRedirector("trigger.root");
  //  TTreeStream &pcstream = (*sred)<<"Trigger";
  //
  //AliTPCcalibTrigger *calibTrigger = this;
  Double_t value;
  THnSparse * his = GetHisto(tname);
  if (!his) return;
  //
  Int_t *bins = new Int_t[100];
  Int_t ndim = his->GetNdimensions();
  Double_t position[10];
  //
  TObjString str(tname);
  Bool_t isAll  = str.String().Contains("all");
  Bool_t hasPIXEL=HasPIXEL(&str);
  Bool_t hasTRD=HasTRD(&str);
  Bool_t hasTOF=HasTOF(&str);
  Bool_t hasACORDE=HasACORDE(&str);
  for (Long64_t i = 0; i < his->GetNbins(); ++i) {
    value = his->GetBinContent(i, bins);
    pcstream<<"val="<<value;
    pcstream<<"tname.="<<&str;
    //
    pcstream<<"all="<<isAll;
    pcstream<<"pixel="<<hasPIXEL;
    pcstream<<"trd="<<hasTRD;
    pcstream<<"tof="<<hasTOF;
    pcstream<<"acorde="<<hasACORDE;
    //
    for (Int_t idim = 0; idim < ndim; idim++) {
      position[idim] = his->GetAxis(idim)->GetBinCenter(bins[idim]);
      pcstream<<Form("%s=",his->GetAxis(idim)->GetName())<<position[idim];
    }
    pcstream<<"\n";
  }
}

Bool_t AliTPCcalibTrigger::HasTOF(TObjString *tname){
  //
  Bool_t result = kFALSE;
  result|=(tname->String().Contains("0OB")>0);
  result|=(tname->String().Contains("0OC")>0);
  return result;
}

Bool_t AliTPCcalibTrigger::HasACORDE(TObjString *tname){
  Bool_t result = kFALSE;
  result|=(tname->String().Contains("0ASL")>0);
  result|=(tname->String().Contains("0AMU")>0);
  result|=(tname->String().Contains("0ASC")>0);
  return result;
}

Bool_t AliTPCcalibTrigger::HasPIXEL(TObjString *tname){
  return (tname->String().Contains("0SCO")>0);
}

Bool_t AliTPCcalibTrigger::HasTRD(TObjString *tname){
  return (tname->String().Contains("1H")>0);
}

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

/*
  // Load libraries
  gSystem->Load("libANALYSIS");
  gSystem->Load("libTPCcalib");

  .x ~/NimStyle.C
  gSystem->Load("libANALYSIS");
  gSystem->Load("libTPCcalib");

  TFile f("CalibObjects.root");
  AliTPCcalibTrigger *calibTrigger = (AliTPCcalibTrigger *)f->Get("TPCCalib")->FindObject("calibTrigger");

  gSystem->AddIncludePath("-I$ALICE_ROOT/TPC/macros");
  gROOT->LoadMacro("$ALICE_ROOT/TPC/macros/AliXRDPROOFtoolkit.cxx+")
  AliXRDPROOFtoolkit tool;
  TChain * chainTrack = tool.MakeChain("trigger.txt","Track",0,10200);
  chainTrack->Lookup();
  TChain * chainEvent = tool.MakeChain("trigger.txt","Event",0,10200);
  chainEvent->Lookup();

*/

#include "Riostream.h"
#include "TChain.h"
#include "TTree.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TH3F.h"
#include "THnSparse.h"
#include "TList.h"
#include "TMath.h"
#include "TCanvas.h"
#include "TFile.h"
#include "TF1.h"
#include "TVectorD.h"
#include "TProfile.h"
#include "TGraphErrors.h"
#include "TCanvas.h"

#include "AliTPCclusterMI.h"
#include "AliTPCseed.h"
#include "AliESDVertex.h"
#include "AliESDEvent.h"
#include "AliESDfriend.h"
#include "AliESDInputHandler.h"
#include "AliAnalysisManager.h"

#include "AliTracker.h"
#include "AliMagF.h"
#include "AliTPCCalROC.h"

#include "AliLog.h"

#include "AliTPCcalibTrigger.h"

#include "TTreeStream.h"
#include "AliTPCTracklet.h"
#include "TTimeStamp.h"
#include "AliTPCcalibDB.h"
#include "AliTPCcalibLaser.h"
#include "AliDCSSensorArray.h"
#include "AliDCSSensor.h"

ClassImp(AliTPCcalibTrigger)

AliTPCcalibTrigger::AliTPCcalibTrigger():
  AliTPCcalibBase("calibTrigger","calibTrigger"),
  fHisMap(0)
{

}

AliTPCcalibTrigger::AliTPCcalibTrigger(const char * name, const char * title):
  AliTPCcalibBase(name,title),
  fHisMap(0)
{
  //
  //
  //
  fHisMap = new TMap;
}

Long64_t AliTPCcalibTrigger::Merge(TCollection *li) {
  //
  // Merge histograms
  //
  TIterator* iter = li->MakeIterator();
  AliTPCcalibTrigger* cal = 0;

  while ((cal = (AliTPCcalibTrigger*)iter->Next())) {
    if (!cal->InheritsFrom(AliTPCcalibTrigger::Class())) {
      Error("Merge","Attempt to add object of class %s to a %s", cal->ClassName(), this->ClassName());
      return -1;
    }
    TMap * addMap=(cal->fHisMap);
    if(!addMap) return 0;
    TIterator* iterator = addMap->MakeIterator();
    iterator->Reset();
    //    TPair* addPair=0;
    TObject *object=0;
    //
    while((object=iterator->Next())){
      THnSparse* his1 = dynamic_cast<THnSparseF*>(cal->fHisMap->GetValue(object->GetName()));
      if (!his1) continue;
      his1->Print();
      THnSparse* his0 = dynamic_cast<THnSparseF*>(fHisMap->GetValue(object->GetName()));

      if(!his0){
        his0=MakeHisto(object->GetName());
        fHisMap->Add(new TObjString(object->GetName()),his0);
      }
      his0->Add(his1);
    }
  }
  return 0;
}

void AliTPCcalibTrigger::Process(AliESDEvent *event){
  //
  //
  //
  if (!event) return;
  const TString &trigger = event->GetFiredTriggerClasses();
  TTreeSRedirector * cstream =  GetDebugStreamer();
  //
  TObjString str(event->GetFiredTriggerClasses());
  Bool_t hasPIXEL=HasPIXEL(&str);
  Bool_t hasTRD=HasTRD(&str);
  Bool_t hasTOF=HasTOF(&str);
  Bool_t hasACORDE=HasACORDE(&str);
  //
  if (!GetHisto(trigger.Data())){
    AddHisto(trigger.Data(),MakeHisto(trigger.Data()));
  }
  if (!GetHisto("all")){
    AddHisto("all",MakeHisto("all"));
  }

  THnSparse *histoAll = GetHisto("all");
  THnSparse *histo = GetHisto(trigger.Data());
  Double_t xcont[9]={0,0,0,0,0,0,0,0,0};

  Int_t ntracks = event->GetNumberOfTracks();
  xcont[0] = ntracks;
  xcont[8] = 1;
  //
  // GetLongest track
  //
  AliESDtrack * longest=0;
  Int_t nclmax=0;
  for (Int_t itrack=0; itrack<ntracks; itrack++){
    AliESDtrack *track=event->GetTrack(itrack);
    if (!track) continue;
    if (track->GetTPCNcls()<=nclmax) continue;
    nclmax = track->GetTPCNcls();
    longest= track;
  }
  xcont[1]  =nclmax;
  histoAll->Fill(xcont);
  histo->Fill(xcont);
  if (cstream) {
    (*cstream) << "Event" <<
      "run="<<fRun<<
      "time="<<fTime<<
      "tname.="<<&str<<
      "pixel="<<hasPIXEL<<
      "trd="<<hasTRD<<
      "tof="<<hasTOF<<
      "acorde="<<hasACORDE<<
      "ntracks="<<ntracks<<
      "\n";
  }
  //
  xcont[8] = -1.;
  for (Int_t itrack=0; itrack<ntracks; itrack++){
    AliESDtrack *track=event->GetTrack(itrack);
    if (!track) continue;
    Float_t dca[2];
    Double_t pxyz[3];
    track->GetDZ(0.,0.,0.,event->GetMagneticField(),dca);
    Bool_t status = track->GetPxPyPz(pxyz);
    Double_t alpha = TMath::ATan2(pxyz[1],pxyz[0]);
    xcont[1]=track->GetTPCNcls();
    xcont[2]=dca[0];
    xcont[3]=dca[1];
    xcont[4]=alpha;
    xcont[5]=track->GetParameter()[3];
    xcont[6]=track->Pt();
    xcont[7]=track->GetTPCsignal();
    histoAll->Fill(xcont);
    histo->Fill(xcont);
    //
    //
    if (cstream) {
      Double_t mpt = track->GetParameter()[4];
      Int_t kokot[1000];
      Int_t nclITS=track->GetITSclusters(kokot);
      Int_t nclTPC=track->GetTPCNcls();
      Int_t nclTRD=track->GetTRDclusters(kokot);
      ULong_t tstatus = track->GetStatus();
      (*cstream) << "Track" <<
	"run="<<fRun<<
	"time="<<fTime<<
	"tname.="<<&str<<
	"status="<<status<<
	//
	"ntracks="<<ntracks<<
	"tstatus="<<status<<
	"nclITS="<<nclITS<<
	"nclTPC="<<nclTPC<<
	"nclTRD="<<nclTRD<<
	//
	"pixel="<<hasPIXEL<<
	"trd="<<hasTRD<<
	"tof="<<hasTOF<<
	"acorde="<<hasACORDE<<
	"ncl="<<xcont[1]<<
	"dcaR="<<xcont[2]<<
	"dcaZ="<<xcont[3]<<
	"alpha="<<xcont[4]<<
	"theta="<<xcont[5]<<
	"pt="<<xcont[6]<<
	"dEdx="<<xcont[7]<<
	"mpt="<<mpt<<
	"\n";
    }
  }
}

THnSparse *AliTPCcalibTrigger::MakeHisto(const char* trigger){
  //
  // Make event/track histograms
  // trigger histo
  //
  //                 ntracks  nclMax dcaR dcaZ alpha   theta pt dEdx ev
  Int_t    bins[9] = {50,     40,    20,  20,  18,     25,   25, 25, 2 };
  //Int_t    bins[9] = {50*   20*    25*  25*  18*     25*   25* 25 };
  Double_t xmin[9] = {0.,     0,      0,  -250,   -3.14, -1.5,  0, 0, -1.};
  Double_t xmax[9] = {50,     160,  150,  250, 3.14,  1.5,   100, 100, 1.};
  TString  axisName[9]={
    "ntracks",
    "ncl",
    "dcaR",
    "dcaZ",
    "alpha",
    "theta",
    "pt",
    "dEdx",
    "ev"
  };
  TString  axisTitle[9]={
    "Number of tracks",
    "N_{cl}",
    "dca_{R} (cm)",
    "dca_{z} (cm)",
    "alpha (mrad)",
    "theta",
    "p_{t} (GeV/c)",
    "dEdx (a.u.)",
    "ev"
  };

  THnSparse *sparse = new THnSparseF(Form("his_%s",trigger), Form("his_%s",trigger), 9, bins, xmin, xmax);
  for (Int_t iaxis=0; iaxis<9; iaxis++){
    sparse->GetAxis(iaxis)->SetName(axisName[iaxis]);
    sparse->GetAxis(iaxis)->SetTitle(axisTitle[iaxis]);
  }
  return sparse;
}

THnSparse * AliTPCcalibTrigger::GetHisto(const char *trigger) {
  //
  // return histogram for given class
  if (!fHisMap) fHisMap=new TMap;
  return (THnSparse*) fHisMap->GetValue(trigger);
}

void   AliTPCcalibTrigger::AddHisto(const char *trigger, THnSparse *his) {
  if (!GetHisto(trigger)) {
    TObjString *pstr = new TObjString(trigger);
    fHisMap->Add(pstr,his);
  }
}

TTree * AliTPCcalibTrigger::MakeTree(const char * fname){
  //
  //
  //
  TTreeSRedirector * sred = new TTreeSRedirector(fname);
  TTreeStream &pcstream = (*sred)<<"Trigger";
  //
  //
  TIterator* iterator = fHisMap->MakeIterator();
  TObject * object=0;
  //
  while((object=iterator->Next())){
    MakeTree(pcstream, object->GetName());
  }
  delete sred;
  TFile *f = new TFile(fname);
  TTree *tree = (TTree*)f->Get("Trigger");
  return tree;
}

void AliTPCcalibTrigger::MakeTree(TTreeStream &pcstream, const char *tname){
  //
  //  TTreeSRedirector * sred = new TTreeSRedirector("trigger.root");
  //  TTreeStream &pcstream = (*sred)<<"Trigger";
  //
  //AliTPCcalibTrigger *calibTrigger = this;
  Double_t value;
  THnSparse * his = GetHisto(tname);
  if (!his) return;
  //
  Int_t *bins = new Int_t[100];
  Int_t ndim = his->GetNdimensions();
  Double_t position[10];
  //
  TObjString str(tname);
  Bool_t isAll  = str.String().Contains("all");
  Bool_t hasPIXEL=HasPIXEL(&str);
  Bool_t hasTRD=HasTRD(&str);
  Bool_t hasTOF=HasTOF(&str);
  Bool_t hasACORDE=HasACORDE(&str);
  for (Long64_t i = 0; i < his->GetNbins(); ++i) {
    value = his->GetBinContent(i, bins);
    pcstream<<"val="<<value;
    pcstream<<"tname.="<<&str;
    //
    pcstream<<"all="<<isAll;
    pcstream<<"pixel="<<hasPIXEL;
    pcstream<<"trd="<<hasTRD;
    pcstream<<"tof="<<hasTOF;
    pcstream<<"acorde="<<hasACORDE;
    //
    for (Int_t idim = 0; idim < ndim; idim++) {
      position[idim] = his->GetAxis(idim)->GetBinCenter(bins[idim]);
      pcstream<<Form("%s=",his->GetAxis(idim)->GetName())<<position[idim];
    }
    pcstream<<"\n";
  }
}

Bool_t AliTPCcalibTrigger::HasTOF(TObjString *tname){
  //
  Bool_t result = kFALSE;
  result|=(tname->String().Contains("0OB")>0);
  result|=(tname->String().Contains("0OC")>0);
  return result;
}

Bool_t AliTPCcalibTrigger::HasACORDE(TObjString *tname){
  Bool_t result = kFALSE;
  result|=(tname->String().Contains("0ASL")>0);
  result|=(tname->String().Contains("0AMU")>0);
  result|=(tname->String().Contains("0ASC")>0);
  return result;
}

Bool_t AliTPCcalibTrigger::HasPIXEL(TObjString *tname){
  return (tname->String().Contains("0SCO")>0);
}

Bool_t AliTPCcalibTrigger::HasTRD(TObjString *tname){
  Bool_t result = kFALSE;
  result|=(tname->String().Contains("TRD")>0);
  result|=(tname->String().Contains("1H")>0);
  return result;
}

<|endoftext|>