<commit_before>/*
	sample of move(reg, LABEL);, L(LABEL), putL(LABEL);
*/
#include <stdio.h>
#define XBYAK_NO_OP_NAMES
#include <xbyak/xbyak.h>

const int expectTbl[] = {
	5, 9, 12
};

struct Code : Xbyak::CodeGenerator {
	explicit Code(int mode, size_t size, void *p)
		: Xbyak::CodeGenerator(size, p)
	{
		inLocalLabel();
#ifdef XBYAK64
		const Xbyak::Reg64& a = rax;
		const Xbyak::Reg64& c = rcx;
#ifdef XBYAK64_WIN
		mov(rax, rcx);
#else
		mov(rax, rdi);
#endif
#else
		const Xbyak::Reg32& a = eax;
		const Xbyak::Reg32& c = ecx;
		mov(a, ptr [esp + 4]);
#endif

		switch (mode) {
		case 0:
			mov(c, ".jmp_table");
			lea(c, ptr [c + a * 8]);
			jmp(c);
		align(8);
			L(".jmp_table");
			mov(a, expectTbl[0]);
			ret();
		align(8);
			mov(a, expectTbl[1]);
			ret();
		align(8);
			mov(a, expectTbl[2]);
			ret();
			break;

		case 1:
			/*
				the label for putL is defined when called
			*/
			mov(c, ".jmp_table");
			jmp(ptr [c + a * (int)sizeof(size_t)]);
		L(".label1");
			mov(a, expectTbl[0]);
			jmp(".end");
		L(".label2");
			mov(a, expectTbl[1]);
			jmp(".end");
		L(".label3");
			mov(a, expectTbl[2]);
			jmp(".end");
		L(".end");
			ret();

			/*
				this table should be in code segment
			*/
			align(8);
		L(".jmp_table");
		putL(".label1");
		putL(".label2");
		putL(".label3");
			break;

		case 2:
			/*
				the label for putL is not defined when called
			*/
			jmp(".in");
			align(8);
			/*
				this table should be in code segment
			*/
		L(".jmp_table");
		putL(".label1");
		putL(".label2");
		putL(".label3");
		L(".in");
			mov(c, ".jmp_table");
			jmp(ptr [c + a * (int)sizeof(size_t)]);
		L(".label1");
			mov(a, expectTbl[0]);
			jmp(".end");
		L(".label2");
			mov(a, expectTbl[1]);
			jmp(".end");
		L(".label3");
			mov(a, expectTbl[2]);
			jmp(".end");
		L(".end");
			ret();
			break;
		}
		outLocalLabel();
	}
};

int main()
	try
{
	for (int mode = 0; mode < 3; mode++) {
		printf("mode=%d\n", mode);
		for (int grow = 0; grow < 2; grow++) {
			printf("auto grow=%s\n", grow ? "on" : "off");
			Code c(mode, grow ? 10 : 4096, grow ? Xbyak::AutoGrow : 0);
			int (*f)(int) = c.getCode<int (*)(int)>();
			c.ready();
			for (int i = 0; i < 3; i++) {
				const int a = expectTbl[i];
				const int b = f(i);
				if (a != b) {
					printf("ERR i=%d, a=%d, b=%d\n", i, a, b);
					exit(1);
				}
			}
		}
	}
	puts("ok");
} catch (Xbyak::Error e) {
	printf("ERR %s\n", Xbyak::ConvertErrorToString(e));
}
<commit_msg>add ud2<commit_after>/*
	sample of move(reg, LABEL);, L(LABEL), putL(LABEL);
*/
#include <stdio.h>
#define XBYAK_NO_OP_NAMES
#include <xbyak/xbyak.h>

const int expectTbl[] = {
	5, 9, 12
};

struct Code : Xbyak::CodeGenerator {
	explicit Code(int mode, size_t size, void *p)
		: Xbyak::CodeGenerator(size, p)
	{
		inLocalLabel();
#ifdef XBYAK64
		const Xbyak::Reg64& a = rax;
		const Xbyak::Reg64& c = rcx;
#ifdef XBYAK64_WIN
		mov(rax, rcx);
#else
		mov(rax, rdi);
#endif
#else
		const Xbyak::Reg32& a = eax;
		const Xbyak::Reg32& c = ecx;
		mov(a, ptr [esp + 4]);
#endif

		switch (mode) {
		case 0:
			mov(c, ".jmp_table");
			lea(c, ptr [c + a * 8]);
			jmp(c);
		align(8);
			L(".jmp_table");
			mov(a, expectTbl[0]);
			ret();
		align(8);
			mov(a, expectTbl[1]);
			ret();
		align(8);
			mov(a, expectTbl[2]);
			ret();
			break;

		case 1:
			/*
				the label for putL is defined when called
			*/
			mov(c, ".jmp_table");
			jmp(ptr [c + a * (int)sizeof(size_t)]);
		L(".label1");
			mov(a, expectTbl[0]);
			jmp(".end");
		L(".label2");
			mov(a, expectTbl[1]);
			jmp(".end");
		L(".label3");
			mov(a, expectTbl[2]);
			jmp(".end");
		L(".end");
			ret();
			ud2();

			align(8);
		L(".jmp_table");
		putL(".label1");
		putL(".label2");
		putL(".label3");
			break;

		case 2:
			/*
				the label for putL is not defined when called
			*/
			jmp(".in");
			ud2();
			align(8);
		L(".jmp_table");
		putL(".label1");
		putL(".label2");
		putL(".label3");
		L(".in");
			mov(c, ".jmp_table");
			jmp(ptr [c + a * (int)sizeof(size_t)]);
		L(".label1");
			mov(a, expectTbl[0]);
			jmp(".end");
		L(".label2");
			mov(a, expectTbl[1]);
			jmp(".end");
		L(".label3");
			mov(a, expectTbl[2]);
			jmp(".end");
		L(".end");
			ret();
			break;
		}
		outLocalLabel();
	}
};

int main()
	try
{
	for (int mode = 0; mode < 3; mode++) {
		printf("mode=%d\n", mode);
		for (int grow = 0; grow < 2; grow++) {
			printf("auto grow=%s\n", grow ? "on" : "off");
			Code c(mode, grow ? 10 : 4096, grow ? Xbyak::AutoGrow : 0);
			int (*f)(int) = c.getCode<int (*)(int)>();
			c.ready();
			for (int i = 0; i < 3; i++) {
				const int a = expectTbl[i];
				const int b = f(i);
				if (a != b) {
					printf("ERR i=%d, a=%d, b=%d\n", i, a, b);
					exit(1);
				}
			}
		}
	}
	puts("ok");
} catch (Xbyak::Error e) {
	printf("ERR %s\n", Xbyak::ConvertErrorToString(e));
}
<|endoftext|>


<commit_before><commit_msg>CWorld: Separate enum definition from declaration<commit_after><|endoftext|>


<commit_before>#include <coffee/core/plat/windows/win_core.h>

#include <coffee/core/plat/platform_detect.h>
#include <coffee/core/coffee_macros.h>
#include <mutex>
#include <atomic>

#ifdef COFFEE_WINDOWS
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

namespace Coffee{

void coffee_enable_core_dump()
{
    C_STUBBED("Core dumping");
    //We don't support this yet.
}

namespace CResources{
namespace CFiles{

bool coffee_file_mkdir(cstring dname, bool createParent)
{
    if(!createParent)
    {
        return CreateDirectory(dname,NULL);
    }else{
        cstring_w path = c_cpy_string(dname);
        szptr bufsize = c_strlen(path) + 2;
        path = (cstring_w)c_realloc(path,bufsize);

        path[bufsize - 2] = '\\';
        path[bufsize - 1] = 0;

        //Beware of magic cookies!
        cstring_w folder = (cstring_w)c_calloc(sizeof(byte),255);
        cstring_w end;

        end = strchr(path, L'\\');
        while (end != NULL)
        {
            strncpy(folder,path,end-path+1);
            if (!CreateDirectory(folder, NULL))
            {
                DWORD err = GetLastError();
                if (err != ERROR_ALREADY_EXISTS)
                    cWarning("Error while creating directories: %i",err);
            }
            end = strchr(++end, L'\\');
        }

        c_free(folder);
        c_free(path);
        return false;
    }
}

}

struct CWinFile
{
    HANDLE hd;
    void* data;
};

CWinFile* _winapi_open_file_read(cstring file){
    CWinFile *f = new CWinFile;
    cstring wfname = c_str_replace(file, "/", "\\");
    f->hd = CreateFile(wfname, GENERIC_READ,
                      FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
                      OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    return f;
}
szptr _winapi_file_get_size(CWinFile *fp)
{
    if (fp->hd == INVALID_HANDLE_VALUE)
        return 0;

    LARGE_INTEGER sz;
    szptr ret = 0;
    if (GetFileSizeEx(fp->hd, &sz))
        ret = (sz.LowPart | sz.HighPart << 32);
    return ret;
}
szptr coffee_file_get_size(cstring file)
{
    CWinFile* fp = _winapi_open_file_read(file);

    szptr ret = _winapi_file_get_size(fp);

    CloseHandle(fp->hd);
    delete fp;
    return ret;
}
}
namespace CMemoryManagement{
void* coffee_memory_map_file(cstring filename, szptr offset, szptr size, int*)
{
    CResources::CWinFile* fp = CResources::_winapi_open_file_read(filename);
    szptr len = CResources::_winapi_file_get_size(fp);

    HANDLE map = CreateFileMapping(fp, NULL, PAGE_READONLY, 0, 0, 0);
    if (map == NULL)
    {
        return nullptr;
    }

    void* ptr = MapViewOfFile(map, FILE_MAP_READ, 0, 0, size);

    //Close file handle at some point!
    return ptr;
}
bool coffee_memory_unmap_file(void* ptr, szptr size)
{
    return UnmapViewOfFile(ptr);
}

}

namespace CFunctional {
    namespace CDebugHelpers{
        cstring_w coffee_clock_string()
        {
            cwstring clock_fmt = c_str_wideconvert("HH:mm:ss");

            size_t len = GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT,
                                         TIME_FORCE24HOURFORMAT,
                                         NULL,
                                         clock_fmt,
                                         NULL,
                                         0);
            cwstring_w wstr = (cwstring_w)c_calloc(sizeof(int16),len);
            GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT,
                            TIME_FORCE24HOURFORMAT,
                            NULL,
                            clock_fmt,
                            wstr,
                            len);
            cstring_w str = c_str_narrowconvert(wstr);
            c_free(wstr);
            return str;
        }
        void coffee_clock_free(cstring_w arg)
        {
            c_free(arg);
        }
    }

    struct WindowsPerformanceCounterData {
        WindowsPerformanceCounterData()
        {
            QueryPerformanceFrequency(&freq);
        }

        std::mutex perf_lock;
        LARGE_INTEGER freq;
        std::atomic_bool loaded;
    };

    static WindowsPerformanceCounterData _win_perfcounter_data;

    uint64 _win_api_get_time()
    {
        LARGE_INTEGER tmp;
        QueryPerformanceCounter(&tmp);
        uint64 tick = tmp.QuadPart;
        return (tick*1000000)/_win_perfcounter_data.freq.QuadPart;
    }
}
}

#endif
<commit_msg> - Disable some Windows code<commit_after>#include <coffee/core/plat/windows/win_core.h>

#include <coffee/core/plat/platform_detect.h>
#include <coffee/core/coffee_macros.h>
#include <mutex>
#include <atomic>

#ifdef COFFEE_WINDOWS____
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

namespace Coffee{

void coffee_enable_core_dump()
{
    C_STUBBED("Core dumping");
    //We don't support this yet.
}

namespace CResources{
namespace CFiles{

bool coffee_file_mkdir(cstring dname, bool createParent)
{
    if(!createParent)
    {
        return CreateDirectory(dname,NULL);
    }else{
        cstring_w path = c_cpy_string(dname);
        szptr bufsize = c_strlen(path) + 2;
        path = (cstring_w)c_realloc(path,bufsize);

        path[bufsize - 2] = '\\';
        path[bufsize - 1] = 0;

        //Beware of magic cookies!
        cstring_w folder = (cstring_w)c_calloc(sizeof(byte),255);
        cstring_w end;

        end = strchr(path, L'\\');
        while (end != NULL)
        {
            strncpy(folder,path,end-path+1);
            if (!CreateDirectory(folder, NULL))
            {
                DWORD err = GetLastError();
                if (err != ERROR_ALREADY_EXISTS)
                    cWarning("Error while creating directories: %i",err);
            }
            end = strchr(++end, L'\\');
        }

        c_free(folder);
        c_free(path);
        return false;
    }
}

}

struct CWinFile
{
    HANDLE hd;
    void* data;
};

CWinFile* _winapi_open_file_read(cstring file){
    CWinFile *f = new CWinFile;
    cstring wfname = c_str_replace(file, "/", "\\");
    f->hd = CreateFile(wfname, GENERIC_READ,
                      FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
                      OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    return f;
}
szptr _winapi_file_get_size(CWinFile *fp)
{
    if (fp->hd == INVALID_HANDLE_VALUE)
        return 0;

    LARGE_INTEGER sz;
    szptr ret = 0;
    if (GetFileSizeEx(fp->hd, &sz))
        ret = (sz.LowPart | sz.HighPart << 32);
    return ret;
}
szptr coffee_file_get_size(cstring file)
{
    CWinFile* fp = _winapi_open_file_read(file);

    szptr ret = _winapi_file_get_size(fp);

    CloseHandle(fp->hd);
    delete fp;
    return ret;
}
}
namespace CMemoryManagement{
void* coffee_memory_map_file(cstring filename, szptr offset, szptr size, int*)
{
    CResources::CWinFile* fp = CResources::_winapi_open_file_read(filename);
    szptr len = CResources::_winapi_file_get_size(fp);

    HANDLE map = CreateFileMapping(fp, NULL, PAGE_READONLY, 0, 0, 0);
    if (map == NULL)
    {
        return nullptr;
    }

    void* ptr = MapViewOfFile(map, FILE_MAP_READ, 0, 0, size);

    //Close file handle at some point!
    return ptr;
}
bool coffee_memory_unmap_file(void* ptr, szptr size)
{
    return UnmapViewOfFile(ptr);
}

}

namespace CFunctional {
    namespace CDebugHelpers{
        cstring_w coffee_clock_string()
        {
            cwstring clock_fmt = c_str_wideconvert("HH:mm:ss");

            size_t len = GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT,
                                         TIME_FORCE24HOURFORMAT,
                                         NULL,
                                         clock_fmt,
                                         NULL,
                                         0);
            cwstring_w wstr = (cwstring_w)c_calloc(sizeof(int16),len);
            GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT,
                            TIME_FORCE24HOURFORMAT,
                            NULL,
                            clock_fmt,
                            wstr,
                            len);
            cstring_w str = c_str_narrowconvert(wstr);
            c_free(wstr);
            return str;
        }
        void coffee_clock_free(cstring_w arg)
        {
            c_free(arg);
        }
    }

    struct WindowsPerformanceCounterData {
        WindowsPerformanceCounterData()
        {
            QueryPerformanceFrequency(&freq);
        }

        std::mutex perf_lock;
        LARGE_INTEGER freq;
        std::atomic_bool loaded;
    };

    uint64 _win_api_get_time()
    {
        LARGE_INTEGER tmp;
        QueryPerformanceCounter(&tmp);
        uint64 tick = tmp.QuadPart;
        return (tick*1000000)/_win_perfcounter_data.freq.QuadPart;
    }
}
}

#endif
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGuiBaseApplication.cpp
    created:    7/2/2008
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2008 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGuiBaseApplication.h"
#include <stdlib.h>
#include <string.h>
#include <limits.h>

// setup default-default path
#ifndef CEGUI_SAMPLE_DATAPATH
    #define CEGUI_SAMPLE_DATAPATH "../datafiles"
#endif

/***********************************************************************
    Static / Const data
*************************************************************************/
const char CEGuiBaseApplication::DATAPATH_VAR_NAME[] = "CEGUI_SAMPLE_DATAPATH";

/***********************************************************************
    Return env var value that tells us where data should be
*************************************************************************/
const char* CEGuiBaseApplication::getDataPathPrefix() const
{
    static char dataPathPrefix[PATH_MAX];
    char* envDataPath = 0;

    // get data path from environment var
    envDataPath = getenv(DATAPATH_VAR_NAME);

    // set data path prefix / base directory.  This will
    // be either from an environment variable, or from
    // a compiled in default based on original configure
    // options
    if (envDataPath != 0)
        strcpy(dataPathPrefix, envDataPath);
    else
        strcpy(dataPathPrefix, CEGUI_SAMPLE_DATAPATH);

    return dataPathPrefix;
}
<commit_msg>MOD: Change Sample base applciation so that on tha Mac it successfully fetches the path of the datafiles directory within the app bundles Resources (now we don't have to rely on working directory being unmodified).<commit_after>/***********************************************************************
    filename:   CEGuiBaseApplication.cpp
    created:    7/2/2008
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2008 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGuiBaseApplication.h"
#include <stdlib.h>
#include <string.h>
#include <limits.h>

// setup default-default path
#ifndef CEGUI_SAMPLE_DATAPATH
    #define CEGUI_SAMPLE_DATAPATH "../datafiles"
#endif

/***********************************************************************
    Static / Const data
*************************************************************************/
const char CEGuiBaseApplication::DATAPATH_VAR_NAME[] = "CEGUI_SAMPLE_DATAPATH";

/***********************************************************************
    Return env var value that tells us where data should be
*************************************************************************/
const char* CEGuiBaseApplication::getDataPathPrefix() const
{
    static char dataPathPrefix[PATH_MAX];

#ifdef __APPLE__
    CFURLRef datafilesURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(),
                                                    CFSTR("datafiles"),
                                                    0, 0);
    CFURLGetFileSystemRepresentation(datafilesURL, true,
                                     reinterpret_cast<UInt8*>(dataPathPrefix),
                                     PATH_MAX);
    CFRelease(datafilesURL);
#else
    char* envDataPath = 0;

    // get data path from environment var
    envDataPath = getenv(DATAPATH_VAR_NAME);

    // set data path prefix / base directory.  This will
    // be either from an environment variable, or from
    // a compiled in default based on original configure
    // options
    if (envDataPath != 0)
        strcpy(dataPathPrefix, envDataPath);
    else
        strcpy(dataPathPrefix, CEGUI_SAMPLE_DATAPATH);
#endif

    return dataPathPrefix;
}
<|endoftext|>


<commit_before><commit_msg>fix example<commit_after><|endoftext|>


<commit_before>#include "cute.h"
#include "test_Box.h"

#include "Box.h"

const MatVec<lengthT, 3> box_dimension{10,20,30};
const unsigned DIM3{3};

void emptyBox() {
	Box<3> box { box_dimension };
	ASSERTM("", box.size() == 0 );
}

void boxSize10() {
	Box<3> box { box_dimension, 10 };
	ASSERTM("", box.size() == 10 );
}

void boxAbmessung() {
	Box<3> box { box_dimension };
	ASSERTM("", box.abmessung() == box_dimension);
}

void addBoxSize() {
	unsigned s1 { 10 }, s2 { 15 };
	Box<3> box1{box_dimension, s1}, box2{box_dimension, s2};
	box1.add(box2);
	ASSERTM("", box1.size() == s1 + s2);
}

void randomAccess_read(){
	Kugel<3> k{1, 1};
	Box<3> box{box_dimension,10,k};

	ASSERTM("", box[3] == k);
}

void randomAccess_constRead(){
	Kugel<3> k{1, 1};
	const Box<3> box{box_dimension,10,k};

	ASSERTM("", box[3] == k);
}

void randomAccess_write(){
	Kugel<3> k1{1, 1}, k2{2, 2};
	Box<3> box{box_dimension,10, k1};

	box[3]=k2;
	ASSERTM("", ( box[3] == k2 && box[0] == k1) );
}

// Geht wahrscheinlich wegen Rundung nicht
void wrapPosition() {
	Box<3> box{box_dimension,1};
	MatVec<lengthT,3> pos{-5, -23, 67}, res_pos{5, 17, 7};

	box[0].position(pos);
	box.wrap();
	std::cout << box[0].position() << '\n' << res_pos << '\n';
	ASSERTM("", box[0].position() == res_pos );
}
/*
void kugel_distance() {
	Box<3> box{box_dimension,1};
	MatVec<lengthT,3> pos1{15*m, 17*m, 15*m};
	MatVec<lengthT,3> pos2{1*m, 2*m, 0*m};
	MatVec<lengthT,3> dist{-4*m, 5*m, 15*m};
	Kugel<3> k1{},k2{};
	k1.position(pos1);
	k2.position(pos2);

	std::cout << box.dist(k1,k2) << '\n'<< dist << '\n';
	ASSERTM("", box.dist(k1,k2) == dist && box.dist(k2,k1) == -dist);
}
*/

void box_fastForward_pos() {
	Kugel<3> k{};
	MatVec<velocityT,3> vel{2,30,10};
	MatVec<lengthT,3> res_pos{6,10,0}; //res_pos{3*m,6*m,9*m};

	k.velocity(vel);
	Box<3> box{box_dimension,1,k};

	box.fast_forward(3);
	std::cout << box[0].position() << '\n' << res_pos << '\n';
	ASSERTM("", box[0].position() == res_pos);
}

void box_fastForward_time() {
	Kugel<3> k{};
	MatVec<velocityT,3> vel{2,30,10};
	MatVec<lengthT,3> res_pos{6,10,0}; //res_pos{3*m,6*m,9*m};

	k.velocity(vel);
	Box<3> box{box_dimension,1,k};

	auto dt = 3. * s;
	box.fast_forward(dt);
	ASSERTM("", box.time() == dt );
}

void box_initiate_given_no_rand() {
	MatVec<lengthT,3> pos1 {5}, pos2 {1};
	Box<3> box{box_dimension, 2, Kugel<3>{1, .1}};

	box[0].position(pos1);
	box[1].position(pos2);
	box.initiate();

	ASSERTM("", box[0].position() == pos1 && box[1].position() == pos2);
}

void box_initiate_given_rand() {
	MatVec<lengthT,3> pos {5};
	Box<3> box{box_dimension, 2, Kugel<3>{1, .1}};

	box[0].position(pos);
	box[1].position(pos);
	box.initiate();

	ASSERTM("", box[0].position() != pos || box[1].position() != pos);
}

void box_collision_time_simple() {
	MatVec<lengthT,3> pos{5, 0, 0};
	MatVec<velocityT,3> vel {1, 0, 0};
	Box<3> box{box_dimension, 2, Kugel<3>{4, 1}};

	box[0].position(pos);
	box[0].velocity(vel);
	box.initiate();

	auto coll_time = box.collide();
	ASSERTM("", coll_time == timeT{3});
}

void problem_3_kugeln_Abraham_1() {
	MatVec<lengthT,DIM3> pos_urspr{10, 10, 0};
	MatVec<lengthT,DIM3> pos1{0, -1, 0};
	MatVec<lengthT,DIM3> pos2{0, 2, 0};
	MatVec<lengthT,DIM3> pos3{-4, 2, 0};

	pos1 += pos_urspr; pos2 += pos_urspr; pos3 += pos_urspr;

	MatVec<velocityT,DIM3> vel12{0, 1, 0};
	MatVec<velocityT,DIM3> vel3{1, 0, 0};

	Box<DIM3> box{MatVec<lengthT,DIM3>{20, 20, 20}, 3, Kugel<DIM3>{2_kg, .5_m}};
	box[0].position(pos1); box[0].velocity(vel12);
	box[1].position(pos2); box[1].velocity(-vel12);
	box[2].position(pos3); box[2].velocity(vel3);

	box.initiate();
	box.collide(); box.collide();

	ASSERTM("", box[0].position() == ( MatVec<lengthT,DIM3>{10, 1, 0} ));
}

void problem_3_kugeln_Abraham_2() {
	MatVec<lengthT,DIM3> pos_urspr{10, 10, 0};
	MatVec<lengthT,DIM3> pos1{0, -1, 0};
	MatVec<lengthT,DIM3> pos2{0, 2, 0};
	MatVec<lengthT,DIM3> pos3{-4, 2, 0};
	MatVec<lengthT,DIM3> pos4{5, 2, 0};

	pos1 += pos_urspr; pos2 += pos_urspr;
	pos3 += pos_urspr; pos4 += pos_urspr;

	MatVec<velocityT,DIM3> vel_x{1, 0, 0};
	MatVec<velocityT,DIM3> vel_y{0, 1, 0};

	Box<DIM3> box{MatVec<lengthT,DIM3>{20, 20, 20}, 4, Kugel<DIM3>{2_kg, .5_m}};
	box[0].position(pos1); box[0].velocity(vel_y);
	box[1].position(pos2); box[1].velocity(-vel_y);
	box[2].position(pos3); box[2].velocity(vel_x);
	box[3].position(pos4); box[3].velocity(-vel_x);

	box.initiate();
	box.collide(); box.collide();

	ASSERTM("", box[2].position() == ( MatVec<lengthT,DIM3>{10, 12, 0} ));
}

cute::suite make_suite_Box(){
	cute::suite s;
	s.push_back(CUTE(emptyBox));
	s.push_back(CUTE(boxSize10));
	s.push_back(CUTE(boxAbmessung));
	s.push_back(CUTE(addBoxSize));
	s.push_back(CUTE(randomAccess_read));
	s.push_back(CUTE(randomAccess_constRead));
	s.push_back(CUTE(randomAccess_write));
	s.push_back(CUTE(wrapPosition));
//	s.push_back(CUTE(kugel_distance));
	s.push_back(CUTE(box_fastForward_pos));
	s.push_back(CUTE(box_fastForward_time));
	s.push_back(CUTE(box_initiate_given_no_rand));
	s.push_back(CUTE(box_initiate_given_rand));
	s.push_back(CUTE(box_collision_time_simple));
	s.push_back(CUTE(problem_3_kugeln_Abraham_1));
	s.push_back(CUTE(problem_3_kugeln_Abraham_2));
	return s;
}
<commit_msg>test_Box::problem_3_kugeln_Abraham_3() added same as ...Abraham_2 with additional collision<commit_after>#include "cute.h"
#include "test_Box.h"

#include "Box.h"

const MatVec<lengthT, 3> box_dimension{10,20,30};
const unsigned DIM3{3};

void emptyBox() {
	Box<3> box { box_dimension };
	ASSERTM("", box.size() == 0 );
}

void boxSize10() {
	Box<3> box { box_dimension, 10 };
	ASSERTM("", box.size() == 10 );
}

void boxAbmessung() {
	Box<3> box { box_dimension };
	ASSERTM("", box.abmessung() == box_dimension);
}

void addBoxSize() {
	unsigned s1 { 10 }, s2 { 15 };
	Box<3> box1{box_dimension, s1}, box2{box_dimension, s2};
	box1.add(box2);
	ASSERTM("", box1.size() == s1 + s2);
}

void randomAccess_read(){
	Kugel<3> k{1, 1};
	Box<3> box{box_dimension,10,k};

	ASSERTM("", box[3] == k);
}

void randomAccess_constRead(){
	Kugel<3> k{1, 1};
	const Box<3> box{box_dimension,10,k};

	ASSERTM("", box[3] == k);
}

void randomAccess_write(){
	Kugel<3> k1{1, 1}, k2{2, 2};
	Box<3> box{box_dimension,10, k1};

	box[3]=k2;
	ASSERTM("", ( box[3] == k2 && box[0] == k1) );
}

// Geht wahrscheinlich wegen Rundung nicht
void wrapPosition() {
	Box<3> box{box_dimension,1};
	MatVec<lengthT,3> pos{-5, -23, 67}, res_pos{5, 17, 7};

	box[0].position(pos);
	box.wrap();
	std::cout << box[0].position() << '\n' << res_pos << '\n';
	ASSERTM("", box[0].position() == res_pos );
}
/*
void kugel_distance() {
	Box<3> box{box_dimension,1};
	MatVec<lengthT,3> pos1{15*m, 17*m, 15*m};
	MatVec<lengthT,3> pos2{1*m, 2*m, 0*m};
	MatVec<lengthT,3> dist{-4*m, 5*m, 15*m};
	Kugel<3> k1{},k2{};
	k1.position(pos1);
	k2.position(pos2);

	std::cout << box.dist(k1,k2) << '\n'<< dist << '\n';
	ASSERTM("", box.dist(k1,k2) == dist && box.dist(k2,k1) == -dist);
}
*/

void box_fastForward_pos() {
	Kugel<3> k{};
	MatVec<velocityT,3> vel{2,30,10};
	MatVec<lengthT,3> res_pos{6,10,0}; //res_pos{3*m,6*m,9*m};

	k.velocity(vel);
	Box<3> box{box_dimension,1,k};

	box.fast_forward(3);
	std::cout << box[0].position() << '\n' << res_pos << '\n';
	ASSERTM("", box[0].position() == res_pos);
}

void box_fastForward_time() {
	Kugel<3> k{};
	MatVec<velocityT,3> vel{2,30,10};
	MatVec<lengthT,3> res_pos{6,10,0}; //res_pos{3*m,6*m,9*m};

	k.velocity(vel);
	Box<3> box{box_dimension,1,k};

	auto dt = 3. * s;
	box.fast_forward(dt);
	ASSERTM("", box.time() == dt );
}

void box_initiate_given_no_rand() {
	MatVec<lengthT,3> pos1 {5}, pos2 {1};
	Box<3> box{box_dimension, 2, Kugel<3>{1, .1}};

	box[0].position(pos1);
	box[1].position(pos2);
	box.initiate();

	ASSERTM("", box[0].position() == pos1 && box[1].position() == pos2);
}

void box_initiate_given_rand() {
	MatVec<lengthT,3> pos {5};
	Box<3> box{box_dimension, 2, Kugel<3>{1, .1}};

	box[0].position(pos);
	box[1].position(pos);
	box.initiate();

	ASSERTM("", box[0].position() != pos || box[1].position() != pos);
}

void box_collision_time_simple() {
	MatVec<lengthT,3> pos{5, 0, 0};
	MatVec<velocityT,3> vel {1, 0, 0};
	Box<3> box{box_dimension, 2, Kugel<3>{4, 1}};

	box[0].position(pos);
	box[0].velocity(vel);
	box.initiate();

	auto coll_time = box.collide();
	ASSERTM("", coll_time == timeT{3});
}

void problem_3_kugeln_Abraham_1() {
	MatVec<lengthT,DIM3> pos_urspr{10, 10, 0};
	MatVec<lengthT,DIM3> pos1{0, -1, 0};
	MatVec<lengthT,DIM3> pos2{0, 2, 0};
	MatVec<lengthT,DIM3> pos3{-4, 2, 0};

	pos1 += pos_urspr; pos2 += pos_urspr; pos3 += pos_urspr;

	MatVec<velocityT,DIM3> vel12{0, 1, 0};
	MatVec<velocityT,DIM3> vel3{1, 0, 0};

	Box<DIM3> box{MatVec<lengthT,DIM3>{20, 20, 20}, 3, Kugel<DIM3>{2_kg, .5_m}};
	box[0].position(pos1); box[0].velocity(vel12);
	box[1].position(pos2); box[1].velocity(-vel12);
	box[2].position(pos3); box[2].velocity(vel3);

	box.initiate();
	box.collide(); box.collide();

	ASSERTM("", box[0].position() == ( MatVec<lengthT,DIM3>{10, 1, 0} ));
}

void problem_3_kugeln_Abraham_2() {
	MatVec<lengthT,DIM3> pos_urspr{10, 10, 0};
	MatVec<lengthT,DIM3> pos1{0, -1, 0};
	MatVec<lengthT,DIM3> pos2{0, 2, 0};
	MatVec<lengthT,DIM3> pos3{-4, 2, 0};
	MatVec<lengthT,DIM3> pos4{5, 2, 0};

	pos1 += pos_urspr; pos2 += pos_urspr;
	pos3 += pos_urspr; pos4 += pos_urspr;

	MatVec<velocityT,DIM3> vel_x{1, 0, 0};
	MatVec<velocityT,DIM3> vel_y{0, 1, 0};

	Box<DIM3> box{MatVec<lengthT,DIM3>{20, 20, 20}, 4, Kugel<DIM3>{2_kg, .5_m}};
	box[0].position(pos1); box[0].velocity(vel_y);
	box[1].position(pos2); box[1].velocity(-vel_y);
	box[2].position(pos3); box[2].velocity(vel_x);
	box[3].position(pos4); box[3].velocity(-vel_x);

	box.initiate();
	box.collide(); box.collide();

	ASSERTM("", box[2].position() == ( MatVec<lengthT,DIM3>{10, 12, 0} ));
}

void problem_3_kugeln_Abraham_3() {
	MatVec<lengthT,DIM3> pos_urspr{10, 10, 0};
	MatVec<lengthT,DIM3> pos1{0, -1, 0};
	MatVec<lengthT,DIM3> pos2{0, 2, 0};
	MatVec<lengthT,DIM3> pos3{-4, 2, 0};
	MatVec<lengthT,DIM3> pos4{5, 2, 0};

	pos1 += pos_urspr; pos2 += pos_urspr;
	pos3 += pos_urspr; pos4 += pos_urspr;

	MatVec<velocityT,DIM3> vel_x{1, 0, 0};
	MatVec<velocityT,DIM3> vel_y{0, 1, 0};

	Box<DIM3> box{MatVec<lengthT,DIM3>{20, 20, 20}, 4, Kugel<DIM3>{2_kg, .5_m}};
	box[0].position(pos1); box[0].velocity(vel_y);
	box[1].position(pos2); box[1].velocity(-vel_y);
	box[2].position(pos3); box[2].velocity(vel_x);
	box[3].position(pos4); box[3].velocity(-vel_x);

	box.initiate();
	box.collide(); box.collide(); box.collide();

	ASSERTM("", box[3].position() == ( MatVec<lengthT,DIM3>{17, 12, 0} ));
}

cute::suite make_suite_Box(){
	cute::suite s;
	s.push_back(CUTE(emptyBox));
	s.push_back(CUTE(boxSize10));
	s.push_back(CUTE(boxAbmessung));
	s.push_back(CUTE(addBoxSize));
	s.push_back(CUTE(randomAccess_read));
	s.push_back(CUTE(randomAccess_constRead));
	s.push_back(CUTE(randomAccess_write));
	s.push_back(CUTE(wrapPosition));
//	s.push_back(CUTE(kugel_distance));
	s.push_back(CUTE(box_fastForward_pos));
	s.push_back(CUTE(box_fastForward_time));
	s.push_back(CUTE(box_initiate_given_no_rand));
	s.push_back(CUTE(box_initiate_given_rand));
	s.push_back(CUTE(box_collision_time_simple));
	s.push_back(CUTE(problem_3_kugeln_Abraham_1));
	s.push_back(CUTE(problem_3_kugeln_Abraham_2));
	s.push_back(CUTE(problem_3_kugeln_Abraham_3));
	return s;
}
<|endoftext|>


<commit_before>
<commit_msg>#i10000#: remove obsolete empty files; trim duplicated header content<commit_after><|endoftext|>


<commit_before>#include "coverage.h"
#include "featurecoverage.h"
#include "feature.h"
#include "featureiterator.h"
#include "drawingcolor.h"
#include "drawers/drawerfactory.h"
#include "rootdrawer.h"
#include "table.h"
#include "range.h"
#include "itemrange.h"
#include "identifieritem.h"
#include "identifierrange.h"
#include "colorrange.h"
#include "colorlookup.h"
#include "itemdomain.h"
#include "representation.h"
#include "drawers/attributevisualproperties.h"
#include "drawers/drawerattributesetter.h"
#include "drawers/drawerattributesetterfactory.h"
#include "drawerattributesetters/basespatialattributesetter.h"
#include "featurelayerdrawer.h"
#include "tesselation/ilwistesselator.h"
//#include "openglhelper.h"

using namespace Ilwis;
using namespace Geodrawer;

REGISTER_DRAWER(FeatureLayerDrawer)

FeatureLayerDrawer::FeatureLayerDrawer(DrawerInterface *parentDrawer, RootDrawer *rootdrawer, const IOOptions &options) : LayerDrawer("FeatureLayerDrawer", parentDrawer, rootdrawer, options)
{
}

DrawerInterface *FeatureLayerDrawer::create(DrawerInterface *parentDrawer, RootDrawer *rootdrawer, const IOOptions &options)
{
    return new FeatureLayerDrawer(parentDrawer, rootdrawer, options)    ;
}

void createAttributeSetter(const IFeatureCoverage& features, std::vector<std::shared_ptr<BaseSpatialAttributeSetter>>& setters, RootDrawer *rootdrawer)
{
    QVariant v = qVariantFromValue((void *) rootdrawer);
    IOOptions opt("rootdrawer", v);
    setters[itPOINT].reset( DrawerAttributeSetterFactory::create<BaseSpatialAttributeSetter>("simplepointsetter",opt));
    setters[itLINE].reset( DrawerAttributeSetterFactory::create<BaseSpatialAttributeSetter>("simplelinesetter",  opt));
    setters[itPOLYGON].reset( DrawerAttributeSetterFactory::create<BaseSpatialAttributeSetter>("simplepolygonsetter", opt));
    for(int i=0; i < setters.size(); ++i){
        if(setters[i]){
            setters[i]->sourceCsySystem(features->coordinateSystem());
        }
    }
}

bool FeatureLayerDrawer::prepare(DrawerInterface::PreparationType prepType, const IOOptions &options)
{
    if(!LayerDrawer::prepare(prepType, options))
        return false;

    if ( hasType(prepType, DrawerInterface::ptGEOMETRY) && !isPrepared(DrawerInterface::ptGEOMETRY)){

        IFeatureCoverage features = coverage().as<FeatureCoverage>();
        if ( !features.isValid()){
            return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"FeatureCoverage", TR("Visualization"));
        }
        // set all to 0
        _indices = std::vector<VertexIndex>();
        _vertices = QVector<QVector3D>();
        _normals = QVector<QVector3D>();
        _colors = std::vector<VertexColor>();
        // get a description of how to render
        VisualAttribute attr = visualAttribute(activeAttribute());

        std::vector<std::shared_ptr<BaseSpatialAttributeSetter>> setters(5); // types are 1 2 4, for performance a vector is used thoug not all elements are used
        // for the moment I use the simple setters, in the future this will be representation dependent
        createAttributeSetter(features, setters, rootDrawer());

        _featureDrawings.resize(features->featureCount());
        int featureIndex = 0;
        for(const SPFeatureI& feature : features){
            QVariant value =  attr.columnIndex() != iUNDEF ? feature(attr.columnIndex()) : featureIndex;
            IlwisTypes geomtype = feature->geometryType();
             _featureDrawings[featureIndex] = setters[geomtype]->setSpatialAttributes(feature,_vertices,_normals);

            setters[geomtype]->setColorAttributes(attr,value,_featureDrawings[featureIndex],_colors) ;
            ++featureIndex;
        }
        // implicity the redoing of the geometry is also redoing the representation stuff(a.o. colors)
        _prepared |= ( DrawerInterface::ptGEOMETRY | DrawerInterface::ptRENDER);

    }
    if ( hasType(prepType, DrawerInterface::ptRENDER) && !isPrepared(DrawerInterface::ptRENDER)){
        IFeatureCoverage features = coverage().as<FeatureCoverage>();
        int featureIndex = 0;
        std::vector<std::shared_ptr<BaseSpatialAttributeSetter>> setters(5); // types are 1 2 4, for performance a vector is used thoug not all elements are used
        // for the moment I use the simple setters, in the future this will be representation dependent
        createAttributeSetter(features, setters, rootDrawer());
        VisualAttribute attr = visualAttribute(activeAttribute());
        if ( !features.isValid()){
            return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"FeatureCoverage", TR("Visualization"));
        }
        _colors.resize(0);
        for(const SPFeatureI& feature : features){
            QVariant value =  attr.columnIndex() != iUNDEF ? feature(attr.columnIndex()) : featureIndex;
            IlwisTypes geomtype = feature->geometryType();
            setters[geomtype]->setColorAttributes(attr,value,_featureDrawings[featureIndex],_colors) ;
            ++featureIndex;
        }
    }

    //initialize();
    return true;
}

void FeatureLayerDrawer::unprepare(DrawerInterface::PreparationType prepType)
{
    LayerDrawer::unprepare(prepType);

    if ( hasType(prepType, DrawerInterface::ptGEOMETRY))    {
        _prepared &= ~ ptGEOMETRY;
    }
}

void FeatureLayerDrawer::setActiveVisualAttribute(const QString &attr)
{
    IFeatureCoverage features = coverage().as<FeatureCoverage>();
    if ( features.isValid())    {
        if ( features->attributeDefinitions().columnIndex(attr) != iUNDEF){

            IRepresentation newrpr = Representation::defaultRepresentation(features->attributeDefinitions().columndefinition(attr).datadef().domain());
            if ( newrpr.isValid()){
                LayerDrawer::setActiveVisualAttribute(attr);
            }
        }
    }
}

void FeatureLayerDrawer::coverage(const ICoverage &cov)
{
    LayerDrawer::coverage(cov);
    setActiveVisualAttribute(sUNDEF);
    IFeatureCoverage features = coverage().as<FeatureCoverage>();

    for(int i = 0; i < features->attributeDefinitions().definitionCount(); ++i){
        IlwisTypes attrType = features->attributeDefinitions().columndefinition(i).datadef().domain()->ilwisType();
        if ( hasType(attrType, itNUMERICDOMAIN | itITEMDOMAIN | itTEXTDOMAIN)){
            VisualAttribute props(features->attributeDefinitions().columndefinition(i).datadef().domain(),i);
            if ( attrType == itNUMERICDOMAIN){
                SPNumericRange numrange = features->attributeDefinitions().columndefinition(i).datadef().range<NumericRange>();
                props.actualRange(NumericRange(numrange->min(), numrange->max(), numrange->resolution()));
            } else if ( attrType == itITEMDOMAIN){
                int count = features->attributeDefinitions().columndefinition(i).datadef().domain()->range<>()->count();
                props.actualRange(NumericRange(0, count - 1,1));
            }
            visualAttribute(features->attributeDefinitions().columndefinition(i).name(), props);
            // try to find a reasonable default for the activeattribute
            if ( activeAttribute() == sUNDEF){
                if ( features->attributeDefinitions().columnIndex(FEATUREVALUECOLUMN) != iUNDEF){
                    setActiveVisualAttribute(FEATUREVALUECOLUMN);
                }else if ( features->attributeDefinitions().columnIndex(COVERAGEKEYCOLUMN) != iUNDEF){
                    setActiveVisualAttribute(COVERAGEKEYCOLUMN);
                }
                else if ( hasType(features->attributeDefinitions().columndefinition(i).datadef().domain()->ilwisType(), itNUMERICDOMAIN)){
                    setActiveVisualAttribute(features->attributeDefinitions().columndefinition(i).name());
                }
            }
        }
    }
}

ICoverage FeatureLayerDrawer::coverage() const
{
    return SpatialDataDrawer::coverage();
}

DrawerInterface::DrawerType FeatureLayerDrawer::drawerType() const
{
    return DrawerInterface::dtMAIN;
}

bool FeatureLayerDrawer::draw(const IOOptions& )
{
    if ( !isActive())
        return false;

    if (!isPrepared()){
        return false;
    }

    if(!_shaders.bind())
        return false;
    QMatrix4x4 mvp = rootDrawer()->mvpMatrix();

    _shaders.setUniformValue(_modelview, mvp);
    _shaders.setUniformValue(_vboAlpha, alpha());
    _shaders.enableAttributeArray(_vboNormal);
    _shaders.enableAttributeArray(_vboPosition);
    _shaders.enableAttributeArray(_vboColor);
    _shaders.setAttributeArray(_vboPosition, _vertices.constData());
    _shaders.setAttributeArray(_vboNormal, _normals.constData());
    _shaders.setAttributeArray(_vboColor, GL_FLOAT, (void *)_colors.data(),4);
    for(const auto& featureDrawing : _featureDrawings){
        if ( featureDrawing._geomtype == itPOINT){
            _shaders.setUniformValue(_scaleCenter, featureDrawing._center);
            _shaders.setUniformValue(_scaleFactor, (float)rootDrawer()->zoomScale());
        }else{
            _shaders.setUniformValue(_scaleFactor, 1.0f);
            if ( featureDrawing._geomtype == itLINE){
                glLineWidth(_lineWidth);
            }
        }

        for( const VertexIndex& featurePart : featureDrawing._indices)
            glDrawArrays(featurePart._oglType,featurePart._start,featurePart._count);
    }
    _shaders.disableAttributeArray(_vboNormal);
    _shaders.disableAttributeArray(_vboPosition);
    _shaders.disableAttributeArray(_vboColor);
    _shaders.release();

    return true;
}

QVariant FeatureLayerDrawer::attribute(const QString &attrName) const
{
    QVariant var = LayerDrawer::attribute(attrName);
    if ( var.isValid())
        return var;

    if ( attrName == "linewidth")
        return _lineWidth;

    return QVariant();
}

void FeatureLayerDrawer::setAttribute(const QString &attrName, const QVariant &value)
{
    LayerDrawer::setAttribute(attrName, value);

    if ( attrName == "linewidth")
        _lineWidth = value.toFloat();
}

<commit_msg>drawer load their own sahders now<commit_after>#include "coverage.h"
#include "featurecoverage.h"
#include "feature.h"
#include "featureiterator.h"
#include "drawingcolor.h"
#include "drawers/drawerfactory.h"
#include "rootdrawer.h"
#include "table.h"
#include "range.h"
#include "itemrange.h"
#include "identifieritem.h"
#include "identifierrange.h"
#include "colorrange.h"
#include "colorlookup.h"
#include "itemdomain.h"
#include "representation.h"
#include "drawers/attributevisualproperties.h"
#include "drawers/drawerattributesetter.h"
#include "drawers/drawerattributesetterfactory.h"
#include "drawerattributesetters/basespatialattributesetter.h"
#include "featurelayerdrawer.h"
#include "tesselation/ilwistesselator.h"
//#include "openglhelper.h"

using namespace Ilwis;
using namespace Geodrawer;

REGISTER_DRAWER(FeatureLayerDrawer)

FeatureLayerDrawer::FeatureLayerDrawer(DrawerInterface *parentDrawer, RootDrawer *rootdrawer, const IOOptions &options) : LayerDrawer("FeatureLayerDrawer", parentDrawer, rootdrawer, options)
{
    _vertexShader = "featurevertexshader_nvdia.glsl";
    _fragmentShader = "featurefragmentshader_nvdia.glsl";
}

DrawerInterface *FeatureLayerDrawer::create(DrawerInterface *parentDrawer, RootDrawer *rootdrawer, const IOOptions &options)
{
    return new FeatureLayerDrawer(parentDrawer, rootdrawer, options)    ;
}

void createAttributeSetter(const IFeatureCoverage& features, std::vector<std::shared_ptr<BaseSpatialAttributeSetter>>& setters, RootDrawer *rootdrawer)
{
    QVariant v = qVariantFromValue((void *) rootdrawer);
    IOOptions opt("rootdrawer", v);
    setters[itPOINT].reset( DrawerAttributeSetterFactory::create<BaseSpatialAttributeSetter>("simplepointsetter",opt));
    setters[itLINE].reset( DrawerAttributeSetterFactory::create<BaseSpatialAttributeSetter>("simplelinesetter",  opt));
    setters[itPOLYGON].reset( DrawerAttributeSetterFactory::create<BaseSpatialAttributeSetter>("simplepolygonsetter", opt));
    for(int i=0; i < setters.size(); ++i){
        if(setters[i]){
            setters[i]->sourceCsySystem(features->coordinateSystem());
        }
    }
}

bool FeatureLayerDrawer::prepare(DrawerInterface::PreparationType prepType, const IOOptions &options)
{
    if(!LayerDrawer::prepare(prepType, options))
        return false;

    if ( hasType(prepType, ptSHADERS) && !isPrepared(ptSHADERS)){
        _vboColor = _shaders.attributeLocation("vertexColor");
        _scaleCenter = _shaders.uniformLocation("scalecenter");
        _scaleFactor = _shaders.uniformLocation("scalefactor");

        _prepared |= DrawerInterface::ptSHADERS;
    }
    if ( hasType(prepType, DrawerInterface::ptGEOMETRY) && !isPrepared(DrawerInterface::ptGEOMETRY)){

        IFeatureCoverage features = coverage().as<FeatureCoverage>();
        if ( !features.isValid()){
            return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"FeatureCoverage", TR("Visualization"));
        }
        // set all to 0
        _indices = std::vector<VertexIndex>();
        _vertices = QVector<QVector3D>();
        _normals = QVector<QVector3D>();
        _colors = std::vector<VertexColor>();
        // get a description of how to render
        VisualAttribute attr = visualAttribute(activeAttribute());

        std::vector<std::shared_ptr<BaseSpatialAttributeSetter>> setters(5); // types are 1 2 4, for performance a vector is used thoug not all elements are used
        // for the moment I use the simple setters, in the future this will be representation dependent
        createAttributeSetter(features, setters, rootDrawer());

        _featureDrawings.resize(features->featureCount());
        int featureIndex = 0;
        for(const SPFeatureI& feature : features){
            QVariant value =  attr.columnIndex() != iUNDEF ? feature(attr.columnIndex()) : featureIndex;
            IlwisTypes geomtype = feature->geometryType();
             _featureDrawings[featureIndex] = setters[geomtype]->setSpatialAttributes(feature,_vertices,_normals);

            setters[geomtype]->setColorAttributes(attr,value,_featureDrawings[featureIndex],_colors) ;
            ++featureIndex;
        }
        // implicity the redoing of the geometry is also redoing the representation stuff(a.o. colors)
        _prepared |= ( DrawerInterface::ptGEOMETRY | DrawerInterface::ptRENDER);

    }
    if ( hasType(prepType, DrawerInterface::ptRENDER) && !isPrepared(DrawerInterface::ptRENDER)){
        IFeatureCoverage features = coverage().as<FeatureCoverage>();
        int featureIndex = 0;
        std::vector<std::shared_ptr<BaseSpatialAttributeSetter>> setters(5); // types are 1 2 4, for performance a vector is used thoug not all elements are used
        // for the moment I use the simple setters, in the future this will be representation dependent
        createAttributeSetter(features, setters, rootDrawer());
        VisualAttribute attr = visualAttribute(activeAttribute());
        if ( !features.isValid()){
            return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"FeatureCoverage", TR("Visualization"));
        }
        _colors.resize(0);
        for(const SPFeatureI& feature : features){
            QVariant value =  attr.columnIndex() != iUNDEF ? feature(attr.columnIndex()) : featureIndex;
            IlwisTypes geomtype = feature->geometryType();
            setters[geomtype]->setColorAttributes(attr,value,_featureDrawings[featureIndex],_colors) ;
            ++featureIndex;
        }
    }

    //initialize();
    return true;
}

void FeatureLayerDrawer::unprepare(DrawerInterface::PreparationType prepType)
{
    LayerDrawer::unprepare(prepType);

    if ( hasType(prepType, DrawerInterface::ptGEOMETRY))    {
        _prepared &= ~ ptGEOMETRY;
    }
}

void FeatureLayerDrawer::setActiveVisualAttribute(const QString &attr)
{
    IFeatureCoverage features = coverage().as<FeatureCoverage>();
    if ( features.isValid())    {
        if ( features->attributeDefinitions().columnIndex(attr) != iUNDEF){

            IRepresentation newrpr = Representation::defaultRepresentation(features->attributeDefinitions().columndefinition(attr).datadef().domain());
            if ( newrpr.isValid()){
                LayerDrawer::setActiveVisualAttribute(attr);
            }
        }
    }
}

void FeatureLayerDrawer::coverage(const ICoverage &cov)
{
    LayerDrawer::coverage(cov);
    setActiveVisualAttribute(sUNDEF);
    IFeatureCoverage features = coverage().as<FeatureCoverage>();

    for(int i = 0; i < features->attributeDefinitions().definitionCount(); ++i){
        IlwisTypes attrType = features->attributeDefinitions().columndefinition(i).datadef().domain()->ilwisType();
        if ( hasType(attrType, itNUMERICDOMAIN | itITEMDOMAIN | itTEXTDOMAIN)){
            VisualAttribute props(features->attributeDefinitions().columndefinition(i).datadef().domain(),i);
            if ( attrType == itNUMERICDOMAIN){
                SPNumericRange numrange = features->attributeDefinitions().columndefinition(i).datadef().range<NumericRange>();
                props.actualRange(NumericRange(numrange->min(), numrange->max(), numrange->resolution()));
            } else if ( attrType == itITEMDOMAIN){
                int count = features->attributeDefinitions().columndefinition(i).datadef().domain()->range<>()->count();
                props.actualRange(NumericRange(0, count - 1,1));
            }
            visualAttribute(features->attributeDefinitions().columndefinition(i).name(), props);
            // try to find a reasonable default for the activeattribute
            if ( activeAttribute() == sUNDEF){
                if ( features->attributeDefinitions().columnIndex(FEATUREVALUECOLUMN) != iUNDEF){
                    setActiveVisualAttribute(FEATUREVALUECOLUMN);
                }else if ( features->attributeDefinitions().columnIndex(COVERAGEKEYCOLUMN) != iUNDEF){
                    setActiveVisualAttribute(COVERAGEKEYCOLUMN);
                }
                else if ( hasType(features->attributeDefinitions().columndefinition(i).datadef().domain()->ilwisType(), itNUMERICDOMAIN)){
                    setActiveVisualAttribute(features->attributeDefinitions().columndefinition(i).name());
                }
            }
        }
    }
}

ICoverage FeatureLayerDrawer::coverage() const
{
    return SpatialDataDrawer::coverage();
}

DrawerInterface::DrawerType FeatureLayerDrawer::drawerType() const
{
    return DrawerInterface::dtMAIN;
}

bool FeatureLayerDrawer::draw(const IOOptions& )
{
    if ( !isActive())
        return false;

    if (!isPrepared()){
        return false;
    }

    if(!_shaders.bind())
        return false;
    QMatrix4x4 mvp = rootDrawer()->mvpMatrix();

    _shaders.setUniformValue(_modelview, mvp);
    _shaders.setUniformValue(_vboAlpha, alpha());
    _shaders.enableAttributeArray(_vboNormal);
    _shaders.enableAttributeArray(_vboPosition);
    _shaders.enableAttributeArray(_vboColor);
    _shaders.setAttributeArray(_vboPosition, _vertices.constData());
    _shaders.setAttributeArray(_vboNormal, _normals.constData());
    _shaders.setAttributeArray(_vboColor, GL_FLOAT, (void *)_colors.data(),4);
    for(const auto& featureDrawing : _featureDrawings){
        if ( featureDrawing._geomtype == itPOINT){
            _shaders.setUniformValue(_scaleCenter, featureDrawing._center);
            _shaders.setUniformValue(_scaleFactor, (float)rootDrawer()->zoomScale());
        }else{
            _shaders.setUniformValue(_scaleFactor, 1.0f);
            if ( featureDrawing._geomtype == itLINE){
                glLineWidth(_lineWidth);
            }
        }

        for( const VertexIndex& featurePart : featureDrawing._indices)
            glDrawArrays(featurePart._oglType,featurePart._start,featurePart._count);
    }
    _shaders.disableAttributeArray(_vboNormal);
    _shaders.disableAttributeArray(_vboPosition);
    _shaders.disableAttributeArray(_vboColor);
    _shaders.release();

    return true;
}

QVariant FeatureLayerDrawer::attribute(const QString &attrName) const
{
    QVariant var = LayerDrawer::attribute(attrName);
    if ( var.isValid())
        return var;

    if ( attrName == "linewidth")
        return _lineWidth;

    return QVariant();
}

void FeatureLayerDrawer::setAttribute(const QString &attrName, const QVariant &value)
{
    LayerDrawer::setAttribute(attrName, value);

    if ( attrName == "linewidth")
        _lineWidth = value.toFloat();
}

<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetHaddTest.cpp
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetHaddTest
#include "JPetBarrelSlot/JPetBarrelSlot.h"
#include "JPetEvent/JPetEvent.h"
#include "JPetReader/JPetReader.h"
#include "JPetScin/JPetScin.h"
#include "JPetTimeWindow/JPetTimeWindow.h"
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>

BOOST_AUTO_TEST_SUITE(JPetHaddTestSuite)

std::string exec(std::string cmd) {
  char buffer[128];
  std::string result = "";
  FILE* pipe = popen(cmd.c_str(), "r");
  if (!pipe)
    throw std::runtime_error("popen() failed!");
  try {
    while (!feof(pipe)) {
      if (fgets(buffer, 128, pipe) != NULL)
        result += buffer;
    }
  } catch (...) {
    pclose(pipe);
    throw;
  }
  pclose(pipe);
  return result;
}

BOOST_AUTO_TEST_CASE(hadd_test) {
  std::string haddedFileName = "";
  std::string firstFileName = "unitTestData/JPetHaddTest/single_link_def/dabc_17237091818.hadd.test.root";
  std::string secondFileName = "unitTestData/JPetHaddTest/single_link_def/dabc_17237093844.hadd.test.root";
#if ROOT_VERSION_CODE < ROOT_VERSION(6, 0, 0)
  haddedFileName = "unitTestData/JPetHaddTest/hadded_root5.hadd.test.root";
#else
  haddedFileName = "unitTestData/JPetHaddTest/hadded_root6.hadd.test.root";
#endif
  exec("hadd -f " + haddedFileName + " " + firstFileName + " " + secondFileName);
  JPetReader readerFirstFile(firstFileName.c_str());
  JPetReader readerSecondFile(secondFileName.c_str());
  JPetReader readerHaddedFile(haddedFileName.c_str());
  BOOST_REQUIRE(readerFirstFile.isOpen());
  BOOST_REQUIRE(readerSecondFile.isOpen());
  BOOST_REQUIRE(readerHaddedFile.isOpen());
  BOOST_REQUIRE_EQUAL(std::string(readerFirstFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
  BOOST_REQUIRE_EQUAL(std::string(readerSecondFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
  BOOST_REQUIRE_EQUAL(std::string(readerHaddedFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
  const auto firstParamBank = readerFirstFile.getObjectFromFile("ParamBank");
  const auto secondParamBank = readerSecondFile.getObjectFromFile("ParamBank");
  const auto haddedParamBank = readerHaddedFile.getObjectFromFile("ParamBank");
  BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (firstParamBank)(0));
  BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (secondParamBank)(0));
  BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (haddedParamBank)(0));

  long long firstFileNumberOfEntries = readerFirstFile.getNbOfAllEntries();
  long long secondFileNumberOfEntries = readerSecondFile.getNbOfAllEntries();
  long long haddedFileNumberOfEntries = readerHaddedFile.getNbOfAllEntries();
  BOOST_REQUIRE_EQUAL(haddedFileNumberOfEntries, firstFileNumberOfEntries + secondFileNumberOfEntries);
  for (long long i = 0; i < haddedFileNumberOfEntries; i++) {
    const auto& haddedTimeWindow = static_cast<const JPetTimeWindow&>(readerHaddedFile.getCurrentEntry());
    const auto& compareTimeWindow = i < firstFileNumberOfEntries ? static_cast<const JPetTimeWindow&>(readerFirstFile.getCurrentEntry())
                                                                 : static_cast<const JPetTimeWindow&>(readerSecondFile.getCurrentEntry());
    BOOST_REQUIRE_EQUAL(haddedTimeWindow.getNumberOfEvents(), compareTimeWindow.getNumberOfEvents());
    BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (haddedTimeWindow.getNumberOfEvents())(0));
    for (size_t i = 0; i < haddedTimeWindow.getNumberOfEvents(); i++) {
      const auto& haddedEvent = static_cast<const JPetEvent&>(haddedTimeWindow[i]);
      const auto& compareEvent = static_cast<const JPetEvent&>(compareTimeWindow[i]);
      const auto& haddedHits = haddedEvent.getHits();
      const auto& compareHits = compareEvent.getHits();
      BOOST_REQUIRE_EQUAL(haddedHits.size(), compareHits.size());
      for (unsigned int i = 0; i < haddedHits.size(); i++) {
        BOOST_REQUIRE_EQUAL(haddedHits[i].getPosX(), compareHits[i].getPosX());
        BOOST_REQUIRE_EQUAL(haddedHits[i].getPosY(), compareHits[i].getPosY());
        BOOST_REQUIRE_EQUAL(haddedHits[i].getPosZ(), compareHits[i].getPosZ());
        BOOST_REQUIRE_EQUAL(haddedHits[i].getEnergy(), compareHits[i].getEnergy());
        BOOST_REQUIRE_EQUAL(haddedHits[i].getQualityOfEnergy(), compareHits[i].getQualityOfEnergy());
        BOOST_REQUIRE_EQUAL(haddedHits[i].getTime(), compareHits[i].getTime());
        BOOST_REQUIRE_EQUAL(haddedHits[i].getTimeDiff(), compareHits[i].getTimeDiff());
        BOOST_REQUIRE_EQUAL(haddedHits[i].getQualityOfTime(), compareHits[i].getQualityOfTime());
        BOOST_REQUIRE_EQUAL(haddedHits[i].getQualityOfTimeDiff(), compareHits[i].getQualityOfTimeDiff());
        BOOST_REQUIRE(haddedHits[i].getScintillator() == compareHits[i].getScintillator());
        BOOST_REQUIRE(haddedHits[i].getBarrelSlot() == compareHits[i].getBarrelSlot());
      }
    }
    readerHaddedFile.nextEntry();
    if (i < firstFileNumberOfEntries)
      readerFirstFile.nextEntry();
    else
      readerSecondFile.nextEntry();
  }
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fix checking pointers<commit_after>/**
 *  @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetHaddTest.cpp
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetHaddTest
#include "JPetBarrelSlot/JPetBarrelSlot.h"
#include "JPetEvent/JPetEvent.h"
#include "JPetReader/JPetReader.h"
#include "JPetScin/JPetScin.h"
#include "JPetTimeWindow/JPetTimeWindow.h"
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>

BOOST_AUTO_TEST_SUITE(JPetHaddTestSuite)

std::string exec(std::string cmd) {
  char buffer[128];
  std::string result = "";
  FILE* pipe = popen(cmd.c_str(), "r");
  if (!pipe)
    throw std::runtime_error("popen() failed!");
  try {
    while (!feof(pipe)) {
      if (fgets(buffer, 128, pipe) != NULL)
        result += buffer;
    }
  } catch (...) {
    pclose(pipe);
    throw;
  }
  pclose(pipe);
  return result;
}

BOOST_AUTO_TEST_CASE(hadd_test) {
  std::string haddedFileName = "";
  std::string firstFileName = "unitTestData/JPetHaddTest/single_link_def/dabc_17237091818.hadd.test.root";
  std::string secondFileName = "unitTestData/JPetHaddTest/single_link_def/dabc_17237093844.hadd.test.root";
#if ROOT_VERSION_CODE < ROOT_VERSION(6, 0, 0)
  haddedFileName = "unitTestData/JPetHaddTest/hadded_root5.hadd.test.root";
#else
  haddedFileName = "unitTestData/JPetHaddTest/hadded_root6.hadd.test.root";
#endif
  exec("hadd -f " + haddedFileName + " " + firstFileName + " " + secondFileName);
  JPetReader readerFirstFile(firstFileName.c_str());
  JPetReader readerSecondFile(secondFileName.c_str());
  JPetReader readerHaddedFile(haddedFileName.c_str());
  BOOST_REQUIRE(readerFirstFile.isOpen());
  BOOST_REQUIRE(readerSecondFile.isOpen());
  BOOST_REQUIRE(readerHaddedFile.isOpen());
  BOOST_REQUIRE_EQUAL(std::string(readerFirstFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
  BOOST_REQUIRE_EQUAL(std::string(readerSecondFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
  BOOST_REQUIRE_EQUAL(std::string(readerHaddedFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
  const auto firstParamBank = readerFirstFile.getObjectFromFile("ParamBank");
  const auto secondParamBank = readerSecondFile.getObjectFromFile("ParamBank");
  const auto haddedParamBank = readerHaddedFile.getObjectFromFile("ParamBank");
  BOOST_CHECK(firstParamBank);
  BOOST_CHECK(secondParamBank);
  BOOST_CHECK(haddedParamBank);

  long long firstFileNumberOfEntries = readerFirstFile.getNbOfAllEntries();
  long long secondFileNumberOfEntries = readerSecondFile.getNbOfAllEntries();
  long long haddedFileNumberOfEntries = readerHaddedFile.getNbOfAllEntries();
  BOOST_REQUIRE_EQUAL(haddedFileNumberOfEntries, firstFileNumberOfEntries + secondFileNumberOfEntries);
  for (long long i = 0; i < haddedFileNumberOfEntries; i++) {
    const auto& haddedTimeWindow = static_cast<const JPetTimeWindow&>(readerHaddedFile.getCurrentEntry());
    const auto& compareTimeWindow = i < firstFileNumberOfEntries ? static_cast<const JPetTimeWindow&>(readerFirstFile.getCurrentEntry())
                                                                 : static_cast<const JPetTimeWindow&>(readerSecondFile.getCurrentEntry());
    BOOST_REQUIRE_EQUAL(haddedTimeWindow.getNumberOfEvents(), compareTimeWindow.getNumberOfEvents());
    BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (haddedTimeWindow.getNumberOfEvents())(0));
    for (size_t i = 0; i < haddedTimeWindow.getNumberOfEvents(); i++) {
      const auto& haddedEvent = static_cast<const JPetEvent&>(haddedTimeWindow[i]);
      const auto& compareEvent = static_cast<const JPetEvent&>(compareTimeWindow[i]);
      const auto& haddedHits = haddedEvent.getHits();
      const auto& compareHits = compareEvent.getHits();
      BOOST_REQUIRE_EQUAL(haddedHits.size(), compareHits.size());
      for (unsigned int i = 0; i < haddedHits.size(); i++) {
        BOOST_REQUIRE_EQUAL(haddedHits[i].getPosX(), compareHits[i].getPosX());
        BOOST_REQUIRE_EQUAL(haddedHits[i].getPosY(), compareHits[i].getPosY());
        BOOST_REQUIRE_EQUAL(haddedHits[i].getPosZ(), compareHits[i].getPosZ());
        BOOST_REQUIRE_EQUAL(haddedHits[i].getEnergy(), compareHits[i].getEnergy());
        BOOST_REQUIRE_EQUAL(haddedHits[i].getQualityOfEnergy(), compareHits[i].getQualityOfEnergy());
        BOOST_REQUIRE_EQUAL(haddedHits[i].getTime(), compareHits[i].getTime());
        BOOST_REQUIRE_EQUAL(haddedHits[i].getTimeDiff(), compareHits[i].getTimeDiff());
        BOOST_REQUIRE_EQUAL(haddedHits[i].getQualityOfTime(), compareHits[i].getQualityOfTime());
        BOOST_REQUIRE_EQUAL(haddedHits[i].getQualityOfTimeDiff(), compareHits[i].getQualityOfTimeDiff());
        BOOST_REQUIRE(haddedHits[i].getScintillator() == compareHits[i].getScintillator());
        BOOST_REQUIRE(haddedHits[i].getBarrelSlot() == compareHits[i].getBarrelSlot());
      }
    }
    readerHaddedFile.nextEntry();
    if (i < firstFileNumberOfEntries)
      readerFirstFile.nextEntry();
    else
      readerSecondFile.nextEntry();
  }
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/*
 * Moon++ Scripts for Ascent MMORPG Server
 * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
 * Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "Setup.h"

void GuardsOnSalute(Player* pPlayer, Unit* pUnit)
{
	if(pPlayer == NULL || pUnit == NULL)
		return;

	// Check if we are friendly with our Guards (they will salute only when You are)
	if(((pUnit->GetEntry() == 68 || pUnit->GetEntry() == 1976) && pPlayer->GetStandingRank(72) >= STANDING_FRIENDLY) || (pUnit->GetEntry() == 3296 && pPlayer->GetStandingRank(76) >= STANDING_FRIENDLY))
	{
		uint32 EmoteChance = RandomUInt(100);
		if(EmoteChance < 33) // 1/3 chance to get Salute from Guard
			pUnit->Emote(EMOTE_ONESHOT_SALUTE);
	}
}

void GaurdsOnKiss(Player* pPlayer, Unit* pUnit)
{
	if(pPlayer == NULL || pUnit == NULL)
		return;

	// Check if we are friendly with our Guards (they will bow only when You are)
	if(((pUnit->GetEntry() == 68 || pUnit->GetEntry() == 1976) && pPlayer->GetStandingRank(72) >= STANDING_FRIENDLY) || (pUnit->GetEntry() == 3296 && pPlayer->GetStandingRank(76) >= STANDING_FRIENDLY))
	{
		uint32 EmoteChance = RandomUInt(100);
		if(EmoteChance < 33) // 1/3 chance to get Bow from Guard
			pUnit->Emote(EMOTE_ONESHOT_BOW);
	}
}

void GuardsOnWave(Player* pPlayer, Unit* pUnit)
{
	if(pPlayer == NULL || pUnit == NULL)
		return;

	// Check if we are friendly with our Guards (they will wave only when You are)
	if(((pUnit->GetEntry() == 68 || pUnit->GetEntry() == 1976) && pPlayer->GetStandingRank(72) >= STANDING_FRIENDLY) || (pUnit->GetEntry() == 3296 && pPlayer->GetStandingRank(76) >= STANDING_FRIENDLY))
	{
		uint32 EmoteChance = RandomUInt(100);
		if(EmoteChance < 33) // 1/3 chance to get Bow from Guard
			pUnit->Emote(EMOTE_ONESHOT_WAVE);
	}
}

void OnEmote(Player* pPlayer, uint32 Emote, Unit* pUnit)
{
	if(!pUnit || !pUnit->isAlive() || pUnit->GetAIInterface()->getNextTarget())
		return;

	// Switch For Emote Name (You do EmoteName to Script Name link).
	switch(Emote)
	{
		case EMOTE_ONESHOT_SALUTE: // <- Its EMOTE name.
			GuardsOnSalute(pPlayer, pUnit); // <- Its Link.
			break;

		case EMOTE_ONESHOT_KISS:
			GaurdsOnKiss(pPlayer, pUnit);
			break;

		case EMOTE_ONESHOT_WAVE:
			GuardsOnWave(pPlayer, pUnit);
			break;
	}
}

class JeanPierrePoulain : public GossipScript
{
		public:
			void GossipHello(Object* pObject, Player* plr)
			{
			GossipMenu* Menu;
				objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 14500, plr);
			if(plr->HasFinishedQuest(13668) || plr->GetQuestLogForEntry(13668) || plr->HasFinishedQuest(13667) || plr->GetQuestLogForEntry(13667))
				Menu->SendTo(plr);
			else
				Menu->AddItem(0, "I'll take the flight."	,1);
				Menu->SendTo(plr);
}

void GossipSelectOption(Object* pObject, Player* Plr, uint32 Id, uint32 IntId, const char* Code)
{
			switch(IntId)
			{
			case 0:
				GossipHello(pObject, Plr);
				break;
			case 1:
				Plr->CastSpell(Plr, 64795, true);
				break;
			}
				Plr->Gossip_Complete();
		}
};

void SetupRandomScripts(ScriptMgr* mgr)
{
	// Register Hook Event here
	mgr->register_hook(SERVER_HOOK_EVENT_ON_EMOTE, (void*)&OnEmote);
	mgr->register_gossip_script(34244, new JeanPierrePoulain);
}<commit_msg>added {} to jean pierre<commit_after>/*
 * Moon++ Scripts for Ascent MMORPG Server
 * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
 * Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "Setup.h"

void GuardsOnSalute(Player* pPlayer, Unit* pUnit)
{
	if(pPlayer == NULL || pUnit == NULL)
		return;

	// Check if we are friendly with our Guards (they will salute only when You are)
	if(((pUnit->GetEntry() == 68 || pUnit->GetEntry() == 1976) && pPlayer->GetStandingRank(72) >= STANDING_FRIENDLY) || (pUnit->GetEntry() == 3296 && pPlayer->GetStandingRank(76) >= STANDING_FRIENDLY))
	{
		uint32 EmoteChance = RandomUInt(100);
		if(EmoteChance < 33) // 1/3 chance to get Salute from Guard
			pUnit->Emote(EMOTE_ONESHOT_SALUTE);
	}
}

void GaurdsOnKiss(Player* pPlayer, Unit* pUnit)
{
	if(pPlayer == NULL || pUnit == NULL)
		return;

	// Check if we are friendly with our Guards (they will bow only when You are)
	if(((pUnit->GetEntry() == 68 || pUnit->GetEntry() == 1976) && pPlayer->GetStandingRank(72) >= STANDING_FRIENDLY) || (pUnit->GetEntry() == 3296 && pPlayer->GetStandingRank(76) >= STANDING_FRIENDLY))
	{
		uint32 EmoteChance = RandomUInt(100);
		if(EmoteChance < 33) // 1/3 chance to get Bow from Guard
			pUnit->Emote(EMOTE_ONESHOT_BOW);
	}
}

void GuardsOnWave(Player* pPlayer, Unit* pUnit)
{
	if(pPlayer == NULL || pUnit == NULL)
		return;

	// Check if we are friendly with our Guards (they will wave only when You are)
	if(((pUnit->GetEntry() == 68 || pUnit->GetEntry() == 1976) && pPlayer->GetStandingRank(72) >= STANDING_FRIENDLY) || (pUnit->GetEntry() == 3296 && pPlayer->GetStandingRank(76) >= STANDING_FRIENDLY))
	{
		uint32 EmoteChance = RandomUInt(100);
		if(EmoteChance < 33) // 1/3 chance to get Bow from Guard
			pUnit->Emote(EMOTE_ONESHOT_WAVE);
	}
}

void OnEmote(Player* pPlayer, uint32 Emote, Unit* pUnit)
{
	if(!pUnit || !pUnit->isAlive() || pUnit->GetAIInterface()->getNextTarget())
		return;

	// Switch For Emote Name (You do EmoteName to Script Name link).
	switch(Emote)
	{
		case EMOTE_ONESHOT_SALUTE: // <- Its EMOTE name.
			GuardsOnSalute(pPlayer, pUnit); // <- Its Link.
			break;

		case EMOTE_ONESHOT_KISS:
			GaurdsOnKiss(pPlayer, pUnit);
			break;

		case EMOTE_ONESHOT_WAVE:
			GuardsOnWave(pPlayer, pUnit);
			break;
	}
}

class JeanPierrePoulain : public GossipScript
{
		public:
			void GossipHello(Object* pObject, Player* plr)
			{
			GossipMenu* Menu;
				objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 14500, plr);
			if(plr->HasFinishedQuest(13668) || plr->GetQuestLogForEntry(13668) || plr->HasFinishedQuest(13667) || plr->GetQuestLogForEntry(13667))
			{
				Menu->SendTo(plr);
			}
			else
			{
				Menu->AddItem(0, "I'll take the flight."	,1);
				Menu->SendTo(plr);
			}
}

void GossipSelectOption(Object* pObject, Player* Plr, uint32 Id, uint32 IntId, const char* Code)
{
			switch(IntId)
			{
			case 0:
				GossipHello(pObject, Plr);
				break;
			case 1:
				Plr->CastSpell(Plr, 64795, true);
				break;
			}
				Plr->Gossip_Complete();
		}
};

void SetupRandomScripts(ScriptMgr* mgr)
{
	// Register Hook Event here
	mgr->register_hook(SERVER_HOOK_EVENT_ON_EMOTE, (void*)&OnEmote);
	mgr->register_gossip_script(34244, new JeanPierrePoulain);
}<|endoftext|>


<commit_before>#include "vtkImageViewer.h"
#include "vtkImageReader.h"
#include "vtkImageImport.h"
#include "vtkImageExport.h"
#include "vtkWindowToImageFilter.h"
#include "vtkPNMWriter.h"

#include "vtkRegressionTestImage.h"

int main( int argc, char *argv[] )
{
 int i,j,k;

 char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/headsq/quarter");

 vtkImageReader *reader = vtkImageReader::New();
 reader->SetDataByteOrderToLittleEndian();
 reader->SetDataExtent(0,63,0,63,1,93);
 reader->SetFilePrefix(fname);
 reader->SetDataMask(0x7fff);
 delete [] fname;

 // create exporter
 vtkImageExport *exporter = vtkImageExport::New();
 exporter->SetInput(reader->GetOutput());
 exporter->ImageLowerLeftOn();

 // get info from exporter and create array to hold data
 int memsize = exporter->GetDataMemorySize();
 int *dimensions = exporter->GetDataDimensions();

 // export the data into the array
 short *data = new short[memsize/sizeof(short)];
 exporter->Export(data);

 // alternative method for getting data
 // short *data = exporter->GetPointerToData();

 // do a little something to the data

 for (i = 0; i < dimensions[2]; i++)
   {
   for (j = 0; j < dimensions[1]; j++)
     {
     for (k = 0; k < dimensions[0]; k++)
       {
       if (k % 10 == 0)
	 {
	 data[k + dimensions[0]*(j + dimensions[1]*i)] = 0;
	 }
       if (j % 10 == 0)
	 {
	 data[k + dimensions[0]*(j + dimensions[1]*i)] = 1000;
	 }
       }
     }
   }

 // create an importer to read the data back in
 vtkImageImport *importer = vtkImageImport::New();
 importer->SetDataExtent(1,dimensions[0],1,dimensions[1],1,dimensions[2]);
 importer->SetDataScalarTypeToShort();
 importer->SetImportVoidPointer(data);

 vtkImageViewer *viewer = vtkImageViewer::New();
 viewer->SetInput(importer->GetOutput());
 viewer->SetZSlice(45);
 viewer->SetColorWindow(2000);
 viewer->SetColorLevel(1000);

 viewer->Render();

 int retVal = vtkRegressionTestImage( viewer->GetImageWindow() );

 viewer->Delete();
 importer->Delete();
 exporter->Delete();
 reader->Delete();

 delete data;

 return !retVal;
}

<commit_msg>GetImageWindow() was deprecated.<commit_after>#include "vtkImageViewer.h"
#include "vtkImageReader.h"
#include "vtkImageImport.h"
#include "vtkImageExport.h"
#include "vtkWindowToImageFilter.h"
#include "vtkPNMWriter.h"

#include "vtkRegressionTestImage.h"

int main( int argc, char *argv[] )
{
 int i,j,k;

 char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/headsq/quarter");

 vtkImageReader *reader = vtkImageReader::New();
 reader->SetDataByteOrderToLittleEndian();
 reader->SetDataExtent(0,63,0,63,1,93);
 reader->SetFilePrefix(fname);
 reader->SetDataMask(0x7fff);
 delete [] fname;

 // create exporter
 vtkImageExport *exporter = vtkImageExport::New();
 exporter->SetInput(reader->GetOutput());
 exporter->ImageLowerLeftOn();

 // get info from exporter and create array to hold data
 int memsize = exporter->GetDataMemorySize();
 int *dimensions = exporter->GetDataDimensions();

 // export the data into the array
 short *data = new short[memsize/sizeof(short)];
 exporter->Export(data);

 // alternative method for getting data
 // short *data = exporter->GetPointerToData();

 // do a little something to the data

 for (i = 0; i < dimensions[2]; i++)
   {
   for (j = 0; j < dimensions[1]; j++)
     {
     for (k = 0; k < dimensions[0]; k++)
       {
       if (k % 10 == 0)
	 {
	 data[k + dimensions[0]*(j + dimensions[1]*i)] = 0;
	 }
       if (j % 10 == 0)
	 {
	 data[k + dimensions[0]*(j + dimensions[1]*i)] = 1000;
	 }
       }
     }
   }

 // create an importer to read the data back in
 vtkImageImport *importer = vtkImageImport::New();
 importer->SetDataExtent(1,dimensions[0],1,dimensions[1],1,dimensions[2]);
 importer->SetDataScalarTypeToShort();
 importer->SetImportVoidPointer(data);

 vtkImageViewer *viewer = vtkImageViewer::New();
 viewer->SetInput(importer->GetOutput());
 viewer->SetZSlice(45);
 viewer->SetColorWindow(2000);
 viewer->SetColorLevel(1000);

 viewer->Render();

 int retVal = vtkRegressionTestImage( viewer->GetRenderWindow() );

 viewer->Delete();
 importer->Delete();
 exporter->Delete();
 reader->Delete();

 delete data;

 return !retVal;
}

<|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System.
 */

#include "gateway_util.h"

#include <vector>

#include "logging.h"
#include "util/string.h"

namespace gateway {

int APIVersion() { return 1; }

bool ReadKeys(const std::string& key_file_name, std::string* key_id,
              std::string* secret) {
  if (!(key_id && secret)) {
    return false;
  }

  FILE* key_file_fd = std::fopen(key_file_name.c_str(), "r");
  if (!key_file_fd) {
    return false;
  }

  std::string line;
  if (!GetLineFile(key_file_fd, &line)) {
    fclose(key_file_fd);
    return false;
  }

  fclose(key_file_fd);

  std::vector<std::string> tokens = SplitString(line, ' ');
  if (tokens.size() < 2) {
    return false;
  }

  if (tokens[0] == "plain_text") {
    *key_id = tokens[1];
    *secret = tokens[2];
  } else {
    return false;
  }

  return true;
}

}  // namespace gateway
<commit_msg>Bump repository gateway protocol version to 2<commit_after>/**
 * This file is part of the CernVM File System.
 */

#include "gateway_util.h"

#include <vector>

#include "logging.h"
#include "util/string.h"

namespace gateway {

int APIVersion() { return 2; }

bool ReadKeys(const std::string& key_file_name, std::string* key_id,
              std::string* secret) {
  if (!(key_id && secret)) {
    return false;
  }

  FILE* key_file_fd = std::fopen(key_file_name.c_str(), "r");
  if (!key_file_fd) {
    return false;
  }

  std::string line;
  if (!GetLineFile(key_file_fd, &line)) {
    fclose(key_file_fd);
    return false;
  }

  fclose(key_file_fd);

  std::vector<std::string> tokens = SplitString(line, ' ');
  if (tokens.size() < 2) {
    return false;
  }

  if (tokens[0] == "plain_text") {
    *key_id = tokens[1];
    *secret = tokens[2];
  } else {
    return false;
  }

  return true;
}

}  // namespace gateway
<|endoftext|>


<commit_before>/**
* \file      main.cc
* \brief     Program for giving an indication when a RFID card has been
* detected, a database connection has been made and a string has been encrypted
* \author    Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de
* Groot, Ricardo Bouwman, Philippe Zwietering, Luuk Steeman, Leo Jenneskens,
* Jeremy Ruijzenaars
* \copyright Copyright (c) 2017, The R2D2 Team
* \license   See LICENSE
*/

#include "config-file-parser.hh"
#include "database-manager.hh"
#include "led-controller.hh"
#include "matrix-keypad.hh"
#include "mfrc522.hh"

#include <wiringPiSPI.h>

#include <iomanip>
#include <string>

// Keypad pinSetup
const int keypadRow[] = {15, 16, 1, 4};
const int keypadColumn[] = {8, 9, 7, 2};

// Magic number declarations
const int redLedPin = 0;
const int greenLedPin = 11;
const int maxSpeedWiringSPI = 10000000; // max speed for mfrc522 is 10Mhz
const int keypadColumnSize = 4;
const int blockSizeWithCrc = 18;
const int blockSize = 16;
const int zeroAscii = 47;
const int nineAscii = 58;
const int blinkTime = 3000;

int main(int argc, char **argv) {

    if(argc != 2 || std::string(argv[1]) != "pin" && std::string(argv[1]) != "no-pin") {
        std::cerr << "Please only put in 'pin' or 'no-pin' as parameter, nothing else." << std::endl
                  << "Your function will then either look like './rfid pin' or './rfid no-pin'" << std::endl;
    }

    // Keypad objects
    MatrixKeypad keypad(keypadRow, keypadColumn, keypadColumnSize);

    LedController redLed(redLedPin);
    LedController greenLed(greenLedPin);

    std::string ip;
    std::string username;
    std::string password;

    ConfigFileParser factory("database-config.txt");
    factory.loadDatabaseSettings(ip, username, password);
    DatabaseManager information;
    information.connectTo(ip, username, password);
    information.selectDatabase("R2D2");

    std::cout << "Made connection to the database\n";
    wiringPiSetup();
    wiringPiSPISetup(0, maxSpeedWiringSPI);

    MFRC522 rfid;
    rfid.PCD_Init();

    while (true) {
        delay(1000);
        std::cout << "\n\nWaiting for RFID tag: \n";

        if (!rfid.PICC_IsNewCardPresent())
            continue;

        if (!rfid.PICC_ReadCardSerial())
            continue;

        std::string id;
        for (byte i = 0; i < rfid.uid.size; ++i) {
            std::stringstream ss;
            ss << std::hex << (int) rfid.uid.uidByte[i];
            id += ss.str();
            if (i != rfid.uid.size - 1) {
                id += ' ';
            }
        }

        bool inDatabase;
        std::cout << id << " is the presented ID\n";
        if (!information.isCardInDatabase(id)) {
            std::cout << "This ID is in the database\n";
            inDatabase = 1;
        } else {
            std::cout << "This ID is NOT in the database\n";
            inDatabase = 0;
        }

        if(std::string(argv[1]) == "pin") {
            MFRC522::MIFARE_Key key = {{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}};
            if (rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A,
                                      (byte) 0x05, &key, &rfid.uid) != 1)
                continue;

            // read pin code
            byte bufferSize = (byte) blockSizeWithCrc;
            byte readArray[blockSizeWithCrc] = {};
            rfid.MIFARE_Read((byte) 0x05, readArray, &bufferSize);
            std::cout << "Read array contains: \n";
            for (int i = 0; i < blockSizeWithCrc; i++) {
                std::cout << (int) readArray[i] << ' ';
            }

            // enter pin code
            std::cout << "\nInput PIN and finish with #\n";
            std::string value = keypad.getString();

            // write pin code
            byte writeArray[blockSize] = {};
            int index = 0;
            for (const auto c : value) {
                if (c > zeroAscii && c < nineAscii) {
                    int number = c - (zeroAscii+1);
                    writeArray[index++] = (byte) number;
                }
            }
            rfid.MIFARE_Write((byte) 0x05, writeArray, (byte) blockSize);
            std::cout << "Write array contains: \n";
            for (int i = 0; i < blockSize; i++) {
                std::cout << (int) writeArray[i] << ' ';
            }
        }

        rfid.PCD_StopCrypto1();
        if (inDatabase) {
            greenLed.blinkLed(blinkTime);
        } else {
            redLed.blinkLed(blinkTime);
        }
    }
}
<commit_msg>[RFID-03] Added parentheses because of warnings -.-<commit_after>/**
* \file      main.cc
* \brief     Program for giving an indication when a RFID card has been
* detected, a database connection has been made and a string has been encrypted
* \author    Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de
* Groot, Ricardo Bouwman, Philippe Zwietering, Luuk Steeman, Leo Jenneskens,
* Jeremy Ruijzenaars
* \copyright Copyright (c) 2017, The R2D2 Team
* \license   See LICENSE
*/

#include "config-file-parser.hh"
#include "database-manager.hh"
#include "led-controller.hh"
#include "matrix-keypad.hh"
#include "mfrc522.hh"

#include <wiringPiSPI.h>

#include <iomanip>
#include <string>

// Keypad pinSetup
const int keypadRow[] = {15, 16, 1, 4};
const int keypadColumn[] = {8, 9, 7, 2};

// Magic number declarations
const int redLedPin = 0;
const int greenLedPin = 11;
const int maxSpeedWiringSPI = 10000000; // max speed for mfrc522 is 10Mhz
const int keypadColumnSize = 4;
const int blockSizeWithCrc = 18;
const int blockSize = 16;
const int zeroAscii = 47;
const int nineAscii = 58;
const int blinkTime = 3000;

int main(int argc, char **argv) {

    if(argc != 2 || (std::string(argv[1]) != "pin" && std::string(argv[1]) != "no-pin")) {
        std::cerr << "Please only put in 'pin' or 'no-pin' as parameter, nothing else." << std::endl
                  << "Your function will then either look like './rfid pin' or './rfid no-pin'" << std::endl;
    }

    // Keypad objects
    MatrixKeypad keypad(keypadRow, keypadColumn, keypadColumnSize);

    LedController redLed(redLedPin);
    LedController greenLed(greenLedPin);

    std::string ip;
    std::string username;
    std::string password;

    ConfigFileParser factory("database-config.txt");
    factory.loadDatabaseSettings(ip, username, password);
    DatabaseManager information;
    information.connectTo(ip, username, password);
    information.selectDatabase("R2D2");

    std::cout << "Made connection to the database\n";
    wiringPiSetup();
    wiringPiSPISetup(0, maxSpeedWiringSPI);

    MFRC522 rfid;
    rfid.PCD_Init();

    while (true) {
        delay(1000);
        std::cout << "\n\nWaiting for RFID tag: \n";

        if (!rfid.PICC_IsNewCardPresent())
            continue;

        if (!rfid.PICC_ReadCardSerial())
            continue;

        std::string id;
        for (byte i = 0; i < rfid.uid.size; ++i) {
            std::stringstream ss;
            ss << std::hex << (int) rfid.uid.uidByte[i];
            id += ss.str();
            if (i != rfid.uid.size - 1) {
                id += ' ';
            }
        }

        bool inDatabase;
        std::cout << id << " is the presented ID\n";
        if (!information.isCardInDatabase(id)) {
            std::cout << "This ID is in the database\n";
            inDatabase = 1;
        } else {
            std::cout << "This ID is NOT in the database\n";
            inDatabase = 0;
        }

        if(std::string(argv[1]) == "pin") {
            MFRC522::MIFARE_Key key = {{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}};
            if (rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A,
                                      (byte) 0x05, &key, &rfid.uid) != 1)
                continue;

            // read pin code
            byte bufferSize = (byte) blockSizeWithCrc;
            byte readArray[blockSizeWithCrc] = {};
            rfid.MIFARE_Read((byte) 0x05, readArray, &bufferSize);
            std::cout << "Read array contains: \n";
            for (int i = 0; i < blockSizeWithCrc; i++) {
                std::cout << (int) readArray[i] << ' ';
            }

            // enter pin code
            std::cout << "\nInput PIN and finish with #\n";
            std::string value = keypad.getString();

            // write pin code
            byte writeArray[blockSize] = {};
            int index = 0;
            for (const auto c : value) {
                if (c > zeroAscii && c < nineAscii) {
                    int number = c - (zeroAscii+1);
                    writeArray[index++] = (byte) number;
                }
            }
            rfid.MIFARE_Write((byte) 0x05, writeArray, (byte) blockSize);
            std::cout << "Write array contains: \n";
            for (int i = 0; i < blockSize; i++) {
                std::cout << (int) writeArray[i] << ' ';
            }
        }

        rfid.PCD_StopCrypto1();
        if (inDatabase) {
            greenLed.blinkLed(blinkTime);
        } else {
            redLed.blinkLed(blinkTime);
        }
    }
}
<|endoftext|>


<commit_before> /**
 * \file      main.cc
 * \brief     Program for giving an indication when a rfid card has been detected, a database connection has been made and a string has been encrypted
 * \author    Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de Groot, Ricardo Bouwman, Philippe Zwietering, Luuk Steeman,Leo Jenneskens
 * \copyright Copyright (c) 2017, The R2D2 Team
 * \license   See LICENSE
 */

#include "mysql.hh"
#include "mfrc522.hh"
#include "led-controller.hh"
#include "matrix-keypad.hh"
#include "config-file-parser.hh"

#include <wiringPi.h>
#include <wiringPiSPI.h>

#include <iostream>

struct MFAuthentData {
    uint8_t command_code;
    uint8_t blockAddress;
    uint8_t sectorKey[5];
    uint8_t serialNumber[4];
};

int main(int argc, char **argv) {
#define USING_PIN           // Comment out this rule if not using a pincode on your application
    try {
        std::string ip;
        std::string username;
        std::string password;
        //int encryptionKey;

        ConfigFileParser factory("database-config.txt");
        factory.loadDatabaseSettings(ip, username, password);

        MySql connection;

        connection.connectTo(ip, username, password);
        connection.selectDatabase("R2D2");

        std::cout << "Made connection to the database\n";
        wiringPiSetup();
        wiringPiSPISetup(0, 10000000);//max speed for mfrc522 is 10Mhz
        MFRC522 rfid;
        rfid.PCD_Init();

        //Keypad pinSetup
        const int keypadRow[] = {15, 16, 1, 4};
        const int keypadColumn[] = {8, 9, 7, 2};

        //Keypad objects
        MatrixKeypad keypad(keypadRow, keypadColumn, 4);
        char c;

        LedController led(0);

        while (true) {
            delay(1000);
            std::cout << "\n\nWaiting for rfid tag: \n";

            rfid.PICC_IsNewCardPresent();

            rfid.PICC_ReadCardSerial();

            // Hier moet het database gedeelte komen om te checken of je ID al in de database staat

#ifdef USING_PIN
            MFRC522::MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
            std::cout << "Input PIN and finish with #\n";
            std::string value = keypad.getString();
            long result;
            if(!rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)0x05, &key, &rfid.uid))
                continue;
            std::cout << (int)status;
	       	byte  writearray[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
		    int index = 0;
            for(auto c :value){
		      if (c >47 && c < 58 ){
		          int number = c - 48;
		          writearray[index++] = (byte)number;
		        }
	        }
            rfid.MIFARE_Write((byte)0x05, writearray, (byte)16);
            for (int i = 0; i < 16; i++){
                std::cout <<(int)writearray[i] << '\n';
            }
            byte buffersize = (byte)18;
            byte readarray[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
            rfid.MIFARE_Read((byte)0x05,readarray, &buffersize);
            std::cout << "Readarray contains: \n";
            for (int i = 0; i < 18; i++){
                std::cout <<(int)readarray[i] << '\n';
            }
#endif

            rfid.PCD_StopCrypto1();

            for(byte i = 0; i < rfid.uid.size; ++i){
                if(rfid.uid.uidByte[i] < 0x10){
                    printf(" 0");
                    printf("%X",rfid.uid.uidByte[i]);
                }
                else{
                    printf(" ");
                    printf("%X", rfid.uid.uidByte[i]);
                }
            }

            connection.executeQuery("SELECT * FROM RFID");

            std::cout << "Database information: "
                      << connection.getPreviousResponseColumn("CARD_ID")
                      << '\n';

            led.blinkLed(1000);
        }
    } catch (const std::string &error) {
        std::cerr << error << '\n';
        exit(EXIT_FAILURE);
    } catch (...) {
        std::cerr << "Something went wrong\n";
        exit(EXIT_FAILURE);
    }
    return 0;
}

<commit_msg> [RFID-03] bug fix<commit_after> /**
 * \file      main.cc
 * \brief     Program for giving an indication when a rfid card has been detected, a database connection has been made and a string has been encrypted
 * \author    Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de Groot, Ricardo Bouwman, Philippe Zwietering, Luuk Steeman,Leo Jenneskens
 * \copyright Copyright (c) 2017, The R2D2 Team
 * \license   See LICENSE
 */

#include "mysql.hh"
#include "mfrc522.hh"
#include "led-controller.hh"
#include "matrix-keypad.hh"
#include "config-file-parser.hh"

#include <wiringPi.h>
#include <wiringPiSPI.h>

#include <iostream>

struct MFAuthentData {
    uint8_t command_code;
    uint8_t blockAddress;
    uint8_t sectorKey[5];
    uint8_t serialNumber[4];
};

int main(int argc, char **argv) {
#define USING_PIN           // Comment out this rule if not using a pincode on your application
    try {
        std::string ip;
        std::string username;
        std::string password;
        //int encryptionKey;

        ConfigFileParser factory("database-config.txt");
        factory.loadDatabaseSettings(ip, username, password);

        MySql connection;

        connection.connectTo(ip, username, password);
        connection.selectDatabase("R2D2");

        std::cout << "Made connection to the database\n";
        wiringPiSetup();
        wiringPiSPISetup(0, 10000000);//max speed for mfrc522 is 10Mhz
        MFRC522 rfid;
        rfid.PCD_Init();

        //Keypad pinSetup
        const int keypadRow[] = {15, 16, 1, 4};
        const int keypadColumn[] = {8, 9, 7, 2};

        //Keypad objects
        MatrixKeypad keypad(keypadRow, keypadColumn, 4);
        char c;

        LedController led(0);

        while (true) {
            delay(1000);
            std::cout << "\n\nWaiting for rfid tag: \n";

            rfid.PICC_IsNewCardPresent();

            rfid.PICC_ReadCardSerial();

            // Hier moet het database gedeelte komen om te checken of je ID al in de database staat

#ifdef USING_PIN
            MFRC522::MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
            std::cout << "Input PIN and finish with #\n";
            std::string value = keypad.getString();
            long result;
            if(!rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)0x05, &key, &rfid.uid))
                continue;
	       	byte  writearray[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
		    int index = 0;
            for(auto c :value){
		      if (c >47 && c < 58 ){
		          int number = c - 48;
		          writearray[index++] = (byte)number;
		        }
	        }
            rfid.MIFARE_Write((byte)0x05, writearray, (byte)16);
            for (int i = 0; i < 16; i++){
                std::cout <<(int)writearray[i] << '\n';
            }
            byte buffersize = (byte)18;
            byte readarray[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
            rfid.MIFARE_Read((byte)0x05,readarray, &buffersize);
            std::cout << "Readarray contains: \n";
            for (int i = 0; i < 18; i++){
                std::cout <<(int)readarray[i] << '\n';
            }
#endif

            rfid.PCD_StopCrypto1();

            for(byte i = 0; i < rfid.uid.size; ++i){
                if(rfid.uid.uidByte[i] < 0x10){
                    printf(" 0");
                    printf("%X",rfid.uid.uidByte[i]);
                }
                else{
                    printf(" ");
                    printf("%X", rfid.uid.uidByte[i]);
                }
            }

            connection.executeQuery("SELECT * FROM RFID");

            std::cout << "Database information: "
                      << connection.getPreviousResponseColumn("CARD_ID")
                      << '\n';

            led.blinkLed(1000);
        }
    } catch (const std::string &error) {
        std::cerr << error << '\n';
        exit(EXIT_FAILURE);
    } catch (...) {
        std::cerr << "Something went wrong\n";
        exit(EXIT_FAILURE);
    }
    return 0;
}

<|endoftext|>