<commit_before>
#include <string>

/// Some documentation
struct s{
	std::string i;
};

int main(int argc, char *argv[]){
	int b = 1;
	b++;

	void* p;

	int* c = new int(2);

	char dir[1024];
	strcpy(dir, argv[1]);
	sprintf(dir, argv[1]);
}

<commit_msg>added missing header<commit_after>
#include <cstring>
#include <string>

/// Some documentation
struct s{
	std::string i;
};

int main(int argc, char *argv[]){
	int b = 1;
	b++;

	void* p;

	int* c = new int(2);

	char dir[1024];
	std::strcpy(dir, argv[1]);
	std::sprintf(dir, argv[1]);
}

<|endoftext|>


<commit_before>#include <iostream>
#include <cmath> ///@todo only needed for example formula, maybe remove later

#include "CalculatorBase.h"
#include "OptSimulatedAnnealing.h"

class MyCalculator : public CalculatorBase
{
public:
    MyCalculator()
    {

    }

    void calculate(OptValue &optValue) const ///@todo make static for easier usage (may not work like this[static] or at least not help)
    {
#ifdef DEBUG
        std::cout << "DEBUG: in MyCalculator" << std::endl;
#endif
        optValue.result = pow(optValue.get_parameter("X"),2);
#ifdef DEBUG
        std::cout << "DEBUG: result: " << optValue.result << std::endl;
#endif
    }
};

using namespace std;

int main()
{
    std::vector<OptBoundary> optBoundaries;
    unsigned int maxCalculations = 100;
    OptTarget optTarget = APPROACH;
    T coolingFactor = 0.9;
    T startChance = 0.25;
    OptBoundary optBoundary(-3.0, 10.0, "X");
    optBoundaries.push_back(optBoundary);
    MyCalculator myCalculator;

    OptSimulatedAnnealing opt(optBoundaries, maxCalculations, &myCalculator, optTarget, 3.0, coolingFactor, startChance);

    OptBase::run_optimisations(1);

    return 0;
}

<commit_msg>changed the test to better test approach<commit_after>#include <iostream>
#include <cmath> ///@todo only needed for example formula, maybe remove later

#include "CalculatorBase.h"
#include "OptSimulatedAnnealing.h"

class MyCalculator : public CalculatorBase
{
public:
    MyCalculator()
    {

    }

    void calculate(OptValue &optValue) const ///@todo make static for easier usage (may not work like this[static] or at least not help)
    {
#ifdef DEBUG
        std::cout << "DEBUG: in MyCalculator" << std::endl;
#endif
        optValue.result = pow(optValue.get_parameter("X"),2);
#ifdef DEBUG
        std::cout << "DEBUG: result: " << optValue.result << std::endl;
#endif
    }
};

using namespace std;

int main()
{
    std::vector<OptBoundary> optBoundaries;
    unsigned int maxCalculations = 1000;
    OptTarget optTarget = APPROACH;
    T coolingFactor = 0.995;
    T startChance = 0.25;
    OptBoundary optBoundary(-3.0, 10.0, "X");
    optBoundaries.push_back(optBoundary);
    MyCalculator myCalculator;

    OptSimulatedAnnealing opt(optBoundaries, maxCalculations, &myCalculator, optTarget, 3.0, coolingFactor, startChance);

    OptBase::run_optimisations(1);

    return 0;
}

<|endoftext|>


<commit_before>76fec8d1-2749-11e6-a52d-e0f84713e7b8<commit_msg>Did ANOTHER thing<commit_after>770e0391-2749-11e6-9716-e0f84713e7b8<|endoftext|>


<commit_before>#include "AnimSymLoader.h"
#include "FilepathHelper.h"
#include "EasyAnimLoader.h"
#include "SpineAnimLoader.h"

#include <sprite2/AnimSymbol.h>

#include <json/json.h>

#include <fstream>

#include <string.h>

namespace gum
{

AnimSymLoader::AnimSymLoader(s2::AnimSymbol* sym,
							 bool flatten,
							 const SymbolLoader* sym_loader,
							 const SpriteLoader* spr_loader)
	: m_sym(sym)
	, m_spr_loader(spr_loader)
	, m_sym_loader(sym_loader)
	, m_flatten(flatten)
{
	if (m_sym) {
		m_sym->AddReference();
	}
}

AnimSymLoader::~AnimSymLoader()
{
	if (m_sym) {
		m_sym->RemoveReference();
	}
}

void AnimSymLoader::LoadJson(const std::string& filepath)
{
	if (!m_sym) {
		return;
	}

	std::string dir = FilepathHelper::Dir(filepath);

	Json::Value val;
	Json::Reader reader;
	std::locale::global(std::locale(""));
	std::ifstream fin(filepath.c_str());
	std::locale::global(std::locale("C"));
	reader.parse(fin, val);
	fin.close();

	if (val.isMember("skeleton") && val["skeleton"].isMember("spine")) {
		SpineAnimLoader loader(m_sym, m_sym_loader, m_spr_loader);
		loader.LoadJson(val, dir, filepath);
	} else {
		EasyAnimLoader loader(m_sym, m_flatten, m_spr_loader);
		loader.LoadJson(val, dir);
	}

	if (m_flatten) {
		m_sym->BuildFlatten(NULL);
	} else {
		m_sym->LoadCopy();
	}
}

void AnimSymLoader::LoadBin(const simp::NodeAnimation* node)
{
	EasyAnimLoader loader(m_sym, m_flatten, m_spr_loader);
	loader.LoadBin(node);

	if (m_flatten) {
		m_sym->BuildFlatten(NULL);
	} else {
		m_sym->LoadCopy();
	}

}

}<commit_msg>[FIXED] up s2, BuildCurr()<commit_after>#include "AnimSymLoader.h"
#include "FilepathHelper.h"
#include "EasyAnimLoader.h"
#include "SpineAnimLoader.h"

#include <sprite2/AnimSymbol.h>

#include <json/json.h>

#include <fstream>

#include <string.h>

namespace gum
{

AnimSymLoader::AnimSymLoader(s2::AnimSymbol* sym,
							 bool flatten,
							 const SymbolLoader* sym_loader,
							 const SpriteLoader* spr_loader)
	: m_sym(sym)
	, m_spr_loader(spr_loader)
	, m_sym_loader(sym_loader)
	, m_flatten(flatten)
{
	if (m_sym) {
		m_sym->AddReference();
	}
}

AnimSymLoader::~AnimSymLoader()
{
	if (m_sym) {
		m_sym->RemoveReference();
	}
}

void AnimSymLoader::LoadJson(const std::string& filepath)
{
	if (!m_sym) {
		return;
	}

	std::string dir = FilepathHelper::Dir(filepath);

	Json::Value val;
	Json::Reader reader;
	std::locale::global(std::locale(""));
	std::ifstream fin(filepath.c_str());
	std::locale::global(std::locale("C"));
	reader.parse(fin, val);
	fin.close();

	if (val.isMember("skeleton") && val["skeleton"].isMember("spine")) {
		SpineAnimLoader loader(m_sym, m_sym_loader, m_spr_loader);
		loader.LoadJson(val, dir, filepath);
	} else {
		EasyAnimLoader loader(m_sym, m_flatten, m_spr_loader);
		loader.LoadJson(val, dir);
	}

	if (m_flatten) {
		m_sym->BuildFlatten(NULL);
	} else {
		m_sym->LoadCopy();
	}
	m_sym->BuildCurr();
}

void AnimSymLoader::LoadBin(const simp::NodeAnimation* node)
{
	EasyAnimLoader loader(m_sym, m_flatten, m_spr_loader);
	loader.LoadBin(node);

	if (m_flatten) {
		m_sym->BuildFlatten(NULL);
	} else {
		m_sym->LoadCopy();
	}
	m_sym->BuildCurr();
}

}<|endoftext|>


<commit_before>5e691cb8-ad5c-11e7-aa66-ac87a332f658<commit_msg>TODO: Add a beter commit message<commit_after>5ee17e38-ad5c-11e7-a086-ac87a332f658<|endoftext|>


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

#include "Electrocardio.h"

template<>
InputParameters validParams<Electrocardio>()
{
  InputParameters params = validParams<Material>();
  params.addRequiredCoupledVar("vmem","Membrane potential needed as input for ion channel model");
  //! @todo: For ion channel models that need the diffusion current, have to fetch the value of Imem somehow
  return params;
}

Electrocardio::Electrocardio(const std::string & name,
                                 InputParameters parameters) :
  Material(name, parameters),
  _Iion(declareProperty<Real>("Iion")),
  _gates(declareProperty<std::vector<Real> >("gates")),
  _gates_old(declarePropertyOld<std::vector<Real> >("gates")),
  // coupled variables
  _vmem(coupledValue("vmem"))
{

  // Create pointer to a Bernus model object using the factory class
  _ionmodel = IionmodelFactory::factory(IionmodelFactory::BERNUS);
}

void
Electrocardio::initQpStatefulProperties()
{
  // initialize local gate variable vector
  _ionmodel->initialize(&(_gates[_qp]));
}

/**
 * @todo documentation
 */
void
Electrocardio::computeQpProperties()
{

  // Compute ionforcing
  _Iion[_qp] = _ionmodel->ionforcing(_vmem[_qp], &(_gates_old[_qp]));

  // Copy old values into _gates as initial value
  for (int i=0; i<_ionmodel->get_ngates(); i++) {
    _gates[_qp][i] = _gates_old[_qp][i];
  }

  // Perform one Rush-Larsen time step to propagate forward gating variables
  _ionmodel->rush_larsen_step(_vmem[_qp], _dt, &(_gates[_qp]));

  /**
   * The mono domain equations reads
   *
   * V_t + div( G grad(V)) = I_ion(V)
   *
   * where G is a conductivity tensor, I_ion the current [unit Ampere] generated by the membrane potential V [unit Volt].
   * The ODE for the membrane states S reads
   *
   * S_t = Z(V,S)
   *
   * with V being the membrane potential.
   * The dependance of I_ion on V and the evolution of the state variables S is given by some membrane model, e.g. Bernus.
   *
   * In propag, the following names are used
   *
   * Vmem = V = membrane potential = variable in reaction-diffusion PDE
   * Iion = I_ion(V) = ion current = reaction term in PDE
   * Imem = diffusion current = div( G grad(V))
   * yyy  = S = cell states = variable in the ODE
   */

}
<commit_msg>avoiding warning messages about being unable to output gates material parameter<commit_after>#include "Electrocardio.h"

template<>
InputParameters validParams<Electrocardio>()
{
  InputParameters params = validParams<Material>();
  params.addRequiredCoupledVar("vmem","Membrane potential needed as input for ion channel model");
  //! @todo: For ion channel models that need the diffusion current, have to fetch the value of Imem somehow

  // we restrict output to Imem to avoid warnings about gates being impossible to be used in output
  std::vector<std::string> output_properties;
  output_properties.push_back("Iion");
  params.set<std::vector<std::string> >("output_properties") = output_properties;
  return params;
}

Electrocardio::Electrocardio(const std::string & name,
                                 InputParameters parameters) :
  Material(name, parameters),
  _Iion(declareProperty<Real>("Iion")),
  _gates(declareProperty<std::vector<Real> >("gates")),
  _gates_old(declarePropertyOld<std::vector<Real> >("gates")),
  // coupled variables
  _vmem(coupledValue("vmem"))
{

  // Create pointer to a Bernus model object using the factory class
  _ionmodel = IionmodelFactory::factory(IionmodelFactory::BERNUS);
}

void
Electrocardio::initQpStatefulProperties()
{
  // initialize local gate variable vector
  _ionmodel->initialize(&(_gates[_qp]));
}

/**
 * @todo documentation
 */
void
Electrocardio::computeQpProperties()
{

  // Compute ionforcing
  _Iion[_qp] = _ionmodel->ionforcing(_vmem[_qp], &(_gates_old[_qp]));

  // Copy old values into _gates as initial value
  for (int i=0; i<_ionmodel->get_ngates(); i++) {
    _gates[_qp][i] = _gates_old[_qp][i];
  }

  // Perform one Rush-Larsen time step to propagate forward gating variables
  _ionmodel->rush_larsen_step(_vmem[_qp], _dt, &(_gates[_qp]));

  /**
   * The mono domain equations reads
   *
   * V_t + div( G grad(V)) = I_ion(V)
   *
   * where G is a conductivity tensor, I_ion the current [unit Ampere] generated by the membrane potential V [unit Volt].
   * The ODE for the membrane states S reads
   *
   * S_t = Z(V,S)
   *
   * with V being the membrane potential.
   * The dependance of I_ion on V and the evolution of the state variables S is given by some membrane model, e.g. Bernus.
   *
   * In propag, the following names are used
   *
   * Vmem = V = membrane potential = variable in reaction-diffusion PDE
   * Iion = I_ion(V) = ion current = reaction term in PDE
   * Imem = diffusion current = div( G grad(V))
   * yyy  = S = cell states = variable in the ODE
   */

}
<|endoftext|>


<commit_before>#pragma once
#include "stdafx.h"
#include "utilities/lua_state_wrapper.h"
#include "hypersomnia_gui.h"
#include "misc/vector_wrapper.h"

#include "misc/stream.h"
#include <chrono>
#include <ctime>
void callback_textbox::set_command_callback(luabind::object callback) {
	//luabind::object callbackobj = *callback;
	textbox_object.command_callback = [callback](std::wstring& wstr)	{
		luabind::call_function<void>(callback, augs::misc::towchar_vec(wstr));
	};
}

augs::misc::vector_wrapper<wchar_t> get_local_time() {
	auto now = std::chrono::system_clock::now();
	auto now_c = std::chrono::system_clock::to_time_t(now);
	auto tm = std::localtime(&now_c);

	return augs::misc::towchar_vec
		(L'[' + augs::misc::wstr<int>(tm->tm_hour) + L':' + augs::misc::wstr<int>(tm->tm_min) + L':' + augs::misc::wstr<int>(tm->tm_sec) + L']');
}

void callback_rect::set_focus_callback(luabind::object callback) {
	rect_obj.focus_callback = [callback]()	{
		luabind::call_function<void>(callback);
	};
}

void callback_rect::set_lpressed_callback(luabind::object callback) {
	rect_obj.lpressed_callback = [callback]()	{
		luabind::call_function<void>(callback);
	};
}

void callback_rect::set_hover_callback(luabind::object callback) {
	rect_obj.hover_callback = [callback]()	{
		luabind::call_function<void>(callback);
	};
}

void callback_rect::set_blur_callback(luabind::object callback) {
	rect_obj.blur_callback = [callback]()	{
		luabind::call_function<void>(callback);
	};
}

void callback_textbox::append_text(augs::graphics::gui::text::fstr& str, bool set_default_font) {
	auto prev_caret_pos = textbox_object.editor.get_caret_pos();
	auto prev_caret_sel = textbox_object.editor.get_selection_offset();

	textbox_object.editor.set_caret_end(false);

	if (set_default_font) {
		auto def_style = textbox_object.editor.get_default_style();

		for (auto& c : str) {
			c.font_used = def_style.f;
		}
	}

	textbox_object.editor.insert(str);

	textbox_object.editor.set_caret(prev_caret_pos, false);
	textbox_object.editor.set_selection_offset(prev_caret_sel);
}
using namespace graphics::gui;

stylesheet::style* resolve_attr(stylesheet& subject, std::string a) {
	if (a == "released") {
		return &subject.released;
	}
	else if (a == "focused") {
		return &subject.focused;
	}
	else if (a == "hovered") {
		return &subject.hovered;
	}
	else if (a == "pushed") {
		return &subject.pushed;
	}

	return nullptr;
}

void set_color(stylesheet& subject, std::string attr, augs::graphics::pixel_32 rgba) {
	auto* s = resolve_attr(subject, attr);

	if (s)
		s->color.set(rgba);
}

void set_border(stylesheet& subject, std::string attr, int w, augs::graphics::pixel_32 rgba) {
	auto* s = resolve_attr(subject, attr);

	if (s)
		s->border.set(solid_stroke(w, material(rgba)));
}

template <typename... Args>
void invokem (Args...) {

}

template<typename Signature>
struct setter_wrapper;

template<typename Ret, typename First, typename... Args>
struct setter_wrapper<Ret (First, Args...)> {
	template <typename T, stylesheet& get_style(T&), Ret setter_func(First, Args...)>
	static Ret setter(T& subject, Args... arguments) {
		return setter_func(get_style(subject), arguments...);
	}
};

#define wrap_set(_s, _g, _t) setter_wrapper<decltype(_s)>::setter<_t, _g, _s>

stylesheet& get_textbox_style(callback_textbox& c) {
	return c.textbox_object.styles;
}

stylesheet& get_rect_style(callback_rect& c) {
	return c.rect_obj.styles;
}

void hypersomnia_gui::bind(augs::lua_state_wrapper& wrapper) {
	callback_textbox a;
	invokem(a.textbox_object.styles, "aaa", augs::graphics::pixel_32(1, 1, 1, 1));

	//setter_wrapper<decltype(set_color)>::invoke(a, "aaa", augs::graphics::pixel_32(1, 1, 1, 1));
	(a, "aaa", augs::graphics::pixel_32(1, 1, 1, 1));
	luabind::module(wrapper.raw)[
		luabind::class_<hypersomnia_gui>("hypersomnia_gui")
		.def(luabind::constructor<augs::window::glwindow&>())
		.def("poll_events", &poll_events)
		.def("setup", &setup)
		.def("blur", &blur)
		.def("draw_call", &draw_call),

		luabind::class_<callback_textbox>("callback_textbox")
		.def(luabind::constructor<hypersomnia_gui&>())
		.def("append_text", &callback_textbox::append_text)
		.def("setup", &callback_textbox::setup)
		.def("set_caret", &callback_textbox::set_caret)
		.def("backspace", &callback_textbox::backspace)
		.def("view_caret", &callback_textbox::view_caret)
		.def("remove_line", &callback_textbox::remove_line)
		.def("is_focused", &callback_textbox::is_focused)
		.def("focus", &callback_textbox::focus)
		.def("get_length", &callback_textbox::get_length)
		.def("draw", &callback_textbox::draw)
		.def("clear_text", &callback_textbox::clear_text)
		.def("is_clean", &callback_textbox::is_clean)
		.def("set_area", &callback_textbox::set_area)
		.def("get_text_bbox", &callback_textbox::get_text_bbox)
		.def("set_alpha_range", &callback_textbox::set_alpha_range)
		.def("set_command_callback", &callback_textbox::set_command_callback),

		luabind::def("get_local_time", get_local_time),

		luabind::def("set_color", wrap_set(set_color, get_textbox_style, callback_textbox)),
		luabind::def("set_color", wrap_set(set_color, get_rect_style, callback_rect)),

		luabind::def("set_border", wrap_set(set_border, get_textbox_style, callback_textbox)),
		luabind::def("set_border", wrap_set(set_border, get_rect_style, callback_rect)),

		luabind::class_<callback_rect>("callback_rect")
		.def(luabind::constructor<hypersomnia_gui&>())
		.def("setup", &callback_rect::setup)
		.def("focus", &callback_rect::focus)
		.def("set_focus_callback", &callback_rect::set_focus_callback)
		.def("set_lpressed_callback", &callback_rect::set_lpressed_callback)
		.def("set_hover_callback", &callback_rect::set_hover_callback)
		.def("set_blur_callback", &callback_rect::set_blur_callback)
	];
}<commit_msg>corrected time formatting<commit_after>#pragma once
#include "stdafx.h"
#include "utilities/lua_state_wrapper.h"
#include "hypersomnia_gui.h"
#include "misc/vector_wrapper.h"

#include "misc/stream.h"
#include <chrono>
#include <ctime>
void callback_textbox::set_command_callback(luabind::object callback) {
	//luabind::object callbackobj = *callback;
	textbox_object.command_callback = [callback](std::wstring& wstr)	{
		luabind::call_function<void>(callback, augs::misc::towchar_vec(wstr));
	};
}

augs::misc::vector_wrapper<wchar_t> get_local_time() {
	auto now = std::chrono::system_clock::now();
	auto now_c = std::chrono::system_clock::to_time_t(now);
	auto tm = std::localtime(&now_c);

	auto hours = augs::misc::wstr<int>(tm->tm_hour);
	auto mins = augs::misc::wstr<int>(tm->tm_min);
	auto secs = augs::misc::wstr<int>(tm->tm_sec);

	if (tm->tm_hour < 10) hours = L'0' + hours;
	if (tm->tm_min < 10) mins = L'0' + mins;
	if (tm->tm_sec < 10) secs = L'0' + secs;

	return augs::misc::towchar_vec
		(L'[' + hours + L':' + mins + L':' + secs + L']');
}

void callback_rect::set_focus_callback(luabind::object callback) {
	rect_obj.focus_callback = [callback]()	{
		luabind::call_function<void>(callback);
	};
}

void callback_rect::set_lpressed_callback(luabind::object callback) {
	rect_obj.lpressed_callback = [callback]()	{
		luabind::call_function<void>(callback);
	};
}

void callback_rect::set_hover_callback(luabind::object callback) {
	rect_obj.hover_callback = [callback]()	{
		luabind::call_function<void>(callback);
	};
}

void callback_rect::set_blur_callback(luabind::object callback) {
	rect_obj.blur_callback = [callback]()	{
		luabind::call_function<void>(callback);
	};
}

void callback_textbox::append_text(augs::graphics::gui::text::fstr& str, bool set_default_font) {
	auto prev_caret_pos = textbox_object.editor.get_caret_pos();
	auto prev_caret_sel = textbox_object.editor.get_selection_offset();

	textbox_object.editor.set_caret_end(false);

	if (set_default_font) {
		auto def_style = textbox_object.editor.get_default_style();

		for (auto& c : str) {
			c.font_used = def_style.f;
		}
	}

	textbox_object.editor.insert(str);

	textbox_object.editor.set_caret(prev_caret_pos, false);
	textbox_object.editor.set_selection_offset(prev_caret_sel);
}
using namespace graphics::gui;

stylesheet::style* resolve_attr(stylesheet& subject, std::string a) {
	if (a == "released") {
		return &subject.released;
	}
	else if (a == "focused") {
		return &subject.focused;
	}
	else if (a == "hovered") {
		return &subject.hovered;
	}
	else if (a == "pushed") {
		return &subject.pushed;
	}

	return nullptr;
}

void set_color(stylesheet& subject, std::string attr, augs::graphics::pixel_32 rgba) {
	auto* s = resolve_attr(subject, attr);

	if (s)
		s->color.set(rgba);
}

void set_border(stylesheet& subject, std::string attr, int w, augs::graphics::pixel_32 rgba) {
	auto* s = resolve_attr(subject, attr);

	if (s)
		s->border.set(solid_stroke(w, material(rgba)));
}

template <typename... Args>
void invokem (Args...) {

}

template<typename Signature>
struct setter_wrapper;

template<typename Ret, typename First, typename... Args>
struct setter_wrapper<Ret (First, Args...)> {
	template <typename T, stylesheet& get_style(T&), Ret setter_func(First, Args...)>
	static Ret setter(T& subject, Args... arguments) {
		return setter_func(get_style(subject), arguments...);
	}
};

#define wrap_set(_s, _g, _t) setter_wrapper<decltype(_s)>::setter<_t, _g, _s>

stylesheet& get_textbox_style(callback_textbox& c) {
	return c.textbox_object.styles;
}

stylesheet& get_rect_style(callback_rect& c) {
	return c.rect_obj.styles;
}

void hypersomnia_gui::bind(augs::lua_state_wrapper& wrapper) {
	callback_textbox a;
	invokem(a.textbox_object.styles, "aaa", augs::graphics::pixel_32(1, 1, 1, 1));

	//setter_wrapper<decltype(set_color)>::invoke(a, "aaa", augs::graphics::pixel_32(1, 1, 1, 1));
	(a, "aaa", augs::graphics::pixel_32(1, 1, 1, 1));
	luabind::module(wrapper.raw)[
		luabind::class_<hypersomnia_gui>("hypersomnia_gui")
		.def(luabind::constructor<augs::window::glwindow&>())
		.def("poll_events", &poll_events)
		.def("setup", &setup)
		.def("blur", &blur)
		.def("draw_call", &draw_call),

		luabind::class_<callback_textbox>("callback_textbox")
		.def(luabind::constructor<hypersomnia_gui&>())
		.def("append_text", &callback_textbox::append_text)
		.def("setup", &callback_textbox::setup)
		.def("set_caret", &callback_textbox::set_caret)
		.def("backspace", &callback_textbox::backspace)
		.def("view_caret", &callback_textbox::view_caret)
		.def("remove_line", &callback_textbox::remove_line)
		.def("is_focused", &callback_textbox::is_focused)
		.def("focus", &callback_textbox::focus)
		.def("get_length", &callback_textbox::get_length)
		.def("draw", &callback_textbox::draw)
		.def("clear_text", &callback_textbox::clear_text)
		.def("is_clean", &callback_textbox::is_clean)
		.def("set_area", &callback_textbox::set_area)
		.def("get_text_bbox", &callback_textbox::get_text_bbox)
		.def("set_alpha_range", &callback_textbox::set_alpha_range)
		.def("set_command_callback", &callback_textbox::set_command_callback),

		luabind::def("get_local_time", get_local_time),

		luabind::def("set_color", wrap_set(set_color, get_textbox_style, callback_textbox)),
		luabind::def("set_color", wrap_set(set_color, get_rect_style, callback_rect)),

		luabind::def("set_border", wrap_set(set_border, get_textbox_style, callback_textbox)),
		luabind::def("set_border", wrap_set(set_border, get_rect_style, callback_rect)),

		luabind::class_<callback_rect>("callback_rect")
		.def(luabind::constructor<hypersomnia_gui&>())
		.def("setup", &callback_rect::setup)
		.def("focus", &callback_rect::focus)
		.def("set_focus_callback", &callback_rect::set_focus_callback)
		.def("set_lpressed_callback", &callback_rect::set_lpressed_callback)
		.def("set_hover_callback", &callback_rect::set_hover_callback)
		.def("set_blur_callback", &callback_rect::set_blur_callback)
	];
}<|endoftext|>


<commit_before>84a4bfca-2749-11e6-834f-e0f84713e7b8<commit_msg>I hope I am done<commit_after>84b40eb0-2749-11e6-ad43-e0f84713e7b8<|endoftext|>


<commit_before>#include "include/main.hpp"
#include <boost/algorithm/string/predicate.hpp>
using namespace std;
using namespace pcp;
using namespace boost;
using namespace boost::program_options;
using namespace boost::algorithm;

int DEBUG_LEVEL = 2;

int main(int argc, char* argv[]) {
	string units, printFile, inputFile;
	int unsuccessfulShake, shakeStart, shakeIncrement, maxTime, rSeed;

	options_description options("General options");
	options.add_options()
		("help,h", "produce help message")
		("print,p", value<string>(&printFile), "set print file (*.gv)")
		("debug,d", value<int>(&DEBUG_LEVEL)->default_value(0), "set debug level")
	;

	options_description vnsOptions("Variable Neighborhood Search options");
	vnsOptions.add_options()
		("units,n", value<string>(&units)->default_value("nc"), "set units")
		("shakeStart,s", value<int>(&shakeStart)->default_value(0), "set shake start")
		("shakeIncrement,i", value<int>(&shakeIncrement)->default_value(10), "set shake increment")
		("unsuccessfulShake,u", value<int>(&unsuccessfulShake)->default_value(10), "set unsuccessful shake threshold")
		("maxTime,t", value<int>(&maxTime)->default_value(10), "set VNS running time (seconds)")
		("checkFinal,c", value<bool>()->zero_tokens() , "disable final check after VNS has finished")
		("checkIntermediate,m", value<bool>()->zero_tokens(), "enable check after each improvement/shake")
		("seed,r", value<int>(&rSeed)->default_value(time(NULL)), "set seed for random number generator")
		#ifdef ubigraph
		("delay", value<bool>()->zero_tokens(), "delay execution after loading the graph and finishing onestepCD")
		("full", value<bool>()->zero_tokens(), "render the full graph after the VNS terminates")
		#endif
	;

	options_description all("Allowed options");
	all.add(options).add(vnsOptions);

	variables_map vm;
	try {
		store(parse_command_line(argc, argv, all), vm);
	}
	catch(const boost::program_options::error& ex) {
		cerr << ex.what() << endl;
		return -1;
	}
	notify(vm);

	if (vm.count("help")) {
		cout << all << endl;
		return 0;
	}

	srand(rSeed);

	if (DEBUG_LEVEL > 4) {
		DEBUG_LEVEL = 4;

		cout << "The specified debug level (-d) exceeds"
		<< " the maximum. It was set to " << DEBUG_LEVEL
		<< "." << endl;
	}
	else if (DEBUG_LEVEL < 0) {
		DEBUG_LEVEL = 0;
	}

	Solution* fullG;

	if (isdigit(cin.peek())) {
		string buffer = "";
		getline(cin, buffer);
		cin.seekg(0);

		if (buffer.find(' ') == string::npos) {
			if (DEBUG_LEVEL > 2)
				cout << "Detected .col.b input." << endl;
			fullG = Solution::fromColBStream(cin);
		}
		else {
			if (DEBUG_LEVEL > 2)
				cout << "Detected .pcp input." << endl;
			fullG = Solution::fromPcpStream(cin);
		}
	}
	else {
		if (DEBUG_LEVEL > 2)
			cout << "Detected .col input." << endl;

		fullG = Solution::fromColStream(cin);
	}

	if (fullG == NULL) {
		cerr << "Failed to parse input!" << endl;
		return -1;
	}

	#ifdef ubigraph
	if (vm.count("delay"))
		usleep(3000000);
	#endif

	if (DEBUG_LEVEL > 3) {
		cout << "Constructing initial solution ..." << endl;
	}

	Solution *onestep = onestepCD(*fullG);

	if (DEBUG_LEVEL > 2)
		cout << "Initial solution uses " << onestep->colorsUsed << " colors." << endl;

	#ifdef ubigraph
	Solution *onecopy = new Solution(onestep);

	if (vm.count("delay"))
		usleep(3000000);
	#endif

	Solution *best = vnsRun(*onestep, *fullG, units, unsuccessfulShake, shakeStart, shakeIncrement, maxTime, vm.count("checkIntermediate"), !vm.count("checkFinal"));

	if (best == NULL)
		return -1;

	if (vm.count("print")) {
		ofstream out(vm["print"].as<string>());

		if (out.fail()) {
			cerr << "Error when trying to access file: " << vm["print"].as<string>() << endl;
			return -1;
		}
		best->print(out);
		out.flush();
		out.close();

		if (DEBUG_LEVEL > 1)
			cout << "Printing to '" << vm["print"].as<string>() << "' done!" << endl;
	}

	#ifdef ubigraph
	int offset = num_vertices(*fullG->g);
	onecopy->redraw(offset);
	if (vm.count("full"))
		fullG->redraw(offset * 2);
	delete onecopy;
	#endif

	delete best;
	delete fullG;

	return 0;
}
<commit_msg>Added comments to clarify behaviour<commit_after>#include "include/main.hpp"
#include <boost/algorithm/string/predicate.hpp>
using namespace std;
using namespace pcp;
using namespace boost;
using namespace boost::program_options;
using namespace boost::algorithm;

int DEBUG_LEVEL = 2;

// main method, starting point of the program
int main(int argc, char* argv[]) {
	string units, printFile, inputFile;
	int unsuccessfulShake, shakeStart, shakeIncrement, maxTime, rSeed;

	// Add program options to be parsed using boost:program_options
	options_description options("General options");
	options.add_options()
		("help,h", "produce help message")
		("print,p", value<string>(&printFile), "set print file (*.gv)")
		("debug,d", value<int>(&DEBUG_LEVEL)->default_value(0), "set debug level")
	;

	options_description vnsOptions("Variable Neighborhood Search options");
	vnsOptions.add_options()
		("units,n", value<string>(&units)->default_value("nc"), "set units")
		("shakeStart,s", value<int>(&shakeStart)->default_value(0), "set shake start")
		("shakeIncrement,i", value<int>(&shakeIncrement)->default_value(10), "set shake increment")
		("unsuccessfulShake,u", value<int>(&unsuccessfulShake)->default_value(10), "set unsuccessful shake threshold")
		("maxTime,t", value<int>(&maxTime)->default_value(10), "set VNS running time (seconds)")
		("checkFinal,c", value<bool>()->zero_tokens() , "disable final check after VNS has finished")
		("checkIntermediate,m", value<bool>()->zero_tokens(), "enable check after each improvement/shake")
		("seed,r", value<int>(&rSeed)->default_value(time(NULL)), "set seed for random number generator")
		#ifdef ubigraph
		("delay", value<bool>()->zero_tokens(), "delay execution after loading the graph and finishing onestepCD")
		("full", value<bool>()->zero_tokens(), "render the full graph after the VNS terminates")
		#endif
	;

	// Parse the options here
	options_description all("Allowed options");
	all.add(options).add(vnsOptions);

	variables_map vm;
	try {
		store(parse_command_line(argc, argv, all), vm);
	}
	catch(const boost::program_options::error& ex) {
		cerr << ex.what() << endl;
		return -1;
	}
	notify(vm);

	if (vm.count("help")) {
		cout << all << endl;
		return 0;
	}

	// Set random number generator's seed here, normally time related, unless
	// specified otherwise
	srand(rSeed);

	if (DEBUG_LEVEL > 4) {
		DEBUG_LEVEL = 4;

		cout << "The specified debug level (-d) exceeds"
		<< " the maximum. It was set to " << DEBUG_LEVEL
		<< "." << endl;
	}
	else if (DEBUG_LEVEL < 0) {
		DEBUG_LEVEL = 0;
	}

	// New solution for the full graph
	Solution* fullG;

	// Decide which format the input is in, and parse accordingly
	if (isdigit(cin.peek())) {
		string buffer = "";
		getline(cin, buffer);
		cin.seekg(0);

		if (buffer.find(' ') == string::npos) {
			if (DEBUG_LEVEL > 2)
				cout << "Detected .col.b input." << endl;
			fullG = Solution::fromColBStream(cin);
		}
		else {
			if (DEBUG_LEVEL > 2)
				cout << "Detected .pcp input." << endl;
			fullG = Solution::fromPcpStream(cin);
		}
	}
	else {
		if (DEBUG_LEVEL > 2)
			cout << "Detected .col input." << endl;

		fullG = Solution::fromColStream(cin);
	}

	if (fullG == NULL) {
		cerr << "Failed to parse input!" << endl;
		return -1;
	}

	// In case of ubigraph visualization stop the program for 3 secs
	#ifdef ubigraph
	if (vm.count("delay"))
		usleep(3000000);
	#endif

	if (DEBUG_LEVEL > 3) {
		cout << "Constructing initial solution ..." << endl;
	}

	// Calcutalte initial solution using oneStepCd
	Solution *onestep = onestepCD(*fullG);

	if (DEBUG_LEVEL > 2)
		cout << "Initial solution uses " << onestep->colorsUsed << " colors." << endl;

	// In case of ubigraph visualization stop here for 3 secs
	#ifdef ubigraph
	Solution *onecopy = new Solution(onestep);

	if (vm.count("delay"))
		usleep(3000000);
	#endif

	// Start Vns
	Solution *best = vnsRun(*onestep, *fullG, units, unsuccessfulShake, shakeStart, shakeIncrement, maxTime, vm.count("checkIntermediate"), !vm.count("checkFinal"));

	if (best == NULL)
		return -1;

	// print output if option is set
	if (vm.count("print")) {
		ofstream out(vm["print"].as<string>());

		if (out.fail()) {
			cerr << "Error when trying to access file: " << vm["print"].as<string>() << endl;
			return -1;
		}
		best->print(out);
		out.flush();
		out.close();

		if (DEBUG_LEVEL > 1)
			cout << "Printing to '" << vm["print"].as<string>() << "' done!" << endl;
	}

	// Visualize the existing onesteo solution along side the new best solution
	#ifdef ubigraph
	int offset = num_vertices(*fullG->g);
	onecopy->redraw(offset);
	if (vm.count("full"))
		fullG->redraw(offset * 2);
	delete onecopy;
	#endif

	// Clean up duty
	delete best;
	delete fullG;

	return 0;
}
<|endoftext|>


<commit_before>#include <SDL.h>
#include <vector>

#include "opengl.h"

int Abs(int num) {
	return num > 0 ? num : -num;
}

int PingPong(int num, int length) {
	return length - Abs((num % (length * 2)) - length);
}

int main() {

	const int WindowWidth = 720;
	const int WindowHeight = 720;

	if (SDL_Init(SDL_INIT_EVERYTHING)) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	SDL_Window* window = SDL_CreateWindow("SDL OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WindowWidth, WindowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
	if (!window) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	//// OpenGL Setup

	// Options
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	// Connect window
	SDL_GLContext context = SDL_GL_CreateContext(window);

	if (!context) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	OpenGL_Init();

	{
		int value = 0;
		SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &value);
		SDL_Log("SDL_GL_CONTEXT_MAJOR_VERSION: %d\n", value);

		SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &value);
		SDL_Log("SDL_GL_CONTEXT_MINOR_VERSION: %d\n", value);
	}

	int r = 0;
	int g = 0;
	int b = 0;
	glViewport(0, 0, WindowWidth, WindowHeight);
	glClearColor(0.39f, 0.58f, 0.92f, 1.0f);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	// Shaders
	const GLchar* vertexShaderSource = "#version 330 core\n"
		"layout (location = 0) in vec3 position;\n"
		"layout (location = 1) in vec3 color;\n"
		"layout (location = 2) in vec2 texCoord;\n"
		"out vec3 ourColor;\n"
		"out vec2 TexCoord;\n"
		"void main()\n"
		"{\n"
		"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
		"TexCoord = texCoord;\n"
		"ourColor = color;\n"
		"}\0";

	const GLchar* fragmentShaderSource = "#version 330 core\n"
		"in vec3 ourColor;\n"
		"in vec2 TexCoord;\n"
		"out vec4 color;\n"
		"uniform sampler2D ourTexture;\n"
		"void main()\n"
		"{\n"
		"color = texture(ourTexture, TexCoord);\n"
		"color.rgb *= ourColor;\n"
		"}\n\0";

	GLint success;
	GLchar logBuffer[512];

	// Vertex
	GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
	glCompileShader(vertexShader);

	glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
	if (!success) {
		glGetShaderInfoLog(vertexShader, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Vertex Compile Error: %s", logBuffer);
	}

	// Fragment
	GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
	glCompileShader(fragmentShader);

	glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
	if (!success) {
		glGetShaderInfoLog(fragmentShader, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Fragment Compile Error: %s", logBuffer);
	}

	// Program
	GLuint shaderProgram = glCreateProgram();
	glAttachShader(shaderProgram, vertexShader);
	glAttachShader(shaderProgram, fragmentShader);
	glLinkProgram(shaderProgram);

	glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
	if (!success) {
		glGetProgramInfoLog(shaderProgram, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Shader Linking Error: %s", logBuffer);
	}

	glDeleteShader(vertexShader);
	glDeleteShader(fragmentShader);

	//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

	GLfloat vertices[] = {
		// Positions          // Colors           	  // Texture Coords
		0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 1.0f,   1.0f, 0.0f, // Top Right
		0.5f, -0.5f, 0.0f,   1.0f, 1.0f, 1.0f,   1.0f, 1.0f, // Bottom Right
		-0.5f, -0.5f, 0.0f,   1.0f, 1.0f, 1.0f,   0.0f, 1.0f, // Bottom Left
		-0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 1.0f,   0.0f, 0.0f  // Top Left
    };

	GLuint indices[] = {
        0, 1, 3,
        1, 2, 3,
	};

    GLuint VBO, VAO, EBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
    glBindVertexArray(VAO);
	{
		// Now the VBO..
		glBindBuffer(GL_ARRAY_BUFFER, VBO);
		glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

		// Finally the EBO
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

		// Vertex Attributes

		glVertexAttribPointer(0, // Layout
							3, // Size
							GL_FLOAT, // Type
							GL_FALSE, // Normalised
							8 * sizeof(GLfloat), // Stride
							(void*) 0); // Array Buffer Offset
		glEnableVertexAttribArray(0);

		glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
		glEnableVertexAttribArray(1);

		glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
		glEnableVertexAttribArray(2);
	}

	glBindVertexArray(0);

	// Texture loading

	SDL_Surface* image = SDL_LoadBMP("texture.bmp");
	if (!image) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to load texture.bmp! %s", SDL_GetError());
		return 1;
	}

	GLuint texture = 0;
	glGenTextures(1, &texture);
	{
		glBindTexture(GL_TEXTURE_2D, texture); // All texture functions will now operate on this texture

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // X wrapping
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Y wrapping

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Far away
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Close up

		// Use GL_BGR because bitmaps are silly
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image->w, image->h, 0, GL_BGR, GL_UNSIGNED_BYTE, image->pixels);
		SDL_FreeSurface(image);
	}
	glBindTexture(GL_TEXTURE_2D, 0); // Unbind

	for(GLenum err; (err = glGetError()) != GL_NO_ERROR;) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "OpenGL Init: 0x%x", err);
	}

	bool running = true;
	SDL_Event event;

	float current = SDL_GetTicks();
	float last = current;
	float interval = 1000 / 60;

	while (running) {

		// Limit frame rate
		current = SDL_GetTicks();

		float dt = current - last;

		if (dt < interval) {
			SDL_Delay(interval - dt);
			continue;
		}

		last = current;

		// Input
		while(SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT) {
				running = false;
				break;
			}

			if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED) {
				int x = event.window.data1;
				int y = event.window.data2;
				glViewport(0, 0, x, y);
			}
		}

		r = (r + 2) % (255 * 2);
		g = (g + 4) % (255 * 2);
		b = (b + 8) % (255 * 2);

		//Rendering
		glClearColor((float)PingPong(r, 255) / 255, (float)PingPong(g, 255) / 255, (float)PingPong(b, 255) / 255, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// Draw Triangle
		glUseProgram(shaderProgram);

		// Bind texture
		glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texture);

		glBindVertexArray(VAO);
		glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
		glBindVertexArray(0);

		SDL_GL_SwapWindow(window);
	}
    // Properly de-allocate all resources once they've outlived their purpose
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    glDeleteBuffers(1, &EBO);
	return 0;
}<commit_msg>Added culling<commit_after>#include <SDL.h>
#include <vector>

#include "opengl.h"

int Abs(int num) {
	return num > 0 ? num : -num;
}

int PingPong(int num, int length) {
	return length - Abs((num % (length * 2)) - length);
}

int main() {

	const int WindowWidth = 720;
	const int WindowHeight = 720;

	if (SDL_Init(SDL_INIT_EVERYTHING)) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	SDL_Window* window = SDL_CreateWindow("SDL OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WindowWidth, WindowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
	if (!window) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	//// OpenGL Setup

	// Options
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	// Connect window
	SDL_GLContext context = SDL_GL_CreateContext(window);

	if (!context) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	OpenGL_Init();

	{
		int value = 0;
		SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &value);
		SDL_Log("SDL_GL_CONTEXT_MAJOR_VERSION: %d\n", value);

		SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &value);
		SDL_Log("SDL_GL_CONTEXT_MINOR_VERSION: %d\n", value);
	}

	int r = 0;
	int g = 0;
	int b = 0;
	glViewport(0, 0, WindowWidth, WindowHeight);
	glClearColor(0.39f, 0.58f, 0.92f, 1.0f);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	glEnable(GL_CULL_FACE);

	// Shaders
	const GLchar* vertexShaderSource = "#version 330 core\n"
		"layout (location = 0) in vec3 position;\n"
		"layout (location = 1) in vec3 color;\n"
		"layout (location = 2) in vec2 texCoord;\n"
		"out vec3 ourColor;\n"
		"out vec2 TexCoord;\n"
		"void main()\n"
		"{\n"
		"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
		"TexCoord = texCoord;\n"
		"ourColor = color;\n"
		"}\0";

	const GLchar* fragmentShaderSource = "#version 330 core\n"
		"in vec3 ourColor;\n"
		"in vec2 TexCoord;\n"
		"out vec4 color;\n"
		"uniform sampler2D ourTexture;\n"
		"void main()\n"
		"{\n"
		"color = texture(ourTexture, TexCoord);\n"
		"color.rgb *= ourColor;\n"
		"}\n\0";

	GLint success;
	GLchar logBuffer[512];

	// Vertex
	GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
	glCompileShader(vertexShader);

	glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
	if (!success) {
		glGetShaderInfoLog(vertexShader, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Vertex Compile Error: %s", logBuffer);
	}

	// Fragment
	GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
	glCompileShader(fragmentShader);

	glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
	if (!success) {
		glGetShaderInfoLog(fragmentShader, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Fragment Compile Error: %s", logBuffer);
	}

	// Program
	GLuint shaderProgram = glCreateProgram();
	glAttachShader(shaderProgram, vertexShader);
	glAttachShader(shaderProgram, fragmentShader);
	glLinkProgram(shaderProgram);

	glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
	if (!success) {
		glGetProgramInfoLog(shaderProgram, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Shader Linking Error: %s", logBuffer);
	}

	glDeleteShader(vertexShader);
	glDeleteShader(fragmentShader);

	//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

	GLfloat vertices[] = {
		// Positions          // Colors           	  // Texture Coords
		-0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 1.0f,   0.0f, 0.0f,  // Top Left
		-0.5f, -0.5f, 0.0f,   1.0f, 1.0f, 1.0f,   0.0f, 1.0f, // Bottom Left
		0.5f, -0.5f, 0.0f,   1.0f, 1.0f, 1.0f,   1.0f, 1.0f, // Bottom Right
		0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 1.0f,   1.0f, 0.0f, // Top Right
    };

	GLuint indices[] = {
        0, 1, 2,
        2, 3, 0,
	};

    GLuint VBO, VAO, EBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
    glBindVertexArray(VAO);
	{
		// Now the VBO..
		glBindBuffer(GL_ARRAY_BUFFER, VBO);
		glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

		// Finally the EBO
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

		// Vertex Attributes

		glVertexAttribPointer(0, // Layout
							3, // Size
							GL_FLOAT, // Type
							GL_FALSE, // Normalised
							8 * sizeof(GLfloat), // Stride
							(void*) 0); // Array Buffer Offset
		glEnableVertexAttribArray(0);

		glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
		glEnableVertexAttribArray(1);

		glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
		glEnableVertexAttribArray(2);
	}

	glBindVertexArray(0);

	// Texture loading

	SDL_Surface* image = SDL_LoadBMP("texture.bmp");
	if (!image) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to load texture.bmp! %s", SDL_GetError());
		return 1;
	}

	GLuint texture = 0;
	glGenTextures(1, &texture);
	{
		glBindTexture(GL_TEXTURE_2D, texture); // All texture functions will now operate on this texture

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // X wrapping
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Y wrapping

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Far away
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Close up

		// Use GL_BGR because bitmaps are silly
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image->w, image->h, 0, GL_BGR, GL_UNSIGNED_BYTE, image->pixels);
		SDL_FreeSurface(image);
	}
	glBindTexture(GL_TEXTURE_2D, 0); // Unbind

	for(GLenum err; (err = glGetError()) != GL_NO_ERROR;) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "OpenGL Init: 0x%x", err);
	}

	bool running = true;
	SDL_Event event;

	float current = SDL_GetTicks();
	float last = current;
	float interval = 1000 / 60;

	while (running) {

		// Limit frame rate
		current = SDL_GetTicks();

		float dt = current - last;

		if (dt < interval) {
			SDL_Delay(interval - dt);
			continue;
		}

		last = current;

		// Input
		while(SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT) {
				running = false;
				break;
			}

			if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED) {
				int x = event.window.data1;
				int y = event.window.data2;
				glViewport(0, 0, x, y);
			}
		}

		r = (r + 2) % (255 * 2);
		g = (g + 4) % (255 * 2);
		b = (b + 8) % (255 * 2);

		//Rendering
		glClearColor((float)PingPong(r, 255) / 255, (float)PingPong(g, 255) / 255, (float)PingPong(b, 255) / 255, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// Draw Triangle
		glUseProgram(shaderProgram);

		// Bind texture
		glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texture);

		glBindVertexArray(VAO);
		glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
		glBindVertexArray(0);

		SDL_GL_SwapWindow(window);
	}
    // Properly de-allocate all resources once they've outlived their purpose
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    glDeleteBuffers(1, &EBO);
	return 0;
}<|endoftext|>


<commit_before>/**
 *
 * Terminology (Matroid - Graph):
 *  Basis - Spanning tree
 *  Independent set - Tree (i.e. subset of a basis)
 *  Circuit - cycle
 *  Cocircuit - minimal edge-cut
 *  Hyperplane - maximal set not containing any basis (= complement of a min-cut)
 *
 *  Spanning forest - union of spanning trees of each component of an unconnected graph
 *
 */

#include "maybe.hpp"
#include "helpers.hpp"

#include <iostream>
#include <stdexcept>
#include <ogdf/basic/Queue.h>
#include <ogdf/basic/Graph.h>
#include <ogdf/basic/simple_graph_alg.h>

enum {
    BLACK,
    RED,
    BLUE
};

using namespace std;
using namespace ogdf;

int m = 3; // Cocircuit size bound

/**
 * @brief Takes a csv file with lines "<id>;<source>;<target>;<edge name>;..." and transforms it into graph
 * @param sEdgesFileName
 * @return Graph
 */
Graph csvToGraph(string sEdgesFileName) { // This copies Graph on exit, to speed up, extend Graph and let this be a new method in our extended class
    Graph G;

    ifstream fEdges(sEdgesFileName);
    if (!fEdges.is_open())
        throw new invalid_argument("Edges file doesn't exist or could not be accessed");

    vector<node> nodes;
    int id, u, v, nSize = 0;

    for (string line; getline(fEdges, line);) {
        sscanf(line.c_str(), "%d;%d;%d;", &id, &u, &v);

        if (u > nSize) {
            nodes.resize(u + 1);
            nSize = u;
        }

        if (v > nSize) {
            nodes.resize(v + 1);
            nSize = v;
        }

        if(nodes.at(u) == nullptr)
            nodes[u] = G.newNode(u);

        if(nodes[v] == nullptr)
            nodes[v] = G.newNode(v);

        G.newEdge(nodes[u], nodes[v], id);
    }

    return G;
}

/**
 * Performs BFS to find the shortest path from s to t in graph g without using any edge from the forbidden edges.
 * Returns empty set if no such path exists.
 */
List<edge> shortestPath(const Graph &G, node s, node t, List<edge> forbidden) {
    List<edge> path;
    node v, u;
    edge e;

    Queue<node> Q;

    NodeArray<node> predecessor(G);
    NodeArray<bool> visited(G, false);

    Q.append(s);
    visited[s] = true;

    while(!Q.empty()) {
        v = Q.pop();

        if (v == t) {
            // traceback predecessors and reconstruct path
            for (node n = t; n != s; n = predecessor[n]) {
                path.pushFront(G.searchEdge(predecessor[n], n));
            }
            break;
        }

        forall_adj_edges(e, v) {
            if (forbidden.search(e).valid()) continue; // TODO: Use BST or array (id -> bool) to represent forbidden?

            u = e->opposite(v);
            if (!visited[u]) {
                predecessor[u] = v; // TODO: Unite predecessor and visited?
                visited[u] = true;
                Q.append(u);
            }
        }
    }

    return path;
}

Maybe<List<edge> > GenCocircuits(const Graph &G, List<edge> X, NodeArray<int> coloring, node red, node blue) {
    // if(E\X contains no hyperplane of M || X.size() > m)
     //   return return_<Nothing>;

    // Find set D = (a short circuit C in G, s. t. |C ∩ X| = 1) \ X
    List<edge> D = shortestPath(G, red, blue, X);
    if (D.size() > 0) {

        // for each c ∈ D, recursively call GenCocircuits(X ∪ {c}).
        for(List<edge>::iterator iterator = D.begin(); iterator != D.end(); iterator++) {
            edge c = *iterator;
            List<edge> newX = X;
            newX.pushBack(c);

            node u = c->source(), v = c->target(); // c = (u,v)
            coloring[u] = RED;

            // Color vertices of c = (u,v)
            // the one closer to any RED vertex, say u, will be red (and so will be all vertices on the path from the first red to u)
            for(List<edge>::iterator j = D.begin(); j != iterator; j++) {
                edge e = *j;
                coloring[e->source()] = RED;
                coloring[e->target()] = RED;
            }

            // Color the rest of the path blue
            for(List<edge>::iterator j = iterator; j != D.end(); j++) {
                edge e = *j;
                coloring[e->source()] = BLUE;
                coloring[e->target()] = BLUE;
            }

            return GenCocircuits(G, newX, coloring, u, v);
        }

    } else {
        // If there is no such circuit C above (line 4), then return ‘Cocircuit: X’.
        return return_<Maybe>(X);
    }
}

/**
 * Returns edges spanning forest of (possibly disconnected) graph G
 * @param G
 */
List<edge> spanningEdges(const Graph &G) {
    EdgeArray<bool> isBackedge(G, false);

    List<edge> backedges;
    isAcyclicUndirected(G, backedges);

    for(List<edge>::iterator i = backedges.begin(); i != backedges.end(); i++) {
        isBackedge[*i] = true;
    }

    List<edge> spanningEdges;
    edge e;
    forall_edges(e, G) {
        if (!isBackedge[e])
            spanningEdges.pushBack(e);
    }

    return spanningEdges;
}

int main()
{
    try {
        Graph G = csvToGraph("data/graph3.csv");

        List<edge> base = spanningEdges(G);

        NodeArray<int> coloring(G, BLACK);

        edge e;
        for(List<edge>::iterator i = base.begin(); i != base.end(); i++) {
            e = *i;

            List<edge> X; // (Indexes might be sufficient? Check later)
            X.pushBack(e);
            coloring[e->source()] = RED;
            coloring[e->target()] = BLUE;
            Maybe<List<edge> > cocircuit = GenCocircuits(G, X, coloring, e->source(), e->target());
            if(cocircuit.isJust()) {
                cout << "Found a cocircuit: " << cocircuit.fromJust() << endl;
            }
        }

    } catch (invalid_argument *e) {
        cerr << "Error: " << e->what() << endl;
        return 1;
    }

    return 0;
}

<commit_msg>Some implementation of hyperplane testing<commit_after>/**
 *
 * Terminology (Matroid - Graph):
 *  Basis - Spanning tree
 *  Independent set - Tree (i.e. subset of a basis)
 *  Circuit - cycle
 *  Cocircuit - minimal edge-cut
 *  Hyperplane - maximal set not containing any basis (= complement of a min-cut)
 *
 *  Spanning forest - union of spanning trees of each component of an unconnected graph
 *
 */

#include "maybe.hpp"
#include "helpers.hpp"

#include <iostream>
#include <stdexcept>
#include <ogdf/basic/Queue.h>
#include <ogdf/basic/Graph.h>
#include <ogdf/basic/Stack.h>
#include <ogdf/basic/simple_graph_alg.h>

enum {
    BLACK,
    RED,
    BLUE
};

using namespace std;
using namespace ogdf;

int m = 3; // Cocircuit size bound

/**
 * @brief Takes a csv file with lines "<id>;<source>;<target>;<edge name>;..." and transforms it into graph
 * @param sEdgesFileName
 * @return Graph
 */
Graph csvToGraph(string sEdgesFileName) { // This copies Graph on exit, to speed up, extend Graph and let this be a new method in our extended class
    Graph G;

    ifstream fEdges(sEdgesFileName);
    if (!fEdges.is_open())
        throw new invalid_argument("Edges file doesn't exist or could not be accessed");

    vector<node> nodes;
    int id, u, v, nSize = 0;

    for (string line; getline(fEdges, line);) {
        sscanf(line.c_str(), "%d;%d;%d;", &id, &u, &v);

        if (u > nSize) {
            nodes.resize(u + 1);
            nSize = u;
        }

        if (v > nSize) {
            nodes.resize(v + 1);
            nSize = v;
        }

        if(nodes.at(u) == nullptr)
            nodes[u] = G.newNode(u);

        if(nodes[v] == nullptr)
            nodes[v] = G.newNode(v);

        G.newEdge(nodes[u], nodes[v], id);
    }

    return G;
}

/**
 * Performs BFS to find the shortest path from s to t in graph g without using any edge from the forbidden edges.
 * Returns empty set if no such path exists.
 */
List<edge> shortestPath(const Graph &G, node s, node t, List<edge> forbidden) {
    List<edge> path;
    node v, u;
    edge e;

    Queue<node> Q;

    NodeArray<node> predecessor(G);
    NodeArray<bool> visited(G, false);

    Q.append(s);
    visited[s] = true;

    while(!Q.empty()) {
        v = Q.pop();

        if (v == t) {
            // traceback predecessors and reconstruct path
            for (node n = t; n != s; n = predecessor[n]) {
                path.pushFront(G.searchEdge(predecessor[n], n));
            }
            break;
        }

        forall_adj_edges(e, v) {
            if (forbidden.search(e).valid()) continue; // TODO: Use BST or array (id -> bool) to represent forbidden?

            u = e->opposite(v);
            if (!visited[u]) {
                predecessor[u] = v; // TODO: Unite predecessor and visited?
                visited[u] = true;
                Q.append(u);
            }
        }
    }

    return path;
}

/**
 * E(G)\X contains a k-way hyperplane of G\X iff G\V(R) contains a connected subgraph G_b spanning all the blue vertices of X
 * @param G
 * @param X
 * @param coloring
 * @param blue
 * @return
 */
bool hasHyperplane(Graph &G, List<edge> X, NodeArray<int> &coloring) {
    for(List<edge>::iterator iterator = X.begin(); iterator != X.end(); ++iterator) {
        G.hideEdge(*iterator);
    }

    // Make a list of all blue vertices of X
    List<node> blues;

    for(List<edge>::iterator iterator = X.begin(); iterator != X.end(); ++iterator) {
        edge e = *iterator;
        node u = e->source(), v = e->target();

        if (coloring[u] == BLUE)
            blues.pushBack(u);

        if (coloring[v] == BLUE)
            blues.pushBack(v);
    }

    // Pick one, call it s
    node s = blues.front();

    // Perform a DFS on G\X from s and see if all vertices are contained
    NodeArray<bool> discovered(G, false);
    Stack<node> S;
    S.push(s);

    node v, u;
    adjEntry adj;
    while(!S.empty()) {
        v = S.pop();

        if (!discovered[v]) {
            discovered[v] = true;

            if (coloring[v] == BLUE) // TODO: If blues were exactly those blues in X, all we would need would be simple count! (Currently the rest of the path D is painted blue)
                blues.removeFirst(v);

            forall_adj(adj, v) {
                u = adj->twinNode();
                S.push(u);
            }
        }
    }

    G.restoreAllEdges();

    return blues.empty();
}

Maybe<List<edge> > GenCocircuits(Graph &G, List<edge> X, NodeArray<int> coloring, node red, node blue) {
    if(!hasHyperplane(G, X, coloring) || X.size() > m) { // E\X contains no hyperplane of M
        return Maybe<List<edge> >();
    }

    // Find set D = (a short circuit C in G, s. t. |C ∩ X| = 1) \ X
    List<edge> D = shortestPath(G, red, blue, X);
    if (D.size() > 0) {

        // for each c ∈ D, recursively call GenCocircuits(X ∪ {c}).
        for(List<edge>::iterator iterator = D.begin(); iterator != D.end(); iterator++) {
            edge c = *iterator;
            List<edge> newX = X;
            newX.pushBack(c);

            node u = c->source(), v = c->target(); // c = (u,v)
            coloring[u] = RED;

            // Color vertices of c = (u,v)
            // the one closer to any RED vertex, say u, will be red (and so will be all vertices on the path from the first red to u)
            for(List<edge>::iterator j = D.begin(); j != iterator; j++) {
                edge e = *j;
                coloring[e->source()] = RED;
                coloring[e->target()] = RED;
            }

            // Color the rest of the path blue
            for(List<edge>::iterator j = iterator; j != D.end(); j++) {
                edge e = *j;
                coloring[e->source()] = BLUE;
                coloring[e->target()] = BLUE;
            }

            return GenCocircuits(G, newX, coloring, u, v);
        }

    } else {
        // If there is no such circuit C above (line 4), then return ‘Cocircuit: X’.
        return return_<Maybe>(X);
    }
}

/**
 * Returns edges spanning forest of (possibly disconnected) graph G
 * @param G
 */
List<edge> spanningEdges(const Graph &G) {
    EdgeArray<bool> isBackedge(G, false);

    List<edge> backedges;
    isAcyclicUndirected(G, backedges);

    for(List<edge>::iterator i = backedges.begin(); i != backedges.end(); i++) {
        isBackedge[*i] = true;
    }

    List<edge> spanningEdges;
    edge e;
    forall_edges(e, G) {
        if (!isBackedge[e])
            spanningEdges.pushBack(e);
    }

    return spanningEdges;
}

int main()
{
    try {
        Graph G = csvToGraph("data/graph2.csv");

        List<edge> base = spanningEdges(G);

        NodeArray<int> coloring(G, BLACK);

        edge e;
        for(List<edge>::iterator i = base.begin(); i != base.end(); i++) {
            e = *i;

            List<edge> X; // (Indexes might be sufficient? Check later)
            X.pushBack(e);
            coloring[e->source()] = RED;
            coloring[e->target()] = BLUE;
            Maybe<List<edge> > cocircuit = GenCocircuits(G, X, coloring, e->source(), e->target());
            if(cocircuit.isJust()) {
                cout << "Found a cocircuit: " << cocircuit.fromJust() << endl;
            }
        }

    } catch (invalid_argument *e) {
        cerr << "Error: " << e->what() << endl;
        return 1;
    }

    return 0;
}

<|endoftext|>


<commit_before>7441fdb8-4b02-11e5-89ed-28cfe9171a43<commit_msg>That didn't fix it<commit_after>7450cc42-4b02-11e5-8126-28cfe9171a43<|endoftext|>


<commit_before>#include "mbed.h"
#include "rtos.h"
#include "encoder.h"
#include "protocol.h"
#include "packet_parser.h"

// Logical to physical pin definitions (change these when changing boards)
#define LED_1_PIN     PTC2
#define LED_2_PIN     PTC3
#define LED_3_PIN     PTA18

#define UART_TX_PIN   PTD7
#define UART_RX_PIN   PTD6

#define SPI_MOSI_PIN  PTC6
#define SPI_MISO_PIN  PTC7
#define SPI_SCK_PIN   PTC5
#define SPI_CS_PIN    PTC4

#define ENABLE_PIN    PTA4
#define DIRECTION_PIN PTA2
#define BRAKE_PIN     PTA1

#define CURRENT_PIN     PTB0
#define TEMPERATURE_PIN PTE30
#define VOLTAGE_PIN     PTD5

// Global object/variable instantiations (these should not change)
DigitalOut led_1(LED_1_PIN);
Encoder encoder(SPI_MOSI_PIN, SPI_MISO_PIN, SPI_SCK_PIN, SPI_CS_PIN);

PwmOut enable(ENABLE_PIN);
DigitalOut direction(DIRECTION_PIN);
DigitalOut brake(BRAKE_PIN);

AnalogIn current_sense(CURRENT_PIN);
AnalogIn temperature_sense(TEMPERATURE_PIN);
AnalogIn voltage_sense(VOLTAGE_PIN);

Timer system_timer;
sensor_data_t last_sensor_data;
command_data_t last_command_data;

// This was the best compromise speed since mbed is 41.94MHz and ImageProc is
// 40MHz
#define SERIAL_BAUDRATE 873813

// Converts ticks/us to rad/s in 16.16 fixed point. Divide resulting number by
// 2^16 for final result
#define TICK_US_TO_RAD_S_FIXP 25142741 //78640346

// ticks to radians in 8.24 fixed point: multiply by 2^24 for scaled value
// 2*pi/(2^14)*2^24 = 6433.9818
// this approximation accumulates one tick of error per 21 revolutions
// 2*pi/(2^14)*2^16 = 25.1327
// this approximation accumulates 0.5% error
#define TICK_TO_RAD_FIXP 25 //6434
int32_t revolutions = 0;
int32_t integrator = 0;
int32_t velocity_filtered = 0;

uint8_t control_mode = 0;

int32_t position_absolute;
int32_t velocity_unfiltered;
uint32_t dt;

#define COMMAND_LIMIT 0.5 // maximum duty cycle: [0,1] (1 is full on)
#define V_TAU 20000 // velocity LP time constant in us

// 16.16 fixed point: divide by 2^16 for scaled value
#define LOW_STOP -2*2*314*(1<<16)/100 // motor position limit
#define HIGH_STOP 17*2*314*(1<<16)/100 // motor high position limit
#define INTEGRATOR_MAX 1*(1<<16) // integrator saturation in rad*s
#define KP 3*(1<<16)/10 // fraction of command per rad
#define KI 1*(1<<16)/100 // fraction of command per rad*s
#define KD 1*(1<<16)/50 // fraction of command per rad/s

// Fills a packet with the most recent acquired sensor data
void get_last_sensor_data(packet_t* pkt, uint8_t flags) {
  pkt->header.type = PKT_TYPE_SENSOR;
  pkt->header.length = sizeof(header_t) + sizeof(sensor_data_t) + 1;
  pkt->header.flags = flags;
  sensor_data_t* sensor_data = (sensor_data_t*)pkt->data_crc;
  sensor_data->time = last_sensor_data.time;
  sensor_data->position = last_sensor_data.position;
  sensor_data->velocity = last_sensor_data.velocity;
  sensor_data->current = last_sensor_data.current;
  sensor_data->voltage = last_sensor_data.voltage;
  sensor_data->temperature = last_sensor_data.temperature;
  sensor_data->uc_temp = last_sensor_data.uc_temp;
}

// Sense and control function to be run at 1kHz
void sense_control_thread(void const *arg) {
  uint32_t last_time = last_sensor_data.time;
  int32_t last_position = last_sensor_data.position; // 3us
  last_sensor_data.time = system_timer.read_us(); // 19.6us
  encoder.update_state();

  dt = last_sensor_data.time - last_time; // timing
  int32_t current_position = encoder.get_cal_state();
  /*
  last_sensor_data.position = encoder.get_cal_state(); // 393us
  last_sensor_data.velocity = (
        TICK_US_TO_RAD_S_FIXP*(last_sensor_data.position - last_position)) /
            (last_sensor_data.time-last_time); // 8.1us
  last_sensor_data.current = current_sense.read_u16(); //85.6us
  last_sensor_data.temperature = temperature_sense.read_u16(); // 85.6us
  last_sensor_data.uc_temp = 0x1234;
  */

  // Position: rad in 15.16 fixed point
  if (current_position > 3<<12 && last_position < 1<<12) {
    revolutions--;
  } else if (current_position < 1<<12 && last_position > 3<<12) {
    revolutions++;
  }
  int32_t last_position_absolute = position_absolute;
  position_absolute = TICK_TO_RAD_FIXP *
        (revolutions*(1<<14) + current_position);

  // Velocity: rad/s in 15.16 fixed point
  velocity_unfiltered = 1000000*(((int64_t)position_absolute -
        (int64_t)last_position_absolute)/dt);
  velocity_filtered =
        dt*velocity_unfiltered/(V_TAU + dt) +
        V_TAU*velocity_filtered/(V_TAU + dt);

  // Add data to struct
  last_sensor_data.position = position_absolute;
  last_sensor_data.velocity = velocity_filtered;
  last_sensor_data.current = current_sense.read_u16();
  last_sensor_data.temperature = temperature_sense.read_u16();
  last_sensor_data.uc_temp = 0x1234;

  // TODO: Calculate and apply control
  int32_t command = 0;
  switch (control_mode) {
    case 0:
      command = 0;
      integrator = 0;
      break;

    case 1:
      // TODO: Current control
      command = 0;
      integrator = 0;
      break;

    case 2:
      int32_t target_position = 0*(1<<16); // rad in 16.16 fixed point
      int32_t target_velocity = 0*(1<<16); // rad/s in 16.16 fixed point

      /*
      if (last_sensor_data.time % 10000000 < 5000000) {
        target_position = 30*(1<<16);//1.5*(1<<16);
      }
      */
      /*
      target_position = 6*(int64_t)last_sensor_data.time*(1<<16)/1000000;
      target_velocity = 6*(1<<16);
      */
      target_position = last_command_data.position_setpoint;

      int32_t position_error = position_absolute - target_position;

      // Integrator: rad*s in 15.16 fixed point
      integrator += (int32_t)((int64_t)position_error*(uint64_t)dt/1000000);
      if (integrator > INTEGRATOR_MAX) { // integrator saturation to prevent windup
        integrator = INTEGRATOR_MAX;
      } else if (integrator < -INTEGRATOR_MAX) {
        integrator = -INTEGRATOR_MAX;
      }

      // Command
      command = (-KP*(int64_t)position_error)/(1<<16) +
            (-KD*((int64_t)velocity_filtered-(int64_t)target_velocity))/(1<<16) +
            (-KI*(int64_t)integrator)/(1<<16);

      break;
  }

  if (position_absolute > HIGH_STOP) { // high limit stop
      command = command > 0.0 ? 0.0 : command;
  } else if (position_absolute < LOW_STOP) { // low limit stop
      command = command < 0.0 ? 0.0 : command;
  }
  float command_magnitude = fabs(static_cast<float>(command)/(1<<16));
  command_magnitude = command_magnitude > COMMAND_LIMIT
      ? COMMAND_LIMIT : command_magnitude; // limit maximum duty cycle
  enable.write(1-command_magnitude);
  direction.write(command > 0);
  // end Calculate and apply control (JY)

  // This puts the packet in the outgoing queue if there is space
  PacketParser* parser = (PacketParser*)(arg);
  packet_union_t* sensor_pkt = parser->get_send_packet();
  if (sensor_pkt != NULL) {
    get_last_sensor_data(&(sensor_pkt->packet),0);
    parser->send_packet(sensor_pkt);
  }
}

int main() {
  enable.period_us(50);
  enable.write(0.9f);
  direction.write(0);
  brake.write(1);

  control_mode = 0; // by default, disable the motor

  led_1 = 1;

  // Start the microsecond time
  system_timer.start();

  // Instantiate packet parser
  PacketParser parser(
      SERIAL_BAUDRATE, UART_TX_PIN, UART_RX_PIN, LED_2_PIN, LED_3_PIN);

  // Run the sense/control thread at 1kHz
  RtosTimer sense_control_ticker(
      &sense_control_thread, osTimerPeriodic, (void*)(&parser));

  sense_control_ticker.start(1);

  // Pointer to received packet
  packet_union_t* recv_pkt = NULL;

  while(1) {

    // See if there is a received packet
    recv_pkt = parser.get_received_packet();

    if (recv_pkt != NULL) {

      led_1 = !(led_1.read());

      switch (recv_pkt->packet.header.type) {

        // If got a command packet, store command value
        case PKT_TYPE_COMMAND:
          memcpy(&last_command_data,recv_pkt->packet.data_crc,
              sizeof(command_data_t));
          // TODO: state machine for control modes
          control_mode = recv_pkt->packet.header.flags;
          // end control modes (JY)
          break;

        default:
          // TODO: do something if we got an unrecognized packet type?
          break;
      }
      parser.free_received_packet(recv_pkt);
    }

    // This will process any outgoing packets
    parser.send_worker();
  }
}
<commit_msg>Fixed wrap-around.<commit_after>#include "mbed.h"
#include "rtos.h"
#include "encoder.h"
#include "protocol.h"
#include "packet_parser.h"

// Logical to physical pin definitions (change these when changing boards)
#define LED_1_PIN     PTC2
#define LED_2_PIN     PTC3
#define LED_3_PIN     PTA18

#define UART_TX_PIN   PTD7
#define UART_RX_PIN   PTD6

#define SPI_MOSI_PIN  PTC6
#define SPI_MISO_PIN  PTC7
#define SPI_SCK_PIN   PTC5
#define SPI_CS_PIN    PTC4

#define ENABLE_PIN    PTA4
#define DIRECTION_PIN PTA2
#define BRAKE_PIN     PTA1

#define CURRENT_PIN     PTB0
#define TEMPERATURE_PIN PTE30
#define VOLTAGE_PIN     PTD5

// Global object/variable instantiations (these should not change)
DigitalOut led_1(LED_1_PIN);
Encoder encoder(SPI_MOSI_PIN, SPI_MISO_PIN, SPI_SCK_PIN, SPI_CS_PIN);

PwmOut enable(ENABLE_PIN);
DigitalOut direction(DIRECTION_PIN);
DigitalOut brake(BRAKE_PIN);

AnalogIn current_sense(CURRENT_PIN);
AnalogIn temperature_sense(TEMPERATURE_PIN);
AnalogIn voltage_sense(VOLTAGE_PIN);

Timer system_timer;
sensor_data_t last_sensor_data;
command_data_t last_command_data;

// This was the best compromise speed since mbed is 41.94MHz and ImageProc is
// 40MHz
#define SERIAL_BAUDRATE 873813

// Converts ticks/us to rad/s in 16.16 fixed point. Divide resulting number by
// 2^16 for final result
#define TICK_US_TO_RAD_S_FIXP 25142741 //78640346

// ticks to radians in 8.24 fixed point: multiply by 2^24 for scaled value
// 2*pi/(2^14)*2^24 = 6433.9818
// this approximation accumulates one tick of error per 21 revolutions
// 2*pi/(2^14)*2^16 = 25.1327
// this approximation accumulates 0.5% error
#define TICK_TO_RAD_FIXP 25 //6434
int32_t revolutions = 0;
int32_t integrator = 0;
int32_t velocity_filtered = 0;
int32_t current_position = 0;

uint8_t control_mode = 0;

int32_t position_absolute;
int32_t velocity_unfiltered;
uint32_t dt;

#define COMMAND_LIMIT 0.5 // maximum duty cycle: [0,1] (1 is full on)
#define V_TAU 20000 // velocity LP time constant in us

// 16.16 fixed point: divide by 2^16 for scaled value
#define LOW_STOP -2*2*314*(1<<16)/100 // motor position limit
#define HIGH_STOP 17*2*314*(1<<16)/100 // motor high position limit
#define INTEGRATOR_MAX 1*(1<<16) // integrator saturation in rad*s
#define KP 3*(1<<16)/10 // fraction of command per rad
#define KI 1*(1<<16)/100 // fraction of command per rad*s
#define KD 1*(1<<16)/50 // fraction of command per rad/s

// Fills a packet with the most recent acquired sensor data
void get_last_sensor_data(packet_t* pkt, uint8_t flags) {
  pkt->header.type = PKT_TYPE_SENSOR;
  pkt->header.length = sizeof(header_t) + sizeof(sensor_data_t) + 1;
  pkt->header.flags = flags;
  sensor_data_t* sensor_data = (sensor_data_t*)pkt->data_crc;
  sensor_data->time = last_sensor_data.time;
  sensor_data->position = last_sensor_data.position;
  sensor_data->velocity = last_sensor_data.velocity;
  sensor_data->current = last_sensor_data.current;
  sensor_data->voltage = last_sensor_data.voltage;
  sensor_data->temperature = last_sensor_data.temperature;
  sensor_data->uc_temp = last_sensor_data.uc_temp;
}

// Sense and control function to be run at 1kHz
void sense_control_thread(void const *arg) {
  uint32_t last_time = last_sensor_data.time;
  int32_t last_position = current_position; // 3us
  last_sensor_data.time = system_timer.read_us(); // 19.6us
  encoder.update_state();

  dt = last_sensor_data.time - last_time; // timing
  current_position = encoder.get_cal_state();
  /*
  last_sensor_data.position = encoder.get_cal_state(); // 393us
  last_sensor_data.velocity = (
        TICK_US_TO_RAD_S_FIXP*(last_sensor_data.position - last_position)) /
            (last_sensor_data.time-last_time); // 8.1us
  last_sensor_data.current = current_sense.read_u16(); //85.6us
  last_sensor_data.temperature = temperature_sense.read_u16(); // 85.6us
  last_sensor_data.uc_temp = 0x1234;
  */

  // Position: rad in 15.16 fixed point
  if (current_position > 3<<12 && last_position < 1<<12) {
    revolutions--;
  } else if (current_position < 1<<12 && last_position > 3<<12) {
    revolutions++;
  }
  int32_t last_position_absolute = position_absolute;
  position_absolute = TICK_TO_RAD_FIXP *
        (revolutions*(1<<14) + current_position);

  // Velocity: rad/s in 15.16 fixed point
  velocity_unfiltered = 1000000*(((int64_t)position_absolute -
        (int64_t)last_position_absolute)/dt);
  velocity_filtered =
        dt*velocity_unfiltered/(V_TAU + dt) +
        V_TAU*velocity_filtered/(V_TAU + dt);

  // Add data to struct
  last_sensor_data.position = position_absolute;
  last_sensor_data.velocity = velocity_filtered;
  last_sensor_data.current = current_sense.read_u16();
  last_sensor_data.temperature = temperature_sense.read_u16();
  last_sensor_data.uc_temp = 0x1234;

  // TODO: Calculate and apply control
  int32_t command = 0;
  switch (control_mode) {
    case 0:
      command = 0;
      integrator = 0;
      break;

    case 1:
      // TODO: Current control
      command = 0;
      integrator = 0;
      break;

    case 2:
      int32_t target_position = 0*(1<<16); // rad in 16.16 fixed point
      int32_t target_velocity = 0*(1<<16); // rad/s in 16.16 fixed point

      /*
      if (last_sensor_data.time % 10000000 < 5000000) {
        target_position = 30*(1<<16);//1.5*(1<<16);
      }
      */
      /*
      target_position = 6*(int64_t)last_sensor_data.time*(1<<16)/1000000;
      target_velocity = 6*(1<<16);
      */
      target_position = last_command_data.position_setpoint;

      int32_t position_error = position_absolute - target_position;

      // Integrator: rad*s in 15.16 fixed point
      integrator += (int32_t)((int64_t)position_error*(uint64_t)dt/1000000);
      if (integrator > INTEGRATOR_MAX) { // integrator saturation to prevent windup
        integrator = INTEGRATOR_MAX;
      } else if (integrator < -INTEGRATOR_MAX) {
        integrator = -INTEGRATOR_MAX;
      }

      // Command
      command = (-KP*(int64_t)position_error)/(1<<16) +
            (-KD*((int64_t)velocity_filtered-(int64_t)target_velocity))/(1<<16) +
            (-KI*(int64_t)integrator)/(1<<16);

      break;
  }

  if (position_absolute > HIGH_STOP) { // high limit stop
      command = command > 0.0 ? 0.0 : command;
  } else if (position_absolute < LOW_STOP) { // low limit stop
      command = command < 0.0 ? 0.0 : command;
  }
  float command_magnitude = fabs(static_cast<float>(command)/(1<<16));
  command_magnitude = command_magnitude > COMMAND_LIMIT
      ? COMMAND_LIMIT : command_magnitude; // limit maximum duty cycle
  enable.write(1-command_magnitude);
  direction.write(command > 0);
  // end Calculate and apply control (JY)

  // This puts the packet in the outgoing queue if there is space
  PacketParser* parser = (PacketParser*)(arg);
  packet_union_t* sensor_pkt = parser->get_send_packet();
  if (sensor_pkt != NULL) {
    get_last_sensor_data(&(sensor_pkt->packet),0);
    parser->send_packet(sensor_pkt);
  }
}

int main() {
  enable.period_us(50);
  enable.write(0.9f);
  direction.write(0);
  brake.write(1);

  control_mode = 0; // by default, disable the motor

  led_1 = 1;

  // Start the microsecond time
  system_timer.start();

  // Instantiate packet parser
  PacketParser parser(
      SERIAL_BAUDRATE, UART_TX_PIN, UART_RX_PIN, LED_2_PIN, LED_3_PIN);

  // Run the sense/control thread at 1kHz
  RtosTimer sense_control_ticker(
      &sense_control_thread, osTimerPeriodic, (void*)(&parser));

  sense_control_ticker.start(1);

  // Pointer to received packet
  packet_union_t* recv_pkt = NULL;

  while(1) {

    // See if there is a received packet
    recv_pkt = parser.get_received_packet();

    if (recv_pkt != NULL) {

      led_1 = !(led_1.read());

      switch (recv_pkt->packet.header.type) {

        // If got a command packet, store command value
        case PKT_TYPE_COMMAND:
          memcpy(&last_command_data,recv_pkt->packet.data_crc,
              sizeof(command_data_t));
          // TODO: state machine for control modes
          control_mode = recv_pkt->packet.header.flags;
          // end control modes (JY)
          break;

        default:
          // TODO: do something if we got an unrecognized packet type?
          break;
      }
      parser.free_received_packet(recv_pkt);
    }

    // This will process any outgoing packets
    parser.send_worker();
  }
}
<|endoftext|>


<commit_before>cfdd1ba6-4b02-11e5-b095-28cfe9171a43<commit_msg>We apologise for the previous fix. Those responsible have been sacked<commit_after>cfebadd9-4b02-11e5-8655-28cfe9171a43<|endoftext|>


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

#include <stdio.h>

extern "C" {
#include <pg_config.h>
#include <postgres.h>
#include <storage/bufpage.h>
#include <storage/itemid.h>
#include <access/htup.h>
}
#define PAGE_SIZE (8*1024)

namespace {

char hexadecimate(unsigned value) {
	switch( value ) {
	case 0: return '0';
	case 1: return '1';
	case 2: return '2';
	case 3: return '3';
	case 4: return '4';
	case 5: return '5';
	case 6: return '6';
	case 7: return '7';
	case 8: return '8';
	case 9: return '9';
	case 10: return 'A';
	case 11: return 'B';
	case 12: return 'C';
	case 13: return 'D';
	case 14: return 'E';
	case 15: return 'F';
	}
	assert(false);
	return '?';
}

inline unsigned integral_division(unsigned dividend, unsigned divisor) {
	unsigned result = dividend/divisor;
	assert( dividend - (divisor*result) == 0 );
	return result;
}

struct Varlena : public varlena {
	unsigned _size() {
		return *reinterpret_cast<unsigned*>(vl_len_);
	}
	unsigned size() {
		assert(false);//WIP
		return _size();
	}
};

struct ItemHeader;
struct ItemData {
	ItemHeader* header;
	char* data;
	unsigned data_size;

	std::string hexadecimate_all(unsigned pos=0,unsigned max=-1) {
		std::string result;
		unsigned end = data_size;
		if( end > max )
			end = max;

		for( unsigned int i = pos; i < end; ++i ) {
			if( isalnum(data[i]) ) {
				result += data[i];
			} else if( data[i] == '\n' ) {
				result += "\\n";
			} else if( data[i] == ' ') {
				result += " ";
			} else {
//				result += std::to_string( data[i] );
//				result += hexadecimate( ((unsigned char)(data[i]))>>4 );
//				result += hexadecimate( data[i]&0xF );
				result += "X";
			}
//			result += " ";
		}
		return result;
	}

	unsigned get_serial(unsigned pos) {
		return *reinterpret_cast<unsigned*>( data+pos );
	};
	unsigned get_serial_size() {
		return 4;
	}

	Varlena* get_varlena(unsigned pos) {
		return reinterpret_cast<Varlena*>( data+pos );
	}
	unsigned get_varlena_size(unsigned pos) {
		return get_varlena(pos)->size();
	}

};

struct ItemHeader : public HeapTupleHeaderData {
	unsigned number_attributes() {
		return unsigned(t_infomask2 & HEAP_NATTS_MASK);
	}

	bool has_bitmap() {
		return bool(t_infomask & HEAP_HASNULL);
	}

	bool has_attribute(unsigned pos) {
		return !bool(att_isnull(pos,t_bits));
	}
};

struct PageData : public PageHeaderData {
	unsigned itemid_count() {
		return integral_division( pd_lower-sizeof(PageHeaderData)+sizeof(ItemIdData), sizeof(ItemIdData) );
	};

	ItemHeader* get_item_header(const ItemIdData& itemid) {
		return reinterpret_cast<ItemHeader*>( reinterpret_cast<char*>(this)+itemid.lp_off );
	};

	ItemData get_item_data(const ItemIdData& itemid) {
		ItemHeader* header = get_item_header(itemid);
		char* data = reinterpret_cast<char*>(header) + header->t_hoff;
		unsigned data_size = itemid.lp_len - header->t_hoff;

		ItemData result = {header,data,data_size};
		return result;
	}
};

char read_page_buffer[PAGE_SIZE];
PageData* read_page(std::istream& stream, unsigned pos) {
	stream.seekg(pos*PAGE_SIZE,std::istream::beg);
	stream.read(read_page_buffer,PAGE_SIZE);
	return reinterpret_cast<PageData*>(&read_page_buffer);
}

}

void user_code(ItemIdData& itemid, ItemHeader& itemheader, ItemData& itemdata);

int main(int argc, char** argv) {
	assert( sizeof(PageData) == 24+sizeof(ItemIdData) );
	assert( sizeof(ItemIdData) == 4 );

	if( argc < 2 ) {
		std::cerr << "Usage " << argv[0] << " input_file" << std::endl;
		return 1;
	}

	std::ifstream input(argv[1]);
	assert( input.good() );

	input.seekg(0, std::ifstream::end);
	unsigned size = input.tellg();
	input.seekg(0, std::ifstream::beg);
	unsigned pages = size/PAGE_SIZE;
	if( size - (pages*PAGE_SIZE) != 0 ) {
		std::cerr << "Given file is not aligned to " << PAGE_SIZE << " bytes" << std::endl;
		return 1;
	}

	if( pages == 0 ) {
		std::cerr << "Given file has zero pages" << std::endl;
		return 1;
	};

	for( unsigned int which_page=0;which_page<pages;++which_page) {
		PageData& page = *read_page(input,which_page);
		std::cout << "Page " << which_page << "(" << page.itemid_count() << " itens)" << std::endl;
		for( unsigned int i = 0; i < page.itemid_count(); ++i ) {
			ItemIdData& itemid = page.pd_linp[i];
			if( itemid.lp_flags != LP_NORMAL ) {
				std::cerr << "\tIgnoring item because it is not marked as LP_NORMAL" << std::endl;
			} else if( itemid.lp_len == 0 ) {
				std::cerr << "\tIgnoring item because it has no storage" << std::endl;
			} else if( itemid.lp_off > PAGE_SIZE ) {
				std::cerr << "\tIgnoring item because it's offset is outside of page" << std::endl;
			} else if( itemid.lp_off + itemid.lp_len > PAGE_SIZE ) {
				std::cerr << "\tIgnoring item because it spans outsize of the page" << std::endl;
			} else {
				ItemHeader& itemheader = *page.get_item_header(itemid);
				std::cout << "\tItem (" << itemid.lp_off << "," << itemid.lp_len << ")~" << itemid.lp_flags;
				std::cout << ", number of attributes is " << itemheader.number_attributes();
				std::cout << " " << (itemheader.has_bitmap() ? "with" : "without") << " bitmap";
				if( itemheader.has_bitmap() ) {
					std::cout << ":\t";
					for( unsigned int j=0; j < itemheader.number_attributes(); ++j) {
						std::cout << " " << itemheader.has_attribute(j);
					}
				}
				ItemData itemdata = page.get_item_data(itemid);
				std::cout << ", data size is " << itemdata.data_size << std::endl;

				user_code(itemid,itemheader,itemdata);
			}
		};
	}

	return 0;
};

void user_code(ItemIdData& itemid, ItemHeader& itemheader, ItemData& itemdata) {
	std::cout << itemdata.hexadecimate_all() << std::endl;

	return;
};
<commit_msg>Fixed bug and handle page parsing correctly<commit_after>#include <fstream>
#include <string>
#include <cassert>
#include <iostream>

#include <stdio.h>

extern "C" {
#include <pg_config.h>
#include <postgres.h>
#include <storage/bufpage.h>
#include <storage/itemid.h>
#include <access/htup.h>
}
#define PAGE_SIZE (8*1024)

namespace {

char hexadecimate(unsigned value) {
	switch( value ) {
	case 0: return '0';
	case 1: return '1';
	case 2: return '2';
	case 3: return '3';
	case 4: return '4';
	case 5: return '5';
	case 6: return '6';
	case 7: return '7';
	case 8: return '8';
	case 9: return '9';
	case 10: return 'A';
	case 11: return 'B';
	case 12: return 'C';
	case 13: return 'D';
	case 14: return 'E';
	case 15: return 'F';
	}
	assert(false);
	return '?';
}

inline unsigned integral_division(unsigned dividend, unsigned divisor) {
	unsigned result = dividend/divisor;
	assert( dividend - (divisor*result) == 0 );
	return result;
}

struct Varlena : public varlena {
	unsigned _size() {
		return *reinterpret_cast<unsigned*>(vl_len_);
	}

	enum LenType {
		NORMAL,COMPRESSED,TOASTED,ONE_BYTE
	};

	LenType len_type() {
		if( vl_len_[0] & 0x1 ) {
			if( vl_len_[0] == 1 ) {
				return TOASTED;
			} else {
				return ONE_BYTE;
			}
		} else {
			if( (vl_len_[0] & 0x2) == 0 ) {
				return NORMAL;
			} else {
				return COMPRESSED;
			}
		}
	};

	unsigned size() {
		switch( len_type() ) {
		case NORMAL: return _size()>>2;
		case COMPRESSED: return _size()>>2;
		case TOASTED: return 18;
		case ONE_BYTE: return (_size()&0xFF)>>1;
		}
	}

	std::string build_string() {
		unsigned size_str = size();

		char* data = reinterpret_cast<char*>(this);
		switch( len_type() ) {
		case COMPRESSED: return "COMPRESSED";
		case TOASTED: return "TOASTED";
		case NORMAL: data += 4; size_str -= 4; break;
		case ONE_BYTE: data += 1; size_str -= 1; break;
		}

		std::string r;
		for( unsigned int i=0;i<size_str;++i ) {
			r += data[i];
		}
		return r;
	};
};

struct ItemHeader;
struct ItemData {
	ItemHeader* header;
	char* data;
	unsigned data_size;

	std::string hexadecimate_all(unsigned pos=0,unsigned max=-1) {
		std::string result;
		unsigned end = data_size;
		if( end > max )
			end = max;

		for( unsigned int i = pos; i < end; ++i ) {
			if( data[i] >= '!' && data[i] <= '~') {
				result += data[i];
			} else if( data[i] == '\n' ) {
				result += "\\n";
			} else if( data[i] == ' ') {
				result += " ";
			} else {
//				result += std::to_string( data[i] );
				result += hexadecimate( ((unsigned char)(data[i]))>>4 );
				result += hexadecimate( data[i]&0xF );
//				result += "X";
			}
			result += " ";
		}
		return result;
	}

	//TODO Assuming numbers are word aligned, check this
	unsigned word_padding(unsigned pos) {
		return (4-(pos%4))%4;
	}

	unsigned get_unsigned(unsigned pos) {
		return *reinterpret_cast<unsigned*>( data+pos+word_padding(pos) );
	};
	unsigned get_unsigned_size(unsigned pos) {
		return 4+word_padding(pos);
	}

	int get_integer(unsigned pos) {
		return *reinterpret_cast<int*>( data+pos+word_padding(pos) );
	};
	int get_integer_size(unsigned pos) {
		return 4+word_padding(pos);
	}

	Varlena* get_varlena(unsigned pos) {
		return reinterpret_cast<Varlena*>( data+pos );
	}
	unsigned get_varlena_size(unsigned pos) {
		return get_varlena(pos)->size();
	}
};

struct ItemHeader : public HeapTupleHeaderData {
	unsigned number_attributes() {
		return unsigned(t_infomask2 & HEAP_NATTS_MASK);
	}

	bool has_bitmap() {
		return bool(t_infomask & HEAP_HASNULL);
	}

	bool has_attribute(unsigned pos) {
		return !bool(att_isnull(pos,t_bits));
	}
};

struct PageData : public PageHeaderData {
	unsigned itemid_count() {
		return integral_division( pd_lower-sizeof(PageHeaderData)+sizeof(ItemIdData), sizeof(ItemIdData) );
	};

	ItemHeader* get_item_header(const ItemIdData& itemid) {
		return reinterpret_cast<ItemHeader*>( reinterpret_cast<char*>(this)+itemid.lp_off );
	};

	ItemData get_item_data(const ItemIdData& itemid) {
		ItemHeader* header = get_item_header(itemid);
		char* data = reinterpret_cast<char*>(header) + header->t_hoff;
		unsigned data_size = itemid.lp_len - header->t_hoff;

		ItemData result = {header,data,data_size};
		return result;
	}
};

char read_page_buffer[PAGE_SIZE];
PageData* read_page(std::istream& stream, unsigned pos) {
	stream.seekg(pos*PAGE_SIZE,std::istream::beg);
	stream.read(read_page_buffer,PAGE_SIZE);
	return reinterpret_cast<PageData*>(&read_page_buffer);
}

}

void user_code(ItemIdData& itemid, ItemHeader& itemheader, ItemData& itemdata);

int main(int argc, char** argv) {
	assert( sizeof(PageData) == 24+sizeof(ItemIdData) );
	assert( sizeof(ItemIdData) == 4 );

	if( argc < 2 ) {
		std::cerr << "Usage " << argv[0] << " input_file" << std::endl;
		return 1;
	}

	std::ifstream input(argv[1]);
	assert( input.good() );

	input.seekg(0, std::ifstream::end);
	unsigned size = input.tellg();
	input.seekg(0, std::ifstream::beg);
	unsigned pages = size/PAGE_SIZE;
	if( size - (pages*PAGE_SIZE) != 0 ) {
		std::cerr << "Given file is not aligned to " << PAGE_SIZE << " bytes" << std::endl;
		return 1;
	}

	if( pages == 0 ) {
		std::cerr << "Given file has zero pages" << std::endl;
		return 1;
	};

	for( unsigned int which_page=0;which_page<pages;++which_page) {
		PageData& page = *read_page(input,which_page);
		std::cout << "Page " << which_page << "(" << page.itemid_count() << " itens)" << std::endl;
		for( unsigned int i = 0; i < page.itemid_count(); ++i ) {
			ItemIdData& itemid = page.pd_linp[i];
			if( itemid.lp_flags != LP_NORMAL ) {
				std::cerr << "\tIgnoring item because it is not marked as LP_NORMAL" << std::endl;
			} else if( itemid.lp_len == 0 ) {
				std::cerr << "\tIgnoring item because it has no storage" << std::endl;
			} else if( itemid.lp_off > PAGE_SIZE ) {
				std::cerr << "\tIgnoring item because it's offset is outside of page" << std::endl;
			} else if( itemid.lp_off + itemid.lp_len > PAGE_SIZE ) {
				std::cerr << "\tIgnoring item because it spans outsize of the page" << std::endl;
			} else {
				ItemHeader& itemheader = *page.get_item_header(itemid);
				std::cout << "\tItem (" << itemid.lp_off << "," << itemid.lp_len << ")~" << itemid.lp_flags;
				std::cout << ", number of attributes is " << itemheader.number_attributes();
				std::cout << " " << (itemheader.has_bitmap() ? "with" : "without") << " bitmap";
				if( itemheader.has_bitmap() ) {
					std::cout << ":\t";
					for( unsigned int j=0; j < itemheader.number_attributes(); ++j) {
						std::cout << " " << itemheader.has_attribute(j);
					}
				}
				ItemData itemdata = page.get_item_data(itemid);
				std::cout << ", data size is " << itemdata.data_size << std::endl;

				user_code(itemid,itemheader,itemdata);
			}
		};
	}

	return 0;
};

void user_code(ItemIdData& itemid, ItemHeader& itemheader, ItemData& itemdata) {
	std::cout << itemdata.hexadecimate_all() << std::endl;

	return;
};
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ins_paste.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 04:03:39 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifdef SD_DLLIMPLEMENTATION
#undef SD_DLLIMPLEMENTATION
#endif

#include "ins_paste.hrc"
#include "ins_paste.hxx"

// --------------------
// - SdInsertPasteDlg -
// --------------------

SdInsertPasteDlg::SdInsertPasteDlg( Window* pWindow ) :
    ModalDialog( pWindow, SdResId( DLG_INSERT_PASTE ) ),
    aFlPosition( this, SdResId( FL_POSITION ) ),
    aRbBefore( this, SdResId( RB_BEFORE ) ),
    aRbAfter( this, SdResId( RB_AFTER ) ),
    aBtnOK( this, SdResId( BTN_OK ) ),
    aBtnCancel( this, SdResId( BTN_CANCEL ) ),
    aBtnHelp( this, SdResId( BTN_HELP ) )
{
    FreeResource();
    aRbAfter.Check( TRUE );
}

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

SdInsertPasteDlg::~SdInsertPasteDlg()
{
}

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

BOOL SdInsertPasteDlg::IsInsertBefore() const
{
    return( aRbBefore.IsChecked() );
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.282); FILE MERGED 2006/09/01 17:36:59 kaib 1.3.282.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ins_paste.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 18:39:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#ifdef SD_DLLIMPLEMENTATION
#undef SD_DLLIMPLEMENTATION
#endif

#include "ins_paste.hrc"
#include "ins_paste.hxx"

// --------------------
// - SdInsertPasteDlg -
// --------------------

SdInsertPasteDlg::SdInsertPasteDlg( Window* pWindow ) :
    ModalDialog( pWindow, SdResId( DLG_INSERT_PASTE ) ),
    aFlPosition( this, SdResId( FL_POSITION ) ),
    aRbBefore( this, SdResId( RB_BEFORE ) ),
    aRbAfter( this, SdResId( RB_AFTER ) ),
    aBtnOK( this, SdResId( BTN_OK ) ),
    aBtnCancel( this, SdResId( BTN_CANCEL ) ),
    aBtnHelp( this, SdResId( BTN_HELP ) )
{
    FreeResource();
    aRbAfter.Check( TRUE );
}

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

SdInsertPasteDlg::~SdInsertPasteDlg()
{
}

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

BOOL SdInsertPasteDlg::IsInsertBefore() const
{
    return( aRbBefore.IsChecked() );
}
<|endoftext|>