<commit_before>//
//  Landscape.cpp
//
//  Created by Soso Limited on 5/26/15.
//
//

#include "Landscape.h"

#include "cinder/Log.h"
#include "Constants.h"

using namespace soso;
using namespace cinder;

namespace {

struct alignas(16) Vertex {
	vec3	position;
	vec3	normal;
	vec2	tex_coord;
	vec2	color_tex_coord;
	float deform_scaling;
	float frame_offset;
	float color_weight;
};

const auto kVertexLayout = ([] {
		auto layout = geom::BufferLayout();
		layout.append( geom::Attrib::POSITION, 3, sizeof(Vertex), offsetof(Vertex, position) );
		layout.append( geom::Attrib::NORMAL, 3, sizeof(Vertex), offsetof(Vertex, normal) );
		layout.append( geom::Attrib::TEX_COORD_0, 2, sizeof(Vertex), offsetof(Vertex, tex_coord) );
		layout.append( geom::Attrib::TEX_COORD_1, 2, sizeof(Vertex), offsetof(Vertex, color_tex_coord) );
		layout.append( geom::Attrib::CUSTOM_0, 1, sizeof(Vertex), offsetof(Vertex, deform_scaling) );
		layout.append( geom::Attrib::CUSTOM_1, 1, sizeof(Vertex), offsetof(Vertex, frame_offset) );
		layout.append( geom::Attrib::CUSTOM_2, 1, sizeof(Vertex), offsetof(Vertex, color_weight) );
		return layout;
	} ());

const auto kVertexMapping = ([] {
		return gl::Batch::AttributeMapping{ { geom::Attrib::CUSTOM_0, "DeformScaling" }, { geom::Attrib::CUSTOM_1, "FrameOffset" }, { geom::Attrib::CUSTOM_2, "ColorWeight" } };
	} ());

// Load a shader and handle exceptions. Return nullptr on failure.
gl::GlslProgRef loadShader( const fs::path &iVertex, const fs::path &iFragment )
{
	try {
		auto shader_format = gl::GlslProg::Format()
			.vertex( app::loadAsset( iVertex ) )
			.fragment( app::loadAsset( iFragment ) );

		return gl::GlslProg::create( shader_format );
	}
	catch( ci::Exception &exc ) {
		CI_LOG_E( "Error loading shader: " << exc.what() );
	}

	return nullptr;
}

///
/// Create a quadrilateral with clockwise vertices abcd.
/// Maps to frame at time and a slice of the video frame.
///
void addQuad( std::vector<Vertex> &vertices, const vec3 &a, const vec3 &b, const vec3 &c, const vec3 &d, float time, const Rectf &slice )
{
	auto normal = vec3( 0, 1, 0 );
	auto deform_scaling = 0.0f;

	vertices.insert( vertices.end(), {
		Vertex{ a, normal, slice.getUpperLeft(), slice.getUpperLeft(), deform_scaling, time, 0.0f },
		Vertex{ b, normal, slice.getUpperRight(), slice.getUpperRight(), deform_scaling, time, 0.0f },
		Vertex{ c, normal, slice.getLowerRight(), slice.getLowerRight(), deform_scaling, time, 0.0f },

		Vertex{ a, normal, slice.getUpperLeft(), slice.getUpperLeft(), deform_scaling, time, 0.0f },
		Vertex{ c, normal, slice.getLowerRight(), slice.getLowerRight(), deform_scaling, time, 0.0f },
		Vertex{ d, normal, slice.getLowerLeft(), slice.getLowerLeft(), deform_scaling, time, 0.0f }
	} );

}

/// Add a ring of geometry containing a given number of time bands (slitscanning effect) and repeats around the donut.
void addRing( std::vector<Vertex> &vertices, const vec3 &center, const vec3 &normal, float inner_radius, float outer_radius, float time_offset, int time_bands, int repeats, float color_weight, const vec2 &texture_insets = vec2( 0.05, 0.0875f ) )
{
	auto rings = time_bands;
	auto segments = 64;

	// Generate cartesian position.
	auto calc_pos = [=] (int r, int s) {
		auto distance = lmap<float>( r, 0, rings, 0.0f, 1.0f );
		auto radius = mix( inner_radius, outer_radius, distance );
		auto t = (float) s / segments;
		auto x = cos( t * Tau ) * radius;
		auto y = sin( t * Tau ) * radius;
		return vec3( x, 0, y ) + center;
	};

	// Generate texture coordinate mirrored at halfway point.
	auto calc_tc = [=] (int r, int s) {
		auto t = (float) s / segments;
		if( t < 1 ) {
			t = glm::fract( t * repeats );
		}
		// mirror copies
		t = std::abs( t - 0.5f ) * 2.0f;
		auto tc = vec2(0);
		// Repeat t with mirroring
		// insetting the texture coordinates minimizes edge color flashing.
		tc.y = mix( texture_insets.y, 1.0f - texture_insets.y, t );
		tc.x = lmap<float>( r, 0, rings, 1.0f - texture_insets.x, texture_insets.x );
		return tc;
	};

	// Add a vertex to texture (color_tc parameter allows us to do flat shading in ES2)
	auto add_vert = [=,&vertices] (int r, int s, const ivec2 &provoking) {
		auto deform_scaling = 0.0f;
		auto pos = calc_pos(r, s);
		auto tc = calc_tc(r, s);
		auto color_tc = calc_tc( provoking.x, provoking.y );
		auto time = time_offset; // + lmap<float>( r, 0, rings, 0.0f, 1.0f / 64.0f );
		if (time_bands > 1) {
			time += lmap<float>( provoking.x, 0.0f, rings, 0.0f, time_bands );
		}
		vertices.push_back( Vertex{ pos, normal, tc, color_tc, deform_scaling, time, color_weight } );
	};

	// Create triangles for flat shading
	for( auto r = 0; r < rings; r += 1 )
	{
		for( auto s = 0; s < segments; s += 1 )
		{
			auto provoking = ivec2(r, s);
			add_vert( r, s, provoking );
			add_vert( r, s + 1, provoking );
			add_vert( r + 1, s + 1, provoking );

			add_vert( r, s, provoking );
			add_vert( r + 1, s, provoking );
			add_vert( r + 1, s + 1, provoking );
		}
	}
}

} // namespace

void Landscape::setup()
{
	auto shader = loadShader( "landscape.vs", "landscape.fs" );

	std::vector<Vertex> vertices;

	auto normal = vec3( 0, 1, 0 );

	auto inner = 0.28f;
	auto outer = 3.0f;

	struct Params {
		float repeats;
		float frames;
		float color_weight;
		vec2	insets;
	};

	auto params = std::vector<Params> {
		{ 2, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 4, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 6, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 8, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 10, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 12, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 10, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 8, 1, 0.1f, vec2( 0.075, 0.1 ) },
		{ 10, 1, 0.25f, vec2( 0.1, 0.125 ) },
		{ 8, 1, 0.5f, vec2( 0.25, 0.15 ) }
	};

	for( auto i = 0; i < params.size(); i += 1 )
	{
		auto &p = params.at( i );
		auto copies = p.repeats;
		auto t = (i + 0.0f) / params.size();
		auto t2 = (i + 1.0f) / params.size();
		auto r1 = mix( inner, outer, t );
		auto r2 = mix( inner, outer, t2 );
		addRing( vertices, vec3( 0, -4, 0 ), normal, r1, r2, i * 2 + 1.0f, 1, copies, p.color_weight, p.insets );
	}

	addRing( vertices, vec3( 0, -4, 0 ), normal, outer, outer + 2.0f, params.size() * 2, 64 - (params.size() * 2), 1, 1.0f );

	// Deform stuff
//	/*
	auto min_distance = inner;
	auto max_distance = outer;
	for( auto &v : vertices ) {
		auto distance = lmap<float>( length( v.position ), min_distance, max_distance, 0.0f, 1.0f );
		// pos is on a radial axis, rotate it 90 degrees to bend along length
		auto axis = glm::rotate( glm::angleAxis( (float)Tau / 4.0f, vec3(0, 1, 0) ), normalize(v.position) );
		auto theta = mix( 0.0f, -(float)Tau / 18.0f, distance );
		auto xf = glm::rotate( theta, axis );
		v.normal = vec3(xf * vec4(v.normal, 0.0f));
//		v.deform_scaling = mix( 0.0f, 4.0f, distance );
		v.position = vec3(xf * vec4(v.position, 1.0f));
//		v.color_weight = 0.0f; // mix( 0.0f, 1.0f, distance * distance );
//		if( distance >= 1.0f ) {
//			v.color_weight = 1.0f;
//		}
	}
//	*/

	// Plug center
	auto h = vec3( inner, 0, inner ) * 1.5f;
	auto c = vec3( 0, -4.0f, 0 );
	addQuad( vertices, c + (h * vec3(-1, 0, -1)), c + (h * vec3(1, 0, -1)), c + (h * vec3(1, 0, 1)), c + (h * vec3(-1, 0, 1)), 0.0f, Rectf( 0, 1, 1, 0 ) );

	auto vbo = gl::Vbo::create( GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW );
	auto mesh = gl::VboMesh::create( vertices.size(), GL_TRIANGLES, {{ kVertexLayout, vbo }} );
	batch = gl::Batch::create( mesh, shader, kVertexMapping );
}

void Landscape::setTextureUnits( uint8_t iClearUnit, uint8_t iBlurredUnit )
{
	auto &shader = batch->getGlslProg();
	shader->uniform( "uClearTexture", iClearUnit );
	shader->uniform( "uBlurredTexture", iBlurredUnit );
}

void Landscape::draw( float iFrameOffset )
{
	auto &shader = batch->getGlslProg();
	shader->uniform( "uCurrentFrame", iFrameOffset );

	batch->draw();
}
<commit_msg>Gradually introduce slit-scanning.<commit_after>//
//  Landscape.cpp
//
//  Created by Soso Limited on 5/26/15.
//
//

#include "Landscape.h"

#include "cinder/Log.h"
#include "Constants.h"

using namespace soso;
using namespace cinder;

namespace {

struct alignas(16) Vertex {
	vec3	position;
	vec3	normal;
	vec2	tex_coord;
	vec2	color_tex_coord;
	float deform_scaling;
	float frame_offset;
	float color_weight;
};

const auto kVertexLayout = ([] {
		auto layout = geom::BufferLayout();
		layout.append( geom::Attrib::POSITION, 3, sizeof(Vertex), offsetof(Vertex, position) );
		layout.append( geom::Attrib::NORMAL, 3, sizeof(Vertex), offsetof(Vertex, normal) );
		layout.append( geom::Attrib::TEX_COORD_0, 2, sizeof(Vertex), offsetof(Vertex, tex_coord) );
		layout.append( geom::Attrib::TEX_COORD_1, 2, sizeof(Vertex), offsetof(Vertex, color_tex_coord) );
		layout.append( geom::Attrib::CUSTOM_0, 1, sizeof(Vertex), offsetof(Vertex, deform_scaling) );
		layout.append( geom::Attrib::CUSTOM_1, 1, sizeof(Vertex), offsetof(Vertex, frame_offset) );
		layout.append( geom::Attrib::CUSTOM_2, 1, sizeof(Vertex), offsetof(Vertex, color_weight) );
		return layout;
	} ());

const auto kVertexMapping = ([] {
		return gl::Batch::AttributeMapping{ { geom::Attrib::CUSTOM_0, "DeformScaling" }, { geom::Attrib::CUSTOM_1, "FrameOffset" }, { geom::Attrib::CUSTOM_2, "ColorWeight" } };
	} ());

// Load a shader and handle exceptions. Return nullptr on failure.
gl::GlslProgRef loadShader( const fs::path &iVertex, const fs::path &iFragment )
{
	try {
		auto shader_format = gl::GlslProg::Format()
			.vertex( app::loadAsset( iVertex ) )
			.fragment( app::loadAsset( iFragment ) );

		return gl::GlslProg::create( shader_format );
	}
	catch( ci::Exception &exc ) {
		CI_LOG_E( "Error loading shader: " << exc.what() );
	}

	return nullptr;
}

///
/// Create a quadrilateral with clockwise vertices abcd.
/// Maps to frame at time and a slice of the video frame.
///
void addQuad( std::vector<Vertex> &vertices, const vec3 &a, const vec3 &b, const vec3 &c, const vec3 &d, float time, const Rectf &slice )
{
	auto normal = vec3( 0, 1, 0 );
	auto deform_scaling = 0.0f;

	vertices.insert( vertices.end(), {
		Vertex{ a, normal, slice.getUpperLeft(), slice.getUpperLeft(), deform_scaling, time, 0.0f },
		Vertex{ b, normal, slice.getUpperRight(), slice.getUpperRight(), deform_scaling, time, 0.0f },
		Vertex{ c, normal, slice.getLowerRight(), slice.getLowerRight(), deform_scaling, time, 0.0f },

		Vertex{ a, normal, slice.getUpperLeft(), slice.getUpperLeft(), deform_scaling, time, 0.0f },
		Vertex{ c, normal, slice.getLowerRight(), slice.getLowerRight(), deform_scaling, time, 0.0f },
		Vertex{ d, normal, slice.getLowerLeft(), slice.getLowerLeft(), deform_scaling, time, 0.0f }
	} );

}

/// Add a ring of geometry containing a given number of time bands (slitscanning effect) and repeats around the donut.
void addRing( std::vector<Vertex> &vertices, const vec3 &center, const vec3 &normal, float inner_radius, float outer_radius, float time_offset, int time_bands, int repeats, float color_weight, const vec2 &texture_insets = vec2( 0.05, 0.0875f ) )
{
	auto rings = time_bands;
	auto segments = 64;

	// Generate cartesian position.
	auto calc_pos = [=] (int r, int s) {
		auto distance = lmap<float>( r, 0, rings, 0.0f, 1.0f );
		auto radius = mix( inner_radius, outer_radius, distance );
		auto t = (float) s / segments;
		auto x = cos( t * Tau ) * radius;
		auto y = sin( t * Tau ) * radius;
		return vec3( x, 0, y ) + center;
	};

	// Generate texture coordinate mirrored at halfway point.
	auto calc_tc = [=] (int r, int s) {
		auto t = (float) s / segments;
		if( t < 1 ) {
			t = glm::fract( t * repeats );
		}
		// mirror copies
		t = std::abs( t - 0.5f ) * 2.0f;
		auto tc = vec2(0);
		// Repeat t with mirroring
		// insetting the texture coordinates minimizes edge color flashing.
		tc.y = mix( texture_insets.y, 1.0f - texture_insets.y, t );
		tc.x = lmap<float>( r, 0, rings, 1.0f - texture_insets.x, texture_insets.x );
		return tc;
	};

	// Add a vertex to texture (color_tc parameter allows us to do flat shading in ES2)
	auto add_vert = [=,&vertices] (int r, int s, const ivec2 &provoking) {
		auto deform_scaling = 0.0f;
		auto pos = calc_pos(r, s);
		auto tc = calc_tc(r, s);
		auto color_tc = calc_tc( provoking.x, provoking.y );
		auto time = time_offset; // + lmap<float>( r, 0, rings, 0.0f, 1.0f / 64.0f );
		if (time_bands > 1) {
			time += lmap<float>( provoking.x, 0.0f, rings, 0.0f, time_bands );
		}
		vertices.push_back( Vertex{ pos, normal, tc, color_tc, deform_scaling, time, color_weight } );
	};

	// Create triangles for flat shading
	for( auto r = 0; r < rings; r += 1 )
	{
		for( auto s = 0; s < segments; s += 1 )
		{
			auto provoking = ivec2(r, s);
			add_vert( r, s, provoking );
			add_vert( r, s + 1, provoking );
			add_vert( r + 1, s + 1, provoking );

			add_vert( r, s, provoking );
			add_vert( r + 1, s, provoking );
			add_vert( r + 1, s + 1, provoking );
		}
	}
}

} // namespace

void Landscape::setup()
{
	auto shader = loadShader( "landscape.vs", "landscape.fs" );

	std::vector<Vertex> vertices;

	auto normal = vec3( 0, 1, 0 );

	auto inner = 0.28f;
	auto outer = 3.0f;

	struct Params {
		float repeats;
		float frames;
		float color_weight;
		vec2	insets;
	};

	auto params = std::vector<Params> {
		{ 2, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 4, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 6, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 8, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 10, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 12, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 10, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 8, 1, 0.1f, vec2( 0.075, 0.1 ) },
		{ 10, 2, 0.25f, vec2( 0.1, 0.125 ) },
		{ 8, 8, 0.5f, vec2( 0.25, 0.15 ) }
	};

	for( auto i = 0; i < params.size(); i += 1 )
	{
		auto &p = params.at( i );
		auto copies = p.repeats;
		auto t = (i + 0.0f) / params.size();
		auto t2 = (i + 1.0f) / params.size();
		auto r1 = mix( inner, outer, t );
		auto r2 = mix( inner, outer, t2 );
		addRing( vertices, vec3( 0, -4, 0 ), normal, r1, r2, i * 2 + 1.0f, p.frames, copies, p.color_weight, p.insets );
	}

	auto last_frame = params.size() * 2 + 4.0f; // actually some overlap
	auto remaining_frames = 64.0f - last_frame;
	addRing( vertices, vec3( 0, -4, 0 ), normal, outer, outer + 2.0f, last_frame, remaining_frames, 1, 1.0f );

	// Deform stuff
//	/*
	auto min_distance = inner;
	auto max_distance = outer;
	for( auto &v : vertices ) {
		auto distance = lmap<float>( length( v.position ), min_distance, max_distance, 0.0f, 1.0f );
		// pos is on a radial axis, rotate it 90 degrees to bend along length
		auto axis = glm::rotate( glm::angleAxis( (float)Tau / 4.0f, vec3(0, 1, 0) ), normalize(v.position) );
		auto theta = mix( 0.0f, -(float)Tau / 18.0f, distance );
		auto xf = glm::rotate( theta, axis );
		v.normal = vec3(xf * vec4(v.normal, 0.0f));
//		v.deform_scaling = mix( 0.0f, 4.0f, distance );
		v.position = vec3(xf * vec4(v.position, 1.0f));
//		v.color_weight = 0.0f; // mix( 0.0f, 1.0f, distance * distance );
//		if( distance >= 1.0f ) {
//			v.color_weight = 1.0f;
//		}
	}
//	*/

	// Plug center
	auto h = vec3( inner, 0, inner ) * 1.5f;
	auto c = vec3( 0, -4.0f, 0 );
	addQuad( vertices, c + (h * vec3(-1, 0, -1)), c + (h * vec3(1, 0, -1)), c + (h * vec3(1, 0, 1)), c + (h * vec3(-1, 0, 1)), 0.0f, Rectf( 0, 1, 1, 0 ) );

	auto vbo = gl::Vbo::create( GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW );
	auto mesh = gl::VboMesh::create( vertices.size(), GL_TRIANGLES, {{ kVertexLayout, vbo }} );
	batch = gl::Batch::create( mesh, shader, kVertexMapping );
}

void Landscape::setTextureUnits( uint8_t iClearUnit, uint8_t iBlurredUnit )
{
	auto &shader = batch->getGlslProg();
	shader->uniform( "uClearTexture", iClearUnit );
	shader->uniform( "uBlurredTexture", iBlurredUnit );
}

void Landscape::draw( float iFrameOffset )
{
	auto &shader = batch->getGlslProg();
	shader->uniform( "uCurrentFrame", iFrameOffset );

	batch->draw();
}
<|endoftext|>


<commit_before>af5e1128-4b02-11e5-8d98-28cfe9171a43<commit_msg>For bobby to integrate at some point<commit_after>af6bdf3a-4b02-11e5-844e-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>
#include <string>

#include "Class.hpp"

using namespace std;
int main() {

    string newName;
    int newHeight;
    double newWeight;

    BMI student_1;

    cout << "Enter Name: ";
    cin >> newName;
    cout << "\nEnter Height: ";
    cin >> newHeight;
    cout << "\nEnter Weight: ";
    cin >> newWeight;

    student_1.setName(newName);
    student_1.setHeight(newHeight);
    student_1.setWeight(newWeight);

    cout << "Name: " << student_1.getName() << endl
    << "Height: " << student_1.getHeight() << endl
    << "Weight: " << student_1.getWeight() << endl;

    return 0;
}
<commit_msg>changed class name to "BMI"<commit_after>#include <iostream>
#include <string>

#include "BMI.hpp"

using namespace std;
int main() {

    string newName;
    int newHeight;
    double newWeight;

    BMI student_1;

    cout << "Enter Name: ";
    cin >> newName;
    cout << "\nEnter Height: ";
    cin >> newHeight;
    cout << "\nEnter Weight: ";
    cin >> newWeight;

    student_1.setName(newName);
    student_1.setHeight(newHeight);
    student_1.setWeight(newWeight);

    cout << "Name: " << student_1.getName() << endl
    << "Height: " << student_1.getHeight() << endl
    << "Weight: " << student_1.getWeight() << endl;

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <unordered_map>
#include <random>
#include <unordered_set>
#include <math.h>
#include <chrono>
#include <string>

using namespace std;

// Maximum allowed duration
int maxDuration = 98;
int heuristicConstant = 1;
double biasParameter = 1 / sqrt(2);
bool TESTING = true;

random_device rseed;
mt19937 rgen(rseed()); // mersenne_twister

int randomIntRange(int min, int max){
    uniform_int_distribution<int> idist(min, max);
    return idist(rgen);
}

class Point {
    int x, y;

    public:
    Point(int _x, int _y){
        x = _x;
        y = _y;
    }

    Point(){
        x = 0;
        y = 0;
    }

    const int getX() const {
        return x;
    }

    const int getY() const {
        return y;
    }

    bool operator==(const Point &other) const {
        return (x == other.x && y == other.y);
    }
};

namespace std
{
    template <>
    struct hash<Point>
    {
        size_t operator()(const Point& k) const
        {
            // Compute individual hash values for two data members and combine them using XOR and bit shifting
            return ((hash<int>()(k.getX()) ^ (hash<int>()(k.getY()) << 1)) >> 1);
        }
    };
}

vector<vector<Point*>> points;
int width = 30, height = 20;

class Board{
    unordered_set<Point*> blocked;

    public:
    Board(){}

    Board(const Board& board) : blocked(board.blocked){}

    void setBlocked(Point* p){
        blocked.insert(p);
    }

    unordered_set<Point*> getBlocked(){
        return blocked;
    }

    bool isBlocked(Point* p){
        return blocked.find(p) != blocked.end();
    }

    Point* getPoint(int x, int y){
        if(x >= 0 && width > x && y >= 0 && height > y){
            return points.at(x).at(y);
        }else{
            return nullptr;
        }
    }

    vector<Point*> getNeighbors(int x, int y){
        vector<Point*> neighbors;

        Point* bottom = getPoint(x, y-1);
        Point* top = getPoint(x, y+1);
        Point* left = getPoint(x-1, y);
        Point* right = getPoint(x+1, y);

        if(top != nullptr){
            neighbors.push_back(top);
        }

        if(bottom != nullptr){
            neighbors.push_back(bottom);
        }

        if(left != nullptr){
            neighbors.push_back(left);
        }

        if(right != nullptr){
            neighbors.push_back(right);
        }

        return neighbors;
    }

    vector<Point*> validNeighbors(int x, int y){
        vector<Point*> valid;
        for(Point*& p : getNeighbors(x, y)){
            if( !isBlocked(p) ){
                valid.push_back(p);
            }
        }

        return valid;
    }

    operator std::string() const {
        return "Hi";
    }

};

class Player{
    public:
    Point* position;

    explicit Player(Point* pos) : position(pos){}

    Player(const Player& p){
        position = p.position;
    }

    Player(){}

    Point* getRandomMove(Board& board){
        vector<Point*> possibleMoves = board.validNeighbors(position->getX(), position->getY());

        if( !possibleMoves.empty()  ){
            int randomPos = (unsigned int) randomIntRange(1, possibleMoves.size()) - 1;
            return possibleMoves.at(randomPos);
        }else{
            // If the enemy cant return a valid choice it has lost
            return nullptr;
        }
    }

    void setPosition(Point* p){
        this->position = p;
    }

    Point* getPosition(){
        return this->position;
    }

    Point* getSemiRandomMove(Board& board, vector<Player>& enemies){
        vector<Point*> possibleMoves = board.validNeighbors(position->getX(), position->getY());

        Point* bestMove = nullptr;
        double bestScore = numeric_limits<double>::max();

        for(Point* move: possibleMoves){
            double currentScore = domainHeuristic(enemies, move);

            if( bestScore > currentScore ){
                bestScore = currentScore;
                bestMove = move;
            }
        }

        if( !possibleMoves.empty()  ){
            if( randomIntRange(1, 100) > 60 ){
                return bestMove;
            }else{
                int randomPos = (unsigned int) randomIntRange(1, possibleMoves.size()) - 1;
                return possibleMoves.at(randomPos);
            }
        }else{
            // If the enemy cant return a valid choice it has lost
            return nullptr;
        }
    }

    /**
    * Using a domain specific heuristic that should help the algorithm choose a better path
    * This will primarily be used for simulating moves for the evemies so that they dont loose as easily in the simulations
    * @param enemies
    * @param player
    * @return
    */

    double domainHeuristic(vector<Player>& enemies, Point*& playerPosition){
        double heuristic = 0;

        for(Player e: enemies){
            heuristic += abs(e.position->getX() - playerPosition->getX()) + abs(e.position->getY() - playerPosition->getY());
        }

        return heuristic;
    }
};

class ActionTree {
    public:
    Point* move;
    vector<ActionTree*> children;
    ActionTree* parent = nullptr;
    float wins = 0, plays = 0;

    ActionTree(Point* _move, ActionTree* _parent){
        move = _move;
        wins = 0;
        plays = 0;
        parent = _parent;
    }

    void win(){
        wins += 1;
        plays += 1;

        if( parent != nullptr){
            parent->win();
        }
    }

    void loss(){
        plays += 1;

        if( parent != nullptr ){
            parent->loss();
        }
    }

    void deleteTree(){
        for(ActionTree*& child : children){
            child->deleteTree();
        }
        delete this;
    }

    double getVariance(){
        int totalWins = 0;
        int total = 0;
        int rewardSquared = 0;

        if( parent != nullptr){
            for(ActionTree*& child : parent->children){
                total += child->plays;
                totalWins += child->wins;

                rewardSquared += pow(child->wins/child->plays, 2);
            }
        }

        if( total > 0 ){
            return rewardSquared - pow(totalWins/total, 2);
        }else {
            return 0;
        }
    }

    double ubc1TunedScore(){
        double winPercentage = 0, exploration = 0;
        // Avoid division by zero

        if (plays != 0){
            winPercentage = wins / plays;

            if( parent != nullptr ){
                 exploration = 2 * biasParameter * sqrt( 2*log(parent->plays) / plays );

                //exploration = sqrt(  (log(parent->plays) / plays) *
                //                     min(0.25,
                //                     (getVariance() + sqrt(2 * log(parent->plays) / plays)  )));
            }
        }

        // +        return avg_payoff + math.sqrt(math.log(number_sampled) / sampled_arm.total) * min(MAX_BERNOULLI_RANDOM_VARIABLE_VARIANCE, variance + math.sqrt(2.0 * math.log(number_sampled) / sampled_arm.total))

        return winPercentage + exploration;
    }

    /* Get the best child based ubc score: higher is better */
    ActionTree* getOptimalChild(Board& board){
        ActionTree* bestChild = nullptr;
        double bestScore = -INFINITY;

        for(ActionTree*& child : children){
            if( !board.isBlocked(child->move) ){
                double ubcScore = child->ubc1TunedScore();
                if( bestScore < ubcScore){
                    bestScore = ubcScore;
                    bestChild = child;
                }
            }
        }

        return bestChild;
    }

    ActionTree* getFinalChoiceChild(){
        cerr << "Position: " <<  move->getX() << " " << move->getY() << endl;
        cerr << "Amount children " << children.size() << endl;

        ActionTree* bestChild = nullptr;
        double bestScore = -INFINITY;

        for(ActionTree*& child : children){
            if( child->plays > 0 ){
                double score = child->wins / child->plays;
                if( bestScore < score){
                    bestScore = score;
                    bestChild = child;
                }
            }
        }

        return bestChild;
    }

};

class MCTS {
    ActionTree* rootNode;

    bool simulateMove(Point*& move, Board board, vector<Player>& enemies, Player player){
        if( board.isBlocked(move) ){
            return false;
        }else{
            board.setBlocked(move);
            player.position = move;
            return playSimulation(board, enemies, player);
        }
    }

    bool playSimulation(Board& board, vector<Player> enemies, Player player){
        vector<Player> playerVector = {player};

        // Run until we are the only one standing
        while( !enemies.empty() ){
            // The enemies makes the first move
            for(Player& enemy : enemies){
                // Make a random move
                //Point* move = enemy.getRandomMove(board);
                Point* move = enemy.getSemiRandomMove(board, playerVector);

                // Check if the move is a valid one i.e. not nullpointer
                if ( move == nullptr ){
                    // Needs to be adjused for more players
                    return true;
                }

                // Move the player to the new positon
                enemy.position = move;

                // And mark the old one as used
                board.setBlocked(move);
            }

            Point* playerMove = player.getRandomMove(board);
            if( playerMove == nullptr ){
                return false;
            }
            player.position = playerMove;
            board.setBlocked(playerMove);
        }
    }

    public:
    MCTS(){
        rootNode = nullptr;
    };

    Point* getBestChoice(const Board& board, const vector<Player>& enemies, const Player& player){
        if( rootNode == nullptr){
            rootNode = new ActionTree(player.position, nullptr);
        }

        int count = 0;
        auto begin = std::chrono::steady_clock::now();
        //RESETLOOP:while ( int(chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()-begin).count()) < maxDuration ) {

            count++;
        RESETLOOP:while ( count++ < 150) {
            // Start from the rootnode
            ActionTree* currentNode = rootNode;
            Board currentBoard = Board(board);
            vector<Player> currentEnemies = vector<Player>{enemies};
            Player currentPlayer = Player(player);

            while( true ){
                // The node has not been visited before, get neighbors as children
                if( currentNode->plays < 2 ){
                    vector<ActionTree*> children = {};
                    // Loop through and add children
                    for(Point*& p: currentBoard.getNeighbors(currentNode->move->getX(), currentNode->move->getY())){
                        ActionTree* childAction = new ActionTree(p, currentNode);

                        // check if this is a valid move
                        if( simulateMove(p, currentBoard, currentEnemies, currentPlayer) ){
                            childAction->win();
                        }else {
                            childAction->loss();
                        }

                        // We need to add a simulation for each child
                        children.push_back(childAction);
                    }

                    // Add the children to the node
                    currentNode->children = children;

                    // Start again from rootnode
                    goto RESETLOOP;

                    // The node has been visited before
                }else{
                    for(Player& e: currentEnemies){
                        Point* newPosition = e.getRandomMove(currentBoard);
                        e.position = newPosition;

                        // They have lost
                        if( newPosition == nullptr){
                            currentNode->win();
                            goto RESETLOOP;
                        }else{
                            currentBoard.setBlocked(newPosition);
                        }
                    }

                    ActionTree* bestChild = currentNode->getOptimalChild(currentBoard);
                    // if the best child is nullptr, we have lost
                    if( bestChild == nullptr ){
                        currentNode->loss();
                        goto RESETLOOP;
                    }else{
                        currentNode = bestChild;
                        currentBoard.setBlocked(currentNode->move);
                        currentPlayer.position = bestChild->move;
                    }
                }
            }
        }

        cerr << " Amount in while " << count << endl;

        // Continue using the branch that we choose -> more simulations will lead to
        // better result and this will lead to more and more simulations as the game progress.

        rootNode = rootNode->getFinalChoiceChild();
        // We cant do anything, do something just to end the turn
        if ( rootNode == nullptr){
            return new Point(-1, -1);
        }else{
            rootNode->parent = nullptr;
            return rootNode->move;
        }

    };
};

string getDirection(Point* origin, Point* destination){
    if( origin->getX() == destination->getX() ){
        if( origin->getY() > destination->getY() ){
            return "UP";
        }else{
            return "DOWN";
        }
    }else{
        if( origin->getX() > destination->getX() ){
            return "LEFT";
        }else{
            return "RIGHT";
        }
    }
}

void gameLoop(Board& board, MCTS& mcts){
    vector<Player> enemies;
    Player player;

    // THE FRIST POSITION IS NOT MARKED AS BLOCKED

    // game loop
    while (1) {
        int N; // total number of players (2 to 4).
        int P; // your player number (0 to 3).
        cin >> N >> P; cin.ignore();
        for (int i = 0; i < N; i++) {
            int X0; // starting X coordinate of lightcycle (or -1)
            int Y0; // starting Y coordinate of lightcycle (or -1)

            int X1; // starting X coordinate of lightcycle (can be the same as X0 if you play before this player)
            int Y1; // starting Y coordinate of lightcycle (can be the same as Y0 if you play before this player)

            cin >> X0 >> Y0 >> X1 >> Y1; cin.ignore();

            if( X0 != -1 && Y0 != -1 ){
                board.setBlocked(board.getPoint(X0, Y0));
            }
            board.setBlocked(board.getPoint(X1, Y1));
            // This player is me
            if(i == P && enemies.size() != N){
                player = Player(board.getPoint(X1, Y1));
            }else if( i == P ){
                player.position = board.getPoint(X1, Y1);
            }else{
                if (enemies.size() != N){
                    enemies.push_back(Player(board.getPoint(X1, Y1)));
                }else {
                    enemies.at(i).position = board.getPoint(X1, Y1);
                }
            }
        }

        // Write an action using cout. DON'T FORGET THE "<< endl"
        // To debug: cerr << "Debug messages..." << endl;
        Point* result = mcts.getBestChoice(board, enemies, player);

        cerr << "Amount of blocked points " << board.getBlocked().size() << endl;

        // IF no valid path exists
        if( result->getX() == -1 ){
            cout << "No Move" << endl;
        }else{
            cout << getDirection(player.position, result) << endl;
        }
    }
}

void init(){
    for(int x = 0; x < width; x++){
        vector<Point*> yVector;
        for(int y = 0; y < height; y++){
            Point* p = new Point(x, y);
            yVector.push_back(p);
        }
        points.push_back(yVector);
    }
}

int main() {
    init();

    MCTS mcts = MCTS();
    Board board = Board();

    if(TESTING){
        Player enemy =  Player(board.getPoint(10, 10));
        vector<Player> enemies = { enemy };
        Player player = Player(board.getPoint(15, 15));

        for(int i = 0; i < 13; i++){
            board.setBlocked(player.position);
            board.setBlocked(enemy.position);

            Point* result = mcts.getBestChoice(board, enemies, player);
            cout << "The best move is: (" << result->getX() << ", " << result->getY() << ")" << std::endl;
            cout << "Direction: " << getDirection(player.position, result) << " FROM (" << player.position->getX() << ", " << player.position->getY() << ") TO (" << result->getX() << ", " << result->getY() << ")" << std::endl;

            player.position = result;
        }

    }else{
        gameLoop(board, mcts);
    }

    return 0;
}<commit_msg>Added a domain heuristic<commit_after>#include <iostream>
#include <vector>
#include <unordered_map>
#include <random>
#include <unordered_set>
#include <math.h>
#include <chrono>
#include <string>

using namespace std;

// Maximum allowed duration
int maxDuration = 98;
int heuristicConstant = 1;
double biasParameter = 1 / sqrt(2);
bool TESTING = true;

random_device rseed;
mt19937 rgen(rseed()); // mersenne_twister

class Player;
class Point;
class Board;
double domainHeuristic(vector<Player>& enemies, Point*& playerPosition);

int randomIntRange(int min, int max){
    uniform_int_distribution<int> idist(min, max);
    return idist(rgen);
}

class Point {
    int x, y;

    public:
    Point(int _x, int _y){
        x = _x;
        y = _y;
    }

    Point(){
        x = 0;
        y = 0;
    }

    const int getX() const {
        return x;
    }

    const int getY() const {
        return y;
    }

    bool operator==(const Point &other) const {
        return (x == other.x && y == other.y);
    }
};

namespace std
{
    template <>
    struct hash<Point>
    {
        size_t operator()(const Point& k) const
        {
            // Compute individual hash values for two data members and combine them using XOR and bit shifting
            return ((hash<int>()(k.getX()) ^ (hash<int>()(k.getY()) << 1)) >> 1);
        }
    };
}

vector<vector<Point*>> points;
int width = 30, height = 20;

class Board{
    unordered_set<Point*> blocked;

    public:
    Board(){}

    Board(const Board& board) : blocked(board.blocked){}

    void setBlocked(Point* p){
        blocked.insert(p);
    }

    unordered_set<Point*> getBlocked(){
        return blocked;
    }

    bool isBlocked(Point* p){
        return blocked.find(p) != blocked.end();
    }

    Point* getPoint(int x, int y){
        if(x >= 0 && width > x && y >= 0 && height > y){
            return points.at(x).at(y);
        }else{
            return nullptr;
        }
    }

    vector<Point*> getNeighbors(int x, int y){
        vector<Point*> neighbors;

        Point* bottom = getPoint(x, y-1);
        Point* top = getPoint(x, y+1);
        Point* left = getPoint(x-1, y);
        Point* right = getPoint(x+1, y);

        if(top != nullptr){
            neighbors.push_back(top);
        }

        if(bottom != nullptr){
            neighbors.push_back(bottom);
        }

        if(left != nullptr){
            neighbors.push_back(left);
        }

        if(right != nullptr){
            neighbors.push_back(right);
        }

        return neighbors;
    }

    vector<Point*> validNeighbors(int x, int y){
        vector<Point*> valid;
        for(Point*& p : getNeighbors(x, y)){
            if( !isBlocked(p) ){
                valid.push_back(p);
            }
        }

        return valid;
    }

    operator std::string() const {
        return "Hi";
    }

};

class Player{
    public:
    Point* position;

    explicit Player(Point* pos) : position(pos){}

    Player(const Player& p){
        position = p.position;
    }

    Player(){}

    Point* getRandomMove(Board& board){
        vector<Point*> possibleMoves = board.validNeighbors(position->getX(), position->getY());

        if( !possibleMoves.empty()  ){
            int randomPos = (unsigned int) randomIntRange(1, possibleMoves.size()) - 1;
            return possibleMoves.at(randomPos);
        }else{
            // If the enemy cant return a valid choice it has lost
            return nullptr;
        }
    }

    Point* getSemiRandomMove(Board& board, vector<Player>& enemies){
        vector<Point*> possibleMoves = board.validNeighbors(position->getX(), position->getY());

        Point* bestMove = nullptr;
        double bestScore = numeric_limits<double>::max();

        for(Point* move: possibleMoves){
            double currentScore = domainHeuristic(enemies, move);

            if( bestScore > currentScore ){
                bestScore = currentScore;
                bestMove = move;
            }
        }

        if( !possibleMoves.empty()  ){
            if( randomIntRange(1, 100) > 60 ){
                return bestMove;
            }else{
                int randomPos = (unsigned int) randomIntRange(1, possibleMoves.size()) - 1;
                return possibleMoves.at(randomPos);
            }
        }else{
            // If the enemy cant return a valid choice it has lost
            return nullptr;
        }
    }
};

/**
* Using a domain specific heuristic that should help the algorithm choose a better path
* This will primarily be used for simulating moves for the evemies so that they dont loose as easily in the simulations
* @param enemies
* @param player
* @return
*/
double domainHeuristic(vector<Player>& enemies, Point*& playerPosition){
    double heuristic = 0;

    for(Player e: enemies){
        heuristic += abs(e.position->getX() - playerPosition->getX()) + abs(e.position->getY() - playerPosition->getY());
    }

    return heuristic;
}

class ActionTree {
    public:
    Point* move;
    vector<ActionTree*> children;
    ActionTree* parent = nullptr;
    float wins = 0, plays = 0;

    ActionTree(Point* _move, ActionTree* _parent){
        move = _move;
        wins = 0;
        plays = 0;
        parent = _parent;
    }

    void win(){
        wins += 1;
        plays += 1;

        if( parent != nullptr){
            parent->win();
        }
    }

    void loss(){
        plays += 1;

        if( parent != nullptr ){
            parent->loss();
        }
    }

    void deleteTree(){
        for(ActionTree*& child : children){
            child->deleteTree();
        }
        delete this;
    }

    double getVariance(){
        int totalWins = 0;
        int total = 0;
        int rewardSquared = 0;

        if( parent != nullptr){
            for(ActionTree*& child : parent->children){
                total += child->plays;
                totalWins += child->wins;

                rewardSquared += pow(child->wins/child->plays, 2);
            }
        }

        if( total > 0 ){
            return rewardSquared - pow(totalWins/total, 2);
        }else {
            return 0;
        }
    }

    /**
     * The algorithm that is used to calculate the best child
     * @return
     */
    double ubc1TunedScore(vector<Player>& enemies){
        double winPercentage = 0, exploration = 0, domain = 0;

        // Avoid division by zero
        if (plays != 0){
            winPercentage = wins / plays;

            if( parent != nullptr ){
                 exploration = 2 * biasParameter * sqrt( 2*log(parent->plays) / plays ) ;
            }
        }
        // Domain specific heuristic
        domain = domainHeuristic(enemies, move) / (1 + plays);

        return winPercentage + exploration + domain;
    }

    /* Get the best child based ubc score: higher is better */
    ActionTree* getOptimalChild(Board& board, vector<Player>& enemies){
        ActionTree* bestChild = nullptr;
        double bestScore = -INFINITY;

        for(ActionTree*& child : children){
            if( !board.isBlocked(child->move) ){
                double ubcScore = child->ubc1TunedScore(enemies);
                if( bestScore < ubcScore){
                    bestScore = ubcScore;
                    bestChild = child;
                }
            }
        }

        return bestChild;
    }

    ActionTree* getFinalChoiceChild(){
        cerr << "Position: " <<  move->getX() << " " << move->getY() << endl;
        cerr << "Amount children " << children.size() << endl;

        ActionTree* bestChild = nullptr;
        double bestScore = -INFINITY;

        for(ActionTree*& child : children){
            if( child->plays > 0 ){
                double score = child->plays;
                if( bestScore < score){
                    bestScore = score;
                    bestChild = child;
                }
            }
        }

        return bestChild;
    }

};

class MCTS {
    ActionTree* rootNode;

    bool simulateMove(Point*& move, Board board, vector<Player>& enemies, Player player){
        if( board.isBlocked(move) ){
            return false;
        }else{
            board.setBlocked(move);
            player.position = move;
            return playSimulation(board, enemies, player);
        }
    }

    bool playSimulation(Board& board, vector<Player> enemies, Player player){
        vector<Player> playerVector = {player};

        // Run until we are the only one standing
        while( !enemies.empty() ){
            // The enemies makes the first move
            for(Player& enemy : enemies){
                // Make a random move
                //Point* move = enemy.getRandomMove(board);
                Point* move = enemy.getSemiRandomMove(board, playerVector);

                // Check if the move is a valid one i.e. not nullpointer
                if ( move == nullptr ){
                    // Needs to be adjused for more players
                    return true;
                }

                // Move the player to the new positon
                enemy.position = move;

                // And mark the old one as used
                board.setBlocked(move);
            }

            Point* playerMove = player.getRandomMove(board);
            if( playerMove == nullptr ){
                return false;
            }
            player.position = playerMove;
            board.setBlocked(playerMove);
        }
    }

    public:
    MCTS(){
        rootNode = nullptr;
    };

    Point* getBestChoice(const Board& board, const vector<Player>& enemies, const Player& player){
        if( rootNode == nullptr){
            rootNode = new ActionTree(player.position, nullptr);
        }

        int count = 0;
        auto begin = std::chrono::steady_clock::now();
        RESETLOOP:while ( (TESTING && count++ < 150) || int(chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()-begin).count()) < maxDuration ) {
            // Start from the rootnode
            ActionTree* currentNode = rootNode;
            Board currentBoard = Board(board);
            vector<Player> currentEnemies = vector<Player>{enemies};
            Player currentPlayer = Player(player);

            while( true ){
                // The node has not been visited before, get neighbors as children
                if( currentNode->plays < 2 ){
                    vector<ActionTree*> children = {};
                    // Loop through and add children
                    for(Point*& p: currentBoard.getNeighbors(currentNode->move->getX(), currentNode->move->getY())){
                        ActionTree* childAction = new ActionTree(p, currentNode);

                        // check if this is a valid move
                        if( simulateMove(p, currentBoard, currentEnemies, currentPlayer) ){
                            childAction->win();
                        }else {
                            childAction->loss();
                        }

                        // We need to add a simulation for each child
                        children.push_back(childAction);
                    }

                    // Add the children to the node
                    currentNode->children = children;

                    // Start again from rootnode
                    goto RESETLOOP;

                    // The node has been visited before
                }else{
                    for(Player& e: currentEnemies){
                        Point* newPosition = e.getRandomMove(currentBoard);
                        e.position = newPosition;

                        // They have lost
                        if( newPosition == nullptr){
                            currentNode->win();
                            goto RESETLOOP;
                        }else{
                            currentBoard.setBlocked(newPosition);
                        }
                    }

                    ActionTree* bestChild = currentNode->getOptimalChild(currentBoard, currentEnemies);
                    // if the best child is nullptr, we have lost
                    if( bestChild == nullptr ){
                        currentNode->loss();
                        goto RESETLOOP;
                    }else{
                        currentNode = bestChild;
                        currentBoard.setBlocked(currentNode->move);
                        currentPlayer.position = bestChild->move;
                    }
                }
            }
        }

        cerr << " Amount in while " << count << endl;

        // Continue using the branch that we choose -> more simulations will lead to
        // better result and this will lead to more and more simulations as the game progress.

        rootNode = rootNode->getFinalChoiceChild();
        // We cant do anything, do something just to end the turn
        if ( rootNode == nullptr){
            return new Point(-1, -1);
        }else{
            rootNode->parent = nullptr;
            return rootNode->move;
        }

    };
};

string getDirection(Point* origin, Point* destination){
    if( origin->getX() == destination->getX() ){
        if( origin->getY() > destination->getY() ){
            return "UP";
        }else{
            return "DOWN";
        }
    }else{
        if( origin->getX() > destination->getX() ){
            return "LEFT";
        }else{
            return "RIGHT";
        }
    }
}

void gameLoop(Board& board, MCTS& mcts){
    vector<Player> enemies;
    Player player;

    // THE FRIST POSITION IS NOT MARKED AS BLOCKED

    // game loop
    while (1) {
        int N; // total number of players (2 to 4).
        int P; // your player number (0 to 3).
        cin >> N >> P; cin.ignore();
        for (int i = 0; i < N; i++) {
            int X0; // starting X coordinate of lightcycle (or -1)
            int Y0; // starting Y coordinate of lightcycle (or -1)

            int X1; // starting X coordinate of lightcycle (can be the same as X0 if you play before this player)
            int Y1; // starting Y coordinate of lightcycle (can be the same as Y0 if you play before this player)

            cin >> X0 >> Y0 >> X1 >> Y1; cin.ignore();

            if( X0 != -1 && Y0 != -1 ){
                board.setBlocked(board.getPoint(X0, Y0));
            }
            board.setBlocked(board.getPoint(X1, Y1));
            // This player is me
            if(i == P && enemies.size() != N){
                player = Player(board.getPoint(X1, Y1));
            }else if( i == P ){
                player.position = board.getPoint(X1, Y1);
            }else{
                if (enemies.size() != N){
                    enemies.push_back(Player(board.getPoint(X1, Y1)));
                }else {
                    enemies.at(i).position = board.getPoint(X1, Y1);
                }
            }
        }

        // Write an action using cout. DON'T FORGET THE "<< endl"
        // To debug: cerr << "Debug messages..." << endl;
        Point* result = mcts.getBestChoice(board, enemies, player);

        cerr << "Amount of blocked points " << board.getBlocked().size() << endl;

        // IF no valid path exists
        if( result->getX() == -1 ){
            cout << "No Move" << endl;
        }else{
            cout << getDirection(player.position, result) << endl;
        }
    }
}

void init(){
    for(int x = 0; x < width; x++){
        vector<Point*> yVector;
        for(int y = 0; y < height; y++){
            Point* p = new Point(x, y);
            yVector.push_back(p);
        }
        points.push_back(yVector);
    }
}

int main() {
    init();

    MCTS mcts = MCTS();
    Board board = Board();

    if(TESTING){
        Player enemy =  Player(board.getPoint(10, 10));
        vector<Player> enemies = { enemy };
        Player player = Player(board.getPoint(15, 15));

        for(int i = 0; i < 13; i++){
            board.setBlocked(player.position);
            board.setBlocked(enemy.position);

            Point* result = mcts.getBestChoice(board, enemies, player);
            cout << "The best move is: (" << result->getX() << ", " << result->getY() << ")" << std::endl;
            cout << "Direction: " << getDirection(player.position, result) << " FROM (" << player.position->getX() << ", " << player.position->getY() << ") TO (" << result->getX() << ", " << result->getY() << ")" << std::endl;

            player.position = result;
        }

    }else{
        gameLoop(board, mcts);
    }

    return 0;
}<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <fstream>

#include "main.h"

using namespace std;

int atomic_distance (int atom_dist_x, int atom_dist_y, int atom_dist_z); //Defines atomic distance as combination of x, y, z coordinates

int main() {
	string input_file_name;
	ifstream input_file;

	//Display prompt for input file name
	cout << "Please input the name of Gaussian optimization file: ";
	cin >> input_file_name;

	//Check that input file opens
	input_file.open(input_file_name.c_str() );
	if (!input_file.is_open() ) {
		cout << "Error: Unable to open the input file.";
		return 1;
	}

	const string gaussian_output::HEADER_STRING = "OPTIMIZED PARAMETERS";
	const string gaussian_output::FOOTER_STRING = "GradGradGradGradGradGradGradGradGradGradGrad";

	//Read through the file and for now output the coordinates
	while (getline(input_file, gaussian_coordinates, FOOTER_STRING))
	{
		if (gaussian_coordinates.find(HEADER_STRING) != string::npos)
		{
			cout << gaussian_coordinates << "\n";
		}
	}

	return 0;
}

<commit_msg>Revised main.cpp to be compilable<commit_after>#include <iostream>
#include <string>
#include <fstream>

#include "main.h"

using namespace std;

int atomic_distance (int atom_dist_x, int atom_dist_y, int atom_dist_z); //Defines atomic distance as combination of x, y, z coordinates

int main() {
	ifstream inputfile;
	string line;
	string header = "OPTIMIZED PARAMETERS";

	//Open the input file and check that it opened
	inputfile.open("gaussian_opt_file");
	if (!inputfile.is_open() ) {
		cout << "Error: Unable to open the input file.";
		return 1;
	}

	//Search the input file
	while (getline(inputfile, line)) {
		if (line.find(header, 0) != string::npos) {
			cout << "Found: " << header << endl;
		}
	}
	inputfile.close();
	return 0;
}

	//const string gaussian_output::HEADER_STRING = "OPTIMIZED PARAMETERS";
	//const string gaussian_output::FOOTER_STRING = "GradGradGradGradGradGradGradGradGradGradGrad";

	//Read through the file and for now output the coordinates
	//while (getline(input_file, gaussian_coordinates, FOOTER_STRING))
	//{
		//if (gaussian_coordinates.find(HEADER_STRING) != string::npos)
		//{
			//cout << gaussian_coordinates << "\n";
		//}
	//}

	//return 0;
//}

<|endoftext|>


<commit_before>//% Rollup drumkit userspace driver
//% Alex Grabovski <hurufu@gmail.com>
//% 2014-04-21
//% WTFPL

#include <iostream>
#include <csignal>
#include <unistd.h>
#include <libusb.h>
#include <jack/jack.h>
#include <jack/midiport.h>

#define VERSION 0.2
#define DRUMKIT_VENDOR_ID 0x1941
#define DRUMKIT_PRODUCT_ID 0x8021
#define DRUMKIT_WMAXPACKETSIZE 8
#define DRUMKIT_ENDPOINT 1
#define NOF_PADS 6

// Error codes
#define SUCCESS 0
#define ERR_ANSWER_LENGTH_MISMATCH 0xff
#define ERR_TRANSFER_FAILED 0xfe
#define ERR_LIBUSB_SPECIFIC 0xfd
#define ERR_JACK_SPECIFIC 0xfc
#define ERR_BAD_ARGUMENT 0xfb
#define ERR_UNKNOWN 0xfa
#define ERR_JACK_SERVER_CLOSED 0xf9

// Program state flags
int r = SUCCESS;
int status = SUCCESS;
int verbatim = 0;
bool run = true;

struct jack_callback_arg {
    jack_port_t * output_port;
    char pad_map[NOF_PADS];
    bool pad_states[NOF_PADS];
    int loop_buffer;
};

libusb_device_handle * open_device(int vendor, int product);
static int process(jack_nframes_t nframes, void * arg);
void option_handler(int ac, char ** av, jack_callback_arg * drumkit_callback);
static void signal_handler(int);
void jack_shutdown_handler(void *);

int main (int ac, char ** av)
{
    libusb_device_handle * usb_drumkit_handle = NULL;
    jack_client_t * jack_midi_drum = NULL;
    const char jack_midi_drum_str[] = "Dreamlink Foldup Drumk Kit";
    volatile unsigned char raw[DRUMKIT_WMAXPACKETSIZE];
    int transfered;

    struct jack_callback_arg drumkit_callback;
    for (int i=0; i < NOF_PADS; i++)
        drumkit_callback.pad_map[i] = 0x20 + i;
    drumkit_callback.loop_buffer = 0;

    option_handler(ac, av, &drumkit_callback);

    r = libusb_init(NULL);
    if (r != SUCCESS) {
        std::cerr << "libusb_init: " << libusb_strerror((enum libusb_error)r) << "\n";
        return ERR_LIBUSB_SPECIFIC;
    }
    libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_INFO);
    usb_drumkit_handle = open_device(DRUMKIT_VENDOR_ID, DRUMKIT_PRODUCT_ID);
    if ( usb_drumkit_handle == NULL ) {
        std::cerr << "Unable to open drumkit! Probably it isn't connected.\n";
        status = ERR_LIBUSB_SPECIFIC;
        goto usb_exit;
    }
    r = libusb_set_auto_detach_kernel_driver(usb_drumkit_handle, 1);
    if (r != SUCCESS) {
        std::cerr << "libusb_set_auto_detach_kernel_driver: " << libusb_strerror((enum libusb_error)r) << "\n";
        status = ERR_LIBUSB_SPECIFIC;
        goto usb_close;
    }
    r = libusb_claim_interface(usb_drumkit_handle, 0);
    if (r != SUCCESS) {
        std::cerr << "libusb_claim_interface: " << libusb_strerror((enum libusb_error)r) << "\n";
        status = ERR_LIBUSB_SPECIFIC;
        goto usb_close;
    }

    jack_midi_drum = jack_client_open(jack_midi_drum_str, JackNullOption, NULL);
    if (jack_midi_drum == NULL) {
        std::cerr << "Unable to initiate jack client! Is JACK server running?\n";
        status = ERR_JACK_SPECIFIC;
        goto usb_release;
    }
    drumkit_callback.output_port = jack_port_register(jack_midi_drum, "out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
    jack_set_process_callback(jack_midi_drum, process, &drumkit_callback);
    jack_on_shutdown(jack_midi_drum, jack_shutdown_handler, &r);
    r = jack_activate(jack_midi_drum);
    if (r != SUCCESS) {
        std::cerr << "Cannot activate client --- " << r << "\n";
        status = ERR_JACK_SPECIFIC;
        goto jack_close;
    }

    signal(SIGQUIT, signal_handler);
    signal(SIGHUP,  signal_handler);
    signal(SIGTERM, signal_handler);
    signal(SIGINT,  signal_handler);

    while(run) {
        unsigned char p = 0;
        for(int i = 0; i <= drumkit_callback.loop_buffer; i++)
        {
            r = libusb_interrupt_transfer (
                usb_drumkit_handle,
                DRUMKIT_ENDPOINT | LIBUSB_ENDPOINT_IN,
                (unsigned char*) raw,
                DRUMKIT_WMAXPACKETSIZE,
                &transfered,
                0
            );
            if(r >= 0) {
                if (transfered != DRUMKIT_WMAXPACKETSIZE) {
                    std::cerr << "Answer length mismatch.\n";
                    status = ERR_ANSWER_LENGTH_MISMATCH;
                    goto jack_deact;
                }
                for (int j = 0; j < transfered; j++)
                    p |= raw[j];
            }
            else {
                std::cerr << libusb_strerror((enum libusb_error)r) << ".\n";
                status = ERR_TRANSFER_FAILED;
                goto jack_deact;
            }
        }
        for (int i = 0; i < NOF_PADS; i++) {
            drumkit_callback.pad_states[i] = p & 1;
            p >>= 1;
        }
    }

jack_deact:
    if (status != ERR_JACK_SERVER_CLOSED)
        jack_deactivate(jack_midi_drum);
jack_close:
    if (status != ERR_JACK_SERVER_CLOSED)
        jack_client_close(jack_midi_drum);
usb_release:
    libusb_release_interface(usb_drumkit_handle, 0);
usb_close:
    libusb_close(usb_drumkit_handle);
usb_exit:
    libusb_exit(NULL);
    return status;
}

void option_handler(int ac, char ** av, jack_callback_arg * drumkit_callback)
{
    //FIXME I dont have enough stamina to write getopt, and I don't want getopt
    // to be larger than actual driver! I have a plan 'bout ultimate™ getopt,
    // but I don't think I'll make it soon... And yeah next routine is
    // dnagerous, but I like danger :P.
    char c;
    int p_tmp = -1;
    int n_tmp;
    while ((c = getopt (ac, av, "Vhv:p:n:b:")) != -1) {
        switch (c) {
            case 'V':
                std::cout << "Verison " << VERSION << std::endl;
                exit(0);
            case '?':
                r = ERR_BAD_ARGUMENT;
            case 'h':
                std::cout << "Usage:\n"
                    << "\t-h\t\tOutput this message and exit\n"
                    << "\t-v <level>\tVerbosity level (default 0). Values 1+ are not implemented\n"
                    << "\t-p <number>\tAsign to pad 0..5\n"
                    << "\t-n <note>\tnote in range 0..127\n"
                    << "\t-b <integer>\tSelect size of loop_buffer (default 0)\n";
                exit(r);
            case 'v':
                verbatim = atoi(optarg);
                break;
            case 'p':
                p_tmp = atoi(optarg);
                if (p_tmp >= NOF_PADS)
                    exit(ERR_BAD_ARGUMENT);
                break;
            case 'n':
                n_tmp = atoi(optarg);
                if (n_tmp > 127)
                    exit(ERR_BAD_ARGUMENT);
                drumkit_callback->pad_map[p_tmp] = n_tmp;
                break;
            case 'b':
                drumkit_callback->loop_buffer = atoi(optarg);
                break;
            default:
                abort();
        }
    }
    if (verbatim)
        std::cout << "Selected loop_buffer: " << drumkit_callback->loop_buffer << std::endl;

    if (p_tmp != -1) {
        std::cout << "Reassigned mapping:";
        for(int q=0; q<NOF_PADS; q++)
            std::cout << "\tPad" << q << ": " << (int) drumkit_callback->pad_map[q];
        std::cout << std::endl;
    }
}

static void signal_handler(int sig)
{
    run = false;
    std::cerr << "Signal " << sig << " received, exiting ...\n";
}

void jack_shutdown_handler(void * arg)
{
    //TODO: Generate signal SIGHUP or SIGUSR1.
    run = false;
    status = ERR_JACK_SERVER_CLOSED;
    std::cerr << "JACK server is not running anymore, exiting\n";
}

static int process(jack_nframes_t nframes, void * arg)
{
    jack_callback_arg drumkit_callback = *(jack_callback_arg*) arg;
    void * port_buf = jack_port_get_buffer(drumkit_callback.output_port, nframes);
    unsigned char * midi_buffer;
    jack_midi_clear_buffer(port_buf);
    static bool was_free[6];

    for (int i = 0; i < 6; i++)
    if (drumkit_callback.pad_states[i]) {
        if (was_free[i]) {
            was_free[i] = false;
            midi_buffer = jack_midi_event_reserve(port_buf, 0, 3);
            midi_buffer[0] = 0x99;
            midi_buffer[1] = drumkit_callback.pad_map[i];
            midi_buffer[2] = 0x7F;
        }
    } else {
        if (!was_free[i]) {
            was_free[i] = true;
            midi_buffer = jack_midi_event_reserve(port_buf, 0, 3);
            midi_buffer[0] = 0x89;
            midi_buffer[1] = drumkit_callback.pad_map[i];
            midi_buffer[2] = 0x00;
        }
    }

    return 0;
}

libusb_device_handle * open_device(int vendor, int product)
{
    libusb_device ** devices;
    libusb_device_descriptor desc;
    libusb_config_descriptor * config;
    libusb_device_handle * devh;
    int r;

    int cnt = libusb_get_device_list(NULL, &devices);
    if (cnt < 0) {
        std::cerr << "libusb_get_device_list: " << libusb_strerror((enum libusb_error)cnt) << "\n";
        return NULL;
    }

    for (int i = 0; i < cnt; i++) {
        libusb_get_device_descriptor(devices[i], &desc);
        if (desc.idVendor == vendor && desc.idProduct == product) {
            if (verbatim)
                std::cout << "Rollup Drumkit connected!\n" << std::endl;
            r = libusb_get_config_descriptor(devices[i], 0, &config);
            if (r < 0) {
                std::cerr << "libusb_get_config_descriptor: " << libusb_strerror((enum libusb_error)r) << "\n";
                return NULL;
            }
            r = libusb_open(devices[i], &devh);
            if (r < 0) {
                std::cerr << "libusb_open: " << libusb_strerror((enum libusb_error)r) << "\n";
                return NULL;
            }
        }
    }
    libusb_free_device_list(devices, 1);
    return devh;
}

<commit_msg>Refactoring<commit_after>//% Rollup drumkit userspace driver
//% Alex Grabovski <hurufu@gmail.com>
//% 2014-04-21
//% WTFPL

#include <iostream>
#include <csignal>
#include <unistd.h>
#include <libusb.h>
#include <jack/jack.h>
#include <jack/midiport.h>

#define VERSION 0.3
#define DRUMKIT_VENDOR_ID 0x1941
#define DRUMKIT_PRODUCT_ID 0x8021
#define DRUMKIT_WMAXPACKETSIZE 8
#define DRUMKIT_ENDPOINT 1
#define NOF_PADS 6

// Error codes
#define SUCCESS 0
#define ERR_ANSWER_LENGTH_MISMATCH 0x1f
#define ERR_TRANSFER_FAILED 0x1e
#define ERR_LIBUSB_SPECIFIC 0x1d
#define ERR_JACK_SPECIFIC 0x1c
#define ERR_BAD_ARGUMENT 0x1b
#define ERR_UNKNOWN 0x1a
#define ERR_JACK_SERVER_CLOSED 0x19

// Program state flags
int r = SUCCESS; // Is used to temporary hold functions return values
int status = SUCCESS; // Overall program status
int verbatim = 0; // Verbosity level
bool run = true; // Main loop trigger

struct jack_callback_arg {
    jack_port_t * output_port;
    char pad_map[NOF_PADS];
    bool pad_states[NOF_PADS];
    int loop_buffer;
};

libusb_device_handle * open_device(int vendor, int product);
static int process(jack_nframes_t nframes, void * arg);
void option_handler(int ac, char ** av, jack_callback_arg * drumkit_callback);
static void signal_handler(int);
void jack_shutdown_handler(void *);

int main (int ac, char ** av)
{
    libusb_device_handle * usb_drumkit_handle = NULL;
    jack_client_t * jack_midi_drum = NULL;
    const char jack_midi_drum_str[] = "Dreamlink Foldup Drumk Kit";
    volatile unsigned char raw[DRUMKIT_WMAXPACKETSIZE];
    int transfered;

    struct jack_callback_arg drumkit_callback;
    for (int i=0; i < NOF_PADS; i++)
        drumkit_callback.pad_map[i] = 0x20 + i;
    drumkit_callback.loop_buffer = 0;

    option_handler(ac, av, &drumkit_callback);

    r = libusb_init(NULL);
    if (r != SUCCESS) {
        std::cerr << "ERROR: " << libusb_strerror((enum libusb_error)r) << "\n";
        return ERR_LIBUSB_SPECIFIC;
    }
    libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_INFO);
    usb_drumkit_handle = open_device(DRUMKIT_VENDOR_ID, DRUMKIT_PRODUCT_ID);
    if ( usb_drumkit_handle == NULL ) {
        std::cerr << "ERROR: Unable to open drumkit! Probably it isn't connected.\n";
        status = ERR_LIBUSB_SPECIFIC;
        goto usb_exit;
    }
    r = libusb_set_auto_detach_kernel_driver(usb_drumkit_handle, 1);
    if (r != SUCCESS) {
        std::cerr << "ERROR: Could not set auto detach usb kernel driver. " << libusb_strerror((enum libusb_error)r) << "\n";
        status = ERR_LIBUSB_SPECIFIC;
        goto usb_close;
    }
    r = libusb_claim_interface(usb_drumkit_handle, 0);
    if (r != SUCCESS) {
        std::cerr << "ERROR: Cannot claim interface. " << libusb_strerror((enum libusb_error)r) << "\n";
        status = ERR_LIBUSB_SPECIFIC;
        goto usb_close;
    }

    jack_midi_drum = jack_client_open(jack_midi_drum_str, JackNullOption, NULL);
    if (jack_midi_drum == NULL) {
        std::cerr << "ERROR: Unable to initiate JACK client! Is JACK server running?\n";
        status = ERR_JACK_SPECIFIC;
        goto usb_release;
    }
    drumkit_callback.output_port = jack_port_register(jack_midi_drum, "out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
    jack_set_process_callback(jack_midi_drum, process, &drumkit_callback);
    jack_on_shutdown(jack_midi_drum, jack_shutdown_handler, &r);
    r = jack_activate(jack_midi_drum);
    if (r != SUCCESS) {
        std::cerr << "ERROR: Cannot activate JACK client --- " << r << "\n";
        status = ERR_JACK_SPECIFIC;
        goto jack_close;
    }

    signal(SIGQUIT, signal_handler);
    signal(SIGHUP,  signal_handler);
    signal(SIGTERM, signal_handler);
    signal(SIGINT,  signal_handler);

    while(run) {
        unsigned char p = 0;
        for(int i = 0; i <= drumkit_callback.loop_buffer; i++)
        {
            r = libusb_interrupt_transfer (
                usb_drumkit_handle,
                DRUMKIT_ENDPOINT | LIBUSB_ENDPOINT_IN,
                (unsigned char*) raw,
                DRUMKIT_WMAXPACKETSIZE,
                &transfered,
                0
            );
            if(r >= 0) {
                if (transfered != DRUMKIT_WMAXPACKETSIZE) {
                    std::cerr << "ERROR: Answer length mismatch.\n";
                    status = ERR_ANSWER_LENGTH_MISMATCH;
                    goto jack_deact;
                }
                for (int j = 0; j < transfered; j++)
                    p |= raw[j];
            }
            else {
                std::cerr << "ERROR: " << libusb_strerror((enum libusb_error)r) << ".\n";
                status = ERR_TRANSFER_FAILED;
                goto jack_deact;
            }
        }
        for (int i = 0; i < NOF_PADS; i++) {
            drumkit_callback.pad_states[i] = p & 1;
            p >>= 1;
        }
    }

jack_deact:
    if (status != ERR_JACK_SERVER_CLOSED)
        jack_deactivate(jack_midi_drum);
jack_close:
    if (status != ERR_JACK_SERVER_CLOSED)
        jack_client_close(jack_midi_drum);
usb_release:
    libusb_release_interface(usb_drumkit_handle, 0);
usb_close:
    libusb_close(usb_drumkit_handle);
usb_exit:
    libusb_exit(NULL);
    return status;
}

void option_handler(int ac, char ** av, jack_callback_arg * drumkit_callback)
{
    //FIXME I dont have enough stamina to write getopt, and I don't want getopt
    // to be larger than actual driver! I have a plan 'bout ultimate™ getopt,
    // but I don't think I'll make it soon... And yeah next routine is
    // dnagerous, but I like danger :P.
    char c;
    int p_tmp = -1;
    int n_tmp;
    while ((c = getopt (ac, av, "Vhv:p:n:b:")) != -1) {
        switch (c) {
            case 'V':
                std::cout << "Verison " << VERSION << std::endl;
                exit(0);
            case '?':
                r = ERR_BAD_ARGUMENT;
            case 'h':
                std::cout << "Usage:\n"
                    << "\t-h\t\tOutput this message and exit\n"
                    << "\t-v <level>\tVerbosity level (default 0). Values 1+ are not implemented\n"
                    << "\t-p <number>\tAsign to pad 0..5\n"
                    << "\t-n <note>\tnote in range 0..127\n"
                    << "\t-b <integer>\tSelect size of loop buffer (default 0)\n";
                exit(r);
            case 'v':
                verbatim = atoi(optarg);
                break;
            case 'p':
                p_tmp = atoi(optarg);
                if (p_tmp >= NOF_PADS)
                    exit(ERR_BAD_ARGUMENT);
                break;
            case 'n':
                n_tmp = atoi(optarg);
                if (n_tmp > 127)
                    exit(ERR_BAD_ARGUMENT);
                drumkit_callback->pad_map[p_tmp] = n_tmp;
                break;
            case 'b':
                drumkit_callback->loop_buffer = atoi(optarg);
                break;
            default:
                abort();
        }
    }
    if (verbatim)
        std::cout << "INFO: Selected loop buffer size: " << drumkit_callback->loop_buffer << std::endl;

    if (p_tmp != -1) {
        std::cout << "INFO: Reassigned mapping:";
        for(int q=0; q<NOF_PADS; q++)
            std::cout << "\tPad" << q << ": " << (int) drumkit_callback->pad_map[q];
        std::cout << std::endl;
    }
}

static void signal_handler(int sig)
{
    run = false;
    std::cerr << "Signal " << sig << " received, exiting ...\n";
}

void jack_shutdown_handler(void * arg)
{
    //TODO: Generate signal SIGHUP or SIGUSR1.
    run = false;
    status = ERR_JACK_SERVER_CLOSED;
    std::cerr << "ERROR: JACK server is not running anymore, exiting\n";
}

static int process(jack_nframes_t nframes, void * arg)
{
    jack_callback_arg drumkit_callback = *(jack_callback_arg*) arg;
    void * port_buf = jack_port_get_buffer(drumkit_callback.output_port, nframes);
    unsigned char * midi_buffer;
    jack_midi_clear_buffer(port_buf);
    static bool was_free[6];

    for (int i = 0; i < 6; i++)
    if (drumkit_callback.pad_states[i]) {
        if (was_free[i]) {
            was_free[i] = false;
            midi_buffer = jack_midi_event_reserve(port_buf, 0, 3);
            midi_buffer[0] = 0x99;
            midi_buffer[1] = drumkit_callback.pad_map[i];
            midi_buffer[2] = 0x7F;
        }
    } else {
        if (!was_free[i]) {
            was_free[i] = true;
            midi_buffer = jack_midi_event_reserve(port_buf, 0, 3);
            midi_buffer[0] = 0x89;
            midi_buffer[1] = drumkit_callback.pad_map[i];
            midi_buffer[2] = 0x00;
        }
    }

    return 0;
}

libusb_device_handle * open_device(int vendor, int product)
{
    libusb_device ** devices;
    libusb_device_descriptor desc;
    libusb_config_descriptor * config;
    libusb_device_handle * devh;
    int r;

    int cnt = libusb_get_device_list(NULL, &devices);
    if (cnt < 0) {
        std::cerr << "ERROR: Cannot get usb devices list." << libusb_strerror((enum libusb_error)cnt) << "\n";
        return NULL;
    }

    for (int i = 0; i < cnt; i++) {
        libusb_get_device_descriptor(devices[i], &desc);
        if (desc.idVendor == vendor && desc.idProduct == product) {
            if (verbatim)
                std::cout << "INFO: Rollup Drumkit connected.\n" << std::endl;
            r = libusb_get_config_descriptor(devices[i], 0, &config);
            if (r < 0) {
                std::cerr << "ERROR: Cannot get config descriptor. " << libusb_strerror((enum libusb_error)r) << "\n";
                return NULL;
            }
            r = libusb_open(devices[i], &devh);
            if (r < 0) {
                std::cerr << "ERROR: Cannot open usb device. " << libusb_strerror((enum libusb_error)r) << "\n";
                return NULL;
            }
        }
    }
    libusb_free_device_list(devices, 1);
    return devh;
}

<|endoftext|>


<commit_before>76ef441e-ad5a-11e7-9409-ac87a332f658<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>779be175-ad5a-11e7-a4bc-ac87a332f658<|endoftext|>


<commit_before>#include <bitset>
#include <iomanip>
#include <iostream>

#ifndef FLOAT_VAL
#define FLOAT_VAL 0xc32d3be7 // -173.234
//#define FLOAT_VAL 0x00000000 // +0
//#define FLOAT_VAL 0x80000000 // -0
//#define FLOAT_VAL 0x7f800000 // +inf
//#define FLOAT_VAL 0xff800000 // -inf
//#define FLOAT_VAL 0xffc20200 // NaN
#endif

namespace
{ // anonymous

// sign * 2^exponent * mantissa
static const uint8_t sign_bits = 1;
static const uint8_t exponent_bits = 8;
static const uint8_t mantissa_bits = 23;

// SEEEEEEE EMMMMMMM MMMMMMMM MMMMMMMM
// 00       7F       FF       FF       Mantissa MASK
// 80       00       00       00       Sign MASK
// 7F       80       00       00       Exponent MASK
static const uint32_t sign_mask = 0x80000000;
static const uint32_t exponent_mask = 0x7F800000;
static const uint32_t mantissa_mask = 0x007FFFFF;

static const uint16_t buffer_size = 256;

} // end anonymous namespace

template <uint32_t sign, uint32_t exponent, uint32_t mantissa> class IEEE_754
{
  private:
    enum colour_codes_e
    {
        console_red = 31,
        console_green = 32,
        console_blue = 34,
        console_purple = 35,
        console_default = 39
    };

    template <colour_codes_e colour> void print_colour(const char* c_str)
    {
        std::cout << "\033[" << colour << "m";
        std::cout << c_str;
        std::cout << "\033[" << console_default << "m";
    }

    template <colour_codes_e colour, size_t bitset_size> void print_colour(std::bitset<bitset_size> bitset)
    {
        std::cout << "\033[" << colour << "m";
        std::cout << bitset;
        std::cout << "\033[" << console_default << "m";
    }

    void print_int_as_string(uint32_t x) const
    {
        while (x != 0)
        {
            int rem = x % 10;
            s_printable_buffer[s_buffer_index++] = (rem > 9) ? (rem - 10) + 'a' : rem + '0';
            x = x / 10;
        }
    }

    static char s_printable_buffer[buffer_size];
    static unsigned int s_buffer_index;

  public:
    constexpr IEEE_754()
    {
        if (sign)
            s_printable_buffer[s_buffer_index++] = '-';

        // Exponent is a 2's complement number
        // exponent has a bias of 127, which we must subtract
        const int32_t adjusted_exp = static_cast<int32_t>(exponent) - 127;

        //// Hidden 24th bit is 1 in mantissa
        const uint32_t full_mantissa = mantissa | (1 << mantissa_bits);

        const uint32_t adjustment = mantissa_bits - adjusted_exp;

        uint32_t integer_component = full_mantissa >> adjustment;

        print_int_as_string(integer_component);
        s_printable_buffer[s_buffer_index++] = '.';

        //// Top of the fraction
        uint32_t frac = full_mantissa & ((1 << adjustment) - 1);

        //// Base of the fraction, must be bigger than frac
        uint32_t base = 1 << adjustment;

        int decimal_places = 0;
        const int max_digits_to_print = 12;
        const int base_10 = 10;
        while (frac != 0 && decimal_places++ < max_digits_to_print)
        {
            frac *= base_10;
            print_int_as_string(frac / base);
            frac %= base;
        }

        s_printable_buffer[s_buffer_index++] = '\0';
    }
    void print()
    {
        print_colour<console_red>("Sign ");
        print_colour<console_blue>("Exponent ");
        print_colour<console_green>("Mantissa ");
        std::cout << std::endl;

        print_colour<console_red, sign_bits>(std::bitset<sign_bits>(sign));
        print_colour<console_blue, exponent_bits>(std::bitset<exponent_bits>(exponent));
        print_colour<console_green, mantissa_bits>(std::bitset<mantissa_bits>(mantissa));
        std::cout << std::endl;

        print_colour<console_purple>("Float: ");
        print_colour<console_purple>(s_printable_buffer);
        std::cout << std::endl;
    }
};

template <uint32_t sign, uint32_t exponent, uint32_t mantissa>
unsigned int IEEE_754<sign, exponent, mantissa>::s_buffer_index = 0;

template <uint32_t sign, uint32_t exponent, uint32_t mantissa>
char IEEE_754<sign, exponent, mantissa>::s_printable_buffer[buffer_size] = {0};

template <uint32_t sign> class IEEE_754<sign, 0u, 0>
{
  private:
    enum colour_codes_e
    {
        console_red = 31,
        console_green = 32,
        console_blue = 34,
        console_purple = 35,
        console_default = 39
    };

    template <colour_codes_e colour> void print_colour(const char* c_str)
    {
        std::cout << "\033[" << colour << "m";
        std::cout << c_str;
        std::cout << "\033[" << console_default << "m";
    }

    template <colour_codes_e colour, size_t bitset_size> void print_colour(std::bitset<bitset_size> bitset)
    {
        std::cout << "\033[" << colour << "m";
        std::cout << bitset;
        std::cout << "\033[" << console_default << "m";
    }

  public:
    void print()
    {
        print_colour<console_red>("Sign ");
        print_colour<console_blue>("Exponent ");
        print_colour<console_green>("Mantissa ");
        std::cout << std::endl;

        print_colour<console_red, sign_bits>(std::bitset<sign_bits>(sign));
        print_colour<console_blue, exponent_bits>(std::bitset<exponent_bits>(0));
        print_colour<console_green, mantissa_bits>(std::bitset<mantissa_bits>(0));
        std::cout << std::endl;

        if (sign)
            print_colour<console_purple>("Float: -0");
        else
            print_colour<console_purple>("Float: +0");
        std::cout << std::endl;
    }
};

template <uint32_t sign> class IEEE_754<sign, 255u, 0u>
{
  private:
    enum colour_codes_e
    {
        console_red = 31,
        console_green = 32,
        console_blue = 34,
        console_purple = 35,
        console_default = 39
    };

    template <colour_codes_e colour> void print_colour(const char* c_str)
    {
        std::cout << "\033[" << colour << "m";
        std::cout << c_str;
        std::cout << "\033[" << console_default << "m";
    }

    template <colour_codes_e colour, size_t bitset_size> void print_colour(std::bitset<bitset_size> bitset)
    {
        std::cout << "\033[" << colour << "m";
        std::cout << bitset;
        std::cout << "\033[" << console_default << "m";
    }

  public:
    void print()
    {
        print_colour<console_red>("Sign ");
        print_colour<console_blue>("Exponent ");
        print_colour<console_green>("Mantissa ");
        std::cout << std::endl;

        print_colour<console_red, sign_bits>(std::bitset<sign_bits>(sign));
        print_colour<console_blue, exponent_bits>(std::bitset<exponent_bits>(255u));
        print_colour<console_green, mantissa_bits>(std::bitset<mantissa_bits>(0u));
        std::cout << std::endl;

        if (sign)
            print_colour<console_purple>("Float: -INF");
        else
            print_colour<console_purple>("Float: +INF");
        std::cout << std::endl;
    }
};

template <uint32_t sign, uint32_t mantissa> class IEEE_754<sign, 255u, mantissa>
{
  private:
    enum colour_codes_e
    {
        console_red = 31,
        console_green = 32,
        console_blue = 34,
        console_purple = 35,
        console_default = 39
    };

    template <colour_codes_e colour> void print_colour(const char* c_str)
    {
        std::cout << "\033[" << colour << "m";
        std::cout << c_str;
        std::cout << "\033[" << console_default << "m";
    }

    template <colour_codes_e colour, size_t bitset_size> void print_colour(std::bitset<bitset_size> bitset)
    {
        std::cout << "\033[" << colour << "m";
        std::cout << bitset;
        std::cout << "\033[" << console_default << "m";
    }

  public:
    void print()
    {
        print_colour<console_red>("Sign ");
        print_colour<console_blue>("Exponent ");
        print_colour<console_green>("Mantissa ");
        std::cout << std::endl;

        print_colour<console_red, sign_bits>(std::bitset<sign_bits>(sign));
        print_colour<console_blue, exponent_bits>(std::bitset<exponent_bits>(255u));
        print_colour<console_green, mantissa_bits>(std::bitset<mantissa_bits>(mantissa));
        std::cout << std::endl;

        print_colour<console_purple>("Float: NaN");
        std::cout << std::endl;
    }
};

int main()
{
    constexpr const uint32_t float_rep = FLOAT_VAL;

    // Get sign bit
    const uint32_t sign = (float_rep & sign_mask) >> (32 - sign_bits);

    // Get 8 exponents bits
    const uint32_t exponent = (float_rep & exponent_mask) >> mantissa_bits;

    // Get 23 mantissa bits
    const uint32_t mantissa = float_rep & mantissa_mask;

    // Get 23 mantissa bits
    // Instantiate print helper class
    IEEE_754<sign, exponent, mantissa> printer;

    // Print to stdout at runtime
    printer.print();

    return 0;
}
<commit_msg>remove code duplication for printing<commit_after>#include <bitset>
#include <iomanip>
#include <iostream>

#ifndef FLOAT_VAL
#define FLOAT_VAL 0xc32d3be7 // -173.234
//#define FLOAT_VAL 0x00000000 // +0
//#define FLOAT_VAL 0x80000000 // -0
//#define FLOAT_VAL 0x7f800000 // +inf
//#define FLOAT_VAL 0xff800000 // -inf
//#define FLOAT_VAL 0xffc20200 // NaN
#endif

namespace
{ // anonymous

// sign * 2^exponent * mantissa
static const uint8_t sign_bits = 1;
static const uint8_t exponent_bits = 8;
static const uint8_t mantissa_bits = 23;

// SEEEEEEE EMMMMMMM MMMMMMMM MMMMMMMM
// 00       7F       FF       FF       Mantissa MASK
// 80       00       00       00       Sign MASK
// 7F       80       00       00       Exponent MASK
static const uint32_t sign_mask = 0x80000000;
static const uint32_t exponent_mask = 0x7F800000;
static const uint32_t mantissa_mask = 0x007FFFFF;

static const uint16_t buffer_size = 256;

enum colour_codes_e
{
    console_red = 31,
    console_green = 32,
    console_blue = 34,
    console_purple = 35,
    console_default = 39
};

template <colour_codes_e colour> void print_colour(const char* c_str)
{
    std::cout << "\033[" << colour << "m";
    std::cout << c_str;
    std::cout << "\033[" << console_default << "m";
}

template <colour_codes_e colour, size_t bitset_size> void print_colour(std::bitset<bitset_size> bitset)
{
    std::cout << "\033[" << colour << "m";
    std::cout << bitset;
    std::cout << "\033[" << console_default << "m";
}

} // end anonymous namespace

template <uint32_t sign, uint32_t exponent, uint32_t mantissa> class IEEE_754
{
  private:
    void print_int_as_string(uint32_t x) const
    {
        while (x != 0)
        {
            int rem = x % 10;
            s_printable_buffer[s_buffer_index++] = (rem > 9) ? (rem - 10) + 'a' : rem + '0';
            x = x / 10;
        }
    }

    static char s_printable_buffer[buffer_size];
    static unsigned int s_buffer_index;

  public:
    constexpr IEEE_754()
    {
        if (sign)
            s_printable_buffer[s_buffer_index++] = '-';

        // Exponent is a 2's complement number
        // exponent has a bias of 127, which we must subtract
        const int32_t adjusted_exp = static_cast<int32_t>(exponent) - 127;

        //// Hidden 24th bit is 1 in mantissa
        const uint32_t full_mantissa = mantissa | (1 << mantissa_bits);

        const uint32_t adjustment = mantissa_bits - adjusted_exp;

        uint32_t integer_component = full_mantissa >> adjustment;

        print_int_as_string(integer_component);
        s_printable_buffer[s_buffer_index++] = '.';

        //// Top of the fraction
        uint32_t frac = full_mantissa & ((1 << adjustment) - 1);

        //// Base of the fraction, must be bigger than frac
        uint32_t base = 1 << adjustment;

        int decimal_places = 0;
        const int max_digits_to_print = 12;
        const int base_10 = 10;
        while (frac != 0 && decimal_places++ < max_digits_to_print)
        {
            frac *= base_10;
            print_int_as_string(frac / base);
            frac %= base;
        }

        s_printable_buffer[s_buffer_index++] = '\0';
    }
    void print()
    {
        print_colour<console_red>("Sign ");
        print_colour<console_blue>("Exponent ");
        print_colour<console_green>("Mantissa ");
        std::cout << std::endl;

        print_colour<console_red, sign_bits>(std::bitset<sign_bits>(sign));
        print_colour<console_blue, exponent_bits>(std::bitset<exponent_bits>(exponent));
        print_colour<console_green, mantissa_bits>(std::bitset<mantissa_bits>(mantissa));
        std::cout << std::endl;

        print_colour<console_purple>("Float: ");
        print_colour<console_purple>(s_printable_buffer);
        std::cout << std::endl;
    }
};

template <uint32_t sign, uint32_t exponent, uint32_t mantissa>
unsigned int IEEE_754<sign, exponent, mantissa>::s_buffer_index = 0;

template <uint32_t sign, uint32_t exponent, uint32_t mantissa>
char IEEE_754<sign, exponent, mantissa>::s_printable_buffer[buffer_size] = {0};

template <uint32_t sign> struct IEEE_754<sign, 0u, 0>
{
    void print()
    {
        print_colour<console_red>("Sign ");
        print_colour<console_blue>("Exponent ");
        print_colour<console_green>("Mantissa ");
        std::cout << std::endl;

        print_colour<console_red, sign_bits>(std::bitset<sign_bits>(sign));
        print_colour<console_blue, exponent_bits>(std::bitset<exponent_bits>(0));
        print_colour<console_green, mantissa_bits>(std::bitset<mantissa_bits>(0));
        std::cout << std::endl;

        if (sign)
            print_colour<console_purple>("Float: -0");
        else
            print_colour<console_purple>("Float: +0");
        std::cout << std::endl;
    }
};

template <uint32_t sign> struct IEEE_754<sign, 255u, 0u>
{
    void print()
    {
        print_colour<console_red>("Sign ");
        print_colour<console_blue>("Exponent ");
        print_colour<console_green>("Mantissa ");
        std::cout << std::endl;

        print_colour<console_red, sign_bits>(std::bitset<sign_bits>(sign));
        print_colour<console_blue, exponent_bits>(std::bitset<exponent_bits>(255u));
        print_colour<console_green, mantissa_bits>(std::bitset<mantissa_bits>(0u));
        std::cout << std::endl;

        if (sign)
            print_colour<console_purple>("Float: -INF");
        else
            print_colour<console_purple>("Float: +INF");
        std::cout << std::endl;
    }
};

template <uint32_t sign, uint32_t mantissa> struct IEEE_754<sign, 255u, mantissa>
{
    void print()
    {
        print_colour<console_red>("Sign ");
        print_colour<console_blue>("Exponent ");
        print_colour<console_green>("Mantissa ");
        std::cout << std::endl;

        print_colour<console_red, sign_bits>(std::bitset<sign_bits>(sign));
        print_colour<console_blue, exponent_bits>(std::bitset<exponent_bits>(255u));
        print_colour<console_green, mantissa_bits>(std::bitset<mantissa_bits>(mantissa));
        std::cout << std::endl;

        print_colour<console_purple>("Float: NaN");
        std::cout << std::endl;
    }
};

int main()
{
    constexpr const uint32_t float_rep = FLOAT_VAL;

    // Get sign bit
    const uint32_t sign = (float_rep & sign_mask) >> (32 - sign_bits);

    // Get 8 exponents bits
    const uint32_t exponent = (float_rep & exponent_mask) >> mantissa_bits;

    // Get 23 mantissa bits
    const uint32_t mantissa = float_rep & mantissa_mask;

    // Get 23 mantissa bits
    // Instantiate print helper class
    IEEE_754<sign, exponent, mantissa> printer;

    // Print to stdout at runtime
    printer.print();

    return 0;
}
<|endoftext|>


<commit_before>b98ad542-ad5b-11e7-9f0a-ac87a332f658<commit_msg>bug fix<commit_after>ba3b3b3a-ad5b-11e7-a1df-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>
#include <linux/i2c-dev.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <string.h>

#define CMD 0x80
#define DATA 0x40

using namespace std;

const char* i2c_bus;
int i2c_bus_handle;
uint8_t oled_address;
bool configured = false;

bool i2c_write_byte(uint8_t reg, uint8_t data) {
    char buf[2];
    buf[0] = reg;
    buf[1] = data;
    if(write(i2c_bus_handle, buf, 2) != 2) {
        cout << "Write to device failed\n";
        return false;
    }
    return true;
}

bool i2c_write_bytes(uint8_t reg, const char* data) {
    int len = sizeof(reg) + strlen(data);
    void *buf = calloc(1, len);
    memcpy(buf, &reg, 1);
    strcat((char*)buf, data);
    if(write(i2c_bus_handle, buf, len) != len) {
        cout << "Write to device failed\n";
        free(buf);
        return false;
    }
    free(buf);
    return true;
}

bool configure_display(const char* bus, uint8_t address) {
    i2c_bus = bus;
    oled_address = address;
    if((i2c_bus_handle = open(i2c_bus, O_RDWR)) < 0) {
        return false;
    } else {
        cout << "Bus access OK\n";
    }
    if (ioctl(i2c_bus_handle, I2C_SLAVE, oled_address) < 0) {
        return false;
    } else {
        cout << "Device access OK\n";
    }
    configured = true;
    return configured;
}

bool init_display() {
    i2c_write_byte(CMD, 0x2a); // **** Set "RE"=1<--->00101010B
    i2c_write_byte(CMD, 0x71);
    i2c_write_byte(CMD, 0x5c);
    i2c_write_byte(CMD, 0x28);
    i2c_write_byte(CMD, 0x08);
    i2c_write_byte(CMD, 0x2a);
    i2c_write_byte(CMD, 0x79);
    i2c_write_byte(CMD, 0xd5);
    i2c_write_byte(CMD, 0x70);
    i2c_write_byte(CMD, 0x78);
    i2c_write_byte(CMD, 0x08);
    i2c_write_byte(CMD, 0x06);
    i2c_write_byte(CMD, 0x2a);
    i2c_write_byte(CMD, 0x79);
    i2c_write_byte(CMD, 0x72);
    i2c_write_byte(CMD, 0x00);
    i2c_write_byte(CMD, 0xda);
    i2c_write_byte(CMD, 0x10);
    i2c_write_byte(CMD, 0x81); // set contrast
    i2c_write_byte(CMD, 0x50); // contrast level
    i2c_write_byte(CMD, 0xdb);
    i2c_write_byte(CMD, 0x30);
    i2c_write_byte(CMD, 0xdc);
    i2c_write_byte(CMD, 0x03);
    i2c_write_byte(CMD, 0x78);
    i2c_write_byte(CMD, 0x28);
    i2c_write_byte(CMD, 0x2a);
    i2c_write_byte(CMD, 0x06);
    i2c_write_byte(CMD, 0x08);
    i2c_write_byte(CMD, 0x28);
    i2c_write_byte(CMD, 0x01);
    i2c_write_byte(CMD, 0x80);
    i2c_write_byte(CMD, 0x0c);
}

int main() {
    configure_display("/dev/i2c-1", 0x3c);
    init_display();
    i2c_write_bytes(DATA, "Heisann hoppsan!");
    return 0;
}<commit_msg>Set cursor position<commit_after>#include <iostream>
#include <linux/i2c-dev.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <string.h>

#define CMD 0x80
#define DATA 0x40

using namespace std;

const char* i2c_bus;
int i2c_bus_handle;
uint8_t oled_address;
bool configured = false;

bool i2c_write_byte(uint8_t reg, uint8_t data) {
    char buf[2];
    buf[0] = reg;
    buf[1] = data;
    if(write(i2c_bus_handle, buf, 2) != 2) {
        cout << "Write to device failed\n";
        return false;
    }
    return true;
}

bool i2c_write_bytes(uint8_t reg, const char* data) {
    int len = sizeof(reg) + strlen(data);
    void *buf = calloc(1, len);
    memcpy(buf, &reg, 1);
    strcat((char*)buf, data);
    if(write(i2c_bus_handle, buf, len) != len) {
        cout << "Write to device failed\n";
        free(buf);
        return false;
    }
    free(buf);
    return true;
}

bool set_cursor_position(uint8_t col, uint8_t row) {
    int line_offsets[] = {
            0x00,  // start of line 1
            0x20,
            0x40,
            0x60   // start of line 4
    };
    return i2c_write_byte(CMD, 0x80 | (col + line_offsets[row]));
}

bool configure_display(const char* bus, uint8_t address) {
    i2c_bus = bus;
    oled_address = address;
    if((i2c_bus_handle = open(i2c_bus, O_RDWR)) < 0) {
        return false;
    } else {
        cout << "Bus access OK\n";
    }
    if (ioctl(i2c_bus_handle, I2C_SLAVE, oled_address) < 0) {
        return false;
    } else {
        cout << "Device access OK\n";
    }
    configured = true;
    return configured;
}

bool init_display() {
    i2c_write_byte(CMD, 0x2a); // **** Set "RE"=1<--->00101010B
    i2c_write_byte(CMD, 0x71);
    i2c_write_byte(CMD, 0x5c);
    i2c_write_byte(CMD, 0x28);
    i2c_write_byte(CMD, 0x08); // display off
    i2c_write_byte(CMD, 0x2a);
    i2c_write_byte(CMD, 0x79);
    i2c_write_byte(CMD, 0xd5);
    i2c_write_byte(CMD, 0x70);
    i2c_write_byte(CMD, 0x78);
    i2c_write_byte(CMD, 0x09);
    i2c_write_byte(CMD, 0x06);
    i2c_write_byte(CMD, 0x72);
    i2c_write_byte(DATA, 0x00);
    i2c_write_byte(CMD, 0x2a);
    i2c_write_byte(CMD, 0x79);
    i2c_write_byte(CMD, 0xda);
    i2c_write_byte(CMD, 0x10);
    i2c_write_byte(CMD, 0xdc);
    i2c_write_byte(CMD, 0x00);
    i2c_write_byte(CMD, 0x81); // set contrast
    i2c_write_byte(CMD, 0x50); // contrast level
    i2c_write_byte(CMD, 0xdb);
    i2c_write_byte(CMD, 0x30);
    i2c_write_byte(CMD, 0xdc);
    i2c_write_byte(CMD, 0x03);
    i2c_write_byte(CMD, 0x78);
    i2c_write_byte(CMD, 0x28);
    i2c_write_byte(CMD, 0x2a);
    i2c_write_byte(CMD, 0x06);
    i2c_write_byte(CMD, 0x28);
    i2c_write_byte(CMD, 0x01);
    i2c_write_byte(CMD, 0x80);
    i2c_write_byte(CMD, 0x0c);
}

int main() {
    configure_display("/dev/i2c-1", 0x3c);
    init_display();
    set_cursor_position(4, 2);
    i2c_write_bytes(DATA, "Heisann hoppsan!");
    return 0;
}<|endoftext|>


<commit_before>aaacc97a-ad58-11e7-a25a-ac87a332f658<commit_msg>The previous fix has been fixed<commit_after>ab288c6b-ad58-11e7-b51d-ac87a332f658<|endoftext|>


<commit_before>/*
 * Copyright 2013 gtalent2@gmail.com
 *
 * 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 <string.h>
#include "core/core.hpp"
#include "models/enginemodels.hpp"
#include "tests.hpp"

using namespace models;
using namespace wombat;

int main(int argc, const char **args) {
	if (core::init(false) != 0) {
		return 1;
	}

	core::Drawer *test = 0;

	if (argc > 0 && !strcmp(args[1], "test")) {
		std::vector<std::string> vargs;
		for (int i = 0; i < argc; i++) {
			vargs.push_back(args[i]);
		}
		tests::test(vargs);
	}

	bool running = true;
	core::addEventListener([&running](core::Event e) {
		if (e.type == core::Quit) {
			running = false;
		}
	});
	while (running) {
		// draw
		core::pollEvents();
		core::draw();
		core::sleep(16);
	}

	if (test)
		delete test;

	return 0;
}
<commit_msg>Fixed crashing when run without any arguments.<commit_after>/*
 * Copyright 2013 gtalent2@gmail.com
 *
 * 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 <string.h>
#include "core/core.hpp"
#include "models/enginemodels.hpp"
#include "tests.hpp"

using namespace models;
using namespace wombat;

int main(int argc, const char **args) {
	if (core::init(false) != 0) {
		return 1;
	}

	core::Drawer *test = 0;

	if (argc > 1 && !strcmp(args[1], "test")) {
		std::vector<std::string> vargs;
		for (int i = 0; i < argc; i++) {
			vargs.push_back(args[i]);
		}
		tests::test(vargs);
	}

	bool running = true;
	core::addEventListener([&running](core::Event e) {
		if (e.type == core::Quit) {
			running = false;
		}
	});
	while (running) {
		// draw
		core::pollEvents();
		core::draw();
		core::sleep(16);
	}

	if (test)
		delete test;

	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
<commit_msg>main.cpp<commit_after>#include <iostream>

using namespace std;

int main()
{

    return 0;
}
<|endoftext|>