<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <boost/compute.hpp>
#include <algorithm>
#include <QtGui>
#include <QtOpenGL>
#include <boost/compute/command_queue.hpp>
#include <boost/compute/kernel.hpp>
#include <boost/compute/program.hpp>
#include <boost/compute/source.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/interop/opengl.hpp>
using namespace std;
namespace compute = boost::compute;

int main (int argc, char* argv[])
{
    // get the default compute device
    compute::device gpu = compute::system::default_device();

    // create a compute context and command queue
    compute::context ctx(gpu);
    compute::command_queue queue(ctx, gpu);

	//set some default values for when no commandline arguments are given
        //create accuracy variable
        int accuracy = 90;

        // create vector on device
        compute::vector<int> device_accuracy(1);

        // copy from host to device
        compute::copy(host_data,
            accuracy,
            device_accuracy.begin());

        //create polygons variable
        int polygons = 50;

        // create vector on device
        compute::vector<int> device_polygons(1);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

        //create vertices variable
        int vertices = 6;

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //read input commandline arguments
    for (int i = 1; i < argc; ++i)
    {
        if (std::string(argv[i]) == "-a")
            {
                //initialise desired accuracy variable according to commandline argument -a
                accuracy = ;

            }
        if (std::string(argv[i]) == "-p")
            {
                //initialise maximum polygons variable according to commandline argument -p
                polygons = ;

            }
        if (std::string(argv[i]) == "-v")
            {
                //initialise maximum verices per polygon variable according to commandline argument -v
                vertices = ;

            }
    }

    //create leaderDNA variable
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //create mutatedDNA variable
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //create leaderDNArender variable
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //create mutatedDNArender variable
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //create original image variable + load image into gpu memory
    if (std::string(argv[i]) == "")
            {
                //load file according to commandline argument into gpu vector

                //get x(max), y(max). (image dimensions)

                //make image vector on device
                compute::vector<float> originalimage(ctx, n);
                // copy data to the device
                compute::copy(
                    host_vector.begin(),
                    host_vector.end(),
                    device_vector.begin(),
                    queue
                );
            }

    //initialise DNA with a random seed
        //create random leader dna
        // generate random dna vector on the host
        std::vector<float> host_vector(1000000);
        std::generate(host_vector.begin(), host_vector.end(), rand);

        // create vector on the device
        compute::vector<float> device_vector(1000000, ctx);

        // copy data to the device
        compute::copy(
            host_vector.begin(),
            host_vector.end(),
            device_vector.begin(),
            queue
        );

    //run render loop until desired accuracy is reached
    while (leaderaccuracy<accuracy)
        {

            //render leader DNA to a raster image in opengl texture
            boost::compute::function<int (int)> renderDNA =
            boost::compute::make_function_from_source<int (int)>(
                "renderDNA",
                "int renderDNA(int x)
                    { //for each shape in dna
                        {
                        glEnable(GL_TEXTURE_2D);
                        glBindTexture(GL_TEXTURE_2D, gl_texture_);
                        glBegin(GL_QUADS);
                        glTexCoord2f(0, 0); glVertex2f(0, 0);
                        glTexCoord2f(0, 1); glVertex2f(0, h);
                        glTexCoord2f(1, 1); glVertex2f(w, h);
                        glTexCoord2f(1, 0); glVertex2f(w, 0);
                        glEnd();
                        } }"
            );

            //compute fitness of leader dna image
    //compute what % match DNAimage is to original image
    boost::compute::function<int (int)> computefitnesspercent =
    boost::compute::make_function_from_source<int (int)>(
        "computefitnesspercent",
        "int computefitnesspercent(int x) { //read leader dna

    //compare input dna to leader dna to find changed polygons
    compareDNA(leaderDNA,DNA);
    //create bounding box containing changed polygons

    //render leader dna within bounding box
    leaderrender = renderDNA(leaderDNA,boundx,boundy);
    //render input dna within bounding box
    inputrender = renderDNA(DNA,boundx,boundy);
    //compare leader and input dna rendered bounding boxes
    compareimage(leaderrender,inputrender);
    //returns % match }"
    );
            while ()
                {
                //mutate from the leaderDNA
                boost::compute::function<int (int)> mutateDNA =
                boost::compute::make_function_from_source<int (int)>(
                    "mutateDNA",
                    "int mutateDNA(int DNA)
                        {
                        //mutate input DNA randomly
                        mutated_shape = RANDINT(NUM_SHAPES);
                        double roulette = RANDDOUBLE(2.8);
                        double drastic = RANDDOUBLE(2);

                        // mutate color
                        if(roulette<1)
                        {
                            if(dna_test[mutated_shape].a < 0.01 // completely transparent shapes are stupid
                            || roulette<0.25)
                        {
                        if(drastic < 1)
                        {
                            dna_test[mutated_shape].a += RANDDOUBLE(0.1);
                        dna_test[mutated_shape].a = CLAMP(dna_test[mutated_shape].a, 0.0, 1.0);
                        }
                        else
                            dna_test[mutated_shape].a = RANDDOUBLE(1.0);
                        }
                        else if(roulette<0.50)
                        {
                        if(drastic < 1)
                        {
                        dna_test[mutated_shape].r += RANDDOUBLE(0.1);
                        dna_test[mutated_shape].r = CLAMP(dna_test[mutated_shape].r, 0.0, 1.0);
                        }
                        else
                        dna_test[mutated_shape].r = RANDDOUBLE(1.0);
                        }
                        else if(roulette<0.75)
                        {
                            if(drastic < 1)
                                {
                                    dna_test[mutated_shape].g += RANDDOUBLE(0.1);
                                    dna_test[mutated_shape].g = CLAMP(dna_test[mutated_shape].g, 0.0, 1.0);
                                }
                            else
                                    dna_test[mutated_shape].g = RANDDOUBLE(1.0);
                        }
                        else
                        {
                        if(drastic < 1)
                        {
                            dna_test[mutated_shape].b += RANDDOUBLE(0.1);
                            dna_test[mutated_shape].b = CLAMP(dna_test[mutated_shape].b, 0.0, 1.0);
                        }
                        else
                            dna_test[mutated_shape].b = RANDDOUBLE(1.0);
                        }
                        }

                        // mutate shape
                        else if(roulette < 2.0)
                        {
                        int point_i = RANDINT(NUM_POINTS);
                        if(roulette<1.5)
                        {
                        if(drastic < 1)
                        {
                            dna_test[mutated_shape].points[point_i].x += (int)RANDDOUBLE(WIDTH/10.0);
                            dna_test[mutated_shape].points[point_i].x = CLAMP(dna_test[mutated_shape].points[point_i].x, 0, WIDTH-1);
                        }
                        else
                            dna_test[mutated_shape].points[point_i].x = RANDDOUBLE(WIDTH);
                        }
                        else
                        {
                        if(drastic < 1)
                        {
                            dna_test[mutated_shape].points[point_i].y += (int)RANDDOUBLE(HEIGHT/10.0);
                            dna_test[mutated_shape].points[point_i].y = CLAMP(dna_test[mutated_shape].points[point_i].y, 0, HEIGHT-1);
                        }
                        else
                            dna_test[mutated_shape].points[point_i].y = RANDDOUBLE(HEIGHT);
                        }
                        }

                        // mutate stacking
                        else
                        {
                            int destination = RANDINT(NUM_SHAPES);
                            shape_t s = dna_test[mutated_shape];
                            dna_test[mutated_shape] = dna_test[destination];
                            dna_test[destination] = s;
                            return destination;
                        }
                        return -1;
                        }"
                );

    //render mutated DNA to a raster image in opengl texture
    boost::compute::function<int (int)> renderDNA =
    boost::compute::make_function_from_source<int (int)>(
        "renderDNA",
        "int renderDNA(int x)
        {
        //for each shape in dna
            {
            glEnable(GL_TEXTURE_2D);
            glBindTexture(GL_TEXTURE_2D, gl_texture_);
            glBegin(GL_QUADS);
            glTexCoord2f(0, 0); glVertex2f(0, 0);
            glTexCoord2f(0, 1); glVertex2f(0, h);
            glTexCoord2f(1, 1); glVertex2f(w, h);
            glTexCoord2f(1, 0); glVertex2f(w, 0);
            glEnd();
            } }"
    );

    //compute fitness of mutated dna image vs leader dna image
    //compute what % match DNAimage is to original image
    boost::compute::function<int (int)> computefitnesspercent =
    boost::compute::make_function_from_source<int (int)>(
        "computefitnesspercent",
        "int computefitnesspercent(int x) { //read leader dna

    //compare input dna to leader dna to find changed polygons
    compareDNA(leaderDNA,DNA);
    //create bounding box containing changed polygons

    //render leader dna within bounding box
    leaderrender = renderDNA(leaderDNA,boundx,boundy);
    //render input dna within bounding box
    inputrender = renderDNA(DNA,boundx,boundy);
    //compare leader and input dna rendered bounding boxes
    compareimage(leaderrender,inputrender);
    //returns % match }"
    );
                //check if it is fitter, if so overwrite leaderDNA
                while (fitness(mutatedDNA,originalimage) < leaderfitness))
                {
                    //overwrite leaderDNA
                    leaderDNA = mutatedDNA;

                    //save dna to disk
                    // start by writing a temp file.
                    pFile = fopen ("volution.dna.temp","w");
                    fprintf (pFile, DNA);
                    fclose (pFile);

                    // Then rename the real backup to a secondary backup.
                    result = rename("volution.dna","volution_2.dna");

                    // Then rename the temp file to the primary backup
                    result = rename("volution.dna.temp","volution.dna");

                    // Then delete the temp file
                    result = remove("volution.dna.temp");
                }
        }
    //perform final render, output svg and raster image
        //render DNA and save resulting image to disk as .svg file and raster image (.png)

    //render image from DNA
    renderDNA(DNA);
    //save resultant image to disk as svg and png files

    //render input DNA to an svg file
    boost::compute::function<int (int)> renderSVG =
    boost::compute::make_function_from_source<int (int)>(
        "renderSVG",
        "int renderSVG(int x) {

            //for each shape in dna
            {
            //add shape to svg file
            }
        }"
    );
}<commit_msg>tidying<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <boost/compute.hpp>
#include <algorithm>
#include <QtGui>
#include <QtOpenGL>
#include <boost/compute/command_queue.hpp>
#include <boost/compute/kernel.hpp>
#include <boost/compute/program.hpp>
#include <boost/compute/source.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/interop/opengl.hpp>
using namespace std;
namespace compute = boost::compute;

int main (int argc, char* argv[])
{
    // get the default compute device
    compute::device gpu = compute::system::default_device();

    // create a compute context and command queue
    compute::context ctx(gpu);
    compute::command_queue queue(ctx, gpu);

	//set some default values for when no commandline arguments are given
        //create accuracy variable
        int accuracy = 90;

        // create vector on device
        compute::vector<int> device_accuracy(1);

        // copy from host to device
        compute::copy(host_data,
            accuracy,
            device_accuracy.begin());

        //create polygons variable
        int polygons = 50;

        // create vector on device
        compute::vector<int> device_polygons(1);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

        //create vertices variable
        int vertices = 6;

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //read input commandline arguments
    for (int i = 1; i < argc; ++i)
    {
        if (std::string(argv[i]) == "-a")
            {
                //initialise desired accuracy variable according to commandline argument -a
                accuracy = ;

            }
        if (std::string(argv[i]) == "-p")
            {
                //initialise maximum polygons variable according to commandline argument -p
                polygons = ;

            }
        if (std::string(argv[i]) == "-v")
            {
                //initialise maximum verices per polygon variable according to commandline argument -v
                vertices = ;

            }
    }

    //create leaderDNA variable
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //create mutatedDNA variable
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //create leaderDNArender variable
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //create mutatedDNArender variable
        // create data array on host
        int host_data[] = { 1, 3, 5, 7, 9 };

        // create vector on device
        compute::vector<int> device_vector(5);

        // copy from host to device
        compute::copy(host_data,
            host_data + 5,
            device_vector.begin());

    //create original image variable + load image into gpu memory
    if (std::string(argv[i]) == "")
            {
                //load file according to commandline argument into gpu vector

                //get x(max), y(max). (image dimensions)

                //make image vector on device
                compute::vector<float> originalimage(ctx, n);
                // copy data to the device
                compute::copy(
                    host_vector.begin(),
                    host_vector.end(),
                    device_vector.begin(),
                    queue
                );
            }

    //initialise DNA with a random seed
        //create random leader dna
        // generate random dna vector on the host
        std::vector<float> host_vector(1000000);
        std::generate(host_vector.begin(), host_vector.end(), rand);

        // create vector on the device
        compute::vector<float> device_vector(1000000, ctx);

        // copy data to the device
        compute::copy(
            host_vector.begin(),
            host_vector.end(),
            device_vector.begin(),
            queue
        );

    //run render loop until desired accuracy is reached
    while (leaderaccuracy<accuracy)
        {

            //render leader DNA to a raster image in opengl texture
            boost::compute::function<int (int)> renderDNA =
            boost::compute::make_function_from_source<int (int)>(
                "renderDNA",
                "int renderDNA(int x)
                    { //for each shape in dna
                        {
                        glEnable(GL_TEXTURE_2D);
                        glBindTexture(GL_TEXTURE_2D, gl_texture_);
                        glBegin(GL_QUADS);
                        glTexCoord2f(0, 0); glVertex2f(0, 0);
                        glTexCoord2f(0, 1); glVertex2f(0, h);
                        glTexCoord2f(1, 1); glVertex2f(w, h);
                        glTexCoord2f(1, 0); glVertex2f(w, 0);
                        glEnd();
                        } }"
            );

            //compute fitness of leader dna image
    //compute what % match DNAimage is to original image
    boost::compute::function<int (int)> computefitnesspercent =
    boost::compute::make_function_from_source<int (int)>(
        "computefitnesspercent",
        "int computefitnesspercent(int x) { //read leader dna

    //compare input dna to leader dna to find changed polygons
    compareDNA(leaderDNA,DNA);
    //create bounding box containing changed polygons

    //render leader dna within bounding box
    leaderrender = renderDNA(leaderDNA,boundx,boundy);
    //render input dna within bounding box
    inputrender = renderDNA(DNA,boundx,boundy);
    //compare leader and input dna rendered bounding boxes
    compareimage(leaderrender,inputrender);
    //returns % match }"
    );
            while ()
                {
                //mutate from the leaderDNA
                boost::compute::function<int (int)> mutateDNA =
                boost::compute::make_function_from_source<int (int)>(
                    "mutateDNA",
                    "int mutateDNA(int DNA)
                        {
                        //mutate input DNA randomly
                        mutated_shape = RANDINT(NUM_SHAPES);
                        double roulette = RANDDOUBLE(3);

                        // mutate color
                            //randomly change mutated_shape colour
                        // mutate shape
                            //randomly move one vertex in mutated_shape
                        // mutate stacking
                            //randomly move one shape up or down stack in mutated_shape
                );

    //render mutated DNA to a raster image in opengl texture
    boost::compute::function<int (int)> renderDNA =
    boost::compute::make_function_from_source<int (int)>(
        "renderDNA",
        "int renderDNA(int x)
        {
        //for each shape in dna
            {
            glEnable(GL_TEXTURE_2D);
            glBindTexture(GL_TEXTURE_2D, gl_texture_);
            glBegin(GL_QUADS);
            glTexCoord2f(0, 0); glVertex2f(0, 0);
            glTexCoord2f(0, 1); glVertex2f(0, h);
            glTexCoord2f(1, 1); glVertex2f(w, h);
            glTexCoord2f(1, 0); glVertex2f(w, 0);
            glEnd();
            } }"
    );

    //compute fitness of mutated dna image vs leader dna image
    //compute what % match DNAimage is to original image
    boost::compute::function<int (int)> computefitnesspercent =
    boost::compute::make_function_from_source<int (int)>(
        "computefitnesspercent",
        "int computefitnesspercent(int x) { //read leader dna

    //compare input dna to leader dna to find changed polygons
    compareDNA(leaderDNA,DNA);
    //create bounding box containing changed polygons

    //render leader dna within bounding box
    leaderrender = renderDNA(leaderDNA,boundx,boundy);
    //render input dna within bounding box
    inputrender = renderDNA(DNA,boundx,boundy);
    //compare leader and input dna rendered bounding boxes
    compareimage(leaderrender,inputrender);
    //returns % match }"
    );
                //check if it is fitter, if so overwrite leaderDNA
                while (fitness(mutatedDNA,originalimage) < leaderfitness))
                {
                    //overwrite leaderDNA
                    leaderDNA = mutatedDNA;

                    //save dna to disk
                    pFile = fopen ("volution.dna","w");
                    fprintf (pFile, DNA);
                    fclose (pFile);
                }
        }
    //perform final render, output svg and raster image
        //render DNA and save resulting image to disk as .svg file and raster image (.png)

        //render image from DNA
        renderDNA(DNA);

        //save resultant image to disk as svg and png files

        //render input DNA to an svg file
        boost::compute::function<int (int)> renderSVG =
        boost::compute::make_function_from_source<int (int)>(
            "renderSVG",
            "int renderSVG(int x) {

                //for each shape in dna
                {
                    //add shape to svg file
                }
            }"
        );
}<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2117
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1270301 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/05/18 03:00:10<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2118
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>#include "Controller.hh"

#include <time.h>

#include <cmath>

#include <map>
#include <set>
#include <string>

#include "Exception.hh"

namespace aegir {
  /*
   * Controller
   */

  Controller *Controller::c_instance(0);

  Controller::Controller(): PINTracker(), c_mq_io(ZMQ::SocketType::SUB), c_ps(ProcessState::getInstance()),
			    c_mq_iocmd(ZMQ::SocketType::PUB), c_stoprecirc(false) {
    // subscribe to our publisher for IO events
    try {
      c_mq_io.connect("inproc://iopub").subscribe("");
      c_mq_iocmd.connect("inproc://iocmd");
    }
    catch (std::exception &e) {
      printf("Sub failed: %s\n", e.what());
    }
    catch (...) {
      printf("Sub failed: unknown exception\n");
    }

    c_cfg = Config::getInstance();

    // reconfigure state variables
    reconfigure();

    c_stagehandlers[ProcessState::States::Empty] = std::bind(&Controller::stageEmpty,
							     std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::Loaded] = std::bind(&Controller::stageLoaded
							      , std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::PreWait] = std::bind(&Controller::stagePreWait,
							       std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::PreHeat] = std::bind(&Controller::stagePreHeat,
							       std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::NeedMalt] = std::bind(&Controller::stageNeedMalt,
								std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::Mashing] = std::bind(&Controller::stageMashing,
							       std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::Sparging] = std::bind(&Controller::stageSparging,
								std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::PreBoil] = std::bind(&Controller::stagePreBoil,
							       std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::Hopping] = std::bind(&Controller::stageHopping,
							       std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::Cooling] = std::bind(&Controller::stageCooling,
							       std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::Finished] = std::bind(&Controller::stageFinished, std::placeholders::_1,
								std::placeholders::_2);

      // finally register to the threadmanager
    auto thrmgr = ThreadManager::getInstance();
    thrmgr->addThread("Controller", *this);
  }

  Controller::~Controller() {
  }

  Controller *Controller::getInstance() {
    if ( !c_instance) c_instance = new Controller();
    return c_instance;
  }

  void Controller::run() {
    printf("Controller started\n");

    // The main event loop
    std::shared_ptr<Message> msg;
    std::chrono::microseconds ival(20000);
    while ( c_run ) {

      // PINTracker's cycle
      startCycle();
      // read the GPIO pin channel first
      try {
	while ( (msg = c_mq_io.recv()) != nullptr ) {
	  if ( msg->type() == MessageType::PINSTATE ) {
	    auto psmsg = std::static_pointer_cast<PinStateMessage>(msg);
#ifdef AEGIR_DEBUG
	    printf("Controller: received %s:%hhu\n", psmsg->getName().c_str(), psmsg->getState());
#endif
	    try {
	      setPIN(psmsg->getName(), psmsg->getState());
	    }
	    catch (Exception &e) {
	      printf("No such pin: '%s' %lu\n", psmsg->getName().c_str(), psmsg->getName().length());
	      continue;
	    }
	  } else if ( msg->type() == MessageType::THERMOREADING ) {
	    auto trmsg = std::static_pointer_cast<ThermoReadingMessage>(msg);
#ifdef AEGIR_DEBUG
	    printf("Controller: got temp reading: %s/%f/%u\n",
		   trmsg->getName().c_str(),
		   trmsg->getTemp(),
		   trmsg->getTimestamp());
#endif
	    // add it to the process state
	    c_ps.addThermoReading(trmsg->getName(), trmsg->getTimestamp(), trmsg->getTemp());
	  } else {
	    printf("Got unhandled message type: %i\n", (int)msg->type());
	    continue;
	  }
	}
      } // End of pin and sensor readings
      catch (Exception &e) {
	printf("Exception: %s\n", e.what());
      }

      // handle the changes
      controlProcess(*this);

      // Send back the commands to IOHandler
      // PINTracker::endCycle() does this
      endCycle();

      // sleep a bit
      std::this_thread::sleep_for(ival);
    }

    printf("Controller stopped\n");
  }

  void Controller::reconfigure() {
    PINTracker::reconfigure();
    c_hecycletime = c_cfg->getHECycleTime();
  }

  void Controller::controlProcess(PINTracker &_pt) {
    ProcessState::Guard guard_ps(c_ps);
    ProcessState::States state = c_ps.getState();

    // The pump&heat control button
    if ( _pt.hasChanges() ) {
      std::shared_ptr<PINTracker::PIN> swon(_pt.getPIN("swon"));
      std::shared_ptr<PINTracker::PIN> swoff(_pt.getPIN("swoff"));
      // whether we have at least one of the controls
      if ( swon->isChanged() || swoff->isChanged() ) {
	if ( swon->getNewValue() != PINState::Off
	     && swoff->getNewValue() == PINState::Off ) {
	  setPIN("swled", PINState::On);
	  c_stoprecirc = true;
	} else if ( swon->getNewValue() == PINState::Off &&
		    swoff->getNewValue() != PINState::Off ) {
	  setPIN("swled", PINState::Off);
	  c_stoprecirc = false;
	}
      }
    } // pump&heat switch

    // state function
    auto it = c_stagehandlers.find(state);
    if ( it != c_stagehandlers.end() ) {
      it->second(this, _pt);
    } else {
      printf("No function found for state %hhu\n", state);
    }

    if ( c_stoprecirc ) {
      setPIN("rimspump", PINState::Off);
      setPIN("rimsheat", PINState::Off);
    } // stop recirc

  } // controlProcess

  void Controller::stageEmpty(PINTracker &_pt) {
    c_lastcontrol = 0;
  }

  void Controller::stageLoaded(PINTracker &_pt) {
    c_prog = c_ps.getProgram();
    // Loaded, so we should verify the timestamps
    uint32_t startat = c_ps.getStartat();
    c_preheat_phase = 0;
    c_hecycletime = c_cfg->getHECycleTime();
    // if we start immediately then jump to PreHeat
    if ( startat == 0 ) {
      c_ps.setState(ProcessState::States::PreHeat);
      c_lastcontrol = 0;
    } else {
      c_ps.setState(ProcessState::States::PreWait);
      c_lastcontrol = 0;
    }
    return;
  }

  void Controller::stagePreWait(PINTracker &_pt) {
    float mttemp = c_ps.getSensorTemp("MashTun");
    if ( mttemp == 0 ) return;
    // let's see how much time do we have till we have to start pre-heating
    uint32_t now = time(0);
    // calculate how much time
    float tempdiff = c_prog->getStartTemp() - mttemp;
    // Pre-Heat time
    // the time we have till pre-heating has to actually start
    uint32_t phtime = 0;

    if ( tempdiff > 0 )
      phtime = calcHeatTime(c_ps.getVolume(), tempdiff, 0.001*c_cfg->getHEPower());

    printf("Controller::controllProcess() td:%.2f PreHeatTime:%u\n", tempdiff, phtime);
    uint32_t startat = c_ps.getStartat();
    if ( (now + phtime*1.15) > startat ) {
      c_ps.setState(ProcessState::States::PreHeat);
      c_lastcontrol = 0;
    }
  }

  void Controller::stagePreHeat(PINTracker &_pt) {
    float mttemp = c_ps.getSensorTemp("MashTun");
    float rimstemp = c_ps.getSensorTemp("RIMS");
    float targettemp = c_prog->getStartTemp();
    float tempdiff = targettemp - mttemp;

#if 0
    int newphase = 0;

    if ( mttemp == 0 || rimstemp == 0 ) {
      newphase = 0;
    } else if ( tempdiff < 0) {
      newphase = 1;
    } else if ( tempdiff < 0.2) {
      newphase = 2;
    } else if ( tempdiff < 1 ) {
      newphase = 3;
    } else {
      newphase = 4;
    }

    printf("Controller/PreHeat: MT:%.2f RIMS:%.2f T:%.2f D:%.2f NP:%i\n",
	   mttemp, rimstemp, targettemp, tempdiff, newphase);

    if ( c_preheat_phase != newphase ) {
      c_preheat_phase = newphase;
      if ( newphase == 0 ) {
	setPIN("rimspump", PINState::Off);
	setPIN("rimsheat", PINState::Off);
      } else if ( newphase == 4 ) {
	setPIN("rimspump", PINState::On);
	setPIN("rimsheat", PINState::On);
      } else if ( newphase == 3 ) {
	setPIN("rimspump", PINState::On);
	setPIN("rimsheat", PINState::Pulsate, c_hecycletime, 0.7);
      } else if ( newphase == 2 ) {
	setPIN("rimspump", PINState::On);
	setPIN("rimsheat", PINState::Pulsate, c_hecycletime, 0.15);
      } else if ( newphase == 1 ) {
	setPIN("rimspump", PINState::On);
	setPIN("rimsheat", PINState::Off);
	c_ps.setState(ProcessState::States::NeedMalt);
	c_lastcontrol = 0;
      }
    }
#endif
    tempControl(targettemp, 6);
    if ( tempdiff < c_cfg->getTempAccuracy() ) {
	c_ps.setState(ProcessState::States::NeedMalt);
	c_lastcontrol = 0;
    }
  }

  void Controller::stageNeedMalt(PINTracker &_pt) {
    setPIN("rimsheat", PINState::Off);
    std::shared_ptr<PINTracker::PIN> buzzer(_pt.getPIN("buzzer"));

    // we keep on beeping
    if ( buzzer->getValue() != PINState::Pulsate ) {
      setPIN("buzzer", PINState::Pulsate, 2.1f, 0.4f);
    }

    // When the malts are added, temperature decreases
    // We have to heat it back up to the designated temperature
    float targettemp = c_prog->getStartTemp();
    tempControl(targettemp, c_cfg->getHeatOverhad());
  }

  void Controller::stageMashing(PINTracker &_pt) {
    printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
  }

  void Controller::stageSparging(PINTracker &_pt) {
    printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
  }

  void Controller::stagePreBoil(PINTracker &_pt) {
    printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
  }

  void Controller::stageHopping(PINTracker &_pt) {
    printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
  }

  void Controller::stageCooling(PINTracker &_pt) {
    printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
  }

  void Controller::stageFinished(PINTracker &_pt) {
    printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
  }

  void Controller::handleOutPIN(PINTracker::PIN &_pin) {
    c_mq_iocmd.send(PinStateMessage(_pin.getName(),
				    _pin.getNewValue(),
				    _pin.getNewCycletime(),
				    _pin.getNewOnratio()));
  }

  void Controller::tempControl(float _target, float _maxoverheat) {
    float mttemp = c_ps.getSensorTemp("MashTun");
    float rimstemp = c_ps.getSensorTemp("RIMS");
    float tgtdiff = _target - mttemp;
    float rimsdiff = rimstemp - _target;

    time_t now = time(0);

    if ( getPIN("rimspump")->getOldValue() != PINState::On )
      setPIN("rimspump", PINState::On);

    // only control every 3 seconds
    if ( now - c_lastcontrol < std::ceil(c_hecycletime) ) return;

    if ( tgtdiff < c_cfg->getTempAccuracy() ) {
      return;
    }
    c_lastcontrol = now;

    // coefficient based on the target temperature different
    float coeff_tgt=0;
    // coefficient based on the rims-mashtun tempdiff
    float coeff_rt=1;

    float halfpi = std::atan(INFINITY);
    if ( tgtdiff  > 0 ) coeff_tgt = std::atan(tgtdiff)/halfpi;
    if ( rimsdiff > 0 ) coeff_rt = std::atan(_maxoverheat-rimsdiff)/halfpi;
    if ( coeff_rt < 0 ) coeff_rt = 0;
    coeff_rt = std::pow(coeff_rt, 1.0/4);
    coeff_tgt = std::pow(coeff_tgt, 1.3);

    float heratio = coeff_tgt * coeff_rt;

#ifdef AEGIR_DEBUG
    printf("Controller::tempControl(): MT:%.2f RIMS:%.2f TGT:%.2f d_tgt:%.2f d_rims:%.2f c_tgt:%.2f c_rt:%.2f HEr:%.2f\n",
	   mttemp, rimstemp, _target, tgtdiff, rimsdiff, coeff_tgt, coeff_rt, heratio);
#endif

    auto pin_he = getPIN("rimsheat");
#ifdef AEGIR_DEBUG
    printf("Controller::tempControl(): rimsheat: ST:%hhu CT:%.2f OR:%.2f\n",
	   pin_he->getValue(), pin_he->getOldCycletime(), pin_he->getOldOnratio());
#endif

    if ( std::abs(pin_he->getOldOnratio()-heratio) > 0.03 )
      setPIN("rimsheat", PINState::Pulsate, c_hecycletime, heratio);
  }

  uint32_t Controller::calcHeatTime(uint32_t _vol, uint32_t _tempdiff, float _pkw) const {
    return (4.2 * _vol * _tempdiff)/_pkw;
  }
}
<commit_msg>[brewd] Controller::tempControl fixes<commit_after>#include "Controller.hh"

#include <time.h>

#include <cmath>

#include <map>
#include <set>
#include <string>

#include "Exception.hh"

namespace aegir {
  /*
   * Controller
   */

  Controller *Controller::c_instance(0);

  Controller::Controller(): PINTracker(), c_mq_io(ZMQ::SocketType::SUB), c_ps(ProcessState::getInstance()),
			    c_mq_iocmd(ZMQ::SocketType::PUB), c_stoprecirc(false) {
    // subscribe to our publisher for IO events
    try {
      c_mq_io.connect("inproc://iopub").subscribe("");
      c_mq_iocmd.connect("inproc://iocmd");
    }
    catch (std::exception &e) {
      printf("Sub failed: %s\n", e.what());
    }
    catch (...) {
      printf("Sub failed: unknown exception\n");
    }

    c_cfg = Config::getInstance();

    // reconfigure state variables
    reconfigure();

    c_stagehandlers[ProcessState::States::Empty] = std::bind(&Controller::stageEmpty,
							     std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::Loaded] = std::bind(&Controller::stageLoaded
							      , std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::PreWait] = std::bind(&Controller::stagePreWait,
							       std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::PreHeat] = std::bind(&Controller::stagePreHeat,
							       std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::NeedMalt] = std::bind(&Controller::stageNeedMalt,
								std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::Mashing] = std::bind(&Controller::stageMashing,
							       std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::Sparging] = std::bind(&Controller::stageSparging,
								std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::PreBoil] = std::bind(&Controller::stagePreBoil,
							       std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::Hopping] = std::bind(&Controller::stageHopping,
							       std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::Cooling] = std::bind(&Controller::stageCooling,
							       std::placeholders::_1, std::placeholders::_2);
    c_stagehandlers[ProcessState::States::Finished] = std::bind(&Controller::stageFinished, std::placeholders::_1,
								std::placeholders::_2);

      // finally register to the threadmanager
    auto thrmgr = ThreadManager::getInstance();
    thrmgr->addThread("Controller", *this);
  }

  Controller::~Controller() {
  }

  Controller *Controller::getInstance() {
    if ( !c_instance) c_instance = new Controller();
    return c_instance;
  }

  void Controller::run() {
    printf("Controller started\n");

    // The main event loop
    std::shared_ptr<Message> msg;
    std::chrono::microseconds ival(20000);
    while ( c_run ) {

      // PINTracker's cycle
      startCycle();
      // read the GPIO pin channel first
      try {
	while ( (msg = c_mq_io.recv()) != nullptr ) {
	  if ( msg->type() == MessageType::PINSTATE ) {
	    auto psmsg = std::static_pointer_cast<PinStateMessage>(msg);
#ifdef AEGIR_DEBUG
	    printf("Controller: received %s:%hhu\n", psmsg->getName().c_str(), psmsg->getState());
#endif
	    try {
	      setPIN(psmsg->getName(), psmsg->getState());
	    }
	    catch (Exception &e) {
	      printf("No such pin: '%s' %lu\n", psmsg->getName().c_str(), psmsg->getName().length());
	      continue;
	    }
	  } else if ( msg->type() == MessageType::THERMOREADING ) {
	    auto trmsg = std::static_pointer_cast<ThermoReadingMessage>(msg);
#ifdef AEGIR_DEBUG
	    printf("Controller: got temp reading: %s/%f/%u\n",
		   trmsg->getName().c_str(),
		   trmsg->getTemp(),
		   trmsg->getTimestamp());
#endif
	    // add it to the process state
	    c_ps.addThermoReading(trmsg->getName(), trmsg->getTimestamp(), trmsg->getTemp());
	  } else {
	    printf("Got unhandled message type: %i\n", (int)msg->type());
	    continue;
	  }
	}
      } // End of pin and sensor readings
      catch (Exception &e) {
	printf("Exception: %s\n", e.what());
      }

      // handle the changes
      controlProcess(*this);

      // Send back the commands to IOHandler
      // PINTracker::endCycle() does this
      endCycle();

      // sleep a bit
      std::this_thread::sleep_for(ival);
    }

    printf("Controller stopped\n");
  }

  void Controller::reconfigure() {
    PINTracker::reconfigure();
    c_hecycletime = c_cfg->getHECycleTime();
  }

  void Controller::controlProcess(PINTracker &_pt) {
    ProcessState::Guard guard_ps(c_ps);
    ProcessState::States state = c_ps.getState();

    // The pump&heat control button
    if ( _pt.hasChanges() ) {
      std::shared_ptr<PINTracker::PIN> swon(_pt.getPIN("swon"));
      std::shared_ptr<PINTracker::PIN> swoff(_pt.getPIN("swoff"));
      // whether we have at least one of the controls
      if ( swon->isChanged() || swoff->isChanged() ) {
	if ( swon->getNewValue() != PINState::Off
	     && swoff->getNewValue() == PINState::Off ) {
	  setPIN("swled", PINState::On);
	  c_stoprecirc = true;
	} else if ( swon->getNewValue() == PINState::Off &&
		    swoff->getNewValue() != PINState::Off ) {
	  setPIN("swled", PINState::Off);
	  c_stoprecirc = false;
	}
      }
    } // pump&heat switch

    // state function
    auto it = c_stagehandlers.find(state);
    if ( it != c_stagehandlers.end() ) {
      it->second(this, _pt);
    } else {
      printf("No function found for state %hhu\n", state);
    }

    if ( c_stoprecirc ) {
      setPIN("rimspump", PINState::Off);
      setPIN("rimsheat", PINState::Off);
    } // stop recirc

  } // controlProcess

  void Controller::stageEmpty(PINTracker &_pt) {
    c_lastcontrol = 0;
  }

  void Controller::stageLoaded(PINTracker &_pt) {
    c_prog = c_ps.getProgram();
    // Loaded, so we should verify the timestamps
    uint32_t startat = c_ps.getStartat();
    c_preheat_phase = 0;
    c_hecycletime = c_cfg->getHECycleTime();
    // if we start immediately then jump to PreHeat
    if ( startat == 0 ) {
      c_ps.setState(ProcessState::States::PreHeat);
      c_lastcontrol = 0;
    } else {
      c_ps.setState(ProcessState::States::PreWait);
      c_lastcontrol = 0;
    }
    return;
  }

  void Controller::stagePreWait(PINTracker &_pt) {
    float mttemp = c_ps.getSensorTemp("MashTun");
    if ( mttemp == 0 ) return;
    // let's see how much time do we have till we have to start pre-heating
    uint32_t now = time(0);
    // calculate how much time
    float tempdiff = c_prog->getStartTemp() - mttemp;
    // Pre-Heat time
    // the time we have till pre-heating has to actually start
    uint32_t phtime = 0;

    if ( tempdiff > 0 )
      phtime = calcHeatTime(c_ps.getVolume(), tempdiff, 0.001*c_cfg->getHEPower());

    printf("Controller::controllProcess() td:%.2f PreHeatTime:%u\n", tempdiff, phtime);
    uint32_t startat = c_ps.getStartat();
    if ( (now + phtime*1.15) > startat ) {
      c_ps.setState(ProcessState::States::PreHeat);
      c_lastcontrol = 0;
    }
  }

  void Controller::stagePreHeat(PINTracker &_pt) {
    float mttemp = c_ps.getSensorTemp("MashTun");
    float rimstemp = c_ps.getSensorTemp("RIMS");
    float targettemp = c_prog->getStartTemp();
    float tempdiff = targettemp - mttemp;

#if 0
    int newphase = 0;

    if ( mttemp == 0 || rimstemp == 0 ) {
      newphase = 0;
    } else if ( tempdiff < 0) {
      newphase = 1;
    } else if ( tempdiff < 0.2) {
      newphase = 2;
    } else if ( tempdiff < 1 ) {
      newphase = 3;
    } else {
      newphase = 4;
    }

    printf("Controller/PreHeat: MT:%.2f RIMS:%.2f T:%.2f D:%.2f NP:%i\n",
	   mttemp, rimstemp, targettemp, tempdiff, newphase);

    if ( c_preheat_phase != newphase ) {
      c_preheat_phase = newphase;
      if ( newphase == 0 ) {
	setPIN("rimspump", PINState::Off);
	setPIN("rimsheat", PINState::Off);
      } else if ( newphase == 4 ) {
	setPIN("rimspump", PINState::On);
	setPIN("rimsheat", PINState::On);
      } else if ( newphase == 3 ) {
	setPIN("rimspump", PINState::On);
	setPIN("rimsheat", PINState::Pulsate, c_hecycletime, 0.7);
      } else if ( newphase == 2 ) {
	setPIN("rimspump", PINState::On);
	setPIN("rimsheat", PINState::Pulsate, c_hecycletime, 0.15);
      } else if ( newphase == 1 ) {
	setPIN("rimspump", PINState::On);
	setPIN("rimsheat", PINState::Off);
	c_ps.setState(ProcessState::States::NeedMalt);
	c_lastcontrol = 0;
      }
    }
#endif
    tempControl(targettemp, 6);
    if ( tempdiff < 0.2 ) {
	c_ps.setState(ProcessState::States::NeedMalt);
	c_lastcontrol = 0;
    }
  }

  void Controller::stageNeedMalt(PINTracker &_pt) {
    std::shared_ptr<PINTracker::PIN> buzzer(_pt.getPIN("buzzer"));

    // we keep on beeping
    if ( buzzer->getValue() != PINState::Pulsate ) {
      setPIN("buzzer", PINState::Pulsate, 2.1f, 0.4f);
    }

    // When the malts are added, temperature decreases
    // We have to heat it back up to the designated temperature
    float targettemp = c_prog->getStartTemp();
    tempControl(targettemp, c_cfg->getHeatOverhad());
  }

  void Controller::stageMashing(PINTracker &_pt) {
    printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
  }

  void Controller::stageSparging(PINTracker &_pt) {
    printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
  }

  void Controller::stagePreBoil(PINTracker &_pt) {
    printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
  }

  void Controller::stageHopping(PINTracker &_pt) {
    printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
  }

  void Controller::stageCooling(PINTracker &_pt) {
    printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
  }

  void Controller::stageFinished(PINTracker &_pt) {
    printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
  }

  void Controller::handleOutPIN(PINTracker::PIN &_pin) {
    c_mq_iocmd.send(PinStateMessage(_pin.getName(),
				    _pin.getNewValue(),
				    _pin.getNewCycletime(),
				    _pin.getNewOnratio()));
  }

  void Controller::tempControl(float _target, float _maxoverheat) {
    float mttemp = c_ps.getSensorTemp("MashTun");
    float rimstemp = c_ps.getSensorTemp("RIMS");

    if ( mttemp == 0.0f || rimstemp == 0.0f ) return;

    float tgtdiff = _target - mttemp;
    float rimsdiff = rimstemp - _target;

    time_t now = time(0);

    if ( getPIN("rimspump")->getOldValue() != PINState::On )
      setPIN("rimspump", PINState::On);

    // only control every 3 seconds
    if ( now - c_lastcontrol < std::ceil(c_hecycletime) ) return;

    if ( tgtdiff < c_cfg->getTempAccuracy() ) {
      return;
    }
    c_lastcontrol = now;

    // coefficient based on the target temperature different
    float coeff_tgt=0;
    // coefficient based on the rims-mashtun tempdiff
    float coeff_rt=1;

    float halfpi = std::atan(INFINITY);
    if ( tgtdiff  > 0 ) coeff_tgt = std::atan(tgtdiff)/halfpi;
    if ( rimsdiff > 0 ) coeff_rt = std::atan(_maxoverheat-rimsdiff)/halfpi;
    if ( coeff_rt < 0 ) coeff_rt = 0;
    coeff_rt = std::pow(coeff_rt, 1.0/4);
    coeff_tgt = std::pow(coeff_tgt, 1.3);

    float heratio = coeff_tgt * coeff_rt;

#ifdef AEGIR_DEBUG_TEMPCTRL
    printf("Controller::tempControl(): MT:%.2f RIMS:%.2f TGT:%.2f d_tgt:%.2f d_rims:%.2f c_tgt:%.2f c_rt:%.2f HEr:%.2f\n",
	   mttemp, rimstemp, _target, tgtdiff, rimsdiff, coeff_tgt, coeff_rt, heratio);
#endif

    auto pin_he = getPIN("rimsheat");
    float absherdiff = std::abs(pin_he->getOldOnratio()-heratio);
#ifdef AEGIR_DEBUG_TEMPCTRL
    printf("Controller::tempControl(): rimsheat: ST:%hhu CT:%.2f OR:%.2f AHD:%.2f\n",
	   pin_he->getValue(), pin_he->getOldCycletime(), pin_he->getOldOnratio(), absherdiff);
#endif

    if (  absherdiff > 0.03 ) {
      setPIN("rimsheat", PINState::Pulsate, c_hecycletime, heratio);
    }
  }

  uint32_t Controller::calcHeatTime(uint32_t _vol, uint32_t _tempdiff, float _pkw) const {
    return (4.2 * _vol * _tempdiff)/_pkw;
  }
}
<|endoftext|>


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

#include "rolling_file_logger.hpp"
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <ostream>

using namespace dlib;
using namespace std;

RollingFileLogger::RollingFileLogger(std::string aName,
                                     int aMaxBackupIndex,
                                     size_t aMaxSize,
                                     RollingSchedule aSchedule)
  : mName(aName), mMaxBackupIndex(aMaxBackupIndex), mMaxSize(aMaxSize),
    mSchedule(aSchedule), mFd(0)
{
  mFileLock = new mutex();

  mFd = ::open(aName.c_str(), O_CREAT | O_APPEND | O_WRONLY, 0644);
  if (mFd < 0)
  {
    cerr << "Cannot log open file " << aName << endl;
    cerr << "Exiting...";
    exit(1);
  }
  file f(aName);
  mFile = f;
  mDirectory = get_parent_directory(mFile);
}

RollingFileLogger::~RollingFileLogger()
{
  delete mFileLock;
  ::close(mFd);
}

int RollingFileLogger::getFileAge()
{
  struct stat buffer;

  int res = ::stat(mFile.full_name().c_str(), &buffer);
  if (res < 0)
    return 0;
  else
    return time(NULL) - buffer.st_ctimespec.tv_sec;
}

const int DAY = 24 * 60 * 60;
void RollingFileLogger::write(const char *aMessage)
{
  size_t len = strlen(aMessage);

  if (mSchedule != NEVER) {
    int age = getFileAge();
    if ((mSchedule == DAILY && age > DAY) ||
        (mSchedule == WEEKLY && age > 7 * DAY))
      rollover(0);

  } else {
    file f(mFile.full_name());
    size_t size = f.size();
    if (size + len >= mMaxSize)
      rollover(size);
  }

  ::write(mFd, aMessage, len);
}

void RollingFileLogger::rollover(size_t aSize)
{
  dlib::auto_mutex M(*mFileLock);

  // File was probable rolled over... threading race.
  if (mSchedule != NEVER) {
    int age = getFileAge();
    if ((mSchedule == DAILY && age < DAY) ||
        (mSchedule == WEEKLY && age < 7 * DAY))
      return;
  } else {
    file f(mFile.full_name());
    if (f.size() < aSize)
      return;
  }

  // Close the current file
  ::close(mFd);

  // Remove the last file
  std::string name = mFile.full_name() + "." + intToString(mMaxBackupIndex);
  if (file_exists(name))
    ::remove(name.c_str());

  // Roll over old log files.
  for (int i = mMaxBackupIndex - 1; i >= 1; i--)
  {
    std::string from = mFile.full_name() + "." + intToString(i);
    if (file_exists(from))
    {
      name = mFile.full_name() + "." + intToString(i + 1);
      ::rename(from.c_str(), name.c_str());
    }
  }

  name = mFile.full_name() + ".1";
  ::rename(mFile.full_name().c_str(), name.c_str());

  // Open new log file
  mFd = ::open(mFile.full_name().c_str(), O_CREAT | O_APPEND | O_WRONLY, 0644);
  if (mFd < 0)
  {
    cerr << "Cannot log open file " << mName << endl;
    cerr << "Exiting...";
    exit(1);
  }
}<commit_msg>Windows porting.<commit_after>/*
 * Copyright Copyright 2012, System Insights, Inc.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

#include "rolling_file_logger.hpp"
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <ostream>

using namespace dlib;
using namespace std;

RollingFileLogger::RollingFileLogger(std::string aName,
                                     int aMaxBackupIndex,
                                     size_t aMaxSize,
                                     RollingSchedule aSchedule)
  : mName(aName), mMaxBackupIndex(aMaxBackupIndex), mMaxSize(aMaxSize),
    mSchedule(aSchedule), mFd(0)
{
  mFileLock = new mutex();

  mFd = ::open(aName.c_str(), O_CREAT | O_APPEND | O_WRONLY, 0644);
  if (mFd < 0)
  {
    cerr << "Cannot log open file " << aName << endl;
    cerr << "Exiting...";
    exit(1);
  }
  file f(aName);
  mFile = f;
  mDirectory = get_parent_directory(mFile);
}

RollingFileLogger::~RollingFileLogger()
{
  delete mFileLock;
  ::close(mFd);
}

int RollingFileLogger::getFileAge()
{
  struct stat buffer;

  int res = ::stat(mFile.full_name().c_str(), &buffer);
  if (res < 0)
    return 0;
  else
#ifndef WIN32
    return time(NULL) - buffer.st_ctimespec.tv_sec;
#else
    return time(NULL) - buffer.st_ctime;
#endif
}

const int DAY = 24 * 60 * 60;
void RollingFileLogger::write(const char *aMessage)
{
  size_t len = strlen(aMessage);

  if (mSchedule != NEVER) {
    int age = getFileAge();
    if ((mSchedule == DAILY && age > DAY) ||
        (mSchedule == WEEKLY && age > 7 * DAY))
      rollover(0);

  } else {
    file f(mFile.full_name());
    size_t size = f.size();
    if (size + len >= mMaxSize)
      rollover(size);
  }

  ::write(mFd, aMessage, len);
}

void RollingFileLogger::rollover(size_t aSize)
{
  dlib::auto_mutex M(*mFileLock);

  // File was probable rolled over... threading race.
  if (mSchedule != NEVER) {
    int age = getFileAge();
    if ((mSchedule == DAILY && age < DAY) ||
        (mSchedule == WEEKLY && age < 7 * DAY))
      return;
  } else {
    file f(mFile.full_name());
    if (f.size() < aSize)
      return;
  }

  // Close the current file
  ::close(mFd);

  // Remove the last file
  std::string name = mFile.full_name() + "." + intToString(mMaxBackupIndex);
  if (file_exists(name))
    ::remove(name.c_str());

  // Roll over old log files.
  for (int i = mMaxBackupIndex - 1; i >= 1; i--)
  {
    std::string from = mFile.full_name() + "." + intToString(i);
    if (file_exists(from))
    {
      name = mFile.full_name() + "." + intToString(i + 1);
      ::rename(from.c_str(), name.c_str());
    }
  }

  name = mFile.full_name() + ".1";
  ::rename(mFile.full_name().c_str(), name.c_str());

  // Open new log file
  mFd = ::open(mFile.full_name().c_str(), O_CREAT | O_APPEND | O_WRONLY, 0644);
  if (mFd < 0)
  {
    cerr << "Cannot log open file " << mName << endl;
    cerr << "Exiting...";
    exit(1);
  }
}<|endoftext|>


<commit_before>#ifndef VFRAME_NO_3D
	#ifndef NO_GLEW
	#include <GL/glew.h>
	#endif
#endif

#include "VGame.h"
#include "VCamera.h"
#include "VGlobal.h"
#include "VTimer.h"
#include "VPostEffect.h"
#include "VState.h"

#include <SFML/System/Clock.hpp>

VGame::~VGame()
{
	if (!cleaned)
	{
		Cleanup();
	}
}

int VGame::Init()
{
	VBase::VLog("Calling Init()");

	try
	{
		#ifndef VFRAME_NO_3D
			#ifndef NO_GLEW
			glewExperimental = GL_TRUE;
			if (glewInit() != GLEW_OK)
				return 2;
			#endif
		#endif

		if (!VGlobal::p()->App->isOpen())
			return 3;

		renderTarget = std::make_unique<sf::RenderTexture>();
		if (!renderTarget->create(VGlobal::p()->Width, VGlobal::p()->Height))
			return 4;

		VGlobal::p()->WorldBounds = sf::FloatRect(0, 0, static_cast<float>(VGlobal::p()->Width), static_cast<float>(VGlobal::p()->Height));
		VGlobal::p()->App->requestFocus();
		VCameraList::Default = renderTarget->getDefaultView();

		vertexArray.resize(4);
		vertexArray.setPrimitiveType(sf::Quads);
		vertexArray[0] = sf::Vertex(sf::Vector2f(), sf::Color::White, sf::Vector2f());
		vertexArray[1] = sf::Vertex(sf::Vector2f(VGlobal::p()->WorldBounds.width, 0.0f),
			sf::Color::White,
			sf::Vector2f(VGlobal::p()->WorldBounds.width, 0.0f));
		vertexArray[2] = sf::Vertex(sf::Vector2f(VGlobal::p()->WorldBounds.width, VGlobal::p()->WorldBounds.height),
			sf::Color::White,
			sf::Vector2f(VGlobal::p()->WorldBounds.width, VGlobal::p()->WorldBounds.height));
		vertexArray[3] = sf::Vertex(sf::Vector2f(0.0f, VGlobal::p()->WorldBounds.height),
			sf::Color::White,
			sf::Vector2f(0.0f, VGlobal::p()->WorldBounds.height));

		ResizeCheck();
	}
	catch (int e)
	{
		return e;
	}

	return EXIT_SUCCESS;
}

int VGame::Cleanup()
{
	VBase::VLog("Calling Cleanup()");

	try
	{
		VGlobal::Cleanup();
		cleaned = true;
	}
	catch (int e)
	{
		VBase::VLog("Cleanup error: %d", e);
		return e;
	}

	return EXIT_SUCCESS;
}

int VGame::Run(const sf::String& title, VState* initialState, int windowwidth, int windowheight, float fps, int flags, const sf::ContextSettings& settings)
{
	return Run(title, initialState, windowwidth, windowheight, windowwidth, windowheight, fps, flags, settings);
}

int VGame::Run(const sf::String& title, VState* initialState, int windowwidth, int windowheight, int screenwidth, int screenheight, float fps, int flags, const sf::ContextSettings& settings)
{
	VGlobal::p()->Width = screenwidth;
	VGlobal::p()->Height = screenheight;
	VGlobal::p()->FPS = fps;
	VGlobal::p()->WindowStyle = flags;
	VGlobal::p()->ContextSettings = settings;
	VGlobal::p()->RenderState = sf::RenderStates::Default;

	VGlobal::p()->App->create(sf::VideoMode(windowwidth, windowheight), title, flags, settings);

	VBase::VLog("Welcome to the ViglanteFramework - Version: %s ", VFRAME_VERSION);

	int error = 0;
	if ((error = Init()))
	{
		VBase::VLogError("Error in Init(): %d", error);
		return error;
	}

	#ifndef VFRAME_NO_3D
		#ifndef NO_GLEW
		VBase::VLog("OpenGL Version: %s", glGetString(GL_VERSION));
		#endif
	#endif
	VBase::VLog("\nStarting Game: %s", title.toUtf8().c_str());

	initialState->DefaultCamera->Reset();
	VGlobal::p()->ChangeState(initialState);
	VGlobal::p()->ChangeState(nullptr);

	sf::Clock clock;
	VBase::VLog("Initialisation finished");

	try
	{
		double end = 0.0;

		while (VGlobal::p()->IsRunning())
		{
			VGlobal::p()->Async->ProcessSyncRequests();

			float dt = 1.0f / VGlobal::p()->FPS;
			double start = clock.getElapsedTime().asSeconds();
			double passed = start - end;
			float frameRate = (float)(1.0 / passed);
			frameRate = frameRate < 12 ? 12 : frameRate;
			float deltaScale = (VGlobal::p()->FPS / frameRate);
			end = start;

			if (VGlobal::p()->IfChangedState)
			{
				VGlobal::p()->ChangeState(nullptr);
			}

			if (VGlobal::p()->IfPushedState)
			{
				VGlobal::p()->PushState(nullptr);
			}

			HandleEvents();

			if (focused)
			{
				Update(dt * deltaScale * VGlobal::p()->TimeScale);
			}

			if (focused && !VGlobal::p()->IfChangedState && !VGlobal::p()->IfPushedState)
			{
				PreRender();
				for (unsigned int c = 0; c < VGlobal::p()->CurrentState()->Cameras.size(); c++)
				{
					Render(VGlobal::p()->CurrentState()->Cameras[c]);
				}
				PostRender();
			}
		}
	}
	catch (int e)
	{
		return e;
	}

	if ((error = Cleanup()))
	{
		VBase::VLogError("Error in Cleanup(): %d", error);
		return error;
	}

	VBase::VLog("Cleanup Successful");

	return EXIT_SUCCESS;
}

void VGame::HandleEvents()
{
	sf::Event event;
	while (VGlobal::p()->App->pollEvent(event))
	{
		if (VGlobal::p()->CurrentState()->SubState)
		{
			VGlobal::p()->CurrentState()->SubState->HandleEvents(event);
		}

		VGlobal::p()->CurrentState()->HandleEvents(event);
		if (event.type == sf::Event::Closed)
		{
			VGlobal::p()->Exit();
		}
		if (VGlobal::p()->FocusPause)
		{
			if (event.type == sf::Event::LostFocus)
			{
				focused = false;
			}
			if (event.type == sf::Event::GainedFocus)
			{
				focused = true;
			}
		}
	}
	ResizeCheck();
}

void VGame::ResizeCheck()
{
	sf::Vector2u windowSize = VGlobal::p()->App->getSize();

	if (windowSize.x != VGlobal::p()->WindowWidth || windowSize.y != VGlobal::p()->WindowHeight)
	{
		VGlobal::p()->WindowWidth = windowSize.x;
		VGlobal::p()->WindowHeight = windowSize.y;
		VGlobal::p()->App->setView(sf::View(sf::FloatRect(0, 0, (float)windowSize.x, (float)windowSize.y)));

		float sx = VGlobal::p()->App->getSize().x / (float)VGlobal::p()->Width;
		float sy = VGlobal::p()->App->getSize().y / (float)VGlobal::p()->Height;
		float scale = std::fminf(sx, sy);

		float scaleW = VGlobal::p()->Width * scale;
		float scaleH = VGlobal::p()->Height * scale;
		float scaleX = (VGlobal::p()->App->getSize().x - scaleW) / 2;
		float scaleY = (VGlobal::p()->App->getSize().y - scaleH) / 2;
		vertexArray[0].position = sf::Vector2f(scaleX, scaleY);
		vertexArray[1].position = sf::Vector2f(scaleX + scaleW, scaleY);
		vertexArray[2].position = sf::Vector2f(scaleX + scaleW, scaleY + scaleH);
		vertexArray[3].position = sf::Vector2f(scaleX, scaleY + scaleH);
		VGlobal::p()->ViewportOffset = vertexArray[0].position;
	}
}

void VGame::Update(float dt)
{
	if (VTimeManager::AnyActiveTimers())
	{
		VTimeManager::p()->Update(dt);
	}

	VGlobal::p()->Input->Update(dt);

	if (VGlobal::p()->CurrentState()->active)
	{
		VGlobal::p()->CurrentState()->Update(dt);
	}

	VGlobal::p()->CurrentState()->ResetSubState();

	if (VGlobal::p()->CurrentState()->SubState)
	{
		VGlobal::p()->CurrentState()->SubState->Update(dt);
	}

	for (unsigned int c = 0; c < VGlobal::p()->CurrentState()->Cameras.size(); c++)
	{
		VGlobal::p()->CurrentState()->Cameras[c]->Update(dt);
	}

	VGlobal::p()->Music->Update(dt);

	if (VGlobal::p()->PostProcess != nullptr && VPostEffectBase::isSupported())
	{
		VGlobal::p()->PostProcess->Update(dt);
	}
}

void VGame::PreRender()
{
	renderTarget->clear(VGlobal::p()->BackgroundColor);
	VGlobal::p()->App->clear();
}

void VGame::Render(VCamera* camera)
{
	if (!camera->Active)
		return;

	renderTarget->setView(camera->GetView());
	VState* currentState = VGlobal::p()->CurrentState();

	if (currentState && currentState->visible)
		currentState->Draw(*renderTarget);

	if (currentState->SubState && currentState->SubState->visible)
		currentState->SubState->Draw(*renderTarget);

	camera->Render(*renderTarget);
}

void VGame::PostRender()
{
	renderTarget->display();
	if (renderTarget->isSmooth() != VGlobal::p()->Antialiasing)
	{
		renderTarget->setSmooth(VGlobal::p()->Antialiasing);
	}

	sf::RenderWindow* app = VGlobal::p()->App.get();

	app->setActive(true);
	app->setVerticalSyncEnabled(VGlobal::p()->VSync);

	sf::View view = app->getView();

	VGlobal::p()->RenderState.texture = &renderTarget->getTexture();
	if (VGlobal::p()->PostProcess == nullptr || !VPostEffectBase::isSupported())
	{
		view.setViewport(sf::FloatRect(0, 0, 1, 1));
		app->draw(vertexArray, VGlobal::p()->RenderState);
	}
	else
	{
		sf::Vector2f position = VGlobal::p()->ViewportOffset;
		sf::Vector2f size = view.getSize();

		float left = position.x / size.x;
		float top = position.y / size.y;
		view.setViewport(sf::FloatRect(left, top, 1 - (left * 2), 1 - (top * 2)));

		VGlobal::p()->PostProcess->Apply(renderTarget->getTexture(), *app);
	}

	app->setView(view);

	VState* currentState = VGlobal::p()->CurrentState();

	if (currentState && currentState->visible)
		currentState->PostDraw(*VGlobal::p()->App);

	if (currentState->SubState && currentState->SubState->visible)
		currentState->SubState->PostDraw(*VGlobal::p()->App);

	app->display();
}
<commit_msg>Doubles to floats<commit_after>#ifndef VFRAME_NO_3D
	#ifndef NO_GLEW
	#include <GL/glew.h>
	#endif
#endif

#include "VGame.h"
#include "VCamera.h"
#include "VGlobal.h"
#include "VTimer.h"
#include "VPostEffect.h"
#include "VState.h"

#include <SFML/System/Clock.hpp>

VGame::~VGame()
{
	if (!cleaned)
	{
		Cleanup();
	}
}

int VGame::Init()
{
	VBase::VLog("Calling Init()");

	try
	{
		#ifndef VFRAME_NO_3D
			#ifndef NO_GLEW
			glewExperimental = GL_TRUE;
			if (glewInit() != GLEW_OK)
				return 2;
			#endif
		#endif

		if (!VGlobal::p()->App->isOpen())
			return 3;

		renderTarget = std::make_unique<sf::RenderTexture>();
		if (!renderTarget->create(VGlobal::p()->Width, VGlobal::p()->Height))
			return 4;

		VGlobal::p()->WorldBounds = sf::FloatRect(0, 0, static_cast<float>(VGlobal::p()->Width), static_cast<float>(VGlobal::p()->Height));
		VGlobal::p()->App->requestFocus();
		VCameraList::Default = renderTarget->getDefaultView();

		vertexArray.resize(4);
		vertexArray.setPrimitiveType(sf::Quads);
		vertexArray[0] = sf::Vertex(sf::Vector2f(), sf::Color::White, sf::Vector2f());
		vertexArray[1] = sf::Vertex(sf::Vector2f(VGlobal::p()->WorldBounds.width, 0.0f),
			sf::Color::White,
			sf::Vector2f(VGlobal::p()->WorldBounds.width, 0.0f));
		vertexArray[2] = sf::Vertex(sf::Vector2f(VGlobal::p()->WorldBounds.width, VGlobal::p()->WorldBounds.height),
			sf::Color::White,
			sf::Vector2f(VGlobal::p()->WorldBounds.width, VGlobal::p()->WorldBounds.height));
		vertexArray[3] = sf::Vertex(sf::Vector2f(0.0f, VGlobal::p()->WorldBounds.height),
			sf::Color::White,
			sf::Vector2f(0.0f, VGlobal::p()->WorldBounds.height));

		ResizeCheck();
	}
	catch (int e)
	{
		return e;
	}

	return EXIT_SUCCESS;
}

int VGame::Cleanup()
{
	VBase::VLog("Calling Cleanup()");

	try
	{
		VGlobal::Cleanup();
		cleaned = true;
	}
	catch (int e)
	{
		VBase::VLog("Cleanup error: %d", e);
		return e;
	}

	return EXIT_SUCCESS;
}

int VGame::Run(const sf::String& title, VState* initialState, int windowwidth, int windowheight, float fps, int flags, const sf::ContextSettings& settings)
{
	return Run(title, initialState, windowwidth, windowheight, windowwidth, windowheight, fps, flags, settings);
}

int VGame::Run(const sf::String& title, VState* initialState, int windowwidth, int windowheight, int screenwidth, int screenheight, float fps, int flags, const sf::ContextSettings& settings)
{
	VGlobal::p()->Width = screenwidth;
	VGlobal::p()->Height = screenheight;
	VGlobal::p()->FPS = fps;
	VGlobal::p()->WindowStyle = flags;
	VGlobal::p()->ContextSettings = settings;
	VGlobal::p()->RenderState = sf::RenderStates::Default;

	VGlobal::p()->App->create(sf::VideoMode(windowwidth, windowheight), title, flags, settings);

	VBase::VLog("Welcome to the ViglanteFramework - Version: %s ", VFRAME_VERSION);

	int error = 0;
	if ((error = Init()))
	{
		VBase::VLogError("Error in Init(): %d", error);
		return error;
	}

	#ifndef VFRAME_NO_3D
		#ifndef NO_GLEW
		VBase::VLog("OpenGL Version: %s", glGetString(GL_VERSION));
		#endif
	#endif
	VBase::VLog("\nStarting Game: %s", title.toUtf8().c_str());

	initialState->DefaultCamera->Reset();
	VGlobal::p()->ChangeState(initialState);
	VGlobal::p()->ChangeState(nullptr);

	sf::Clock clock;
	VBase::VLog("Initialisation finished");

	try
	{
		float dt = 1.0f / VGlobal::p()->FPS;
		float end = 0.0f;
		float frameDelay = dt;

		while (VGlobal::p()->IsRunning())
		{
			VGlobal::p()->Async->ProcessSyncRequests();

			float start = clock.getElapsedTime().asSeconds();
			float passed = start - end;
			float frameRate = 1.0f / passed;
			frameRate = frameRate < 12 ? 12 : frameRate;
			float deltaScale = (VGlobal::p()->FPS / frameRate);
			end = start;

			frameDelay += passed;

			if (VGlobal::p()->IfChangedState)
			{
				VGlobal::p()->ChangeState(nullptr);
			}

			if (VGlobal::p()->IfPushedState)
			{
				VGlobal::p()->PushState(nullptr);
			}

			HandleEvents();

			if (focused)
			{
				Update(dt * deltaScale * VGlobal::p()->TimeScale);

				if (!VGlobal::p()->IfChangedState && !VGlobal::p()->IfPushedState && frameDelay >= dt)
				{
					PreRender();
					for (unsigned int c = 0; c < VGlobal::p()->CurrentState()->Cameras.size(); c++)
					{
						Render(VGlobal::p()->CurrentState()->Cameras[c]);
					}
					PostRender();
					frameDelay = 0.0f;
				}
			}
		}
	}
	catch (int e)
	{
		return e;
	}

	if ((error = Cleanup()))
	{
		VBase::VLogError("Error in Cleanup(): %d", error);
		return error;
	}

	VBase::VLog("Cleanup Successful");

	return EXIT_SUCCESS;
}

void VGame::HandleEvents()
{
	sf::Event event;
	while (VGlobal::p()->App->pollEvent(event))
	{
		if (VGlobal::p()->CurrentState()->SubState)
		{
			VGlobal::p()->CurrentState()->SubState->HandleEvents(event);
		}

		VGlobal::p()->CurrentState()->HandleEvents(event);
		if (event.type == sf::Event::Closed)
		{
			VGlobal::p()->Exit();
		}
		if (VGlobal::p()->FocusPause)
		{
			if (event.type == sf::Event::LostFocus)
			{
				focused = false;
			}
			if (event.type == sf::Event::GainedFocus)
			{
				focused = true;
			}
		}
	}
	ResizeCheck();
}

void VGame::ResizeCheck()
{
	sf::Vector2u windowSize = VGlobal::p()->App->getSize();

	if (windowSize.x != VGlobal::p()->WindowWidth || windowSize.y != VGlobal::p()->WindowHeight)
	{
		VGlobal::p()->WindowWidth = windowSize.x;
		VGlobal::p()->WindowHeight = windowSize.y;
		VGlobal::p()->App->setView(sf::View(sf::FloatRect(0, 0, (float)windowSize.x, (float)windowSize.y)));

		float sx = VGlobal::p()->App->getSize().x / (float)VGlobal::p()->Width;
		float sy = VGlobal::p()->App->getSize().y / (float)VGlobal::p()->Height;
		float scale = std::fminf(sx, sy);

		float scaleW = VGlobal::p()->Width * scale;
		float scaleH = VGlobal::p()->Height * scale;
		float scaleX = (VGlobal::p()->App->getSize().x - scaleW) / 2;
		float scaleY = (VGlobal::p()->App->getSize().y - scaleH) / 2;
		vertexArray[0].position = sf::Vector2f(scaleX, scaleY);
		vertexArray[1].position = sf::Vector2f(scaleX + scaleW, scaleY);
		vertexArray[2].position = sf::Vector2f(scaleX + scaleW, scaleY + scaleH);
		vertexArray[3].position = sf::Vector2f(scaleX, scaleY + scaleH);
		VGlobal::p()->ViewportOffset = vertexArray[0].position;
	}
}

void VGame::Update(float dt)
{
	if (VTimeManager::AnyActiveTimers())
	{
		VTimeManager::p()->Update(dt);
	}

	VGlobal::p()->Input->Update(dt);

	if (VGlobal::p()->CurrentState()->active)
	{
		VGlobal::p()->CurrentState()->Update(dt);
	}

	VGlobal::p()->CurrentState()->ResetSubState();

	if (VGlobal::p()->CurrentState()->SubState)
	{
		VGlobal::p()->CurrentState()->SubState->Update(dt);
	}

	for (unsigned int c = 0; c < VGlobal::p()->CurrentState()->Cameras.size(); c++)
	{
		VGlobal::p()->CurrentState()->Cameras[c]->Update(dt);
	}

	VGlobal::p()->Music->Update(dt);

	if (VGlobal::p()->PostProcess != nullptr && VPostEffectBase::isSupported())
	{
		VGlobal::p()->PostProcess->Update(dt);
	}
}

void VGame::PreRender()
{
	renderTarget->clear(VGlobal::p()->BackgroundColor);
	VGlobal::p()->App->clear();
}

void VGame::Render(VCamera* camera)
{
	if (!camera->Active)
		return;

	renderTarget->setView(camera->GetView());
	VState* currentState = VGlobal::p()->CurrentState();

	if (currentState && currentState->visible)
		currentState->Draw(*renderTarget);

	if (currentState->SubState && currentState->SubState->visible)
		currentState->SubState->Draw(*renderTarget);

	camera->Render(*renderTarget);
}

void VGame::PostRender()
{
	renderTarget->display();
	if (renderTarget->isSmooth() != VGlobal::p()->Antialiasing)
	{
		renderTarget->setSmooth(VGlobal::p()->Antialiasing);
	}

	sf::RenderWindow* app = VGlobal::p()->App.get();

	app->setActive(true);
	app->setVerticalSyncEnabled(VGlobal::p()->VSync);

	sf::View view = app->getView();

	VGlobal::p()->RenderState.texture = &renderTarget->getTexture();
	if (VGlobal::p()->PostProcess == nullptr || !VPostEffectBase::isSupported())
	{
		view.setViewport(sf::FloatRect(0, 0, 1, 1));
		app->draw(vertexArray, VGlobal::p()->RenderState);
	}
	else
	{
		sf::Vector2f position = VGlobal::p()->ViewportOffset;
		sf::Vector2f size = view.getSize();

		float left = position.x / size.x;
		float top = position.y / size.y;
		view.setViewport(sf::FloatRect(left, top, 1 - (left * 2), 1 - (top * 2)));

		VGlobal::p()->PostProcess->Apply(renderTarget->getTexture(), *app);
	}

	app->setView(view);

	VState* currentState = VGlobal::p()->CurrentState();

	if (currentState && currentState->visible)
		currentState->PostDraw(*VGlobal::p()->App);

	if (currentState->SubState && currentState->SubState->visible)
		currentState->SubState->PostDraw(*VGlobal::p()->App);

	app->display();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <boost/program_options.hpp>

#include "configuration.h"

using namespace std;

namespace Gps2EventDb {

    using namespace boost::program_options;

    boost::program_options::variables_map &getConfig()
    {
        static boost::program_options::variables_map theOneAndOnlyVariableMapInstance;
        return theOneAndOnlyVariableMapInstance;
    }

    void dumpConfiguration(ostream &out)
    {
        // Print out the configuration information.
        variables_map &config=getConfig();
        out << endl << "Using this runtime configuration: " << endl;
        for (variables_map::const_iterator i=config.begin(); i!=config.end(); ++i) {
            // Annoying that we have to iterate over types.
            if (i->second.value().type()==typeid(string))
                out << i->first << " = " << i->second.as<string>() << endl;
            else if (i->second.value().type()==typeid(int))
                out << i->first << " = " << i->second.as<int>() << endl;
            else if (i->second.value().type()==typeid(unsigned int))
                out << i->first << " = " << i->second.as<unsigned int>() << endl;
            else if (i->second.value().type()==typeid(double))
                out << i->first << " = " << i->second.as<double>() << endl;
            else if (i->second.value().type()==typeid(float))
                out << i->first << " = " << i->second.as<float>() << endl;
            else if (i->second.value().type()==typeid(time_t))
                out << i->first << " = " << i->second.as<time_t>() << endl;
            else if (i->second.value().type()==typeid(bool))
                out << i->first << " = " << (i->second.as<bool>()==true ? "true" : "false") << endl;
            else
                out << i->first << " = " << "[I don't know how to display this type. Ask Geoff to add it.]" << endl;
        }
        out << endl;
    }

    bool loadConfiguration(int argc, char **argv)
    {
        string binName=basename(argv[0]);
        const unsigned int lineLen=120;

        // Declare a group of options that will be
        // allowed only on command line
        options_description generic("Command line only options", lineLen);
        generic.add_options()
            ("help,h", "Show help message.")
            ("configFile,c", value<string>()->default_value(binName + ".cfg"), "The location of the configuration file.")
            ;

        options_description config("Functional Options. (Allowed on command line or in configuration file.)", lineLen);
        config.add_options()
            ("radius,r", value<double>()->default_value(180.0), "The radius, in meters, in which nodes can hear each other")
            ("scenario,s", value<string>(), "The MANE scenario file to use. Required arguement.")
            ("database,d", value<string>()->default_value("event.db"), "The name of the created watcher event datbase.")
            ;

        variables_map &vm=getConfig();
        options_description cmdline_options(lineLen);
        options_description config_file_options(lineLen);

        // Try to sort out all options and complain/exit on error
        try {
            cmdline_options.add(generic).add(config);
            config_file_options.add(config);
            store(parse_command_line(argc, argv, cmdline_options), vm);
            ifstream confFile(vm["configFile"].as<string>().c_str());
            if (confFile.is_open()) {
                store(parse_config_file(confFile, config_file_options), vm);
                confFile.close();
            }
        }
        catch (const invalid_option_value &e) {
            cerr << "Option Error - " << e.what() << endl;
            exit(EXIT_FAILURE);
        }
        catch (const invalid_command_line_syntax &e) {
            cerr << "Syntax Error - " << e.what() << endl;
            exit(EXIT_FAILURE);
        }

        notify(vm);

        if (vm.count("help")) {
            cerr << cmdline_options << endl;
            return false;
        }
        if (!vm.count("scenario")) {
            cerr << cmdline_options << endl;
            cerr << endl << "scenario is a required argument." << endl << endl;
            exit(EXIT_FAILURE);
        }
        return true;
    }
}
<commit_msg>fixed mispleling.<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <boost/program_options.hpp>

#include "configuration.h"

using namespace std;

namespace Gps2EventDb {

    using namespace boost::program_options;

    boost::program_options::variables_map &getConfig()
    {
        static boost::program_options::variables_map theOneAndOnlyVariableMapInstance;
        return theOneAndOnlyVariableMapInstance;
    }

    void dumpConfiguration(ostream &out)
    {
        // Print out the configuration information.
        variables_map &config=getConfig();
        out << endl << "Using this runtime configuration: " << endl;
        for (variables_map::const_iterator i=config.begin(); i!=config.end(); ++i) {
            // Annoying that we have to iterate over types.
            if (i->second.value().type()==typeid(string))
                out << i->first << " = " << i->second.as<string>() << endl;
            else if (i->second.value().type()==typeid(int))
                out << i->first << " = " << i->second.as<int>() << endl;
            else if (i->second.value().type()==typeid(unsigned int))
                out << i->first << " = " << i->second.as<unsigned int>() << endl;
            else if (i->second.value().type()==typeid(double))
                out << i->first << " = " << i->second.as<double>() << endl;
            else if (i->second.value().type()==typeid(float))
                out << i->first << " = " << i->second.as<float>() << endl;
            else if (i->second.value().type()==typeid(time_t))
                out << i->first << " = " << i->second.as<time_t>() << endl;
            else if (i->second.value().type()==typeid(bool))
                out << i->first << " = " << (i->second.as<bool>()==true ? "true" : "false") << endl;
            else
                out << i->first << " = " << "[I don't know how to display this type. Ask Geoff to add it.]" << endl;
        }
        out << endl;
    }

    bool loadConfiguration(int argc, char **argv)
    {
        string binName=basename(argv[0]);
        const unsigned int lineLen=120;

        // Declare a group of options that will be
        // allowed only on command line
        options_description generic("Command line only options", lineLen);
        generic.add_options()
            ("help,h", "Show help message.")
            ("configFile,c", value<string>()->default_value(binName + ".cfg"), "The location of the configuration file.")
            ;

        options_description config("Functional Options. (Allowed on command line or in configuration file.)", lineLen);
        config.add_options()
            ("radius,r", value<double>()->default_value(180.0), "The radius, in meters, in which nodes can hear each other")
            ("scenario,s", value<string>(), "The MANE scenario file to use. Required argument.")
            ("database,d", value<string>()->default_value("event.db"), "The name of the created watcher event datbase.")
            ;

        variables_map &vm=getConfig();
        options_description cmdline_options(lineLen);
        options_description config_file_options(lineLen);

        // Try to sort out all options and complain/exit on error
        try {
            cmdline_options.add(generic).add(config);
            config_file_options.add(config);
            store(parse_command_line(argc, argv, cmdline_options), vm);
            ifstream confFile(vm["configFile"].as<string>().c_str());
            if (confFile.is_open()) {
                store(parse_config_file(confFile, config_file_options), vm);
                confFile.close();
            }
        }
        catch (const invalid_option_value &e) {
            cerr << "Option Error - " << e.what() << endl;
            exit(EXIT_FAILURE);
        }
        catch (const invalid_command_line_syntax &e) {
            cerr << "Syntax Error - " << e.what() << endl;
            exit(EXIT_FAILURE);
        }

        notify(vm);

        if (vm.count("help")) {
            cerr << cmdline_options << endl;
            return false;
        }
        if (!vm.count("scenario")) {
            cerr << cmdline_options << endl;
            cerr << endl << "scenario is a required argument." << endl << endl;
            exit(EXIT_FAILURE);
        }
        return true;
    }
}
<|endoftext|>


<commit_before>#include "omnicore/notifications.h"

#include "omnicore/log.h"
#include "omnicore/omnicore.h"
#include "omnicore/rules.h"
#include "omnicore/utilsbitcoin.h"
#include "omnicore/version.h"

#include "main.h"
#include "util.h"
#include "ui_interface.h"

#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

#include <stdint.h>
#include <string>
#include <vector>

namespace mastercore
{

//! Vector of currently active Omni alerts
std::vector<AlertData> currentOmniAlerts;

/**
 * Adds a new alert to the alerts vector
 *
 */
void AddAlert(uint16_t alertType, uint32_t alertExpiry, const std::string& alertMessage)
{
    AlertData newAlert;
    newAlert.alert_type = alertType;
    newAlert.alert_expiry = alertExpiry;
    newAlert.alert_message = alertMessage;

    // very basic sanity checks to catch malformed packets
    if (alertType > 3) {
        PrintToLog("New alert REJECTED (alert type not recognized): %d, %d, %s\n", alertType, alertExpiry, alertMessage);
        return;
    }
    if (alertType == 1 && alertExpiry > 999999) {
        PrintToLog("New alert REJECTED (block value too large): %d, %d, %s\n", alertType, alertExpiry, alertMessage);
        return;
    }
    if (alertType == 2 && (alertExpiry < 1439256200 || alertExpiry > 1639256200)) {
        PrintToLog("New alert REJECTED (block time values invalid): %d, %d, %s\n", alertType, alertExpiry, alertMessage);
        return;
    }
    if (alertType == 3 && (alertExpiry < 100 || alertExpiry > 900000)) {
        PrintToLog("New alert REJECTED (client version invalid): %d, %d, %s\n", alertType, alertExpiry, alertMessage);
        return;
    }

    currentOmniAlerts.push_back(newAlert);
    PrintToLog("New alert added: %d, %d, %s\n", alertType, alertExpiry, alertMessage);
}

/**
 * Determines whether the sender is an authorized source for Omni Core alerts.
 *
 * The option "-omnialertallowsender=source" can be used to whitelist additional sources,
 * and the option "-omnialertignoresender=source" can be used to ignore a source.
 *
 * To consider any alert as authorized, "-omnialertallowsender=any" can be used. This
 * should only be done for testing purposes!
 */
bool CheckAlertAuthorization(const std::string& sender)
{
    std::set<std::string> whitelisted;

    // TODO: check email addresses

    // Mainnet
    whitelisted.insert("16Zwbujf1h3v1DotKcn9XXt1m7FZn2o4mj"); // Craig   <craig@omni.foundation>
    whitelisted.insert("1MicH2Vu4YVSvREvxW1zAx2XKo2GQomeXY"); // Michael <michael@omni.foundation>
    whitelisted.insert("1zAtHRASgdHvZDfHs6xJquMghga4eG7gy");  // Zathras <zathras@omni.foundation>
    whitelisted.insert("1dexX7zmPen1yBz2H9ZF62AK5TGGqGTZH");  // dexX7   <dexx@bitwatch.co>
    whitelisted.insert("1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P"); // Exodus (who has access?)

    // Testnet
    whitelisted.insert("mpDex4kSX4iscrmiEQ8fBiPoyeTH55z23j"); // Michael <michael@omni.foundation>
    whitelisted.insert("mpZATHupfCLqet5N1YL48ByCM1ZBfddbGJ"); // Zathras <zathras@omni.foundation>
    whitelisted.insert("mk5SSx4kdexENHzLxk9FLhQdbbBexHUFTW"); // dexX7   <dexx@bitwatch.co>

    // Add manually whitelisted sources
    if (mapArgs.count("-omnialertallowsender")) {
        const std::vector<std::string>& sources = mapMultiArgs["-omnialertallowsender"];

        for (std::vector<std::string>::const_iterator it = sources.begin(); it != sources.end(); ++it) {
            whitelisted.insert(*it);
        }
    }

    // Remove manually ignored sources
    if (mapArgs.count("-omnialertignoresender")) {
        const std::vector<std::string>& sources = mapMultiArgs["-omnialertignoresender"];

        for (std::vector<std::string>::const_iterator it = sources.begin(); it != sources.end(); ++it) {
            whitelisted.erase(*it);
        }
    }

    bool fAuthorized = (whitelisted.count(sender) ||
                        whitelisted.count("any"));

    return fAuthorized;
}

/**
 * Alerts including meta data.
 */
std::vector<AlertData> GetOmniCoreAlerts()
{
    return currentOmniAlerts;
}

/**
 * Human readable alert messages.
 */
std::vector<std::string> GetOmniCoreAlertMessages()
{
    std::vector<std::string> vstr;
    for (std::vector<AlertData>::iterator it = currentOmniAlerts.begin(); it != currentOmniAlerts.end(); it++) {
        vstr.push_back((*it).alert_message);
    }
    return vstr;
}

/**
 * Expires any alerts that need expiring.
 */
bool CheckExpiredAlerts(unsigned int curBlock, uint64_t curTime)
{
    for (std::vector<AlertData>::iterator it = currentOmniAlerts.begin(); it != currentOmniAlerts.end(); ) {
        AlertData alert = *it;
        switch (alert.alert_type) {
            case 1: // alert expiring by block number
                if (curBlock >= alert.alert_expiry) {
                    PrintToLog("Expiring alert (type:%d expiry:%d message:%s)\n", alert.alert_type, alert.alert_expiry, alert.alert_message);
                    it = currentOmniAlerts.erase(it);
                    uiInterface.OmniStateChanged();
                } else {
                    it++;
                }
            break;
            case 2: // alert expiring by block time
                if (curTime > alert.alert_expiry) {
                    PrintToLog("Expiring alert (type:%d expiry:%d message:%s)\n", alert.alert_type, alert.alert_expiry, alert.alert_message);
                    it = currentOmniAlerts.erase(it);
                    uiInterface.OmniStateChanged();
                } else {
                    it++;
                }
            break;
            case 3: // alert expiring by client version
                if (OMNICORE_VERSION > alert.alert_expiry) {
                    PrintToLog("Expiring alert (type:%d expiry:%d message:%s)\n", alert.alert_type, alert.alert_expiry, alert.alert_message);
                    it = currentOmniAlerts.erase(it);
                    uiInterface.OmniStateChanged();
                } else {
                    it++;
                }
            break;
            default: // unrecognized alert type
                    PrintToLog("Removing invalid alert (type:%d expiry:%d message:%s)\n", alert.alert_type, alert.alert_expiry, alert.alert_message);
                    it = currentOmniAlerts.erase(it);
                    uiInterface.OmniStateChanged();
            break;
        }
    }
    return true;
}

} // namespace mastercore
<commit_msg>Remove magic number sanity checks on AddAlert<commit_after>#include "omnicore/notifications.h"

#include "omnicore/log.h"
#include "omnicore/omnicore.h"
#include "omnicore/rules.h"
#include "omnicore/utilsbitcoin.h"
#include "omnicore/version.h"

#include "main.h"
#include "util.h"
#include "ui_interface.h"

#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

#include <stdint.h>
#include <string>
#include <vector>

namespace mastercore
{

//! Vector of currently active Omni alerts
std::vector<AlertData> currentOmniAlerts;

/**
 * Adds a new alert to the alerts vector
 *
 */
void AddAlert(uint16_t alertType, uint32_t alertExpiry, const std::string& alertMessage)
{
    AlertData newAlert;
    newAlert.alert_type = alertType;
    newAlert.alert_expiry = alertExpiry;
    newAlert.alert_message = alertMessage;

    // very basic sanity checks to catch malformed packets
    if (alertType < 1 || alertType > 3) {
        PrintToLog("New alert REJECTED (alert type not recognized): %d, %d, %s\n", alertType, alertExpiry, alertMessage);
        return;
    }

    currentOmniAlerts.push_back(newAlert);
    PrintToLog("New alert added: %d, %d, %s\n", alertType, alertExpiry, alertMessage);
}

/**
 * Determines whether the sender is an authorized source for Omni Core alerts.
 *
 * The option "-omnialertallowsender=source" can be used to whitelist additional sources,
 * and the option "-omnialertignoresender=source" can be used to ignore a source.
 *
 * To consider any alert as authorized, "-omnialertallowsender=any" can be used. This
 * should only be done for testing purposes!
 */
bool CheckAlertAuthorization(const std::string& sender)
{
    std::set<std::string> whitelisted;

    // TODO: check email addresses

    // Mainnet
    whitelisted.insert("16Zwbujf1h3v1DotKcn9XXt1m7FZn2o4mj"); // Craig   <craig@omni.foundation>
    whitelisted.insert("1MicH2Vu4YVSvREvxW1zAx2XKo2GQomeXY"); // Michael <michael@omni.foundation>
    whitelisted.insert("1zAtHRASgdHvZDfHs6xJquMghga4eG7gy");  // Zathras <zathras@omni.foundation>
    whitelisted.insert("1dexX7zmPen1yBz2H9ZF62AK5TGGqGTZH");  // dexX7   <dexx@bitwatch.co>
    whitelisted.insert("1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P"); // Exodus (who has access?)

    // Testnet
    whitelisted.insert("mpDex4kSX4iscrmiEQ8fBiPoyeTH55z23j"); // Michael <michael@omni.foundation>
    whitelisted.insert("mpZATHupfCLqet5N1YL48ByCM1ZBfddbGJ"); // Zathras <zathras@omni.foundation>
    whitelisted.insert("mk5SSx4kdexENHzLxk9FLhQdbbBexHUFTW"); // dexX7   <dexx@bitwatch.co>

    // Add manually whitelisted sources
    if (mapArgs.count("-omnialertallowsender")) {
        const std::vector<std::string>& sources = mapMultiArgs["-omnialertallowsender"];

        for (std::vector<std::string>::const_iterator it = sources.begin(); it != sources.end(); ++it) {
            whitelisted.insert(*it);
        }
    }

    // Remove manually ignored sources
    if (mapArgs.count("-omnialertignoresender")) {
        const std::vector<std::string>& sources = mapMultiArgs["-omnialertignoresender"];

        for (std::vector<std::string>::const_iterator it = sources.begin(); it != sources.end(); ++it) {
            whitelisted.erase(*it);
        }
    }

    bool fAuthorized = (whitelisted.count(sender) ||
                        whitelisted.count("any"));

    return fAuthorized;
}

/**
 * Alerts including meta data.
 */
std::vector<AlertData> GetOmniCoreAlerts()
{
    return currentOmniAlerts;
}

/**
 * Human readable alert messages.
 */
std::vector<std::string> GetOmniCoreAlertMessages()
{
    std::vector<std::string> vstr;
    for (std::vector<AlertData>::iterator it = currentOmniAlerts.begin(); it != currentOmniAlerts.end(); it++) {
        vstr.push_back((*it).alert_message);
    }
    return vstr;
}

/**
 * Expires any alerts that need expiring.
 */
bool CheckExpiredAlerts(unsigned int curBlock, uint64_t curTime)
{
    for (std::vector<AlertData>::iterator it = currentOmniAlerts.begin(); it != currentOmniAlerts.end(); ) {
        AlertData alert = *it;
        switch (alert.alert_type) {
            case 1: // alert expiring by block number
                if (curBlock >= alert.alert_expiry) {
                    PrintToLog("Expiring alert (type:%d expiry:%d message:%s)\n", alert.alert_type, alert.alert_expiry, alert.alert_message);
                    it = currentOmniAlerts.erase(it);
                    uiInterface.OmniStateChanged();
                } else {
                    it++;
                }
            break;
            case 2: // alert expiring by block time
                if (curTime > alert.alert_expiry) {
                    PrintToLog("Expiring alert (type:%d expiry:%d message:%s)\n", alert.alert_type, alert.alert_expiry, alert.alert_message);
                    it = currentOmniAlerts.erase(it);
                    uiInterface.OmniStateChanged();
                } else {
                    it++;
                }
            break;
            case 3: // alert expiring by client version
                if (OMNICORE_VERSION > alert.alert_expiry) {
                    PrintToLog("Expiring alert (type:%d expiry:%d message:%s)\n", alert.alert_type, alert.alert_expiry, alert.alert_message);
                    it = currentOmniAlerts.erase(it);
                    uiInterface.OmniStateChanged();
                } else {
                    it++;
                }
            break;
            default: // unrecognized alert type
                    PrintToLog("Removing invalid alert (type:%d expiry:%d message:%s)\n", alert.alert_type, alert.alert_expiry, alert.alert_message);
                    it = currentOmniAlerts.erase(it);
                    uiInterface.OmniStateChanged();
            break;
        }
    }
    return true;
}

} // namespace mastercore
<|endoftext|>