<commit_before>#ifdef WIN32
/////////////////////////////////////////////////////////////////////////////
// Disable unavoidable warning messages:

//  4103: used #pragma pack to change alignment
//  4114: same type qualifier used more than once
//  4201: nonstandard extension used : nameless struct/union
//  4237: "keyword" reserved for future use
//  4251: class needs to have dll-interface to export class
//  4275: non DLL-interface class used as base for DLL-interface class
//  4290: C++ Exception Specification ignored
//  4503: decorated name length exceeded, name was truncated
//  4786: string too long - truncated to 255 characters

#pragma warning(disable : 4103 4114 4201 4237 4251 4275 4290 4503 4335 4786)

#endif // WIN32

#include <osgViewer/Viewer>
#include <osgViewer/StatsHandler>
#include <osgViewer/HelpHandler>
#include <osgViewer/ViewerEventHandlers>

#include <osg/Group>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Texture2D>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/CoordinateSystemNode>

#include <osgDB/FileUtils>
#include <osgDB/ReadFile>

#include <osgText/Text>

#include <osg/CoordinateSystemNode>

#include <osgSim/OverlayNode>
#include <osgSim/SphereSegment>

#include <osgGA/NodeTrackerManipulator>
#include <osgGA/StateSetManipulator>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgGA/KeySwitchMatrixManipulator>
#include <osgGA/AnimationPathManipulator>
#include <osgGA/TerrainManipulator>

#include <iostream>

osg::Node* createEarth()
{
    osg::TessellationHints* hints = new osg::TessellationHints;
    hints->setDetailRatio(5.0f);

    osg::ShapeDrawable* sd = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0,0.0,0.0), osg::WGS_84_RADIUS_POLAR), hints);

    osg::Geode* geode = new osg::Geode;
    geode->addDrawable(sd);

    std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");
    geode->getOrCreateStateSet()->setTextureAttributeAndModes(0, new osg::Texture2D(osgDB::readImageFile(filename)));

    osg::CoordinateSystemNode* csn = new osg::CoordinateSystemNode;
    csn->setEllipsoidModel(new osg::EllipsoidModel());
    csn->addChild(geode);

    return csn;

}

class ModelPositionCallback : public osg::NodeCallback
{
public:

    ModelPositionCallback(double speed):
        _latitude(0.0),
        _longitude(0.0),
        _height(100000.0),
        _speed(speed)
    {
        _rotation.makeRotate(osg::DegreesToRadians(90.0),0.0,0.0,1.0);
    }

    void updateParameters()
    {
        _longitude += _speed * ((2.0*osg::PI)/360.0)/20.0;
    }

    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
    {
        updateParameters();

        osg::NodePath nodePath = nv->getNodePath();

        osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
        if (mt)
        {
            osg::CoordinateSystemNode* csn = 0;

            // find coordinate system node from our parental chain
            unsigned int i;
            for(i=0; i<nodePath.size() && csn==0; ++i)
            {
                csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
            }

            if (csn)
            {

                osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
                if (ellipsoid)
                {
                    osg::Matrix inheritedMatrix;
                    for(i+=1; i<nodePath.size()-1; ++i)
                    {
                        osg::Transform* transform = nodePath[i]->asTransform();
                        if (transform) transform->computeLocalToWorldMatrix(inheritedMatrix, nv);
                    }

                    osg::Matrixd matrix(inheritedMatrix);

                    //osg::Matrixd matrix;
                    ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
                    matrix.preMult(osg::Matrix::rotate(_rotation));

                    mt->setMatrix(matrix);
                }

            }
        }

        traverse(node,nv);
    }

    double                  _latitude;
    double                  _longitude;
    double                  _height;
    osg::Quat               _rotation;
    double                  _speed;
};

class FindNamedNodeVisitor : public osg::NodeVisitor
{
public:
    FindNamedNodeVisitor(const std::string& name):
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _name(name) {}

    virtual void apply(osg::Node& node)
    {
        if (node.getName()==_name)
        {
            _foundNodes.push_back(&node);
        }
        traverse(node);
    }

    typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;

    std::string _name;
    NodeList _foundNodes;
};

int main(int argc, char **argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of node tracker.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName());
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");

    // construct the viewer.
    osgViewer::Viewer viewer;

    // add the state manipulator
    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );

    // add the thread model handler
    viewer.addEventHandler(new osgViewer::ThreadingHandler);

    // add the window size toggle handler
    viewer.addEventHandler(new osgViewer::WindowSizeHandler);

    // add the stats handler
    viewer.addEventHandler(new osgViewer::StatsHandler);

    // add the help handler
    viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));

    // set the near far ration computation up.
    viewer.getCamera()->setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
    viewer.getCamera()->setNearFarRatio(0.00001f);

    double speed = 1.0;
    while (arguments.read("-f") || arguments.read("--fixed")) speed = 0.0;

    osg::Quat rotation;
    osg::Vec4 vec4;
    while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
    {
        osg::Quat local_rotate;
        local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);

        rotation = rotation * local_rotate;
    }

    osg::NodeCallback* nc = 0;
    std::string flightpath_filename;
    while (arguments.read("--flight-path",flightpath_filename))
    {
        std::ifstream fin(flightpath_filename.c_str());
        if (fin)
        {
            osg::AnimationPath* path = new osg::AnimationPath;
            path->read(fin);
            nc = new osg::AnimationPathCallback(path);
        }
    }

    osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
    std::string mode;
    while (arguments.read("--tracker-mode",mode))
    {
        if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
        else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
        else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
        else
        {
            std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_ROTATION"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_AZIM"<<std::endl;
            std::cout<<"    NODE_CENTER"<<std::endl;
            return 1;
        }
    }

    osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
    while (arguments.read("--rotation-mode",mode))
    {
        if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
        else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
        else
        {
            std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    TRACKBALL"<<std::endl;
            std::cout<<"    ELEVATION_AZIM"<<std::endl;
            return 1;
        }
    }

    bool useOverlay = true;
    while (arguments.read("--no-overlay") || arguments.read("-n")) useOverlay = false;

    osgSim::OverlayNode::OverlayTechnique technique = osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY;
    while (arguments.read("--object")) technique = osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY;
    while (arguments.read("--ortho") || arguments.read("--orthographic")) technique = osgSim::OverlayNode::VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY;
    while (arguments.read("--persp") || arguments.read("--perspective")) technique = osgSim::OverlayNode::VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY;

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    // read the scene from the list of file specified commandline args.
    osg::ref_ptr<osg::Node> root = osgDB::readNodeFiles(arguments);

    if (!root) root = createEarth();

    if (!root) return 0;

    // add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData(root.get());

    osg::ref_ptr<osgGA::NodeTrackerManipulator> tm;

    osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
    if (csn)
    {

        osg::ref_ptr<osgSim::OverlayNode> overlayNode;
        if (useOverlay)
        {
            overlayNode = new osgSim::OverlayNode(technique);

            // insert the OverlayNode between the coordinate system node and its children.
            for(unsigned int i=0; i<csn->getNumChildren(); ++i)
            {
                overlayNode->addChild( csn->getChild(i) );
            }

            csn->removeChildren(0, csn->getNumChildren());
            csn->addChild(overlayNode.get());

            // tell the overlay node to continously update its overlay texture
            // as we know we'll be tracking a moving target.
            overlayNode->setContinuousUpdate(true);
        }

        osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
        if (cessna)
        {
            double s = 200000.0 / cessna->getBound().radius();

            osg::MatrixTransform* scaler = new osg::MatrixTransform;
            scaler->addChild(cessna);
            scaler->setMatrix(osg::Matrixd::scale(s,s,s)*osg::Matrixd::rotate(rotation));
            scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);

            if (false)
            {
                osgSim::SphereSegment* ss = new osgSim::SphereSegment(
                                    osg::Vec3(0.0f,0.0f,0.0f), // center
                                    19.9f, // radius
                                    osg::DegreesToRadians(135.0f),
                                    osg::DegreesToRadians(240.0f),
                                    osg::DegreesToRadians(-10.0f),
                                    osg::DegreesToRadians(30.0f),
                                    60);

                scaler->addChild(ss);
            }

            osg::MatrixTransform* mt = new osg::MatrixTransform;
            mt->addChild(scaler);

            if (!nc) nc = new ModelPositionCallback(speed);

            mt->setUpdateCallback(nc);

            csn->addChild(mt);

            // if we are using an overaly node, use the cessna subgraph as the overlay subgraph
            if (overlayNode.valid())
            {
                overlayNode->setOverlaySubgraph(mt);
            }

            tm = new osgGA::NodeTrackerManipulator;
            tm->setTrackerMode(trackerMode);
            tm->setRotationMode(rotationMode);
            tm->setTrackNode(scaler);
        }
        else
        {
             std::cout<<"Failed to read cessna.osg"<<std::endl;
        }

    }

    // set up camera manipulators.
    {
        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;

        if (tm.valid()) keyswitchManipulator->addMatrixManipulator( '0', "Trackball", tm.get() );
        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );

        viewer.setCameraManipulator( keyswitchManipulator.get() );
    }

    viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);

    return viewer.run();
}
<commit_msg>Made the near far ratio lower to allow one to be near the terrain before clipping comes in to effect<commit_after>#ifdef WIN32
/////////////////////////////////////////////////////////////////////////////
// Disable unavoidable warning messages:

//  4103: used #pragma pack to change alignment
//  4114: same type qualifier used more than once
//  4201: nonstandard extension used : nameless struct/union
//  4237: "keyword" reserved for future use
//  4251: class needs to have dll-interface to export class
//  4275: non DLL-interface class used as base for DLL-interface class
//  4290: C++ Exception Specification ignored
//  4503: decorated name length exceeded, name was truncated
//  4786: string too long - truncated to 255 characters

#pragma warning(disable : 4103 4114 4201 4237 4251 4275 4290 4503 4335 4786)

#endif // WIN32

#include <osgViewer/Viewer>
#include <osgViewer/StatsHandler>
#include <osgViewer/HelpHandler>
#include <osgViewer/ViewerEventHandlers>

#include <osg/Group>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Texture2D>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/CoordinateSystemNode>

#include <osgDB/FileUtils>
#include <osgDB/ReadFile>

#include <osgText/Text>

#include <osg/CoordinateSystemNode>

#include <osgSim/OverlayNode>
#include <osgSim/SphereSegment>

#include <osgGA/NodeTrackerManipulator>
#include <osgGA/StateSetManipulator>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgGA/KeySwitchMatrixManipulator>
#include <osgGA/AnimationPathManipulator>
#include <osgGA/TerrainManipulator>

#include <iostream>

osg::Node* createEarth()
{
    osg::TessellationHints* hints = new osg::TessellationHints;
    hints->setDetailRatio(5.0f);

    osg::ShapeDrawable* sd = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0,0.0,0.0), osg::WGS_84_RADIUS_POLAR), hints);

    osg::Geode* geode = new osg::Geode;
    geode->addDrawable(sd);

    std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");
    geode->getOrCreateStateSet()->setTextureAttributeAndModes(0, new osg::Texture2D(osgDB::readImageFile(filename)));

    osg::CoordinateSystemNode* csn = new osg::CoordinateSystemNode;
    csn->setEllipsoidModel(new osg::EllipsoidModel());
    csn->addChild(geode);

    return csn;

}

class ModelPositionCallback : public osg::NodeCallback
{
public:

    ModelPositionCallback(double speed):
        _latitude(0.0),
        _longitude(0.0),
        _height(100000.0),
        _speed(speed)
    {
        _rotation.makeRotate(osg::DegreesToRadians(90.0),0.0,0.0,1.0);
    }

    void updateParameters()
    {
        _longitude += _speed * ((2.0*osg::PI)/360.0)/20.0;
    }

    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
    {
        updateParameters();

        osg::NodePath nodePath = nv->getNodePath();

        osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
        if (mt)
        {
            osg::CoordinateSystemNode* csn = 0;

            // find coordinate system node from our parental chain
            unsigned int i;
            for(i=0; i<nodePath.size() && csn==0; ++i)
            {
                csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
            }

            if (csn)
            {

                osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
                if (ellipsoid)
                {
                    osg::Matrix inheritedMatrix;
                    for(i+=1; i<nodePath.size()-1; ++i)
                    {
                        osg::Transform* transform = nodePath[i]->asTransform();
                        if (transform) transform->computeLocalToWorldMatrix(inheritedMatrix, nv);
                    }

                    osg::Matrixd matrix(inheritedMatrix);

                    //osg::Matrixd matrix;
                    ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
                    matrix.preMult(osg::Matrix::rotate(_rotation));

                    mt->setMatrix(matrix);
                }

            }
        }

        traverse(node,nv);
    }

    double                  _latitude;
    double                  _longitude;
    double                  _height;
    osg::Quat               _rotation;
    double                  _speed;
};

class FindNamedNodeVisitor : public osg::NodeVisitor
{
public:
    FindNamedNodeVisitor(const std::string& name):
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _name(name) {}

    virtual void apply(osg::Node& node)
    {
        if (node.getName()==_name)
        {
            _foundNodes.push_back(&node);
        }
        traverse(node);
    }

    typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;

    std::string _name;
    NodeList _foundNodes;
};

int main(int argc, char **argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of node tracker.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName());
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");

    // construct the viewer.
    osgViewer::Viewer viewer;

    // add the state manipulator
    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );

    // add the thread model handler
    viewer.addEventHandler(new osgViewer::ThreadingHandler);

    // add the window size toggle handler
    viewer.addEventHandler(new osgViewer::WindowSizeHandler);

    // add the stats handler
    viewer.addEventHandler(new osgViewer::StatsHandler);

    // add the help handler
    viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));

    // set the near far ration computation up.
    viewer.getCamera()->setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
    viewer.getCamera()->setNearFarRatio(0.000003f);

    double speed = 1.0;
    while (arguments.read("-f") || arguments.read("--fixed")) speed = 0.0;

    osg::Quat rotation;
    osg::Vec4 vec4;
    while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
    {
        osg::Quat local_rotate;
        local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);

        rotation = rotation * local_rotate;
    }

    osg::NodeCallback* nc = 0;
    std::string flightpath_filename;
    while (arguments.read("--flight-path",flightpath_filename))
    {
        std::ifstream fin(flightpath_filename.c_str());
        if (fin)
        {
            osg::AnimationPath* path = new osg::AnimationPath;
            path->read(fin);
            nc = new osg::AnimationPathCallback(path);
        }
    }

    osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
    std::string mode;
    while (arguments.read("--tracker-mode",mode))
    {
        if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
        else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
        else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
        else
        {
            std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_ROTATION"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_AZIM"<<std::endl;
            std::cout<<"    NODE_CENTER"<<std::endl;
            return 1;
        }
    }

    osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
    while (arguments.read("--rotation-mode",mode))
    {
        if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
        else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
        else
        {
            std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    TRACKBALL"<<std::endl;
            std::cout<<"    ELEVATION_AZIM"<<std::endl;
            return 1;
        }
    }

    bool useOverlay = true;
    while (arguments.read("--no-overlay") || arguments.read("-n")) useOverlay = false;

    osgSim::OverlayNode::OverlayTechnique technique = osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY;
    while (arguments.read("--object")) technique = osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY;
    while (arguments.read("--ortho") || arguments.read("--orthographic")) technique = osgSim::OverlayNode::VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY;
    while (arguments.read("--persp") || arguments.read("--perspective")) technique = osgSim::OverlayNode::VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY;

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    // read the scene from the list of file specified commandline args.
    osg::ref_ptr<osg::Node> root = osgDB::readNodeFiles(arguments);

    if (!root) root = createEarth();

    if (!root) return 0;

    // add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData(root.get());

    osg::ref_ptr<osgGA::NodeTrackerManipulator> tm;

    osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
    if (csn)
    {

        osg::ref_ptr<osgSim::OverlayNode> overlayNode;
        if (useOverlay)
        {
            overlayNode = new osgSim::OverlayNode(technique);

            // insert the OverlayNode between the coordinate system node and its children.
            for(unsigned int i=0; i<csn->getNumChildren(); ++i)
            {
                overlayNode->addChild( csn->getChild(i) );
            }

            csn->removeChildren(0, csn->getNumChildren());
            csn->addChild(overlayNode.get());

            // tell the overlay node to continously update its overlay texture
            // as we know we'll be tracking a moving target.
            overlayNode->setContinuousUpdate(true);
        }

        osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
        if (cessna)
        {
            double s = 200000.0 / cessna->getBound().radius();

            osg::MatrixTransform* scaler = new osg::MatrixTransform;
            scaler->addChild(cessna);
            scaler->setMatrix(osg::Matrixd::scale(s,s,s)*osg::Matrixd::rotate(rotation));
            scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);

            if (false)
            {
                osgSim::SphereSegment* ss = new osgSim::SphereSegment(
                                    osg::Vec3(0.0f,0.0f,0.0f), // center
                                    19.9f, // radius
                                    osg::DegreesToRadians(135.0f),
                                    osg::DegreesToRadians(240.0f),
                                    osg::DegreesToRadians(-10.0f),
                                    osg::DegreesToRadians(30.0f),
                                    60);

                scaler->addChild(ss);
            }

            osg::MatrixTransform* mt = new osg::MatrixTransform;
            mt->addChild(scaler);

            if (!nc) nc = new ModelPositionCallback(speed);

            mt->setUpdateCallback(nc);

            csn->addChild(mt);

            // if we are using an overaly node, use the cessna subgraph as the overlay subgraph
            if (overlayNode.valid())
            {
                overlayNode->setOverlaySubgraph(mt);
            }

            tm = new osgGA::NodeTrackerManipulator;
            tm->setTrackerMode(trackerMode);
            tm->setRotationMode(rotationMode);
            tm->setTrackNode(scaler);
        }
        else
        {
             std::cout<<"Failed to read cessna.osg"<<std::endl;
        }

    }

    // set up camera manipulators.
    {
        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;

        if (tm.valid()) keyswitchManipulator->addMatrixManipulator( '0', "Trackball", tm.get() );
        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );

        viewer.setCameraManipulator( keyswitchManipulator.get() );
    }

    viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);

    return viewer.run();
}
<|endoftext|>


<commit_before>//Abstract class for mutation operators. Lets us define any mutation operation we like.

#include <random>
#include <chrono>
#include <string>
#include <sstream>
#include "nodes/EANode/MutationOperation.hpp"

using namespace std;

MutationOperation::MutationOperation() {
	seed = chrono::system_clock::now().time_since_epoch().count();
	init(0, seed);
}

MutationOperation::MutationOperation(double newMutationRate) {
	seed = chrono::system_clock::now().time_since_epoch().count();
	init(newMutationRate, seed);
}

MutationOperation::MutationOperation(double newMutationRate, unsigned newSeed) {
	init(newMutationRate, newSeed);
}

void MutationOperation::init(double newMutationRate, unsigned newSeed) {
	mutationRate = newMutationRate;
	seed = newSeed;
	generator = mt19937(seed);
}

Genome * MutationOperation::mutate(Genome * initialGenome) {
	vector<int> newGenome, existingGenome = initialGenome->getGenome();
	vector<Locus*> loci = initialGenome->getLoci();
	uniform_real_distribution<double> mutationDist(0, 1);
	for (int i = 0; i < initialGenome->genomeLength(); i++) {
		if (mutationDist(this->generator) < this->mutationRate) {
			newGenome.push_back(
				this->getNewLocusValue(
					existingGenome[i],
					loci[i]->topIndex()
				)
			);
		} else {
			newGenome.push_back(existingGenome[i]);
		}
	}
	return new Genome(newGenome, loci);
}

string MutationOperation::toString() {
	string returnString = "";
	stringstream ss;

	ss << "Random seed: " << seed << "\nMutation rate: " << mutationRate << "\n";

	returnString = ss.str();

	return returnString;

}
<commit_msg>[MutationOperation]: Slight code cleanup<commit_after>//Abstract class for mutation operators. Lets us define any mutation operation we like.

#include <random>
#include <chrono>
#include <sstream>
#include "nodes/EANode/MutationOperation.hpp"

using namespace std;

MutationOperation::MutationOperation() {
	seed = chrono::system_clock::now().time_since_epoch().count();
	this->init(0, seed);
}

MutationOperation::MutationOperation(double mutationRate) {
	seed = chrono::system_clock::now().time_since_epoch().count();
	this->init(mutationRate, seed);
}

MutationOperation::MutationOperation(double mutationRate, unsigned seed) {
	this->init(mutationRate, seed);
}

void MutationOperation::init(double mutationRate, unsigned seed) {
	this->mutationRate = mutationRate;
	this->seed = seed;
	this->generator = mt19937(seed);
}

Genome * MutationOperation::mutate(Genome * initialGenome) {
	vector<int> newGenome, existingGenome = initialGenome->getGenome();
	vector<Locus*> loci = initialGenome->getLoci();
	uniform_real_distribution<double> mutationDist(0, 1);
	for (int i = 0; i < initialGenome->genomeLength(); i++) {
		if (mutationDist(this->generator) < this->mutationRate) {
			newGenome.push_back(
				this->getNewLocusValue(
					existingGenome[i],
					loci[i]->topIndex()
				)
			);
		} else {
			newGenome.push_back(existingGenome[i]);
		}
	}
	return new Genome(newGenome, loci);
}

string MutationOperation::toString() {
	stringstream ss;

	ss << "Random seed: " << seed
		<< "\nMutation rate: " << mutationRate
		<< "\n";

	return ss.str();

}
<|endoftext|>


<commit_before>/*
    Copyright (c) 2008 Bruno Virlet <bvirlet@kdemail.net>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This library is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "kcalmodel.h"
#include "kcalmimetypevisitor.h"

#include <akonadi/item.h>
#include <akonadi/itemfetchjob.h>
#include <akonadi/itemfetchscope.h>
#include <akonadi/collection.h>

#include <kcal/incidence.h>
#include <kcal/event.h>

#include <klocale.h>
#include <boost/shared_ptr.hpp>

#include <kiconloader.h>
#include <QtGui/QPixmap>

typedef boost::shared_ptr<KCal::Incidence> IncidencePtr;

using namespace Akonadi;

class KCalModel::Private
{
  public:
    Private( KCalModel *model )
    :q( model )
    {
    }

    static QStringList allMimeTypes()
    {
        QStringList types;
        types << KCalMimeTypeVisitor::eventMimeType()
              << KCalMimeTypeVisitor::todoMimeType()
              << KCalMimeTypeVisitor::journalMimeType()
              << KCalMimeTypeVisitor::freeBusyMimeType();
        return types;
    }
    bool collectionMatchesMimeTypes() const
    {
      Q_FOREACH( QString type, allMimeTypes() ) {
      if ( q->collection().contentMimeTypes().contains( type ) )
        return true;
      }
      return false;
    }
  private:
    KCalModel *q;
};

KCalModel::KCalModel( QObject *parent )
  : ItemModel( parent ),
    d( new Private( this ) )
{
  fetchScope().fetchFullPayload();
}

KCalModel::~KCalModel()
{
  delete d;
}

QStringList KCalModel::mimeTypes() const
{
  return QStringList()
      << QLatin1String("text/uri-list")
      << d->allMimeTypes();
}

int KCalModel::columnCount( const QModelIndex& ) const
{
  if ( d->collectionMatchesMimeTypes() )
    return 4;
  else
    return 1;
}

int KCalModel::rowCount( const QModelIndex& ) const
{
  if ( d->collectionMatchesMimeTypes() )
    return ItemModel::rowCount();
  else
    return 1;
}

QVariant KCalModel::data( const QModelIndex &index,  int role ) const
{
  if ( role == ItemModel::IdRole )
    return ItemModel::data( index, role );

  if ( !index.isValid() || index.row() >= rowCount() )
    return QVariant();

  // guard against use with collections that do not have the right contents
  if ( !d->collectionMatchesMimeTypes() ) {
    if ( role == Qt::DisplayRole )
      // FIXME: i18n when strings unfreeze for 4.4
      return QString::fromLatin1( "This model can only handle event, task, journal or free-busy list folders. The current collection holds mimetypes: %1").arg(
                 collection().contentMimeTypes().join( QLatin1String(",") ) );
    return QVariant();
  }

  const Item item = itemForIndex( index );

  if ( !item.hasPayload<IncidencePtr>() )
    return QVariant();

  const IncidencePtr incidence = item.payload<IncidencePtr>();

  // Icon for the model entry
  switch( role ) {
  case Qt::DecorationRole:
    if ( index.column() == 0 ) {
      if ( incidence->type() == "Todo" ) {
        return SmallIcon( QLatin1String( "view-pim-tasks" ) );
      } else if ( incidence->type() == "Journal" ) {
        return SmallIcon( QLatin1String( "view-pim-journal" ) );
      } else if ( incidence->type() == "Event" ) {
        return SmallIcon( QLatin1String( "view-pim-calendar" ) );
      } else {
        return SmallIcon( QLatin1String( "network-wired" ) );
      }
    }
    break;
  case Qt::DisplayRole:
    switch( index.column() ) {
    case Summary:
      return incidence->summary();
      break;
    case DateTimeStart:
      return incidence->dtStart().toString();
      break;
    case DateTimeEnd:
      return incidence->dtEnd().toString();
      break;
    case Type:
      return incidence->type();
      break;
    default:
      break;
    }
    break;
  default:
    return QVariant();
    break;
  }

  return QVariant();
}

QVariant KCalModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
  if ( !d->collectionMatchesMimeTypes() )
    return QVariant();

  if ( role == Qt::DisplayRole && orientation == Qt::Horizontal ) {
    switch( section ) {
    case Summary:
      return i18nc( "@title:column, calendar event summary", "Summary" );
    case DateTimeStart:
      return i18nc( "@title:column, calendar event start date and time", "Start date and time" );
    case DateTimeEnd:
      return i18nc( "@title:column, calendar event end date and time", "End date and time" );
    case Type:
      return i18nc( "@title:column, calendar event type", "Type" );
    default:
      return QString();
    }
  }

  return ItemModel::headerData( section, orientation, role );
}
<commit_msg>Make the kcal model only report that it can only deal with calendar collections when the current collection is valid.<commit_after>/*
    Copyright (c) 2008 Bruno Virlet <bvirlet@kdemail.net>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This library is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "kcalmodel.h"
#include "kcalmimetypevisitor.h"

#include <akonadi/item.h>
#include <akonadi/itemfetchjob.h>
#include <akonadi/itemfetchscope.h>
#include <akonadi/collection.h>

#include <kcal/incidence.h>
#include <kcal/event.h>

#include <klocale.h>
#include <boost/shared_ptr.hpp>

#include <kiconloader.h>
#include <QtGui/QPixmap>

typedef boost::shared_ptr<KCal::Incidence> IncidencePtr;

using namespace Akonadi;

class KCalModel::Private
{
  public:
    Private( KCalModel *model )
    :q( model )
    {
    }

    static QStringList allMimeTypes()
    {
        QStringList types;
        types << KCalMimeTypeVisitor::eventMimeType()
              << KCalMimeTypeVisitor::todoMimeType()
              << KCalMimeTypeVisitor::journalMimeType()
              << KCalMimeTypeVisitor::freeBusyMimeType();
        return types;
    }
    bool collectionMatchesMimeTypes() const
    {
      Q_FOREACH( QString type, allMimeTypes() ) {
      if ( q->collection().contentMimeTypes().contains( type ) )
        return true;
      }
      return false;
    }
  private:
    KCalModel *q;
};

KCalModel::KCalModel( QObject *parent )
  : ItemModel( parent ),
    d( new Private( this ) )
{
  fetchScope().fetchFullPayload();
}

KCalModel::~KCalModel()
{
  delete d;
}

QStringList KCalModel::mimeTypes() const
{
  return QStringList()
      << QLatin1String("text/uri-list")
      << d->allMimeTypes();
}

int KCalModel::columnCount( const QModelIndex& ) const
{
  if ( d->collectionMatchesMimeTypes() )
    return 4;
  else
    return 1;
}

int KCalModel::rowCount( const QModelIndex& ) const
{
  if ( !collection().isValid() || d->collectionMatchesMimeTypes() )
    return ItemModel::rowCount();
  else
    return 1;
}

QVariant KCalModel::data( const QModelIndex &index,  int role ) const
{
  if ( role == ItemModel::IdRole )
    return ItemModel::data( index, role );

  if ( !index.isValid() || index.row() >= rowCount() )
    return QVariant();

  // guard against use with collections that do not have the right contents
  if ( !d->collectionMatchesMimeTypes() ) {
    if ( role == Qt::DisplayRole )
      // FIXME: i18n when strings unfreeze for 4.4
      return QString::fromLatin1( "This model can only handle event, task, journal or free-busy list folders. The current collection holds mimetypes: %1").arg(
                 collection().contentMimeTypes().join( QLatin1String(",") ) );
    return QVariant();
  }

  const Item item = itemForIndex( index );

  if ( !item.hasPayload<IncidencePtr>() )
    return QVariant();

  const IncidencePtr incidence = item.payload<IncidencePtr>();

  // Icon for the model entry
  switch( role ) {
  case Qt::DecorationRole:
    if ( index.column() == 0 ) {
      if ( incidence->type() == "Todo" ) {
        return SmallIcon( QLatin1String( "view-pim-tasks" ) );
      } else if ( incidence->type() == "Journal" ) {
        return SmallIcon( QLatin1String( "view-pim-journal" ) );
      } else if ( incidence->type() == "Event" ) {
        return SmallIcon( QLatin1String( "view-pim-calendar" ) );
      } else {
        return SmallIcon( QLatin1String( "network-wired" ) );
      }
    }
    break;
  case Qt::DisplayRole:
    switch( index.column() ) {
    case Summary:
      return incidence->summary();
      break;
    case DateTimeStart:
      return incidence->dtStart().toString();
      break;
    case DateTimeEnd:
      return incidence->dtEnd().toString();
      break;
    case Type:
      return incidence->type();
      break;
    default:
      break;
    }
    break;
  default:
    return QVariant();
    break;
  }

  return QVariant();
}

QVariant KCalModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
  if ( !d->collectionMatchesMimeTypes() )
    return QVariant();

  if ( role == Qt::DisplayRole && orientation == Qt::Horizontal ) {
    switch( section ) {
    case Summary:
      return i18nc( "@title:column, calendar event summary", "Summary" );
    case DateTimeStart:
      return i18nc( "@title:column, calendar event start date and time", "Start date and time" );
    case DateTimeEnd:
      return i18nc( "@title:column, calendar event end date and time", "End date and time" );
    case Type:
      return i18nc( "@title:column, calendar event type", "Type" );
    default:
      return QString();
    }
  }

  return ItemModel::headerData( section, orientation, role );
}
<|endoftext|>


<commit_before>// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Actions/Choose.hpp>
#include <Rosetta/Actions/Draw.hpp>
#include <Rosetta/Actions/Generic.hpp>
#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Commons/Utils.hpp>
#include <Rosetta/Enchants/Power.hpp>
#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Games/GameManager.hpp>
#include <Rosetta/Policies/Policy.hpp>
#include <Rosetta/Tasks/PlayerTasks/AttackTask.hpp>
#include <Rosetta/Tasks/PlayerTasks/PlayCardTask.hpp>
#include <Rosetta/Tasks/Tasks.hpp>

#include <effolkronium/random.hpp>

#include <algorithm>

using Random = effolkronium::random_static;

namespace RosettaStone
{
Game::Game(GameConfig& gameConfig) : m_gameConfig(gameConfig)
{
    // Set game to player
    for (auto& p : m_players)
    {
        p.SetGame(this);
    }

    // Add hero and hero power
    GetPlayer1().AddHeroAndPower(
        Cards::GetInstance().GetHeroCard(gameConfig.player1Class),
        Cards::GetInstance().GetDefaultHeroPower(gameConfig.player1Class));
    GetPlayer2().AddHeroAndPower(
        Cards::GetInstance().GetHeroCard(gameConfig.player2Class),
        Cards::GetInstance().GetDefaultHeroPower(gameConfig.player2Class));

    // Set opponent player
    GetPlayer1().SetOpponent(&GetPlayer2());
    GetPlayer2().SetOpponent(&GetPlayer1());
}

Player& Game::GetPlayer1()
{
    return m_players[0];
}

Player& Game::GetPlayer2()
{
    return m_players[1];
}

Player& Game::GetCurrentPlayer() const
{
    return *m_currentPlayer;
}

Player& Game::GetOpponentPlayer() const
{
    return m_currentPlayer->GetOpponent();
}

std::size_t Game::GetNextID()
{
    return m_entityID++;
}

std::size_t Game::GetNextOOP()
{
    return m_oopIndex++;
}

void Game::BeginFirst()
{
    // Set next step
    nextStep = Step::BEGIN_SHUFFLE;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::BeginShuffle()
{
    // Shuffle cards in deck
    if (m_gameConfig.doShuffle)
    {
        GetPlayer1().GetDeck().Shuffle();
        GetPlayer2().GetDeck().Shuffle();
    }

    // Set next step
    nextStep = Step::BEGIN_DRAW;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::BeginDraw()
{
    for (auto& p : m_players)
    {
        // Draw 3 cards
        Generic::Draw(p);
        Generic::Draw(p);
        Generic::Draw(p);

        if (&p != m_firstPlayer)
        {
            // Draw 4th card for second player
            Generic::Draw(p);

            // Give "The Coin" card to second player
            Card coin = Cards::GetInstance().FindCardByID("GAME_005");
            p.GetHand().AddCard(*Entity::GetFromCard(p, std::move(coin)));
        }
    }

    // Set next step
    nextStep =
        m_gameConfig.skipMulligan ? Step::MAIN_BEGIN : Step::BEGIN_MULLIGAN;

    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::BeginMulligan()
{
    // Start mulligan state
    GetPlayer1().mulliganState = Mulligan::INPUT;
    GetPlayer2().mulliganState = Mulligan::INPUT;

    // Collect cards that can redraw
    std::vector<std::size_t> p1HandIDs, p2HandIDs;
    for (auto& entity : GetPlayer1().GetHand().GetAllCards())
    {
        p1HandIDs.emplace_back(entity->id);
    }
    for (auto& entity : GetPlayer2().GetHand().GetAllCards())
    {
        p2HandIDs.emplace_back(entity->id);
    }

    // Create choice for each player
    Generic::CreateChoice(GetPlayer1(), ChoiceType::MULLIGAN,
                          ChoiceAction::HAND, p1HandIDs);
    Generic::CreateChoice(GetPlayer2(), ChoiceType::MULLIGAN,
                          ChoiceAction::HAND, p2HandIDs);

    Player& player1 = GetPlayer1();
    TaskMeta p1Choice = player1.GetPolicy().Require(player1, TaskID::MULLIGAN);
    Generic::ChoiceMulligan(player1,
                            p1Choice.GetObject<std::vector<std::size_t>>());

    Player& player2 = GetPlayer2();
    TaskMeta p2Choice = player2.GetPolicy().Require(player2, TaskID::MULLIGAN);
    Generic::ChoiceMulligan(player2,
                            p2Choice.GetObject<std::vector<std::size_t>>());

    nextStep = Step::MAIN_BEGIN;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainBegin()
{
    // Set next step
    nextStep = Step::MAIN_READY;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainReady()
{
    // Reset the number of attacked
    for (auto& p : m_players)
    {
        // Hero
        p.GetHero()->numAttacked = 0;
        // Field
        for (auto& m : p.GetField().GetAllMinions())
        {
            m->numAttacked = 0;
        }
    }

    // Reset exhaust for current player
    auto& curPlayer = GetCurrentPlayer();
    // Hero
    curPlayer.GetHero()->SetGameTag(GameTag::EXHAUSTED, 0);
    // Weapon
    if (curPlayer.GetHero()->weapon != nullptr)
    {
        curPlayer.GetHero()->weapon->SetGameTag(GameTag::EXHAUSTED, 0);
    }
    // Hero power
    curPlayer.GetHero()->heroPower->SetGameTag(GameTag::EXHAUSTED, 0);
    // Field
    for (auto& m : curPlayer.GetField().GetAllMinions())
    {
        m->SetGameTag(GameTag::EXHAUSTED, 0);
    }

    // Set next step
    nextStep = Step::MAIN_START_TRIGGERS;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainStartTriggers()
{
    // Set next step
    nextStep = Step::MAIN_RESOURCE;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainResource()
{
    auto& curPlayer = GetCurrentPlayer();

    // Add mana crystal to current player
    Generic::ChangeManaCrystal(curPlayer, 1, false);

    // Reset current mana
    curPlayer.currentMana = curPlayer.maximumMana;

    // Set next step
    nextStep = Step::MAIN_DRAW;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainDraw()
{
    // Draw a card for current player
    Generic::Draw(GetCurrentPlayer());

    // Set next step
    nextStep = Step::MAIN_START;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainStart()
{
    // Set next step
    nextStep = Step::MAIN_ACTION;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainAction()
{
    auto& player = GetCurrentPlayer();

    TaskMeta next = player.GetPolicy().Next(*this);
    if (next.GetID() == +TaskID::END_TURN)
    {
        nextStep = Step::MAIN_END;
        if (m_gameConfig.autoRun)
        {
            GameManager::ProcessNextStep(*this, nextStep);
        }
        return;
    }

    TaskMeta req = player.GetPolicy().Require(player, next.GetID());
    SizedPtr<Entity*> list = req.GetObject<SizedPtr<Entity*>>();
    switch (next.GetID())
    {
        case TaskID::ATTACK:
        {
            Entity* source = list[0];
            Entity* target = list[1];
            Task::Run(player, PlayerTasks::AttackTask(source, target));
            break;
        }
        case TaskID::PLAY_CARD:
        {
            Entity* source = list[0];
            switch (source->card.cardType)
            {
                case CardType::MINION:
                    Task::Run(player, PlayerTasks::PlayCardTask::Minion(
                                          player, source));
                    break;
                case CardType::SPELL:
                    if (list.size() == 1)
                    {
                        Task::Run(player, PlayerTasks::PlayCardTask::Spell(
                                              player, source));
                    }
                    else
                    {
                        Entity* target = list[1];
                        Task::Run(player,
                                  PlayerTasks::PlayCardTask::SpellTarget(
                                      player, source, target));
                    }
                    break;
                case CardType::WEAPON:
                    Task::Run(player, PlayerTasks::PlayCardTask::Weapon(
                                          player, source));
                    break;
                default:
                    throw std::invalid_argument(
                        "Game::MainAction() - Invalid card type!");
            }
            break;
        }
        default:
            throw std::invalid_argument(
                "Game::MainAction() - Invalid task type!");
    }

    nextStep = Step::MAIN_ACTION;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
    return;
}

void Game::MainEnd()
{
    // Set next step
    nextStep = Step::MAIN_CLEANUP;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainCleanUp()
{
    auto& curPlayer = GetCurrentPlayer();

    // Unfreeze all characters they control that are Frozen, don't have
    // summoning sickness (or do have Charge) and have not attacked that turn
    // Hero
    if (curPlayer.GetHero()->GetGameTag(GameTag::FROZEN) == 1 &&
        curPlayer.GetHero()->numAttacked == 0)
    {
        curPlayer.GetHero()->SetGameTag(GameTag::FROZEN, 0);
    }
    // Field
    for (auto& m : curPlayer.GetField().GetAllMinions())
    {
        if (m->GetGameTag(GameTag::FROZEN) == 1 && m->numAttacked == 0 &&
            m->GetGameTag(GameTag::EXHAUSTED) == 0)
        {
            m->SetGameTag(GameTag::FROZEN, 0);
        }
    }

    // Set next step
    nextStep = Step::MAIN_NEXT;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainNext()
{
    // Set player for next turn
    m_currentPlayer = &m_currentPlayer->GetOpponent();

    // Count next turn
    m_turn++;

    // Set next step
    nextStep = Step::MAIN_READY;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::FinalWrapUp()
{
    // Set game states according by result
    for (auto& p : m_players)
    {
        if (p.playState == +PlayState::LOSING ||
            p.playState == +PlayState::CONCEDED)
        {
            p.playState = PlayState::LOST;
            p.GetOpponent().playState = PlayState::WON;
        }
    }

    // Set next step
    nextStep = Step::FINAL_GAMEOVER;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::FinalGameOver()
{
    // Set game state to complete
    state = State::COMPLETE;
}

void Game::StartGame()
{
    // Reverse card order in deck
    if (!m_gameConfig.doShuffle)
    {
        std::reverse(m_gameConfig.player1Deck.begin(),
                     m_gameConfig.player1Deck.end());
        std::reverse(m_gameConfig.player2Deck.begin(),
                     m_gameConfig.player2Deck.end());
    }

    // Set up decks
    for (auto& card : m_gameConfig.player1Deck)
    {
        if (card.cardType == +CardType::INVALID)
        {
            continue;
        }

        Entity* entity = Entity::GetFromCard(GetPlayer1(), std::move(card));
        GetPlayer1().GetDeck().AddCard(*entity);
    }
    for (auto& card : m_gameConfig.player2Deck)
    {
        if (card.cardType == +CardType::INVALID)
        {
            continue;
        }

        Entity* entity = Entity::GetFromCard(GetPlayer2(), std::move(card));
        GetPlayer2().GetDeck().AddCard(*entity);
    }

    // Fill cards to deck
    if (m_gameConfig.doFillDecks)
    {
        for (auto& p : m_players)
        {
            for (auto& cardID : m_gameConfig.fillCardIDs)
            {
                Card card = Cards::GetInstance().FindCardByID(cardID);
                Entity* entity = Entity::GetFromCard(p, std::move(card));
                p.GetDeck().AddCard(*entity);
            }
        }
    }

    // Set game states
    state = State::RUNNING;
    for (auto& p : m_players)
    {
        p.playState = PlayState::PLAYING;
    }

    // Determine first player
    switch (m_gameConfig.startPlayer)
    {
        case PlayerType::RANDOM:
        {
            const auto val = Random::get(0, 1);
            m_firstPlayer = &m_players[val];
            break;
        }
        case PlayerType::PLAYER1:
            m_firstPlayer = &m_players[0];
            break;
        case PlayerType::PLAYER2:
            m_firstPlayer = &m_players[1];
            break;
    }
    m_currentPlayer = m_firstPlayer;

    // Set first turn
    m_turn = 1;

    // Set next step
    nextStep = Step::BEGIN_FIRST;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::ProcessDestroy()
{
    // Destroy weapons
    if (GetPlayer1().GetHero()->weapon != nullptr &&
        GetPlayer1().GetHero()->weapon->isDestroyed == true)
    {
        GetPlayer1().GetHero()->RemoveWeapon();
    }
    if (GetPlayer2().GetHero()->weapon != nullptr &&
        GetPlayer2().GetHero()->weapon->isDestroyed == true)
    {
        GetPlayer2().GetHero()->RemoveWeapon();
    }

    // Destroy minions
    if (deadMinions.size() > 0)
    {
        for (auto& deadMinion : deadMinions)
        {
            Minion* minion = deadMinion.second;

            // Process deathrattle tasks
            for (auto& power : minion->card.power.GetDeathrattleTask())
            {
                if (power == nullptr)
                {
                    continue;
                }

                power->Run(minion->GetOwner());
            }

            // Remove minion from battlefield
            minion->GetOwner().GetField().RemoveMinion(*minion);
            // Add minion to graveyard
            minion->GetOwner().GetGraveyard().AddCard(*minion);
        }

        deadMinions.clear();
    }
}

void Game::ProcessUntil(Step step)
{
    m_gameConfig.autoRun = false;
    while (nextStep != step)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}
}  // namespace RosettaStone
<commit_msg>fix: Fix duplicated variable names<commit_after>// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Actions/Choose.hpp>
#include <Rosetta/Actions/Draw.hpp>
#include <Rosetta/Actions/Generic.hpp>
#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Commons/Utils.hpp>
#include <Rosetta/Enchants/Power.hpp>
#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Games/GameManager.hpp>
#include <Rosetta/Policies/Policy.hpp>
#include <Rosetta/Tasks/PlayerTasks/AttackTask.hpp>
#include <Rosetta/Tasks/PlayerTasks/PlayCardTask.hpp>
#include <Rosetta/Tasks/Tasks.hpp>

#include <effolkronium/random.hpp>

#include <algorithm>

using Random = effolkronium::random_static;

namespace RosettaStone
{
Game::Game(GameConfig& gameConfig) : m_gameConfig(gameConfig)
{
    // Set game to player
    for (auto& p : m_players)
    {
        p.SetGame(this);
    }

    // Add hero and hero power
    GetPlayer1().AddHeroAndPower(
        Cards::GetInstance().GetHeroCard(gameConfig.player1Class),
        Cards::GetInstance().GetDefaultHeroPower(gameConfig.player1Class));
    GetPlayer2().AddHeroAndPower(
        Cards::GetInstance().GetHeroCard(gameConfig.player2Class),
        Cards::GetInstance().GetDefaultHeroPower(gameConfig.player2Class));

    // Set opponent player
    GetPlayer1().SetOpponent(&GetPlayer2());
    GetPlayer2().SetOpponent(&GetPlayer1());
}

Player& Game::GetPlayer1()
{
    return m_players[0];
}

Player& Game::GetPlayer2()
{
    return m_players[1];
}

Player& Game::GetCurrentPlayer() const
{
    return *m_currentPlayer;
}

Player& Game::GetOpponentPlayer() const
{
    return m_currentPlayer->GetOpponent();
}

std::size_t Game::GetNextID()
{
    return m_entityID++;
}

std::size_t Game::GetNextOOP()
{
    return m_oopIndex++;
}

void Game::BeginFirst()
{
    // Set next step
    nextStep = Step::BEGIN_SHUFFLE;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::BeginShuffle()
{
    // Shuffle cards in deck
    if (m_gameConfig.doShuffle)
    {
        GetPlayer1().GetDeck().Shuffle();
        GetPlayer2().GetDeck().Shuffle();
    }

    // Set next step
    nextStep = Step::BEGIN_DRAW;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::BeginDraw()
{
    for (auto& p : m_players)
    {
        // Draw 3 cards
        Generic::Draw(p);
        Generic::Draw(p);
        Generic::Draw(p);

        if (&p != m_firstPlayer)
        {
            // Draw 4th card for second player
            Generic::Draw(p);

            // Give "The Coin" card to second player
            Card coin = Cards::GetInstance().FindCardByID("GAME_005");
            p.GetHand().AddCard(*Entity::GetFromCard(p, std::move(coin)));
        }
    }

    // Set next step
    nextStep =
        m_gameConfig.skipMulligan ? Step::MAIN_BEGIN : Step::BEGIN_MULLIGAN;

    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::BeginMulligan()
{
    // Start mulligan state
    GetPlayer1().mulliganState = Mulligan::INPUT;
    GetPlayer2().mulliganState = Mulligan::INPUT;

    // Collect cards that can redraw
    std::vector<std::size_t> p1HandIDs, p2HandIDs;
    for (auto& entity : GetPlayer1().GetHand().GetAllCards())
    {
        p1HandIDs.emplace_back(entity->id);
    }
    for (auto& entity : GetPlayer2().GetHand().GetAllCards())
    {
        p2HandIDs.emplace_back(entity->id);
    }

    // Create choice for each player
    Generic::CreateChoice(GetPlayer1(), ChoiceType::MULLIGAN,
                          ChoiceAction::HAND, p1HandIDs);
    Generic::CreateChoice(GetPlayer2(), ChoiceType::MULLIGAN,
                          ChoiceAction::HAND, p2HandIDs);

    Player& player1 = GetPlayer1();
    TaskMeta p1Choice = player1.GetPolicy().Require(player1, TaskID::MULLIGAN);
    Generic::ChoiceMulligan(player1,
                            p1Choice.GetObject<std::vector<std::size_t>>());

    Player& player2 = GetPlayer2();
    TaskMeta p2Choice = player2.GetPolicy().Require(player2, TaskID::MULLIGAN);
    Generic::ChoiceMulligan(player2,
                            p2Choice.GetObject<std::vector<std::size_t>>());

    nextStep = Step::MAIN_BEGIN;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainBegin()
{
    // Set next step
    nextStep = Step::MAIN_READY;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainReady()
{
    // Reset the number of attacked
    for (auto& p : m_players)
    {
        // Hero
        p.GetHero()->numAttacked = 0;
        // Field
        for (auto& m : p.GetField().GetAllMinions())
        {
            m->numAttacked = 0;
        }
    }

    // Reset exhaust for current player
    auto& curPlayer = GetCurrentPlayer();
    // Hero
    curPlayer.GetHero()->SetGameTag(GameTag::EXHAUSTED, 0);
    // Weapon
    if (curPlayer.GetHero()->weapon != nullptr)
    {
        curPlayer.GetHero()->weapon->SetGameTag(GameTag::EXHAUSTED, 0);
    }
    // Hero power
    curPlayer.GetHero()->heroPower->SetGameTag(GameTag::EXHAUSTED, 0);
    // Field
    for (auto& m : curPlayer.GetField().GetAllMinions())
    {
        m->SetGameTag(GameTag::EXHAUSTED, 0);
    }

    // Set next step
    nextStep = Step::MAIN_START_TRIGGERS;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainStartTriggers()
{
    // Set next step
    nextStep = Step::MAIN_RESOURCE;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainResource()
{
    auto& curPlayer = GetCurrentPlayer();

    // Add mana crystal to current player
    Generic::ChangeManaCrystal(curPlayer, 1, false);

    // Reset current mana
    curPlayer.currentMana = curPlayer.maximumMana;

    // Set next step
    nextStep = Step::MAIN_DRAW;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainDraw()
{
    // Draw a card for current player
    Generic::Draw(GetCurrentPlayer());

    // Set next step
    nextStep = Step::MAIN_START;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainStart()
{
    // Set next step
    nextStep = Step::MAIN_ACTION;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainAction()
{
    auto& player = GetCurrentPlayer();

    TaskMeta next = player.GetPolicy().Next(*this);
    if (next.GetID() == +TaskID::END_TURN)
    {
        nextStep = Step::MAIN_END;
        if (m_gameConfig.autoRun)
        {
            GameManager::ProcessNextStep(*this, nextStep);
        }
        return;
    }

    TaskMeta req = player.GetPolicy().Require(player, next.GetID());
    SizedPtr<Entity*> list = req.GetObject<SizedPtr<Entity*>>();
    switch (next.GetID())
    {
        case TaskID::ATTACK:
        {
            Entity* source = list[0];
            Entity* target = list[1];
            Task::Run(player, PlayerTasks::AttackTask(source, target));
            break;
        }
        case TaskID::PLAY_CARD:
        {
            Entity* source = list[0];
            switch (source->card.cardType)
            {
                case CardType::MINION:
                    Task::Run(player, PlayerTasks::PlayCardTask::Minion(
                                          player, source));
                    break;
                case CardType::SPELL:
                    if (list.size() == 1)
                    {
                        Task::Run(player, PlayerTasks::PlayCardTask::Spell(
                                              player, source));
                    }
                    else
                    {
                        Entity* target = list[1];
                        Task::Run(player,
                                  PlayerTasks::PlayCardTask::SpellTarget(
                                      player, source, target));
                    }
                    break;
                case CardType::WEAPON:
                    Task::Run(player, PlayerTasks::PlayCardTask::Weapon(
                                          player, source));
                    break;
                default:
                    throw std::invalid_argument(
                        "Game::MainAction() - Invalid card type!");
            }
            break;
        }
        default:
            throw std::invalid_argument(
                "Game::MainAction() - Invalid task type!");
    }

    nextStep = Step::MAIN_ACTION;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
    return;
}

void Game::MainEnd()
{
    // Set next step
    nextStep = Step::MAIN_CLEANUP;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainCleanUp()
{
    auto& curPlayer = GetCurrentPlayer();

    // Unfreeze all characters they control that are Frozen, don't have
    // summoning sickness (or do have Charge) and have not attacked that turn
    // Hero
    if (curPlayer.GetHero()->GetGameTag(GameTag::FROZEN) == 1 &&
        curPlayer.GetHero()->numAttacked == 0)
    {
        curPlayer.GetHero()->SetGameTag(GameTag::FROZEN, 0);
    }
    // Field
    for (auto& m : curPlayer.GetField().GetAllMinions())
    {
        if (m->GetGameTag(GameTag::FROZEN) == 1 && m->numAttacked == 0 &&
            m->GetGameTag(GameTag::EXHAUSTED) == 0)
        {
            m->SetGameTag(GameTag::FROZEN, 0);
        }
    }

    // Set next step
    nextStep = Step::MAIN_NEXT;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::MainNext()
{
    // Set player for next turn
    m_currentPlayer = &m_currentPlayer->GetOpponent();

    // Count next turn
    m_turn++;

    // Set next step
    nextStep = Step::MAIN_READY;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::FinalWrapUp()
{
    // Set game states according by result
    for (auto& p : m_players)
    {
        if (p.playState == +PlayState::LOSING ||
            p.playState == +PlayState::CONCEDED)
        {
            p.playState = PlayState::LOST;
            p.GetOpponent().playState = PlayState::WON;
        }
    }

    // Set next step
    nextStep = Step::FINAL_GAMEOVER;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::FinalGameOver()
{
    // Set game state to complete
    state = State::COMPLETE;
}

void Game::StartGame()
{
    // Reverse card order in deck
    if (!m_gameConfig.doShuffle)
    {
        std::reverse(m_gameConfig.player1Deck.begin(),
                     m_gameConfig.player1Deck.end());
        std::reverse(m_gameConfig.player2Deck.begin(),
                     m_gameConfig.player2Deck.end());
    }

    // Set up decks
    for (auto& card : m_gameConfig.player1Deck)
    {
        if (card.cardType == +CardType::INVALID)
        {
            continue;
        }

        Entity* entity = Entity::GetFromCard(GetPlayer1(), std::move(card));
        GetPlayer1().GetDeck().AddCard(*entity);
    }
    for (auto& card : m_gameConfig.player2Deck)
    {
        if (card.cardType == +CardType::INVALID)
        {
            continue;
        }

        Entity* entity = Entity::GetFromCard(GetPlayer2(), std::move(card));
        GetPlayer2().GetDeck().AddCard(*entity);
    }

    // Fill cards to deck
    if (m_gameConfig.doFillDecks)
    {
        for (auto& p : m_players)
        {
            for (auto& cardID : m_gameConfig.fillCardIDs)
            {
                Card card = Cards::GetInstance().FindCardByID(cardID);
                Entity* entity = Entity::GetFromCard(p, std::move(card));
                p.GetDeck().AddCard(*entity);
            }
        }
    }

    // Set game states
    state = State::RUNNING;
    for (auto& p : m_players)
    {
        p.playState = PlayState::PLAYING;
    }

    // Determine first player
    switch (m_gameConfig.startPlayer)
    {
        case PlayerType::RANDOM:
        {
            const auto val = Random::get(0, 1);
            m_firstPlayer = &m_players[val];
            break;
        }
        case PlayerType::PLAYER1:
            m_firstPlayer = &m_players[0];
            break;
        case PlayerType::PLAYER2:
            m_firstPlayer = &m_players[1];
            break;
    }
    m_currentPlayer = m_firstPlayer;

    // Set first turn
    m_turn = 1;

    // Set next step
    nextStep = Step::BEGIN_FIRST;
    if (m_gameConfig.autoRun)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}

void Game::ProcessDestroy()
{
    // Destroy weapons
    if (GetPlayer1().GetHero()->weapon != nullptr &&
        GetPlayer1().GetHero()->weapon->isDestroyed == true)
    {
        GetPlayer1().GetHero()->RemoveWeapon();
    }
    if (GetPlayer2().GetHero()->weapon != nullptr &&
        GetPlayer2().GetHero()->weapon->isDestroyed == true)
    {
        GetPlayer2().GetHero()->RemoveWeapon();
    }

    // Destroy minions
    if (deadMinions.size() > 0)
    {
        for (auto& deadMinion : deadMinions)
        {
            Minion* minion = deadMinion.second;

            // Process deathrattle tasks
            for (auto& power : minion->card.power.GetDeathrattleTask())
            {
                if (power == nullptr)
                {
                    continue;
                }

                power->Run(minion->GetOwner());
            }

            // Remove minion from battlefield
            minion->GetOwner().GetField().RemoveMinion(*minion);
            // Add minion to graveyard
            minion->GetOwner().GetGraveyard().AddCard(*minion);
        }

        deadMinions.clear();
    }
}

void Game::ProcessUntil(Step untilStep)
{
    m_gameConfig.autoRun = false;
    while (nextStep != untilStep)
    {
        GameManager::ProcessNextStep(*this, nextStep);
    }
}
}  // namespace RosettaStone
<|endoftext|>


<commit_before>// RUN: %clangxx_asan -O0 %s -o %t
// RUN: %env_asan_opts=allocator_may_return_null=0 not %run %t 2>&1 | FileCheck %s
// RUN: %env_asan_opts=allocator_may_return_null=1 %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-NULL

#include <stdio.h>
#include <stdlib.h>

extern void *aligned_alloc (size_t alignment, size_t size);

int main() {
  void *p = aligned_alloc(17, 100);
  // CHECK: ERROR: AddressSanitizer: invalid allocation alignment: 17
  // CHECK: {{#0 0x.* in .*aligned_alloc}}
  // CHECK: {{#1 0x.* in main .*aligned_alloc-alignment.cc:}}[[@LINE-3]]
  // CHECK: SUMMARY: AddressSanitizer: invalid-allocation-alignment

  printf("pointer after failed aligned_alloc: %zd\n", (size_t)p);
  // CHECK-NULL: pointer after failed aligned_alloc: 0

  return 0;
}
<commit_msg>[ASan] Disable aligned_alloc-alignment.cc on Android.<commit_after>// RUN: %clangxx_asan -O0 %s -o %t
// RUN: %env_asan_opts=allocator_may_return_null=0 not %run %t 2>&1 | FileCheck %s
// RUN: %env_asan_opts=allocator_may_return_null=1 %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-NULL

// UNSUPPORTED: android

#include <stdio.h>
#include <stdlib.h>

extern void *aligned_alloc(size_t alignment, size_t size);

int main() {
  void *p = aligned_alloc(17, 100);
  // CHECK: ERROR: AddressSanitizer: invalid allocation alignment: 17
  // CHECK: {{#0 0x.* in .*aligned_alloc}}
  // CHECK: {{#1 0x.* in main .*aligned_alloc-alignment.cc:}}[[@LINE-3]]
  // CHECK: SUMMARY: AddressSanitizer: invalid-allocation-alignment

  printf("pointer after failed aligned_alloc: %zd\n", (size_t)p);
  // CHECK-NULL: pointer after failed aligned_alloc: 0

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <hspp/Models/Entity.hpp>
#include <hspp/Models/Player.hpp>

namespace Hearthstonepp
{
Entity::Entity(Player& _owner, Card& _card) : card(_card), m_owner(&_owner)
{
    for (auto& mechanic : _card.mechanics)
    {
        Entity::SetGameTag(mechanic, 1);
    }
}

Entity::Entity(const Entity& ent) : m_owner(ent.m_owner)
{
    FreeMemory();

    card = ent.card;
    m_owner = ent.m_owner;
    m_gameTags = ent.m_gameTags;
}

Entity::Entity(Entity&& ent) noexcept : m_owner(ent.m_owner)
{
    FreeMemory();

    card = ent.card;
    m_owner = ent.m_owner;
    m_gameTags = ent.m_gameTags;
}

Entity::~Entity()
{
    FreeMemory();
}

Entity& Entity::operator=(const Entity& ent)
{
    if (this == &ent)
    {
        return *this;
    }

    FreeMemory();

    card = ent.card;
    m_owner = ent.m_owner;
    m_gameTags = ent.m_gameTags;

    return *this;
}

Entity& Entity::operator=(Entity&& ent) noexcept
{
    if (this == &ent)
    {
        return *this;
    }

    FreeMemory();

    card = ent.card;
    m_owner = ent.m_owner;
    m_gameTags = ent.m_gameTags;

    return *this;
}

Player& Entity::GetOwner() const
{
    return *m_owner;
}

void Entity::SetOwner(Player& owner)
{
    m_owner = &owner;
}

int Entity::GetGameTag(GameTag tag) const
{
    if (m_gameTags.find(tag) == m_gameTags.end())
    {
        return 0;
    }

    return m_gameTags.at(tag);
}

void Entity::SetGameTag(GameTag tag, int value)
{
    m_gameTags.insert_or_assign(tag, value);
}

void Entity::Destroy()
{
    // Do nothing
}

Entity* Entity::GetFromCard(Player& player, Card card)
{
    Entity* result;

    switch (card.cardType)
    {
        case +CardType::MINION:
            result = new Minion(player, card);
            break;
        case +CardType::SPELL:
            result = new Spell(player, card);
            break;
        case +CardType::WEAPON:
            result = new Weapon(player, card);
            break;
        default:
            throw std::invalid_argument(
                "Generic::DrawCard() - Invalid card type!");
    }

    return result;
}

void Entity::FreeMemory()
{
    m_gameTags.clear();
}
}  // namespace Hearthstonepp<commit_msg>[ci skip] refactor: Consider hero and hero power card<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <hspp/Models/Entity.hpp>
#include <hspp/Models/Player.hpp>

namespace Hearthstonepp
{
Entity::Entity(Player& _owner, Card& _card) : card(_card), m_owner(&_owner)
{
    for (auto& mechanic : _card.mechanics)
    {
        Entity::SetGameTag(mechanic, 1);
    }
}

Entity::Entity(const Entity& ent) : m_owner(ent.m_owner)
{
    FreeMemory();

    card = ent.card;
    m_owner = ent.m_owner;
    m_gameTags = ent.m_gameTags;
}

Entity::Entity(Entity&& ent) noexcept : m_owner(ent.m_owner)
{
    FreeMemory();

    card = ent.card;
    m_owner = ent.m_owner;
    m_gameTags = ent.m_gameTags;
}

Entity::~Entity()
{
    FreeMemory();
}

Entity& Entity::operator=(const Entity& ent)
{
    if (this == &ent)
    {
        return *this;
    }

    FreeMemory();

    card = ent.card;
    m_owner = ent.m_owner;
    m_gameTags = ent.m_gameTags;

    return *this;
}

Entity& Entity::operator=(Entity&& ent) noexcept
{
    if (this == &ent)
    {
        return *this;
    }

    FreeMemory();

    card = ent.card;
    m_owner = ent.m_owner;
    m_gameTags = ent.m_gameTags;

    return *this;
}

Player& Entity::GetOwner() const
{
    return *m_owner;
}

void Entity::SetOwner(Player& owner)
{
    m_owner = &owner;
}

int Entity::GetGameTag(GameTag tag) const
{
    if (m_gameTags.find(tag) == m_gameTags.end())
    {
        return 0;
    }

    return m_gameTags.at(tag);
}

void Entity::SetGameTag(GameTag tag, int value)
{
    m_gameTags.insert_or_assign(tag, value);
}

void Entity::Destroy()
{
    // Do nothing
}

Entity* Entity::GetFromCard(Player& player, Card card)
{
    Entity* result;

    switch (card.cardType)
    {
        case +CardType::HERO:
            result = new Hero(player, card);
            break;
        case +CardType::HERO_POWER:
            result = new HeroPower(player, card);
            break;
        case +CardType::MINION:
            result = new Minion(player, card);
            break;
        case +CardType::SPELL:
            result = new Spell(player, card);
            break;
        case +CardType::WEAPON:
            result = new Weapon(player, card);
            break;
        default:
            throw std::invalid_argument(
                "Generic::DrawCard() - Invalid card type!");
    }

    return result;
}

void Entity::FreeMemory()
{
    m_gameTags.clear();
}
}  // namespace Hearthstonepp<|endoftext|>


<commit_before>#include "gtest/gtest.h"

#include "IFile.h"
#include "IFolder.h"
#include "IMediaLibrary.h"

class Folders : public testing::Test
{
    public:
        static std::unique_ptr<IMediaLibrary> ml;

    protected:
        virtual void SetUp()
        {
            ml.reset( MediaLibraryFactory::create() );
            bool res = ml->initialize( "test.db" );
            ASSERT_TRUE( res );
        }

        virtual void TearDown()
        {
            ml.reset();
            unlink("test.db");
        }
};

std::unique_ptr<IMediaLibrary> Folders::ml;

TEST_F( Folders, Add )
{
    auto f = ml->addFolder( "." );
    ASSERT_NE( f, nullptr );

    auto files = ml->files();

    ASSERT_EQ( files.size(), 2u );
    ASSERT_FALSE( files[0]->isStandAlone() );
}

TEST_F( Folders, Delete )
{
    auto f = ml->addFolder( "." );
    ASSERT_NE( f, nullptr );

    auto files = ml->files();
    ASSERT_EQ( files.size(), 2u );

    ml->deleteFolder( f );

    files = ml->files();
    ASSERT_EQ( files.size(), 0u );
}

TEST_F( Folders, Load )
{
    auto f = ml->addFolder( "." );
    ASSERT_NE( f, nullptr );

    auto files = ml->files();
    ASSERT_EQ( files.size(), 2u );

    SetUp();

    files = ml->files();
    ASSERT_EQ( files.size(), 2u );
    ASSERT_FALSE( files[0]->isStandAlone() );
    ASSERT_FALSE( files[1]->isStandAlone() );
}

TEST_F( Folders, InvalidPath )
{
    auto f = ml->addFolder( "/invalid/path" );
    ASSERT_EQ( f, nullptr );

    auto files = ml->files();
    ASSERT_EQ( files.size(), 0u );
}
<commit_msg>tests: Folders deletion: Add extra checks<commit_after>#include "gtest/gtest.h"

#include "IFile.h"
#include "IFolder.h"
#include "IMediaLibrary.h"

class Folders : public testing::Test
{
    public:
        static std::unique_ptr<IMediaLibrary> ml;

    protected:
        virtual void SetUp()
        {
            ml.reset( MediaLibraryFactory::create() );
            bool res = ml->initialize( "test.db" );
            ASSERT_TRUE( res );
        }

        virtual void TearDown()
        {
            ml.reset();
            unlink("test.db");
        }
};

std::unique_ptr<IMediaLibrary> Folders::ml;

TEST_F( Folders, Add )
{
    auto f = ml->addFolder( "." );
    ASSERT_NE( f, nullptr );

    auto files = ml->files();

    ASSERT_EQ( files.size(), 2u );
    ASSERT_FALSE( files[0]->isStandAlone() );
}

TEST_F( Folders, Delete )
{
    auto f = ml->addFolder( "." );
    ASSERT_NE( f, nullptr );

    auto folderPath = f->path();

    auto files = ml->files();
    ASSERT_EQ( files.size(), 2u );

    auto filePath = files[0]->mrl();

    ml->deleteFolder( f );

    f = ml->folder( folderPath );
    ASSERT_EQ( nullptr, f );

    files = ml->files();
    ASSERT_EQ( files.size(), 0u );

    // Check the file isn't cached anymore:
    auto file = ml->file( filePath );
    ASSERT_EQ( nullptr, file );

    SetUp();

    // Recheck folder deletion from DB:
    f = ml->folder( folderPath );
    ASSERT_EQ( nullptr, f );
}

TEST_F( Folders, Load )
{
    auto f = ml->addFolder( "." );
    ASSERT_NE( f, nullptr );

    auto files = ml->files();
    ASSERT_EQ( files.size(), 2u );

    SetUp();

    files = ml->files();
    ASSERT_EQ( files.size(), 2u );
    ASSERT_FALSE( files[0]->isStandAlone() );
    ASSERT_FALSE( files[1]->isStandAlone() );
}

TEST_F( Folders, InvalidPath )
{
    auto f = ml->addFolder( "/invalid/path" );
    ASSERT_EQ( f, nullptr );

    auto files = ml->files();
    ASSERT_EQ( files.size(), 0u );
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include <map>
#include <string>

#include "atom/common/crash_reporter/crash_reporter.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "base/bind.h"
#include "native_mate/dictionary.h"

#include "atom/common/node_includes.h"

using crash_reporter::CrashReporter;

namespace mate {

template<>
struct Converter<CrashReporter::UploadReportResult> {
  static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
      const CrashReporter::UploadReportResult& reports) {
    mate::Dictionary dict(isolate, v8::Object::New(isolate));
    dict.Set("date", v8::Date::New(isolate, reports.first*1000.0));
    dict.Set("id", reports.second);
    return dict.GetHandle();
  }
};

}  // namespace mate

namespace {

void SetExtraParameter(const std::string& key, mate::Arguments* args) {
  std::string value;
  if (args->GetNext(&value))
    CrashReporter::GetInstance()->SetExtraParameter(key, value);
  else
    CrashReporter::GetInstance()->RemoveExtraParameter(key);
}

void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
                v8::Local<v8::Context> context, void* priv) {
  mate::Dictionary dict(context->GetIsolate(), exports);
  auto reporter = base::Unretained(CrashReporter::GetInstance());
  dict.SetMethod("start", base::Bind(&CrashReporter::Start, reporter));
  dict.SetMethod("setExtraParameter", &SetExtraParameter);
  dict.SetMethod("getUploadedReports",
                 base::Bind(&CrashReporter::GetUploadedReports, reporter));
  dict.SetMethod("setUploadToServer",
                 base::Bind(&CrashReporter::SetUploadToServer, reporter));
  dict.SetMethod("getUploadToServer",
                 base::Bind(&CrashReporter::GetUploadToServer, reporter));
}

}  // namespace

NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_crash_reporter, Initialize)
<commit_msg>extrapolate removeExtraParameter into new method<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include <map>
#include <string>

#include "atom/common/crash_reporter/crash_reporter.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "base/bind.h"
#include "native_mate/dictionary.h"

#include "atom/common/node_includes.h"

using crash_reporter::CrashReporter;

namespace mate {

template<>
struct Converter<CrashReporter::UploadReportResult> {
  static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
      const CrashReporter::UploadReportResult& reports) {
    mate::Dictionary dict(isolate, v8::Object::New(isolate));
    dict.Set("date", v8::Date::New(isolate, reports.first*1000.0));
    dict.Set("id", reports.second);
    return dict.GetHandle();
  }
};

}  // namespace mate

namespace {

void SetExtraParameter(const std::string& key, const std::string& value) {
  CrashReporter::GetInstance()->SetExtraParameter(key, value);
}

void RemoveExtraParameter(const std::string& key) {
  CrashReporter::GetInstance()->RemoveExtraParameter(key);
}

void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
                v8::Local<v8::Context> context, void* priv) {
  mate::Dictionary dict(context->GetIsolate(), exports);
  auto reporter = base::Unretained(CrashReporter::GetInstance());
  dict.SetMethod("start", base::Bind(&CrashReporter::Start, reporter));
  dict.SetMethod("setExtraParameter", &SetExtraParameter);
  dict.SetMethod("removeExtraParameter", &SetExtraParameter);
  dict.SetMethod("getUploadedReports",
                 base::Bind(&CrashReporter::GetUploadedReports, reporter));
  dict.SetMethod("setUploadToServer",
                 base::Bind(&CrashReporter::SetUploadToServer, reporter));
  dict.SetMethod("getUploadToServer",
                 base::Bind(&CrashReporter::GetUploadToServer, reporter));
}

}  // namespace

NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_crash_reporter, Initialize)
<|endoftext|>


<commit_before>AliAnalysisTaskHaHFECorrel *AddTaskHaHFECorrel(Double_t period, Double_t MinPtEvent, Double_t MaxPtEvent, Bool_t TRDQA, Bool_t TagEff, Bool_t RecEff, Bool_t OneTimeCheck, Bool_t CorrHadron, Bool_t CorrLP, Bool_t MCTruth,  Bool_t IsMC, Bool_t IsAOD, Bool_t IsHFE, Bool_t UseTender, Double_t EtaMax, Int_t ITSnCut, Float_t ITSSharedCluster,  Int_t TPCnCut, Int_t TPCnCutdEdx,   Double_t PhotElecPtCut, Int_t PhotElecTPCnCut,Bool_t PhotElecITSrefitCut, Int_t PhotCorrCase, Double_t InvmassCut, Int_t HTPCnCut,   Bool_t HITSrefitCut, Bool_t HTPCrefitCut, Bool_t UseITS, Double_t SigmaITScut, Double_t SigmaTOFcut, Double_t SigmaTPCcut, const char * ID="")
{
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskHaHFECorrel", "No analysis manager found.");
    return 0;
  }

  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskHaHFECorrel", "This task requires an input event handler");
    return 0x0;
  }

  TString type = mgr->GetInputEventHandler()->GetDataType();

  /*
  AliMCEventHandler* mcHand = new AliMCEventHandler();
  mgr->SetMCtruthEventHandler(mcHand);
  Bool_t MCthere=kTRUE;
  AliMCEventHandler *mcH = dynamic_cast<AliMCEventHandler*>(mgr->GetMCtruthEventHandler());
  if (!mcH) {
    MCthere=kFALSE;
  }
  */

  gROOT->LoadMacro("$ALICE_PHYSICS/PWGHF/hfe/macros/configs/pp/ConfigHaHFECorrel.C");
  AliAnalysisTaskHaHFECorrel *taskMB =
    ConfigHaHFECorrel(period, MinPtEvent, MaxPtEvent, TRDQA, TagEff, RecEff, OneTimeCheck,  CorrHadron, CorrLP, MCTruth, IsMC, IsAOD, IsHFE, UseTender,EtaMax, ITSnCut, ITSSharedCluster, TPCnCut, TPCnCutdEdx, PhotElecPtCut,PhotElecTPCnCut, PhotElecITSrefitCut, PhotCorrCase, InvmassCut,  HTPCnCut,  HITSrefitCut, HTPCrefitCut, UseITS, SigmaITScut, SigmaTOFcut, SigmaTPCcut, ID);
  if (!taskMB) {
    Error("AddTaskHaHFECorrel", "No task found.");
  }
  taskMB->SelectCollisionCandidates(AliVEvent::kINT7);

  // Load correction weights for pi0, eta
  if (IsMC) {
    TH1::AddDirectory(kFALSE);
    printf("Loading Pi0EtaCorrectionFiles\n");
    TString CorrectPi0EtaFile;
    if (!IsHFE) CorrectPi0EtaFile="alien:///alice/cern.ch/user/f/flherrma/HaHFECorrel/Pi0EtaWeightsMinBias.root";
    else if (IsHFE) CorrectPi0EtaFile="alien:///alice/cern.ch/user/f/flherrma/HaHFECorrel/Pi0EtaWeightsHFE.root";
    TFile *CorrectPi0Eta = TFile::Open(CorrectPi0EtaFile.Data());
    if (CorrectPi0Eta) {
      TH1F * Pi0W = (TH1F*)CorrectPi0Eta->Get("Pi0WeightsIncl");
      TH1F * EtaW = (TH1F*)CorrectPi0Eta->Get("EtaWeightsIncl");
      if (Pi0W) taskMB->SetPi0WeightToData(*Pi0W);
      else printf("Could not load Pi0Weights\n");
      if (EtaW)  taskMB->SetEtaWeightToData(*EtaW);
      else printf("Could not load EtaWeights\n");
    }
    else printf("Could not open Pi0Eta correction file \n");
    TH1::AddDirectory(kTRUE);
  }

  TH1::AddDirectory(kFALSE);
  printf("Loading SPDnTrAvg\n");
  TString SPDnTrFileName;
  if (IsMC) SPDnTrFileName="alien:///alice/cern.ch/user/f/flherrma/HaHFECorrel/SPDnTrAvg_MC.root";
  else SPDnTrFileName="alien:///alice/cern.ch/user/f/flherrma/HaHFECorrel/SPDnTrAvg_Data.root";
  TFile *SPDnTrFile  = TFile::Open(SPDnTrFileName.Data());
  if (SPDnTrFile) {
    TProfile* SPDnTrAvg = (TProfile*)SPDnTrFile->Get("SPDnTrAvg");
    if (SPDnTrAvg) taskMB->SetSPDnTrAvg(*SPDnTrAvg);
    else printf("Could not load SPDnTrAvg\n");
    }
    else printf("Could not open SPDnTrAvg correction file \n");
  TH1::AddDirectory(kTRUE);

  TH1::AddDirectory(kFALSE);
  printf("Loading RecEffFiles\n");
  TString RecEffFileName="alien:///alice/cern.ch/user/f/flherrma/HaHFECorrel/RecEff.root";
  TFile *RecEffFile = TFile::Open(RecEffFileName.Data());
  RecEffFile->ls();
  //RecEffFile->ls();
  if (RecEffFile) {
    TH3F * HadRecEff = (TH3F*)RecEffFile->Get("HadRecEff");
    TH2F * EleRecEff = (TH2F*)RecEffFile->Get("EleRecEff");
    if (HadRecEff) taskMB->SetHadRecEff(*HadRecEff);
    else printf("Could not load HadRecEff\n");
    if (EleRecEff) taskMB->SetEleRecEff(*EleRecEff);
    else printf("Could not load EleRecEff\n");
  }
  else printf("Could not open RecEff correction file \n");
  TH1::AddDirectory(kTRUE);

  TH1::AddDirectory(kFALSE);
  printf("Loading NonTagCorr\n");
  TString NonTagFileName="alien:///alice/cern.ch/user/f/flherrma/HaHFECorrel/NonTagCorrHist.root";
  TFile *NonTagFile = TFile::Open(NonTagFileName.Data());
  NonTagFile->ls();
  if (NonTagFile) {
    TH1F * NonTagCorr = (TH1F*)NonTagFile->Get("NonTagCorr");
    if (NonTagCorr) taskMB->SetNonTagCorr(*NonTagCorr);
    else printf("Could not load NonTagCorr\n");
  }
  else printf("Could not open NonTag correction file \n");
  TH1::AddDirectory(kTRUE);

  mgr->AddTask(taskMB);

  TString containerName1 = mgr->GetCommonFileName();
  containerName1 += ":PWGHF_HaHFECorrel_kINT7_";
  containerName1 += ID;

  TString name1 = "histMB_";
  name1 += ID;

  TString name2 = "Main_";
  name2 += ID;
  TString name3 = "LP_";
  name3 += ID;
  TString name4 = "Hadron_";
  name4 += ID;
  TString name5 = "QA_";
  name5 += ID;

  AliAnalysisDataContainer *cinput      = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput1    = mgr->CreateContainer(name1.Data(), TList::Class(),AliAnalysisManager::kOutputContainer, containerName1.Data());
  AliAnalysisDataContainer *coutputMain = mgr->CreateContainer(name2.Data(), TList::Class(),AliAnalysisManager::kOutputContainer, containerName1.Data());
  AliAnalysisDataContainer *coutputLP   = mgr->CreateContainer(name3.Data(), TList::Class(),AliAnalysisManager::kOutputContainer, containerName1.Data());
  AliAnalysisDataContainer *coutputHa   = mgr->CreateContainer(name4.Data(), TList::Class(),AliAnalysisManager::kOutputContainer, containerName1.Data());
  AliAnalysisDataContainer *coutputQA   = mgr->CreateContainer(name5.Data(), TList::Class(),AliAnalysisManager::kOutputContainer, containerName1.Data());

  mgr->ConnectInput(taskMB, 0, cinput);
  mgr->ConnectOutput(taskMB, 1, coutput1);
  mgr->ConnectOutput(taskMB, 2, coutputMain);
  mgr->ConnectOutput(taskMB, 3, coutputLP);
  mgr->ConnectOutput(taskMB, 4, coutputHa);
  mgr->ConnectOutput(taskMB, 5, coutputQA);

  return NULL;
}
<commit_msg>Root6 Transition<commit_after>#if defined(__CLING__)

  R__ADD_INCLUDE_PATH($ALICE_PHYSICS)
  #include <PWGHF/hfe/macros/configs/pp/ConfigHaHFECorrel.C>

#elif defined(__CINT__)
  // ROOT5-specific code here ...
#endif

AliAnalysisTaskHaHFECorrel *AddTaskHaHFECorrel(Double_t period, Double_t MinPtEvent, Double_t MaxPtEvent, Bool_t TRDQA, Bool_t TagEff, Bool_t RecEff, Bool_t OneTimeCheck, Bool_t CorrHadron, Bool_t CorrLP, Bool_t MCTruth,  Bool_t IsMC, Bool_t IsAOD, Bool_t IsHFE, Bool_t UseTender, Double_t EtaMax, Int_t ITSnCut, Float_t ITSSharedCluster,  Int_t TPCnCut, Int_t TPCnCutdEdx,   Double_t PhotElecPtCut, Int_t PhotElecTPCnCut,Bool_t PhotElecITSrefitCut, Int_t PhotCorrCase, Double_t InvmassCut, Int_t HTPCnCut,   Bool_t HITSrefitCut, Bool_t HTPCrefitCut, Bool_t UseITS, Double_t SigmaITScut, Double_t SigmaTOFcut, Double_t SigmaTPCcut, const char * ID="")
{
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskHaHFECorrel", "No analysis manager found.");
    return 0;
  }

  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskHaHFECorrel", "This task requires an input event handler");
    return 0x0;
  }

  TString type = mgr->GetInputEventHandler()->GetDataType();

  /*
  AliMCEventHandler* mcHand = new AliMCEventHandler();
  mgr->SetMCtruthEventHandler(mcHand);
  Bool_t MCthere=kTRUE;
  AliMCEventHandler *mcH = dynamic_cast<AliMCEventHandler*>(mgr->GetMCtruthEventHandler());
  if (!mcH) {
    MCthere=kFALSE;
  }
  */

  gROOT->LoadMacro("$ALICE_PHYSICS/PWGHF/hfe/macros/configs/pp/ConfigHaHFECorrel.C");
  AliAnalysisTaskHaHFECorrel *taskMB =
    ConfigHaHFECorrel(period, MinPtEvent, MaxPtEvent, TRDQA, TagEff, RecEff, OneTimeCheck,  CorrHadron, CorrLP, MCTruth, IsMC, IsAOD, IsHFE, UseTender,EtaMax, ITSnCut, ITSSharedCluster, TPCnCut, TPCnCutdEdx, PhotElecPtCut,PhotElecTPCnCut, PhotElecITSrefitCut, PhotCorrCase, InvmassCut,  HTPCnCut,  HITSrefitCut, HTPCrefitCut, UseITS, SigmaITScut, SigmaTOFcut, SigmaTPCcut, ID);
  if (!taskMB) {
    Error("AddTaskHaHFECorrel", "No task found.");
  }
  taskMB->SelectCollisionCandidates(AliVEvent::kINT7);

  // Load correction weights for pi0, eta
  if (IsMC) {
    TH1::AddDirectory(kFALSE);
    printf("Loading Pi0EtaCorrectionFiles\n");
    TString CorrectPi0EtaFile;
    if (!IsHFE) CorrectPi0EtaFile="alien:///alice/cern.ch/user/f/flherrma/HaHFECorrel/Pi0EtaWeightsMinBias.root";
    else if (IsHFE) CorrectPi0EtaFile="alien:///alice/cern.ch/user/f/flherrma/HaHFECorrel/Pi0EtaWeightsHFE.root";
    TFile *CorrectPi0Eta = TFile::Open(CorrectPi0EtaFile.Data());
    if (CorrectPi0Eta) {
      TH1F * Pi0W = (TH1F*)CorrectPi0Eta->Get("Pi0WeightsIncl");
      TH1F * EtaW = (TH1F*)CorrectPi0Eta->Get("EtaWeightsIncl");
      if (Pi0W) taskMB->SetPi0WeightToData(*Pi0W);
      else printf("Could not load Pi0Weights\n");
      if (EtaW)  taskMB->SetEtaWeightToData(*EtaW);
      else printf("Could not load EtaWeights\n");
    }
    else printf("Could not open Pi0Eta correction file \n");
    TH1::AddDirectory(kTRUE);
  }

  TH1::AddDirectory(kFALSE);
  printf("Loading SPDnTrAvg\n");
  TString SPDnTrFileName;
  if (IsMC) SPDnTrFileName="alien:///alice/cern.ch/user/f/flherrma/HaHFECorrel/SPDnTrAvg_MC.root";
  else SPDnTrFileName="alien:///alice/cern.ch/user/f/flherrma/HaHFECorrel/SPDnTrAvg_Data.root";
  TFile *SPDnTrFile  = TFile::Open(SPDnTrFileName.Data());
  if (SPDnTrFile) {
    TProfile* SPDnTrAvg = (TProfile*)SPDnTrFile->Get("SPDnTrAvg");
    if (SPDnTrAvg) taskMB->SetSPDnTrAvg(*SPDnTrAvg);
    else printf("Could not load SPDnTrAvg\n");
    }
    else printf("Could not open SPDnTrAvg correction file \n");
  TH1::AddDirectory(kTRUE);

  TH1::AddDirectory(kFALSE);
  printf("Loading RecEffFiles\n");
  TString RecEffFileName="alien:///alice/cern.ch/user/f/flherrma/HaHFECorrel/RecEff.root";
  TFile *RecEffFile = TFile::Open(RecEffFileName.Data());
  RecEffFile->ls();
  //RecEffFile->ls();
  if (RecEffFile) {
    TH3F * HadRecEff = (TH3F*)RecEffFile->Get("HadRecEff");
    TH2F * EleRecEff = (TH2F*)RecEffFile->Get("EleRecEff");
    if (HadRecEff) taskMB->SetHadRecEff(*HadRecEff);
    else printf("Could not load HadRecEff\n");
    if (EleRecEff) taskMB->SetEleRecEff(*EleRecEff);
    else printf("Could not load EleRecEff\n");
  }
  else printf("Could not open RecEff correction file \n");
  TH1::AddDirectory(kTRUE);

  TH1::AddDirectory(kFALSE);
  printf("Loading NonTagCorr\n");
  TString NonTagFileName="alien:///alice/cern.ch/user/f/flherrma/HaHFECorrel/NonTagCorrHist.root";
  TFile *NonTagFile = TFile::Open(NonTagFileName.Data());
  NonTagFile->ls();
  if (NonTagFile) {
    TH1F * NonTagCorr = (TH1F*)NonTagFile->Get("NonTagCorr");
    if (NonTagCorr) taskMB->SetNonTagCorr(*NonTagCorr);
    else printf("Could not load NonTagCorr\n");
  }
  else printf("Could not open NonTag correction file \n");
  TH1::AddDirectory(kTRUE);

  mgr->AddTask(taskMB);

  TString containerName1 = mgr->GetCommonFileName();
  containerName1 += ":PWGHF_HaHFECorrel_kINT7_";
  containerName1 += ID;

  TString name1 = "histMB_";
  name1 += ID;

  TString name2 = "Main_";
  name2 += ID;
  TString name3 = "LP_";
  name3 += ID;
  TString name4 = "Hadron_";
  name4 += ID;
  TString name5 = "QA_";
  name5 += ID;

  AliAnalysisDataContainer *cinput      = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput1    = mgr->CreateContainer(name1.Data(), TList::Class(),AliAnalysisManager::kOutputContainer, containerName1.Data());
  AliAnalysisDataContainer *coutputMain = mgr->CreateContainer(name2.Data(), TList::Class(),AliAnalysisManager::kOutputContainer, containerName1.Data());
  AliAnalysisDataContainer *coutputLP   = mgr->CreateContainer(name3.Data(), TList::Class(),AliAnalysisManager::kOutputContainer, containerName1.Data());
  AliAnalysisDataContainer *coutputHa   = mgr->CreateContainer(name4.Data(), TList::Class(),AliAnalysisManager::kOutputContainer, containerName1.Data());
  AliAnalysisDataContainer *coutputQA   = mgr->CreateContainer(name5.Data(), TList::Class(),AliAnalysisManager::kOutputContainer, containerName1.Data());

  mgr->ConnectInput(taskMB, 0, cinput);
  mgr->ConnectOutput(taskMB, 1, coutput1);
  mgr->ConnectOutput(taskMB, 2, coutputMain);
  mgr->ConnectOutput(taskMB, 3, coutputLP);
  mgr->ConnectOutput(taskMB, 4, coutputHa);
  mgr->ConnectOutput(taskMB, 5, coutputQA);

  return NULL;
}
<|endoftext|>


<commit_before>#include <boost/python.hpp>
#include "cimage.h"
#include "cproc.h"

using namespace boost::python;

class CimageWrapper
    : public Cimage
    , public wrapper<Cimage>
{
public:
    CimageWrapper(size_t width, size_t height)
        : Cimage(width, height)
    {

    }

public:
    void info()
    {
        override f = this->get_override("info");
        if (f)
            f();
        else
            Cimage::info();
    }
};

BOOST_PYTHON_MODULE(pymycpp)
{
    class_<CimageWrapper, boost::noncopyable>(
            "Cimage", init<size_t, size_t>())
        .def("width", &CimageWrapper::width)
        .def("height", &CimageWrapper::height)
        .def("how_many_bytes", &CimageWrapper::how_many_bytes)
        .staticmethod("how_many_bytes")
        .def("info", &CimageWrapper::info)
        ;

    class_<Cproc, boost::noncopyable>(
            "Cproc", init<>())
        .def("run", &Cproc::run)
        ;
}
<commit_msg>Issue #1: exposed stop of Cproc to Python<commit_after>#include <boost/python.hpp>
#include "cimage.h"
#include "cproc.h"

using namespace boost::python;

class CimageWrapper
    : public Cimage
    , public wrapper<Cimage>
{
public:
    CimageWrapper(size_t width, size_t height)
        : Cimage(width, height)
    {

    }

public:
    void info()
    {
        override f = this->get_override("info");
        if (f)
            f();
        else
            Cimage::info();
    }
};

BOOST_PYTHON_MODULE(pymycpp)
{
    class_<CimageWrapper, boost::noncopyable>(
            "Cimage", init<size_t, size_t>())
        .def("width", &CimageWrapper::width)
        .def("height", &CimageWrapper::height)
        .def("how_many_bytes", &CimageWrapper::how_many_bytes)
        .staticmethod("how_many_bytes")
        .def("info", &CimageWrapper::info)
        ;

    class_<Cproc, boost::noncopyable>(
            "Cproc", init<>())
        .def("run", &Cproc::run)
        .def("stop", &Cproc::stop)
        ;
}
<|endoftext|>