<commit_before>/*
 * optitrack.cpp
 *
 *  Created on: Aug 19, 2014
 *      Author: Bjorn Blissing
 */

#include "optitrack.h"
#include <iostream>

int OptiTrack::initialize()
{
	if (m_projectFile.empty()) {
		std::cerr << "Error: OptiTrack Project filename cannot be empty." << std::endl;
		return 1;
	}

	int errorCode = 0;
	// Try to initialize the OptiTrack system
	errorCode = checkResult(TT_Initialize());

	// Do an update to pick up any recently-arrived cameras.
	errorCode = checkResult(TT_Update());

	// Load project definition file
	errorCode = checkResult(TT_LoadProject(m_projectFile.c_str()));

	if (errorCode == NPRESULT_SUCCESS) {
		m_initialized = true;
		return 0;
	}

	return errorCode;
}

int OptiTrack::terminate() {
	int errorCode = checkResult(TT_Shutdown());

	errorCode = checkResult(TT_FinalCleanup());

	m_initialized = false;

	return 0;
}

size_t OptiTrack::getNumberOfCameras() const {
	if (m_initialized) {
		return TT_TrackableCount();
	}
	return 0;
}

size_t OptiTrack::getNumberOfRigidBodies() const {
	if (m_initialized) {
		return TT_TrackableCount();
	}
	return 0;
}

std::string OptiTrack::getNameOfCamera(int id) const {
	if (m_initialized) {
		if (id <= TT_TrackableCount()) {
			return std::string(TT_TrackableName(id));
		}
	}
	return std::string("");
}

std::string OptiTrack::getNameOfRigidBody(int id) const {
	if (m_initialized) {
		if (id <= TT_TrackableCount()) {
			return std::string(TT_TrackableName(id));
		}
	}
	return std::string("");
}

bool OptiTrack::getPosition(int rigidBodyId, float& x, float& y, float& z)
{
	if(m_initialized &&  TT_Update() == NPRESULT_SUCCESS ) {
		float qx, qy, qz, qw, yaw, pitch, roll;
		TT_TrackableLocation( rigidBodyId, &x, &y, &z, &qx, &qy, &qz, &qw, &yaw, &pitch, &roll);
		if( TT_IsTrackableTracked(rigidBodyId)) {
			return true;
		}
	}
	return false;
}

bool OptiTrack::getOrientation(int rigidBodyId, float& yaw, float& pitch, float& roll)
{
	if(m_initialized &&  TT_Update() == NPRESULT_SUCCESS ) {
		float x, y, z, qx, qy, qz, qw;
		TT_TrackableLocation( rigidBodyId, &x, &y, &z, &qx, &qy, &qz, &qw, &yaw, &pitch, &roll);
		if( TT_IsTrackableTracked(rigidBodyId)) {
			return true;
		}
	}
	return false;
}

bool OptiTrack::getOrientation(int rigidBodyId, float& qx, float& qy, float& qz, float& qw)
{
	if(m_initialized &&  TT_Update() == NPRESULT_SUCCESS ) {
		float x, y, z, yaw, pitch, roll;
		TT_TrackableLocation( rigidBodyId, &x, &y, &z, &qx, &qy, &qz, &qw, &yaw, &pitch, &roll);
		if( TT_IsTrackableTracked(rigidBodyId)) {
			return true;
		}
	}
	return false;
}

bool OptiTrack::getPositionAndOrientation(int rigidBodyId, float& x, float& y, float& z, float& yaw, float& pitch, float& roll)
{
	if(m_initialized &&  TT_Update() == NPRESULT_SUCCESS ) {
		float qx,qy,qz,qw;
		TT_TrackableLocation( rigidBodyId, &x, &y, &z, &qx, &qy, &qz, &qw, &yaw, &pitch, &roll);
		if( TT_IsTrackableTracked(rigidBodyId)) {
			return true;
		}
	}
	return false;
}

bool OptiTrack::getPositionAndOrientation(int rigidBodyId, float& x, float& y, float& z, float& qx, float& qy, float& qz, float& qw)
{
	if(m_initialized &&  TT_Update() == NPRESULT_SUCCESS ) {
		float yaw, pitch, roll;
		TT_TrackableLocation( rigidBodyId, &x, &y, &z, &qx, &qy, &qz, &qw, &yaw, &pitch, &roll);
		if( TT_IsTrackableTracked(rigidBodyId)) {
			return true;
		}
	}
	return false;
}

int OptiTrack::checkResult(int result) {
	if (result != NPRESULT_SUCCESS) {
		std::cerr << "Error: " << TT_GetResultString(result) << std::endl;
	}
	return result;
}
<commit_msg>Updated to support Motive 1.9<commit_after>/*
 * optitrack.cpp
 *
 *  Created on: Aug 19, 2014
 *      Author: Bjorn Blissing
 */

#include "optitrack.h"
#include <iostream>

int OptiTrack::initialize()
{
	if (m_projectFile.empty()) {
		std::cerr << "Error: OptiTrack Project filename cannot be empty." << std::endl;
		return 1;
	}

	int errorCode = 0;
	// Try to initialize the OptiTrack system
	errorCode = checkResult(TT_Initialize());
	// Do an update to pick up any recently-arrived cameras.
	errorCode = checkResult(TT_Update());
	// Load project definition file
	errorCode = checkResult(TT_LoadProject(m_projectFile.c_str()));

	if (errorCode == NPRESULT_SUCCESS) {
		m_initialized = true;
		return 0;
	}

	return errorCode;
}

int OptiTrack::terminate()
{
	int errorCode = checkResult(TT_Shutdown());
	m_initialized = false;
	return errorCode;
}

size_t OptiTrack::getNumberOfCameras() const
{
	if (m_initialized) {
		return TT_CameraCount();
	}

	return 0;
}

size_t OptiTrack::getNumberOfRigidBodies() const
{
	if (m_initialized) {
		return TT_RigidBodyCount();
	}

	return 0;
}

std::string OptiTrack::getNameOfCamera(int id) const
{
	if (m_initialized) {
		if (id <= TT_CameraCount()) {
			return std::string(TT_CameraName(id));
		}
	}

	return std::string("");
}

std::string OptiTrack::getNameOfRigidBody(int id) const
{
	if (m_initialized) {
		if (id <= TT_RigidBodyCount()) {
			return std::string(TT_RigidBodyName(id));
		}
	}

	return std::string("");
}

bool OptiTrack::getPosition(int rigidBodyId, float& x, float& y, float& z)
{
	if (m_initialized &&  TT_Update() == NPRESULT_SUCCESS ) {
		float qx, qy, qz, qw, yaw, pitch, roll;
		TT_RigidBodyLocation( rigidBodyId, &x, &y, &z, &qx, &qy, &qz, &qw, &yaw, &pitch, &roll);

		if ( TT_IsRigidBodyTracked(rigidBodyId)) {
			return true;
		}
	}

	return false;
}

bool OptiTrack::getOrientation(int rigidBodyId, float& yaw, float& pitch, float& roll)
{
	if (m_initialized &&  TT_Update() == NPRESULT_SUCCESS ) {
		float x, y, z, qx, qy, qz, qw;
		TT_RigidBodyLocation( rigidBodyId, &x, &y, &z, &qx, &qy, &qz, &qw, &yaw, &pitch, &roll);

		if ( TT_IsRigidBodyTracked(rigidBodyId)) {
			return true;
		}
	}

	return false;
}

bool OptiTrack::getOrientation(int rigidBodyId, float& qx, float& qy, float& qz, float& qw)
{
	if (m_initialized &&  TT_Update() == NPRESULT_SUCCESS ) {
		float x, y, z, yaw, pitch, roll;
		TT_RigidBodyLocation( rigidBodyId, &x, &y, &z, &qx, &qy, &qz, &qw, &yaw, &pitch, &roll);

		if ( TT_IsRigidBodyTracked(rigidBodyId)) {
			return true;
		}
	}

	return false;
}

bool OptiTrack::getPositionAndOrientation(int rigidBodyId, float& x, float& y, float& z, float& yaw, float& pitch, float& roll)
{
	if (m_initialized &&  TT_Update() == NPRESULT_SUCCESS ) {
		float qx,qy,qz,qw;
		TT_RigidBodyLocation( rigidBodyId, &x, &y, &z, &qx, &qy, &qz, &qw, &yaw, &pitch, &roll);

		if ( TT_IsRigidBodyTracked(rigidBodyId)) {
			return true;
		}
	}

	return false;
}

bool OptiTrack::getPositionAndOrientation(int rigidBodyId, float& x, float& y, float& z, float& qx, float& qy, float& qz, float& qw)
{
	if (m_initialized &&  TT_Update() == NPRESULT_SUCCESS ) {
		float yaw, pitch, roll;
		TT_RigidBodyLocation( rigidBodyId, &x, &y, &z, &qx, &qy, &qz, &qw, &yaw, &pitch, &roll);

		if ( TT_IsRigidBodyTracked(rigidBodyId)) {
			return true;
		}
	}

	return false;
}

int OptiTrack::checkResult(int result)
{
	if (result != NPRESULT_SUCCESS) {
		std::cerr << "Error: " << TT_GetResultString(result) << std::endl;
	}

	return result;
}
<|endoftext|>


<commit_before>// This file is part of the GLERI project
//
// Copyright (c) 2012 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.

#include "twin.h"

//{{{ Vertex data ------------------------------------------------------
namespace {

static const CTestWindow::coord_t _vdata1[] = {
    0,0, 0,479, 639,479, 639,0,
    50,50, 50,300, 150,300, 150,50,
    100,100, 200,200, 300,200, 300,300,
    250,250, 250,400, 350,250, 500,450,
    250,50, 300,100, 300,50, 350,75,
    0,0, 0,-1, 1,0, 1,-1
};
enum {
    vb_WindowBorderOffset,
    vb_WindowBorderSize = 4,	// In vertices
    vb_PurpleQuadOffset = vb_WindowBorderOffset+vb_WindowBorderSize,
    vb_PurpleQuadSize = 4,
    vb_BrokenLineOffset = vb_PurpleQuadOffset+vb_PurpleQuadSize,
    vb_BrokenLineSize = 4,
    vb_TransparentStripOffset = vb_BrokenLineOffset+vb_BrokenLineSize,
    vb_TransparentStripSize = 4,
    vb_SkewQuadOffset = vb_TransparentStripOffset+vb_TransparentStripSize,
    vb_SkewQuadSize = 4,
    vb_FanOverlayOffset = vb_SkewQuadOffset + vb_SkewQuadSize,
    vb_FanOverlaySize = 4
};
enum {
    walk_SpriteW = 64,
    walk_SpriteH = walk_SpriteW,
    walk_StripUp = walk_SpriteH*0,
    walk_StripLeft = walk_SpriteH*1,
    walk_StripDown = walk_SpriteH*2,
    walk_StripRight = walk_SpriteH*3,
    walk_StripLength = walk_SpriteW*9
};

//}}}-------------------------------------------------------------------
//{{{ Gradient shader

static const char c_gradShader_v[] =
"#version 330 core\n"
"\n"
"uniform vec4 Color;\n"
"layout(location=0) in vec2 Vertex;\n"
"invariant out vec4 gl_Position;\n"
"invariant out vec4 f_color;\n"
"\n"
"void main() {\n"
"    gl_Position = vec4(Vertex,1,1);\n"
"    f_color = Color*vec4(1,1,1,gl_Position.x*-gl_Position.y);\n"
"}";

static const char c_gradShader_f[] =
"#version 330 core\n"
"\n"
"invariant in vec4 f_color;\n"
"invariant out vec4 gl_FragColor;\n"
"\n"
"void main() {\n"
"    gl_FragColor = f_color;\n"
"}";

} // namespace
//}}}-------------------------------------------------------------------

void CTestWindow::OnInit (void)
{
    CWindow::OnInit();
    Open (640, 480);
    printf ("Initializing test window\n");
    _vbuf = BufferData (_vdata1, sizeof(_vdata1));
    _walk = LoadTexture ("test/princess.png");
    _gradShader = LoadShader (c_gradShader_v, c_gradShader_f);
}

void CTestWindow::OnResize (dim_t w, dim_t h)
{
    CWindow::OnResize (w,h);
    printf ("Test window OnResize\n");
    const coord_t sw = w-1, sh = h-1;
    const coord_t _vdata1[] = { sh, sw,sh, sw };
    BufferSubData (_vbuf, _vdata1, sizeof(_vdata1), 3*sizeof(int16_t));
    _wx = 0; _wy = (h-walk_SpriteH)/2;
    _wsx = 0*walk_SpriteW; _wsy = walk_StripRight;
    WaitForTime (_wtimer = NowMS()+1000/30);
}

void CTestWindow::OnKey (key_t key)
{
    CWindow::OnKey (key);
    if (key == 'q' || key == Key::Escape) {
	printf ("Event received, quitting\n");
	CApp::Instance().Quit();
    } else if (key == Key::Up) {
	if (--_wy < 0)
	    _wy = 0;
	_wsy = walk_StripUp;
	_wsx += walk_SpriteW;
	if (_wsx >= walk_StripLength)
	    _wsx = 0;
	Draw();
    } else if (key == Key::Down) {
	if (++_wy > Info().h-walk_SpriteH)
	    _wy = Info().h-walk_SpriteH;
	_wsy = walk_StripDown;
	_wsx += walk_SpriteW;
	if (_wsx >= walk_StripLength)
	    _wsx = 0;
	Draw();
    } else if (key == Key::Left) {
	if (--_wx < 0)
	    _wx = 0;
	_wsy = walk_StripLeft;
	_wsx += walk_SpriteW;
	if (_wsx >= walk_StripLength)
	    _wsx = 0;
	Draw();
    } else if (key == Key::Right) {
	if (++_wx > Info().w-walk_SpriteW)
	    _wx = Info().w-walk_SpriteW;
	_wsy = walk_StripRight;
	_wsx += walk_SpriteW;
	if (_wsx >= walk_StripLength)
	    _wsx = 0;
	Draw();
    }
}

void CTestWindow::OnTimer (uint64_t tms)
{
    CWindow::OnTimer (tms);
    if (tms != _wtimer)
	return;

    if (++_wx > Info().w-walk_SpriteW)
	_wx = Info().w-walk_SpriteW;
    _wsy = walk_StripRight;
    _wsx += walk_SpriteW;
    if (_wsx >= walk_StripLength)
	_wsx = 0;
    Draw();

    WaitForTime (_wtimer += 1000/30);
}

ONDRAWIMPL(CTestWindow)::OnDraw (Drw& drw) const
{
    CWindow::OnDraw (drw);

    drw.Clear (RGB(0,0,64));

    drw.VertexPointer (_vbuf);

    drw.Color (0,255,255);
    drw.LineLoop (vb_WindowBorderOffset, vb_WindowBorderSize);
    drw.Color (255,255,255);
    drw.LineStrip (vb_BrokenLineOffset, vb_BrokenLineSize);

    drw.Image (200, 75, _walk);
    drw.Offset (_wx, _wy);
    drw.Sprite (0, 0, _walk, _wsx, _wsy, walk_SpriteW, walk_SpriteH);
    drw.Offset (0, 0);

    drw.Color (ARGB(0xc0804040));
    drw.TriangleStrip (vb_TransparentStripOffset, vb_TransparentStripSize);
    drw.Color (128,170,170);
    drw.TriangleStrip (vb_SkewQuadOffset, vb_SkewQuadSize);

    drw.Color (0,240,255,128);
    drw.Text (300, 250, "Hello world from OpenGL!");

    drw.Color (255,255,255);
    drw.Text (300, 420, "A quick brown fox jumps over the lazy dog");
    uint32_t lrt = LastRenderTimeNS();
    drw.Textf (10,10, "FPS %u", 1000000000/(lrt ? lrt : 1));

    drw.Color (128,90,150,220);
    drw.TriangleFan (vb_PurpleQuadOffset, vb_PurpleQuadSize);

    drw.Shader (_gradShader);
    drw.Color (0,128,128);
    drw.TriangleStrip (vb_FanOverlayOffset, vb_FanOverlaySize);
    drw.DefaultShader();
}
<commit_msg>Have timer follow vsync closer<commit_after>// This file is part of the GLERI project
//
// Copyright (c) 2012 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.

#include "twin.h"

//{{{ Vertex data ------------------------------------------------------
namespace {

static const CTestWindow::coord_t _vdata1[] = {
    0,0, 0,479, 639,479, 639,0,
    50,50, 50,300, 150,300, 150,50,
    100,100, 200,200, 300,200, 300,300,
    250,250, 250,400, 350,250, 500,450,
    250,50, 300,100, 300,50, 350,75,
    0,0, 0,-1, 1,0, 1,-1
};
enum {
    vb_WindowBorderOffset,
    vb_WindowBorderSize = 4,	// In vertices
    vb_PurpleQuadOffset = vb_WindowBorderOffset+vb_WindowBorderSize,
    vb_PurpleQuadSize = 4,
    vb_BrokenLineOffset = vb_PurpleQuadOffset+vb_PurpleQuadSize,
    vb_BrokenLineSize = 4,
    vb_TransparentStripOffset = vb_BrokenLineOffset+vb_BrokenLineSize,
    vb_TransparentStripSize = 4,
    vb_SkewQuadOffset = vb_TransparentStripOffset+vb_TransparentStripSize,
    vb_SkewQuadSize = 4,
    vb_FanOverlayOffset = vb_SkewQuadOffset + vb_SkewQuadSize,
    vb_FanOverlaySize = 4
};
enum {
    walk_SpriteW = 64,
    walk_SpriteH = walk_SpriteW,
    walk_StripUp = walk_SpriteH*0,
    walk_StripLeft = walk_SpriteH*1,
    walk_StripDown = walk_SpriteH*2,
    walk_StripRight = walk_SpriteH*3,
    walk_StripLength = walk_SpriteW*9
};

//}}}-------------------------------------------------------------------
//{{{ Gradient shader

static const char c_gradShader_v[] =
"#version 330 core\n"
"\n"
"uniform vec4 Color;\n"
"layout(location=0) in vec2 Vertex;\n"
"invariant out vec4 gl_Position;\n"
"invariant out vec4 f_color;\n"
"\n"
"void main() {\n"
"    gl_Position = vec4(Vertex,1,1);\n"
"    f_color = Color*vec4(1,1,1,gl_Position.x*-gl_Position.y);\n"
"}";

static const char c_gradShader_f[] =
"#version 330 core\n"
"\n"
"invariant in vec4 f_color;\n"
"invariant out vec4 gl_FragColor;\n"
"\n"
"void main() {\n"
"    gl_FragColor = f_color;\n"
"}";

} // namespace
//}}}-------------------------------------------------------------------

void CTestWindow::OnInit (void)
{
    CWindow::OnInit();
    Open (640, 480);
    printf ("Initializing test window\n");
    _vbuf = BufferData (_vdata1, sizeof(_vdata1));
    _walk = LoadTexture ("test/princess.png");
    _gradShader = LoadShader (c_gradShader_v, c_gradShader_f);
}

void CTestWindow::OnResize (dim_t w, dim_t h)
{
    CWindow::OnResize (w,h);
    printf ("Test window OnResize\n");
    const coord_t sw = w-1, sh = h-1;
    const coord_t _vdata1[] = { sh, sw,sh, sw };
    BufferSubData (_vbuf, _vdata1, sizeof(_vdata1), 3*sizeof(int16_t));
    _wx = 0; _wy = (h-walk_SpriteH)/2;
    _wsx = 0*walk_SpriteW; _wsy = walk_StripRight;
    WaitForTime (_wtimer = NowMS()+1000/30);
}

void CTestWindow::OnKey (key_t key)
{
    CWindow::OnKey (key);
    if (key == 'q' || key == Key::Escape) {
	printf ("Event received, quitting\n");
	CApp::Instance().Quit();
    } else if (key == Key::Up) {
	if (--_wy < 0)
	    _wy = 0;
	_wsy = walk_StripUp;
	_wsx += walk_SpriteW;
	if (_wsx >= walk_StripLength)
	    _wsx = 0;
	Draw();
    } else if (key == Key::Down) {
	if (++_wy > Info().h-walk_SpriteH)
	    _wy = Info().h-walk_SpriteH;
	_wsy = walk_StripDown;
	_wsx += walk_SpriteW;
	if (_wsx >= walk_StripLength)
	    _wsx = 0;
	Draw();
    } else if (key == Key::Left) {
	if (--_wx < 0)
	    _wx = 0;
	_wsy = walk_StripLeft;
	_wsx += walk_SpriteW;
	if (_wsx >= walk_StripLength)
	    _wsx = 0;
	Draw();
    } else if (key == Key::Right) {
	if (++_wx > Info().w-walk_SpriteW)
	    _wx = Info().w-walk_SpriteW;
	_wsy = walk_StripRight;
	_wsx += walk_SpriteW;
	if (_wsx >= walk_StripLength)
	    _wsx = 0;
	Draw();
    }
}

void CTestWindow::OnTimer (uint64_t tms)
{
    CWindow::OnTimer (tms);
    if (tms != _wtimer)
	return;

    if (++_wx >= Info().w)
	_wx = -walk_SpriteW;
    _wsy = walk_StripRight;
    _wsx += walk_SpriteW;
    if (_wsx >= walk_StripLength)
	_wsx = 0;
    Draw();

    uint32_t wt = 1000/60;
    if (RefreshTimeNS())
	wt = RefreshTimeNS()/1000000;
    WaitForTime (_wtimer += wt);
}

ONDRAWIMPL(CTestWindow)::OnDraw (Drw& drw) const
{
    CWindow::OnDraw (drw);

    drw.Clear (RGB(0,0,64));

    drw.VertexPointer (_vbuf);

    drw.Color (0,255,255);
    drw.LineLoop (vb_WindowBorderOffset, vb_WindowBorderSize);
    drw.Color (255,255,255);
    drw.LineStrip (vb_BrokenLineOffset, vb_BrokenLineSize);

    drw.Image (200, 75, _walk);
    drw.Offset (_wx, _wy);
    drw.Sprite (0, 0, _walk, _wsx, _wsy, walk_SpriteW, walk_SpriteH);
    drw.Offset (0, 0);

    drw.Color (ARGB(0xc0804040));
    drw.TriangleStrip (vb_TransparentStripOffset, vb_TransparentStripSize);
    drw.Color (128,170,170);
    drw.TriangleStrip (vb_SkewQuadOffset, vb_SkewQuadSize);

    drw.Color (0,240,255,128);
    drw.Text (300, 250, "Hello world from OpenGL!");

    drw.Color (255,255,255);
    drw.Text (300, 420, "A quick brown fox jumps over the lazy dog");
    uint32_t lrt = LastRenderTimeNS();
    uint32_t lft = RefreshTimeNS();
    drw.Textf (10,10, "FPS %u, VSync %u", 1000000000/(lrt?lrt:1), 1000000000/(lft?lft:1));

    drw.Color (128,90,150,220);
    drw.TriangleFan (vb_PurpleQuadOffset, vb_PurpleQuadSize);

    drw.Shader (_gradShader);
    drw.Color (0,128,128);
    drw.TriangleStrip (vb_FanOverlayOffset, vb_FanOverlaySize);
    drw.DefaultShader();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <iomanip>
#include "Usb/SetupPacket.hpp"
#include "Usb/Endpoint.hpp"
#include "USB/Packet.hpp"
#include "USB/Device.hpp"
#include "USB/Memory.hpp"

using PacketT = Kvasir::Usb::Packet <Kvasir::Usb::CompactPacket::ImplType>;
using Alloc = Kvasir::Usb::CompactPacket::Allocator<PacketT,12>;
using Device = Kvasir::Usb::Device<Alloc, Kvasir::Usb::CompactPacket::Queue<PacketT>, Kvasir::Usb::CompactPacket::Transfer<PacketT, Alloc>>;

int usbTest()
{
	Alloc::initialize();
	{
		auto packet = Alloc::allocate();
		//set address
		for (auto d : { 0, 5, 5, 0, 0, 0, 0, 0 }) {
			packet.pushBack(d);
		}
		auto cmd = Device::onSetupPacket(std::move(packet));
		if (cmd.type_ != Device::HalCommand::Type::setAddress) {
			return 1;
		}
		if (cmd.packet_.getSize() != 0) {
			return 1;
		}
		auto cmd2 = Device::onControlIn(std::move(cmd.packet_));
		if (cmd2.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd2.packet_) {
			return 1;
		}
	}
	{
		//GetDevice descriptor
		auto packet = Alloc::allocate();
		for (auto d : { 0x80, 6, 0, 1, 0, 0, 8, 0 }) {
			packet.pushBack(d);
		}
		auto cmd = Device::onSetupPacket(std::move(packet));
		if (cmd.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd.packet_.getSize() != 8) {
			return 1;
		}
		auto cmd2 = Device::onControlIn(std::move(cmd.packet_));
		if (cmd2.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd2.packet_) {
			return 1;
		}
	}
	{
		//GetDevice descriptor
		auto packet = Alloc::allocate();
		for (auto d : { 0x80, 0x06, 0x00, 0x01, 0x00, 0x00, 0x12, 0x00 }) {
			packet.pushBack(d);
		}
		auto cmd = Device::onSetupPacket(std::move(packet));
		if (cmd.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd.packet_.getSize() != 18) {
			return 1;
		}
		auto cmd2 = Device::onControlIn(std::move(cmd.packet_));
		if (cmd2.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd2.packet_) {
			return 1;
		}
	}
	{
		//Get Configuration descriptor
		auto packet = Alloc::allocate();
		for (auto d : { 0x80, 0x06, 0x00, 0x02, 0x00, 0x00, 0x09, 0x00 }) {
			packet.pushBack(d);
		}
		auto cmd = Device::onSetupPacket(std::move(packet));
		if (cmd.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd.packet_.getSize() != 9) {
			return 1;
		}
		auto cmd2 = Device::onControlIn(std::move(cmd.packet_));
		if (cmd2.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd2.packet_) {
			return 1;
		}
	}
	{
		//Get Configuration descriptor
		auto packet = Alloc::allocate();
		for (auto d : { 0x80, 0x06, 0x00, 0x02, 0x00, 0x00, 0x4B, 0x00 }) {
			packet.pushBack(d);
		}
		auto cmd = Device::onSetupPacket(std::move(packet));
		if (cmd.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd.packet_.getSize() != 64) {
			return 1;
		}
		if (cmd.packet_[0] != 9) {
			return 1;
		}
		auto cmd2 = Device::onControlIn(std::move(cmd.packet_));
		if (cmd2.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd2.packet_.getSize() != 11) {
			return 1;
		}
		if (cmd2.packet_[2] != 2) {
			return 1;
		}
		auto cmd3 = Device::onControlIn(std::move(cmd2.packet_));
		if (cmd3.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd3.packet_) {
			return 1;
		}
	}
	return 0;
}

<commit_msg>added usb unit tests<commit_after>#include <iostream>
#include <sstream>
#include <iomanip>
#include "Usb/SetupPacket.hpp"
#include "Usb/Endpoint.hpp"
#include "USB/Packet.hpp"
#include "USB/Device.hpp"
#include "USB/Memory.hpp"

using PacketT = Kvasir::Usb::Packet <Kvasir::Usb::CompactPacket::ImplType>;
using Alloc = Kvasir::Usb::CompactPacket::Allocator<PacketT,12>;
using Device = Kvasir::Usb::Device<Alloc, Kvasir::Usb::CompactPacket::Queue<PacketT>, Kvasir::Usb::CompactPacket::Transfer<PacketT, Alloc>>;

template<typename T>
decltype(Alloc::allocate()) makePacket(std::initializer_list<T> l) {
	auto packet = Alloc::allocate();
	for (auto d : l) {
		packet.pushBack(d);
	}
	return packet;
}

int usbTest()
{
	Alloc::initialize();
	{
		//set address
		auto cmd = Device::onSetupPacket(makePacket({ 0, 5, 5, 0, 0, 0, 0, 0 }));
		if (cmd.type_ != Device::HalCommand::Type::setAddress) {
			return 1;
		}
		if (cmd.packet_.getSize() != 0) {
			return 1;
		}
		auto cmd2 = Device::onControlIn(std::move(cmd.packet_));
		if (cmd2.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd2.packet_) {
			return 1;
		}
	}
	{
		//GetDevice descriptor
		auto cmd = Device::onSetupPacket(makePacket({ 0x80, 6, 0, 1, 0, 0, 8, 0 }));
		if (cmd.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd.packet_.getSize() != 8) {
			return 1;
		}
		auto cmd2 = Device::onControlIn(std::move(cmd.packet_));
		if (cmd2.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd2.packet_) {
			return 1;
		}
	}
	{
		//GetDevice descriptor
		auto cmd = Device::onSetupPacket(makePacket({ 0x80, 0x06, 0x00, 0x01, 0x00, 0x00, 0x12, 0x00 }));
		if (cmd.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd.packet_.getSize() != 18) {
			return 1;
		}
		auto cmd2 = Device::onControlIn(std::move(cmd.packet_));
		if (cmd2.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd2.packet_) {
			return 1;
		}
	}
	{
		//Get Configuration descriptor
		auto cmd = Device::onSetupPacket(makePacket({ 0x80, 0x06, 0x00, 0x02, 0x00, 0x00, 0x09, 0x00 }));
		if (cmd.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd.packet_.getSize() != 9) {
			return 1;
		}
		auto cmd2 = Device::onControlIn(std::move(cmd.packet_));
		if (cmd2.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd2.packet_) {
			return 1;
		}
	}
	{
		//Get Configuration descriptor
		auto cmd = Device::onSetupPacket(makePacket({ 0x80, 0x06, 0x00, 0x02, 0x00, 0x00, 0x4B, 0x00 }));
		if (cmd.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd.packet_.getSize() != 64) {
			return 1;
		}
		if (cmd.packet_[0] != 9) {
			return 1;
		}
		auto cmd2 = Device::onControlIn(std::move(cmd.packet_));
		if (cmd2.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd2.packet_.getSize() != 11) {
			return 1;
		}
		if (cmd2.packet_[0] != 2) {
			return 1;
		}
		auto cmd3 = Device::onControlIn(std::move(cmd2.packet_));
		if (cmd3.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd3.packet_) {
			return 1;
		}
	}
	{
		//Get String descriptor
		auto cmd = Device::onSetupPacket(makePacket({ 0x80, 0x06, 0x00, 0x03, 0x00, 0x00, 0xFF, 0x00 }));
		if (cmd.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd.packet_.getSize() != 4) {
			return 1;
		}
		if (cmd.packet_[0] != 4) {
			return 1;
		}
		auto cmd2 = Device::onControlIn(std::move(cmd.packet_));
		if (cmd2.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd2.packet_) {
			return 1;
		}
	}
	{
		//Get String descriptor
		auto cmd = Device::onSetupPacket(makePacket({ 0x80, 0x06, 0x02, 0x03, 0x09, 0x04, 0xFF, 0x00 }));
		if (cmd.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd.packet_.getSize() != 22) {
			return 1;
		}
		if (cmd.packet_[0] != 0x16) {
			return 1;
		}
		auto cmd2 = Device::onControlIn(std::move(cmd.packet_));
		if (cmd2.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd2.packet_) {
			return 1;
		}
	}
	{
		//Get String descriptor
		auto cmd = Device::onSetupPacket(makePacket({ 0x80, 0x06, 0x03, 0x03, 0x09, 0x04, 0xFF, 0x00 }));
		if (cmd.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd.packet_.getSize() != 22) {
			return 1;
		}
		if (cmd.packet_[0] != 0x16) {
			return 1;
		}
		auto cmd2 = Device::onControlIn(std::move(cmd.packet_));
		if (cmd2.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd2.packet_) {
			return 1;
		}
	}
	{
		//GetDevice descriptor
		auto cmd = Device::onSetupPacket(makePacket({ 0x80, 0x06, 0x00, 0x01, 0x00, 0x00, 0x12, 0x00 }));
		if (cmd.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd.packet_.getSize() != 18) {
			return 1;
		}
		auto cmd2 = Device::onControlIn(std::move(cmd.packet_));
		if (cmd2.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd2.packet_) {
			return 1;
		}
	}
	{
		//Get Configuration descriptor
		auto cmd = Device::onSetupPacket(makePacket({ 0x80, 0x06, 0x00, 0x02, 0x00, 0x00, 0x09, 0x01 }));
		if (cmd.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd.packet_.getSize() != 64) {
			return 1;
		}
		if (cmd.packet_[0] != 9) {
			return 1;
		}
		auto cmd2 = Device::onControlIn(std::move(cmd.packet_));
		if (cmd2.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd2.packet_.getSize() != 11) {
			return 1;
		}
		if (cmd2.packet_[0] != 2) {
			return 1;
		}
		auto cmd3 = Device::onControlIn(std::move(cmd2.packet_));
		if (cmd3.type_ != Device::HalCommand::Type::noAction) {
			return 1;
		}
		if (cmd3.packet_) {
			return 1;
		}
	}
	return 0;
}

<|endoftext|>


<commit_before>// Author: Mihai Niculescu 2013

/**************************************************************************
 * Copyright(c) 1998-2013, ALICE Experiment at CERN, all rights reserved. *
 * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
 * full copyright notice.                                                 *
 **************************************************************************/

#include <stdlib.h>

#include <zmq.hpp>

#include <TCondition.h>
#include <TBufferFile.h>
#include <TMessage.h>
#include <TObjArray.h>
#include <TStreamerInfo.h>
#include <TThread.h>

#include <AliESDEvent.h>
#include <AliESDfriend.h>
#include <AliRawReader.h>
#include <AliRunLoader.h>
#include <AliReconstruction.h>

#include "AliRecoServerThread.h"

ClassImp(AliRecoServerThread);
AliRecoServerThread::AliRecoServerThread(zmq::context_t *context, AliReconstruction* reco)
  : TQObject(),
		fContext(0),
  	fReco(0),
  	fHost("tcp://*:5051"),
    fThread(0),
    fCond(0)
{
	fContext = context;
	fReco = reco;
}

AliRecoServerThread::~AliRecoServerThread()
{
	Stop();
}

Bool_t AliRecoServerThread::Start(const char* host)
{
	if(!fThread){
  	fHost = host;
  	fCond = new TCondition(0);
  	fThread = new TThread("AliRecoServerThread", (void(*) (void *) ) &RunThreaded, (void*)  this );
  	fThread->Run();

  	return kTRUE;
	}

	return kFALSE;
}

Int_t AliRecoServerThread::Stop()
{
	fCond->Signal();

  return 0;
}

Bool_t AliRecoServerThread::ForceStop()
{
	if(fThread){
		fThread->Kill();
		fThread->Delete();
		fThread=0;

		return kTRUE;
	}

	return kFALSE;
}

void AliRecoServerThread::Finished(Int_t status)
{
  Emit("Finished(Int_t)", status);
}

void AliRecoServerThread::SendStreamerInfos(TMessage* mess, zmq::socket_t *sock)
{
	//printf("Sending Streamer Infos....\n");

	// Check if TStreamerInfo must be sent. The list of TStreamerInfo of classes
   // in the object in the message is in the fInfos list of the message.
   // We send only the TStreamerInfos not yet sent on this socket.
	TList* infos = mess->GetStreamerInfos();

      TIter next(infos);
      TStreamerInfo *info;
      TList *minilist = 0;
      while ((info = (TStreamerInfo*)next())) {
         Int_t uid = info->GetNumber();
         if (!minilist) minilist = new TList();

         minilist->Add(info);
      }

      if (minilist) {
         TMessage messinfo(kMESS_STREAMERINFO);
         messinfo.WriteObject(minilist);
         delete minilist;
         if (messinfo.GetStreamerInfos())
            messinfo.GetStreamerInfos()->Clear();

           messinfo.SetLength();

          int bufsize = messinfo.Length();
        	char* buf = (char*) malloc(bufsize * sizeof(char));
          memcpy(buf, messinfo.Buffer(), bufsize);

        	// send!
          zmq::message_t message((void*)buf, bufsize, 0, 0);

         if (sock->send(message, ZMQ_SNDMORE))
            Warning("SendStreamerInfos", "problems sending TStreamerInfo's ...");
      }

   return;
}

void AliRecoServerThread::SendEvent(AliESDEvent* event, zmq::socket_t* socket)
{
  if(!event) return;

  TMessage tmess(kMESS_OBJECT);
  tmess.Reset();
  tmess.WriteObject(event);

  TMessage::EnableSchemaEvolutionForAll(kTRUE);
  SendStreamerInfos(&tmess, socket);

  tmess.SetLength();

  int bufsize = tmess.Length();
  char* buf = (char*) malloc(bufsize * sizeof(char));
  memcpy(buf, tmess.Buffer(), bufsize);

  // send!
  zmq::message_t message((void*)buf, bufsize, 0, 0);
  socket->send(message);

}

void* AliRecoServerThread::RunThreaded(void* arg)
{
	TThread::SetCancelAsynchronous();
	TThread::SetCancelOn();

	AliRecoServerThread* recoTh = (AliRecoServerThread*)arg;

	const char* host = recoTh->GetHost();
	zmq::context_t* context = recoTh->GetContext();
	AliReconstruction* reco   = recoTh->GetReconstruction();

	zmq::socket_t publisher(*context, ZMQ_PUB);
	publisher.bind(host);

  if(reco==0) return 0;

  AliESDEvent* event;

	reco->Begin(NULL);
  if (reco->GetAbort() != TSelector::kContinue) return 0;

  reco->SlaveBegin(NULL);
	if (reco->GetAbort() != TSelector::kContinue) return 0;

  //******* The loop over events
    Int_t iEvent = 0;
    while ( reco->HasNextEventAfter(iEvent) ) {
      // check if process has enough resources
      if (!reco->HasEnoughResources(iEvent)) break;
      Bool_t status = reco->ProcessEvent(iEvent);

      if (status)
      {
				event = reco->GetESDEvent();
				SendEvent(event, &publisher);

   			sleep(1);
     }
      else {
        reco->Abort("ProcessEvent",TSelector::kAbortFile);
      }

      reco->CleanProcessedEvent();
      if(recoTh->Condition()->TimedWaitRelative(500)==0){
				break;
			}
      iEvent++;
    }
    reco->SlaveTerminate();
    if (reco->GetAbort() != TSelector::kContinue) return 0;
    reco->Terminate();
    if (reco->GetAbort() != TSelector::kContinue) return 0;

}
<commit_msg>Compilation with Root6<commit_after>// Author: Mihai Niculescu 2013

/**************************************************************************
 * Copyright(c) 1998-2013, ALICE Experiment at CERN, all rights reserved. *
 * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
 * full copyright notice.                                                 *
 **************************************************************************/

#include <RVersion.h>
#include <stdlib.h>

#include <zmq.hpp>

#include <TCondition.h>
#include <TBufferFile.h>
#include <TMessage.h>
#include <TObjArray.h>
#include <TStreamerInfo.h>
#include <TThread.h>

#include <AliESDEvent.h>
#include <AliESDfriend.h>
#include <AliRawReader.h>
#include <AliRunLoader.h>
#include <AliReconstruction.h>

#include "AliRecoServerThread.h"

ClassImp(AliRecoServerThread);
AliRecoServerThread::AliRecoServerThread(zmq::context_t *context, AliReconstruction* reco)
  : TQObject(),
		fContext(0),
  	fReco(0),
  	fHost("tcp://*:5051"),
    fThread(0),
    fCond(0)
{
	fContext = context;
	fReco = reco;
}

AliRecoServerThread::~AliRecoServerThread()
{
	Stop();
}

Bool_t AliRecoServerThread::Start(const char* host)
{
	if(!fThread){
  	fHost = host;
  	fCond = new TCondition(0);
  	fThread = new TThread("AliRecoServerThread", (void(*) (void *) ) &RunThreaded, (void*)  this );
  	fThread->Run();

  	return kTRUE;
	}

	return kFALSE;
}

Int_t AliRecoServerThread::Stop()
{
	fCond->Signal();

  return 0;
}

Bool_t AliRecoServerThread::ForceStop()
{
	if(fThread){
		fThread->Kill();
		fThread->Delete();
		fThread=0;

		return kTRUE;
	}

	return kFALSE;
}

void AliRecoServerThread::Finished(Int_t status)
{
  Emit("Finished(Int_t)", status);
}

void AliRecoServerThread::SendStreamerInfos(TMessage* mess, zmq::socket_t *sock)
{
	//printf("Sending Streamer Infos....\n");

	// Check if TStreamerInfo must be sent. The list of TStreamerInfo of classes
   // in the object in the message is in the fInfos list of the message.
   // We send only the TStreamerInfos not yet sent on this socket.
	TList* infos = mess->GetStreamerInfos();

      TIter next(infos);
      TStreamerInfo *info;
      TList *minilist = 0;
      while ((info = (TStreamerInfo*)next())) {
         Int_t uid = info->GetNumber();
         if (!minilist) minilist = new TList();

         minilist->Add(info);
      }

      if (minilist) {
         TMessage messinfo(kMESS_STREAMERINFO);
         messinfo.WriteObject(minilist);
         delete minilist;
         if (messinfo.GetStreamerInfos())
            messinfo.GetStreamerInfos()->Clear();
#if ROOT_VERSION_CODE < ROOT_VERSION(5,99,0)
           messinfo.SetLength();
#endif

          int bufsize = messinfo.Length();
        	char* buf = (char*) malloc(bufsize * sizeof(char));
          memcpy(buf, messinfo.Buffer(), bufsize);

        	// send!
          zmq::message_t message((void*)buf, bufsize, 0, 0);

         if (sock->send(message, ZMQ_SNDMORE))
            Warning("SendStreamerInfos", "problems sending TStreamerInfo's ...");
      }

   return;
}

void AliRecoServerThread::SendEvent(AliESDEvent* event, zmq::socket_t* socket)
{
  if(!event) return;

  TMessage tmess(kMESS_OBJECT);
  tmess.Reset();
  tmess.WriteObject(event);

  TMessage::EnableSchemaEvolutionForAll(kTRUE);
  SendStreamerInfos(&tmess, socket);

#if ROOT_VERSION_CODE < ROOT_VERSION(5,99,0)
  tmess.SetLength();
#endif
  int bufsize = tmess.Length();
  char* buf = (char*) malloc(bufsize * sizeof(char));
  memcpy(buf, tmess.Buffer(), bufsize);

  // send!
  zmq::message_t message((void*)buf, bufsize, 0, 0);
  socket->send(message);

}

void* AliRecoServerThread::RunThreaded(void* arg)
{
	TThread::SetCancelAsynchronous();
	TThread::SetCancelOn();

	AliRecoServerThread* recoTh = (AliRecoServerThread*)arg;

	const char* host = recoTh->GetHost();
	zmq::context_t* context = recoTh->GetContext();
	AliReconstruction* reco   = recoTh->GetReconstruction();

	zmq::socket_t publisher(*context, ZMQ_PUB);
	publisher.bind(host);

  if(reco==0) return 0;

  AliESDEvent* event;

	reco->Begin(NULL);
  if (reco->GetAbort() != TSelector::kContinue) return 0;

  reco->SlaveBegin(NULL);
	if (reco->GetAbort() != TSelector::kContinue) return 0;

  //******* The loop over events
    Int_t iEvent = 0;
    while ( reco->HasNextEventAfter(iEvent) ) {
      // check if process has enough resources
      if (!reco->HasEnoughResources(iEvent)) break;
      Bool_t status = reco->ProcessEvent(iEvent);

      if (status)
      {
				event = reco->GetESDEvent();
				SendEvent(event, &publisher);

   			sleep(1);
     }
      else {
        reco->Abort("ProcessEvent",TSelector::kAbortFile);
      }

      reco->CleanProcessedEvent();
      if(recoTh->Condition()->TimedWaitRelative(500)==0){
				break;
			}
      iEvent++;
    }
    reco->SlaveTerminate();
    if (reco->GetAbort() != TSelector::kContinue) return 0;
    reco->Terminate();
    if (reco->GetAbort() != TSelector::kContinue) return 0;

}
<|endoftext|>


<commit_before>
// NetherFortGen.cpp

// Implements the cNetherFortGen class representing the nether fortress generator

#include "Globals.h"
#include "NetherFortGen.h"
#include "Prefabs/NetherFortPrefabs.h"

static const int NEIGHBORHOOD_SIZE = 3;

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cNetherFortGen::cNetherFort:

class cNetherFortGen::cNetherFort :
	public cGridStructGen::cStructure
{
	typedef cGridStructGen::cStructure super;

public:
	cNetherFortGen & m_ParentGen;
	int m_GridSize;
	int m_Seed;
	cPlacedPieces m_Pieces;

	cNetherFort(cNetherFortGen & a_ParentGen, int a_OriginX, int a_OriginZ, int a_GridSize, int a_MaxDepth, int a_Seed) :
		super(a_OriginX, a_OriginZ),
		m_ParentGen(a_ParentGen),
		m_GridSize(a_GridSize),
		m_Seed(a_Seed)
	{
		// TODO: Proper Y-coord placement
		int BlockY = 64;

		// Generate pieces:
		for (int i = 0; m_Pieces.size() < (size_t)(a_MaxDepth * a_MaxDepth / 8 + a_MaxDepth); i++)
		{
			cBFSPieceGenerator pg(cNetherFortGen::m_PiecePool, a_Seed + i);
			pg.PlacePieces(a_OriginX, BlockY, a_OriginZ, a_MaxDepth, m_Pieces);
		}
	}

	~cNetherFort()
	{
		cPieceGenerator::FreePieces(m_Pieces);
	}

	/** Carves the system into the chunk data */
	virtual void DrawIntoChunk(cChunkDesc & a_Chunk)
	{
		for (cPlacedPieces::const_iterator itr = m_Pieces.begin(), end = m_Pieces.end(); itr != end; ++itr)
		{
			const cPrefab & Prefab = (const cPrefab &)((*itr)->GetPiece());
			Prefab.Draw(a_Chunk, *itr);
		}  // for itr - m_PlacedPieces[]
	}
};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Performance test of the NetherFort generator:

/*
#include "OSSupport/Timer.h"
static class cNetherFortPerfTest
{
public:
	cNetherFortPerfTest(void)
	{
		cTimer Timer;
		long long StartTime = Timer.GetNowTime();

		const int GridSize = 512;
		const int MaxDepth = 12;
		const int NumIterations = 100;
		for (int i = 0; i < NumIterations; i++)
		{
			cNetherFortGen FortGen(i, GridSize, MaxDepth);
			delete new cNetherFortGen::cNetherFort(FortGen, 0, 0, GridSize, MaxDepth, i);
		}

		long long EndTime = Timer.GetNowTime();
		printf("%d forts took %lld msec (%f sec) to generate\n", NumIterations, EndTime - StartTime, ((double)(EndTime - StartTime)) / 1000);
		exit(0);
	}

} g_PerfTest;
//*/

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cNetherFortGen:

cPrefabPiecePool cNetherFortGen::m_PiecePool(g_NetherFortPrefabs, g_NetherFortPrefabsCount, g_NetherFortStartingPrefabs, g_NetherFortStartingPrefabsCount);

cNetherFortGen::cNetherFortGen(int a_Seed, int a_GridSize, int a_MaxDepth) :
	super(a_Seed, a_GridSize, a_GridSize, a_MaxDepth * 10, a_MaxDepth * 10, 200),
	m_MaxDepth(a_MaxDepth)
{
	/*
	// DEBUG: Try one round of placement:
	cPlacedPieces Pieces;
	cBFSPieceGenerator pg(m_PiecePool, a_Seed);
	pg.PlacePieces(0, 64, 0, a_MaxDepth, Pieces);
	//*/
}

cGridStructGen::cStructurePtr cNetherFortGen::CreateStructure(int a_OriginX, int a_OriginZ)
{
	return cStructurePtr(new cNetherFort(*this, a_OriginX, a_OriginZ, m_GridSizeX, m_MaxDepth, m_Seed));
}

<commit_msg>Removed an unused NetherFortGen variable.<commit_after>
// NetherFortGen.cpp

// Implements the cNetherFortGen class representing the nether fortress generator

#include "Globals.h"
#include "NetherFortGen.h"
#include "Prefabs/NetherFortPrefabs.h"

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cNetherFortGen::cNetherFort:

class cNetherFortGen::cNetherFort :
	public cGridStructGen::cStructure
{
	typedef cGridStructGen::cStructure super;

public:
	cNetherFortGen & m_ParentGen;
	int m_GridSize;
	int m_Seed;
	cPlacedPieces m_Pieces;

	cNetherFort(cNetherFortGen & a_ParentGen, int a_OriginX, int a_OriginZ, int a_GridSize, int a_MaxDepth, int a_Seed) :
		super(a_OriginX, a_OriginZ),
		m_ParentGen(a_ParentGen),
		m_GridSize(a_GridSize),
		m_Seed(a_Seed)
	{
		// TODO: Proper Y-coord placement
		int BlockY = 64;

		// Generate pieces:
		for (int i = 0; m_Pieces.size() < (size_t)(a_MaxDepth * a_MaxDepth / 8 + a_MaxDepth); i++)
		{
			cBFSPieceGenerator pg(cNetherFortGen::m_PiecePool, a_Seed + i);
			pg.PlacePieces(a_OriginX, BlockY, a_OriginZ, a_MaxDepth, m_Pieces);
		}
	}

	~cNetherFort()
	{
		cPieceGenerator::FreePieces(m_Pieces);
	}

	/** Carves the system into the chunk data */
	virtual void DrawIntoChunk(cChunkDesc & a_Chunk)
	{
		for (cPlacedPieces::const_iterator itr = m_Pieces.begin(), end = m_Pieces.end(); itr != end; ++itr)
		{
			const cPrefab & Prefab = (const cPrefab &)((*itr)->GetPiece());
			Prefab.Draw(a_Chunk, *itr);
		}  // for itr - m_PlacedPieces[]
	}
};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Performance test of the NetherFort generator:

/*
#include "OSSupport/Timer.h"
static class cNetherFortPerfTest
{
public:
	cNetherFortPerfTest(void)
	{
		cTimer Timer;
		long long StartTime = Timer.GetNowTime();

		const int GridSize = 512;
		const int MaxDepth = 12;
		const int NumIterations = 100;
		for (int i = 0; i < NumIterations; i++)
		{
			cNetherFortGen FortGen(i, GridSize, MaxDepth);
			delete new cNetherFortGen::cNetherFort(FortGen, 0, 0, GridSize, MaxDepth, i);
		}

		long long EndTime = Timer.GetNowTime();
		printf("%d forts took %lld msec (%f sec) to generate\n", NumIterations, EndTime - StartTime, ((double)(EndTime - StartTime)) / 1000);
		exit(0);
	}

} g_PerfTest;
//*/

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cNetherFortGen:

cPrefabPiecePool cNetherFortGen::m_PiecePool(g_NetherFortPrefabs, g_NetherFortPrefabsCount, g_NetherFortStartingPrefabs, g_NetherFortStartingPrefabsCount);

cNetherFortGen::cNetherFortGen(int a_Seed, int a_GridSize, int a_MaxDepth) :
	super(a_Seed, a_GridSize, a_GridSize, a_MaxDepth * 10, a_MaxDepth * 10, 200),
	m_MaxDepth(a_MaxDepth)
{
	/*
	// DEBUG: Try one round of placement:
	cPlacedPieces Pieces;
	cBFSPieceGenerator pg(m_PiecePool, a_Seed);
	pg.PlacePieces(0, 64, 0, a_MaxDepth, Pieces);
	//*/
}

cGridStructGen::cStructurePtr cNetherFortGen::CreateStructure(int a_OriginX, int a_OriginZ)
{
	return cStructurePtr(new cNetherFort(*this, a_OriginX, a_OriginZ, m_GridSizeX, m_MaxDepth, m_Seed));
}

<|endoftext|>


<commit_before><commit_msg>add error returns missing from protoc to prevent it from exiting with a successful return value when writing the zip file fails<commit_after><|endoftext|>


<commit_before>#include "stdafx.h"
#include "ObjectPoolTest.h"
#include "ObjectPool.h"
#include "TestFixtures/SimpleThreaded.h"

class PooledObject {
};

TEST_F(ObjectPoolTest, VerifyOutstandingLimit) {
  ObjectPool<PooledObject> pool(2);

  std::shared_ptr<PooledObject> obj1, obj2, obj3;

  // Try to grab some objects out of the pool:
  pool(obj1);
  pool(obj2);

  // Verify that grabbing a third object fails:
  pool(obj3);
  EXPECT_TRUE(obj3 == nullptr) << "Object pool issued more objects than it was authorized to issue";
}

TEST_F(ObjectPoolTest, VerifyAsynchronousUsage) {
  AutoCreateContext ctxt;
  CurrentContextPusher pshr(ctxt);

  AutoRequired<SimpleThreadedT<PooledObject>> obj;
  AutoFired<SharedPtrReceiver<PooledObject>> spr;
  ObjectPool<PooledObject> pool(3);

  {
    // Obtain the pool limit in objects:
    std::shared_ptr<PooledObject> obj1, obj2, obj3;
    pool(obj1);
    pool(obj2);
    pool(obj3);

    // Block--verify that we _do not_ get any of those objects back while they are
    // still outstanding.
    {
      auto obj4 = pool.WaitFor(boost::chrono::milliseconds(1));
      EXPECT_TRUE(obj4 == nullptr) << "Pool issued another element even though it should have hit its outstanding limit";
    }

    // Now we kick off threads:
    AutoCurrentContext()->Initiate();

    // Fire off a few events:
    spr(&SharedPtrReceiver<PooledObject>::OnEvent)(obj1);
    spr(&SharedPtrReceiver<PooledObject>::OnEvent)(obj2);
    spr(&SharedPtrReceiver<PooledObject>::OnEvent)(obj3);
  }

  // This should return more or less right away as objects become available:
  {
    auto obj4 = pool.WaitFor(boost::chrono::milliseconds(10));
    EXPECT_TRUE(obj4 != nullptr) << "Object pool failed to be notified that it received a new element";
  }

  // Cause the thread to quit:
  *obj += [&obj] { obj->Stop(); };
  obj->Wait();
}

TEST_F(ObjectPoolTest, ClearCachedEntities) {
  ObjectPool<PooledObject> pool(3);

  // Create a pool and get a few items in its cache:
  pool.Wait(),
  pool.Wait(),
  pool.Wait();

  // Verify the expected initial cache count:
  ASSERT_EQ(3UL, pool.GetCached()) << "Expected pool outstanding count to have hit 3 entries";

  // Now verify that we can clear the object pool at a point in time when it should already be empty:
  pool.ClearCachedEntities();

  // And we should be legitimately empty at this point
  ASSERT_EQ(0UL, pool.GetCached()) << "After invoking a cache clearing operation, the cache was nevertheless not cleared";
}

TEST_F(ObjectPoolTest, VerifyOutOfOrderDestruction) {
  std::shared_ptr<int> ptr;

  {
    ObjectPool<int> pool;
    pool(ptr);
  }

  // Verify that returning a shared pointer after the pool is gone does not result in an exception
  ASSERT_NO_THROW(ptr.reset()) << "Attempting to release a shared pointer on a destroyed pool caused an unexpected exception";
}

class HoldsSharedPtrThenQuits:
  public CoreThread
{
public:
  std::shared_ptr<int> m_ptr;

  void Run(void) override {
    ThreadSleep(boost::chrono::milliseconds(100));
    m_ptr.reset();
  }
};

TEST_F(ObjectPoolTest, EmptyPoolIssuance) {
  ObjectPool<int> pool;

  // Create the thread which will hold the shared pointer for awhile:
  AutoRequired<HoldsSharedPtrThenQuits> thread;
  pool(thread->m_ptr);
  std::weak_ptr<int> ptrWeak = thread->m_ptr;

  ASSERT_FALSE(ptrWeak.expired()) << "Object pool failed to issue a shared pointer as expected";

  // Verify properties now that we've zeroized the limit:
  pool.SetOutstandingLimit(0);
  EXPECT_ANY_THROW(pool.SetOutstandingLimit(1)) << "An attempt to alter a zeroized outstanding limit did not throw an exception as expected";
  EXPECT_ANY_THROW(pool.Wait()) << "An attempt to obtain an element on an empty pool did not throw an exception as expected";

  // Now see if we can delay for the thread to back out:
  m_create->Initiate();
  pool.Rundown();

  // Verify that it got released as expected:
  ASSERT_TRUE(ptrWeak.expired()) << "Not all shared pointers issued by an object pool expired in a timely fashion";
}

TEST_F(ObjectPoolTest, CanRundownOneIssued) {
  ObjectPool<int> pool;
  pool.Wait();
  pool.Rundown();
}<commit_msg>Comment to discuss why there are no assertions or tests of any kind in a unit test<commit_after>#include "stdafx.h"
#include "ObjectPoolTest.h"
#include "ObjectPool.h"
#include "TestFixtures/SimpleThreaded.h"

class PooledObject {
};

TEST_F(ObjectPoolTest, VerifyOutstandingLimit) {
  ObjectPool<PooledObject> pool(2);

  std::shared_ptr<PooledObject> obj1, obj2, obj3;

  // Try to grab some objects out of the pool:
  pool(obj1);
  pool(obj2);

  // Verify that grabbing a third object fails:
  pool(obj3);
  EXPECT_TRUE(obj3 == nullptr) << "Object pool issued more objects than it was authorized to issue";
}

TEST_F(ObjectPoolTest, VerifyAsynchronousUsage) {
  AutoCreateContext ctxt;
  CurrentContextPusher pshr(ctxt);

  AutoRequired<SimpleThreadedT<PooledObject>> obj;
  AutoFired<SharedPtrReceiver<PooledObject>> spr;
  ObjectPool<PooledObject> pool(3);

  {
    // Obtain the pool limit in objects:
    std::shared_ptr<PooledObject> obj1, obj2, obj3;
    pool(obj1);
    pool(obj2);
    pool(obj3);

    // Block--verify that we _do not_ get any of those objects back while they are
    // still outstanding.
    {
      auto obj4 = pool.WaitFor(boost::chrono::milliseconds(1));
      EXPECT_TRUE(obj4 == nullptr) << "Pool issued another element even though it should have hit its outstanding limit";
    }

    // Now we kick off threads:
    AutoCurrentContext()->Initiate();

    // Fire off a few events:
    spr(&SharedPtrReceiver<PooledObject>::OnEvent)(obj1);
    spr(&SharedPtrReceiver<PooledObject>::OnEvent)(obj2);
    spr(&SharedPtrReceiver<PooledObject>::OnEvent)(obj3);
  }

  // This should return more or less right away as objects become available:
  {
    auto obj4 = pool.WaitFor(boost::chrono::milliseconds(10));
    EXPECT_TRUE(obj4 != nullptr) << "Object pool failed to be notified that it received a new element";
  }

  // Cause the thread to quit:
  *obj += [&obj] { obj->Stop(); };
  obj->Wait();
}

TEST_F(ObjectPoolTest, ClearCachedEntities) {
  ObjectPool<PooledObject> pool(3);

  // Create a pool and get a few items in its cache:
  pool.Wait(),
  pool.Wait(),
  pool.Wait();

  // Verify the expected initial cache count:
  ASSERT_EQ(3UL, pool.GetCached()) << "Expected pool outstanding count to have hit 3 entries";

  // Now verify that we can clear the object pool at a point in time when it should already be empty:
  pool.ClearCachedEntities();

  // And we should be legitimately empty at this point
  ASSERT_EQ(0UL, pool.GetCached()) << "After invoking a cache clearing operation, the cache was nevertheless not cleared";
}

TEST_F(ObjectPoolTest, VerifyOutOfOrderDestruction) {
  std::shared_ptr<int> ptr;

  {
    ObjectPool<int> pool;
    pool(ptr);
  }

  // Verify that returning a shared pointer after the pool is gone does not result in an exception
  ASSERT_NO_THROW(ptr.reset()) << "Attempting to release a shared pointer on a destroyed pool caused an unexpected exception";
}

class HoldsSharedPtrThenQuits:
  public CoreThread
{
public:
  std::shared_ptr<int> m_ptr;

  void Run(void) override {
    ThreadSleep(boost::chrono::milliseconds(100));
    m_ptr.reset();
  }
};

TEST_F(ObjectPoolTest, EmptyPoolIssuance) {
  ObjectPool<int> pool;

  // Create the thread which will hold the shared pointer for awhile:
  AutoRequired<HoldsSharedPtrThenQuits> thread;
  pool(thread->m_ptr);
  std::weak_ptr<int> ptrWeak = thread->m_ptr;

  ASSERT_FALSE(ptrWeak.expired()) << "Object pool failed to issue a shared pointer as expected";

  // Verify properties now that we've zeroized the limit:
  pool.SetOutstandingLimit(0);
  EXPECT_ANY_THROW(pool.SetOutstandingLimit(1)) << "An attempt to alter a zeroized outstanding limit did not throw an exception as expected";
  EXPECT_ANY_THROW(pool.Wait()) << "An attempt to obtain an element on an empty pool did not throw an exception as expected";

  // Now see if we can delay for the thread to back out:
  m_create->Initiate();
  pool.Rundown();

  // Verify that it got released as expected:
  ASSERT_TRUE(ptrWeak.expired()) << "Not all shared pointers issued by an object pool expired in a timely fashion";
}

TEST_F(ObjectPoolTest, CanRundownOneIssued) {
  // No conditions to be checked, we just know these routines should not deadlock.
  ObjectPool<int> pool;
  pool.Wait();
  pool.Rundown();
}<|endoftext|>


<commit_before>#include "SDL/SDL.h"
#include "SDL/SDL_ttf.h"
#include <string>
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <functional>
#include <stdexcept>

#include "utils.h"
#include "timer.h"
#include "renderable.h"
#include "entity.h"
#include "ball.h"
#include "bat.h"
#include "brick.h"
#include "image_pack.h"
#include "score_counter.h"

const char *CAPTION = "Breakout";
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;
const int N_BRICKS = 20;

enum { ERROR_INITIALIZE = 1,
       ERROR_LOAD_IMAGES,
       ERROR_FLIP };

const int MAXIMUM_FPS = 50;

SDL_Surface *screen = NULL;
SDL_Event event;

void clean_up();
bool init();

int main (int argc, char **argv) {
    using namespace breakout;
    using namespace std;

    list<Entity*> entities = list<Entity*>();
    list<Renderable*> renders = list<Renderable*>();

    if (!init()) {
        cerr << "Error initializing SDL.";
        return ERROR_INITIALIZE;
    }

    const char *paths[] = {"ball.png", "bat.png", "brick.png"};
    vector<string> image_paths(paths, paths + sizeof(paths) / sizeof(char*));
    ImagePack *images;

    try {
        images = new ImagePack(image_paths);
    } catch (std::runtime_error e) {
        cerr << "Error loading images.";
        return ERROR_LOAD_IMAGES;
    }

    bool running = true;
    Timer timer = Timer();
    Ball ball = Ball(images->get_image("ball.png"), SCREEN_WIDTH / 2,
                     SCREEN_HEIGHT / 2, 5, 7);
    Bat bat = Bat(images->get_image("bat.png"), SCREEN_WIDTH / 2,
                  SCREEN_HEIGHT - 50);
    SDL_Color score_color = {0, 0, 0};
    ScoreCounter score = ScoreCounter(0, string("LiberationSans-Regular.ttf"), 20,
                                      score_color);
    int remaining = 0;

    Brick brick = Brick(images->get_image("brick.png"));
    brick.set_x(40);
    brick.set_y(50);

    entities.push_back(&ball);
    entities.push_back(&bat);
    entities.push_back(&brick);

    renders.push_back(&ball);
    renders.push_back(&bat);
    renders.push_back(&score);
    renders.push_back(&brick);

    int bat_width = bat.get_rect().w;
    int ball_width = ball.get_rect().w;
    int ball_height = ball.get_rect().h;

    while (running) {
        timer.start();

        /** game logic **/

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

        for_each(entities.begin(), entities.end(), mem_fun(&Entity::step));
        entities.remove_if(mem_fun(&Entity::is_dead));

        if (collides(&ball, &bat)) {
            ball.set_x_velocity(-ball.get_x_velocity());
            ball.set_y_velocity(-ball.get_y_velocity());
        }

        if (collides(&ball, &brick)) {
            brick.destroy();
        }

        if (ball.get_x() < 0 || ball.get_x() >= SCREEN_WIDTH - ball_width) {
            ball.set_x_velocity(-ball.get_x_velocity());
        }

        if (ball.get_y() < 0 || ball.get_y() >= SCREEN_HEIGHT - ball_height) {
            ball.set_y_velocity(-ball.get_y_velocity());
        }

        if (bat.get_x() < 0) {
            bat.set_x(0);
        } else if (bat.get_x() > SCREEN_WIDTH - bat_width) {
            bat.set_x(SCREEN_WIDTH - bat_width);
        }

        /** rendering logic **/
        // white background
        SDL_FillRect(screen, &screen->clip_rect,
                     SDL_MapRGB(screen->format, 0xFF, 0xFF, 0xFF));
        for_each(renders.begin(), renders.end(),
                 bind2nd(mem_fun<void, Renderable, SDL_Surface *>(&Renderable::render),
                         screen));
        renders.remove_if(mem_fun(&Renderable::is_dead));

        /** limit framerate **/

        remaining = 1000 / MAXIMUM_FPS - timer.get_ticks();

        if (SDL_Flip(screen) == -1) {
            cerr << "Flip error.";
            return ERROR_FLIP;
        }

        if (remaining > 0) {
            SDL_Delay(remaining);
        }
    }

    delete images;

    clean_up();

    return 0;
}

/**
 * Closes external libraries (SDL, TTF)
 */
void clean_up() {
    TTF_Quit();
    SDL_Quit();
}

/**
 * Sets up external libraries and window
 */
bool init() {
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
        return false;
    }

    if (TTF_Init() == -1) {
        return false;
    }

    screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP,
                              SDL_SWSURFACE);
    if (screen == NULL) return false;
    SDL_WM_SetCaption(CAPTION, NULL);
    return true;
}
<commit_msg>Score counter now updates; ball bounces when hits brick.<commit_after>#include "SDL/SDL.h"
#include "SDL/SDL_ttf.h"
#include <string>
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <functional>
#include <stdexcept>

#include "utils.h"
#include "timer.h"
#include "renderable.h"
#include "entity.h"
#include "ball.h"
#include "bat.h"
#include "brick.h"
#include "image_pack.h"
#include "score_counter.h"

const char *CAPTION = "Breakout";
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;
const int N_BRICKS = 20;

enum { ERROR_INITIALIZE = 1,
       ERROR_LOAD_IMAGES,
       ERROR_FLIP };

const int MAXIMUM_FPS = 50;

SDL_Surface *screen = NULL;
SDL_Event event;

void clean_up();
bool init();

int main (int argc, char **argv) {
    using namespace breakout;
    using namespace std;

    list<Entity*> entities = list<Entity*>();
    list<Renderable*> renders = list<Renderable*>();

    if (!init()) {
        cerr << "Error initializing SDL.";
        return ERROR_INITIALIZE;
    }

    const char *paths[] = {"ball.png", "bat.png", "brick.png"};
    vector<string> image_paths(paths, paths + sizeof(paths) / sizeof(char*));
    ImagePack *images;

    try {
        images = new ImagePack(image_paths);
    } catch (std::runtime_error e) {
        cerr << "Error loading images.";
        return ERROR_LOAD_IMAGES;
    }

    bool running = true;
    Timer timer = Timer();
    Ball ball = Ball(images->get_image("ball.png"), SCREEN_WIDTH / 2,
                     SCREEN_HEIGHT / 2, 5, 7);
    Bat bat = Bat(images->get_image("bat.png"), SCREEN_WIDTH / 2,
                  SCREEN_HEIGHT - 50);
    SDL_Color score_color = {0, 0, 0};
    ScoreCounter score = ScoreCounter(0, string("LiberationSans-Regular.ttf"), 20,
                                      score_color);
    int remaining = 0;

    Brick brick = Brick(images->get_image("brick.png"));
    brick.set_x(40);
    brick.set_y(50);

    entities.push_back(&ball);
    entities.push_back(&bat);
    entities.push_back(&brick);

    renders.push_back(&ball);
    renders.push_back(&bat);
    renders.push_back(&score);
    renders.push_back(&brick);

    int bat_width = bat.get_rect().w;
    int ball_width = ball.get_rect().w;
    int ball_height = ball.get_rect().h;

    while (running) {
        timer.start();

        /** game logic **/

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

        for_each(entities.begin(), entities.end(), mem_fun(&Entity::step));
        entities.remove_if(mem_fun(&Entity::is_dead));

        if (collides(&ball, &bat)) {
            ball.set_x_velocity(-ball.get_x_velocity());
            ball.set_y_velocity(-ball.get_y_velocity());
        }

        if (collides(&ball, &brick)) {
            brick.destroy();
            ball.set_x_velocity(-ball.get_x_velocity());
            ball.set_y_velocity(-ball.get_y_velocity());
            score.add_score(10);
        }

        if (ball.get_x() < 0 || ball.get_x() >= SCREEN_WIDTH - ball_width) {
            ball.set_x_velocity(-ball.get_x_velocity());
        }

        if (ball.get_y() < 0 || ball.get_y() >= SCREEN_HEIGHT - ball_height) {
            ball.set_y_velocity(-ball.get_y_velocity());
        }

        if (bat.get_x() < 0) {
            bat.set_x(0);
        } else if (bat.get_x() > SCREEN_WIDTH - bat_width) {
            bat.set_x(SCREEN_WIDTH - bat_width);
        }

        /** rendering logic **/
        // white background
        SDL_FillRect(screen, &screen->clip_rect,
                     SDL_MapRGB(screen->format, 0xFF, 0xFF, 0xFF));
        for_each(renders.begin(), renders.end(),
                 bind2nd(mem_fun<void, Renderable, SDL_Surface *>(&Renderable::render),
                         screen));
        renders.remove_if(mem_fun(&Renderable::is_dead));

        /** limit framerate **/

        remaining = 1000 / MAXIMUM_FPS - timer.get_ticks();

        if (SDL_Flip(screen) == -1) {
            cerr << "Flip error.";
            return ERROR_FLIP;
        }

        if (remaining > 0) {
            SDL_Delay(remaining);
        }
    }

    delete images;

    clean_up();

    return 0;
}

/**
 * Closes external libraries (SDL, TTF)
 */
void clean_up() {
    TTF_Quit();
    SDL_Quit();
}

/**
 * Sets up external libraries and window
 */
bool init() {
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
        return false;
    }

    if (TTF_Init() == -1) {
        return false;
    }

    screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP,
                              SDL_SWSURFACE);
    if (screen == NULL) return false;
    SDL_WM_SetCaption(CAPTION, NULL);
    return true;
}
<|endoftext|>


<commit_before>//// Fancy ncurses terminal for calculators
//// Author: David P. Sicilia, June 2016

#include <ncurses.h>
#include <string>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <iostream>
#include <string.h>

#include "assert.hpp"
#include "scope_exit.hpp"
#include "input.hpp"

struct Entry
{
    std::string one_line;
    std::vector<std::string> grid;
};

struct Stripe
{
    Entry e;
    bool is_left;
    int y;
    int x;
};

auto render_stripe( int width, Stripe const& s ) -> std::vector<std::string>
{
    auto out = std::vector<std::string>( s.y+2 );
    int start_x = s.is_left ? 1 : width-1-s.x;
    auto pad = std::string( start_x, ' ' );
    auto end_pad = std::string( width-start_x-s.x, ' ' );
    for( int i = 0; i < s.y; ++i )
        out[i+1] = pad + s.e.grid[i] + end_pad;
    out[0]     = pad + std::string( s.x, ' ' ) + end_pad;
    out[s.y+1] = pad + std::string( s.x, ' ' ) + end_pad;
    return out;
}

auto draw_stripe( int width, int start_y, bool highlight, Stripe const& s ) -> void
{
    auto text = render_stripe( width, s );
    if( highlight ) attron( A_REVERSE );
    for( int i = text.size(); i > 0; --i ) {
        if( start_y-i < 0 )
            break;
        mvprintw( start_y-text.size()+i, 0, text[i-1].c_str() );
    }
    if( highlight ) attroff( A_REVERSE );
}

auto draw_stripes( int highlight, std::vector<Stripe> const& v ) -> void
{
    int height = 0, width = 0;
    getmaxyx( stdscr, height, width );
    (void)height;
    int start_y = height-2;
    int highlight_j = v.size() - highlight;
    for( int j = v.size(); j > 0; --j ) {
        if( start_y < 0 )
            break;
        Stripe const& s = v[j-1];
        bool highlight = (j == highlight_j);
        draw_stripe( width, start_y, highlight, s );
        start_y -= (s.y+2);
    }
}

std::vector<std::string> s1 = {
    "  1 + 2  ",
    "---------",
    "      5  ",
    " 3 + --- ",
    "      6  "
};

std::vector<std::string> s2 = {
    "     1     0.002     r    ",
    "    --- + ------- + 7     ",
    "     x       y            ",
    "--------------------------",
    "                        w ",
    " /                     \\  ",
    " |     1     4 + t     |  ",
    " |1 + --- + ------- + y|  ",
    " |     6       y       |  ",
    " \\                     /  "
};

std::vector<std::string> s3 = {
    "                                        -w",
    "/                  \\ /                 \\  ",
    "| 1       1       r| | t + 4         7 |  ",
    "|--- + ------- + 7 |*|------- + y + ---|  ",
    "| x     y*500      | |   y           6 |  ",
    "\\                  / \\                 /  "
};

std::vector<std::string> s4 = { "1" };

std::vector<std::string> s5 = { "1.000000000000000000000000000000000000000000000000" };

std::vector<Stripe> vs = {
    { {"123",s2}, false,  (int)s2.size(), (int)s2[0].length() },
    { {"123",s3}, true,   (int)s3.size(), (int)s3[0].length() },
    { {"123",s1}, false,  (int)s1.size(), (int)s1[0].length() },
    { {"123",s1}, true,   (int)s1.size(), (int)s1[0].length() },
    { {"123",s3}, false,  (int)s3.size(), (int)s3[0].length() },
    { {"123",s1}, true,   (int)s1.size(), (int)s1[0].length() },
    { {"123",s2}, false,  (int)s2.size(), (int)s2[0].length() },
    { {"123",s1}, true,   (int)s1.size(), (int)s1[0].length() },
    { {"123",s1}, false,  (int)s1.size(), (int)s1[0].length() },
    { {"123",s2}, true,   (int)s2.size(), (int)s2[0].length() },
    { {"123",s3}, false,  (int)s3.size(), (int)s3[0].length() },
    { {"123",s3}, true,   (int)s3.size(), (int)s3[0].length() },
    { {"123",s1}, false,  (int)s1.size(), (int)s1[0].length() },
    { {"123",s4}, true,   (int)s4.size(), (int)s4[0].length() },
    { {"123",s5}, false,  (int)s5.size(), (int)s5[0].length() },
};

int _main(int argc, char* argv[])
{
    initscr();
    SCOPE_EXIT( endwin() )
    raw();
    nonl();
    noecho();
    keypad(stdscr, TRUE);
    draw_stripes( -1, vs );
    int ch;
    int highlight = -1;
    int height = 0, width = 0;
    getmaxyx( stdscr, height, width );
    Input in( width-2 );
    bool editing = true;
    move( height-1, 1 );
    while( (ch = getch()) != (int)'q' )
    {
        char const* name = keyname( ch );
        ASSERT( strlen( name ) > 0 )
        bool ctrl = (name[0] == '^' && strlen( name ) > 1);
        mvprintw( 0, 0, "%x    ", ch );
        mvprintw( 1, 0, "%s    ", name );
        mvprintw( 2, 0, "%x    ", '\n' );
        //ASSERT( (char)(ch & 0xff) != 'K' )
        if( ch == KEY_UP || (ctrl && name[1] == 'K') ) {
            highlight += 1;
            editing = false;
        }
        else if ( ch == KEY_DOWN || (ctrl && name[1] == 'J') ) {
            highlight -= 1;
            if( highlight < -1 )
                highlight = -1;
            if( highlight == -1 )
                editing = true;
        }
        else if( ch == '\n' || ch == '\r' ) {
            if( editing ) {
                std::string const& str = in.get_string();
                if( !str.empty() ) {
                    Stripe s({ {str,{str}}, true, (int)1, (int)str.length() });
                    vs.push_back( s );
                    Stripe s2({ {str,{str}}, false, (int)1, (int)str.length() });
                    vs.push_back( s2 );
                    in.clear();
                }
            }
            else {
                std::string to_insert = vs[vs.size() - highlight - 1].e.one_line;
                in.paste( to_insert );
                highlight = -1;
                editing = true;
            }
        }
        else {
            if( editing )
                in.key_press( ch );
        }
        draw_stripes( highlight, vs );
        in.draw( height-1, 1 );
        move( height-1, 1+in.get_cursor() );
        refresh();
    }
    return 0;
}

int main( int argc, char* argv[] )
{
    try {
        return _main(argc, argv);
    } catch( std::exception const& e ) {
        std::cout << "exception:" << e.what() << std::endl;
        return 1;
    }
}
<commit_msg>Add more asserts<commit_after>//// Fancy ncurses terminal for calculators
//// Author: David P. Sicilia, June 2016

#include <ncurses.h>
#include <string>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <iostream>
#include <string.h>

#include "assert.hpp"
#include "scope_exit.hpp"
#include "input.hpp"

struct Entry
{
    std::string one_line;
    std::vector<std::string> grid;
};

struct Stripe
{
    Entry e;
    bool is_left;
    int y;
    int x;
};

auto render_stripe( int width, Stripe const& s ) -> std::vector<std::string>
{
    ASSERT( s.x >= 0 )
    ASSERT( s.y >= 0 )
    auto out = std::vector<std::string>( s.y+2 );
    int start_x = s.is_left ? 1 : width-1-s.x;
    ASSERT( start_x >= 0 )
    auto pad = std::string( start_x, ' ' );
    ASSERT( width-start_x-s.x >= 0 )
    auto end_pad = std::string( width-start_x-s.x, ' ' );
    for( int i = 0; i < s.y; ++i )
        out[i+1] = pad + s.e.grid[i] + end_pad;
    out[0]     = pad + std::string( s.x, ' ' ) + end_pad;
    out[s.y+1] = pad + std::string( s.x, ' ' ) + end_pad;
    return out;
}

auto draw_stripe( int width, int start_y, bool highlight, Stripe const& s ) -> void
{
    auto text = render_stripe( width, s );
    if( highlight ) attron( A_REVERSE );
    for( int i = text.size(); i > 0; --i ) {
        if( start_y-i < 0 )
            break;
        ASSERT( start_y-text.size()+i >= 0 )
        mvprintw( start_y-text.size()+i, 0, text[i-1].c_str() );
    }
    if( highlight ) attroff( A_REVERSE );
}

auto draw_stripes( int highlight, std::vector<Stripe> const& v ) -> void
{
    int height = 0, width = 0;
    getmaxyx( stdscr, height, width );
    (void)height;
    int start_y = height-2;
    ASSERT( start_y >= 0 )
    int highlight_j = v.size() - highlight;
    ASSERT( highlight_j >= 0 )
    for( int j = v.size(); j > 0; --j ) {
        if( start_y < 0 )
            break;
        Stripe const& s = v[j-1];
        bool highlight = (j == highlight_j);
        draw_stripe( width, start_y, highlight, s );
        start_y -= (s.y+2);
    }
}

std::vector<std::string> s1 = {
    "  1 + 2  ",
    "---------",
    "      5  ",
    " 3 + --- ",
    "      6  "
};

std::vector<std::string> s2 = {
    "     1     0.002     r    ",
    "    --- + ------- + 7     ",
    "     x       y            ",
    "--------------------------",
    "                        w ",
    " /                     \\  ",
    " |     1     4 + t     |  ",
    " |1 + --- + ------- + y|  ",
    " |     6       y       |  ",
    " \\                     /  "
};

std::vector<std::string> s3 = {
    "                                        -w",
    "/                  \\ /                 \\  ",
    "| 1       1       r| | t + 4         7 |  ",
    "|--- + ------- + 7 |*|------- + y + ---|  ",
    "| x     y*500      | |   y           6 |  ",
    "\\                  / \\                 /  "
};

std::vector<std::string> s4 = { "1" };

std::vector<std::string> s5 = { "1.000000000000000000000000000000000000000000000000" };

std::vector<Stripe> vs = {
    { {"123",s2}, false,  (int)s2.size(), (int)s2[0].length() },
    { {"123",s3}, true,   (int)s3.size(), (int)s3[0].length() },
    { {"123",s1}, false,  (int)s1.size(), (int)s1[0].length() },
    { {"123",s1}, true,   (int)s1.size(), (int)s1[0].length() },
    { {"123",s3}, false,  (int)s3.size(), (int)s3[0].length() },
    { {"123",s1}, true,   (int)s1.size(), (int)s1[0].length() },
    { {"123",s2}, false,  (int)s2.size(), (int)s2[0].length() },
    { {"123",s1}, true,   (int)s1.size(), (int)s1[0].length() },
    { {"123",s1}, false,  (int)s1.size(), (int)s1[0].length() },
    { {"123",s2}, true,   (int)s2.size(), (int)s2[0].length() },
    { {"123",s3}, false,  (int)s3.size(), (int)s3[0].length() },
    { {"123",s3}, true,   (int)s3.size(), (int)s3[0].length() },
    { {"123",s1}, false,  (int)s1.size(), (int)s1[0].length() },
    { {"123",s4}, true,   (int)s4.size(), (int)s4[0].length() },
    { {"123",s5}, false,  (int)s5.size(), (int)s5[0].length() },
};

int _main(int argc, char* argv[])
{
    initscr();
    SCOPE_EXIT( endwin() )
    raw();
    nonl();
    noecho();
    keypad(stdscr, TRUE);
    draw_stripes( -1, vs );
    int ch;
    int highlight = -1;
    int height = 0, width = 0;
    getmaxyx( stdscr, height, width );
    Input in( width-2 );
    bool editing = true;
    move( height-1, 1 );
    while( (ch = getch()) != (int)'q' )
    {
        char const* name = keyname( ch );
        ASSERT( strlen( name ) > 0 )
        bool ctrl = (name[0] == '^' && strlen( name ) > 1);
        mvprintw( 0, 0, "%x    ", ch );
        mvprintw( 1, 0, "%s    ", name );
        mvprintw( 2, 0, "%x    ", '\n' );
        //ASSERT( (char)(ch & 0xff) != 'K' )
        if( ch == KEY_UP || (ctrl && name[1] == 'K') ) {
            highlight += 1;
            editing = false;
        }
        else if ( ch == KEY_DOWN || (ctrl && name[1] == 'J') ) {
            highlight -= 1;
            if( highlight < -1 )
                highlight = -1;
            if( highlight == -1 )
                editing = true;
        }
        else if( ch == '\n' || ch == '\r' ) {
            if( editing ) {
                std::string const& str = in.get_string();
                if( !str.empty() ) {
                    Stripe s({ {str,{str}}, true, (int)1, (int)str.length() });
                    vs.push_back( s );
                    Stripe s2({ {str,{str}}, false, (int)1, (int)str.length() });
                    vs.push_back( s2 );
                    in.clear();
                }
            }
            else {
                std::string to_insert = vs[vs.size() - highlight - 1].e.one_line;
                in.paste( to_insert );
                highlight = -1;
                editing = true;
            }
        }
        else {
            if( editing )
                in.key_press( ch );
        }
        draw_stripes( highlight, vs );
        in.draw( height-1, 1 );
        move( height-1, 1+in.get_cursor() );
        refresh();
    }
    return 0;
}

int main( int argc, char* argv[] )
{
    try {
        return _main(argc, argv);
    } catch( std::exception const& e ) {
        std::cout << "exception:" << e.what() << std::endl;
        return 1;
    }
}
<|endoftext|>


<commit_before>/*
 * Medical Image Registration ToolKit (MIRTK)
 *
 * Copyright 2008-2015 Imperial College London
 * Copyright 2008-2013 Daniel Rueckert, Julia Schnabel
 * Copyright 2013-2015 Andreas Schuh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <mirtkVoxel.h>

namespace mirtk {

// -----------------------------------------------------------------------------
template <> string ToString(const ImageDataType &value, int w, char c, bool left)
{
  const char *str = "unknown";
  switch (value) {
    case MIRTK_VOXEL_CHAR:           str = "char"; break;
    case MIRTK_VOXEL_UNSIGNED_CHAR:  str = "uchar"; break;
    case MIRTK_VOXEL_SHORT:          str = "short"; break;
    case MIRTK_VOXEL_UNSIGNED_SHORT: str = "ushort"; break;
    case MIRTK_VOXEL_INT:            str = "int"; break;
    case MIRTK_VOXEL_UNSIGNED_INT:   str = "uint"; break;
    case MIRTK_VOXEL_FLOAT:          str = "float"; break;
    case MIRTK_VOXEL_DOUBLE:         str = "double"; break;
    case MIRTK_VOXEL_RGB:            str = "RGB"; break;
    case MIRTK_VOXEL_FLOAT1:         str = "float1"; break;
    case MIRTK_VOXEL_FLOAT2:         str = "float2"; break;
    case MIRTK_VOXEL_FLOAT3:         str = "float3"; break;
    case MIRTK_VOXEL_FLOAT4:         str = "float4"; break;
    case MIRTK_VOXEL_FLOAT1x1:       str = "float1x1"; break;
    case MIRTK_VOXEL_FLOAT2x2:       str = "float2x2"; break;
    case MIRTK_VOXEL_FLOAT3x3:       str = "float3x3"; break;
    case MIRTK_VOXEL_FLOAT3x4:       str = "float3x4"; break;
    case MIRTK_VOXEL_FLOAT4x4:       str = "float4x4"; break;
    case MIRTK_VOXEL_DOUBLE1:        str = "double1"; break;
    case MIRTK_VOXEL_DOUBLE2:        str = "double2"; break;
    case MIRTK_VOXEL_DOUBLE3:        str = "double3"; break;
    case MIRTK_VOXEL_DOUBLE4:        str = "double4"; break;
    case MIRTK_VOXEL_DOUBLE1x1:      str = "double1x1"; break;
    case MIRTK_VOXEL_DOUBLE2x2:      str = "double2x2"; break;
    case MIRTK_VOXEL_DOUBLE3x3:      str = "double3x3"; break;
    case MIRTK_VOXEL_DOUBLE3x4:      str = "double3x4"; break;
    case MIRTK_VOXEL_DOUBLE4x4:      str = "double4x4"; break;
    default:                         str = "unknown"; break;
  }
  return ToString(str, c, w, left);
}

// -----------------------------------------------------------------------------
template <> bool FromString(const char *str, ImageDataType &value)
{
  value = static_cast<ImageDataType>(MIRKT_VOXEL_LAST - 1);
  while (value != MIRTK_VOXEL_UNKNOWN) {
    if (ToString(value) == str) break;
    value = static_cast<ImageDataType>(value - 1);
  }
  return value != MIRTK_VOXEL_UNKNOWN;
}

// -----------------------------------------------------------------------------
int DataTypeSize(int type)
{
  switch (type){
    case MIRTK_VOXEL_CHAR:           return sizeof(char);
    case MIRTK_VOXEL_UNSIGNED_CHAR:  return sizeof(unsigned char);
    case MIRTK_VOXEL_SHORT:          return sizeof(short);
    case MIRTK_VOXEL_UNSIGNED_SHORT: return sizeof(unsigned short);
    case MIRTK_VOXEL_INT:            return sizeof(int);
    case MIRTK_VOXEL_UNSIGNED_INT:   return sizeof(unsigned int);
    case MIRTK_VOXEL_FLOAT:          return sizeof(float);
    case MIRTK_VOXEL_DOUBLE:         return sizeof(double);
    case MIRTK_VOXEL_FLOAT1:         return sizeof(float1);
    case MIRTK_VOXEL_FLOAT2:         return sizeof(float2);
    case MIRTK_VOXEL_FLOAT3:         return sizeof(float3);
    case MIRTK_VOXEL_FLOAT4:         return sizeof(float4);
    case MIRTK_VOXEL_FLOAT2x2:       return sizeof(float2x2);
    case MIRTK_VOXEL_FLOAT3x3:       return sizeof(float3x3);
    case MIRTK_VOXEL_FLOAT3x4:       return sizeof(float3x4);
    case MIRTK_VOXEL_FLOAT4x4:       return sizeof(float4x4);
    case MIRTK_VOXEL_DOUBLE1:        return sizeof(double1);
    case MIRTK_VOXEL_DOUBLE2:        return sizeof(double2);
    case MIRTK_VOXEL_DOUBLE3:        return sizeof(double3);
    case MIRTK_VOXEL_DOUBLE4:        return sizeof(double4);
    case MIRTK_VOXEL_DOUBLE2x2:      return sizeof(double2x2);
    case MIRTK_VOXEL_DOUBLE3x3:      return sizeof(double3x3);
    case MIRTK_VOXEL_DOUBLE3x4:      return sizeof(double3x4);
    case MIRTK_VOXEL_DOUBLE4x4:      return sizeof(double4x4);
    default:                         return 0;
  }
}

} // namespace mirtk
<commit_msg>fix: Conversion of ImageDataType to string [Image]<commit_after>/*
 * Medical Image Registration ToolKit (MIRTK)
 *
 * Copyright 2008-2015 Imperial College London
 * Copyright 2008-2013 Daniel Rueckert, Julia Schnabel
 * Copyright 2013-2015 Andreas Schuh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <mirtkVoxel.h>

namespace mirtk {

// -----------------------------------------------------------------------------
template <> string ToString(const ImageDataType &value, int w, char c, bool left)
{
  const char *str = "unknown";
  switch (value) {
    case MIRTK_VOXEL_CHAR:           str = "char"; break;
    case MIRTK_VOXEL_UNSIGNED_CHAR:  str = "uchar"; break;
    case MIRTK_VOXEL_SHORT:          str = "short"; break;
    case MIRTK_VOXEL_UNSIGNED_SHORT: str = "ushort"; break;
    case MIRTK_VOXEL_INT:            str = "int"; break;
    case MIRTK_VOXEL_UNSIGNED_INT:   str = "uint"; break;
    case MIRTK_VOXEL_FLOAT:          str = "float"; break;
    case MIRTK_VOXEL_DOUBLE:         str = "double"; break;
    case MIRTK_VOXEL_RGB:            str = "RGB"; break;
    case MIRTK_VOXEL_FLOAT1:         str = "float1"; break;
    case MIRTK_VOXEL_FLOAT2:         str = "float2"; break;
    case MIRTK_VOXEL_FLOAT3:         str = "float3"; break;
    case MIRTK_VOXEL_FLOAT4:         str = "float4"; break;
    case MIRTK_VOXEL_FLOAT1x1:       str = "float1x1"; break;
    case MIRTK_VOXEL_FLOAT2x2:       str = "float2x2"; break;
    case MIRTK_VOXEL_FLOAT3x3:       str = "float3x3"; break;
    case MIRTK_VOXEL_FLOAT3x4:       str = "float3x4"; break;
    case MIRTK_VOXEL_FLOAT4x4:       str = "float4x4"; break;
    case MIRTK_VOXEL_DOUBLE1:        str = "double1"; break;
    case MIRTK_VOXEL_DOUBLE2:        str = "double2"; break;
    case MIRTK_VOXEL_DOUBLE3:        str = "double3"; break;
    case MIRTK_VOXEL_DOUBLE4:        str = "double4"; break;
    case MIRTK_VOXEL_DOUBLE1x1:      str = "double1x1"; break;
    case MIRTK_VOXEL_DOUBLE2x2:      str = "double2x2"; break;
    case MIRTK_VOXEL_DOUBLE3x3:      str = "double3x3"; break;
    case MIRTK_VOXEL_DOUBLE3x4:      str = "double3x4"; break;
    case MIRTK_VOXEL_DOUBLE4x4:      str = "double4x4"; break;
    default:                         str = "unknown"; break;
  }
  return ToString(str, w, c, left);
}

// -----------------------------------------------------------------------------
template <> bool FromString(const char *str, ImageDataType &value)
{
  value = static_cast<ImageDataType>(MIRKT_VOXEL_LAST - 1);
  while (value != MIRTK_VOXEL_UNKNOWN) {
    if (ToString(value) == str) break;
    value = static_cast<ImageDataType>(value - 1);
  }
  return value != MIRTK_VOXEL_UNKNOWN;
}

// -----------------------------------------------------------------------------
int DataTypeSize(int type)
{
  switch (type){
    case MIRTK_VOXEL_CHAR:           return sizeof(char);
    case MIRTK_VOXEL_UNSIGNED_CHAR:  return sizeof(unsigned char);
    case MIRTK_VOXEL_SHORT:          return sizeof(short);
    case MIRTK_VOXEL_UNSIGNED_SHORT: return sizeof(unsigned short);
    case MIRTK_VOXEL_INT:            return sizeof(int);
    case MIRTK_VOXEL_UNSIGNED_INT:   return sizeof(unsigned int);
    case MIRTK_VOXEL_FLOAT:          return sizeof(float);
    case MIRTK_VOXEL_DOUBLE:         return sizeof(double);
    case MIRTK_VOXEL_FLOAT1:         return sizeof(float1);
    case MIRTK_VOXEL_FLOAT2:         return sizeof(float2);
    case MIRTK_VOXEL_FLOAT3:         return sizeof(float3);
    case MIRTK_VOXEL_FLOAT4:         return sizeof(float4);
    case MIRTK_VOXEL_FLOAT2x2:       return sizeof(float2x2);
    case MIRTK_VOXEL_FLOAT3x3:       return sizeof(float3x3);
    case MIRTK_VOXEL_FLOAT3x4:       return sizeof(float3x4);
    case MIRTK_VOXEL_FLOAT4x4:       return sizeof(float4x4);
    case MIRTK_VOXEL_DOUBLE1:        return sizeof(double1);
    case MIRTK_VOXEL_DOUBLE2:        return sizeof(double2);
    case MIRTK_VOXEL_DOUBLE3:        return sizeof(double3);
    case MIRTK_VOXEL_DOUBLE4:        return sizeof(double4);
    case MIRTK_VOXEL_DOUBLE2x2:      return sizeof(double2x2);
    case MIRTK_VOXEL_DOUBLE3x3:      return sizeof(double3x3);
    case MIRTK_VOXEL_DOUBLE3x4:      return sizeof(double3x4);
    case MIRTK_VOXEL_DOUBLE4x4:      return sizeof(double4x4);
    default:                         return 0;
  }
}

} // namespace mirtk
<|endoftext|>


<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2009 Sage Weil <sage@newdream.net>
 *
 * This 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.  See file COPYING.
 *
 */

using namespace std;

#include "common/config.h"

#include "common/ConfUtils.h"
#include "common/ceph_argparse.h"
#include "global/global_context.h"
#include "global/global_init.h"
#include "auth/Crypto.h"
#include "auth/Auth.h"
#include "auth/KeyRing.h"

#include <sstream>

void usage()
{
  cout << "usage: cauthtool keyringfile [OPTIONS]...\n"
       << "where the options are:\n"
       << "  -l, --list                    will list all keys and capabilities present in\n"
       << "                                the keyring\n"
       << "  -p, --print                   will print an encoded key for the specified\n"
       << "                                entityname. This is suitable for the\n"
       << "                                'mount -o secret=..' argument\n"
       << "  -C, --create-keyring          will create a new keyring, overwriting any\n"
       << "                                existing keyringfile\n"
       << "  --gen-key                     will generate a new secret key for the\n"
       << "                                specified entityname\n"
       << "  --add-key                     will add an encoded key to the keyring\n"
       << "  --cap subsystem capability    will set the capability for given subsystem\n"
       << "  --caps capsfile               will set all of capabilities associated with a\n"
       << "                                given key, for all subsystems\n"
       << "  -b, --bin                     will create a binary formatted keyring" << std::endl;
  exit(1);
}

int main(int argc, const char **argv)
{
  vector<const char*> args;
  argv_to_vec(argc, argv, args);
  env_to_vec(args);
  DEFINE_CONF_VARS(usage);

  global_init(args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY,
	      CINIT_FLAG_NO_DEFAULT_CONFIG_FILE);
  common_init_finish(g_ceph_context);
  EntityName ename(g_conf->name);

  const char *me = argv[0];

  const char *fn = 0;
  bool gen_key = false;
  bool gen_print_key = false;
  const char *add_key = 0;
  bool list = false;
  bool print_key = false;
  bool create_keyring = false;
  const char *caps_fn = NULL;
  const char *import_keyring = NULL;
  bool set_auid = false;
  uint64_t auid = CEPH_AUTH_UID_DEFAULT;
  map<string,bufferlist> caps;
  bool bin_keyring = false;

  FOR_EACH_ARG(args) {
    if (CEPH_ARGPARSE_EQ("gen-key", 'g')) {
      CEPH_ARGPARSE_SET_ARG_VAL(&gen_key, OPT_BOOL);
    } else if (CEPH_ARGPARSE_EQ("gen-print-key", '\0')) {
      CEPH_ARGPARSE_SET_ARG_VAL(&gen_print_key, OPT_BOOL);
    } else if (CEPH_ARGPARSE_EQ("add-key", 'a')) {
      CEPH_ARGPARSE_SET_ARG_VAL(&add_key, OPT_STR);
    } else if (CEPH_ARGPARSE_EQ("list", 'l')) {
      CEPH_ARGPARSE_SET_ARG_VAL(&list, OPT_BOOL);
    } else if (CEPH_ARGPARSE_EQ("caps", '\0')) {
      CEPH_ARGPARSE_SET_ARG_VAL(&caps_fn, OPT_STR);
    } else if (CEPH_ARGPARSE_EQ("cap", '\0')) {
      const char *key, *val;
      CEPH_ARGPARSE_SET_ARG_VAL(&key, OPT_STR);
      CEPH_ARGPARSE_SET_ARG_VAL(&val, OPT_STR);
      ::encode(val, caps[key]);
    } else if (CEPH_ARGPARSE_EQ("print-key", 'p')) {
      CEPH_ARGPARSE_SET_ARG_VAL(&print_key, OPT_BOOL);
    } else if (CEPH_ARGPARSE_EQ("create-keyring", '\0')) {
      CEPH_ARGPARSE_SET_ARG_VAL(&create_keyring, OPT_BOOL);
    } else if (CEPH_ARGPARSE_EQ("import-keyring", '\0')) {
      CEPH_ARGPARSE_SET_ARG_VAL(&import_keyring, OPT_STR);
    } else if (CEPH_ARGPARSE_EQ("set-uid", 'u')) {
      CEPH_ARGPARSE_SET_ARG_VAL(&auid, OPT_LONGLONG);
      set_auid = true;
    } else if (CEPH_ARGPARSE_EQ("bin", 'b')) {
      CEPH_ARGPARSE_SET_ARG_VAL(&bin_keyring, OPT_BOOL);
    } else if (!fn) {
      fn = args[i];
    } else
      usage();
  }
  if (!fn && !gen_print_key) {
    cerr << me << ": must specify filename" << std::endl;
    usage();
  }
  if (!(gen_key ||
	gen_print_key ||
	add_key ||
	list ||
	caps_fn ||
	caps.size() ||
	set_auid ||
	print_key ||
	create_keyring ||
	import_keyring)) {
    cerr << "no command specified" << std::endl;
    usage();
  }
  if (gen_key && add_key) {
    cerr << "can't both gen_key and add_key" << std::endl;
    usage();
  }

  if (gen_print_key) {
    CryptoKey key;
    key.create(g_ceph_context, CEPH_CRYPTO_AES);
    cout << key << std::endl;
    return 0;
  }

  // keyring --------
  bool modified = false;
  KeyRing keyring;

  bufferlist bl;
  int r = 0;
  if (create_keyring) {
    cout << "creating " << fn << std::endl;
    modified = true;
  } else {
    std::string err;
    r = bl.read_file(fn, &err);
    if (r >= 0) {
      try {
	bufferlist::iterator iter = bl.begin();
	::decode(keyring, iter);
      } catch (const buffer::error &err) {
	cerr << "error reading file " << fn << std::endl;
	exit(1);
      }
    } else {
      cerr << "can't open " << fn << ": " << err << std::endl;
      exit(1);
    }
  }

  // write commands
  if (import_keyring) {
    KeyRing other;
    bufferlist obl;
    std::string err;
    int r = obl.read_file(import_keyring, &err);
    if (r >= 0) {
      try {
	bufferlist::iterator iter = obl.begin();
	::decode(other, iter);
      } catch (const buffer::error &err) {
	cerr << "error reading file " << import_keyring << std::endl;
	exit(1);
      }

      cout << "importing contents of " << import_keyring << " into " << fn << std::endl;
      //other.print(cout);
      keyring.import(g_ceph_context, other);
      modified = true;
    } else {
      cerr << "can't open " << import_keyring << ": " << err << std::endl;
      exit(1);
    }
  }
  if (gen_key) {
    EntityAuth eauth;
    eauth.key.create(g_ceph_context, CEPH_CRYPTO_AES);
    keyring.add(ename, eauth);
    modified = true;
  }
  if (add_key) {
    EntityAuth eauth;
    string ekey(add_key);
    try {
      eauth.key.decode_base64(ekey);
    } catch (const buffer::error &err) {
      cerr << "can't decode key '" << add_key << "'" << std::endl;
      exit(1);
    }
    keyring.add(ename, eauth);
    modified = true;
    cout << "added entity " << ename << " auth " << eauth << std::endl;
  }
  if (caps_fn) {
    ConfFile cf;
    std::deque<std::string> parse_errors;
    if (cf.parse_file(caps_fn, &parse_errors) != 0) {
      cerr << "could not parse caps file " << caps_fn << std::endl;
      exit(1);
    }
    complain_about_parse_errors(g_ceph_context, &parse_errors);
    map<string, bufferlist> caps;
    const char *key_names[] = { "mon", "osd", "mds", NULL };
    for (int i=0; key_names[i]; i++) {
      std::string val;
      if (cf.read("global", key_names[i], val) == 0) {
        bufferlist bl;
        ::encode(val, bl);
        string s(key_names[i]);
        caps[s] = bl;
      }
    }
    keyring.set_caps(ename, caps);
    modified = true;
  }
  if (caps.size()) {
    keyring.set_caps(ename, caps);
    modified = true;
  }
  if (set_auid) {
    keyring.set_uid(ename, auid);
    modified = true;
  }

  // read commands
  if (list) {
    keyring.print(cout);
  }
  if (print_key) {
    CryptoKey key;
    if (keyring.get_secret(ename, key)) {
      cout << key << std::endl;
    } else {
      cerr << "entity " << ename << " not found" << std::endl;
    }
  }

  // write result?
  if (modified) {
    bufferlist bl;
    if (bin_keyring) {
      ::encode(keyring, bl);
    } else {
      keyring.encode_plaintext(bl);
    }
    r = bl.write_file(fn, 0600);
    if (r < 0) {
      cerr << "could not write " << fn << std::endl;
    }
    //cout << "wrote " << bl.length() << " bytes to " << fn << std::endl;
  }

  return 0;
}
<commit_msg>cauthtool: convert to new-style arg parsing<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2009 Sage Weil <sage@newdream.net>
 *
 * This 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.  See file COPYING.
 *
 */

using namespace std;

#include "common/config.h"
#include "common/strtol.h"

#include "common/ConfUtils.h"
#include "common/ceph_argparse.h"
#include "global/global_context.h"
#include "global/global_init.h"
#include "auth/Crypto.h"
#include "auth/Auth.h"
#include "auth/KeyRing.h"

#include <sstream>

void usage()
{
  cout << "usage: cauthtool keyringfile [OPTIONS]...\n"
       << "where the options are:\n"
       << "  -l, --list                    will list all keys and capabilities present in\n"
       << "                                the keyring\n"
       << "  -p, --print                   will print an encoded key for the specified\n"
       << "                                entityname. This is suitable for the\n"
       << "                                'mount -o secret=..' argument\n"
       << "  -C, --create-keyring          will create a new keyring, overwriting any\n"
       << "                                existing keyringfile\n"
       << "  --gen-key                     will generate a new secret key for the\n"
       << "                                specified entityname\n"
       << "  --add-key                     will add an encoded key to the keyring\n"
       << "  --cap subsystem capability    will set the capability for given subsystem\n"
       << "  --caps capsfile               will set all of capabilities associated with a\n"
       << "                                given key, for all subsystems\n"
       << "  -b, --bin                     will create a binary formatted keyring" << std::endl;
  exit(1);
}

int main(int argc, const char **argv)
{
  vector<const char*> args;
  argv_to_vec(argc, argv, args);
  env_to_vec(args);

  bool gen_key = false;
  bool gen_print_key = false;
  std::string add_key;
  bool list = false;
  bool print_key = false;
  bool create_keyring = false;
  std::string caps_fn;
  std::string import_keyring;
  bool set_auid = false;
  uint64_t auid = CEPH_AUTH_UID_DEFAULT;
  map<string,bufferlist> caps;
  bool bin_keyring = false;
  std::string fn;

  global_init(args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY,
	      CINIT_FLAG_NO_DEFAULT_CONFIG_FILE);
  std::vector<const char*>::iterator i;
  for (i = args.begin(); i != args.end(); ) {
    std::string val;
    if (ceph_argparse_double_dash(args, i)) {
      break;
    } else if (ceph_argparse_flag(args, i, "-g", "--gen-key", (char*)NULL)) {
      gen_key = true;
    } else if (ceph_argparse_flag(args, i, "--gen-print-key", (char*)NULL)) {
      gen_print_key = true;
    } else if (ceph_argparse_witharg(args, i, &val, "-a", "--add-key", (char*)NULL)) {
      add_key = val;
    } else if (ceph_argparse_flag(args, i, &val, "-l", "--list", (char*)NULL)) {
      list = true;
    } else if (ceph_argparse_witharg(args, i, &val, "--caps", (char*)NULL)) {
      caps_fn = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--cap", (char*)NULL)) {
      std::string my_key = val;
      if (i == args.end()) {
	cerr << "must give two arguments to --cap: key and val." << std::endl;
	exit(1);
      }
      std::string my_val = *i;
      ++i;
      ::encode(my_val, caps[my_key]);
    } else if (ceph_argparse_flag(args, i, "-p", "--print-key", (char*)NULL)) {
      print_key = true;
    } else if (ceph_argparse_flag(args, i, "--create-keyring", (char*)NULL)) {
      create_keyring = true;
    } else if (ceph_argparse_witharg(args, i, &val, "--import-keyring", (char*)NULL)) {
      import_keyring = val;
    } else if (ceph_argparse_witharg(args, i, &val, "-u", "--set-uid", (char*)NULL)) {
      std::string err;
      auid = strict_strtoll(val.c_str(), 10, &err);
      if (!err.empty()) {
	cerr << "error parsing UID: " << err << std::endl;
	exit(1);
      }
      set_auid = true;
    } else if (ceph_argparse_flag(args, i, "-b", "--bin", (char*)NULL)) {
      bin_keyring = true;
    } else if (fn.empty()) {
      fn = *i++;
    } else {
      usage();
    }
  }
  if (fn.empty() && !gen_print_key) {
    cerr << argv[0] << ": must specify filename" << std::endl;
    usage();
  }
  if (!(gen_key ||
	gen_print_key ||
	!add_key.empty() ||
	list ||
	!caps_fn.empty() ||
	caps.size() ||
	set_auid ||
	print_key ||
	create_keyring ||
	!import_keyring.empty())) {
    cerr << "no command specified" << std::endl;
    usage();
  }
  if (gen_key && (!add_key.empty())) {
    cerr << "can't both gen_key and add_key" << std::endl;
    usage();
  }

  common_init_finish(g_ceph_context);
  EntityName ename(g_conf->name);

  if (gen_print_key) {
    CryptoKey key;
    key.create(g_ceph_context, CEPH_CRYPTO_AES);
    cout << key << std::endl;
    return 0;
  }

  // keyring --------
  bool modified = false;
  KeyRing keyring;

  bufferlist bl;
  int r = 0;
  if (create_keyring) {
    cout << "creating " << fn << std::endl;
    modified = true;
  } else {
    std::string err;
    r = bl.read_file(fn.c_str(), &err);
    if (r >= 0) {
      try {
	bufferlist::iterator iter = bl.begin();
	::decode(keyring, iter);
      } catch (const buffer::error &err) {
	cerr << "error reading file " << fn << std::endl;
	exit(1);
      }
    } else {
      cerr << "can't open " << fn << ": " << err << std::endl;
      exit(1);
    }
  }

  // write commands
  if (!import_keyring.empty()) {
    KeyRing other;
    bufferlist obl;
    std::string err;
    int r = obl.read_file(import_keyring.c_str(), &err);
    if (r >= 0) {
      try {
	bufferlist::iterator iter = obl.begin();
	::decode(other, iter);
      } catch (const buffer::error &err) {
	cerr << "error reading file " << import_keyring << std::endl;
	exit(1);
      }

      cout << "importing contents of " << import_keyring << " into " << fn << std::endl;
      //other.print(cout);
      keyring.import(g_ceph_context, other);
      modified = true;
    } else {
      cerr << "can't open " << import_keyring << ": " << err << std::endl;
      exit(1);
    }
  }
  if (gen_key) {
    EntityAuth eauth;
    eauth.key.create(g_ceph_context, CEPH_CRYPTO_AES);
    keyring.add(ename, eauth);
    modified = true;
  }
  if (!add_key.empty()) {
    EntityAuth eauth;
    try {
      eauth.key.decode_base64(add_key);
    } catch (const buffer::error &err) {
      cerr << "can't decode key '" << add_key << "'" << std::endl;
      exit(1);
    }
    keyring.add(ename, eauth);
    modified = true;
    cout << "added entity " << ename << " auth " << eauth << std::endl;
  }
  if (!caps_fn.empty()) {
    ConfFile cf;
    std::deque<std::string> parse_errors;
    if (cf.parse_file(caps_fn, &parse_errors) != 0) {
      cerr << "could not parse caps file " << caps_fn << std::endl;
      exit(1);
    }
    complain_about_parse_errors(g_ceph_context, &parse_errors);
    map<string, bufferlist> caps;
    const char *key_names[] = { "mon", "osd", "mds", NULL };
    for (int i=0; key_names[i]; i++) {
      std::string val;
      if (cf.read("global", key_names[i], val) == 0) {
        bufferlist bl;
        ::encode(val, bl);
        string s(key_names[i]);
        caps[s] = bl;
      }
    }
    keyring.set_caps(ename, caps);
    modified = true;
  }
  if (caps.size()) {
    keyring.set_caps(ename, caps);
    modified = true;
  }
  if (set_auid) {
    keyring.set_uid(ename, auid);
    modified = true;
  }

  // read commands
  if (list) {
    keyring.print(cout);
  }
  if (print_key) {
    CryptoKey key;
    if (keyring.get_secret(ename, key)) {
      cout << key << std::endl;
    } else {
      cerr << "entity " << ename << " not found" << std::endl;
    }
  }

  // write result?
  if (modified) {
    bufferlist bl;
    if (bin_keyring) {
      ::encode(keyring, bl);
    } else {
      keyring.encode_plaintext(bl);
    }
    r = bl.write_file(fn.c_str(), 0600);
    if (r < 0) {
      cerr << "could not write " << fn << std::endl;
    }
    //cout << "wrote " << bl.length() << " bytes to " << fn << std::endl;
  }

  return 0;
}
<|endoftext|>