<commit_before>#include "res_settings.h"
#include "dlg_controls.h"
#include "registry.h"

namespace App {
	using namespace Intl;

	bool SetControls::PerformOnInitPage() {
		Caption(SIDSettingsControls);

		ControlText(IDC_GROUP_CLICK, SIDSettingsControlsClick);
		ControlText(IDC_TEXT_CTRL_LMOUSECLICK, SIDSettingsControlsLeftMouse);
		ControlText(IDC_TEXT_CTRL_MMOUSECLICK, SIDSettingsControlsMiddleMouse);
		ControlText(IDC_TEXT_CTRL_RMOUSECLICK, SIDSettingsControlsRightMouse);
		ControlText(IDC_TEXT_CTRL_XMOUSE1CLICK, SIDSettingsControlsExtra1Mouse);
		ControlText(IDC_TEXT_CTRL_XMOUSE2CLICK, SIDSettingsControlsExtra2Mouse);

		ControlText(IDC_GROUP_DOUBLECLICK, SIDSettingsControlsDoubleClick);
		ControlText(IDC_TEXT_CTRL_LMOUSEDOUBLECLICK, SIDSettingsControlsLeftMouse);
		ControlText(IDC_TEXT_CTRL_MMOUSEDOUBLECLICK, SIDSettingsControlsMiddleMouse);
		ControlText(IDC_TEXT_CTRL_RMOUSEDOUBLECLICK, SIDSettingsControlsRightMouse);
		ControlText(IDC_TEXT_CTRL_XMOUSE1DOUBLECLICK, SIDSettingsControlsExtra1Mouse);
		ControlText(IDC_TEXT_CTRL_XMOUSE2DOUBLECLICK, SIDSettingsControlsExtra2Mouse);

		ControlText(IDC_GROUP_MWHEEL, SIDSettingsControlsScrollWheel);
		ControlText(IDC_TEXT_CTRL_MWHEELUP, SIDSettingsControlsWheelUp);
		ControlText(IDC_TEXT_CTRL_MWHEELDOWN, SIDSettingsControlsWheelDown);

		m_cbLeftMouse = CreateComboBox(IDC_COMBO_CTRL_LMOUSE);
		m_cbMiddleMouse = CreateComboBox(IDC_COMBO_CTRL_MMOUSE);
		m_cbRightMouse = CreateComboBox(IDC_COMBO_CTRL_RMOUSE);
		m_cbExtra1Mouse = CreateComboBox(IDC_COMBO_CTRL_XMOUSE1);
		m_cbExtra2Mouse = CreateComboBox(IDC_COMBO_CTRL_XMOUSE2);

		m_cbLeftMouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_LMOUSEDBL);
		m_cbMiddleMouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_MMOUSEDBL);
		m_cbRightMouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_RMOUSEDBL);
		m_cbExtra1MouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_XMOUSE1DBL);
		m_cbExtra2MouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_XMOUSE2DBL);

		m_cbWheelDown = CreateComboBox(IDC_COMBO_CTRL_MWHEELDOWN);
		m_cbWheelUp = CreateComboBox(IDC_COMBO_CTRL_MWHEELUP);

		initMouseButtonList(m_cbLeftMouse);
		initMouseButtonList(m_cbMiddleMouse);
		initMouseButtonList(m_cbRightMouse);
		initMouseButtonList(m_cbExtra1Mouse);
		initMouseButtonList(m_cbExtra2Mouse);

		initMouseDblList(m_cbLeftMouseDoubleClick);
		initMouseDblList(m_cbMiddleMouseDoubleClick);
		initMouseDblList(m_cbRightMouseDoubleClick);
		initMouseDblList(m_cbExtra1MouseDoubleClick);
		initMouseDblList(m_cbExtra2MouseDoubleClick);

		initMouseWheelList(m_cbWheelUp);
		initMouseWheelList(m_cbWheelDown);

		return true;
	}

	void SetControls::PerformUpdateFromSettings(const Reg::Settings& settings) {
		m_cbLeftMouse->SetSelection(settings.Mouse.OnMouseLeft);
		m_cbMiddleMouse->SetSelection(settings.Mouse.OnMouseMiddle);
		m_cbRightMouse->SetSelection(settings.Mouse.OnMouseRight);
		m_cbExtra1Mouse->SetSelection(settings.Mouse.OnMouseExtra1);
		m_cbExtra2Mouse->SetSelection(settings.Mouse.OnMouseExtra2);

		m_cbLeftMouseDoubleClick->SetSelection(settings.Mouse.OnMouseLeftDbl);
		m_cbMiddleMouseDoubleClick->SetSelection(settings.Mouse.OnMouseMiddleDbl);
		m_cbRightMouseDoubleClick->SetSelection(settings.Mouse.OnMouseRightDbl);
		m_cbExtra1MouseDoubleClick->SetSelection(settings.Mouse.OnMouseExtra1Dbl);
		m_cbExtra2MouseDoubleClick->SetSelection(settings.Mouse.OnMouseExtra2Dbl);

		m_cbWheelUp->SetSelection(settings.Mouse.OnMouseWheelUp);
		m_cbWheelDown->SetSelection(settings.Mouse.OnMouseWheelDown);
	}

	void SetControls::onWriteSettings(Reg::Settings& settings) {
		settings.Mouse.OnMouseLeft = App::MouseAction(m_cbLeftMouse->GetSelectionData());
		settings.Mouse.OnMouseMiddle = App::MouseAction(m_cbMiddleMouse->GetSelectionData());
		settings.Mouse.OnMouseRight = App::MouseAction(m_cbRightMouse->GetSelectionData());
		settings.Mouse.OnMouseExtra1 = App::MouseAction(m_cbExtra1Mouse->GetSelectionData());
		settings.Mouse.OnMouseExtra2 = App::MouseAction(m_cbExtra2Mouse->GetSelectionData());

		settings.Mouse.OnMouseLeftDbl = App::MouseAction(m_cbLeftMouseDoubleClick->GetSelectionData());
		settings.Mouse.OnMouseMiddleDbl = App::MouseAction(m_cbMiddleMouseDoubleClick->GetSelectionData());
		settings.Mouse.OnMouseRightDbl = App::MouseAction(m_cbRightMouseDoubleClick->GetSelectionData());
		settings.Mouse.OnMouseExtra1Dbl = App::MouseAction(m_cbExtra1MouseDoubleClick->GetSelectionData());
		settings.Mouse.OnMouseExtra2Dbl = App::MouseAction(m_cbExtra2MouseDoubleClick->GetSelectionData());

		settings.Mouse.OnMouseWheelUp = App::MouseAction(m_cbWheelUp->GetSelectionData());
		settings.Mouse.OnMouseWheelDown = App::MouseAction(m_cbWheelDown->GetSelectionData());
	}

	SetControls::SetControls():
		App::SettingsPage(IDD_SET_CTRL_MOUSE),
		m_cbLeftMouse{ nullptr },
		m_cbMiddleMouse{ nullptr },
		m_cbRightMouse{ nullptr },
		m_cbExtra1Mouse{ nullptr },
		m_cbExtra2Mouse{ nullptr },
		m_cbLeftMouseDoubleClick{ nullptr },
		m_cbMiddleMouseDoubleClick{ nullptr },
		m_cbRightMouseDoubleClick{ nullptr },
		m_cbExtra1MouseDoubleClick{ nullptr },
		m_cbExtra2MouseDoubleClick{ nullptr },
		m_cbWheelUp{ nullptr },
		m_cbWheelDown{ nullptr }
	{}

	void SetControls::initMouseButtonList(Win::ComboBox* ctrl) {
		ctrl->Reset();
		ctrl->AddItem(SIDActionDisable, MouseDisable);
		ctrl->AddItem(SIDActionPan, MousePan);
		ctrl->AddItem(SIDActionContextMenu, MouseContext);
		ctrl->AddItem(SIDActionToggleFullSizeDefaultZoom, MouseToggleFullSizeDefaultZoom);
		ctrl->AddItem(SIDActionFullscreen, MouseFullscreen);
		ctrl->AddItem(SIDActionNextImage, MouseNextImage);
		ctrl->AddItem(SIDActionPreviousImage, MousePrevImage);
	}

	void SetControls::initMouseDblList(Win::ComboBox* ctrl) {
		ctrl->Reset();
		ctrl->AddItem(SIDActionDisable, MouseDisable);
		ctrl->AddItem(SIDActionToggleFullSizeDefaultZoom, MouseToggleFullSizeDefaultZoom);
		ctrl->AddItem(SIDActionFullscreen, MouseFullscreen);
	}

	void SetControls::initMouseWheelList(Win::ComboBox* ctrl) {
		ctrl->Reset();
		ctrl->AddItem(SIDActionDisable, MouseDisable);
		ctrl->AddItem(SIDActionNextImage, MouseNextImage);
		ctrl->AddItem(SIDActionPreviousImage, MousePrevImage);
		ctrl->AddItem(SIDActionZoomIn, MouseZoomIn);
		ctrl->AddItem(SIDActionZoomOut, MouseZoomOut);
	}
}
<commit_msg>Add more mouse actions for clicks and doubleclicks<commit_after>#include "res_settings.h"
#include "dlg_controls.h"
#include "registry.h"

namespace App {
	using namespace Intl;

	bool SetControls::PerformOnInitPage() {
		Caption(SIDSettingsControls);

		ControlText(IDC_GROUP_CLICK, SIDSettingsControlsClick);
		ControlText(IDC_TEXT_CTRL_LMOUSECLICK, SIDSettingsControlsLeftMouse);
		ControlText(IDC_TEXT_CTRL_MMOUSECLICK, SIDSettingsControlsMiddleMouse);
		ControlText(IDC_TEXT_CTRL_RMOUSECLICK, SIDSettingsControlsRightMouse);
		ControlText(IDC_TEXT_CTRL_XMOUSE1CLICK, SIDSettingsControlsExtra1Mouse);
		ControlText(IDC_TEXT_CTRL_XMOUSE2CLICK, SIDSettingsControlsExtra2Mouse);

		ControlText(IDC_GROUP_DOUBLECLICK, SIDSettingsControlsDoubleClick);
		ControlText(IDC_TEXT_CTRL_LMOUSEDOUBLECLICK, SIDSettingsControlsLeftMouse);
		ControlText(IDC_TEXT_CTRL_MMOUSEDOUBLECLICK, SIDSettingsControlsMiddleMouse);
		ControlText(IDC_TEXT_CTRL_RMOUSEDOUBLECLICK, SIDSettingsControlsRightMouse);
		ControlText(IDC_TEXT_CTRL_XMOUSE1DOUBLECLICK, SIDSettingsControlsExtra1Mouse);
		ControlText(IDC_TEXT_CTRL_XMOUSE2DOUBLECLICK, SIDSettingsControlsExtra2Mouse);

		ControlText(IDC_GROUP_MWHEEL, SIDSettingsControlsScrollWheel);
		ControlText(IDC_TEXT_CTRL_MWHEELUP, SIDSettingsControlsWheelUp);
		ControlText(IDC_TEXT_CTRL_MWHEELDOWN, SIDSettingsControlsWheelDown);

		m_cbLeftMouse = CreateComboBox(IDC_COMBO_CTRL_LMOUSE);
		m_cbMiddleMouse = CreateComboBox(IDC_COMBO_CTRL_MMOUSE);
		m_cbRightMouse = CreateComboBox(IDC_COMBO_CTRL_RMOUSE);
		m_cbExtra1Mouse = CreateComboBox(IDC_COMBO_CTRL_XMOUSE1);
		m_cbExtra2Mouse = CreateComboBox(IDC_COMBO_CTRL_XMOUSE2);

		m_cbLeftMouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_LMOUSEDBL);
		m_cbMiddleMouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_MMOUSEDBL);
		m_cbRightMouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_RMOUSEDBL);
		m_cbExtra1MouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_XMOUSE1DBL);
		m_cbExtra2MouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_XMOUSE2DBL);

		m_cbWheelDown = CreateComboBox(IDC_COMBO_CTRL_MWHEELDOWN);
		m_cbWheelUp = CreateComboBox(IDC_COMBO_CTRL_MWHEELUP);

		initMouseButtonList(m_cbLeftMouse);
		initMouseButtonList(m_cbMiddleMouse);
		initMouseButtonList(m_cbRightMouse);
		initMouseButtonList(m_cbExtra1Mouse);
		initMouseButtonList(m_cbExtra2Mouse);

		initMouseDblList(m_cbLeftMouseDoubleClick);
		initMouseDblList(m_cbMiddleMouseDoubleClick);
		initMouseDblList(m_cbRightMouseDoubleClick);
		initMouseDblList(m_cbExtra1MouseDoubleClick);
		initMouseDblList(m_cbExtra2MouseDoubleClick);

		initMouseWheelList(m_cbWheelUp);
		initMouseWheelList(m_cbWheelDown);

		return true;
	}

	void SetControls::PerformUpdateFromSettings(const Reg::Settings& settings) {
		m_cbLeftMouse->SetSelection(settings.Mouse.OnMouseLeft);
		m_cbMiddleMouse->SetSelection(settings.Mouse.OnMouseMiddle);
		m_cbRightMouse->SetSelection(settings.Mouse.OnMouseRight);
		m_cbExtra1Mouse->SetSelection(settings.Mouse.OnMouseExtra1);
		m_cbExtra2Mouse->SetSelection(settings.Mouse.OnMouseExtra2);

		m_cbLeftMouseDoubleClick->SetSelection(settings.Mouse.OnMouseLeftDbl);
		m_cbMiddleMouseDoubleClick->SetSelection(settings.Mouse.OnMouseMiddleDbl);
		m_cbRightMouseDoubleClick->SetSelection(settings.Mouse.OnMouseRightDbl);
		m_cbExtra1MouseDoubleClick->SetSelection(settings.Mouse.OnMouseExtra1Dbl);
		m_cbExtra2MouseDoubleClick->SetSelection(settings.Mouse.OnMouseExtra2Dbl);

		m_cbWheelUp->SetSelection(settings.Mouse.OnMouseWheelUp);
		m_cbWheelDown->SetSelection(settings.Mouse.OnMouseWheelDown);
	}

	void SetControls::onWriteSettings(Reg::Settings& settings) {
		settings.Mouse.OnMouseLeft = App::MouseAction(m_cbLeftMouse->GetSelectionData());
		settings.Mouse.OnMouseMiddle = App::MouseAction(m_cbMiddleMouse->GetSelectionData());
		settings.Mouse.OnMouseRight = App::MouseAction(m_cbRightMouse->GetSelectionData());
		settings.Mouse.OnMouseExtra1 = App::MouseAction(m_cbExtra1Mouse->GetSelectionData());
		settings.Mouse.OnMouseExtra2 = App::MouseAction(m_cbExtra2Mouse->GetSelectionData());

		settings.Mouse.OnMouseLeftDbl = App::MouseAction(m_cbLeftMouseDoubleClick->GetSelectionData());
		settings.Mouse.OnMouseMiddleDbl = App::MouseAction(m_cbMiddleMouseDoubleClick->GetSelectionData());
		settings.Mouse.OnMouseRightDbl = App::MouseAction(m_cbRightMouseDoubleClick->GetSelectionData());
		settings.Mouse.OnMouseExtra1Dbl = App::MouseAction(m_cbExtra1MouseDoubleClick->GetSelectionData());
		settings.Mouse.OnMouseExtra2Dbl = App::MouseAction(m_cbExtra2MouseDoubleClick->GetSelectionData());

		settings.Mouse.OnMouseWheelUp = App::MouseAction(m_cbWheelUp->GetSelectionData());
		settings.Mouse.OnMouseWheelDown = App::MouseAction(m_cbWheelDown->GetSelectionData());
	}

	SetControls::SetControls():
		App::SettingsPage(IDD_SET_CTRL_MOUSE),
		m_cbLeftMouse{ nullptr },
		m_cbMiddleMouse{ nullptr },
		m_cbRightMouse{ nullptr },
		m_cbExtra1Mouse{ nullptr },
		m_cbExtra2Mouse{ nullptr },
		m_cbLeftMouseDoubleClick{ nullptr },
		m_cbMiddleMouseDoubleClick{ nullptr },
		m_cbRightMouseDoubleClick{ nullptr },
		m_cbExtra1MouseDoubleClick{ nullptr },
		m_cbExtra2MouseDoubleClick{ nullptr },
		m_cbWheelUp{ nullptr },
		m_cbWheelDown{ nullptr }
	{}

	void SetControls::initMouseButtonList(Win::ComboBox* ctrl) {
		ctrl->Reset();
		ctrl->AddItem(SIDActionDisable, MouseDisable);
		ctrl->AddItem(SIDActionPan, MousePan);
		ctrl->AddItem(SIDActionContextMenu, MouseContext);
		ctrl->AddItem(SIDActionToggleFullSizeDefaultZoom, MouseToggleFullSizeDefaultZoom);
		ctrl->AddItem(SIDActionFullscreen, MouseFullscreen);
		ctrl->AddItem(SIDActionNextImage, MouseNextImage);
		ctrl->AddItem(SIDActionPreviousImage, MousePrevImage);
		ctrl->AddItem(SIDActionZoomIn, MouseZoomIn);
		ctrl->AddItem(SIDActionZoomOut, MouseZoomOut);
	}

	void SetControls::initMouseDblList(Win::ComboBox* ctrl) {
		ctrl->Reset();
		ctrl->AddItem(SIDActionDisable, MouseDisable);
		ctrl->AddItem(SIDActionContextMenu, MouseContext);
		ctrl->AddItem(SIDActionToggleFullSizeDefaultZoom, MouseToggleFullSizeDefaultZoom);
		ctrl->AddItem(SIDActionFullscreen, MouseFullscreen);
		ctrl->AddItem(SIDActionNextImage, MouseNextImage);
		ctrl->AddItem(SIDActionPreviousImage, MousePrevImage);
		ctrl->AddItem(SIDActionZoomIn, MouseZoomIn);
		ctrl->AddItem(SIDActionZoomOut, MouseZoomOut);
	}

	void SetControls::initMouseWheelList(Win::ComboBox* ctrl) {
		ctrl->Reset();
		ctrl->AddItem(SIDActionDisable, MouseDisable);
		ctrl->AddItem(SIDActionNextImage, MouseNextImage);
		ctrl->AddItem(SIDActionPreviousImage, MousePrevImage);
		ctrl->AddItem(SIDActionZoomIn, MouseZoomIn);
		ctrl->AddItem(SIDActionZoomOut, MouseZoomOut);
	}
}
<|endoftext|>


<commit_before><commit_msg>crs wants tabs=4<commit_after><|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: lineModel.C,v 1.8 2003/12/12 17:51:51 amoll Exp $

#include <BALL/VIEW/MODELS/lineModel.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/VIEW/PRIMITIVES/point.h>
#include <BALL/VIEW/PRIMITIVES/twoColoredLine.h>

using namespace std;

namespace BALL
{
	namespace VIEW
	{

AddLineModel::AddLineModel()
	throw()
	: AtomBondModelBaseProcessor()
{
}

AddLineModel::AddLineModel(const AddLineModel& model)
	throw()
	: AtomBondModelBaseProcessor(model)
{
}

AddLineModel::~AddLineModel()
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "Destructing object " << (void *)this
							  << " of class " << RTTI::getName<AddLineModel>() << std::endl;
	#endif
}

Processor::Result AddLineModel::operator() (Composite &composite)
{
	if (!RTTI::isKindOf<Atom>(composite))
	{
		return Processor::CONTINUE;
	}

	Atom *atom = RTTI::castTo<Atom>(composite);

	Point *point_ptr = new Point;

	if (point_ptr == 0) throw Exception::OutOfMemory(__FILE__, __LINE__, sizeof(Point));

	point_ptr->setVertex(atom->getPosition());
	point_ptr->setComposite(atom);

	// append line in Atom
	geometric_objects_.push_back(point_ptr);

	// collect used atoms
	insertAtom_(atom);

	return Processor::CONTINUE;
}

void AddLineModel::dump(ostream& s, Size depth) const
	throw()
{
	BALL_DUMP_STREAM_PREFIX(s);

	BALL_DUMP_DEPTH(s, depth);
	BALL_DUMP_HEADER(s, this, this);

	AtomBondModelBaseProcessor::dump(s, depth + 1);

	BALL_DUMP_STREAM_SUFFIX(s);
}

void AddLineModel::visualiseBond_(const Bond& bond)
	throw()
{
	// generate two colored tube
	TwoColoredLine *line = new TwoColoredLine;

	if (line == 0) throw Exception::OutOfMemory(__FILE__, __LINE__, sizeof(TwoColoredLine));

	if (bond.getFirstAtom() == 0 ||
			bond.getSecondAtom() == 0)
	{
		throw Exception::NullPointer(__FILE__, __LINE__);
	}

	line->setVertex1Address(bond.getFirstAtom()->getPosition());
	line->setVertex2Address(bond.getSecondAtom()->getPosition());
	line->setComposite(&bond);
	geometric_objects_.push_back(line);
}

	} // namespace VIEW
} // namespace BALL
<commit_msg>fixed: now using pointer for vertex in point<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: lineModel.C,v 1.9 2003/12/16 21:16:34 amoll Exp $

#include <BALL/VIEW/MODELS/lineModel.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/VIEW/PRIMITIVES/point.h>
#include <BALL/VIEW/PRIMITIVES/twoColoredLine.h>

using namespace std;

namespace BALL
{
	namespace VIEW
	{

AddLineModel::AddLineModel()
	throw()
	: AtomBondModelBaseProcessor()
{
}

AddLineModel::AddLineModel(const AddLineModel& model)
	throw()
	: AtomBondModelBaseProcessor(model)
{
}

AddLineModel::~AddLineModel()
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "Destructing object " << (void *)this
							  << " of class " << RTTI::getName<AddLineModel>() << std::endl;
	#endif
}

Processor::Result AddLineModel::operator() (Composite &composite)
{
	if (!RTTI::isKindOf<Atom>(composite))
	{
		return Processor::CONTINUE;
	}

	Atom *atom = RTTI::castTo<Atom>(composite);

	Point *point_ptr = new Point;

	if (point_ptr == 0) throw Exception::OutOfMemory(__FILE__, __LINE__, sizeof(Point));

	point_ptr->setVertexAddress(atom->getPosition());
	point_ptr->setComposite(atom);

	// append line in Atom
	geometric_objects_.push_back(point_ptr);

	// collect used atoms
	insertAtom_(atom);

	return Processor::CONTINUE;
}

void AddLineModel::dump(ostream& s, Size depth) const
	throw()
{
	BALL_DUMP_STREAM_PREFIX(s);

	BALL_DUMP_DEPTH(s, depth);
	BALL_DUMP_HEADER(s, this, this);

	AtomBondModelBaseProcessor::dump(s, depth + 1);

	BALL_DUMP_STREAM_SUFFIX(s);
}

void AddLineModel::visualiseBond_(const Bond& bond)
	throw()
{
	// generate two colored tube
	TwoColoredLine *line = new TwoColoredLine;

	if (line == 0) throw Exception::OutOfMemory(__FILE__, __LINE__, sizeof(TwoColoredLine));

	if (bond.getFirstAtom() == 0 ||
			bond.getSecondAtom() == 0)
	{
		throw Exception::NullPointer(__FILE__, __LINE__);
	}

	line->setVertex1Address(bond.getFirstAtom()->getPosition());
	line->setVertex2Address(bond.getSecondAtom()->getPosition());
	line->setComposite(&bond);
	geometric_objects_.push_back(line);
}

	} // namespace VIEW
} // namespace BALL
<|endoftext|>


<commit_before>#include <stdio.h>
#include "Halide.h"
#include <fstream>
#include <cassert>
#include <iostream>

#include "test/common/halide_test_dirs.h"

using namespace Halide;

int main(int argc, char **argv) {
    Var x("x"), y("y");
    Func f("f");

    f(x, y) = 42;

    std::string bitcode_file = Internal::get_test_tmp_dir() + "extern.bc";
    f.compile_to_bitcode(bitcode_file, {}, "extern");

    std::vector<uint8_t> bitcode;
    std::ifstream bitcode_stream(bitcode_file, std::ios::in | std::ios::binary);
    bitcode_stream.seekg(0, std::ios::end);
    bitcode.resize(bitcode_stream.tellg());
    bitcode_stream.seekg(0, std::ios::beg);
    bitcode_stream.read(reinterpret_cast<char *>(&bitcode[0]), bitcode.size());

    ExternalCode external_code = ExternalCode::bitcode_wrapper(get_target_from_environment(), bitcode, "extern");

    Func f_extern;
    f_extern.define_extern("extern", { }, type_of<int32_t>(), 2);

    Func result;
    result(x, y) = f_extern(x, y);

    Module module = result.compile_to_module({}, "forty_two");

    module.append(external_code);

    auto forty_two = module.get_function_by_name("forty_two");

    Internal::JITModule jit_module(module, forty_two, {});

    auto main_function = (int (*)(halide_buffer_t *buf))jit_module.main_function();
    Buffer<int32_t> buf(16, 16);

    int ret_code = main_function(buf.raw_buffer());

    assert(ret_code == 0);
    for (int i = 0; i < 16; i++) {
        for (int j = 0; j < 16; j++) {
            assert(buf(i, j) == 42);
        }
    }

    printf("Success!\n");
    return 0;
}
<commit_msg>Attempt to fix MinGW test failure.<commit_after>#include <stdio.h>
#include "Halide.h"
#include <fstream>
#include <cassert>
#include <iostream>

#include "test/common/halide_test_dirs.h"

using namespace Halide;

int main(int argc, char **argv) {
    Var x("x"), y("y");
    Func f("f");

    f(x, y) = 42;

    std::string bitcode_file = Internal::get_test_tmp_dir() + "extern.bc";
    f.compile_to_bitcode(bitcode_file, {}, "extern");

    std::vector<uint8_t> bitcode;
    std::ifstream bitcode_stream(bitcode_file, std::ios::in | std::ios::binary);
    bitcode_stream.seekg(0, std::ios::end);
    bitcode.resize(bitcode_stream.tellg());
    bitcode_stream.seekg(0, std::ios::beg);
    bitcode_stream.read(reinterpret_cast<char *>(&bitcode[0]), bitcode.size());

    ExternalCode external_code =
        ExternalCode::bitcode_wrapper(get_jit_target_from_environment(), bitcode, "extern");

    Func f_extern;
    f_extern.define_extern("extern", { }, type_of<int32_t>(), 2);

    Func result;
    result(x, y) = f_extern(x, y);

    Module module = result.compile_to_module({}, "forty_two");

    module.append(external_code);

    auto forty_two = module.get_function_by_name("forty_two");

    Internal::JITModule jit_module(module, forty_two, {});

    auto main_function = (int (*)(halide_buffer_t *buf))jit_module.main_function();
    Buffer<int32_t> buf(16, 16);

    int ret_code = main_function(buf.raw_buffer());

    assert(ret_code == 0);
    for (int i = 0; i < 16; i++) {
        for (int j = 0; j < 16; j++) {
            assert(buf(i, j) == 42);
        }
    }

    printf("Success!\n");
    return 0;
}
<|endoftext|>


<commit_before>
#include <time.h>

#include "core/EpsilonManager.h"

#include <SFML/Window/Event.hpp>
#include <SFML/System/Clock.hpp>

#include "render/MeshFactory.h"
#include "math/Defines.h"

namespace epsilon
{
	EpsilonManager::EpsilonManager(void)
	{
	}

	EpsilonManager::~EpsilonManager(void)
	{
		//if ( sceneManager ) { delete sceneManager; }
		if ( uiManager ) { delete uiManager; }
		if ( renderManager ) { delete renderManager; }
		if ( scriptManager ) { delete scriptManager; }
	}

	void EpsilonManager::Setup(void)
	{
		Log("Initialising Epsilon Manager");

		scriptManager = new ScriptManager();
		scriptManager->Setup();

		renderManager = new RenderManager();
		renderManager->Setup();

		uiManager = new UIManager();
		uiManager->Setup();

		ConsoleWindow::Ptr consoleWindow = ConsoleWindow::Create();
		consoleWindow->Setup();
		uiManager->AddUIWindow(consoleWindow);

		//sceneManager = new SceneManager();
		sceneManager = &SceneManager::GetInstance();
		sceneManager->Setup();

		renderManager->SetSceneManager(sceneManager);
		renderManager->SetUIManager(uiManager);

		MeshTest();

		Log("Finished Setup");

		cycle.SetFrequency(100);

		camera = sceneManager->CurrentScene()->GetActiveCamera();
		camera->GetComponent<Transform>()->SetPosition(0.0f, 1.0f, -8.f);
		camera->LookAt(Vector3());
	}

	void EpsilonManager::MeshTest(void)
	{
		//Node::Ptr triangle2 = sceneManager->CurrentScene()->Root()->CreateChildNode();
		//triangle2->SetName("triangle");
		//triangle2->AddComponent(Renderer::Create());
		//triangle2->GetComponent<Renderer>()
		//		 ->SetMesh(MeshFactory::GenerateTriangle());
		//triangleTrans = triangle2->GetComponent<Transform>();
		//triangleTrans->SetPosition(0.f, 0.f, 0.f);
		//
		//// Add a sub child
		Node::Ptr tChild = sceneManager->CurrentScene()->Root()->CreateChildNode();
		tChild->SetName("sphere");
		tChild->AddComponent(Renderer::Create());
		tChild->GetComponent<Renderer>()
			  ->SetMesh(MeshFactory::GenerateSphere());
		tChild->GetComponent<Transform>()
			  ->SetPosition(1.0f, 1.0f, 0.0f);
		//
		Node::Ptr plane = sceneManager->CurrentScene()->Root()->CreateChildNode();
		plane->SetName("plane");

		plane->AddComponent(Renderer::Create());
		plane->GetComponent<Renderer>()
			  ->SetMesh(MeshFactory::GeneratePlane(4, 4));

		float angle = Math::DegreesToRadians(1.0f);
		plane->GetComponent<Transform>()
			  //->SetPosition(0.0f, -0.0f, 0.0f)
			  //.Yaw(angle)
			  ->SetScale(Vector3(2.0f));

		plane->AddComponent(scriptManager->CreateBehaviour("MyBehaviour.py"));

		// Create a Grid
		if ( true )
		{
			Node::Ptr grid = sceneManager->CurrentScene()->Root()->CreateChildNode();
			grid->SetName("grid");

			grid->AddComponent(Renderer::Create());
			grid->GetComponent<Renderer>()
				->SetMesh(MeshFactory::GenerateGrid(10, 1));
		}
	}

	//void EpsilonManager::OnUpdate(sf::Time el)
	void EpsilonManager::OnUpdate(float el)
	{
		scriptManager->Update(el);
		uiManager->OnUpdate(el);
		sceneManager->Cull();
		renderManager->Draw(el);
	}

	void EpsilonManager::Run(void)
	{
		// Run Loop

		// Handle events here until event manager is implemented.
		sf::Event event;
		//sf::Clock clock;
		clock_t lastTime = clock();
		float el = 0.0f;

		while ( renderManager->WindowOpen() )
		{
			//clock.restart();
			//sleep(Time(milliseconds(1)));

			while ( renderManager->PollEvent( event ) )
			{
				uiManager->ProcessEvent(event);

				if ( event.type == sf::Event::Closed )
				{
					renderManager->CloseWindow();
				}

				if ( event.type == sf::Event::KeyPressed )
				{

					if ( event.key.code == sf::Keyboard::Escape )
					{
						renderManager->CloseWindow();
					}
				}

				if ( event.type == sf::Event::KeyReleased )
				{
					Transform::Ptr camTrans = camera->GetComponent<Transform>();
					float amount = 1.0f;// * el;
					Vector3 trans;
					switch ( event.key.code )
					{
					case sf::Keyboard::A:
						trans.x = -amount;
						break;
					case sf::Keyboard::D:
						trans.x = amount;
						break;
					case sf::Keyboard::W:
						trans.z = amount;
						break;
					case sf::Keyboard::S:
						trans.z = -amount;
						break;

					case sf::Keyboard::R:
						trans.y = amount;
						break;
					case sf::Keyboard::F:
						trans.y = -amount;
						break;
					}
					camTrans->Translate(trans);
					//triangleTrans->Translate(trans);
					//aLog(std::to_string(triangleTrans->GetPosition().z));
					Vector3 la = camTrans->GetPosition() + (Vector3(0, 0, 5.0f));
					camera->LookAt(Vector3());
				}

			}
			//OnUpdate(clock.getElapsedTime());
			clock_t currTime = clock();
			el = (float)diffclock(currTime, lastTime) / 1000.0f;
			OnUpdate(el);
			lastTime = currTime;
		}
	}
}<commit_msg>M Fixed elapsed time calculation M Made changes as to how managers are handled as they become Singletons.<commit_after>
#include <time.h>

#include "core/EpsilonManager.h"

#include <SFML/Window/Event.hpp>
#include <SFML/System/Clock.hpp>

#include "render/MeshFactory.h"
#include "math/Defines.h"

namespace epsilon
{
	EpsilonManager::EpsilonManager(void)
	{
	}

	EpsilonManager::~EpsilonManager(void)
	{
		if ( uiManager ) { delete uiManager; }
		//if ( renderManager ) { delete renderManager; }
	}

	void EpsilonManager::Setup(void)
	{
		Log("Initialising Epsilon Manager");

		scriptManager = &ScriptManager::GetInstance();
		scriptManager->Setup();

		renderManager = &RenderManager::GetInstance();
		renderManager->Setup();

		uiManager = new UIManager();
		uiManager->Setup();

		ConsoleWindow::Ptr consoleWindow = ConsoleWindow::Create();
		consoleWindow->Setup();
		uiManager->AddUIWindow(consoleWindow);

		sceneManager = &SceneManager::GetInstance();
		sceneManager->Setup();

		renderManager->SetSceneManager(sceneManager);
		renderManager->SetUIManager(uiManager);

		MeshTest();

		Log("Finished Setup");

		cycle.SetFrequency(100);

		camera = sceneManager->CurrentScene()->GetActiveCamera();
		camera->GetComponent<Transform>()->SetPosition(0.0f, 1.0f, -8.f);
		camera->LookAt(Vector3());
	}

	void EpsilonManager::MeshTest(void)
	{
		//Node::Ptr triangle2 = sceneManager->CurrentScene()->Root()->CreateChildNode();
		//triangle2->SetName("triangle");
		//triangle2->AddComponent(Renderer::Create());
		//triangle2->GetComponent<Renderer>()
		//		 ->SetMesh(MeshFactory::GenerateTriangle());
		//triangleTrans = triangle2->GetComponent<Transform>();
		//triangleTrans->SetPosition(0.f, 0.f, 0.f);
		//
		//// Add a sub child
		Node::Ptr tChild = sceneManager->CurrentScene()->Root()->CreateChildNode();
		tChild->SetName("sphere");
		tChild->AddComponent(Renderer::Create());
		tChild->GetComponent<Renderer>()
			  ->SetMesh(MeshFactory::GenerateSphere());
		tChild->GetComponent<Transform>()
			  ->SetPosition(1.0f, 1.0f, 0.0f);
		tChild->AddComponent(scriptManager->CreateBehaviour("MyBehaviourClass.py"));
		//
		Node::Ptr plane = sceneManager->CurrentScene()->Root()->CreateChildNode();
		plane->SetName("plane");

		plane->AddComponent(Renderer::Create());
		plane->GetComponent<Renderer>()
			  ->SetMesh(MeshFactory::GeneratePlane(4, 4));

		Node::Ptr scriptsRoot = sceneManager->CurrentScene()->Root()->CreateChildNode();
		scriptsRoot->SetName("scriptRoot");

		Node::Ptr script2 = scriptsRoot->CreateChildNode();
		script2->AddComponent(scriptManager->CreateBehaviour("TestingFeatures.py"));

		// Create a Grid
		if ( true )
		{
			Node::Ptr grid = sceneManager->CurrentScene()->Root()->CreateChildNode();
			grid->SetName("grid");

			grid->AddComponent(Renderer::Create());
			grid->GetComponent<Renderer>()
				->SetMesh(MeshFactory::GenerateGrid(10, 1));
		}
	}

	//void EpsilonManager::OnUpdate(sf::Time el)
	void EpsilonManager::OnUpdate(float el)
	{
		scriptManager->Update(el);
		uiManager->OnUpdate(el);
		sceneManager->Cull();
		renderManager->Draw(el);
	}

	void EpsilonManager::Run(void)
	{
		// Run Loop

		// Handle events here until event manager is implemented.
		sf::Event event;
		sf::Clock clock;

		while ( renderManager->WindowOpen() )
		{
			while ( renderManager->PollEvent( event ) )
			{
				uiManager->ProcessEvent(event);

				if ( event.type == sf::Event::Closed )
				{
					renderManager->CloseWindow();
				}

				if ( event.type == sf::Event::KeyPressed )
				{

					if ( event.key.code == sf::Keyboard::Escape )
					{
						renderManager->CloseWindow();
					}
				}

				if ( event.type == sf::Event::KeyReleased )
				{
					Transform::Ptr camTrans = camera->GetComponent<Transform>();
					float amount = 1.0f;// * el;
					Vector3 trans;
					switch ( event.key.code )
					{
					case sf::Keyboard::A:
						trans.x = -amount;
						break;
					case sf::Keyboard::D:
						trans.x = amount;
						break;
					case sf::Keyboard::W:
						trans.z = amount;
						break;
					case sf::Keyboard::S:
						trans.z = -amount;
						break;

					case sf::Keyboard::R:
						trans.y = amount;
						break;
					case sf::Keyboard::F:
						trans.y = -amount;
						break;
					}
					camTrans->Translate(trans);
					Vector3 la = camTrans->GetPosition() + (Vector3(0, 0, 5.0f));
					camera->LookAt(Vector3());
				}

			}
			float el = clock.getElapsedTime().asMicroseconds() / 1000000.0f;
			// Restart timing for next sequence
			clock.restart();

			OnUpdate(el);

		}
	}
}<|endoftext|>


<commit_before>/* This code is subject to the terms of the Mozilla Public License, v.2.0. http://mozilla.org/MPL/2.0/. */
#include "unittest.h"

#include "FileStore.h"

#include "readstream.h"
#include "writestream.h"
#include "common/MyMemberId.h"
#include "file/File.h"
#include "serialize/str_join.h"

#include <boost/filesystem.hpp>
#include <memory>
#include <string>
#include <vector>
using std::shared_ptr;
using std::string;
using std::vector;

namespace {
	string _test_dir = "/tmp/turbo_fs_test";

	class DirectoryCleaner
	{
	public:
		~DirectoryCleaner()
		{
			boost::filesystem::remove_all(_test_dir);
		}

	protected:
	};

	class TestableFileStore : public FileStore
	{
	public:
		using FileStore::FileStore;

		using FileStore::bestVersion;
		using FileStore::dirpath;
		using FileStore::filepath;
	};

	void write_file(FileStore& store, const std::string& name, const std::string& contents)
	{
		writestream writer = store.write(name);
		assert( writer.good() );
		writer.write(contents.data(), contents.size());
		writer.close();
	}
}

TEST_CASE( "FileStoreTest/testPaths", "[unit]" )
{
	DirectoryCleaner cleaner;

	TestableFileStore store(_test_dir);
	assertEquals( "/tmp/turbo_fs_test/myfile",  store.dirpath("myfile") );
	assertEquals( "/tmp/turbo_fs_test/myfile/v1",  store.filepath("myfile", "v1") );
}

TEST_CASE( "FileStoreTest/testWrite", "[unit]" )
{
	MyMemberId("1");
	DirectoryCleaner cleaner;

	FileStore store(_test_dir);
	writestream writer = store.write("myfile");
	assertTrue( writer.good() );

	string bytes = "0123456789";
	assertEquals( 10, writer.write(bytes.data(), bytes.size()) );

	// won't be in the right place while the write is in progress.
	vector<string> versions = store.versions("myfile");
	assertEquals( "", turbo::str::join(versions) );

	// but if we ask for in progress writes, we should see it.
	versions = store.versions("myfile", true);
	assertEquals( "1,1:1", turbo::str::join(versions) );

	readstream reader = store.read("myfile", "1,1:1");
	assertFalse( reader.good() );

	// close/commit, and all is well.
	assertTrue( writer.close() );

	versions = store.versions("myfile");
	assertEquals( "1,1:1", turbo::str::join(versions) );

	reader = store.read("myfile", "1,1:1");
	assertTrue( reader.good() );
	assertEquals( 10, reader.size() );
}

TEST_CASE( "FileStoreTest/testReadNewest", "[unit]" )
{
	MyMemberId("1");
	DirectoryCleaner cleaner;

	FileStore store(_test_dir);

	{
		writestream writer = store.write("myfile");
		assertTrue( writer.good() );

		string bytes = "0123456789";
		assertEquals( 10, writer.write(bytes.data(), bytes.size()) );
		assertTrue( writer.close() );
	}
	{
		readstream reader = store.read("myfile");
		assertTrue( reader.good() );
		assertEquals( "1,1:1", reader.version() );
		assertEquals( 10, reader.size() );
	}

	{
		writestream writer = store.write("myfile");
		assertTrue( writer.good() );

		string bytes = "abcdef";
		assertEquals( 6, writer.write(bytes.data(), bytes.size()) );
		assertTrue( writer.close() );
	}
	{
		readstream reader = store.read("myfile");
		assertTrue( reader );
		assertEquals( "1,1:2", reader.version() );
		assertEquals( 6, reader.size() );
	}
}

TEST_CASE( "FileStoreTest/testReadAll", "[unit]" )
{
	MyMemberId("1");
	DirectoryCleaner cleaner;

	FileStore store(_test_dir);

	{
		VectorClock version;
		version.increment("foo");
		writestream writer = store.write("myfile", version.toString());
		assertTrue( writer.good() );

		string bytes = "0123456789";
		assertEquals( 10, writer.write(bytes.data(), bytes.size()) );
		assertTrue( writer.close() );
	}
	{
		readstream reader = store.read("myfile");
		assertTrue( reader.good() );
		assertEquals( "1,foo:1", reader.version() );
		assertEquals( 10, reader.size() );
	}

	{
		VectorClock version;
		version.increment("bar");
		writestream writer = store.write("myfile", version.toString());
		assertTrue( writer.good() );

		string bytes = "abcdef";
		assertEquals( 6, writer.write(bytes.data(), bytes.size()) );
		assertTrue( writer.close() );

		readstream reader = store.read("myfile", version.toString());
		assertTrue( reader );
		assertEquals( "1,bar:1", reader.version() );
		assertEquals( 6, reader.size() );
	}

	std::vector<readstream> readers = store.readAll("myfile");
	assertEquals( 2, readers.size() );

	assertTrue( readers[0] );
	assertEquals( "1,foo:1", readers[0].version() );
	assertEquals( 10, readers[0].size() );

	assertTrue( readers[1] );
	assertEquals( "1,bar:1", readers[1].version() );
	assertEquals( 6, readers[1].size() );
}

TEST_CASE( "FileStoreTest/testEnumerate", "[unit]" )
{
	MyMemberId("1");
	DirectoryCleaner cleaner;

	FileStore store(_test_dir);
	write_file(store, "foo", "0123456789");
	write_file(store, "bar", "abcde");
	write_file(store, "oof", "lmno");

	std::vector<string> files;
	auto fun = [&files] (const std::string& name) { files.push_back(name); return true; };
	store.enumerate(fun, 100);

	assertEquals( "foo oof bar", turbo::str::join(files) );
}

<commit_msg>sort plz k thx.<commit_after>/* This code is subject to the terms of the Mozilla Public License, v.2.0. http://mozilla.org/MPL/2.0/. */
#include "unittest.h"

#include "FileStore.h"

#include "readstream.h"
#include "writestream.h"
#include "common/MyMemberId.h"
#include "file/File.h"
#include "serialize/str_join.h"

#include <boost/filesystem.hpp>
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
using std::shared_ptr;
using std::string;
using std::vector;

namespace {
	string _test_dir = "/tmp/turbo_fs_test";

	class DirectoryCleaner
	{
	public:
		~DirectoryCleaner()
		{
			boost::filesystem::remove_all(_test_dir);
		}

	protected:
	};

	class TestableFileStore : public FileStore
	{
	public:
		using FileStore::FileStore;

		using FileStore::bestVersion;
		using FileStore::dirpath;
		using FileStore::filepath;
	};

	void write_file(FileStore& store, const std::string& name, const std::string& contents)
	{
		writestream writer = store.write(name);
		assert( writer.good() );
		writer.write(contents.data(), contents.size());
		writer.close();
	}
}

TEST_CASE( "FileStoreTest/testPaths", "[unit]" )
{
	DirectoryCleaner cleaner;

	TestableFileStore store(_test_dir);
	assertEquals( "/tmp/turbo_fs_test/myfile",  store.dirpath("myfile") );
	assertEquals( "/tmp/turbo_fs_test/myfile/v1",  store.filepath("myfile", "v1") );
}

TEST_CASE( "FileStoreTest/testWrite", "[unit]" )
{
	MyMemberId("1");
	DirectoryCleaner cleaner;

	FileStore store(_test_dir);
	writestream writer = store.write("myfile");
	assertTrue( writer.good() );

	string bytes = "0123456789";
	assertEquals( 10, writer.write(bytes.data(), bytes.size()) );

	// won't be in the right place while the write is in progress.
	vector<string> versions = store.versions("myfile");
	assertEquals( "", turbo::str::join(versions) );

	// but if we ask for in progress writes, we should see it.
	versions = store.versions("myfile", true);
	assertEquals( "1,1:1", turbo::str::join(versions) );

	readstream reader = store.read("myfile", "1,1:1");
	assertFalse( reader.good() );

	// close/commit, and all is well.
	assertTrue( writer.close() );

	versions = store.versions("myfile");
	assertEquals( "1,1:1", turbo::str::join(versions) );

	reader = store.read("myfile", "1,1:1");
	assertTrue( reader.good() );
	assertEquals( 10, reader.size() );
}

TEST_CASE( "FileStoreTest/testReadNewest", "[unit]" )
{
	MyMemberId("1");
	DirectoryCleaner cleaner;

	FileStore store(_test_dir);

	{
		writestream writer = store.write("myfile");
		assertTrue( writer.good() );

		string bytes = "0123456789";
		assertEquals( 10, writer.write(bytes.data(), bytes.size()) );
		assertTrue( writer.close() );
	}
	{
		readstream reader = store.read("myfile");
		assertTrue( reader.good() );
		assertEquals( "1,1:1", reader.version() );
		assertEquals( 10, reader.size() );
	}

	{
		writestream writer = store.write("myfile");
		assertTrue( writer.good() );

		string bytes = "abcdef";
		assertEquals( 6, writer.write(bytes.data(), bytes.size()) );
		assertTrue( writer.close() );
	}
	{
		readstream reader = store.read("myfile");
		assertTrue( reader );
		assertEquals( "1,1:2", reader.version() );
		assertEquals( 6, reader.size() );
	}
}

TEST_CASE( "FileStoreTest/testReadAll", "[unit]" )
{
	MyMemberId("1");
	DirectoryCleaner cleaner;

	FileStore store(_test_dir);

	{
		VectorClock version;
		version.increment("foo");
		writestream writer = store.write("myfile", version.toString());
		assertTrue( writer.good() );

		string bytes = "0123456789";
		assertEquals( 10, writer.write(bytes.data(), bytes.size()) );
		assertTrue( writer.close() );
	}
	{
		readstream reader = store.read("myfile");
		assertTrue( reader.good() );
		assertEquals( "1,foo:1", reader.version() );
		assertEquals( 10, reader.size() );
	}

	{
		VectorClock version;
		version.increment("bar");
		writestream writer = store.write("myfile", version.toString());
		assertTrue( writer.good() );

		string bytes = "abcdef";
		assertEquals( 6, writer.write(bytes.data(), bytes.size()) );
		assertTrue( writer.close() );

		readstream reader = store.read("myfile", version.toString());
		assertTrue( reader );
		assertEquals( "1,bar:1", reader.version() );
		assertEquals( 6, reader.size() );
	}

	std::vector<readstream> readers = store.readAll("myfile");
	assertEquals( 2, readers.size() );

	assertTrue( readers[0] );
	assertEquals( "1,foo:1", readers[0].version() );
	assertEquals( 10, readers[0].size() );

	assertTrue( readers[1] );
	assertEquals( "1,bar:1", readers[1].version() );
	assertEquals( 6, readers[1].size() );
}

TEST_CASE( "FileStoreTest/testEnumerate", "[unit]" )
{
	MyMemberId("1");
	DirectoryCleaner cleaner;

	FileStore store(_test_dir);
	write_file(store, "foo", "0123456789");
	write_file(store, "bar", "abcde");
	write_file(store, "oof", "lmno");

	std::vector<string> files;
	auto fun = [&files] (const std::string& name) { files.push_back(name); return true; };
	store.enumerate(fun, 100);

	std::sort(files.begin(), files.end());
	assertEquals( "bar foo oof", turbo::str::join(files) );
}

<|endoftext|>


<commit_before>#ifdef STAN_OPENCL
#include <stan/math/prim/mat/fun/typedefs.hpp>
#include <stan/math/opencl/copy.hpp>
#include <stan/math/opencl/add.hpp>
#include <gtest/gtest.h>
#include <algorithm>

TEST(MathMatrixGPU, add_v_exception_pass) {
  stan::math::vector_d d1, d2;

  d1.resize(3);
  d2.resize(3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(3, 1);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_v_exception_pass_zero) {
  stan::math::vector_d d1, d2;
  d1.resize(0);
  d2.resize(0);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(0, 1);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_v_exception_pass_invalid_arg) {
  stan::math::row_vector_d d1, d2;

  d1.resize(2);
  d2.resize(3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(3, 0);
  EXPECT_THROW(d33 = d11 + d22, std::invalid_argument);
}

TEST(MathMatrixGPU, add_rv_exception_pass) {
  stan::math::row_vector_d d1, d2;

  d1.resize(3);
  d2.resize(3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(1, 3);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_rv_exception_pass_zero) {
  stan::math::row_vector_d d1, d2;

  d1.resize(0);
  d2.resize(0);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(1, 0);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_rv_exception_fail_invalid_arg) {
  stan::math::row_vector_d d1, d2;

  d1.resize(2);
  d2.resize(3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(3, 1);
  EXPECT_THROW(d33 = d11 + d22, std::invalid_argument);
}

TEST(MathMatrixGPU, add_m_exception_pass_simple) {
  stan::math::matrix_d d1, d2;

  d1.resize(2, 3);
  d2.resize(2, 3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(2, 3);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_m_exception_pass_zero) {
  stan::math::matrix_d d1, d2;
  d1.resize(0, 0);
  d2.resize(0, 0);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(0, 0);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_m_exception_fail_invalid_arg) {
  stan::math::matrix_d d1, d2;
  d1.resize(2, 3);
  d2.resize(3, 3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(2, 3);
  EXPECT_THROW(d33 = d11 + d22, std::invalid_argument);
}

TEST(MathMatrixGPU, add_non_matching_sizes_exception) {
  stan::math::vector_d v1(2);
  v1 << 1, 2;
  stan::math::vector_d v2(3);
  v2 << 10, 100, 1000;

  stan::math::row_vector_d rv1(2);
  rv1 << 1, 2;
  stan::math::row_vector_d rv2(3);
  rv2 << 10, 100, 1000;

  stan::math::matrix_d m1(2, 3);
  m1 << 1, 2, 3, 4, 5, 6;
  stan::math::matrix_d m2(3, 2);
  m2 << 10, 100, 1000, 0, -10, -12;

  using stan::math::add;
  using stan::math::matrix_cl;
  matrix_cl v11(v1);
  matrix_cl v22(v2);
  matrix_cl v33(v1);
  matrix_cl rv11(rv1);
  matrix_cl rv22(rv2);
  matrix_cl rv33(rv1);
  matrix_cl m11(m1);
  matrix_cl m22(m2);
  matrix_cl m33(m1);

  EXPECT_THROW(v33 = v11 + v22, std::invalid_argument);
  EXPECT_THROW(rv33 = rv11 + rv22, std::invalid_argument);
  EXPECT_THROW(m33 = m11 + m22, std::invalid_argument);
}

TEST(MathMatrixGPU, add_value_check) {
  stan::math::vector_d v1(3);
  v1 << 1, 2, 3;
  stan::math::vector_d v2(3);
  v2 << 10, 100, 1000;
  stan::math::vector_d v3(3);

  stan::math::row_vector_d rv1(3);
  rv1 << 1, 2, 3;
  stan::math::row_vector_d rv2(3);
  rv2 << 10, 100, 1000;
  stan::math::row_vector_d rv3(3);

  stan::math::matrix_d m1(3, 3);
  m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;
  stan::math::matrix_d m2(3, 3);
  m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;
  stan::math::matrix_d m3(3, 3);

  using stan::math::add;
  using stan::math::matrix_cl;
  matrix_cl v11(v1);
  matrix_cl v22(v2);
  matrix_cl v33(3, 1);
  matrix_cl rv11(rv1);
  matrix_cl rv22(rv2);
  matrix_cl rv33(1, 3);
  matrix_cl m11(m1);
  matrix_cl m22(m2);
  matrix_cl m33(3, 3);

  EXPECT_NO_THROW(v33 = v11 + v22);
  EXPECT_NO_THROW(rv33 = rv11 + rv22);
  EXPECT_NO_THROW(m33 = m11 + m22);

  stan::math::copy(v3, v33);
  EXPECT_EQ(11, v3(0));
  EXPECT_EQ(102, v3(1));
  EXPECT_EQ(1003, v3(2));

  stan::math::copy(rv3, rv33);
  EXPECT_EQ(11, rv3(0));
  EXPECT_EQ(102, rv3(1));
  EXPECT_EQ(1003, rv3(2));

  stan::math::copy(m3, m33);
  EXPECT_EQ(11, m3(0, 0));
  EXPECT_EQ(102, m3(0, 1));
  EXPECT_EQ(1003, m3(0, 2));
  EXPECT_EQ(4, m3(1, 0));
  EXPECT_EQ(-5, m3(1, 1));
  EXPECT_EQ(-6, m3(1, 2));
  EXPECT_EQ(9, m3(2, 0));
  EXPECT_EQ(12, m3(2, 1));
  EXPECT_EQ(17, m3(2, 2));
}

TEST(MathMatrixGPU, add_batch) {
  // used to represent 5 matrices of size 10x10
  const int batch_size = 11;
  const int size = 13;
  stan::math::matrix_d a(size, size * batch_size);
  stan::math::matrix_d a_res(size, size);
  for (int k = 0; k < batch_size; k++) {
    for (int i = 0; i < size; i++)
      for (int j = 0; j < size; j++) {
        a(i, k * size + j) = k;
      }
  }
  stan::math::matrix_cl a_cl(a);
  stan::math::matrix_cl a_cl_res(size, size);
  stan::math::opencl_kernels::add_batch(cl::NDRange(size, size),
                                        a_cl_res, a_cl, size,
                                        size, batch_size);
  copy(a_res, a_cl_res);
  for (int k = 0; k < batch_size; k++) {
    for (int i = 0; i < size; i++)
      for (int j = 0; j < size; j++) {
        a(i, j) += a(i, k * size + j);
      }
  }
  for (int i = 0; i < size; i++) {
    for (int j = 0; j < size; j++) {
      EXPECT_EQ(a(i, j), a_res(i, j));
    }
  }
}
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.2-svn328729-1~exp1~20180509124008.99 (branches/release_50)<commit_after>#ifdef STAN_OPENCL
#include <stan/math/prim/mat/fun/typedefs.hpp>
#include <stan/math/opencl/copy.hpp>
#include <stan/math/opencl/add.hpp>
#include <gtest/gtest.h>
#include <algorithm>

TEST(MathMatrixGPU, add_v_exception_pass) {
  stan::math::vector_d d1, d2;

  d1.resize(3);
  d2.resize(3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(3, 1);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_v_exception_pass_zero) {
  stan::math::vector_d d1, d2;
  d1.resize(0);
  d2.resize(0);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(0, 1);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_v_exception_pass_invalid_arg) {
  stan::math::row_vector_d d1, d2;

  d1.resize(2);
  d2.resize(3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(3, 0);
  EXPECT_THROW(d33 = d11 + d22, std::invalid_argument);
}

TEST(MathMatrixGPU, add_rv_exception_pass) {
  stan::math::row_vector_d d1, d2;

  d1.resize(3);
  d2.resize(3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(1, 3);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_rv_exception_pass_zero) {
  stan::math::row_vector_d d1, d2;

  d1.resize(0);
  d2.resize(0);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(1, 0);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_rv_exception_fail_invalid_arg) {
  stan::math::row_vector_d d1, d2;

  d1.resize(2);
  d2.resize(3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(3, 1);
  EXPECT_THROW(d33 = d11 + d22, std::invalid_argument);
}

TEST(MathMatrixGPU, add_m_exception_pass_simple) {
  stan::math::matrix_d d1, d2;

  d1.resize(2, 3);
  d2.resize(2, 3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(2, 3);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_m_exception_pass_zero) {
  stan::math::matrix_d d1, d2;
  d1.resize(0, 0);
  d2.resize(0, 0);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(0, 0);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_m_exception_fail_invalid_arg) {
  stan::math::matrix_d d1, d2;
  d1.resize(2, 3);
  d2.resize(3, 3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(2, 3);
  EXPECT_THROW(d33 = d11 + d22, std::invalid_argument);
}

TEST(MathMatrixGPU, add_non_matching_sizes_exception) {
  stan::math::vector_d v1(2);
  v1 << 1, 2;
  stan::math::vector_d v2(3);
  v2 << 10, 100, 1000;

  stan::math::row_vector_d rv1(2);
  rv1 << 1, 2;
  stan::math::row_vector_d rv2(3);
  rv2 << 10, 100, 1000;

  stan::math::matrix_d m1(2, 3);
  m1 << 1, 2, 3, 4, 5, 6;
  stan::math::matrix_d m2(3, 2);
  m2 << 10, 100, 1000, 0, -10, -12;

  using stan::math::add;
  using stan::math::matrix_cl;
  matrix_cl v11(v1);
  matrix_cl v22(v2);
  matrix_cl v33(v1);
  matrix_cl rv11(rv1);
  matrix_cl rv22(rv2);
  matrix_cl rv33(rv1);
  matrix_cl m11(m1);
  matrix_cl m22(m2);
  matrix_cl m33(m1);

  EXPECT_THROW(v33 = v11 + v22, std::invalid_argument);
  EXPECT_THROW(rv33 = rv11 + rv22, std::invalid_argument);
  EXPECT_THROW(m33 = m11 + m22, std::invalid_argument);
}

TEST(MathMatrixGPU, add_value_check) {
  stan::math::vector_d v1(3);
  v1 << 1, 2, 3;
  stan::math::vector_d v2(3);
  v2 << 10, 100, 1000;
  stan::math::vector_d v3(3);

  stan::math::row_vector_d rv1(3);
  rv1 << 1, 2, 3;
  stan::math::row_vector_d rv2(3);
  rv2 << 10, 100, 1000;
  stan::math::row_vector_d rv3(3);

  stan::math::matrix_d m1(3, 3);
  m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;
  stan::math::matrix_d m2(3, 3);
  m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;
  stan::math::matrix_d m3(3, 3);

  using stan::math::add;
  using stan::math::matrix_cl;
  matrix_cl v11(v1);
  matrix_cl v22(v2);
  matrix_cl v33(3, 1);
  matrix_cl rv11(rv1);
  matrix_cl rv22(rv2);
  matrix_cl rv33(1, 3);
  matrix_cl m11(m1);
  matrix_cl m22(m2);
  matrix_cl m33(3, 3);

  EXPECT_NO_THROW(v33 = v11 + v22);
  EXPECT_NO_THROW(rv33 = rv11 + rv22);
  EXPECT_NO_THROW(m33 = m11 + m22);

  stan::math::copy(v3, v33);
  EXPECT_EQ(11, v3(0));
  EXPECT_EQ(102, v3(1));
  EXPECT_EQ(1003, v3(2));

  stan::math::copy(rv3, rv33);
  EXPECT_EQ(11, rv3(0));
  EXPECT_EQ(102, rv3(1));
  EXPECT_EQ(1003, rv3(2));

  stan::math::copy(m3, m33);
  EXPECT_EQ(11, m3(0, 0));
  EXPECT_EQ(102, m3(0, 1));
  EXPECT_EQ(1003, m3(0, 2));
  EXPECT_EQ(4, m3(1, 0));
  EXPECT_EQ(-5, m3(1, 1));
  EXPECT_EQ(-6, m3(1, 2));
  EXPECT_EQ(9, m3(2, 0));
  EXPECT_EQ(12, m3(2, 1));
  EXPECT_EQ(17, m3(2, 2));
}

TEST(MathMatrixGPU, add_batch) {
  // used to represent 5 matrices of size 10x10
  const int batch_size = 11;
  const int size = 13;
  stan::math::matrix_d a(size, size * batch_size);
  stan::math::matrix_d a_res(size, size);
  for (int k = 0; k < batch_size; k++) {
    for (int i = 0; i < size; i++)
      for (int j = 0; j < size; j++) {
        a(i, k * size + j) = k;
      }
  }
  stan::math::matrix_cl a_cl(a);
  stan::math::matrix_cl a_cl_res(size, size);
  stan::math::opencl_kernels::add_batch(cl::NDRange(size, size), a_cl_res, a_cl,
                                        size, size, batch_size);
  copy(a_res, a_cl_res);
  for (int k = 0; k < batch_size; k++) {
    for (int i = 0; i < size; i++)
      for (int j = 0; j < size; j++) {
        a(i, j) += a(i, k * size + j);
      }
  }
  for (int i = 0; i < size; i++) {
    for (int j = 0; j < size; j++) {
      EXPECT_EQ(a(i, j), a_res(i, j));
    }
  }
}
#endif
<|endoftext|>


<commit_before>// This file is part of the dune-pymor project:
//   https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_PYMOR_OPERATORS_AFFINE_HH
#define DUNE_PYMOR_OPERATORS_AFFINE_HH

#include <dune/pymor/common/exceptions.hh>
#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/parameters/functional.hh>
#include "interfaces.hh"

namespace Dune {
namespace Pymor {

class AffinelyDecomposedOperator
  : public OperatorInterface
{
public:
  AffinelyDecomposedOperator(const ParameterType& tt = ParameterType())
    : OperatorInterface(tt)
    , linear_(true)
    , size_(0)
    , hasAffinePart_(false)
    , dim_source_(0)
    , dim_range_(0)
    , type_source_("")
    , type_range_("")
  {}

  ~AffinelyDecomposedOperator()
  {
    if (hasAffinePart_)
      delete affinePart_;
    for (auto& element : components_)
      delete element;
    for (auto& element : coefficients_)
      delete element;
  }

  /**
   * \attention This class takes ownership of aff!
   */
  void register_component(const OperatorInterface* aff) throw (Exception::this_does_not_make_any_sense,
                                                               Exception::sizes_do_not_match,
                                                               Exception::types_are_not_compatible)
  {
    if (hasAffinePart_)
      DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense,
                       "do not call register_component(affinePart) if hasAffinePart() == true!");
    if (aff->parametric())
      DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense,
                       "the affinePart must not be parametric!");
    if (size_ == 0) {
      dim_source_ = aff->dim_source();
      dim_range_ = aff->dim_range();
      type_source_ = aff->type_source();
      type_range_ = aff->type_range();
      linear_ = aff->linear();
    } else {
      if (aff->dim_source() != dim_source_)
        DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                         "the dim_source of aff (" << aff->dim_source() << ") does not match the dim_source of this ("
                         << dim_source_ << ")!");
      if (aff->dim_range() != dim_range_)
        DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                         "the dim_range of aff (" << aff->dim_range() << ") does not match the dim_range of this ("
                         << dim_range_ << ")!");
      if (aff->type_source() != type_source_)
        DUNE_PYMOR_THROW(Exception::types_are_not_compatible,
                         "the type_source of aff (" << aff->type_source() << ") does not match the type_source of this ("
                         << type_source_ << ")!");
      if (aff->type_range() != type_range_)
        DUNE_PYMOR_THROW(Exception::types_are_not_compatible,
                         "the type_range of aff (" << aff->type_range() << ") does not match the type_range of this ("
                         << type_range_ << ")!");
      if (!aff->linear() != linear_)
        linear_ = false;
    }
    affinePart_ = aff;
    hasAffinePart_ = true;
  } // ... register_component(...)

  /**
   * \attention This class takes ownership of comp and coeff!
   */
  void register_component(const OperatorInterface* comp, const ParameterFunctional* coeff)
  {
    if (comp->parametric())
      DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense,
                       "a component must not be parametric!");
    if (size_ == 0 && !hasAffinePart_) {
      dim_source_ = comp->dim_source();
      dim_range_ = comp->dim_range();
      type_source_ = comp->type_source();
      type_range_ = comp->type_range();
      linear_ = comp->linear();
    } else {
    if (comp->dim_source() != dim_source_)
      DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                       "the dim_source of comp (" << comp->dim_source() << ") does not match the dim_source of this ("
                       << dim_source_ << ")!");
    if (comp->dim_range() != dim_range_)
      DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                       "the dim_range of comp (" << comp->dim_range() << ") does not match the dim_range of this ("
                       << dim_range_ << ")!");
    if (comp->type_source() != type_source_)
      DUNE_PYMOR_THROW(Exception::types_are_not_compatible,
                       "the type_source of comp (" << comp->type_source() << ") does not match the type_source of this ("
                       << type_source_ << ")!");
    if (comp->type_range() != type_range_)
      DUNE_PYMOR_THROW(Exception::types_are_not_compatible,
                       "the type_range of comp (" << comp->type_range() << ") does not match the type_range of this ("
                       << type_range_ << ")!");
    }
    if (!comp->linear() != linear_)
      linear_ = false;
    if (coeff->parameter_type() != Parametric::parameter_type())
      DUNE_PYMOR_THROW(Exception::wrong_parameter_type,
                       "a different parameter type for coeff (" << coeff->parameter_type() << ") and this ("
                       << Parametric::parameter_type() << ") is not yet supported!");
    components_.push_back(comp);
    coefficients_.push_back(coeff);
    ++size_;
  } // ... register_component(..., ...)

  unsigned int size() const
  {
    return size_;
  }

  /**
   * \attention The ownership of the component remains with this class!
   */
  OperatorInterface* component(const int ii) throw (Exception::requirements_not_met, Exception::index_out_of_range)
  {
    if (size() == 0)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call component(ii) if size() == 0!");
    if (ii < 0 || ii >= size())
      DUNE_PYMOR_THROW(Exception::index_out_of_range,
                       "the condition 0 < ii < size() is not fulfilled for ii = " << ii << "and size() = "
                       << size() << "!");
    return components_[ii];
  }

  /**
   * \attention The ownership of the component remains with this class!
   */
  const OperatorInterface* component(const int ii) const throw (Exception::requirements_not_met,
                                                                Exception::index_out_of_range)
  {
    if (size() == 0)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call component(ii) if size() == 0!");
    if (ii < 0 || ii >= size())
      DUNE_PYMOR_THROW(Exception::index_out_of_range,
                       "the condition 0 < ii < size() is not fulfilled for ii = " << ii << "and size() = "
                       << size() << "!");
    return components_[ii];
  }

  /**
   * \attention The ownership of the coefficient remains with this class!
   */
  const ParameterFunctional* coefficient(const int ii) const throw (Exception::requirements_not_met,
                                                                    Exception::index_out_of_range)
  {
    if (size() == 0)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call coefficient(ii) if size() == 0!");
    if (ii < 0 || ii >= size())
      DUNE_PYMOR_THROW(Exception::index_out_of_range,
                       "the condition 0 < ii < size() is not fulfilled for ii = " << ii << "and size() = "
                       << size() << "!");
    return coefficient[ii];

  }

  bool hasAffinePart() const
  {
    return hasAffinePart_;
  }

  /**
   * \attention The ownership of the affinePart remains with this class!
   */
  OperatorInterface* affinePart() throw(Exception::requirements_not_met)
  {
    if (!hasAffinePart())
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call affinePart() if hasAffinePart() == false!");
    return affinePart_;
  }

  /**
   * \attention The ownership of affinePart() remains in this class!
   */
  const OperatorInterface* affinePart(const int ii) const
  {
    if (!hasAffinePart())
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call affinePart() if hasAffinePart() == false!");
    return affinePart_;
  }

  virtual bool linear() const
  {
    return linear_;
  }

  virtual unsigned int dim_source() const
  {
    return dim_source_;
  }

  virtual unsigned int dim_range() const
  {
    return dim_range_;
  }

  virtual std::string type_source() const
  {
    return type_source_;
  }

  virtual std::string type_range() const
  {
    return type_range_;
  }

  virtual void apply(const LA::VectorInterface* source,
                     LA::VectorInterface* range,
                     const Parameter mu = Parameter()) const
    throw (Exception::types_are_not_compatible,
           Exception::you_have_to_implement_this,
           Exception::sizes_do_not_match,
           Exception::wrong_parameter_type,
           Exception::requirements_not_met)
  {
    if (source->dim() != dim_source())
      DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                       "the dim of source (" << source->dim() << ") does not match the dim of this ("
                       << dim_source() << ")!");
    if (range->dim() != dim_range())
      DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                       "the dim of range (" << range->dim() << ") does not match the dim of this ("
                       << dim_range() << ")!");
    if (mu.type() != Parametric::parameter_type())
      DUNE_PYMOR_THROW(Exception::wrong_parameter_type,
                       "the type of mu (" << mu.report() << "does not match the parameter_type of this ("
                       << Parametric::parameter_type() << ")!");
    if (size() == 0 && !hasAffinePart_)
      DUNE_THROW(Exception::requirements_not_met,
                 "do not call apply() if size() == 0 and hasAffinePart() == false!");
    if (hasAffinePart_) {
      affinePart_->apply(source, range);
      if (size_ > 0) {
        LA::VectorInterface* tmp = LA::createVector(range->type());
        assert(components_.size() == size_ && "This should not happen!");
        assert(coefficients_.size() == size_ && "This should not happen!");
        for (size_t ii = 0; ii < size_; ++ii) {
          components_[ii]->apply(source, tmp);
          tmp->scal(coefficients_[ii]->evaluate(mu));
          range->iadd(tmp);
        }
      }
    } else {
      assert(components_.size() == size_ && "This should not happen!");
      assert(coefficients_.size() == size_ && "This should not happen!");
      components_[0]->apply(source, range);
      range->scal(coefficients_[0]->evaluate());
      if (size_ > 1) {
        LA::VectorInterface* tmp = LA::createVector(range->type());
        for (size_t ii = 1; ii < size_; ++ii) {
          components_[ii]->apply(source, tmp);
          tmp->scal(coefficients_[ii]->evaluate(mu));
          range->iadd(tmp);
        }
      }
    }
  } // void apply(...)

private:
  bool linear_;
  unsigned int size_;
  bool hasAffinePart_;
  unsigned int dim_source_;
  unsigned int dim_range_;
  std::string type_source_;
  std::string type_range_;
  std::vector< const OperatorInterface* > components_;
  std::vector< const ParameterFunctional* > coefficients_;
  OperatorInterface* affinePart_;
}; // class AffinelyDecomposedOperator

} // namespace Pymor
} // namespace Dune

#endif // DUNE_PYMOR_OPERATORS_AFFINE_HH
<commit_msg>[operators.affine] renamed AffinelyDecomposedOperator -> Operators::AffinelyDecomposed<commit_after>// This file is part of the dune-pymor project:
//   https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_PYMOR_OPERATORS_AFFINE_HH
#define DUNE_PYMOR_OPERATORS_AFFINE_HH

#include <dune/pymor/common/exceptions.hh>
#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/parameters/functional.hh>
#include "interfaces.hh"

namespace Dune {
namespace Pymor {
namespace Operators {

class AffinelyDecomposed
  : public OperatorInterface
{
public:
  AffinelyDecomposed(const ParameterType& tt = ParameterType())
    : OperatorInterface(tt)
    , linear_(true)
    , size_(0)
    , hasAffinePart_(false)
    , dim_source_(0)
    , dim_range_(0)
    , type_source_("")
    , type_range_("")
  {}

  AffinelyDecomposed(OperatorInterface* aff, const ParameterType& tt = ParameterType())
    throw (Exception::requirements_not_met)
    : OperatorInterface(tt)
    , linear_(aff->linear())
    , size_(0)
    , hasAffinePart_(true)
    , dim_source_(aff->dim_source())
    , dim_range_(aff->dim_range())
    , type_source_(aff->type_source())
    , type_range_(aff->type_range())
    , affinePart_(aff)
  {
    if (affinePart_->parametric())
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "the affinePart must not be parametric!");
  }

  virtual ~AffinelyDecomposed()
  {
    if (hasAffinePart_)
      delete affinePart_;
    for (auto& element : components_)
      delete element;
    for (auto& element : coefficients_)
      delete element;
  }

  /**
   * \attention This class takes ownership of aff!
   */
  virtual void register_component(OperatorInterface* aff) throw (Exception::this_does_not_make_any_sense,
                                                                 Exception::sizes_do_not_match,
                                                                 Exception::types_are_not_compatible)
  {
    if (hasAffinePart_)
      DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense,
                       "do not call register_component(affinePart) if hasAffinePart() == true!");
    if (aff->parametric())
      DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense,
                       "the affinePart must not be parametric!");
    if (size_ == 0) {
      dim_source_ = aff->dim_source();
      dim_range_ = aff->dim_range();
      type_source_ = aff->type_source();
      type_range_ = aff->type_range();
      linear_ = aff->linear();
    } else {
      if (aff->dim_source() != dim_source_)
        DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                         "the dim_source of aff (" << aff->dim_source() << ") does not match the dim_source of this ("
                         << dim_source_ << ")!");
      if (aff->dim_range() != dim_range_)
        DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                         "the dim_range of aff (" << aff->dim_range() << ") does not match the dim_range of this ("
                         << dim_range_ << ")!");
      if (aff->type_source() != type_source_)
        DUNE_PYMOR_THROW(Exception::types_are_not_compatible,
                         "the type_source of aff (" << aff->type_source() << ") does not match the type_source of this ("
                         << type_source_ << ")!");
      if (aff->type_range() != type_range_)
        DUNE_PYMOR_THROW(Exception::types_are_not_compatible,
                         "the type_range of aff (" << aff->type_range() << ") does not match the type_range of this ("
                         << type_range_ << ")!");
      if (!aff->linear() != linear_)
        linear_ = false;
    }
    affinePart_ = aff;
    hasAffinePart_ = true;
  } // ... register_component(...)

  /**
   * \attention This class takes ownership of comp and coeff!
   */
  virtual void register_component(OperatorInterface* comp, const ParameterFunctional* coeff)
  {
    if (comp->parametric())
      DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense,
                       "a component must not be parametric!");
    if (size_ == 0 && !hasAffinePart_) {
      dim_source_ = comp->dim_source();
      dim_range_ = comp->dim_range();
      type_source_ = comp->type_source();
      type_range_ = comp->type_range();
      linear_ = comp->linear();
    } else {
    if (comp->dim_source() != dim_source_)
      DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                       "the dim_source of comp (" << comp->dim_source() << ") does not match the dim_source of this ("
                       << dim_source_ << ")!");
    if (comp->dim_range() != dim_range_)
      DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                       "the dim_range of comp (" << comp->dim_range() << ") does not match the dim_range of this ("
                       << dim_range_ << ")!");
    if (comp->type_source() != type_source_)
      DUNE_PYMOR_THROW(Exception::types_are_not_compatible,
                       "the type_source of comp (" << comp->type_source() << ") does not match the type_source of this ("
                       << type_source_ << ")!");
    if (comp->type_range() != type_range_)
      DUNE_PYMOR_THROW(Exception::types_are_not_compatible,
                       "the type_range of comp (" << comp->type_range() << ") does not match the type_range of this ("
                       << type_range_ << ")!");
    }
    if (!comp->linear() != linear_)
      linear_ = false;
    if (coeff->parameter_type() != Parametric::parameter_type())
      DUNE_PYMOR_THROW(Exception::wrong_parameter_type,
                       "a different parameter types for coeff (" << coeff->parameter_type() << ") and this ("
                       << Parametric::parameter_type() << ") is not yet supported!");
    components_.push_back(comp);
    coefficients_.push_back(coeff);
    ++size_;
  } // ... register_component(..., ...)

  virtual unsigned int size() const
  {
    return size_;
  }

  /**
   * \attention The ownership of the component remains with this class!
   */
  virtual OperatorInterface* component(const int ii) throw (Exception::requirements_not_met,
                                                            Exception::index_out_of_range)
  {
    if (size() == 0)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call component(ii) if size() == 0!");
    if (ii < 0 || ii >= size())
      DUNE_PYMOR_THROW(Exception::index_out_of_range,
                       "the condition 0 < ii < size() is not fulfilled for ii = " << ii << "and size() = "
                       << size() << "!");
    return components_[ii];
  }

  /**
   * \attention The ownership of the component remains with this class!
   */
  virtual const OperatorInterface* component(const int ii) const throw (Exception::requirements_not_met,
                                                                        Exception::index_out_of_range)
  {
    if (size() == 0)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call component(ii) if size() == 0!");
    if (ii < 0 || ii >= size())
      DUNE_PYMOR_THROW(Exception::index_out_of_range,
                       "the condition 0 < ii < size() is not fulfilled for ii = " << ii << "and size() = "
                       << size() << "!");
    return components_[ii];
  }

  /**
   * \attention The ownership of the coefficient remains with this class!
   */
  virtual const ParameterFunctional* coefficient(const int ii) const throw (Exception::requirements_not_met,
                                                                            Exception::index_out_of_range)
  {
    if (size() == 0)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call coefficient(ii) if size() == 0!");
    if (ii < 0 || ii >= size())
      DUNE_PYMOR_THROW(Exception::index_out_of_range,
                       "the condition 0 < ii < size() is not fulfilled for ii = " << ii << "and size() = "
                       << size() << "!");
    return coefficients_[ii];

  }

  virtual bool hasAffinePart() const
  {
    return hasAffinePart_;
  }

  /**
   * \attention The ownership of the affinePart remains with this class!
   */
  virtual OperatorInterface* affinePart() throw(Exception::requirements_not_met)
  {
    if (!hasAffinePart())
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call affinePart() if hasAffinePart() == false!");
    return affinePart_;
  }

  /**
   * \attention The ownership of affinePart() remains in this class!
   */
  virtual const OperatorInterface* affinePart() const throw(Exception::requirements_not_met)
  {
    if (!hasAffinePart())
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                       "do not call affinePart() if hasAffinePart() == false!");
    return affinePart_;
  }

  virtual bool linear() const
  {
    return linear_;
  }

  virtual unsigned int dim_source() const
  {
    return dim_source_;
  }

  virtual unsigned int dim_range() const
  {
    return dim_range_;
  }

  virtual std::string type_source() const
  {
    return type_source_;
  }

  virtual std::string type_range() const
  {
    return type_range_;
  }

  virtual void apply(const LA::VectorInterface* source,
                     LA::VectorInterface* range,
                     const Parameter mu = Parameter()) const
    throw (Exception::types_are_not_compatible,
           Exception::you_have_to_implement_this,
           Exception::sizes_do_not_match,
           Exception::wrong_parameter_type,
           Exception::requirements_not_met)
  {
    if (source->dim() != dim_source())
      DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                       "the dim of source (" << source->dim() << ") does not match the dim of this ("
                       << dim_source() << ")!");
    if (range->dim() != dim_range())
      DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
                       "the dim of range (" << range->dim() << ") does not match the dim of this ("
                       << dim_range() << ")!");
    if (mu.type() != Parametric::parameter_type())
      DUNE_PYMOR_THROW(Exception::wrong_parameter_type,
                       "the type of mu (" << mu.type() << "does not match the parameter_type of this ("
                       << Parametric::parameter_type() << ")!");
    if (size() == 0 && !hasAffinePart_)
      DUNE_PYMOR_THROW(Exception::requirements_not_met,
                 "do not call apply() if size() == 0 and hasAffinePart() == false!");
    if (hasAffinePart_) {
      affinePart_->apply(source, range);
      if (size_ > 0) {
        LA::VectorInterface* tmp = LA::createVector(range->type(), dim_range());
        assert(components_.size() == size_ && "This should not happen!");
        assert(coefficients_.size() == size_ && "This should not happen!");
        for (size_t ii = 0; ii < size_; ++ii) {
          components_[ii]->apply(source, tmp);
          tmp->scal(coefficients_[ii]->evaluate(mu));
          range->iadd(tmp);
        }
      }
    } else {
      assert(components_.size() == size_ && "This should not happen!");
      assert(coefficients_.size() == size_ && "This should not happen!");
      components_[0]->apply(source, range);
      range->scal(coefficients_[0]->evaluate(mu));
      if (size_ > 1) {
        LA::VectorInterface* tmp = LA::createVector(range->type(), dim_range());
        for (size_t ii = 1; ii < size_; ++ii) {
          components_[ii]->apply(source, tmp);
          tmp->scal(coefficients_[ii]->evaluate(mu));
          range->iadd(tmp);
        }
      }
    }
  } // void apply(...)

private:
  bool linear_;
  unsigned int size_;
  bool hasAffinePart_;
  unsigned int dim_source_;
  unsigned int dim_range_;
  std::string type_source_;
  std::string type_range_;
  std::vector< OperatorInterface* > components_;
  std::vector< const ParameterFunctional* > coefficients_;
  OperatorInterface* affinePart_;
}; // class AffinelyDecomposed

} // namespace Operators
} // namespace Pymor
} // namespace Dune

#endif // DUNE_PYMOR_OPERATORS_AFFINE_HH
<|endoftext|>


<commit_before>#include "GLIcoSphere.h"
#include "GL/glew.h"
#include <map>
#include <stdint.h>

GLIcoSphere::GLIcoSphere( const int entityID /*= 0*/ ) : IComponent(entityID) { }

unsigned int GLIcoSphere::VertBuf() const {
	return this->vertBuf;
}

void GLIcoSphere::VertBuf(unsigned int vb) {
	this->vertBuf = vb;
}

unsigned int GLIcoSphere::ColBuf() const {
	return this->colBuf;
}

void GLIcoSphere::ColBuf(unsigned int cb) {
	this->colBuf = cb;
}

unsigned int GLIcoSphere::Vao() const {
	return this->vao;
}

void GLIcoSphere::Vao(unsigned int v) {
	this->vao = v;
}

unsigned int GLIcoSphere::ElemBuf() const {
	return this->elemBuf;
}

void GLIcoSphere::ElemBuf(unsigned int eb) {
	this->elemBuf = eb;
}

GLIcoSphere* GLIcoSphere::Factory(int entityID) {
	GLIcoSphere* sphere = new GLIcoSphere(entityID);

	// We must create a vao and then store it in our GLIcoSphere.
	GLuint vaoID;
	glGenVertexArrays(1, &vaoID);
	glBindVertexArray(vaoID);

	// Create the verts to begin our deforming at.
	double t = (1.0 + glm::sqrt(5.0)) / 2.0;
	glm::vec2 coordPair = glm::normalize(glm::vec2(1,t));

	sphere->verts.push_back(vertex(-coordPair.r, coordPair.g, 0));
	sphere->verts.push_back(vertex(coordPair.r, coordPair.g, 0));
	sphere->verts.push_back(vertex(-coordPair.r, -coordPair.g, 0));
	sphere->verts.push_back(vertex(coordPair.r, -coordPair.g, 0));

	sphere->verts.push_back(vertex(0, -coordPair.r, coordPair.g));
	sphere->verts.push_back(vertex(0, coordPair.r, coordPair.g));
	sphere->verts.push_back(vertex(0, -coordPair.r, -coordPair.g));
	sphere->verts.push_back(vertex(0, coordPair.r, -coordPair.g));

	sphere->verts.push_back(vertex(coordPair.g, 0, -coordPair.r));
	sphere->verts.push_back(vertex(coordPair.g, 0, coordPair.r));
	sphere->verts.push_back(vertex(-coordPair.g, 0, -coordPair.r));
	sphere->verts.push_back(vertex(-coordPair.g, 0, coordPair.r));

	std::vector<face> faceLevelZero;

	faceLevelZero.push_back(face(0,11,5));
	faceLevelZero.push_back(face(0,5,1));
	faceLevelZero.push_back(face(0,1,7));
	faceLevelZero.push_back(face(0,7,10));
	faceLevelZero.push_back(face(0,10,11));

	faceLevelZero.push_back(face(1,5,9));
	faceLevelZero.push_back(face(5,11,4));
	faceLevelZero.push_back(face(11,10,2));
	faceLevelZero.push_back(face(10,7,6));
	faceLevelZero.push_back(face(7,1,8));

	faceLevelZero.push_back(face(3,9,4));
	faceLevelZero.push_back(face(3,4,2));
	faceLevelZero.push_back(face(3,2,6));
	faceLevelZero.push_back(face(3,6,8));
	faceLevelZero.push_back(face(3,8,9));

	faceLevelZero.push_back(face(4,9,5));
	faceLevelZero.push_back(face(2,4,11));
	faceLevelZero.push_back(face(6,2,10));
	faceLevelZero.push_back(face(8,6,7));
	faceLevelZero.push_back(face(9,8,1));

	sphere->Refine(sphere->verts, faceLevelZero, 2);
	sphere->faces = faceLevelZero;

	GLuint vertbuf;
	glGenBuffers(1, &vertbuf);
	glBindBuffer(GL_ARRAY_BUFFER, vertbuf);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertex) * sphere->verts.size(), &sphere->verts.front(), GL_STATIC_DRAW);
	GLint posLocation = glGetAttribLocation(GLIcoSphere::shader.GetProgram(), "in_Position");
	glVertexAttribPointer(posLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);
	glEnableVertexAttribArray(posLocation);

	GLuint elembuf;
	glGenBuffers(1, &elembuf);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elembuf);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(face) * sphere->faces.size(), &sphere->faces.front(), GL_STATIC_DRAW);

	static const GLfloat col[1];

	GLuint colorbuf;
	glGenBuffers(1, &colorbuf);
	glBindBuffer(GL_ARRAY_BUFFER, colorbuf);
	glBufferData(GL_ARRAY_BUFFER, sizeof(col), col, GL_STATIC_DRAW);
	GLint colLocation = glGetAttribLocation(GLIcoSphere::shader.GetProgram(), "in_Color");
	glVertexAttribPointer(colLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);
	glEnableVertexAttribArray(colLocation);
	glBindVertexArray(0);

	sphere->Vao(vaoID);
	sphere->VertBuf(vertbuf);
	sphere->ColBuf(colorbuf);
	sphere->ElemBuf(elembuf);

	return sphere;
}

void GLIcoSphere::LoadShader() {
	GLIcoSphere::shader.LoadFromFile(GL_VERTEX_SHADER, "..\\..\\shaders\\vert.shade");
	GLIcoSphere::shader.LoadFromFile(GL_FRAGMENT_SHADER, "..\\..\\shaders\\frag.shade");
	GLIcoSphere::shader.CreateAndLinkProgram();
}

glm::vec3 GetMidPoint(vertex v1, vertex v2) {
	return glm::normalize(glm::vec3((v1.x + v2.x) / 2.0, (v1.y + v2.y) / 2.0, (v1.z + v2.z) / 2.0));
}

void GLIcoSphere::Refine(std::vector<vertex> &verts, std::vector<face> &faces, int level) {
	std::map<int64_t, int> cache;

	// refine faces
	std::vector<face> newFaces = faces;
	for (int i = 0; i < level; ++i) {
		std::vector<face> tempFaces;
		for (auto faceitr = newFaces.begin(); faceitr != newFaces.end(); ++faceitr) {
			int a,b,c;

			{
				int v1 = (*faceitr).v1;
				int v2 = (*faceitr).v2;
				// first check if we have it already
				bool firstIsSmaller = v1 < v2;
				int64_t smallerIndex = firstIsSmaller ? v1 : v2;
				int64_t greaterIndex = firstIsSmaller ? v2 : v1;
				int64_t key = (smallerIndex << 32) + greaterIndex;

				if (cache.find(key) != cache.end()) {
					a = cache[key];
				} else {
					glm::vec3 middle = GetMidPoint(this->verts[v1], this->verts[v2]);

					verts.push_back(vertex(middle.x, middle.y, middle.z));

					a = cache[key] = this->verts.size() - 1;
				}
			}
			{
				int v1 = (*faceitr).v2;
				int v2 = (*faceitr).v3;
				// first check if we have it already
				bool firstIsSmaller = v1 < v2;
				int64_t smallerIndex = firstIsSmaller ? v1 : v2;
				int64_t greaterIndex = firstIsSmaller ? v2 : v1;
				int64_t key = (smallerIndex << 32) + greaterIndex;

				if (cache.find(key) != cache.end()) {
					b = cache[key];
				} else {
					glm::vec3 middle = GetMidPoint(this->verts[v1], this->verts[v2]);

					verts.push_back(vertex(middle.x, middle.y, middle.z));

					b = cache[key] = this->verts.size() - 1;
				}
			}
			{
				int v1 = (*faceitr).v3;
				int v2 = (*faceitr).v1;
				// first check if we have it already
				bool firstIsSmaller = v1 < v2;
				int64_t smallerIndex = firstIsSmaller ? v1 : v2;
				int64_t greaterIndex = firstIsSmaller ? v2 : v1;
				int64_t key = (smallerIndex << 32) + greaterIndex;

				if (cache.find(key) != cache.end()) {
					c = cache[key];
				} else {
					glm::vec3 middle = GetMidPoint(this->verts[v1], this->verts[v2]);

					verts.push_back(vertex(middle.x, middle.y, middle.z));

					c = cache[key] = this->verts.size() - 1;
				}
			}

			tempFaces.push_back(face((*faceitr).v1, a, c));
			tempFaces.push_back(face((*faceitr).v2, b, a));
			tempFaces.push_back(face((*faceitr).v3, c, b));
			tempFaces.push_back(face(a, b, c));
		}
		newFaces = tempFaces;
	}
	faces = newFaces;
}

GLSLShader GLIcoSphere::shader;
<commit_msg>Fix color buffer issues in GLIcoSpehre<commit_after>#include "GLIcoSphere.h"
#include "GL/glew.h"
#include <map>
#include <stdint.h>

GLIcoSphere::GLIcoSphere( const int entityID /*= 0*/ ) : IComponent(entityID) { }

unsigned int GLIcoSphere::VertBuf() const {
	return this->vertBuf;
}

void GLIcoSphere::VertBuf(unsigned int vb) {
	this->vertBuf = vb;
}

unsigned int GLIcoSphere::ColBuf() const {
	return this->colBuf;
}

void GLIcoSphere::ColBuf(unsigned int cb) {
	this->colBuf = cb;
}

unsigned int GLIcoSphere::Vao() const {
	return this->vao;
}

void GLIcoSphere::Vao(unsigned int v) {
	this->vao = v;
}

unsigned int GLIcoSphere::ElemBuf() const {
	return this->elemBuf;
}

void GLIcoSphere::ElemBuf(unsigned int eb) {
	this->elemBuf = eb;
}

GLIcoSphere* GLIcoSphere::Factory(int entityID) {
	GLIcoSphere* sphere = new GLIcoSphere(entityID);

	// We must create a vao and then store it in our GLIcoSphere.
	GLuint vaoID;
	glGenVertexArrays(1, &vaoID);
	glBindVertexArray(vaoID);

	// Create the verts to begin our deforming at.
	double t = (1.0 + glm::sqrt(5.0)) / 2.0;
	glm::vec2 coordPair = glm::normalize(glm::vec2(1,t));

	sphere->verts.push_back(vertex(-coordPair.r, coordPair.g, 0));
	sphere->verts.push_back(vertex(coordPair.r, coordPair.g, 0));
	sphere->verts.push_back(vertex(-coordPair.r, -coordPair.g, 0));
	sphere->verts.push_back(vertex(coordPair.r, -coordPair.g, 0));

	sphere->verts.push_back(vertex(0, -coordPair.r, coordPair.g));
	sphere->verts.push_back(vertex(0, coordPair.r, coordPair.g));
	sphere->verts.push_back(vertex(0, -coordPair.r, -coordPair.g));
	sphere->verts.push_back(vertex(0, coordPair.r, -coordPair.g));

	sphere->verts.push_back(vertex(coordPair.g, 0, -coordPair.r));
	sphere->verts.push_back(vertex(coordPair.g, 0, coordPair.r));
	sphere->verts.push_back(vertex(-coordPair.g, 0, -coordPair.r));
	sphere->verts.push_back(vertex(-coordPair.g, 0, coordPair.r));

	std::vector<face> faceLevelZero;

	faceLevelZero.push_back(face(0,11,5));
	faceLevelZero.push_back(face(0,5,1));
	faceLevelZero.push_back(face(0,1,7));
	faceLevelZero.push_back(face(0,7,10));
	faceLevelZero.push_back(face(0,10,11));

	faceLevelZero.push_back(face(1,5,9));
	faceLevelZero.push_back(face(5,11,4));
	faceLevelZero.push_back(face(11,10,2));
	faceLevelZero.push_back(face(10,7,6));
	faceLevelZero.push_back(face(7,1,8));

	faceLevelZero.push_back(face(3,9,4));
	faceLevelZero.push_back(face(3,4,2));
	faceLevelZero.push_back(face(3,2,6));
	faceLevelZero.push_back(face(3,6,8));
	faceLevelZero.push_back(face(3,8,9));

	faceLevelZero.push_back(face(4,9,5));
	faceLevelZero.push_back(face(2,4,11));
	faceLevelZero.push_back(face(6,2,10));
	faceLevelZero.push_back(face(8,6,7));
	faceLevelZero.push_back(face(9,8,1));

	sphere->Refine(sphere->verts, faceLevelZero, 2);
	sphere->faces = faceLevelZero;

	GLuint vertbuf;
	glGenBuffers(1, &vertbuf);
	glBindBuffer(GL_ARRAY_BUFFER, vertbuf);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertex) * sphere->verts.size(), &sphere->verts.front(), GL_STATIC_DRAW);
	GLint posLocation = glGetAttribLocation(GLIcoSphere::shader.GetProgram(), "in_Position");
	glVertexAttribPointer(posLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);
	glEnableVertexAttribArray(posLocation);

	GLuint elembuf;
	glGenBuffers(1, &elembuf);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elembuf);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(face) * sphere->faces.size(), &sphere->faces.front(), GL_STATIC_DRAW);

	/*static const GLfloat col[1];

	GLuint colorbuf;
	glGenBuffers(1, &colorbuf);
	glBindBuffer(GL_ARRAY_BUFFER, colorbuf);
	glBufferData(GL_ARRAY_BUFFER, sizeof(col), col, GL_STATIC_DRAW);
	GLint colLocation = glGetAttribLocation(GLIcoSphere::shader.GetProgram(), "in_Color");
	glVertexAttribPointer(colLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);
	glEnableVertexAttribArray(colLocation);*/
	glBindVertexArray(0);

	sphere->Vao(vaoID);
	sphere->VertBuf(vertbuf);
	//sphere->ColBuf(colorbuf);
	sphere->ElemBuf(elembuf);

	return sphere;
}

void GLIcoSphere::LoadShader() {
	GLIcoSphere::shader.LoadFromFile(GL_VERTEX_SHADER, "..\\..\\shaders\\vert.shade");
	GLIcoSphere::shader.LoadFromFile(GL_FRAGMENT_SHADER, "..\\..\\shaders\\frag.shade");
	GLIcoSphere::shader.CreateAndLinkProgram();
}

glm::vec3 GetMidPoint(vertex v1, vertex v2) {
	return glm::normalize(glm::vec3((v1.x + v2.x) / 2.0, (v1.y + v2.y) / 2.0, (v1.z + v2.z) / 2.0));
}

void GLIcoSphere::Refine(std::vector<vertex> &verts, std::vector<face> &faces, int level) {
	std::map<int64_t, int> cache;

	// refine faces
	std::vector<face> newFaces = faces;
	for (int i = 0; i < level; ++i) {
		std::vector<face> tempFaces;
		for (auto faceitr = newFaces.begin(); faceitr != newFaces.end(); ++faceitr) {
			int a,b,c;

			{
				int v1 = (*faceitr).v1;
				int v2 = (*faceitr).v2;
				// first check if we have it already
				bool firstIsSmaller = v1 < v2;
				int64_t smallerIndex = firstIsSmaller ? v1 : v2;
				int64_t greaterIndex = firstIsSmaller ? v2 : v1;
				int64_t key = (smallerIndex << 32) + greaterIndex;

				if (cache.find(key) != cache.end()) {
					a = cache[key];
				} else {
					glm::vec3 middle = GetMidPoint(this->verts[v1], this->verts[v2]);

					verts.push_back(vertex(middle.x, middle.y, middle.z));

					a = cache[key] = this->verts.size() - 1;
				}
			}
			{
				int v1 = (*faceitr).v2;
				int v2 = (*faceitr).v3;
				// first check if we have it already
				bool firstIsSmaller = v1 < v2;
				int64_t smallerIndex = firstIsSmaller ? v1 : v2;
				int64_t greaterIndex = firstIsSmaller ? v2 : v1;
				int64_t key = (smallerIndex << 32) + greaterIndex;

				if (cache.find(key) != cache.end()) {
					b = cache[key];
				} else {
					glm::vec3 middle = GetMidPoint(this->verts[v1], this->verts[v2]);

					verts.push_back(vertex(middle.x, middle.y, middle.z));

					b = cache[key] = this->verts.size() - 1;
				}
			}
			{
				int v1 = (*faceitr).v3;
				int v2 = (*faceitr).v1;
				// first check if we have it already
				bool firstIsSmaller = v1 < v2;
				int64_t smallerIndex = firstIsSmaller ? v1 : v2;
				int64_t greaterIndex = firstIsSmaller ? v2 : v1;
				int64_t key = (smallerIndex << 32) + greaterIndex;

				if (cache.find(key) != cache.end()) {
					c = cache[key];
				} else {
					glm::vec3 middle = GetMidPoint(this->verts[v1], this->verts[v2]);

					verts.push_back(vertex(middle.x, middle.y, middle.z));

					c = cache[key] = this->verts.size() - 1;
				}
			}

			tempFaces.push_back(face((*faceitr).v1, a, c));
			tempFaces.push_back(face((*faceitr).v2, b, a));
			tempFaces.push_back(face((*faceitr).v3, c, b));
			tempFaces.push_back(face(a, b, c));
		}
		newFaces = tempFaces;
	}
	faces = newFaces;
}

GLSLShader GLIcoSphere::shader;
<|endoftext|>