<commit_before>/* -*-c++-*-
 *
 * Copyright (C) 2006-2007 Mathias Froehlich, Tim Moore
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 */

#ifdef HAVE_CONFIG_H
#  include <simgear_config.h>
#endif

#include "SGOceanTile.hxx"

#include <math.h>
#include <simgear/compiler.h>

#include <osg/Geode>
#include <osg/Geometry>
#include <osg/MatrixTransform>
#include <osg/StateSet>

#include <simgear/bucket/newbucket.hxx>
#include <simgear/math/sg_geodesy.hxx>
#include <simgear/math/sg_types.hxx>
#include <simgear/misc/texcoord.hxx>
#include <simgear/scene/material/mat.hxx>
#include <simgear/scene/material/matlib.hxx>
#include <simgear/scene/util/VectorArrayAdapter.hxx>

using namespace simgear;
// Ocean tile with curvature and apron to hide cracks. The cracks are
// mostly with adjoining coastal tiles that assume a flat ocean
// between corners of a tile; they also hide the micro cracks between
// adjoining ocean tiles. This is probably over-engineered, but it
// serves as a testbed for some things that will come later.

// Helper class for building and accessing the mesh. The layout of the
// points in the mesh is a little wacky. First is the bottom row of
// the points for the apron. Next is the left apron point, the points
// in the mesh, and the right apron point, for each of the rows of the
// mesh; the points for the top apron come last. This order should
// help with things like vertex caching in the OpenGL driver, though
// it may be superfluous for such a small mesh.
namespace
{
const int lonPoints = 5;
const int latPoints = 5;

class OceanMesh {
public:
    OceanMesh():
        geoPoints(latPoints * lonPoints + 2 * (lonPoints + latPoints)),
        geod_nodes(latPoints * lonPoints),
        vl(new osg::Vec3Array(geoPoints)),
        nl(new osg::Vec3Array(geoPoints)),
        tl(new osg::Vec2Array(geoPoints)),
        vlArray(*vl, lonPoints + 2, lonPoints, 1),
        nlArray(*nl, lonPoints + 2, lonPoints, 1),
        tlArray(*tl, lonPoints + 2, lonPoints, 1)
    {
    }
    const int geoPoints;
    SGGeod geod[latPoints][lonPoints];
    SGVec3f normals[latPoints][lonPoints];
    SGVec3d rel[latPoints][lonPoints];

    point_list geod_nodes;

    osg::Vec3Array* vl;
    osg::Vec3Array* nl;
    osg::Vec2Array* tl;
    VectorArrayAdapter<osg::Vec3Array> vlArray;
    VectorArrayAdapter<osg::Vec3Array> nlArray;
    VectorArrayAdapter<osg::Vec2Array> tlArray;

    void calcMesh(const SGVec3d& cartCenter, double clon, double clat,
                  double height, double width, double tex_width);
    void calcApronPt(int latIdx, int lonIdx, int latInner, int lonInner,
                     int destIdx, double tex_width);
    void calcApronPts(double tex_width);

};
}

void OceanMesh::calcMesh(const SGVec3d& cartCenter, double clon, double clat,
                         double height, double width, double tex_width)
{
    // Calculate vertices. By splitting the tile up into 4 quads on a
    // side we avoid curvature-of-the-earth problems; the error should
    // be less than .5 meters.
    double longInc = width * .25;
    double latInc = height * .25;
    double startLat = clat - height * .5;
    double startLon = clon - width * .5;
    for (int j = 0; j < latPoints; j++) {
        double lat = startLat + j * latInc;
        for (int i = 0; i < lonPoints; i++) {
            geod[j][i] = SGGeod::fromDeg(startLon + i * longInc, lat);
            SGVec3d cart = SGVec3d::fromGeod(geod[j][i]);
            rel[j][i] = cart - cartCenter;
            normals[j][i] = toVec3f(normalize(cart));
        }
    }

    // Calculate texture coordinates
    point_list geod_nodes(latPoints * lonPoints);
    VectorArrayAdapter<point_list> geodNodesArray(geod_nodes, lonPoints);
    int_list rectangle(latPoints * lonPoints);
    VectorArrayAdapter<int_list> rectArray(rectangle, lonPoints);
    for (int j = 0; j < latPoints; j++) {
        for (int i = 0; i < lonPoints; i++) {
            geodNodesArray(j, i) = Point3D(geod[j][i].getLongitudeDeg(),
                                           geod[j][i].getLatitudeDeg(),
                                           geod[j][i].getElevationM());
            rectArray(j, i) = j * 5 + i;
        }
    }
    point_list texs = sgCalcTexCoords( clat, geod_nodes, rectangle,
                                       1000.0 / tex_width );
    VectorArrayAdapter<point_list> texsArray(texs, lonPoints);

    for (int j = 0; j < latPoints; j++) {
        for (int i = 0; i < lonPoints; ++i) {
            vlArray(j, i) = rel[j][i].osg();
            nlArray(j, i) = normals[j][i].osg();
            tlArray(j, i) = texsArray(j, i).toSGVec2f().osg();
        }
    }

}

// Apron points. For each point on the edge we'll go 150
// metres "down" and 40 metres "out" to create a nice overlap. The
// texture should be applied according to this dimension. The
// normals of the apron polygons will be the same as the those of
// the points on the edge to better disguise the apron.
void OceanMesh::calcApronPt(int latIdx, int lonIdx, int latInner, int lonInner,
                            int destIdx, double tex_width)
{
    static const float downDist = 150.0f;
    static const float outDist = 40.0f;
    // Get vector along edge, in the right direction to make a cross
    // product with the normal vector that will point out from the
    // mesh.
    osg::Vec3f edgePt = vlArray(latIdx, lonIdx);
    osg::Vec3f edgeVec;
    if (lonIdx == lonInner) {   // bottom or top edge
        if (lonIdx > 0)
            edgeVec = vlArray(latIdx, lonIdx - 1) - edgePt;
        else
            edgeVec = edgePt - vlArray(latIdx, lonIdx + 1);
        if (latIdx > latInner)
            edgeVec = -edgeVec;  // Top edge
    } else {                     // right or left edge
        if (latIdx > 0)
            edgeVec = edgePt - vlArray(latIdx - 1, lonIdx);
        else
            edgeVec = vlArray(latIdx + 1, lonIdx) - edgePt;
        if (lonIdx > lonInner)  // right edge
            edgeVec = -edgeVec;
    }
    edgeVec.normalize();
    osg::Vec3f outVec = nlArray(latIdx, lonIdx) ^ edgeVec;
    (*vl)[destIdx]
        = edgePt - nlArray(latIdx, lonIdx) * downDist + outVec * outDist;
    (*nl)[destIdx] = nlArray(latIdx, lonIdx);
    static const float apronDist
        = sqrtf(downDist * downDist  + outDist * outDist);
    float texDelta = apronDist / tex_width;
    if (lonIdx == lonInner) {
        if (latIdx > latInner)
            (*tl)[destIdx]
                = tlArray(latIdx, lonIdx) + osg::Vec2f(0.0f, texDelta);
        else
            (*tl)[destIdx]
                = tlArray(latIdx, lonIdx) - osg::Vec2f(0.0f, texDelta);
    } else {
        if (lonIdx > lonInner)
            (*tl)[destIdx]
                = tlArray(latIdx, lonIdx) + osg::Vec2f(texDelta, 0.0f);
        else
            (*tl)[destIdx]
                = tlArray(latIdx, lonIdx) - osg::Vec2f(texDelta, 0.0f);
    }
}

void OceanMesh::calcApronPts(double tex_width)
{
    for (int i = 0; i < lonPoints; i++)
        calcApronPt(0, i, 1, i, i, tex_width);
    int topApronOffset = latPoints + (2 + lonPoints) * latPoints;
    for (int i = 0; i < lonPoints; i++)
        calcApronPt(latPoints - 1, i, latPoints - 2, i,
                    i + topApronOffset, tex_width);
    for (int i = 0; i < latPoints; i++) {
        calcApronPt(i, 0, i, 1, lonPoints + i * (lonPoints + 2), tex_width);
        calcApronPt(i, lonPoints - 1, i, lonPoints - 2,
                    lonPoints + i * (lonPoints + 2) + 1 + lonPoints, tex_width);
    }
}

namespace
{
// Enter the vertices of triangles that fill one row of the
// mesh. The vertices are entered in counter-clockwise order.
void fillDrawElementsRow(int width, short row0Start, short row1Start,
                         osg::DrawElementsUShort::vector_type::iterator&
                         elements)
{
    short row0Idx = row0Start;
    short row1Idx = row1Start;
    for (int i = 0; i < width - 1; i++, row0Idx++, row1Idx++) {
        *elements++ = row0Idx;
        *elements++ = row0Idx + 1;
        *elements++ = row1Idx;
        *elements++ = row1Idx;
        *elements++ = row0Idx + 1;
        *elements++ = row1Idx + 1;
    }
}

void fillDrawElementsWithApron(short height, short width,
                               osg::DrawElementsUShort::vector_type::iterator
                               elements)
{
    // First apron row
    fillDrawElementsRow(width, 0, width + 1, elements);
    for (short i = 0; i < height - 1; i++)
        fillDrawElementsRow(width + 2, width + i * (width + 2),
                            width + (i + 1) * (width + 2),
                            elements);
    // Last apron row
    short topApronBottom = width + (height - 1) * (width + 2) + 1;
    fillDrawElementsRow(width, topApronBottom, topApronBottom + width + 1,
                        elements);
}
}

osg::Node* SGOceanTile(const SGBucket& b, SGMaterialLib *matlib)
{
    osg::StateSet *stateSet = 0;

    double tex_width = 1000.0;

    // find Ocean material in the properties list
    SGMaterial *mat = matlib->find( "Ocean" );
    if ( mat != NULL ) {
        // set the texture width and height values for this
        // material
        tex_width = mat->get_xsize();

        // set OSG State
        stateSet = mat->get_state();
    } else {
        SG_LOG( SG_TERRAIN, SG_ALERT, "Ack! unknown use material name = Ocean");
    }
    OceanMesh grid;
    // Calculate center point
    SGVec3d cartCenter = SGVec3d::fromGeod(b.get_center());

    double clon = b.get_center_lon();
    double clat = b.get_center_lat();
    double height = b.get_height();
    double width = b.get_width();

    grid.calcMesh(cartCenter, clon, clat, height, width, tex_width);
    grid.calcApronPts(tex_width);

    osg::Vec4Array* cl = new osg::Vec4Array;
    cl->push_back(osg::Vec4(1, 1, 1, 1));

    osg::Geometry* geometry = new osg::Geometry;
    geometry->setVertexArray(grid.vl);
    geometry->setNormalArray(grid.nl);
    geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
    geometry->setColorArray(cl);
    geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
    geometry->setTexCoordArray(0, grid.tl);

    // Allocate the indices for triangles in the mesh and the apron
    osg::DrawElementsUShort* drawElements
        = new osg::DrawElementsUShort(GL_TRIANGLES,
                                      6 * ((latPoints - 1) * (lonPoints + 1)
                                           + 2 * (latPoints - 1)));
    fillDrawElementsWithApron(latPoints, lonPoints, drawElements->begin());
    geometry->addPrimitiveSet(drawElements);

    osg::Geode* geode = new osg::Geode;
    geode->setName("Ocean tile");
    geode->addDrawable(geometry);
    geode->setStateSet(stateSet);

    osg::MatrixTransform* transform = new osg::MatrixTransform;
    transform->setName("Ocean");
    transform->setMatrix(osg::Matrix::translate(cartCenter.osg()));
    transform->addChild(geode);

    return transform;
}
<commit_msg>ocean state set in osg::Geometry<commit_after>/* -*-c++-*-
 *
 * Copyright (C) 2006-2007 Mathias Froehlich, Tim Moore
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 */

#ifdef HAVE_CONFIG_H
#  include <simgear_config.h>
#endif

#include "SGOceanTile.hxx"

#include <math.h>
#include <simgear/compiler.h>

#include <osg/Geode>
#include <osg/Geometry>
#include <osg/MatrixTransform>
#include <osg/StateSet>

#include <simgear/bucket/newbucket.hxx>
#include <simgear/math/sg_geodesy.hxx>
#include <simgear/math/sg_types.hxx>
#include <simgear/misc/texcoord.hxx>
#include <simgear/scene/material/mat.hxx>
#include <simgear/scene/material/matlib.hxx>
#include <simgear/scene/util/VectorArrayAdapter.hxx>

using namespace simgear;
// Ocean tile with curvature and apron to hide cracks. The cracks are
// mostly with adjoining coastal tiles that assume a flat ocean
// between corners of a tile; they also hide the micro cracks between
// adjoining ocean tiles. This is probably over-engineered, but it
// serves as a testbed for some things that will come later.

// Helper class for building and accessing the mesh. The layout of the
// points in the mesh is a little wacky. First is the bottom row of
// the points for the apron. Next is the left apron point, the points
// in the mesh, and the right apron point, for each of the rows of the
// mesh; the points for the top apron come last. This order should
// help with things like vertex caching in the OpenGL driver, though
// it may be superfluous for such a small mesh.
namespace
{
const int lonPoints = 5;
const int latPoints = 5;

class OceanMesh {
public:
    OceanMesh():
        geoPoints(latPoints * lonPoints + 2 * (lonPoints + latPoints)),
        geod_nodes(latPoints * lonPoints),
        vl(new osg::Vec3Array(geoPoints)),
        nl(new osg::Vec3Array(geoPoints)),
        tl(new osg::Vec2Array(geoPoints)),
        vlArray(*vl, lonPoints + 2, lonPoints, 1),
        nlArray(*nl, lonPoints + 2, lonPoints, 1),
        tlArray(*tl, lonPoints + 2, lonPoints, 1)
    {
    }
    const int geoPoints;
    SGGeod geod[latPoints][lonPoints];
    SGVec3f normals[latPoints][lonPoints];
    SGVec3d rel[latPoints][lonPoints];

    point_list geod_nodes;

    osg::Vec3Array* vl;
    osg::Vec3Array* nl;
    osg::Vec2Array* tl;
    VectorArrayAdapter<osg::Vec3Array> vlArray;
    VectorArrayAdapter<osg::Vec3Array> nlArray;
    VectorArrayAdapter<osg::Vec2Array> tlArray;

    void calcMesh(const SGVec3d& cartCenter, double clon, double clat,
                  double height, double width, double tex_width);
    void calcApronPt(int latIdx, int lonIdx, int latInner, int lonInner,
                     int destIdx, double tex_width);
    void calcApronPts(double tex_width);

};
}

void OceanMesh::calcMesh(const SGVec3d& cartCenter, double clon, double clat,
                         double height, double width, double tex_width)
{
    // Calculate vertices. By splitting the tile up into 4 quads on a
    // side we avoid curvature-of-the-earth problems; the error should
    // be less than .5 meters.
    double longInc = width * .25;
    double latInc = height * .25;
    double startLat = clat - height * .5;
    double startLon = clon - width * .5;
    for (int j = 0; j < latPoints; j++) {
        double lat = startLat + j * latInc;
        for (int i = 0; i < lonPoints; i++) {
            geod[j][i] = SGGeod::fromDeg(startLon + i * longInc, lat);
            SGVec3d cart = SGVec3d::fromGeod(geod[j][i]);
            rel[j][i] = cart - cartCenter;
            normals[j][i] = toVec3f(normalize(cart));
        }
    }

    // Calculate texture coordinates
    point_list geod_nodes(latPoints * lonPoints);
    VectorArrayAdapter<point_list> geodNodesArray(geod_nodes, lonPoints);
    int_list rectangle(latPoints * lonPoints);
    VectorArrayAdapter<int_list> rectArray(rectangle, lonPoints);
    for (int j = 0; j < latPoints; j++) {
        for (int i = 0; i < lonPoints; i++) {
            geodNodesArray(j, i) = Point3D(geod[j][i].getLongitudeDeg(),
                                           geod[j][i].getLatitudeDeg(),
                                           geod[j][i].getElevationM());
            rectArray(j, i) = j * 5 + i;
        }
    }
    point_list texs = sgCalcTexCoords( clat, geod_nodes, rectangle,
                                       1000.0 / tex_width );
    VectorArrayAdapter<point_list> texsArray(texs, lonPoints);

    for (int j = 0; j < latPoints; j++) {
        for (int i = 0; i < lonPoints; ++i) {
            vlArray(j, i) = rel[j][i].osg();
            nlArray(j, i) = normals[j][i].osg();
            tlArray(j, i) = texsArray(j, i).toSGVec2f().osg();
        }
    }

}

// Apron points. For each point on the edge we'll go 150
// metres "down" and 40 metres "out" to create a nice overlap. The
// texture should be applied according to this dimension. The
// normals of the apron polygons will be the same as the those of
// the points on the edge to better disguise the apron.
void OceanMesh::calcApronPt(int latIdx, int lonIdx, int latInner, int lonInner,
                            int destIdx, double tex_width)
{
    static const float downDist = 150.0f;
    static const float outDist = 40.0f;
    // Get vector along edge, in the right direction to make a cross
    // product with the normal vector that will point out from the
    // mesh.
    osg::Vec3f edgePt = vlArray(latIdx, lonIdx);
    osg::Vec3f edgeVec;
    if (lonIdx == lonInner) {   // bottom or top edge
        if (lonIdx > 0)
            edgeVec = vlArray(latIdx, lonIdx - 1) - edgePt;
        else
            edgeVec = edgePt - vlArray(latIdx, lonIdx + 1);
        if (latIdx > latInner)
            edgeVec = -edgeVec;  // Top edge
    } else {                     // right or left edge
        if (latIdx > 0)
            edgeVec = edgePt - vlArray(latIdx - 1, lonIdx);
        else
            edgeVec = vlArray(latIdx + 1, lonIdx) - edgePt;
        if (lonIdx > lonInner)  // right edge
            edgeVec = -edgeVec;
    }
    edgeVec.normalize();
    osg::Vec3f outVec = nlArray(latIdx, lonIdx) ^ edgeVec;
    (*vl)[destIdx]
        = edgePt - nlArray(latIdx, lonIdx) * downDist + outVec * outDist;
    (*nl)[destIdx] = nlArray(latIdx, lonIdx);
    static const float apronDist
        = sqrtf(downDist * downDist  + outDist * outDist);
    float texDelta = apronDist / tex_width;
    if (lonIdx == lonInner) {
        if (latIdx > latInner)
            (*tl)[destIdx]
                = tlArray(latIdx, lonIdx) + osg::Vec2f(0.0f, texDelta);
        else
            (*tl)[destIdx]
                = tlArray(latIdx, lonIdx) - osg::Vec2f(0.0f, texDelta);
    } else {
        if (lonIdx > lonInner)
            (*tl)[destIdx]
                = tlArray(latIdx, lonIdx) + osg::Vec2f(texDelta, 0.0f);
        else
            (*tl)[destIdx]
                = tlArray(latIdx, lonIdx) - osg::Vec2f(texDelta, 0.0f);
    }
}

void OceanMesh::calcApronPts(double tex_width)
{
    for (int i = 0; i < lonPoints; i++)
        calcApronPt(0, i, 1, i, i, tex_width);
    int topApronOffset = latPoints + (2 + lonPoints) * latPoints;
    for (int i = 0; i < lonPoints; i++)
        calcApronPt(latPoints - 1, i, latPoints - 2, i,
                    i + topApronOffset, tex_width);
    for (int i = 0; i < latPoints; i++) {
        calcApronPt(i, 0, i, 1, lonPoints + i * (lonPoints + 2), tex_width);
        calcApronPt(i, lonPoints - 1, i, lonPoints - 2,
                    lonPoints + i * (lonPoints + 2) + 1 + lonPoints, tex_width);
    }
}

namespace
{
// Enter the vertices of triangles that fill one row of the
// mesh. The vertices are entered in counter-clockwise order.
void fillDrawElementsRow(int width, short row0Start, short row1Start,
                         osg::DrawElementsUShort::vector_type::iterator&
                         elements)
{
    short row0Idx = row0Start;
    short row1Idx = row1Start;
    for (int i = 0; i < width - 1; i++, row0Idx++, row1Idx++) {
        *elements++ = row0Idx;
        *elements++ = row0Idx + 1;
        *elements++ = row1Idx;
        *elements++ = row1Idx;
        *elements++ = row0Idx + 1;
        *elements++ = row1Idx + 1;
    }
}

void fillDrawElementsWithApron(short height, short width,
                               osg::DrawElementsUShort::vector_type::iterator
                               elements)
{
    // First apron row
    fillDrawElementsRow(width, 0, width + 1, elements);
    for (short i = 0; i < height - 1; i++)
        fillDrawElementsRow(width + 2, width + i * (width + 2),
                            width + (i + 1) * (width + 2),
                            elements);
    // Last apron row
    short topApronBottom = width + (height - 1) * (width + 2) + 1;
    fillDrawElementsRow(width, topApronBottom, topApronBottom + width + 1,
                        elements);
}
}

osg::Node* SGOceanTile(const SGBucket& b, SGMaterialLib *matlib)
{
    osg::StateSet *stateSet = 0;

    double tex_width = 1000.0;

    // find Ocean material in the properties list
    SGMaterial *mat = matlib->find( "Ocean" );
    if ( mat != NULL ) {
        // set the texture width and height values for this
        // material
        tex_width = mat->get_xsize();

        // set OSG State
        stateSet = mat->get_state();
    } else {
        SG_LOG( SG_TERRAIN, SG_ALERT, "Ack! unknown use material name = Ocean");
    }
    OceanMesh grid;
    // Calculate center point
    SGVec3d cartCenter = SGVec3d::fromGeod(b.get_center());

    double clon = b.get_center_lon();
    double clat = b.get_center_lat();
    double height = b.get_height();
    double width = b.get_width();

    grid.calcMesh(cartCenter, clon, clat, height, width, tex_width);
    grid.calcApronPts(tex_width);

    osg::Vec4Array* cl = new osg::Vec4Array;
    cl->push_back(osg::Vec4(1, 1, 1, 1));

    osg::Geometry* geometry = new osg::Geometry;
    geometry->setVertexArray(grid.vl);
    geometry->setNormalArray(grid.nl);
    geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
    geometry->setColorArray(cl);
    geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
    geometry->setTexCoordArray(0, grid.tl);

    // Allocate the indices for triangles in the mesh and the apron
    osg::DrawElementsUShort* drawElements
        = new osg::DrawElementsUShort(GL_TRIANGLES,
                                      6 * ((latPoints - 1) * (lonPoints + 1)
                                           + 2 * (latPoints - 1)));
    fillDrawElementsWithApron(latPoints, lonPoints, drawElements->begin());
    geometry->addPrimitiveSet(drawElements);
    geometry->setStateSet(stateSet);

    osg::Geode* geode = new osg::Geode;
    geode->setName("Ocean tile");
    geode->addDrawable(geometry);

    osg::MatrixTransform* transform = new osg::MatrixTransform;
    transform->setName("Ocean");
    transform->setMatrix(osg::Matrix::translate(cartCenter.osg()));
    transform->addChild(geode);

    return transform;
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
 * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
 * full copyright notice.                                                 *
 **************************************************************************/

// Macro to visualise rootified raw-data from AD.
//

#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TStyle.h>
#include <TEveManager.h>

#include <AliESDAD.h>
#include <AliEveEventManager.h>
#include <AliEveADModule.h>
#else
class AliESDAD;
class AliEveADModule;
#endif

void ad_esd(Int_t maxCharge = 3000, Bool_t showLegend = kFALSE)
{
  gStyle->SetPalette(1, 0);

  AliESDAD *adESD = AliEveEventManager::AssertESD()->GetADData();

  gEve->DisableRedraw();

  AliEveADModule* esdA = new AliEveADModule("AD_ESD_A", kTRUE, maxCharge, showLegend);
  esdA->LoadEsd(adESD);

  AliEveADModule* esdC = new AliEveADModule("AD_ESD_C", kFALSE, maxCharge, showLegend);
  esdC->LoadEsd(adESD);

  gEve->EnableRedraw();
}
<commit_msg>Default value too optimistic<commit_after>/**************************************************************************
 * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
 * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
 * full copyright notice.                                                 *
 **************************************************************************/

// Macro to visualise rootified raw-data from AD.
//

#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TStyle.h>
#include <TEveManager.h>

#include <AliESDAD.h>
#include <AliEveEventManager.h>
#include <AliEveADModule.h>
#else
class AliESDAD;
class AliEveADModule;
#endif

void ad_esd(Int_t maxCharge = 300, Bool_t showLegend = kFALSE)
{
  gStyle->SetPalette(1, 0);

  AliESDAD *adESD = AliEveEventManager::AssertESD()->GetADData();

  gEve->DisableRedraw();

  AliEveADModule* esdA = new AliEveADModule("AD_ESD_A", kTRUE, maxCharge, showLegend);
  esdA->LoadEsd(adESD);

  AliEveADModule* esdC = new AliEveADModule("AD_ESD_C", kFALSE, maxCharge, showLegend);
  esdC->LoadEsd(adESD);

  gEve->EnableRedraw();
}
<|endoftext|>


<commit_before>/*
* ArcScript Scripts for Arcemu MMORPG Server
* Copyright (C) 2008-2009 Arcemu Team
* Copyright (C) 2007 Moon++ <http://www.moonplusplus.com/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "StdAfx.h"
#include "Setup.h"

//Alice : Correct formula for Rogue - Preparation

bool Preparation(uint32 i, Spell * pSpell)
{
	if(!pSpell->p_caster) return true;

	pSpell->p_caster->ClearCooldownForSpell( 5277 );        // Evasion Rank 1
	pSpell->p_caster->ClearCooldownForSpell( 26669 );       // Evasion Rank 2
	pSpell->p_caster->ClearCooldownForSpell( 2983 );        // Sprint Rank 1
	pSpell->p_caster->ClearCooldownForSpell( 8696 );        // Sprint Rank 2
	pSpell->p_caster->ClearCooldownForSpell( 11305 );       // Sprint Rank 3
	pSpell->p_caster->ClearCooldownForSpell( 1856 );        // Vanish Rank 1
	pSpell->p_caster->ClearCooldownForSpell( 1857 );        // Vanish Rank 2
	pSpell->p_caster->ClearCooldownForSpell( 26889 );       // Vanish Rank 3
	pSpell->p_caster->ClearCooldownForSpell( 14177 );       // Cold Blood
	pSpell->p_caster->ClearCooldownForSpell( 14183 );       // Premeditation
	pSpell->p_caster->ClearCooldownForSpell( 36554 );       // Shadowstep
	return true;
}

bool Shiv(uint32 i, Spell *pSpell){
	Unit *pTarget = pSpell->GetUnitTarget();
	if(!pSpell->p_caster || !pTarget) return true;

	pSpell->p_caster->CastSpell(pTarget->GetGUID(), 4950, true);

	if( pSpell->p_caster->GetItemInterface() )
	{
		Item *it = pSpell->p_caster->GetItemInterface()->GetInventoryItem( EQUIPMENT_SLOT_OFFHAND );
		if(!it) return true;

		EnchantmentInstance * ench = it->GetEnchantment( 1 ); // temp enchantment slot
		if(ench) {
			EnchantEntry* Entry = ench->Enchantment;
			for( uint32 c = 0; c < 3; c++ )
			{
				if( Entry->type[c] && Entry->spell[c] )
				{
					SpellEntry *sp = dbcSpell.LookupEntry( Entry->spell[c] );
					if(!sp) return true;

					if( sp->c_is_flags & SPELL_FLAG_IS_POISON )
					{
						pSpell->p_caster->CastSpell(pTarget->GetGUID(),Entry->spell[c], true);
					}
				}
			}
		}
	}
	return true;
}

void SetupRogueSpells(ScriptMgr * mgr)
{
	mgr->register_dummy_spell(5938, &Shiv);
	mgr->register_dummy_spell(14185, &Preparation);
}
<commit_msg>* Corrected: Typo in RogueSpells.cpp.<commit_after>/*
* ArcScript Scripts for Arcemu MMORPG Server
* Copyright (C) 2008-2009 Arcemu Team
* Copyright (C) 2007 Moon++ <http://www.moonplusplus.com/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "StdAfx.h"
#include "Setup.h"

//Alice : Correct formula for Rogue - Preparation

bool Preparation(uint32 i, Spell * pSpell)
{
	if(!pSpell->p_caster) return true;

	pSpell->p_caster->ClearCooldownForSpell( 5277 );        // Evasion Rank 1
	pSpell->p_caster->ClearCooldownForSpell( 26669 );       // Evasion Rank 2
	pSpell->p_caster->ClearCooldownForSpell( 2983 );        // Sprint Rank 1
	pSpell->p_caster->ClearCooldownForSpell( 8696 );        // Sprint Rank 2
	pSpell->p_caster->ClearCooldownForSpell( 11305 );       // Sprint Rank 3
	pSpell->p_caster->ClearCooldownForSpell( 1856 );        // Vanish Rank 1
	pSpell->p_caster->ClearCooldownForSpell( 1857 );        // Vanish Rank 2
	pSpell->p_caster->ClearCooldownForSpell( 26889 );       // Vanish Rank 3
	pSpell->p_caster->ClearCooldownForSpell( 14177 );       // Cold Blood
	pSpell->p_caster->ClearCooldownForSpell( 14183 );       // Premeditation
	pSpell->p_caster->ClearCooldownForSpell( 36554 );       // Shadowstep
	return true;
}

bool Shiv(uint32 i, Spell *pSpell){
	Unit *pTarget = pSpell->GetUnitTarget();
	if(!pSpell->p_caster || !pTarget) return true;

	pSpell->p_caster->CastSpell(pTarget->GetGUID(), 5940, true);

	if( pSpell->p_caster->GetItemInterface() )
	{
		Item *it = pSpell->p_caster->GetItemInterface()->GetInventoryItem( EQUIPMENT_SLOT_OFFHAND );
		if(!it) return true;

		EnchantmentInstance * ench = it->GetEnchantment( 1 ); // temp enchantment slot
		if(ench) {
			EnchantEntry* Entry = ench->Enchantment;
			for( uint32 c = 0; c < 3; c++ )
			{
				if( Entry->type[c] && Entry->spell[c] )
				{
					SpellEntry *sp = dbcSpell.LookupEntry( Entry->spell[c] );
					if(!sp) return true;

					if( sp->c_is_flags & SPELL_FLAG_IS_POISON )
					{
						pSpell->p_caster->CastSpell(pTarget->GetGUID(),Entry->spell[c], true);
					}
				}
			}
		}
	}
	return true;
}

void SetupRogueSpells(ScriptMgr * mgr)
{
	mgr->register_dummy_spell(5938, &Shiv);
	mgr->register_dummy_spell(14185, &Preparation);
}
<|endoftext|>


<commit_before>/**
 * @file   strategy.hpp
 * @author Matheus Vieira Portela
 * @date   23/03/2014
 *
 * @attention Copyright (C) 2014 UnBall Robot Soccer Team
 *
 * @brief  Strategy class
 *
 * Defines strategy for robots
 */

#ifndef UNBALL_STRATEGY_H_
#define UNBALL_STRATEGY_H_

#include <vector>
#include "robot.hpp"
#include "ball.hpp"

class Strategy
{
  public:
    void run();

    void setRobotLocation(float x, float y, int robot_number);
    std::vector<float> getRobotVelocities(int robot_number);

    void setBallLocation(float x, float y);

  private:
    Robot robots_[6];
    Ball ball_;
};

#endif  // UNBALL_STRATEGY_H_
<commit_msg>Inserting two comments (minor changes)<commit_after>/**
 * @file   strategy.hpp
 * @author Matheus Vieira Portela
 * @date   23/03/2014
 *
 * @attention Copyright (C) 2014 UnBall Robot Soccer Team
 *
 * @brief  Strategy class
 *
 * Defines strategy for robots
 */

#ifndef UNBALL_STRATEGY_H_
#define UNBALL_STRATEGY_H_

#include <vector>
#include "robot.hpp"
#include "ball.hpp"

class Strategy
{
  public:
    void run();

    // Robot methods
    void setRobotLocation(float x, float y, int robot_number);
    std::vector<float> getRobotVelocities(int robot_number);

    // Ball methods
    void setBallLocation(float x, float y);

  private:
    Robot robots_[6];
    Ball ball_;
};

#endif  // UNBALL_STRATEGY_H_
<|endoftext|>


<commit_before><commit_msg>change a couple local variables from float to double<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 * Copyright (c) 2014 eProsima. All rights reserved.
 *
 * This copy of eProsima RTPS is licensed to you under the terms described in the
 * EPROSIMARTPS_LIBRARY_LICENSE file included in this distribution.
 *
 *************************************************************************/

/**
 * @file EDPStatic.cpp
 *
 */

#include "eprosimartps/builtin/discovery/endpoint/EDPStatic.h"
#include "eprosimartps/builtin/discovery/participant/PDPSimple.h"

#include "eprosimartps/reader/WriterProxyData.h"
#include "eprosimartps/writer/ReaderProxyData.h"

#include "eprosimartps/reader/RTPSReader.h"
#include "eprosimartps/writer/RTPSWriter.h"

#include "eprosimartps/utils/RTPSLog.h"

#include <sstream>

namespace eprosima {
namespace rtps {

EDPStatic::EDPStatic(PDPSimple* p,ParticipantImpl* part):
																																																EDP(p,part)
{

}

EDPStatic::~EDPStatic()
{

}

bool EDPStatic::initEDP(BuiltinAttributes& attributes)
{
	pInfo(RTPS_B_CYAN<<"Initializing  STATIC EndpointDiscoveryProtocol"<<endl);
	m_attributes = attributes;
	return this->m_edpXML.loadXMLFile(m_attributes.m_staticEndpointXMLFilename);
}

std::pair<std::string,std::string> EDPStaticProperty::toProperty(std::string type,std::string status,uint16_t id,const EntityId_t& ent)
{
	std::pair<std::string,std::string> property;
	std::stringstream ss;
	ss << "eProsimaEDPStatic_"<<type<<"_"<<status<<"_ID_"<<id;
	property.first = ss.str();
	ss.clear();
	ss.str(std::string());
	ss << ent.value[0]<<".";
	ss << ent.value[1]<<".";
	ss << ent.value[2]<<".";
	ss << ent.value[3];
	property.second = ss.str();
	return property;
}

bool EDPStaticProperty::fromProperty(std::pair<std::string,std::string> property)
{
	int pos1 = property.first.find("_");
	str1 = property.first.substr(0,pos1);

	int pos2 = property.first.find("_",pos1+1);
	type = property.first.substr(pos1+1,pos2);

	pos1 = property.first.find("_",pos2+1);
	status = property.first.substr(pos2+1,pos1);

	pos2 = property.first.find("_",pos1+1);
	idstr = property.first.substr(pos1+1,pos2);

	userIDstr = property.first.substr(pos2+1);

	if(str1 == "eProsimaEDPStatic" && idstr == "ID")
	{
		std::stringstream ss;
		ss << userIDstr;
		ss >> userId;
		ss.clear();
		ss.str(std::string());
		ss << property.second;
		int a,b,c,d;
		char ch;
		ss >> a >> ch >> b >> ch >> c >>ch >> d;
		entityId.value[0] = (octet)a;entityId.value[1] = (octet)b;
		entityId.value[2] = (octet)c;entityId.value[3] = (octet)d;
		return true;
	}
	return false;
}

bool EDPStatic::processLocalReaderProxyData(ReaderProxyData* rdata)
{
	//Add the property list entry to our local pdp
	ParticipantProxyData* localpdata = this->mp_PDP->getLocalParticipantProxyData();
	localpdata->m_properties.properties.push_back(EDPStaticProperty::toProperty("Reader","ALIVE",rdata->m_userDefinedId,rdata->m_guid.entityId));
	return true;
}

bool EDPStatic::processLocalWriterProxyData(WriterProxyData* wdata)
{
	//Add the property list entry to our local pdp
	ParticipantProxyData* localpdata = this->mp_PDP->getLocalParticipantProxyData();
	localpdata->m_properties.properties.push_back(EDPStaticProperty::toProperty("Writer","ALIVE",wdata->m_userDefinedId,wdata->m_guid.entityId));
	return true;
}

bool EDPStatic::removeLocalReader(RTPSReader* R)
{
	ParticipantProxyData* localpdata = this->mp_PDP->getLocalParticipantProxyData();
	for(std::vector<std::pair<std::string,std::string>>::iterator pit = localpdata->m_properties.properties.begin();
			pit!=localpdata->m_properties.properties.end();++pit)
	{
		EDPStaticProperty staticproperty;
		if(staticproperty.fromProperty(*pit))
		{
			if(staticproperty.entityId == R->getGuid().entityId)
			{
				*pit = EDPStaticProperty::toProperty("Reader","DEAD",R->getUserDefinedId(),R->getGuid().entityId);
			}
		}
	}
	return false;
}

bool EDPStatic::removeLocalWriter(RTPSWriter*W)
{
	ParticipantProxyData* localpdata = this->mp_PDP->getLocalParticipantProxyData();
	for(std::vector<std::pair<std::string,std::string>>::iterator pit = localpdata->m_properties.properties.begin();
			pit!=localpdata->m_properties.properties.end();++pit)
	{
		EDPStaticProperty staticproperty;
		if(staticproperty.fromProperty(*pit))
		{
			if(staticproperty.entityId == W->getGuid().entityId)
			{
				*pit = EDPStaticProperty::toProperty("Writer","DEAD",W->getUserDefinedId(),W->getGuid().entityId);
			}
		}
	}
	return false;
}

void EDPStatic::assignRemoteEndpoints(ParticipantProxyData* pdata)
{
	for(std::vector<std::pair<std::string,std::string>>::iterator pit = pdata->m_properties.properties.begin();
			pit!=pdata->m_properties.properties.end();++pit)
	{
		EDPStaticProperty staticproperty;
		if(staticproperty.fromProperty(*pit))
		{
			if(staticproperty.type == "Reader" && staticproperty.status=="ALIVE")
			{
				ReaderProxyData* rdata=NULL;
				GUID_t guid(pdata->m_guid.guidPrefix,staticproperty.entityId);
				if(!this->mp_PDP->lookupReaderProxyData(guid,&rdata))//IF NOT FOUND, we CREATE AND PAIR IT
				{
					newRemoteReader(pdata,staticproperty.userId,staticproperty.entityId);
				}
			}
			else if(staticproperty.type == "Writer" && staticproperty.status == "ALIVE")
			{
				WriterProxyData* wdata=NULL;
				GUID_t guid(pdata->m_guid.guidPrefix,staticproperty.entityId);
				if(!this->mp_PDP->lookupWriterProxyData(guid,&wdata))//IF NOT FOUND, we CREATE AND PAIR IT
				{
					newRemoteWriter(pdata,staticproperty.userId,staticproperty.entityId);
				}
			}
			else if(staticproperty.type == "Reader" && staticproperty.status == "DEAD")
			{
				ReaderProxyData* rdata=NULL;
				GUID_t guid(pdata->m_guid.guidPrefix,staticproperty.entityId);
				if(this->mp_PDP->lookupReaderProxyData(guid,&rdata))//IF FOUND, we UNPAIR and remove IT
				{
					this->removeReaderProxy(guid);
				}
			}
			else if(staticproperty.type == "Writer" && staticproperty.status == "DEAD")
			{
				WriterProxyData* wdata=NULL;
				GUID_t guid(pdata->m_guid.guidPrefix,staticproperty.entityId);
				if(this->mp_PDP->lookupWriterProxyData(guid,&wdata)) //IF FOUND, we UNPAIR and remove IT
				{
					this->removeWriterProxy(guid);
				}
			}
			else
			{
				pWarning("eProsimaEDPStatic property with type: "<<staticproperty.type << " and status "<<staticproperty.status << " not recognized"<<endl);
			}
		}
	}
}

bool EDPStatic::newRemoteReader(ParticipantProxyData* pdata,uint16_t userId,EntityId_t& entId)
{
	ReaderProxyData* rpd = NULL;
	if(m_edpXML.lookforReader(pdata->m_participantName,userId,&rpd))
	{
		ReaderProxyData* newRPD = new ReaderProxyData();
		newRPD->copy(rpd);
		newRPD->m_guid.guidPrefix = pdata->m_guid.guidPrefix;
		newRPD->m_guid.entityId = entId;
		newRPD->m_key = newRPD->m_guid;
		newRPD->m_participantKey = pdata->m_guid;
		if(this->mp_PDP->addReaderProxyData(newRPD,false))
		{
			//CHECK the locators:
			if(newRPD->m_unicastLocatorList.empty())
				newRPD->m_unicastLocatorList = pdata->m_defaultUnicastLocatorList;
			if(newRPD->m_multicastLocatorList.empty())
				newRPD->m_multicastLocatorList = pdata->m_defaultMulticastLocatorList;
			newRPD->m_isAlive = true;
			this->pairReaderProxy(newRPD);
			return true;
		}
	}
	return false;
}

bool EDPStatic::newRemoteWriter(ParticipantProxyData* pdata,uint16_t userId,EntityId_t& entId)
{
	WriterProxyData* wpd = NULL;
	if(m_edpXML.lookforWriter(pdata->m_participantName,userId,&wpd))
	{
		WriterProxyData* newWPD = new WriterProxyData();
		newWPD->copy(wpd);
		newWPD->m_guid.guidPrefix = pdata->m_guid.guidPrefix;
		newWPD->m_guid.entityId = entId;
		newWPD->m_key = newWPD->m_guid;
		newWPD->m_participantKey = pdata->m_guid;
		if(this->mp_PDP->addWriterProxyData(newWPD,false))
		{
			//CHECK the locators:
			if(newWPD->m_unicastLocatorList.empty())
				newWPD->m_unicastLocatorList = pdata->m_defaultUnicastLocatorList;
			if(newWPD->m_multicastLocatorList.empty())
				newWPD->m_multicastLocatorList = pdata->m_defaultMulticastLocatorList;
			newWPD->m_isAlive = true;
			this->pairWriterProxy(newWPD);
			return true;
		}
	}
	return false;
}

} /* namespace rtps */
} /* namespace eprosima */
<commit_msg>EDPStatic fixed small bug<commit_after>/*************************************************************************
 * Copyright (c) 2014 eProsima. All rights reserved.
 *
 * This copy of eProsima RTPS is licensed to you under the terms described in the
 * EPROSIMARTPS_LIBRARY_LICENSE file included in this distribution.
 *
 *************************************************************************/

/**
 * @file EDPStatic.cpp
 *
 */

#include "eprosimartps/builtin/discovery/endpoint/EDPStatic.h"
#include "eprosimartps/builtin/discovery/participant/PDPSimple.h"

#include "eprosimartps/reader/WriterProxyData.h"
#include "eprosimartps/writer/ReaderProxyData.h"

#include "eprosimartps/reader/RTPSReader.h"
#include "eprosimartps/writer/RTPSWriter.h"

#include "eprosimartps/utils/RTPSLog.h"

#include <sstream>

namespace eprosima {
namespace rtps {

EDPStatic::EDPStatic(PDPSimple* p,ParticipantImpl* part):
																																																		EDP(p,part)
{

}

EDPStatic::~EDPStatic()
{

}

bool EDPStatic::initEDP(BuiltinAttributes& attributes)
{
	pInfo(RTPS_B_CYAN<<"Initializing  STATIC EndpointDiscoveryProtocol"<<endl);
	m_attributes = attributes;
	return this->m_edpXML.loadXMLFile(m_attributes.m_staticEndpointXMLFilename);
}

std::pair<std::string,std::string> EDPStaticProperty::toProperty(std::string type,std::string status,uint16_t id,const EntityId_t& ent)
{
	std::pair<std::string,std::string> property;
	std::stringstream ss;
	ss << "eProsimaEDPStatic_"<<type<<"_"<<status<<"_ID_"<<id;
	property.first = ss.str();
	ss.clear();
	ss.str(std::string());
	ss << ent.value[0]<<".";
	ss << ent.value[1]<<".";
	ss << ent.value[2]<<".";
	ss << ent.value[3];
	property.second = ss.str();
	return property;
}

bool EDPStaticProperty::fromProperty(std::pair<std::string,std::string> property)
{
	int pos1 = property.first.find("_");
	str1 = property.first.substr(0,pos1);

	int pos2 = property.first.find("_",pos1+1);
	type = property.first.substr(pos1+1,pos2);

	pos1 = property.first.find("_",pos2+1);
	status = property.first.substr(pos2+1,pos1);

	pos2 = property.first.find("_",pos1+1);
	idstr = property.first.substr(pos1+1,pos2);

	userIDstr = property.first.substr(pos2+1);

	if(str1 == "eProsimaEDPStatic" && idstr == "ID")
	{
		std::stringstream ss;
		ss << userIDstr;
		ss >> userId;
		ss.clear();
		ss.str(std::string());
		ss << property.second;
		int a,b,c,d;
		char ch;
		ss >> a >> ch >> b >> ch >> c >>ch >> d;
		entityId.value[0] = (octet)a;entityId.value[1] = (octet)b;
		entityId.value[2] = (octet)c;entityId.value[3] = (octet)d;
		return true;
	}
	return false;
}

bool EDPStatic::processLocalReaderProxyData(ReaderProxyData* rdata)
{
	//Add the property list entry to our local pdp
	ParticipantProxyData* localpdata = this->mp_PDP->getLocalParticipantProxyData();
	localpdata->m_properties.properties.push_back(EDPStaticProperty::toProperty("Reader","ALIVE",rdata->m_userDefinedId,rdata->m_guid.entityId));
	return true;
}

bool EDPStatic::processLocalWriterProxyData(WriterProxyData* wdata)
{
	//Add the property list entry to our local pdp
	ParticipantProxyData* localpdata = this->mp_PDP->getLocalParticipantProxyData();
	localpdata->m_properties.properties.push_back(EDPStaticProperty::toProperty("Writer","ALIVE",wdata->m_userDefinedId,wdata->m_guid.entityId));
	return true;
}

bool EDPStatic::removeLocalReader(RTPSReader* R)
{
	ParticipantProxyData* localpdata = this->mp_PDP->getLocalParticipantProxyData();
	for(std::vector<std::pair<std::string,std::string>>::iterator pit = localpdata->m_properties.properties.begin();
			pit!=localpdata->m_properties.properties.end();++pit)
	{
		EDPStaticProperty staticproperty;
		if(staticproperty.fromProperty(*pit))
		{
			if(staticproperty.entityId == R->getGuid().entityId)
			{
				*pit = EDPStaticProperty::toProperty("Reader","DEAD",R->getUserDefinedId(),R->getGuid().entityId);
			}
		}
	}
	return false;
}

bool EDPStatic::removeLocalWriter(RTPSWriter*W)
{
	ParticipantProxyData* localpdata = this->mp_PDP->getLocalParticipantProxyData();
	for(std::vector<std::pair<std::string,std::string>>::iterator pit = localpdata->m_properties.properties.begin();
			pit!=localpdata->m_properties.properties.end();++pit)
	{
		EDPStaticProperty staticproperty;
		if(staticproperty.fromProperty(*pit))
		{
			if(staticproperty.entityId == W->getGuid().entityId)
			{
				*pit = EDPStaticProperty::toProperty("Writer","DEAD",W->getUserDefinedId(),W->getGuid().entityId);
			}
		}
	}
	return false;
}

void EDPStatic::assignRemoteEndpoints(ParticipantProxyData* pdata)
{
	for(std::vector<std::pair<std::string,std::string>>::iterator pit = pdata->m_properties.properties.begin();
			pit!=pdata->m_properties.properties.end();++pit)
	{
		EDPStaticProperty staticproperty;
		if(staticproperty.fromProperty(*pit))
		{
			if(staticproperty.type == "Reader" && staticproperty.status=="ALIVE")
			{
				ReaderProxyData* rdata=NULL;
				GUID_t guid(pdata->m_guid.guidPrefix,staticproperty.entityId);
				if(!this->mp_PDP->lookupReaderProxyData(guid,&rdata))//IF NOT FOUND, we CREATE AND PAIR IT
				{
					newRemoteReader(pdata,staticproperty.userId,staticproperty.entityId);
				}
			}
			else if(staticproperty.type == "Writer" && staticproperty.status == "ALIVE")
			{
				WriterProxyData* wdata=NULL;
				GUID_t guid(pdata->m_guid.guidPrefix,staticproperty.entityId);
				if(!this->mp_PDP->lookupWriterProxyData(guid,&wdata))//IF NOT FOUND, we CREATE AND PAIR IT
				{
					newRemoteWriter(pdata,staticproperty.userId,staticproperty.entityId);
				}
			}
			else if(staticproperty.type == "Reader" && staticproperty.status == "DEAD")
			{
				GUID_t guid(pdata->m_guid.guidPrefix,staticproperty.entityId);
				this->removeReaderProxy(guid);
			}
			else if(staticproperty.type == "Writer" && staticproperty.status == "DEAD")
			{
				GUID_t guid(pdata->m_guid.guidPrefix,staticproperty.entityId);
				this->removeWriterProxy(guid);
			}
			else
			{
				pWarning("eProsimaEDPStatic property with type: "<<staticproperty.type << " and status "<<staticproperty.status << " not recognized"<<endl);
			}
		}
	}
}

bool EDPStatic::newRemoteReader(ParticipantProxyData* pdata,uint16_t userId,EntityId_t& entId)
{
	ReaderProxyData* rpd = NULL;
	if(m_edpXML.lookforReader(pdata->m_participantName,userId,&rpd))
	{
		ReaderProxyData* newRPD = new ReaderProxyData();
		newRPD->copy(rpd);
		newRPD->m_guid.guidPrefix = pdata->m_guid.guidPrefix;
		newRPD->m_guid.entityId = entId;
		newRPD->m_key = newRPD->m_guid;
		newRPD->m_participantKey = pdata->m_guid;
		if(this->mp_PDP->addReaderProxyData(newRPD,false))
		{
			//CHECK the locators:
			if(newRPD->m_unicastLocatorList.empty())
				newRPD->m_unicastLocatorList = pdata->m_defaultUnicastLocatorList;
			if(newRPD->m_multicastLocatorList.empty())
				newRPD->m_multicastLocatorList = pdata->m_defaultMulticastLocatorList;
			newRPD->m_isAlive = true;
			this->pairReaderProxy(newRPD);
			return true;
		}
	}
	return false;
}

bool EDPStatic::newRemoteWriter(ParticipantProxyData* pdata,uint16_t userId,EntityId_t& entId)
{
	WriterProxyData* wpd = NULL;
	if(m_edpXML.lookforWriter(pdata->m_participantName,userId,&wpd))
	{
		WriterProxyData* newWPD = new WriterProxyData();
		newWPD->copy(wpd);
		newWPD->m_guid.guidPrefix = pdata->m_guid.guidPrefix;
		newWPD->m_guid.entityId = entId;
		newWPD->m_key = newWPD->m_guid;
		newWPD->m_participantKey = pdata->m_guid;
		if(this->mp_PDP->addWriterProxyData(newWPD,false))
		{
			//CHECK the locators:
			if(newWPD->m_unicastLocatorList.empty())
				newWPD->m_unicastLocatorList = pdata->m_defaultUnicastLocatorList;
			if(newWPD->m_multicastLocatorList.empty())
				newWPD->m_multicastLocatorList = pdata->m_defaultMulticastLocatorList;
			newWPD->m_isAlive = true;
			this->pairWriterProxy(newWPD);
			return true;
		}
	}
	return false;
}

} /* namespace rtps */
} /* namespace eprosima */
<|endoftext|>


<commit_before>#include "workerCL.hpp"

#define __CL_DEFINE_EXCEPTIONS
#include <CL/cl.hpp>

#include <vector>
#include <string>
#include <iostream>

#include "log.hpp"
#include "reads.hpp"

using namespace std;

WorkerCL::WorkerCL(size_t platform_id, size_t device_id){
	/* GPU environment preparation */

	//Get platforms (drivers) list and keep the one to be use
	vector<cl::Platform> all_platforms;
	cl::Platform::get(&all_platforms);
	if(!all_platforms.size()){
		//No platform ? Send error
		string error = "OPENCL: no platforms found.";
		throw(error);
	}
	m_platform = all_platforms[platform_id];

	//Get devices list and keep the one to use
	vector<cl::Device> devices;
	m_platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
	if(device_id >= devices.size()){
		string error = "OPENCL: no device of id "+to_string(device_id)+
			" on platform "+to_string(platform_id)+" ("+to_string(devices.size())+" devices)";
		throw(error);
	}
	m_device = devices[device_id];

	//Create context
	m_context = cl::Context({m_device});

	//initialize commands queue
	m_commandqueue = cl::CommandQueue(m_context, m_device);

	//Build kernel sources
	m_program = cl::Program(m_context, kernel_cmp_2_contigs);
	if(m_program.build({m_device}) != CL_SUCCESS){
		string error = "Error building: ";
		error += m_program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(m_device);
		throw(error);
	}

	//Make the kernel
	m_kernel = cl::Kernel(m_program, "cmp_2_contigs");

}

WorkerCL::~WorkerCL(){
}

void WorkerCL::run(Contigs contigs){
	/*
	Create the string containing all contigs sequences
	and store the list of contigs size (in same orders)
	to be able to retrieve contigs. Size is store in
	an uint64_t (ulong) to be sure it is 64bits as cl_ulong
	*/

	//Get list of contigs size and the total length of the
	//contigs concatenation
	uint64_t nbContigs = contigs.get_nbContigs();
	uint64_t ultraSequenceSize = 0;
	vector<uint64_t> contigs_size (nbContigs, 0);
	for(uint64_t i=0; i < nbContigs; i++){
		contigs_size[i] = contigs.get_sizeContig(i);
		ultraSequenceSize += contigs_size[i];
	}

	//Create the ultraSequence
	char* ultraSequence = new char[ultraSequenceSize];
	uint64_t i = 0;
		//Get each contigs sequence and add it in ultraSequence
	for(uint64_t c=0; c < nbContigs; c++){
		string seq = contigs.get_seqContig(c);
		for(size_t j=0; j < seq.size();j++){
			ultraSequence[i] = seq[j];
			i++;
		}
	}
	cout << "UltraSequence:" << endl;
	cout << ultraSequence << endl;

	//Prepare GPU for the run
	cl::Event ev;
		//infos buffer (64bits): nbcontigs
		//buffer only accepts non-dynamics arrays (even of size 1)
	uint64_t infos[1] = {ultraSequenceSize};
	cl::Buffer buf_infos (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t));
	m_commandqueue.enqueueWriteBuffer(buf_infos, CL_TRUE, 0, sizeof(uint64_t), infos);

	//Update the kernel (gpu function)
	m_kernel.setArg(0, buf_infos);

	//Run the kernel and wait the end
	m_commandqueue.enqueueNDRangeKernel(m_kernel,cl::NullRange, cl::NullRange, cl::NullRange, NULL, &ev);
	ev.wait();

	//Clean the memory
	delete ultraSequence;

}

void WorkerCL::list_infos(Log& output){
	string txt;

	//Get platforms
	txt = "\n\t[Platforms list]";
	output.write(txt);
	vector<cl::Platform> platforms;
	cl::Platform::get(&platforms);
	if(!platforms.size()){
		txt = "No platform detected";
		output.write(txt);
		return;
	}
	txt = "platform_id\tplatform_name\tplatform_profile\tplatform_vendor\tplatform_version";
	output.write(txt);
	for(size_t i=0; i < platforms.size(); i++){
		cl::Platform& p = platforms[i];

		txt += "\t" + p.getInfo<CL_PLATFORM_NAME>();
		txt += "\t" + p.getInfo<CL_PLATFORM_PROFILE>();
		txt += "\t" + p.getInfo<CL_PLATFORM_VENDOR>();
		txt += "\t" + p.getInfo<CL_PLATFORM_VERSION>();
		//txt += "\t" + p.getInfo<CL_PLATFORM_EXTENSIONS>();
		output.write(txt);
	}

	//Get devices
	txt = "\n\t[Devices list]";
	output.write(txt);
	txt = "platform_id\tdevice_id\tdevice_name\tdevice_vendor\tdevice_profile\tdevice_version\tdriver_version\topencl_c_version";
	output.write(txt);
	for(size_t p = 0; p < platforms.size(); p++){
		vector<cl::Device> devices;
		platforms[p].getDevices(CL_DEVICE_TYPE_ALL, &devices);
		for(size_t d = 0; d < devices.size(); d++){
			cl::Device& device = devices[d];
			txt = to_string(p)+"\t"+to_string(d);
			txt += "\t" + device.getInfo<CL_DEVICE_NAME>();
			txt += "\t" + device.getInfo<CL_DEVICE_VENDOR>();
			txt += "\t" + device.getInfo<CL_DEVICE_PROFILE>();
			txt += "\t" + device.getInfo<CL_DEVICE_VERSION>();
			txt += "\t" + device.getInfo<CL_DRIVER_VERSION>();
			txt += "\t" + device.getInfo<CL_DEVICE_OPENCL_C_VERSION>();
			output.write(txt);
		}
	}
}

/*
Les balises 'R"CLCODE(' et ')CLCODE'   (du type R"NAME( ... )NAME") servent à définir un
string litéral brut. C'est utile pour avoir un string sur plusieurs ligne, comme un code,
et cela évite d'avoir à ouvrir puis fermer les guillemets à chaque ligne.
*/

string WorkerCL::kernel_cmp_2_contigs = R"CLCODE(
	kernel void cmp_2_contigs(){
		int i = 0;
	}
)CLCODE";
<commit_msg>Ajout du buffer de la taille des contigs et du gid (NBRange)<commit_after>#include "workerCL.hpp"

#define __CL_DEFINE_EXCEPTIONS
#include <CL/cl.hpp>

#include <vector>
#include <string>
#include <iostream>

#include "log.hpp"
#include "reads.hpp"

using namespace std;

WorkerCL::WorkerCL(size_t platform_id, size_t device_id){
	/* GPU environment preparation */

	//Get platforms (drivers) list and keep the one to be use
	vector<cl::Platform> all_platforms;
	cl::Platform::get(&all_platforms);
	if(!all_platforms.size()){
		//No platform ? Send error
		string error = "OPENCL: no platforms found.";
		throw(error);
	}
	m_platform = all_platforms[platform_id];

	//Get devices list and keep the one to use
	vector<cl::Device> devices;
	m_platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
	if(device_id >= devices.size()){
		string error = "OPENCL: no device of id "+to_string(device_id)+
			" on platform "+to_string(platform_id)+" ("+to_string(devices.size())+" devices)";
		throw(error);
	}
	m_device = devices[device_id];

	//Create context
	m_context = cl::Context({m_device});

	//initialize commands queue
	m_commandqueue = cl::CommandQueue(m_context, m_device);

	//Build kernel sources
	m_program = cl::Program(m_context, kernel_cmp_2_contigs);
	if(m_program.build({m_device}) != CL_SUCCESS){
		string error = "Error building: ";
		error += m_program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(m_device);
		throw(error);
	}

	//Make the kernel
	m_kernel = cl::Kernel(m_program, "cmp_2_contigs");

}

WorkerCL::~WorkerCL(){
}

void WorkerCL::run(Contigs contigs){
	/*
	Create the string containing all contigs sequences
	and store the list of contigs size (in same orders)
	to be able to retrieve contigs. Size is store in
	an uint64_t (ulong) to be sure it is 64bits as cl_ulong
	*/

	//Get list of contigs size and the total length of the
	//contigs concatenation
	uint64_t nbContigs = contigs.get_nbContigs();
	uint64_t ultraSequenceSize = 0;
	vector<uint64_t> contigs_size (nbContigs, 0);
	for(uint64_t i=0; i < nbContigs; i++){
		contigs_size[i] = contigs.get_sizeContig(i);
		ultraSequenceSize += contigs_size[i];
	}

	//Create the ultraSequence
	char* ultraSequence = new char[ultraSequenceSize];
	uint64_t i = 0;
		//Get each contigs sequence and add it in ultraSequence
	for(uint64_t c=0; c < nbContigs; c++){
		string seq = contigs.get_seqContig(c);
		for(size_t j=0; j < seq.size();j++){
			ultraSequence[i] = seq[j];
			i++;
		}
	}
	cout << "UltraSequence:" << endl;
	cout << ultraSequence << endl;

	//Prepare GPU for the run
	cl::Event ev;
		//infos buffer (64bits): nbcontigs
		//buffer only accepts non-dynamics arrays (even of size 1)
	uint64_t infos[1] = {ultraSequenceSize};
	cl::Buffer buf_infos (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t));
	m_commandqueue.enqueueWriteBuffer(buf_infos, CL_TRUE, 0, sizeof(uint64_t), &infos);
		//sequences sizes (array of 64bits) buffer
	cl::Buffer buf_sizes (m_context, CL_ME_READ_ONLY, sizeof(uint64_t)*nbContigs);
	m_commandqueue.enqueueWriteBuffer(buf_sizes, CL_TRUE, 0, sizeof(uint64_t)*nbContigs, &contigs_size[0]);

	//Update the kernel (gpu function)
	m_kernel.setArg(0, buf_infos);

	//Run the kernel and wait the end
	m_commandqueue.enqueueNDRangeKernel(m_kernel,cl::NullRange, cl::NDRange::NDRange(nbContigs, nbContigs), cl::NullRange, NULL, &ev);
	ev.wait();

	//Clean the memory
	delete ultraSequence;

}

void WorkerCL::list_infos(Log& output){
	string txt;

	//Get platforms
	txt = "\n\t[Platforms list]";
	output.write(txt);
	vector<cl::Platform> platforms;
	cl::Platform::get(&platforms);
	if(!platforms.size()){
		txt = "No platform detected";
		output.write(txt);
		return;
	}
	txt = "platform_id\tplatform_name\tplatform_profile\tplatform_vendor\tplatform_version";
	output.write(txt);
	for(size_t i=0; i < platforms.size(); i++){
		cl::Platform& p = platforms[i];

		txt += "\t" + p.getInfo<CL_PLATFORM_NAME>();
		txt += "\t" + p.getInfo<CL_PLATFORM_PROFILE>();
		txt += "\t" + p.getInfo<CL_PLATFORM_VENDOR>();
		txt += "\t" + p.getInfo<CL_PLATFORM_VERSION>();
		//txt += "\t" + p.getInfo<CL_PLATFORM_EXTENSIONS>();
		output.write(txt);
	}

	//Get devices
	txt = "\n\t[Devices list]";
	output.write(txt);
	txt = "platform_id\tdevice_id\tdevice_name\tdevice_vendor\tdevice_profile\tdevice_version\tdriver_version\topencl_c_version";
	output.write(txt);
	for(size_t p = 0; p < platforms.size(); p++){
		vector<cl::Device> devices;
		platforms[p].getDevices(CL_DEVICE_TYPE_ALL, &devices);
		for(size_t d = 0; d < devices.size(); d++){
			cl::Device& device = devices[d];
			txt = to_string(p)+"\t"+to_string(d);
			txt += "\t" + device.getInfo<CL_DEVICE_NAME>();
			txt += "\t" + device.getInfo<CL_DEVICE_VENDOR>();
			txt += "\t" + device.getInfo<CL_DEVICE_PROFILE>();
			txt += "\t" + device.getInfo<CL_DEVICE_VERSION>();
			txt += "\t" + device.getInfo<CL_DRIVER_VERSION>();
			txt += "\t" + device.getInfo<CL_DEVICE_OPENCL_C_VERSION>();
			output.write(txt);
		}
	}
}

/*
Les balises 'R"CLCODE(' et ')CLCODE'   (du type R"NAME( ... )NAME") servent à définir un
string litéral brut. C'est utile pour avoir un string sur plusieurs ligne, comme un code,
et cela évite d'avoir à ouvrir puis fermer les guillemets à chaque ligne.
*/

string WorkerCL::kernel_cmp_2_contigs = R"CLCODE(
	kernel void cmp_2_contigs(){
		int i = 0;
	}
)CLCODE";
<|endoftext|>


<commit_before>#include "StarControl.h"
#include "ObjectParticles.h"
#include "Engine.h"
#include "Game.h"
#include "Object.h"
#include "Player.h"
#include "Common.h"
#include "App.h"

CStarControl::CStarControl(void)
{
	m_pStarNormal = NULL;
	m_pStarClick = NULL;
	m_fViewDistance = 0.5f;
	m_nClickState = 0;
	m_fClickScale = 1.0f;
	Init();
}

CStarControl::~CStarControl(void)
{
	g_Engine.pGame->RemoveNode(m_pStarNormal);
	g_Engine.pGame->RemoveNode(m_pStarClick);
}

int CStarControl::Init()
{
	return Load("data/StarControl/Star_mesh.node", "data/StarControl/Star_click.node");
}

void CStarControl::Update(const vec3& vPos, const vec3& vDir)
{
	m_fClickScale += m_nClickState * g_Engine.pGame->GetIFps() * 5.5f;
	if (m_fClickScale <= 0.8f)
	{
		m_nClickState = 1;
	}
	else if (m_fClickScale >= 1.0f)
	{
		m_fClickScale = 1.0f;
		m_nClickState = 0;
	}

}
<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "StarControl.h"
#include "ObjectParticles.h"
#include "Engine.h"
#include "Game.h"
#include "Object.h"
#include "Player.h"
#include "Common.h"
#include "App.h"

CStarControl::CStarControl(void)
{
	m_pStarNormal = NULL;
	m_pStarClick = NULL;
	m_fViewDistance = 0.5f;
	m_nClickState = 0;
	m_fClickScale = 1.0f;
	Init();
}

CStarControl::~CStarControl(void)
{
	g_Engine.pGame->RemoveNode(m_pStarNormal);
	g_Engine.pGame->RemoveNode(m_pStarClick);
}

int CStarControl::Init()
{
	return Load("data/StarControl/Star_mesh.node", "data/StarControl/Star_click.node");
}

void CStarControl::Update(const vec3& vPos, const vec3& vDir)
{
	m_fClickScale += m_nClickState * g_Engine.pGame->GetIFps() * 5.5f;
	if (m_fClickScale <= 0.8f)
	{
		m_nClickState = 1;
	}
	else if (m_fClickScale >= 1.0f)
	{
		m_fClickScale = 1.0f;
		m_nClickState = 0;
	}
	float fViewDistance = m_fViewDistance;
	mat4 matStar = Translate(vPos + vDir * fViewDistance);
	CPlayer* pPlayer = g_Engine.pGame->GetPlayer();
}
<|endoftext|>


<commit_before>#include "includes/SuperImposer.hpp"
#include "includes/dcd/DCDManager.hpp"
#include "includes/pdb/CGReader.hpp"
using namespace coffeemill;

SnapShot pickup_chain(const SnapShot& ss,
                      const std::vector<int>& chain_ids,
                      const std::vector<int>& chain_sizes);

int main(int argc, char *argv[])
{
    if(!(argc == 2 || argc == 3))
    {
        std::cout << "Coffee-mill DCD SuperImposer" << std::endl;
        std::cout << "Usage: ./superimpose <filename>.dcd [ChainIDs]"
                  << std::endl;
        std::cout << "Usage: option [chainIDs] enables if there are "
                  << "CG style pdb file having same name as dcd file"
                  << std::endl;
        std::cout << "Info : SuperImposer outputs dcd file "
                  << "containing superimposed structure" << std::endl;
        return 1;
    }

    std::string infile(argv[1]);
    DCDReader reader(infile);
    reader.read_file();

    std::vector<int> chain_nums;
    std::vector<int> chain_sizes;
    if(argc == 3)
    {
        std::string chainIDs = argv[2];
        std::transform(chainIDs.cbegin(), chainIDs.cend(),
                       chainIDs.begin(), toupper);
        std::string cgpdb(infile.substr(0, infile.size()-3) + "pdb");
        CGReader cgreader(cgpdb);
        cgreader.read_file();
        CGMdlSptr model(cgreader.get_model(0));

        for(int i(0); i < model->size(); ++i)
            chain_sizes.push_back(model->at(i)->get_size());

        for(auto iter = chainIDs.begin(); iter != chainIDs.end(); ++iter)
            chain_nums.push_back(model->find_id(*iter));
    }

    std::vector<SnapShot> data(reader.get_all_data());
    std::vector<SnapShot> imposed(data.size());

    SuperImposer simposer;

    if(argc == 2)
    {
        simposer.set_data(data.at(1), data.at(0));
        simposer.superimpose();
        imposed.at(0) = simposer.get_data2();
    }
    else if(argc == 3)
    {
        SnapShot data0(pickup_chain(data.at(0), chain_nums, chain_sizes));
        SnapShot data1(pickup_chain(data.at(1), chain_nums, chain_sizes));
        simposer.set_data(data1, data0);
        Matrix3 R(simposer.get_R());

        SnapShot data1_rot(data.at(1));
        for(SnapShot::iterator iter = data1_rot.begin();
            iter != data1_rot.end(); ++iter)
        {
            Realvec temp(R * (*iter));
            *iter = temp;
        }
        imposed.at(0) = data.at(0);
        imposed.at(1) = data1_rot;
    }

    for(size_t i(2); i<data.size(); ++i)
    {
        if(argc == 2)
        {
            simposer.set_data_push(data.at(i));
            simposer.superimpose();
            imposed.at(i-1) = simposer.get_data2();
        }
        else if(argc == 3)
        {
            SnapShot datai(pickup_chain(data.at(i), chain_nums, chain_sizes));
            simposer.set_data_push(datai);
            Matrix3 R(simposer.get_R());

            SnapShot data_rot(data.at(i));
            for(SnapShot::iterator iter = data_rot.begin();
                iter != data_rot.end(); ++iter)
            {
                Realvec temp(R * (*iter));
                *iter = temp;
            }
            imposed.at(i) = data_rot;
        }
    }
    if(argc == 2)
        imposed.at(data.size()-1) = simposer.get_data1();

    std::string outfile("SupImp"+infile);
    DCDWriter writer(outfile);

    set_header_from_reader(&writer, &reader);
    writer.set_all_data(imposed);

    writer.write_file();

    return 0;
}

SnapShot pickup_chain(const SnapShot& ss,
                                 const std::vector<int>& chain_ids,
                                 const std::vector<int>& chain_sizes)
{
    SnapShot retval(ss);

    SnapShot::iterator ssiter = retval.begin();

    for(size_t i(0); i<chain_sizes.size(); ++i)
    {
        if(std::find(chain_ids.begin(), chain_ids.end(), i) != chain_ids.end())
        {
            ssiter = ssiter + chain_sizes.at(i);
        }
        else
        {
            retval.erase(ssiter, ssiter + chain_sizes.at(i));
        }
    }

    return retval;
}
//(c)Toru Niina 2015 all rights reserved.
<commit_msg>fix SuperImposer with specification of chains: zeroing<commit_after>#include "includes/SuperImposer.hpp"
#include "includes/dcd/DCDManager.hpp"
#include "includes/pdb/CGReader.hpp"
using namespace coffeemill;

SnapShot pickup_chain(const SnapShot& ss,
                      const std::vector<int>& chain_ids,
                      const std::vector<int>& chain_sizes);

int main(int argc, char *argv[])
{
    if(!(argc == 2 || argc == 3))
    {
        std::cout << "Coffee-mill DCD SuperImposer" << std::endl;
        std::cout << "Usage: ./superimpose <filename>.dcd [ChainIDs]"
                  << std::endl;
        std::cout << "Usage: option [chainIDs] enables if there are "
                  << "CG style pdb file having same name as dcd file"
                  << std::endl;
        std::cout << "Info : SuperImposer outputs dcd file "
                  << "containing superimposed structure" << std::endl;
        return 1;
    }

    std::string infile(argv[1]);
    DCDReader reader(infile);
    reader.read_file();

    std::vector<int> chain_nums;
    std::vector<int> chain_sizes;
    if(argc == 3)
    {
        std::string chainIDs = argv[2];
        std::transform(chainIDs.cbegin(), chainIDs.cend(),
                       chainIDs.begin(), toupper);
        std::string cgpdb(infile.substr(0, infile.size()-3) + "pdb");
        CGReader cgreader(cgpdb);
        cgreader.read_file();
        CGMdlSptr model(cgreader.get_model(0));

        for(int i(0); i < model->size(); ++i)
            chain_sizes.push_back(model->at(i)->get_size());

        for(auto iter = chainIDs.begin(); iter != chainIDs.end(); ++iter)
            chain_nums.push_back(model->find_id(*iter));
    }

    std::vector<SnapShot> data(reader.get_all_data());
    std::vector<SnapShot> imposed(data.size());

    SuperImposer simposer;

    if(argc == 2)
    {
        simposer.set_data(data.at(1), data.at(0));
        simposer.superimpose();
        imposed.at(0) = simposer.get_data2();
    }
    else if(argc == 3)
    {
        SnapShot data0(pickup_chain(data.at(0), chain_nums, chain_sizes));
        SnapShot data1(pickup_chain(data.at(1), chain_nums, chain_sizes));
        simposer.set_data(data1, data0);
        Matrix3 R(simposer.get_R());

        SnapShot data0_rot(data.at(0));
        SnapShot data1_rot(data.at(1));

        Realvec sum0(0e0, 0e0, 0e0);
        Realvec sum1(0e0, 0e0, 0e0);
        SnapShot::iterator iter0 = data0_rot.begin();
        for(SnapShot::iterator iter = data1_rot.begin();
            iter != data1_rot.end(); ++iter)
        {
            sum0 += (*iter0);
            sum1 += (*iter);
            ++iter0;
        }
        sum0 /= static_cast<double>(data0_rot.size());
        sum1 /= static_cast<double>(data1_rot.size());
        iter0 = data0_rot.begin();
        for(SnapShot::iterator iter = data1_rot.begin();
            iter != data1_rot.end(); ++iter)
        {
            *iter0 -= sum0;
            *iter -= sum1;
            ++iter0;
        }

        for(SnapShot::iterator iter = data1_rot.begin();
            iter != data1_rot.end(); ++iter)
        {
            Realvec temp(R * (*iter));
            *iter = temp;
        }
        imposed.at(0) = data0_rot;
        imposed.at(1) = data1_rot;
    }

    for(size_t i(2); i<data.size(); ++i)
    {
        if(argc == 2)
        {
            simposer.set_data_push(data.at(i));
            simposer.superimpose();
            imposed.at(i-1) = simposer.get_data2();
        }
        else if(argc == 3)
        {
            SnapShot datai(pickup_chain(data.at(i), chain_nums, chain_sizes));
            simposer.set_data_push(datai);
            Matrix3 R(simposer.get_R());

            SnapShot data_rot(data.at(i));

            Realvec sum(0e0, 0e0, 0e0);
            for(SnapShot::iterator iter = data_rot.begin();
                iter != data_rot.end(); ++iter)
            {
                sum += *iter;
            }
            sum /= static_cast<double>(data_rot.size());

            for(SnapShot::iterator iter = data_rot.begin();
                iter != data_rot.end(); ++iter)
            {
                *iter -= sum;
            }

            for(SnapShot::iterator iter = data_rot.begin();
                iter != data_rot.end(); ++iter)
            {
                Realvec temp(R * (*iter));
                *iter = temp;
            }
            imposed.at(i) = data_rot;
        }
    }
    if(argc == 2)
        imposed.at(data.size()-1) = simposer.get_data1();

    std::string outfile("SupImp"+infile);
    DCDWriter writer(outfile);

    set_header_from_reader(&writer, &reader);
    writer.set_all_data(imposed);

    writer.write_file();

    return 0;
}

SnapShot pickup_chain(const SnapShot& ss,
                                 const std::vector<int>& chain_ids,
                                 const std::vector<int>& chain_sizes)
{
    SnapShot retval(ss);

    SnapShot::iterator ssiter = retval.begin();

    for(size_t i(0); i<chain_sizes.size(); ++i)
    {
        if(std::find(chain_ids.begin(), chain_ids.end(), i) != chain_ids.end())
        {
            ssiter = ssiter + chain_sizes.at(i);
        }
        else
        {
            retval.erase(ssiter, ssiter + chain_sizes.at(i));
        }
    }

    return retval;
}
//(c)Toru Niina 2015 all rights reserved.
<|endoftext|>


<commit_before><commit_msg>Make test_clearEecache nondestructive<commit_after><|endoftext|>


<commit_before>#pragma once
#ifndef ARRAYDELEGATE_HPP
# define ARRAYDELEGATE_HPP

#include <cassert>

#include <cstddef>

#include <memory>

#include <new>

#include <type_traits>

#include <utility>

namespace detail
{
  struct holder
  {
    virtual ~holder() { }

    virtual void* get(void*) = 0;

    virtual void clone(void*) = 0;
    virtual void move(void*) = 0;
  };

  template <typename T>
  struct any_store : holder
  {
    template <typename U>
    any_store(U&& t) : held(::std::forward<U>(t)) { }

    void* get(void* const) override { return &held; }

    void clone(void* const dst) override
    {
      new (dst) any_store<T>(held);
    }

    void move(void* const dst) override
    {
      new (dst) any_store<T>(::std::move(held));
    }

  private:
    T held;
  };

  template <>
  struct any_store<::std::nullptr_t> : holder
  {
    void* get(void* const p) override { return p; }

    void clone(void* const dst) override
    {
      new (dst) any_store<::std::nullptr_t>();
    }

    void move(void* const dst) override
    {
      new (dst) any_store<::std::nullptr_t>();
    }
  };
}

template <typename T> class delegate;

template<class R, class ...A>
class delegate<R (A...)>
{
  static constexpr auto max_store_size = 10 * sizeof(::std::size_t);

  using stub_ptr_type = R (*)(void*, A&&...);

  delegate(void* const o, stub_ptr_type const m) noexcept
    : object_ptr_(o),
      stub_ptr_(m)
  {
  }

public:
  delegate() = default;

  delegate(delegate const& other) { *this = other; }

  delegate(delegate&& other) { *this = ::std::move(other); }

  delegate(::std::nullptr_t const) noexcept : delegate() { }

  template <class C>
  explicit delegate(C const* const o) noexcept
    : object_ptr_(const_cast<C*>(o))
  {
  }

  template <class C>
  explicit delegate(C const& o) noexcept
    : object_ptr_(const_cast<C*>(&o))
  {
  }

  delegate(R (* const function_ptr)(A...))
  {
    *this = from(function_ptr);
  }

  template <class C>
  delegate(C* const object_ptr, R (C::* const method_ptr)(A...))
  {
    *this = from(object_ptr, method_ptr);
  }

  template <class C>
  delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)
  {
    *this = from(object_ptr, method_ptr);
  }

  template <class C>
  delegate(C& object, R (C::* const method_ptr)(A...))
  {
    *this = from(object, method_ptr);
  }

  template <class C>
  delegate(C const& object, R (C::* const method_ptr)(A...) const)
  {
    *this = from(object, method_ptr);
  }

  template <
    typename T,
    typename = typename ::std::enable_if<
      !::std::is_same<delegate, typename ::std::decay<T>::type>{}
    >::type
  >
  delegate(T&& f)
  {
    using functor_type = typename ::std::decay<T>::type;

    static_assert(sizeof(T) <= sizeof(store_), "increase store_ size");
    holder_ = new (store_) ::detail::any_store<functor_type>(
      ::std::forward<T>(f));

    object_ptr_ = holder_->get(store_);
    stub_ptr_ = functor_stub<functor_type>;
  }

  ~delegate() { holder_->::detail::holder::~holder(); }

  delegate& operator=(delegate const& rhs)
  {
    holder_->::detail::holder::~holder();
    rhs.holder_->clone(store_);

    object_ptr_ = holder_->get(rhs.object_ptr_);
    stub_ptr_ = rhs.stub_ptr_;

    return *this;
  }

  delegate& operator=(delegate&& rhs)
  {
    holder_->::detail::holder::~holder();
    rhs.holder_->move(store_);

    object_ptr_ = holder_->get(rhs.object_ptr_);
    stub_ptr_ = rhs.stub_ptr_;

    return *this;
  }

  delegate& operator=(R (* const rhs)(A...))
  {
    return *this = from(rhs);
  }

  template <class C>
  delegate& operator=(R (C::* const rhs)(A...))
  {
    return *this = from(static_cast<C*>(object_ptr_), rhs);
  }

  template <class C>
  delegate& operator=(R (C::* const rhs)(A...) const)
  {
    return *this = from(static_cast<C const*>(object_ptr_), rhs);
  }

  template <
    typename T,
    typename = typename ::std::enable_if<
      !::std::is_same<delegate, typename ::std::decay<T>::type>{}
    >::type
  >
  delegate& operator=(T&& f)
  {
    using functor_type = typename ::std::decay<T>::type;

    holder_->::detail::holder::~holder();

    static_assert(sizeof(T) <= sizeof(store_), "increase store_ size");
    holder_ = new (store_) ::detail::any_store<functor_type>(
      ::std::forward<T>(f));

    object_ptr_ = holder_->get(store_);
    stub_ptr_ = functor_stub<functor_type>;

    return *this;
  }

  template <R (* const function_ptr)(A...)>
  static delegate from() noexcept
  {
    return { nullptr, function_stub<function_ptr> };
  }

  template <class C, R (C::* const method_ptr)(A...)>
  static delegate from(C* const object_ptr) noexcept
  {
    return { object_ptr, method_stub<C, method_ptr> };
  }

  template <class C, R (C::* const method_ptr)(A...) const>
  static delegate from(C const* const object_ptr) noexcept
  {
    return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };
  }

  template <class C, R (C::* const method_ptr)(A...)>
  static delegate from(C& object) noexcept
  {
    return { &object, method_stub<C, method_ptr> };
  }

  template <class C, R (C::* const method_ptr)(A...) const>
  static delegate from(C const& object) noexcept
  {
    return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };
  }

  template <typename T>
  static delegate from(T&& f)
  {
    return ::std::forward<T>(f);
  }

  static delegate from(R (* const function_ptr)(A...))
  {
    return [function_ptr](A&&... args) {
      return (*function_ptr)(::std::forward<A>(args)...); };
  }

  template <class C>
  static delegate from(C* const object_ptr,
    R (C::* const method_ptr)(A...))
  {
    return [object_ptr, method_ptr](A&&... args) {
      return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
  }

  template <class C>
  static delegate from(C const* const object_ptr,
    R (C::* const method_ptr)(A...) const)
  {
    return [object_ptr, method_ptr](A&&... args) {
      return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
  }

  template <class C>
  static delegate from(C& object, R (C::* const method_ptr)(A...))
  {
    return [&object, method_ptr](A&&... args) {
      return (object.*method_ptr)(::std::forward<A>(args)...); };
  }

  template <class C>
  static delegate from(C const& object,
    R (C::* const method_ptr)(A...) const)
  {
    return [&object, method_ptr](A&&... args) {
      return (object.*method_ptr)(::std::forward<A>(args)...); };
  }

  void reset() { stub_ptr_ = nullptr; }

  void reset_stub() noexcept { stub_ptr_ = nullptr; }

  void swap(delegate& other) noexcept { ::std::swap(*this, other); }

  bool operator==(delegate const& rhs) const noexcept
  {
    return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);
  }

  bool operator!=(delegate const& rhs) const noexcept
  {
    return !operator==(rhs);
  }

  bool operator<(delegate const& rhs) const noexcept
  {
    return (object_ptr_ < rhs.object_ptr_) ||
      ((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));
  }

  bool operator==(::std::nullptr_t const) const noexcept
  {
    return !stub_ptr_;
  }

  bool operator!=(::std::nullptr_t const) const noexcept
  {
    return stub_ptr_;
  }

  explicit operator bool() const noexcept { return stub_ptr_; }

  R operator()(A... args) const
  {
//  assert(stub_ptr);
    return stub_ptr_(object_ptr_, ::std::forward<A>(args)...);
  }

private:
  friend class ::std::hash<delegate>;

  void* object_ptr_;
  stub_ptr_type stub_ptr_{};

  alignas(::max_align_t) char store_[max_store_size];

  ::detail::holder* holder_{new (store_) ::detail::any_store<::std::nullptr_t>};

  template <R (*function_ptr)(A...)>
  static R function_stub(void* const, A&&... args)
  {
    return function_ptr(::std::forward<A>(args)...);
  }

  template <class C, R (C::*method_ptr)(A...)>
  static R method_stub(void* const object_ptr, A&&... args)
  {
    return (static_cast<C*>(object_ptr)->*method_ptr)(
      ::std::forward<A>(args)...);
  }

  template <class C, R (C::*method_ptr)(A...) const>
  static R const_method_stub(void* const object_ptr, A&&... args)
  {
    return (static_cast<C const*>(object_ptr)->*method_ptr)(
      ::std::forward<A>(args)...);
  }

  template <typename T>
  static R functor_stub(void* const object_ptr, A&&... args)
  {
    return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...);
  }
};

namespace std
{
  template <typename R, typename ...A>
  struct hash<delegate<R (A...)> >
  {
    size_t operator()(delegate<R (A...)> const& d) const noexcept
    {
      auto const seed(hash<void*>()(d.object_ptr_));

      return hash<typename delegate<R (A...)>::stub_ptr_type>()(
        d.stub_ptr_) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
    }
  };
}

#endif // ARRAYDELEGATE_HPP
<commit_msg>some fixes<commit_after>#pragma once
#ifndef ARRAYDELEGATE_HPP
# define ARRAYDELEGATE_HPP

#include <cassert>

#include <cstddef>

#include <memory>

#include <new>

#include <type_traits>

#include <utility>

namespace detail
{
  struct holder
  {
    virtual ~holder() { }

    virtual void* get(void*) = 0;

    virtual void clone(void*) = 0;
    virtual void move(void*) = 0;
  };

  template <typename T>
  struct any_store : holder
  {
    template <typename U>
    any_store(U&& t) : held(::std::forward<U>(t)) { }

    void* get(void* const) override { return &held; }

    void clone(void* const dst) override
    {
      new (dst) any_store<T>(held);
    }

    void move(void* const dst) override
    {
      new (dst) any_store<T>(::std::move(held));
    }

  private:
    T held;
  };

  template <>
  struct any_store<::std::nullptr_t> : holder
  {
    void* get(void* const p) override { return p; }

    void clone(void* const dst) override
    {
      new (dst) any_store<::std::nullptr_t>;
    }

    void move(void* const dst) override
    {
      new (dst) any_store<::std::nullptr_t>;
    }
  };
}

template <typename T> class delegate;

template<class R, class ...A>
class delegate<R (A...)>
{
  static constexpr auto max_store_size = 10 * sizeof(::std::size_t);

  using stub_ptr_type = R (*)(void*, A&&...);

  delegate(void* const o, stub_ptr_type const m) noexcept
    : object_ptr_(o),
      stub_ptr_(m)
  {
  }

public:
  delegate() = default;

  delegate(delegate const& other) { *this = other; }

  delegate(delegate&& other) { *this = ::std::move(other); }

  delegate(::std::nullptr_t const) noexcept : delegate() { }

  template <class C>
  explicit delegate(C const* const o) noexcept
    : object_ptr_(const_cast<C*>(o))
  {
  }

  template <class C>
  explicit delegate(C const& o) noexcept
    : object_ptr_(const_cast<C*>(&o))
  {
  }

  delegate(R (* const function_ptr)(A...))
  {
    *this = from(function_ptr);
  }

  template <class C>
  delegate(C* const object_ptr, R (C::* const method_ptr)(A...))
  {
    *this = from(object_ptr, method_ptr);
  }

  template <class C>
  delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)
  {
    *this = from(object_ptr, method_ptr);
  }

  template <class C>
  delegate(C& object, R (C::* const method_ptr)(A...))
  {
    *this = from(object, method_ptr);
  }

  template <class C>
  delegate(C const& object, R (C::* const method_ptr)(A...) const)
  {
    *this = from(object, method_ptr);
  }

  template <
    typename T,
    typename = typename ::std::enable_if<
      !::std::is_same<delegate, typename ::std::decay<T>::type>{}
    >::type
  >
  delegate(T&& f)
  {
    using functor_type = typename ::std::decay<T>::type;

    static_assert(sizeof(T) <= sizeof(store_), "increase store_ size");
    holder_ = new (store_) ::detail::any_store<functor_type>(
      ::std::forward<T>(f));

    object_ptr_ = holder_->get(store_);
    stub_ptr_ = functor_stub<functor_type>;
  }

  ~delegate() { holder_->::detail::holder::~holder(); }

  delegate& operator=(delegate const& rhs)
  {
    holder_->::detail::holder::~holder();
    rhs.holder_->clone(store_);

    object_ptr_ = holder_->get(rhs.object_ptr_);
    stub_ptr_ = rhs.stub_ptr_;

    return *this;
  }

  delegate& operator=(delegate&& rhs)
  {
    holder_->::detail::holder::~holder();
    rhs.holder_->move(store_);

    object_ptr_ = holder_->get(rhs.object_ptr_);
    stub_ptr_ = rhs.stub_ptr_;

    return *this;
  }

  delegate& operator=(R (* const rhs)(A...))
  {
    return *this = from(rhs);
  }

  template <class C>
  delegate& operator=(R (C::* const rhs)(A...))
  {
    return *this = from(static_cast<C*>(object_ptr_), rhs);
  }

  template <class C>
  delegate& operator=(R (C::* const rhs)(A...) const)
  {
    return *this = from(static_cast<C const*>(object_ptr_), rhs);
  }

  template <
    typename T,
    typename = typename ::std::enable_if<
      !::std::is_same<delegate, typename ::std::decay<T>::type>{}
    >::type
  >
  delegate& operator=(T&& f)
  {
    using functor_type = typename ::std::decay<T>::type;

    holder_->::detail::holder::~holder();

    static_assert(sizeof(T) <= sizeof(store_), "increase store_ size");
    holder_ = new (store_) ::detail::any_store<functor_type>(
      ::std::forward<T>(f));

    object_ptr_ = holder_->get(store_);
    stub_ptr_ = functor_stub<functor_type>;

    return *this;
  }

  template <R (* const function_ptr)(A...)>
  static delegate from() noexcept
  {
    return { nullptr, function_stub<function_ptr> };
  }

  template <class C, R (C::* const method_ptr)(A...)>
  static delegate from(C* const object_ptr) noexcept
  {
    return { object_ptr, method_stub<C, method_ptr> };
  }

  template <class C, R (C::* const method_ptr)(A...) const>
  static delegate from(C const* const object_ptr) noexcept
  {
    return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };
  }

  template <class C, R (C::* const method_ptr)(A...)>
  static delegate from(C& object) noexcept
  {
    return { &object, method_stub<C, method_ptr> };
  }

  template <class C, R (C::* const method_ptr)(A...) const>
  static delegate from(C const& object) noexcept
  {
    return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };
  }

  template <typename T>
  static delegate from(T&& f)
  {
    return ::std::forward<T>(f);
  }

  static delegate from(R (* const function_ptr)(A...))
  {
    return [function_ptr](A&&... args) {
      return (*function_ptr)(::std::forward<A>(args)...); };
  }

  template <class C>
  static delegate from(C* const object_ptr,
    R (C::* const method_ptr)(A...))
  {
    return [object_ptr, method_ptr](A&&... args) {
      return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
  }

  template <class C>
  static delegate from(C const* const object_ptr,
    R (C::* const method_ptr)(A...) const)
  {
    return [object_ptr, method_ptr](A&&... args) {
      return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
  }

  template <class C>
  static delegate from(C& object, R (C::* const method_ptr)(A...))
  {
    return [&object, method_ptr](A&&... args) {
      return (object.*method_ptr)(::std::forward<A>(args)...); };
  }

  template <class C>
  static delegate from(C const& object,
    R (C::* const method_ptr)(A...) const)
  {
    return [&object, method_ptr](A&&... args) {
      return (object.*method_ptr)(::std::forward<A>(args)...); };
  }

  void reset() { stub_ptr_ = nullptr; }

  void reset_stub() noexcept { stub_ptr_ = nullptr; }

  void swap(delegate& other) noexcept { ::std::swap(*this, other); }

  bool operator==(delegate const& rhs) const noexcept
  {
    return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);
  }

  bool operator!=(delegate const& rhs) const noexcept
  {
    return !operator==(rhs);
  }

  bool operator<(delegate const& rhs) const noexcept
  {
    return (object_ptr_ < rhs.object_ptr_) ||
      ((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));
  }

  bool operator==(::std::nullptr_t const) const noexcept
  {
    return !stub_ptr_;
  }

  bool operator!=(::std::nullptr_t const) const noexcept
  {
    return stub_ptr_;
  }

  explicit operator bool() const noexcept { return stub_ptr_; }

  R operator()(A... args) const
  {
//  assert(stub_ptr);
    return stub_ptr_(object_ptr_, ::std::forward<A>(args)...);
  }

private:
  friend class ::std::hash<delegate>;

  void* object_ptr_;
  stub_ptr_type stub_ptr_{};

  alignas(::max_align_t) char store_[max_store_size];

  ::detail::holder* holder_{new (store_) ::detail::any_store<::std::nullptr_t>};

  template <R (*function_ptr)(A...)>
  static R function_stub(void* const, A&&... args)
  {
    return function_ptr(::std::forward<A>(args)...);
  }

  template <class C, R (C::*method_ptr)(A...)>
  static R method_stub(void* const object_ptr, A&&... args)
  {
    return (static_cast<C*>(object_ptr)->*method_ptr)(
      ::std::forward<A>(args)...);
  }

  template <class C, R (C::*method_ptr)(A...) const>
  static R const_method_stub(void* const object_ptr, A&&... args)
  {
    return (static_cast<C const*>(object_ptr)->*method_ptr)(
      ::std::forward<A>(args)...);
  }

  template <typename T>
  static R functor_stub(void* const object_ptr, A&&... args)
  {
    return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...);
  }
};

namespace std
{
  template <typename R, typename ...A>
  struct hash<delegate<R (A...)> >
  {
    size_t operator()(delegate<R (A...)> const& d) const noexcept
    {
      auto const seed(hash<void*>()(d.object_ptr_));

      return hash<typename delegate<R (A...)>::stub_ptr_type>()(
        d.stub_ptr_) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
    }
  };
}

#endif // ARRAYDELEGATE_HPP
<|endoftext|>