<commit_before>#include <nan.h>
#include <QObject>
#include <QVariant>
#include <QMetaType>
#include <QQmlComponent>
#include "utils.h"

namespace Brig {

	using namespace v8;
	using namespace node;

	namespace Utils {

		Local<Value> QDataToV8(int type, void *value)
		{
			Nan::EscapableHandleScope scope;

			return scope.Escape(QVariantToV8(type, QVariant(type, value)));
		}

		Local<Value> QVariantToV8(int type, QVariant v)
		{
			Nan::EscapableHandleScope scope;

			switch(type) {
			case QMetaType::Bool:
				//return scope.Escape(Boolean::New(v.toBool()));
				return scope.Escape(Nan::New<Boolean>(v.toBool()));

			case QMetaType::Int:
				//return scope.Escape(Nan::New<Number>(v.toInt()));
				return scope.Escape(Nan::New<Int32>(v.toInt()));

			case QMetaType::UInt:
				return scope.Escape(Nan::New<Uint32>(v.toUInt()));

			case QMetaType::Float:
				return scope.Escape(Nan::New<Number>(v.toFloat()));

			case QMetaType::Double:
				return scope.Escape(Nan::New<Number>(v.toDouble()));

			case QMetaType::LongLong:

				return scope.Escape(Nan::New<Number>(v.toLongLong()));

			case QMetaType::ULongLong:
				return scope.Escape(Nan::New<Number>(v.toULongLong()));

			case QMetaType::QString:
				//return scope.Escape(Nan::New<String>(v.toString().toUtf8().constData()));
				return scope.Escape(Nan::New<String>(v.toString().toStdString()).ToLocalChecked());

			default:

				if (type == qMetaTypeId<QQmlComponent::Status>()) {
					return scope.Escape(Nan::New<Number>(v.toInt()));
				} else if (type == qMetaTypeId<qreal>()) {
					return scope.Escape(Nan::New<Number>(v.toDouble()));
				}

//			case QMetaType::QVariant:
			}

			return scope.Escape(Nan::Undefined());
		}

		QVariant V8ToQVariant(Local<Value> value)
		{
			QVariant v;

			// Check data type
			if (value->IsNull()) {
				v.setValue(QVariant(QMetaType::VoidStar, 0));
			} else if (value->IsTrue() || value->IsFalse() || value->IsBoolean() ) {
				v.setValue(QVariant(value->ToBoolean()->Value()));
			} else if (value->IsNumber()) {
				v.setValue(QVariant(value->NumberValue()));
			} else if (value->IsInt32()) {
				v.setValue(QVariant(value->ToInt32()->Value()));
			} else if (value->IsString()) {
				String::Utf8Value _v(value->ToString());
				v.setValue(QVariant(static_cast<char *>(*_v)));
			}

			// Undefined
			return v;
		}

		QJSValue V8ToQJSValue(QQmlEngine *engine, Local<Value> value)
		{
			// Check data type
			if (value->IsNull()) {
				return engine->evaluate("null");
			} else if (value->IsTrue() || value->IsFalse() || value->IsBoolean() ) {
				return engine->toScriptValue(value->ToBoolean()->Value());
			} else if (value->IsNumber()) {
				return engine->toScriptValue(value->NumberValue());
			} else if (value->IsInt32()) {
				return engine->toScriptValue(value->ToInt32()->Value());
			} else if (value->IsString()) {
				String::Utf8Value _v(value->ToString());
				return engine->toScriptValue(QString(*_v));
			}

			// TODO: support array and object
			return engine->evaluate("undefined");
		}

		ParamData *MakeParameter(int type, Local<Value> value)
		{
			// Null
			if (value->IsNull()) {
				return new ParamData();
			}

			switch(type) {
			case QMetaType::Bool:
				return new ParamData(static_cast<bool>(value->ToBoolean()->Value()));
			case QMetaType::Int:
				return new ParamData(static_cast<qint32>(value->Int32Value()));
			case QMetaType::UInt:
				return new ParamData(static_cast<quint32>(value->Uint32Value()));
			case QMetaType::Float:
				return new ParamData(static_cast<float>(value->NumberValue()));
			case QMetaType::Double:
				return new ParamData(static_cast<double>(value->NumberValue()));
			case QMetaType::LongLong:
				return new ParamData(static_cast<long long>(value->IntegerValue()));
			case QMetaType::ULongLong:
				return new ParamData(static_cast<unsigned long long>(value->IntegerValue()));
			case QMetaType::QString:
				return new ParamData(*String::Utf8Value(value->ToString()));
			case QMetaType::QVariant:
				return new ParamData(V8ToQVariant(value));
			}

			return NULL;
		}
	}
}
<commit_msg>replace deprecated api<commit_after>#include <nan.h>
#include <QObject>
#include <QVariant>
#include <QMetaType>
#include <QQmlComponent>
#include "utils.h"

namespace Brig {

	using namespace v8;
	using namespace node;

	namespace Utils {

		Local<Value> QDataToV8(int type, void *value)
		{
			Nan::EscapableHandleScope scope;

			return scope.Escape(QVariantToV8(type, QVariant(type, value)));
		}

		Local<Value> QVariantToV8(int type, QVariant v)
		{
			Nan::EscapableHandleScope scope;

			switch(type) {
			case QMetaType::Bool:
				//return scope.Escape(Boolean::New(v.toBool()));
				return scope.Escape(Nan::New<Boolean>(v.toBool()));

			case QMetaType::Int:
				//return scope.Escape(Nan::New<Number>(v.toInt()));
				return scope.Escape(Nan::New<Int32>(v.toInt()));

			case QMetaType::UInt:
				return scope.Escape(Nan::New<Uint32>(v.toUInt()));

			case QMetaType::Float:
				return scope.Escape(Nan::New<Number>(v.toFloat()));

			case QMetaType::Double:
				return scope.Escape(Nan::New<Number>(v.toDouble()));

			case QMetaType::LongLong:

				return scope.Escape(Nan::New<Number>(v.toLongLong()));

			case QMetaType::ULongLong:
				return scope.Escape(Nan::New<Number>(v.toULongLong()));

			case QMetaType::QString:
				//return scope.Escape(Nan::New<String>(v.toString().toUtf8().constData()));
				return scope.Escape(Nan::New<String>(v.toString().toStdString()).ToLocalChecked());

			default:

				if (type == qMetaTypeId<QQmlComponent::Status>()) {
					return scope.Escape(Nan::New<Number>(v.toInt()));
				} else if (type == qMetaTypeId<qreal>()) {
					return scope.Escape(Nan::New<Number>(v.toDouble()));
				}

//			case QMetaType::QVariant:
			}

			return scope.Escape(Nan::Undefined());
		}

		QVariant V8ToQVariant(Local<Value> value)
		{
			QVariant v;

			// Check data type
			if (value->IsNull()) {
				v.setValue(QVariant(QMetaType::VoidStar, 0));
			} else if (value->IsTrue() || value->IsFalse() || value->IsBoolean() ) {
				v.setValue(QVariant(value->BooleanValue()));
			} else if (value->IsNumber()) {
				v.setValue(QVariant(value->NumberValue()));
			} else if (value->IsInt32()) {
				v.setValue(QVariant(value->Int32Value()));
			} else if (value->IsString()) {
				String::Utf8Value _v(value->ToString());
				v.setValue(QVariant(static_cast<char *>(*_v)));
			}

			// Undefined
			return v;
		}

		QJSValue V8ToQJSValue(QQmlEngine *engine, Local<Value> value)
		{
			// Check data type
			if (value->IsNull()) {
				return engine->evaluate("null");
			} else if (value->IsTrue() || value->IsFalse() || value->IsBoolean() ) {
				return engine->toScriptValue(value->BooleanValue());
			} else if (value->IsNumber()) {
				return engine->toScriptValue(value->NumberValue());
			} else if (value->IsInt32()) {
				return engine->toScriptValue(value->Int32Value());
			} else if (value->IsString()) {
				String::Utf8Value _v(value->ToString());
				return engine->toScriptValue(QString(*_v));
			}

			// TODO: support array and object
			return engine->evaluate("undefined");
		}

		ParamData *MakeParameter(int type, Local<Value> value)
		{
			// Null
			if (value->IsNull()) {
				return new ParamData();
			}

			switch(type) {
			case QMetaType::Bool:
				return new ParamData(static_cast<bool>(value->BooleanValue()));
			case QMetaType::Int:
				return new ParamData(static_cast<qint32>(value->Int32Value()));
			case QMetaType::UInt:
				return new ParamData(static_cast<quint32>(value->Uint32Value()));
			case QMetaType::Float:
				return new ParamData(static_cast<float>(value->NumberValue()));
			case QMetaType::Double:
				return new ParamData(static_cast<double>(value->NumberValue()));
			case QMetaType::LongLong:
				return new ParamData(static_cast<long long>(value->IntegerValue()));
			case QMetaType::ULongLong:
				return new ParamData(static_cast<unsigned long long>(value->IntegerValue()));
			case QMetaType::QString:
				return new ParamData(*String::Utf8Value(value->ToString()));
			case QMetaType::QVariant:
				return new ParamData(V8ToQVariant(value));
			}

			return NULL;
		}
	}
}
<|endoftext|>


<commit_before>#include <vili/utils.hpp>

#include <algorithm>

namespace vili::utils::string
{
    size_t count(const std::string& str, const std::string& occur)
    {
        int occurrences = 0;
        std::string::size_type start = 0;
        while ((start = str.find(occur, start)) != std::string::npos)
        {
            ++occurrences;
            start += occur.length();
        }
        return occurrences;
    }

    bool is_int(const std::string& str)
    {
        if (!str.empty())
        {
            if (str.substr(0, 1) == "-")
                return std::all_of(str.begin() + 1, str.end(), isdigit);
            return std::all_of(str.begin(), str.end(), isdigit);
        }
        return false;
    }

    bool is_float(const std::string& str)
    {
        std::string float_str = str;
        bool is_a_float = false;
        if (!float_str.empty())
        {
            if (float_str.substr(0, 1) == "-")
                float_str = float_str.substr(1);
            if (count(float_str, ".") == 1)
            {
                is_a_float = true;
                float_str.erase(float_str.find('.'));
            }
            return (std::all_of(float_str.begin(), float_str.end(), std::isdigit)
                && is_a_float);
        }
        return false;
    }

    std::string truncate_float(const std::string& str)
    {
        std::string result = str;
        while (
            result.size() > 2 && result.back() == '0' && result[result.size() - 2] != '.')
            result.pop_back();
        return result;
    }

    std::string quote(const std::string& str)
    {
        return "\"" + str + "\"";
    }

    std::string replace(
        std::string subject, const std::string& search, const std::string& replace)
    {
        size_t pos = 0;
        while ((pos = subject.find(search, pos)) != std::string::npos)
        {
            subject.replace(pos, search.length(), replace);
            pos += replace.length();
        }
        return subject;
    }
}<commit_msg>Fixed bad include<commit_after>#include <vili/utils.hpp>

#include <algorithm>
#include <cctype>

namespace vili::utils::string
{
    size_t count(const std::string& str, const std::string& occur)
    {
        int occurrences = 0;
        std::string::size_type start = 0;
        while ((start = str.find(occur, start)) != std::string::npos)
        {
            ++occurrences;
            start += occur.length();
        }
        return occurrences;
    }

    bool is_int(const std::string& str)
    {
        if (!str.empty())
        {
            if (str.substr(0, 1) == "-")
                return std::all_of(str.begin() + 1, str.end(), std::isdigit);
            return std::all_of(str.begin(), str.end(), std::isdigit);
        }
        return false;
    }

    bool is_float(const std::string& str)
    {
        std::string float_str = str;
        bool is_a_float = false;
        if (!float_str.empty())
        {
            if (float_str.substr(0, 1) == "-")
                float_str = float_str.substr(1);
            if (count(float_str, ".") == 1)
            {
                is_a_float = true;
                float_str.erase(float_str.find('.'));
            }
            return (std::all_of(float_str.begin(), float_str.end(), std::isdigit)
                && is_a_float);
        }
        return false;
    }

    std::string truncate_float(const std::string& str)
    {
        std::string result = str;
        while (
            result.size() > 2 && result.back() == '0' && result[result.size() - 2] != '.')
            result.pop_back();
        return result;
    }

    std::string quote(const std::string& str)
    {
        return "\"" + str + "\"";
    }

    std::string replace(
        std::string subject, const std::string& search, const std::string& replace)
    {
        size_t pos = 0;
        while ((pos = subject.find(search, pos)) != std::string::npos)
        {
            subject.replace(pos, search.length(), replace);
            pos += replace.length();
        }
        return subject;
    }
}<|endoftext|>


<commit_before>#include <cstring>
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include "words.h"
#include "test.cpp"

//implementation of Node
Node::Node(string token) {
    this->content = token;
}

void Node::setNext(Node* n) {
    this->next = n;
}

Node* Node::getNext() {
    return this->next;
}

string Node::getContent() {
    return this->content;
}

//state = 0 means success
//state = -1 means fail
void Node::run(int state) {
    //BEGIN: if the node is a connector
    if (content == "||") {
        if (state == 0) {
            next->run(-1);
        }else {
            next->run(0);
        }
        return;
    }

    if (content == "&&") {
        if (state == 0) {
            next->run(0);
        }else {
            next->run(-1);
        }
        return;
    }

    if (content == ";") {
        if (next == 0) {
        }else {
            next->run(0);
        }
        return;
    }
    //END: if the node is a connector

    //Then the node is a bash command
    if (state == 0){
        //strtok messes a WHOLE LOT with dynamic allocated arrays
        //to a point where properly freeing them isn't possible.
        char test[999];
        char cstr[999];
        char *pch1,*pch2, quit[] = "exit";
        int count = 0, i = 0;

        //we're cutting the string up twice
        //first time is to know how many slots in cmd do we need
        //second time creates the actual char** cmd into execute()
        strcpy(test, content.c_str());
        strcpy(cstr, content.c_str());

        pch1 = strtok(test, " ");
        while (pch1 != NULL) {
            count++;
            pch1 = strtok(NULL, " ");
        }

        //-Werror and -pedantic gave me a lot of trouble for this
        //so a variable length array is no good.
        char* cmd[100];
        pch2 = strtok(cstr, " ");
        while (pch2 != NULL) {
            cmd[i] = pch2;
            i++;
            pch2 = strtok(NULL, " ");
        }

        //quit rshell if the command is "exit" followed by whatever
        if (!strcmp(cmd[0], quit)) {
            exit(0);
        }

        cmd[count] = NULL;

        int status = execute(cmd);

        //if there's no other nodes behind this then return
        if (next == 0) return;

        //all things checked, run next string
        next->run(status);

        //delete[] test;
        //delete[] cstr;

    }else {
        if (next == 0) return;
        next->run(-1);
    }
}

//implementation of Line
Line::Line(const vector<string> &input) {
    head = 0;

    if (!input.empty()) {
        Node *a;

        head = new Node(input.at(0));
        a = head;

        for (unsigned int i = 1; i < input.size(); i++) {
            a->setNext(new Node(input.at(i)));
            a = a->getNext();
        }

        a->setNext(0);
    }
}

Line::~Line() {
    Node* a = head;
    Node* x;

    while (a != 0) {
        x = a;
        a = a->getNext();

        delete x;
    }
}

void Line::run(){
    if (head != 0) head->run(0);
}

//for testing purposes only
void Line::printLine() {
    Node* a = head;
    while (a != 0) {
        cout << a->getContent() << endl;
        a = a->getNext();
    }
}

//Executes a bash command, returns 0 if successful, -1 if uneventful.
//Note execvp returns success if the command is valid but the flag is not.
int execute(char* cmd[]) {

    pid_t pid;
    int status;
    int testResult;
    int output = 0;
    int fd[2];    //Wangho: This is a pipe made for passing variable
                  //        (this case: output) between parent and child
                  //        process.

    if (strcmp(cmd[0], "test") == 0 || strcmp(cmd[0], "[") == 0) {
        //cout << "I'm in the test zone" << endl;
        testResult = test(cmd);

        if (testResult == 0) {
            return 0;
        }else {
            return -1;
        }
    }

    if (pipe(fd) == -1) {
        perror("Pipe error");
    }

    pid = fork();
    if (pid < 0) {
        perror("fork() function error");
    }else if (pid == 0) {
        //Wangho: Close the read function of pipe
        if (close(fd[0] == -1)) {
            perror("Pipe closing error [0]");
        }
        //Wangho: This is the child process
        output = execvp(cmd[0], cmd);

        //Wangho: Will only be here if execp() fail, which means output failed
        if (write(fd[1], &output, sizeof(output)) == -1) {
            perror("Pipe writing error");
        }

        //perror for execvp
        perror(cmd[0]);
        exit(1);
    }else if (pid > 0) {
        //Wangho: Close the write function of pipe
        if (close(fd[1])) {
            perror("Pipe closing error [1]");
        }
        //Wangho: This is the parent process
        if (waitpid(pid, &status, 0) == -1) {
            perror("waitpid error");
        }

        //Wangho: When child process is fully returned
        if(WIFEXITED(status)){
            //Wangho: Take the output value; if execvp failed, it returns -1
            if (read(fd[0], &output, sizeof(output)) == -1) {
                perror("Pipe reading error");
            }
            return output;
        }
    }
    return -1;
}

/*
int main(){
    vector<string> ss;
    ss.push_back("ls      -a");
    ss.push_back("&&");
    ss.push_back("echo why");
    ss.push_back(";");
    ss.push_back("echo hello");

    Line abc(ss);
    abc.run();
    return 0;
}
*/
<commit_msg>Modified some code of the test command<commit_after>#include <cstring>
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include "words.h"
#include "test.cpp"

//implementation of Node
Node::Node(string token) {
    this->content = token;
}

void Node::setNext(Node* n) {
    this->next = n;
}

Node* Node::getNext() {
    return this->next;
}

string Node::getContent() {
    return this->content;
}

//state = 0 means success
//state = -1 means fail
void Node::run(int state) {
    //BEGIN: if the node is a connector
    if (content == "||") {
        if (state == 0) {
            next->run(-1);
        }else {
            next->run(0);
        }
        return;
    }

    if (content == "&&") {
        if (state == 0) {
            next->run(0);
        }else {
            next->run(-1);
        }
        return;
    }

    if (content == ";") {
        if (next == 0) {
        }else {
            next->run(0);
        }
        return;
    }
    //END: if the node is a connector

    //Then the node is a bash command
    if (state == 0){
        //strtok messes a WHOLE LOT with dynamic allocated arrays
        //to a point where properly freeing them isn't possible.
        char test[999];
        char cstr[999];
        char *pch1,*pch2, quit[] = "exit";
        int count = 0, i = 0;

        //we're cutting the string up twice
        //first time is to know how many slots in cmd do we need
        //second time creates the actual char** cmd into execute()
        strcpy(test, content.c_str());
        strcpy(cstr, content.c_str());

        pch1 = strtok(test, " ");
        while (pch1 != NULL) {
            count++;
            pch1 = strtok(NULL, " ");
        }

        //-Werror and -pedantic gave me a lot of trouble for this
        //so a variable length array is no good.
        char* cmd[100];
        pch2 = strtok(cstr, " ");
        while (pch2 != NULL) {
            cmd[i] = pch2;
            i++;
            pch2 = strtok(NULL, " ");
        }

        //quit rshell if the command is "exit" followed by whatever
        if (!strcmp(cmd[0], quit)) {
            exit(0);
        }

        cmd[count] = NULL;

        int status = execute(cmd);

        //if there's no other nodes behind this then return
        if (next == 0) return;

        //all things checked, run next string
        next->run(status);

        //delete[] test;
        //delete[] cstr;

    }else {
        if (next == 0) return;
        next->run(-1);
    }
}

//implementation of Line
Line::Line(const vector<string> &input) {
    head = 0;

    if (!input.empty()) {
        Node *a;

        head = new Node(input.at(0));
        a = head;

        for (unsigned int i = 1; i < input.size(); i++) {
            a->setNext(new Node(input.at(i)));
            a = a->getNext();
        }

        a->setNext(0);
    }
}

Line::~Line() {
    Node* a = head;
    Node* x;

    while (a != 0) {
        x = a;
        a = a->getNext();

        delete x;
    }
}

void Line::run(){
    if (head != 0) head->run(0);
}

//for testing purposes only
void Line::printLine() {
    Node* a = head;
    while (a != 0) {
        cout << a->getContent() << endl;
        a = a->getNext();
    }
}

//Executes a bash command, returns 0 if successful, -1 if uneventful.
//Note execvp returns success if the command is valid but the flag is not.
int execute(char* cmd[]) {

    pid_t pid;
    int status;
    int testResult;
    int output = 0;
    int fd[2];    //Wangho: This is a pipe made for passing variable
                  //        (this case: output) between parent and child
                  //        process.
    int last;

    for (int i = 0; cmd[i] != NULL; i++) {
        last++;
    }
    last = last - 1;
    //cout << "Last is: " << last << " content: " << cmd[last] << endl;

    if (strcmp(cmd[0], "test") == 0) {
        //cout << "I'm in the test zone" << endl;
        testResult = test(cmd);

        if (testResult == 0) {
            return 0;
        }else {
            return -1;
        }
    }

    if (strcmp(cmd[0], "[") == 0 && strcmp(cmd[last], "]") == 0) {
        testResult = test(cmd);

        if (testResult == 0) {
            return 0;
        }else {
            return -1;
        }
    }

    if (pipe(fd) == -1) {
        perror("Pipe error");
    }

    pid = fork();
    if (pid < 0) {
        perror("fork() function error");
    }else if (pid == 0) {
        //Wangho: Close the read function of pipe
        if (close(fd[0] == -1)) {
            perror("Pipe closing error [0]");
        }
        //Wangho: This is the child process
        output = execvp(cmd[0], cmd);

        //Wangho: Will only be here if execp() fail, which means output failed
        if (write(fd[1], &output, sizeof(output)) == -1) {
            perror("Pipe writing error");
        }

        //perror for execvp
        perror(cmd[0]);
        exit(1);
    }else if (pid > 0) {
        //Wangho: Close the write function of pipe
        if (close(fd[1])) {
            perror("Pipe closing error [1]");
        }
        //Wangho: This is the parent process
        if (waitpid(pid, &status, 0) == -1) {
            perror("waitpid error");
        }

        //Wangho: When child process is fully returned
        if(WIFEXITED(status)){
            //Wangho: Take the output value; if execvp failed, it returns -1
            if (read(fd[0], &output, sizeof(output)) == -1) {
                perror("Pipe reading error");
            }
            return output;
        }
    }
    return -1;
}

/*
int main(){
    vector<string> ss;
    ss.push_back("ls      -a");
    ss.push_back("&&");
    ss.push_back("echo why");
    ss.push_back(";");
    ss.push_back("echo hello");

    Line abc(ss);
    abc.run();
    return 0;
}
*/
<|endoftext|>


<commit_before>#ifndef X_XFT_HPP
#define X_XFT_HPP

#include <iostream>
#include <unordered_map>

#include <X11/Xft/Xft.h>

#include "data_types.hpp"

namespace x {

class xft {
  public:
    xft(Display * dpy,
        XVisualInfo * const visual_info, const Colormap & colormap,
        unsigned int width, unsigned int height)
      : m_dpy(dpy),
        m_visual_info(visual_info), m_colormap(colormap),
        m_width(width), m_height(height)
    {
      m_drawable = XCreatePixmap(
          m_dpy, DefaultRootWindow(m_dpy), width, height, m_visual_info->depth);
      m_xftdraw = XftDrawCreate(m_dpy, m_drawable, m_visual_info->visual, m_colormap);
    }

    ~xft(void)
    {
      XftDrawDestroy(m_xftdraw);

      for (auto & item : m_colors) {
        XftColorFree(m_dpy, m_visual_info->visual, m_colormap, &item.second);
      }

      for (auto & item : m_fonts) {
        XftFontClose(m_dpy, item.second);
      }

      if (m_drawable != None) XFreePixmap(m_dpy, m_drawable);
    }

    xft(const xft &) = delete;
    xft & operator=(const xft &) = delete;

    xft &
    draw_string_utf8(const std::string & text,
                     const unsigned int & x, const unsigned int & y)
    {
      XftDrawStringUtf8(m_xftdraw, &m_fg_color, m_font, x, y,
                        (FcChar8 *)text.c_str(), text.length());
      return *this;
    }

    XGlyphInfo
    text_extents_utf8(const x::type::fontname & fontname,
                      const std::string & text)
    {
      XGlyphInfo extents;
      XftTextExtentsUtf8(m_dpy, (*this)[fontname],
                         (FcChar8 *)text.c_str(), text.length(), &extents);
      return extents;
    }

    XftFont * const
    operator[](const x::type::fontname & fontname)
    {
      try {
        return m_fonts.at(*fontname);
      } catch (...) {
        m_fonts[*fontname] =
          XftFontOpenName(m_dpy, DefaultScreen(m_dpy), fontname->c_str());
        return m_fonts[*fontname];
      }
    }

    XftColor * const
    operator[](const x::type::colorname & colorname)
    {
      try {
        return &m_colors.at(*colorname);
      } catch (...) {
        XftColorAllocName(m_dpy, m_visual_info->visual, m_colormap,
                          colorname->c_str(), &m_colors[*colorname]);
        return &m_colors[*colorname];
      }
    }

    const Drawable & drawable(void)
    {
      return m_drawable;
    }

    xft & font(const x::type::fontname & font)
    {
      m_font = (*this)[font];
      return *this;
    }

    xft & foreground(const x::type::colorname & foreground)
    {
      m_fg_color = *(*this)[foreground];
      return *this;
    }

    xft & background(const x::type::colorname & background)
    {
      m_bg_color = *(*this)[background];
      return *this;
    }

    xft & fg_alpha(const double & a)
    {
      m_fg_color.color.alpha *= a;
      return *this;
    }

    xft & bg_alpha(const double & a)
    {
      m_bg_color.color.alpha *= a;
      return *this;
    }

    xft & fill(unsigned int x = 0, unsigned int y = 0,
               unsigned int width = 0, unsigned int height = 0)
    {
      width = width == 0 ? m_width : width;
      height = height == 0 ? m_height : height;
      XftDrawRect(m_xftdraw, &m_bg_color, x, y, m_width, m_height);
      return *this;
    }

  private:
    XftDraw * m_xftdraw;
    Display * m_dpy;
    Drawable m_drawable = None;

    XVisualInfo * const m_visual_info;
    const Colormap & m_colormap;

    unsigned int m_width = 0;
    unsigned int m_height = 0;

    XftFont * m_font;
    XftColor m_fg_color;
    XftColor m_bg_color;

    std::unordered_map<std::string, XftColor> m_colors;
    std::unordered_map<std::string, XftFont *> m_fonts;
}; // class xft

}; // namespace x

#endif // X_XFT_HPP
<commit_msg>Actually set the alpha value<commit_after>#ifndef X_XFT_HPP
#define X_XFT_HPP

#include <iostream>
#include <unordered_map>

#include <X11/Xft/Xft.h>

#include "data_types.hpp"

namespace x {

class xft {
  public:
    xft(Display * dpy,
        XVisualInfo * const visual_info, const Colormap & colormap,
        unsigned int width, unsigned int height)
      : m_dpy(dpy),
        m_visual_info(visual_info), m_colormap(colormap),
        m_width(width), m_height(height)
    {
      m_drawable = XCreatePixmap(
          m_dpy, DefaultRootWindow(m_dpy), width, height, m_visual_info->depth);
      m_xftdraw = XftDrawCreate(m_dpy, m_drawable, m_visual_info->visual, m_colormap);
    }

    ~xft(void)
    {
      XftDrawDestroy(m_xftdraw);

      for (auto & item : m_colors) {
        XftColorFree(m_dpy, m_visual_info->visual, m_colormap, &item.second);
      }

      for (auto & item : m_fonts) {
        XftFontClose(m_dpy, item.second);
      }

      if (m_drawable != None) XFreePixmap(m_dpy, m_drawable);
    }

    xft(const xft &) = delete;
    xft & operator=(const xft &) = delete;

    xft &
    draw_string_utf8(const std::string & text,
                     const unsigned int & x, const unsigned int & y)
    {
      XftDrawStringUtf8(m_xftdraw, &m_fg_color, m_font, x, y,
                        (FcChar8 *)text.c_str(), text.length());
      return *this;
    }

    XGlyphInfo
    text_extents_utf8(const x::type::fontname & fontname,
                      const std::string & text)
    {
      XGlyphInfo extents;
      XftTextExtentsUtf8(m_dpy, (*this)[fontname],
                         (FcChar8 *)text.c_str(), text.length(), &extents);
      return extents;
    }

    XftFont * const
    operator[](const x::type::fontname & fontname)
    {
      try {
        return m_fonts.at(*fontname);
      } catch (...) {
        m_fonts[*fontname] =
          XftFontOpenName(m_dpy, DefaultScreen(m_dpy), fontname->c_str());
        return m_fonts[*fontname];
      }
    }

    XftColor * const
    operator[](const x::type::colorname & colorname)
    {
      try {
        return &m_colors.at(*colorname);
      } catch (...) {
        XftColorAllocName(m_dpy, m_visual_info->visual, m_colormap,
                          colorname->c_str(), &m_colors[*colorname]);
        return &m_colors[*colorname];
      }
    }

    const Drawable & drawable(void)
    {
      return m_drawable;
    }

    xft & font(const x::type::fontname & font)
    {
      m_font = (*this)[font];
      return *this;
    }

    xft & foreground(const x::type::colorname & foreground)
    {
      m_fg_color = *(*this)[foreground];
      return *this;
    }

    xft & background(const x::type::colorname & background)
    {
      m_bg_color = *(*this)[background];
      return *this;
    }

    xft & fg_alpha(const double & a)
    {
      m_fg_color.color.alpha = a * 0xffff;
      return *this;
    }

    xft & bg_alpha(const double & a)
    {
      m_bg_color.color.alpha = a * 0xffff;
      return *this;
    }

    xft & fill(unsigned int x = 0, unsigned int y = 0,
               unsigned int width = 0, unsigned int height = 0)
    {
      width = width == 0 ? m_width : width;
      height = height == 0 ? m_height : height;
      XftDrawRect(m_xftdraw, &m_bg_color, x, y, m_width, m_height);
      return *this;
    }

  private:
    XftDraw * m_xftdraw;
    Display * m_dpy;
    Drawable m_drawable = None;

    XVisualInfo * const m_visual_info;
    const Colormap & m_colormap;

    unsigned int m_width = 0;
    unsigned int m_height = 0;

    XftFont * m_font;
    XftColor m_fg_color;
    XftColor m_bg_color;

    std::unordered_map<std::string, XftColor> m_colors;
    std::unordered_map<std::string, XftFont *> m_fonts;
}; // class xft

}; // namespace x

#endif // X_XFT_HPP
<|endoftext|>


<commit_before>// Filename: 	localsearch.cpp
// Author: 		Christopher Goes
// Course: 		CS 572 Evolutionary Computation
// Semester: 	Fall 2016
// Description:	Assignment 1 - Local Search
// Github:		https://github.com/GhostofGoes/cgoes-cs572

#include "localSearchLib.h"
int encoding, mutation;

inline double fitness( double x, double y );  // Single-peak fitness function that evaluates quality of x and y
inline Bit64 randomJump( Bit64 chromosome, int size );  // Mutation randomly jumps to somewhere in search space
inline Bit64 bitFlip( Bit64 chromosome );  // Mutation randomly flips exactly one bit in the 20 bit chromosome
Bit64 sdIncDec( Bit64 chromosome ); // Mutation increments or decrements one of the fields of 10 bits fields for x or for y (4 possible changes/neighbors)

Bit32 extractX( Bit64 genome ); // Gets x chromosome from the genome
Bit32 extractY( Bit64 genome ); // Gets y chromosome from the genome
inline Bit64 randomGenotype();

int main( int argc, char *argv[] ) {
	if(argc < 3) { // so we don't segfault on something silly like forgetting arguments lol
		cout << "Not enough arguments: need encoding(0|1) and mutation(0|1|2)." << endl;
		return 1;
	}
	encoding = (int)*argv[1];  // 0 = identity, 1 = Grey
	mutation = (int)*argv[2];  // 0 = random jump, 1 = bit flip, 2 = int/dec
	initRand();  // Initialize random number generator

	if(false) {
		cout << fitness(5, 1) << endl;
		Bit64 test = 1048575; // 2^20 - 1, which is first 20 bits set to 1
		//test = bitGray(test);
		Bit64 x = extractX(test);
		Bit64 y = extractY(test);
		cout << map(double(x), 0.0, 1023.0, 0.0, 10.0) << endl;
		cout << map(double(y), 0.0, 1023.0, -10.0, 10.0) << endl;
		printBinary(test);
		printBinary(x);
		printBinary(y);
		Bit64 randJump = randomJump(test, 20);
		Bit64 bflip = bitFlip(test);
		Bit64 sd = sdIncDec(test);
		printf("randJump(%llu): %llu\n", test, randJump);
		printBinary(randJump);
		printf("bitFlip(%llu): %llu\n", test, bflip);
		printBinary(bflip);
		printf("sdIncDec(%llu): %llu\n", test, sd);
		printBinary(sd);
		Bit64 temp = randomGenotype();
		printBinary(temp);
		cout << temp << endl;

	}
	else {
		int runs = 1000;
		if(TESTING) runs = 1;
		for( int i = 0; i < runs; i++ ) { // Used to average behavior of program across many runs
			Bit64 genotype = randomGenotype(); // Represents chromosome, 20 Least-signifigant Bits (LSB) of an UUL
			Bit32 x = 0; // Chromosome composed of the 10 Most-signifigant bits (MSB) of the Genotype
			Bit32 y = 0; // Chromosome compoased of 10 LSB of the Genotype
			double xprime = 0; // Used to represent decimal value of X for fitness function
			double yprime = 0; // See above
			double currentFitness = 0.0; // Current fitness to compare against best
			double bestFitness = 0.0; // Best fitness found
			int numImproveMoves = 0; // Number of times fitness was improved
			int numFitEvalsBest = 0; // Number of fitness evaluations it took to get best fitness
			double fit_xprime = 0.0;
			double fit_yprime = 0.0;

			if(TESTING) printBinary(genotype);
			int evals = 10000;
			if(TESTING) evals = 5;
			for( int fitEvals = 0; fitEvals < evals; fitEvals++ ) { // Fitness evaluation loop
				// Mutate: 0 = random jump, 1 = bit flip, 2 = int/dec
				if( mutation == 0 ) {
					x = randomJump(genotype, 10);
					y = randomJump(genotype, 10);
				} else if( mutation == 1 ) {
					x = bitFlip(genotype);
					y = bitFlip(genotype);
				} else if( mutation == 2 ) {
					x = sdIncDec(genotype);
					y = sdIncDec(genotype);
				}

				// Convert binary mutations to decimal for fitness evaluation
				xprime = map(double(x), 0.0, 1023.0, 0.0, 10.0); 	// x range = [0, 10]
				yprime = map(double(y), 0.0, 1023.0, -10.0, 10.0); 	// y range = [-10, 10]
				printf("Pre-eval:\txprime: %f\typrime: %f\n", xprime, yprime);
				// Evaluate fitness
				currentFitness = fitness(xprime, yprime);

				// If the fitness we found is better, save it's genotype, fitness, and iterations taken
				if( currentFitness > bestFitness ) {
					bestFitness = currentFitness;
					numFitEvalsBest = fitEvals;
					fit_xprime = xprime;
					fit_yprime = yprime;
					numImproveMoves++;
				}

			} // end fitness eval loop

			// Output results of the run
			printf("%d %d %f %f %f\n", numFitEvalsBest, numImproveMoves, fit_xprime, fit_yprime, bestFitness);
			//cout << numFitEvalsBest << numImproveMoves << fit_xprime << fit_yprime << bestFitness << endl;
		} // end program loop
	}
	return 0;
} // end main

inline double fitness( double x, double y ) {
	return 1.0 / ( pow((x - 1.0), 2) + pow((y - 3.0), 2) + 1.0 );
}

inline Bit64 randomJump( Bit64 chromosome, int size ) {
	return randMask((1ULL << size) - 1); // Mask is number of bits in chromosome
}

inline Bit64 bitFlip( Bit64 chromosome ) { // Assumes a 20 bit chromosome
	// int randBit = randMod(20) + 1; // We want range to be [1, 20] not [0, 19], hence the +1
	return chromosome ^ (1ULL << (randMod(20) + 1)); // Flip a random bit in the chromosome
}

Bit64 sdIncDec( Bit64 chromosome ) {
	Bit32 x = chromosome >> 10;
	Bit32 y = chromosome & ((1ULL << 10) - 1);
	Bit64 newChromosome = 0;
	int change = randMod(4); // 0 = x + inc, 1 = x + dec, 2 = y + inc, 3 = y + dec
	// printf("OLD\t chromo: %llu \t x: %d \t y: %d \n", chromosome, x, y);
	if( change == 0 ) { // Increment X (MSD of genotype)
		if( x == 1023 ) x = 0; // 1024 == 2^10 (or 2**10 in python its handy)
		else x += 1;
	} else if( change == 1 ) { // Decrement X (MSD of genotype)
		if( x == 0 ) x = 1023;
		else x -= 1;
	} else if( change == 2 ) { // Increment Y (LSD of genotype)
		if( y == 1023 ) y = 0;
		else y += 1;
	} else if( change == 3 ) { // Decrement Y (LSD of genotype)
		if( y == 0 ) y = 1023;
		else y -= 1;
	}

	// Recombine modified X and Y
	newChromosome = x << 10;
	newChromosome |= y;
	// printf("NEW\t chromo: %llu \t x: %d \t  y: %d \n", newChromosome, x, y);
	return newChromosome;
}

Bit32 extractX( Bit64 genome ) {
	Bit32 x = genome >> 10; // Get the 10 Most signifigant bits in genome
	if( encoding == 1 ) // Grey code mapping
		x = bitDeGray(x);
	return x;
}

Bit32 extractY( Bit64 genome ) {
	Bit32 y = genome & ((1ULL << 10) - 1); // Get the 10 Least signifigant bits out of genome
	if( encoding == 1 ) // Grey code mapping
		y = bitDeGray(y);
	return y;
}

inline Bit64 randomGenotype() {
	return randULL() & 1048575; // 2^20 - 1
}
<commit_msg>Actually doing things now huh<commit_after>// Filename: 	localsearch.cpp
// Author: 		Christopher Goes
// Course: 		CS 572 Evolutionary Computation
// Semester: 	Fall 2016
// Description:	Assignment 1 - Local Search
// Github:		https://github.com/GhostofGoes/cgoes-cs572

#include "localSearchLib.h"
int encoding, mutation;

inline double fitness( double x, double y );  // Single-peak fitness function that evaluates quality of x and y
inline Bit64 randomJump( Bit64 chromosome, int size );  // Mutation randomly jumps to somewhere in search space
inline Bit64 bitFlip( Bit64 chromosome );  // Mutation randomly flips exactly one bit in the 20 bit chromosome
Bit64 sdIncDec( Bit64 chromosome ); // Mutation increments or decrements one of the fields of 10 bits fields for x or for y (4 possible changes/neighbors)

Bit32 extractX( Bit64 genome ); // Gets x chromosome from the genome
Bit32 extractY( Bit64 genome ); // Gets y chromosome from the genome
inline Bit64 randomGenotype();

int main( int argc, char *argv[] ) {
	if(argc < 3) { // so we don't segfault on something silly like forgetting arguments lol
		cout << "Not enough arguments: need encoding(0|1) and mutation(0|1|2)." << endl;
		return 1;
	}
	encoding = (int)*argv[1];  // 0 = identity, 1 = Grey
	mutation = (int)*argv[2];  // 0 = random jump, 1 = bit flip, 2 = int/dec
	initRand();  // Initialize random number generator

	if(false) {
		cout << fitness(5, 1) << endl;
		Bit64 test = 1048575; // 2^20 - 1, which is first 20 bits set to 1
		//test = bitGray(test);
		Bit64 x = extractX(test);
		Bit64 y = extractY(test);
		cout << map(double(x), 0.0, 1023.0, 0.0, 10.0) << endl;
		cout << map(double(y), 0.0, 1023.0, -10.0, 10.0) << endl;
		printBinary(test);
		printBinary(x);
		printBinary(y);
		Bit64 randJump = randomJump(test, 20);
		Bit64 bflip = bitFlip(test);
		Bit64 sd = sdIncDec(test);
		printf("randJump(%llu): %llu\n", test, randJump);
		printBinary(randJump);
		printf("bitFlip(%llu): %llu\n", test, bflip);
		printBinary(bflip);
		printf("sdIncDec(%llu): %llu\n", test, sd);
		printBinary(sd);
		Bit64 temp = randomGenotype();
		printBinary(temp);
		cout << temp << endl;
	}
	else {
		int runs = 1000;
		if(TESTING) runs = 1;
		for( int i = 0; i < runs; i++ ) { // Used to average behavior of program across many runs
			Bit64 genotype = randomGenotype(); // Represents chromosome, 20 Least-signifigant Bits (LSB) of an UUL
			if(TESTING) printBinary(genotype);
			Bit32 x = 0; // Chromosome composed of the 10 Most-signifigant bits (MSB) of the Genotype
			Bit32 y = 0; // Chromosome compoased of 10 LSB of the Genotype
			double xprime = 0; // Used to represent decimal value of X for fitness function
			double yprime = 0; // See above
			double currentFitness = 0.0; // Current fitness to compare against best
			double bestFitness = 0.0; // Best fitness found
			int numImproveMoves = 0; // Number of times fitness was improved
			int numFitEvalsBest = 0; // Number of fitness evaluations it took to get best fitness
			double fit_xprime = 0.0;
			double fit_yprime = 0.0;

			int evals = 10000;
			if(TESTING) evals = 5;
			for( int fitEvals = 0; fitEvals < evals; fitEvals++ ) { // Fitness evaluation loop
				// Mutate: 0 = random jump, 1 = bit flip, 2 = int/dec
				if( mutation == 0 ) {
					genotype = randomJump(genotype, 20);
				} else if( mutation == 1 ) {
					genotype = bitFlip(genotype);
				} else if( mutation == 2 ) {
					genotype = sdIncDec(genotype);
				}

				// Genotype to phenotype mapping
				x = extractX(genotype);
				y = extractY(genotype);
				xprime = map(double(x), 0.0, 1023.0, 0.0, 10.0); 	// x range = [0, 10]
				yprime = map(double(y), 0.0, 1023.0, -10.0, 10.0); 	// y range = [-10, 10]
				printf("Pre-eval:\txprime: %f\typrime: %f\n", xprime, yprime);

				// Evaluate fitness
				currentFitness = fitness(xprime, yprime);

				// If the fitness we found is better, save it's genotype, fitness, and iterations taken
				if( currentFitness > bestFitness ) {
					bestFitness = currentFitness;
					numFitEvalsBest = fitEvals;
					fit_xprime = xprime;
					fit_yprime = yprime;
					numImproveMoves++;
				}
			} // end fitness eval loop

			// Output results of the run
			printf("%d %d %f %f %f\n", numFitEvalsBest, numImproveMoves, fit_xprime, fit_yprime, bestFitness);
			//cout << numFitEvalsBest << numImproveMoves << fit_xprime << fit_yprime << bestFitness << endl;
		} // end program loop
	}
	return 0;
} // end main

inline double fitness( double x, double y ) {
	return 1.0 / ( pow((x - 1.0), 2) + pow((y - 3.0), 2) + 1.0 );
}

inline Bit64 randomJump( Bit64 chromosome, int size ) {
	return randMask((1ULL << size) - 1); // Mask is number of bits in chromosome
}

inline Bit64 bitFlip( Bit64 chromosome ) { // Assumes a 20 bit chromosome
	// int randBit = randMod(20) + 1; // We want range to be [1, 20] not [0, 19], hence the +1
	return chromosome ^ (1ULL << (randMod(20) + 1)); // Flip a random bit in the chromosome
}

Bit64 sdIncDec( Bit64 chromosome ) {
	// TODO: issue with grey encoding here!
	Bit32 x = chromosome >> 10;
	Bit32 y = chromosome & ((1ULL << 10) - 1);
	Bit64 newChromosome = 0;
	int change = randMod(4); // 0 = x + inc, 1 = x + dec, 2 = y + inc, 3 = y + dec
	// printf("OLD\t chromo: %llu \t x: %d \t y: %d \n", chromosome, x, y);
	if( change == 0 ) { // Increment X (MSD of genotype)
		if( x == 1023 ) x = 0; // 1024 == 2^10 (or 2**10 in python its handy)
		else x += 1;
	} else if( change == 1 ) { // Decrement X (MSD of genotype)
		if( x == 0 ) x = 1023;
		else x -= 1;
	} else if( change == 2 ) { // Increment Y (LSD of genotype)
		if( y == 1023 ) y = 0;
		else y += 1;
	} else if( change == 3 ) { // Decrement Y (LSD of genotype)
		if( y == 0 ) y = 1023;
		else y -= 1;
	}

	// Recombine modified X and Y
	newChromosome = x << 10;
	newChromosome |= y;
	// printf("NEW\t chromo: %llu \t x: %d \t  y: %d \n", newChromosome, x, y);
	return newChromosome;
}

Bit32 extractX( Bit64 genome ) {
	Bit32 x = genome >> 10; // Get the 10 Most signifigant bits in genome
	if( encoding == 1 ) // Grey code mapping
		x = bitDeGray(x);
	return x;
}

Bit32 extractY( Bit64 genome ) {
	Bit32 y = genome & ((1ULL << 10) - 1); // Get the 10 Least signifigant bits out of genome
	if( encoding == 1 ) // Grey code mapping
		y = bitDeGray(y);
	return y;
}

inline Bit64 randomGenotype() {
	return randULL() & 1048575; // 2^20 - 1
}
<|endoftext|>


<commit_before>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"

using namespace MathLib;

#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO

/*
*/
#define ACTOR_BASE_IFPS             (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP            89.9f
#define ACTOR_BASE_COLLISIONS       4

/*
*/
CActorBase::CActorBase()
{
	m_vUp = vec3(0.0f, 0.0f, 1.0f);
	m_pObject = new CObjectDummy();
	m_pDummy = new CBodyDummy();
	m_pShape = new CShapeCapsule(1.0f, 1.0f);

	m_nFlush = 0;
	m_vPosition = Vec3_zero;
	m_vVelocity = Vec3_zero;
	m_fPhiAngle = 0.0f;			//倾斜角		二维平面坐标系中，直线向Y周延伸的方向与X轴正向之间的夹角
	m_fThetaAngle = 0.0f;			//方位角，正北方那条线与当前线条按照顺时针走过的角度

	for (int i = 0; i < NUM_STATES; i++)
	{
		m_pStates[i] = 0;
		m_pTimes[i] = 0.0f;
	}
	m_pDummy->SetEnabled(1);
	m_pObject->SetBody(NULL);
	m_pObject->SetBody(m_pDummy);
	m_pShape->SetBody(NULL);
	m_pShape->SetBody(m_pDummy);

	m_pObject->SetWorldTransform(Get_Body_Transform());
	m_pShape->SetRestitution(0.0f);
	m_pShape->SetCollisionMask(2);

	SetEnabled(1);
	SetViewDirection(vec3(0.0f, 1.0f, 0.0f));
	SetCollision(1);
	SetCollisionRadius(0.3f);
	SetCollisionHeight(1.0f);
	SetFriction(2.0f);
	SetMinVelocity(2.0f);
	SetMaxVelocity(4.0f);
	SetAcceleration(8.0f);
	SetDamping(8.0f);
	SetJumping(1.5f);

	SetGround(0);
	SetCeiling(0);
}

CActorBase::~CActorBase()
{
	m_pDummy->SetObject(NULL);
	delete m_pObject;
	delete m_pDummy;
}

void CActorBase::SetEnabled(int enable)
{
	m_nEnable = enable;
	m_pDummy->SetEnabled(m_nEnable);
}

int CActorBase::IsEnabled() const
{
	return m_nEnable;
}
void CActorBase::Update(float ifps)
{
	if (!m_nEnable)
	{
		return;
	}

	// impulse
	vec3 impulse = vec3_zero;

	// ortho basis
	vec3 tangent, binormal;
	OrthoBasis(m_vUp, tangent, binormal);

	// current basis
	vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
	vec3 y = Normalize(Cross(m_vUp, x));
	vec3 z = Normalize(Cross(x, y));

	handle states
		Update_States(1, ifps);

	// old velocity
	float x_velocity = Dot(x, m_vVelocity);
	float y_velocity = Dot(y, m_vVelocity);
	float z_velocity = Dot(z, m_vVelocity);
	// movement
	if (m_pStates[STATE_FORWARD]) impulse += x;
	if (m_pStates[STATE_BACKWARD]) impulse -= x;
	if (m_pStates[STATE_MOVE_LEFT]) impulse += y;
	if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y;
	impulse.normalize();
	//velocity
	if (m_pStates[STATE_RUN])
		impulse *= m_fMaxVelocity;
	else
		impulse *= m_fMinVelocity;
	// jump
	if (m_pStates[STATE_JUMP] == STATE_BEGIN)
	{
		impulse += z * CMathCore::Sqrt(2.0f * 9.8f * m_fJumping) / (m_fAcceleration * ifps);
	}

	// rotate velocity
	if (GetGround())
	{
		m_vVelocity = x * x_velocity + y * y_velocity + z * z_velocity;
	}

	// time
	float time = ifps * g_Engine.pPhysics->GetScale();

	// target velocity
	float target_velocity = Length(vec2(Dot(x, impulse), Dot(y, impulse)));

	// penetration tolerance
	float penetration = g_Engine.pPhysics->GetPenetrationTolerance();
	float penetration_2 = penetration * 2.0f;

	// frozen linear velocity
	float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();

	// friction
	float friction = 0.0f;
	if (target_velocity < EPSILON)
	{
		friction = m_fFriction;
	}

}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"

using namespace MathLib;

#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO

/*
*/
#define ACTOR_BASE_IFPS             (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP            89.9f
#define ACTOR_BASE_COLLISIONS       4

/*
*/
CActorBase::CActorBase()
{
	m_vUp = vec3(0.0f, 0.0f, 1.0f);
	m_pObject = new CObjectDummy();
	m_pDummy = new CBodyDummy();
	m_pShape = new CShapeCapsule(1.0f, 1.0f);

	m_nFlush = 0;
	m_vPosition = Vec3_zero;
	m_vVelocity = Vec3_zero;
	m_fPhiAngle = 0.0f;			//倾斜角		二维平面坐标系中，直线向Y周延伸的方向与X轴正向之间的夹角
	m_fThetaAngle = 0.0f;			//方位角，正北方那条线与当前线条按照顺时针走过的角度

	for (int i = 0; i < NUM_STATES; i++)
	{
		m_pStates[i] = 0;
		m_pTimes[i] = 0.0f;
	}
	m_pDummy->SetEnabled(1);
	m_pObject->SetBody(NULL);
	m_pObject->SetBody(m_pDummy);
	m_pShape->SetBody(NULL);
	m_pShape->SetBody(m_pDummy);

	m_pObject->SetWorldTransform(Get_Body_Transform());
	m_pShape->SetRestitution(0.0f);
	m_pShape->SetCollisionMask(2);

	SetEnabled(1);
	SetViewDirection(vec3(0.0f, 1.0f, 0.0f));
	SetCollision(1);
	SetCollisionRadius(0.3f);
	SetCollisionHeight(1.0f);
	SetFriction(2.0f);
	SetMinVelocity(2.0f);
	SetMaxVelocity(4.0f);
	SetAcceleration(8.0f);
	SetDamping(8.0f);
	SetJumping(1.5f);

	SetGround(0);
	SetCeiling(0);
}

CActorBase::~CActorBase()
{
	m_pDummy->SetObject(NULL);
	delete m_pObject;
	delete m_pDummy;
}

void CActorBase::SetEnabled(int enable)
{
	m_nEnable = enable;
	m_pDummy->SetEnabled(m_nEnable);
}

int CActorBase::IsEnabled() const
{
	return m_nEnable;
}
void CActorBase::Update(float ifps)
{
	if (!m_nEnable)
	{
		return;
	}

	// impulse
	vec3 impulse = vec3_zero;

	// ortho basis
	vec3 tangent, binormal;
	OrthoBasis(m_vUp, tangent, binormal);

	// current basis
	vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
	vec3 y = Normalize(Cross(m_vUp, x));
	vec3 z = Normalize(Cross(x, y));

	handle states
		Update_States(1, ifps);

	// old velocity
	float x_velocity = Dot(x, m_vVelocity);
	float y_velocity = Dot(y, m_vVelocity);
	float z_velocity = Dot(z, m_vVelocity);
	// movement
	if (m_pStates[STATE_FORWARD]) impulse += x;
	if (m_pStates[STATE_BACKWARD]) impulse -= x;
	if (m_pStates[STATE_MOVE_LEFT]) impulse += y;
	if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y;
	impulse.normalize();
	//velocity
	if (m_pStates[STATE_RUN])
		impulse *= m_fMaxVelocity;
	else
		impulse *= m_fMinVelocity;
	// jump
	if (m_pStates[STATE_JUMP] == STATE_BEGIN)
	{
		impulse += z * CMathCore::Sqrt(2.0f * 9.8f * m_fJumping) / (m_fAcceleration * ifps);
	}

	// rotate velocity
	if (GetGround())
	{
		m_vVelocity = x * x_velocity + y * y_velocity + z * z_velocity;
	}

	// time
	float time = ifps * g_Engine.pPhysics->GetScale();

	// target velocity
	float target_velocity = Length(vec2(Dot(x, impulse), Dot(y, impulse)));

	// penetration tolerance
	float penetration = g_Engine.pPhysics->GetPenetrationTolerance();
	float penetration_2 = penetration * 2.0f;

	// frozen linear velocity
	float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();

	// friction
	float friction = 0.0f;
	if (target_velocity < EPSILON)
	{
		friction = m_fFriction;
	}

	//clear collision flags
	if (GetCollision())
	{
		m_nGround = 0;
		m_nCeiling = 0;
	}

}<|endoftext|>


<commit_before>// Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//

// SMESH SMESHGUI : GUI for SMESH component
// File   : SMESHGUI_MeshUtils.cxx
// Author : Open CASCADE S.A.S.
// SMESH includes
//
#include "SMESHGUI_MeshUtils.h"

#include "SMESHGUI.h"
#include "SMESHGUI_Utils.h"

// SALOME KERNEL includes
#include <SALOMEDSClient_Study.hxx>

// Qt includes
#include <QStringList>

// IDL includes
#include <SALOMEconfig.h>
#include CORBA_SERVER_HEADER(SMESH_Group)
#include CORBA_SERVER_HEADER(SMESH_Measurements)

namespace SMESH
{
  SMESH_Mesh_var GetMeshByIO(const Handle(SALOME_InteractiveObject)& theIO)
  {
    CORBA::Object_var anObj = IObjectToObject(theIO);
    if(!CORBA::is_nil(anObj)){
      SMESH_Mesh_var aMesh = SMESH_Mesh::_narrow(anObj);
      if(!CORBA::is_nil(aMesh))
        return aMesh;
      SMESH_GroupBase_var aGroup = SMESH_GroupBase::_narrow(anObj);
      if(!CORBA::is_nil(aGroup))
        return aGroup->GetMesh();
      SMESH_subMesh_var aSubMesh = SMESH_subMesh::_narrow(anObj);
      if(!CORBA::is_nil(aSubMesh))
        return aSubMesh->GetFather();
    }
    return SMESH_Mesh::_nil();
  }

  QString UniqueMeshName(const QString& theBaseName, const QString& thePostfix)
  {
    QString baseName = thePostfix.isEmpty() ?
      theBaseName : theBaseName + "_" + thePostfix;
    if ( _PTR(Study) aStudy = GetActiveStudyDocument() ) {
      QString name = baseName;
      while ( !aStudy->FindObjectByName( name.toLatin1().data(), "SMESH" ).empty() ) {
        int nb = 0;
        QStringList names = name.split("_", QString::KeepEmptyParts);
        if ( names.count() > 0 ) {
          bool ok;
          int index = names.last().toInt( &ok );
          if ( ok ) {
            nb = index;
            names.removeLast();
          }
        }
        names.append( QString::number( nb+1 ) );
        name = names.join( "_" );
      }
      return name;
    }
    return baseName;
  }

  QString UniqueName(const QString& theBaseName, _PTR(SObject) theParent, const QString& thePostfix)
  {
    QString baseName = thePostfix.isEmpty() ?
      theBaseName : theBaseName + "_" + thePostfix;
    QString name = baseName;
    if ( _PTR(Study) aStudy = GetActiveStudyDocument() ) {
      _PTR(SObject) p = theParent;
      if ( !p ) p = aStudy->FindComponent( "SMESH" );
      if ( p ) {
        _PTR(ChildIterator) iter = aStudy->NewChildIterator( p );
        int idx = 0;
        while( true ) {
          bool found = false;
          for ( ; iter->More(); iter->Next() ) {
            _PTR(SObject) so = iter->Value();
            if ( !so ) continue; // skip bad objects
            _PTR(SObject) ref;
            if ( so->ReferencedObject( ref ) ) continue; // skip references
            QString n = so->GetName().c_str();
            if ( !n.isEmpty() && n == name ) {
              QStringList names = name.split("_", QString::KeepEmptyParts);
              if ( names.count() > 0 ) {
                bool ok;
                names.last().toInt( &ok );
                if ( ok )
                  names.removeLast();
              }
              names.append( QString::number( ++idx ) );
              name = names.join( "_" );
              found = true;
              break;
            }
          }
          if ( !found ) break;
        }
      }
    }
    return name;
  }

  SMESH::Measurements_var& GetMeasurements()
  {
    static SMESH::Measurements_var aMeasurements;
    if (CORBA::is_nil(aMeasurements)) {
      aMeasurements = SMESHGUI::GetSMESHGen()->CreateMeasurements();
    }
    return aMeasurements;
  }
} // end of namespace SMESH
<commit_msg>0022108: EDF 2547 SMESH: Duplicate elements only<commit_after>// Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//

// SMESH SMESHGUI : GUI for SMESH component
// File   : SMESHGUI_MeshUtils.cxx
// Author : Open CASCADE S.A.S.
// SMESH includes
//
#include "SMESHGUI_MeshUtils.h"

#include "SMESHGUI.h"
#include "SMESHGUI_Utils.h"

// SALOME KERNEL includes
#include <SALOMEDSClient_Study.hxx>

// Qt includes
#include <QStringList>

// IDL includes
#include <SALOMEconfig.h>
#include CORBA_SERVER_HEADER(SMESH_Group)
#include CORBA_SERVER_HEADER(SMESH_Measurements)

namespace SMESH
{
  SMESH_Mesh_var GetMeshByIO(const Handle(SALOME_InteractiveObject)& theIO)
  {
    CORBA::Object_var anObj = IObjectToObject(theIO);
    if(!CORBA::is_nil(anObj)){
      SMESH_Mesh_var aMesh = SMESH_Mesh::_narrow(anObj);
      if(!CORBA::is_nil(aMesh))
        return aMesh;
      SMESH_GroupBase_var aGroup = SMESH_GroupBase::_narrow(anObj);
      if(!CORBA::is_nil(aGroup))
        return aGroup->GetMesh();
      SMESH_subMesh_var aSubMesh = SMESH_subMesh::_narrow(anObj);
      if(!CORBA::is_nil(aSubMesh))
        return aSubMesh->GetFather();
    }
    return SMESH_Mesh::_nil();
  }

  QString UniqueMeshName(const QString& theBaseName, const QString& thePostfix)
  {
    QString baseName = thePostfix.isEmpty() ?
      theBaseName : theBaseName + "_" + thePostfix;
    if ( _PTR(Study) aStudy = GetActiveStudyDocument() ) {
      QString name = baseName;
      while ( !aStudy->FindObjectByName( name.toLatin1().data(), "SMESH" ).empty() ) {
        int nb = 0;
        QStringList names = name.split("_", QString::KeepEmptyParts);
        if ( names.count() > 0 ) {
          bool ok;
          int index = names.last().toInt( &ok );
          if ( ok ) {
            nb = index;
            names.removeLast();
          }
        }
        names.append( QString::number( nb+1 ) );
        name = names.join( "_" );
      }
      return name;
    }
    return baseName;
  }

  QString UniqueName(const QString& theBaseName, _PTR(SObject) theParent, const QString& thePostfix)
  {
    QString baseName = thePostfix.isEmpty() ?
      theBaseName : theBaseName + "_" + thePostfix;
    QString name = baseName;
    if ( _PTR(Study) aStudy = GetActiveStudyDocument() ) {
      _PTR(SObject) p = theParent;
      if ( !p ) p = aStudy->FindComponent( "SMESH" );
      if ( p ) {
        _PTR(ChildIterator) iter = aStudy->NewChildIterator( p );
        iter->InitEx(/*allLevels=*/true);
        int idx = 0;
        while( true ) {
          bool found = false;
          for ( ; iter->More(); iter->Next() ) {
            _PTR(SObject) so = iter->Value();
            if ( !so ) continue; // skip bad objects
            _PTR(SObject) ref;
            if ( so->ReferencedObject( ref ) ) continue; // skip references
            QString n = so->GetName().c_str();
            if ( !n.isEmpty() && n == name ) {
              QStringList names = name.split("_", QString::KeepEmptyParts);
              if ( names.count() > 0 ) {
                bool ok;
                names.last().toInt( &ok );
                if ( ok )
                  names.removeLast();
              }
              names.append( QString::number( ++idx ) );
              name = names.join( "_" );
              found = true;
              break;
            }
          }
          if ( !found ) break;
        }
      }
    }
    return name;
  }

  SMESH::Measurements_var& GetMeasurements()
  {
    static SMESH::Measurements_var aMeasurements;
    if (CORBA::is_nil(aMeasurements)) {
      aMeasurements = SMESHGUI::GetSMESHGen()->CreateMeasurements();
    }
    return aMeasurements;
  }
} // end of namespace SMESH
<|endoftext|>


<commit_before>#include <cstdio>
#include <string>
#include <regex>
#include <fstream>
#include <sys/stat.h>
// http://tclap.sourceforge.net/manual.html
#include "tclap/CmdLine.h"
#include "HCIDumpParser.h"
#include "MsgPublisherTypeConstraint.h"

static HCIDumpParser parserLogic;

#define STOP_MARKER_FILE "STOP"

inline bool stopMarkerExists() {
    struct stat buffer;
    bool stop = (stat (STOP_MARKER_FILE, &buffer) == 0);
    if(stop) {
        printf("Found STOP marker file, will exit...\n");
    }
    return stop;
}
static long eventCount = 0;
static int64_t lastMarkerCheckTime = 0;

/**
* Callback invoked by the hdidumpinternal.c code when a LE_ADVERTISING_REPORT event is seen on the stack
*/
extern "C" bool beacon_event_callback(const beacon_info *info) {
#ifdef PRINT_DEBUG
    printf("beacon_event_callback(%ld: %s, code=%d, time=%lld)\n", eventCount, info->uuid, info->code, info->time);
#endif
    parserLogic.beaconEvent(info);
    eventCount ++;
    // Check for a termination marker every 1000 events or 5 seconds
    bool stop = false;
    int64_t elapsed = info->time - lastMarkerCheckTime;
    if((eventCount % 1000) == 0 || elapsed > 5000) {
        lastMarkerCheckTime = info->time;
        stop = stopMarkerExists();
    }
    return stop;
}

using namespace std;

/**
* A version of the native scanner that directly integrates with the bluez stack hcidump command rather than parsing
* the hcidump output.
*/
int main(int argc, const char **argv) {

    printf("NativeScanner starting up...\n");
    TCLAP::CmdLine cmd("NativeScanner command line options", ' ', "0.1");
    //
    TCLAP::ValueArg<std::string> scannerID("s", "scannerID",
            "Specify the ID of the scanner generating the beacon events",
            true, "DEFAULT", "string", cmd);
    TCLAP::ValueArg<std::string> rawDumpFile("d", "rawDumpFile",
            "Specify a path to an hcidump file to parse for testing",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> clientID("c", "clientID",
            "Specify the clientID to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> username("u", "username",
            "Specify the username to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> password("p", "password",
            "Specify the password to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> brokerURL("b", "brokerURL",
            "Specify the brokerURL to connect to the MQTT broker with; default tcp://localhost:1883",
            false, "tcp://localhost:1883", "string", cmd);
    TCLAP::ValueArg<std::string> topicName("t", "destinationName",
            "Specify the name of the queue on the MQTT broker to publish to; default beaconEvents",
            false, "beaconEvents", "string", cmd);
    TCLAP::SwitchArg skipPublish("S", "skipPublish",
            "Indicate that the parsed beacons should not be published",
            false);
    TCLAP::SwitchArg asyncMode("A", "asyncMode",
            "Indicate that the parsed beacons should be published using async delivery mode",
            false);
    TCLAP::SwitchArg useQueues("Q", "useQueues",
            "Indicate that the destination type is a queue. If not given the default type is a topic.",
            false);
    TCLAP::ValueArg<std::string> hciDev("D", "hciDev",
            "Specify the name of the host controller interface to use; default hci0",
            false, "hci0", "string", cmd);
    MsgPublisherTypeConstraint pubTypeConstraint;
    TCLAP::ValueArg<std::string> pubType("P", "pubType",
            "Specify the MsgPublisherType enum for the publisher implementation to use; default PAHO_MQTT",
            false, "PAHO_MQTT", &pubTypeConstraint, cmd, nullptr);

    try {
        // Add the flag arguments
        cmd.add(skipPublish);
        cmd.add(asyncMode);
        cmd.add(useQueues);
        // Parse the argv array.
        printf("Parsing command line...\n");
        cmd.parse( argc, argv );
        printf("done\n");
    }
    catch (TCLAP::ArgException &e) {
        fprintf(stderr, "error: %s for arg: %s\n", e.error().c_str(), e.argId().c_str());
    }

    // Remove any stop marker file
    if(remove(STOP_MARKER_FILE) == 0) {
        printf("Removed existing %s marker file\n", STOP_MARKER_FILE);
    }

    HCIDumpCommand command(scannerID.getValue(), brokerURL.getValue(), clientID.getValue(), topicName.getValue());
    command.setSkipPublish(skipPublish.getValue());
    command.setHciDev(hciDev.getValue());
    command.setAsyncMode(asyncMode.getValue());
    command.setPubType(pubTypeConstraint.toType(pubType.getValue()));
    printf("Begin scanning...\n");
    parserLogic.processHCI(command);
    parserLogic.cleanup();
    printf("End scanning\n");
    return 0;
}
<commit_msg>Add maxCount argument to stop the scanner after a given number of events<commit_after>#include <cstdio>
#include <string>
#include <regex>
#include <fstream>
#include <sys/stat.h>
// http://tclap.sourceforge.net/manual.html
#include "tclap/CmdLine.h"
#include "HCIDumpParser.h"
#include "MsgPublisherTypeConstraint.h"

static HCIDumpParser parserLogic;

#define STOP_MARKER_FILE "STOP"

inline bool stopMarkerExists() {
    struct stat buffer;
    bool stop = (stat (STOP_MARKER_FILE, &buffer) == 0);
    if(stop) {
        printf("Found STOP marker file, will exit...\n");
    }
    return stop;
}
static long eventCount = 0;
static long maxEventCount = 0;
static int64_t lastMarkerCheckTime = 0;

/**
* Callback invoked by the hdidumpinternal.c code when a LE_ADVERTISING_REPORT event is seen on the stack
*/
extern "C" bool beacon_event_callback(const beacon_info *info) {
#ifdef PRINT_DEBUG
    printf("beacon_event_callback(%ld: %s, code=%d, time=%lld)\n", eventCount, info->uuid, info->code, info->time);
#endif
    parserLogic.beaconEvent(info);
    eventCount ++;
    // Check for a termination marker every 1000 events or 5 seconds
    bool stop = false;
    int64_t elapsed = info->time - lastMarkerCheckTime;
    if((eventCount % 1000) == 0 || elapsed > 5000) {
        lastMarkerCheckTime = info->time;
        stop = stopMarkerExists();
    }
    // Check max event count limit
    if(maxEventCount > 0 && eventCount >= maxEventCount)
        stop = true;
    return stop;
}

using namespace std;

/**
* A version of the native scanner that directly integrates with the bluez stack hcidump command rather than parsing
* the hcidump output.
*/
int main(int argc, const char **argv) {

    printf("NativeScanner starting up...\n");
    TCLAP::CmdLine cmd("NativeScanner command line options", ' ', "0.1");
    //
    TCLAP::ValueArg<std::string> scannerID("s", "scannerID",
            "Specify the ID of the scanner generating the beacon events",
            true, "DEFAULT", "string", cmd);
    TCLAP::ValueArg<std::string> rawDumpFile("d", "rawDumpFile",
            "Specify a path to an hcidump file to parse for testing",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> clientID("c", "clientID",
            "Specify the clientID to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> username("u", "username",
            "Specify the username to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> password("p", "password",
            "Specify the password to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> brokerURL("b", "brokerURL",
            "Specify the brokerURL to connect to the MQTT broker with; default tcp://localhost:1883",
            false, "tcp://localhost:1883", "string", cmd);
    TCLAP::ValueArg<std::string> topicName("t", "destinationName",
            "Specify the name of the queue on the MQTT broker to publish to; default beaconEvents",
            false, "beaconEvents", "string", cmd);
    TCLAP::SwitchArg skipPublish("S", "skipPublish",
            "Indicate that the parsed beacons should not be published",
            false);
    TCLAP::SwitchArg asyncMode("A", "asyncMode",
            "Indicate that the parsed beacons should be published using async delivery mode",
            false);
    TCLAP::SwitchArg useQueues("Q", "useQueues",
            "Indicate that the destination type is a queue. If not given the default type is a topic.",
            false);
    TCLAP::ValueArg<std::string> hciDev("D", "hciDev",
            "Specify the name of the host controller interface to use; default hci0",
            false, "hci0", "string", cmd);
    MsgPublisherTypeConstraint pubTypeConstraint;
    TCLAP::ValueArg<std::string> pubType("P", "pubType",
            "Specify the MsgPublisherType enum for the publisher implementation to use; default PAHO_MQTT",
            false, "PAHO_MQTT", &pubTypeConstraint, cmd, nullptr);
    TCLAP::ValueArg<int> maxCount("C", "maxCount",
            "Specify a maxium number of events the scanner should process before exiting; default 0 means no limit",
            false, 0, "int", cmd);

    try {
        // Add the flag arguments
        cmd.add(skipPublish);
        cmd.add(asyncMode);
        cmd.add(useQueues);
        // Parse the argv array.
        printf("Parsing command line...\n");
        cmd.parse( argc, argv );
        printf("done\n");
    }
    catch (TCLAP::ArgException &e) {
        fprintf(stderr, "error: %s for arg: %s\n", e.error().c_str(), e.argId().c_str());
    }

    // Remove any stop marker file
    if(remove(STOP_MARKER_FILE) == 0) {
        printf("Removed existing %s marker file\n", STOP_MARKER_FILE);
    }

    HCIDumpCommand command(scannerID.getValue(), brokerURL.getValue(), clientID.getValue(), topicName.getValue());
    command.setSkipPublish(skipPublish.getValue());
    command.setHciDev(hciDev.getValue());
    command.setAsyncMode(asyncMode.getValue());
    command.setPubType(pubTypeConstraint.toType(pubType.getValue()));
    if(maxCount.getValue() > 0) {
        maxEventCount = maxCount.getValue();
        printf("Set maxEventCount: %ld\n", maxEventCount);
    }
    printf("Begin scanning...\n");
    parserLogic.processHCI(command);
    parserLogic.cleanup();
    printf("End scanning\n");
    return 0;
}
<|endoftext|>


<commit_before>//=============================================================================================================
/**
* @file     main.cpp
* @author   Jana Kiesel <jana.kiesel@tu-ilmenau.de>
*           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     Mai, 2015
*
* @section  LICENSE
*
* Copyright (C) 2015, Jana Kiesel, Christoph Dinh and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
*       to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief    Example of reading BEM data
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include <iostream>
#include <mne/mne.h>
#include <utils/ioutils.h>

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QtCore/QCoreApplication>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace MNELIB;

//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================

//=============================================================================================================
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QFile t_fileBem("./MNE-sample-data/subjects/sample/bem/sample-5120-5120-5120-bem.fif");
//    QFile t_fileBem("./MNE-sample-data/subjects/sample/bem/sample-all-src.fif");
//    QFile t_fileBem("./MNE-sample-data/subjects/sample/bem/sample-5120-bem-sol.fif");
//    QFile t_fileBem("./MNE-sample-data/subjects/sample/bem/sample-5120-bem.fif");
//    QFile t_fileBem("./MNE-sample-data/subjects/sample/bem/sample-head.fif");

    MNEBem t_Bem (t_fileBem) ;

    QString folder = "C:/Users/Jana/Documents/MATLAB/AVG4-0Years_segmented_BEM3/";

    MNEBem t_BemIso2Mesh;
    MNEBemSurface  p_Brain;
    p_Brain.id = FIFFV_BEM_SURF_ID_BRAIN;
    QString path=folder;
//    MatrixXd rr = IOUtils::read_eigen_matrix(path.append("brain_vert.txt"));
    p_Brain.rr = IOUtils::read_eigen_matrix(path.append("brain_vert.txt")).cast<float>();
    path=folder;
//    MatrixXd tris = IOUtils::read_eigen_matrix(path.append("brain_tri.txt"));
    p_Brain.tris = IOUtils::read_eigen_matrix(path.append("brain_tri.txt")).cast<int>();
    p_Brain.np = p_Brain.rr.rows();
    p_Brain.ntri = p_Brain.tris.rows();
    p_Brain.addTriangleData();
    p_Brain.addVertexNormals();
    t_BemIso2Mesh<<p_Brain;

    MNEBemSurface  p_Skull;
    p_Skull.id = FIFFV_BEM_SURF_ID_SKULL;
    path=folder;
    p_Skull.rr = IOUtils::read_eigen_matrix(path.append("skull_vert.txt")).cast<float>();
    path=folder;
    p_Skull.tris = IOUtils::read_eigen_matrix(path.append("skull_tri.txt")).cast<int>();
    p_Skull.np = p_Skull.rr.rows();
    p_Skull.ntri = p_Skull.tris.rows();
    p_Skull.addTriangleData();
    p_Skull.addVertexNormals();
    t_BemIso2Mesh<<p_Skull;

    MNEBemSurface  p_Head;
    p_Head.id = FIFFV_BEM_SURF_ID_HEAD;
    path=folder;
    p_Head.rr = IOUtils::read_eigen_matrix(path.append("head_vert.txt")).cast<float>();
    path=folder;
    p_Head.tris = IOUtils::read_eigen_matrix(path.append("head_tri.txt")).cast<int>();
    p_Head.np = p_Head.rr.rows();
    p_Head.ntri = p_Head.tris.rows();
    p_Head.addTriangleData();
    p_Head.addVertexNormals();
    t_BemIso2Mesh<<p_Head;

    QFile t_fileBemTest("D:/Studium/Master/Masterarbeit/Programming/Iso2MeshBem/AVG4-0Years_segmented_BEM3.fif");
    t_BemIso2Mesh.write(t_fileBemTest);
    t_fileBemTest.close();

    MNEBem t_BemTest (t_fileBemTest) ;

    qDebug() << "Put your stuff your interest in here";

    return a.exec();
}
<commit_msg>readBEM example update<commit_after>//=============================================================================================================
/**
* @file     main.cpp
* @author   Jana Kiesel <jana.kiesel@tu-ilmenau.de>
*           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     Mai, 2015
*
* @section  LICENSE
*
* Copyright (C) 2015, Jana Kiesel, Christoph Dinh and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
*       to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief    Example of reading BEM data
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include <iostream>
#include <mne/mne.h>
#include <utils/ioutils.h>

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QtCore/QCoreApplication>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace MNELIB;

//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================

//=============================================================================================================
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QFile t_fileBem("./MNE-sample-data/subjects/sample/bem/sample-5120-5120-5120-bem.fif");
//    QFile t_fileBem("./MNE-sample-data/subjects/sample/bem/sample-all-src.fif");
//    QFile t_fileBem("./MNE-sample-data/subjects/sample/bem/sample-5120-bem-sol.fif");
//    QFile t_fileBem("./MNE-sample-data/subjects/sample/bem/sample-5120-bem.fif");
//    QFile t_fileBem("./MNE-sample-data/subjects/sample/bem/sample-head.fif");

    MNEBem t_Bem (t_fileBem) ;

    QString folder = "C:/Users/Jana/Documents/MATLAB/AVG4-0Years_segmented_BEM3/";

    MatrixXd help;

    MNEBem t_BemIso2Mesh;
    MNEBemSurface  p_Brain;
    p_Brain.id = FIFFV_BEM_SURF_ID_BRAIN;
    QString path=folder;
    IOUtils::read_eigen_matrix(help, path.append("brain_vert.txt"));
    p_Brain.rr= help.cast<float>();
    path=folder;
    IOUtils::read_eigen_matrix(help, path.append("brain_tri.txt"));
    p_Brain.tris = help.cast<int>();
    p_Brain.np = p_Brain.rr.rows();
    p_Brain.ntri = p_Brain.tris.rows();
    p_Brain.addTriangleData();
    p_Brain.addVertexNormals();
    t_BemIso2Mesh<<p_Brain;

    MNEBemSurface  p_Skull;
    p_Skull.id = FIFFV_BEM_SURF_ID_SKULL;
    path=folder;
    IOUtils::read_eigen_matrix(help,path.append("skull_vert.txt"));
    p_Skull.rr =  help.cast<float>();
    path=folder;
    IOUtils::read_eigen_matrix(help,path.append("skull_tri.txt"));
    p_Skull.tris =  help.cast<int>();
    p_Skull.np = p_Skull.rr.rows();
    p_Skull.ntri = p_Skull.tris.rows();
    p_Skull.addTriangleData();
    p_Skull.addVertexNormals();
    t_BemIso2Mesh<<p_Skull;

    MNEBemSurface  p_Head;
    p_Head.id = FIFFV_BEM_SURF_ID_HEAD;
    path=folder;
    IOUtils::read_eigen_matrix(help,path.append("head_vert.txt"));
    p_Head.rr =  help.cast<float>();
    path=folder;
    IOUtils::read_eigen_matrix(help,path.append("head_tri.txt"));
    p_Head.tris =  help.cast<int>();
    p_Head.np = p_Head.rr.rows();
    p_Head.ntri = p_Head.tris.rows();
    p_Head.addTriangleData();
    p_Head.addVertexNormals();
    t_BemIso2Mesh<<p_Head;

    QFile t_fileBemTest("D:/Studium/Master/Masterarbeit/Programming/Iso2MeshBem/AVG4-0Years_segmented_BEM3.fif");
    t_BemIso2Mesh.write(t_fileBemTest);
    t_fileBemTest.close();

    MNEBem t_BemTest (t_fileBemTest) ;

    qDebug() << "Put your stuff your interest in here";

    return a.exec();
}
<|endoftext|>


<commit_before>#ifndef INCLUDE_UNITTESTS_DECIMATER_HH
#define INCLUDE_UNITTESTS_DECIMATER_HH

#include <gtest/gtest.h>
#include <Unittests/unittests_common.hh>

class OpenMeshProperties : public OpenMeshBase {

    protected:

        // This function is called before each test is run
        virtual void SetUp() {

            // Do some initial stuff with the member data here...
        }

        // This function is called after all tests are through
        virtual void TearDown() {

            // Do some final stuff with the member data here...
        }

    // Member already defined in OpenMeshBase
    //Mesh mesh_;
};

/*
 * ====================================================================
 * Define tests below
 * ====================================================================
 */

/* Creates a double property and checks if it works
 */
TEST_F(OpenMeshProperties, VertexPropertyCheckDouble) {

  mesh_.clear();

  // Add some vertices
  Mesh::VertexHandle vhandle[4];

  vhandle[0] = mesh_.add_vertex(Mesh::Point(0, 0, 0));
  vhandle[1] = mesh_.add_vertex(Mesh::Point(0, 1, 0));
  vhandle[2] = mesh_.add_vertex(Mesh::Point(1, 1, 0));
  vhandle[3] = mesh_.add_vertex(Mesh::Point(1, 0, 0));

  // Add two faces
  std::vector<Mesh::VertexHandle> face_vhandles;

  face_vhandles.push_back(vhandle[2]);
  face_vhandles.push_back(vhandle[1]);
  face_vhandles.push_back(vhandle[0]);
  mesh_.add_face(face_vhandles);

  face_vhandles.clear();

  face_vhandles.push_back(vhandle[2]);
  face_vhandles.push_back(vhandle[0]);
  face_vhandles.push_back(vhandle[3]);
  mesh_.add_face(face_vhandles);

  // Test setup:
  //  1 === 2
  //  |   / |
  //  |  /  |
  //  | /   |
  //  0 === 3

  // Check setup
  EXPECT_EQ(4u, mesh_.n_vertices() ) << "Wrong number of vertices";
  EXPECT_EQ(2u, mesh_.n_faces() )    << "Wrong number of faces";

  // Add a double vertex property
  OpenMesh::VPropHandleT<double> doubleHandle;

  EXPECT_FALSE( mesh_.get_property_handle(doubleHandle,"doubleProp") );

  mesh_.add_property(doubleHandle,"doubleProp");

  EXPECT_TRUE(mesh_.get_property_handle(doubleHandle,"doubleProp"));

  // Fill property
  double index = 0.0;

  for ( Mesh::VertexIter v_it = mesh_.vertices_begin() ; v_it != mesh_.vertices_end(); ++v_it ) {
    mesh_.property(doubleHandle,v_it) = index;
    index += 1.0;
  }

  // Check if it is ok.
  Mesh::VertexIter v_it = mesh_.vertices_begin();
  EXPECT_EQ( mesh_.property(doubleHandle,v_it) , 0.0 ) << "Invalid double value for vertex 0";
  ++v_it;

  EXPECT_EQ( mesh_.property(doubleHandle,v_it) , 1.0 ) << "Invalid double value for vertex 1";
  ++v_it;

  EXPECT_EQ( mesh_.property(doubleHandle,v_it) , 2.0 ) << "Invalid double value for vertex 2";
  ++v_it;

  EXPECT_EQ( mesh_.property(doubleHandle,v_it) , 3.0 ) << "Invalid double value for vertex 3";

  // Try to get the stl iterators:
  std::vector<double>::iterator it=mesh_.property(doubleHandle).data_vector().begin();
  std::vector<double>::iterator end=mesh_.property(doubleHandle).data_vector().end();

  EXPECT_EQ( *it , 0.0 ) << "Invalid double value for vertex 0";
  ++it;

  EXPECT_EQ( *it , 1.0 ) << "Invalid double value for vertex 1";
  ++it;

  EXPECT_EQ( *it , 2.0 ) << "Invalid double value for vertex 2";
  ++it;

  EXPECT_EQ( *it , 3.0 ) << "Invalid double value for vertex 3";
  ++it;

  EXPECT_EQ( it, end ) << "End iterator not mathing!";

}

/* Creates a bool property and checks if it works
 */
TEST_F(OpenMeshProperties, VertexPropertyCheckBool) {

  mesh_.clear();

  // Add some vertices
  Mesh::VertexHandle vhandle[4];

  vhandle[0] = mesh_.add_vertex(Mesh::Point(0, 0, 0));
  vhandle[1] = mesh_.add_vertex(Mesh::Point(0, 1, 0));
  vhandle[2] = mesh_.add_vertex(Mesh::Point(1, 1, 0));
  vhandle[3] = mesh_.add_vertex(Mesh::Point(1, 0, 0));

  // Add two faces
  std::vector<Mesh::VertexHandle> face_vhandles;

  face_vhandles.push_back(vhandle[2]);
  face_vhandles.push_back(vhandle[1]);
  face_vhandles.push_back(vhandle[0]);
  mesh_.add_face(face_vhandles);

  face_vhandles.clear();

  face_vhandles.push_back(vhandle[2]);
  face_vhandles.push_back(vhandle[0]);
  face_vhandles.push_back(vhandle[3]);
  mesh_.add_face(face_vhandles);

  // Test setup:
  //  1 === 2
  //  |   / |
  //  |  /  |
  //  | /   |
  //  0 === 3

  // Check setup
  EXPECT_EQ(4u, mesh_.n_vertices() ) << "Wrong number of vertices";
  EXPECT_EQ(2u, mesh_.n_faces() )    << "Wrong number of faces";

  // Add a double vertex property
  OpenMesh::VPropHandleT<bool> boolHandle;

  EXPECT_FALSE( mesh_.get_property_handle(boolHandle,"boolProp") );

  mesh_.add_property(boolHandle,"boolProp");

  EXPECT_TRUE(mesh_.get_property_handle(boolHandle,"boolProp"));

  // Fill property
  bool current = true;

  for ( Mesh::VertexIter v_it = mesh_.vertices_begin() ; v_it != mesh_.vertices_end(); ++v_it ) {
    mesh_.property(boolHandle,v_it) = current;
    current = !current;
  }

  // Check if it is ok.
  Mesh::VertexIter v_it = mesh_.vertices_begin();
  EXPECT_TRUE( mesh_.property(boolHandle,v_it) ) << "Invalid bool value for vertex 0";
  ++v_it;

  EXPECT_FALSE( mesh_.property(boolHandle,v_it) ) << "Invalid bool value for vertex 1";
  ++v_it;

  EXPECT_TRUE( mesh_.property(boolHandle,v_it) ) << "Invalid bool value for vertex 2";
  ++v_it;

  EXPECT_FALSE( mesh_.property(boolHandle,v_it) ) << "Invalid bool value for vertex 3";

  // Try to get the stl iterators:
  std::vector<bool>::iterator it=mesh_.property(boolHandle).data_vector().begin();
  std::vector<bool>::iterator end=mesh_.property(boolHandle).data_vector().end();

  EXPECT_TRUE( *it ) << "Invalid bool value for vertex 0";
  ++it;

  EXPECT_FALSE( *it ) << "Invalid bool value for vertex 1";
  ++it;

  EXPECT_TRUE( *it ) << "Invalid bool value for vertex 2";
  ++it;

  EXPECT_FALSE( *it ) << "Invalid bool value for vertex 3";
  ++it;

  EXPECT_EQ( it, end ) << "End iterator not mathing!";

}

/*
 * Checking for deleted flags of halfedge and edge handles
 *
 * Checks if after deleting a face, all halfedges and edges are arked as deleted as well
*/
TEST_F(OpenMeshProperties, CheckStatusPropertiesHalfedgeEdgeAllDeleted) {

  mesh_.clear();

  mesh_.request_vertex_status();
  mesh_.request_face_status();
  mesh_.request_halfedge_status();
  mesh_.request_edge_status();

  // Define positions
  Mesh::Point p1 = Mesh::Point(0, 0, 0);
  Mesh::Point p2 = Mesh::Point(0, 1, 0);
  Mesh::Point p3 = Mesh::Point(1, 1, 0);
  Mesh::Point p4 = Mesh::Point(0, 0, 1);

  // Add some vertices
  Mesh::VertexHandle vh1 = mesh_.add_vertex(p1);
  Mesh::VertexHandle vh2 = mesh_.add_vertex(p2);
  Mesh::VertexHandle vh3 = mesh_.add_vertex(p3);
  Mesh::VertexHandle vh4 = mesh_.add_vertex(p4);

  // Add some faces
  Mesh::FaceHandle f1 = mesh_.add_face(vh1,vh3,vh2);
  Mesh::FaceHandle f2 = mesh_.add_face(vh1,vh2,vh4);
  Mesh::FaceHandle f3 = mesh_.add_face(vh2,vh3,vh4);
  Mesh::FaceHandle f4 = mesh_.add_face(vh3,vh1,vh4);

  // delete all faces
  mesh_.delete_face(f1);
  mesh_.delete_face(f2);
  mesh_.delete_face(f3);
  mesh_.delete_face(f4);

  for( Mesh::ConstHalfedgeIter he_it = mesh_.halfedges_begin(); he_it != mesh_.halfedges_end(); ++he_it)
  {
      EXPECT_TRUE( mesh_.status(mesh_.edge_handle(he_it.handle())).deleted()  ) << "Edge not deleted";
      EXPECT_TRUE( mesh_.status(he_it.handle()).deleted()                     ) << "Halfedge not deleted";
  }

}

#endif // INCLUDE GUARD
<commit_msg>Fixed wrong unittest include guard<commit_after>#ifndef INCLUDE_UNITTESTS_PROPERTY_HH
#define INCLUDE_UNITTESTS_PROPERTY_HH

#include <gtest/gtest.h>
#include <Unittests/unittests_common.hh>

class OpenMeshProperties : public OpenMeshBase {

    protected:

        // This function is called before each test is run
        virtual void SetUp() {

            // Do some initial stuff with the member data here...
        }

        // This function is called after all tests are through
        virtual void TearDown() {

            // Do some final stuff with the member data here...
        }

    // Member already defined in OpenMeshBase
    //Mesh mesh_;
};

/*
 * ====================================================================
 * Define tests below
 * ====================================================================
 */

/* Creates a double property and checks if it works
 */
TEST_F(OpenMeshProperties, VertexPropertyCheckDouble) {

  mesh_.clear();

  // Add some vertices
  Mesh::VertexHandle vhandle[4];

  vhandle[0] = mesh_.add_vertex(Mesh::Point(0, 0, 0));
  vhandle[1] = mesh_.add_vertex(Mesh::Point(0, 1, 0));
  vhandle[2] = mesh_.add_vertex(Mesh::Point(1, 1, 0));
  vhandle[3] = mesh_.add_vertex(Mesh::Point(1, 0, 0));

  // Add two faces
  std::vector<Mesh::VertexHandle> face_vhandles;

  face_vhandles.push_back(vhandle[2]);
  face_vhandles.push_back(vhandle[1]);
  face_vhandles.push_back(vhandle[0]);
  mesh_.add_face(face_vhandles);

  face_vhandles.clear();

  face_vhandles.push_back(vhandle[2]);
  face_vhandles.push_back(vhandle[0]);
  face_vhandles.push_back(vhandle[3]);
  mesh_.add_face(face_vhandles);

  // Test setup:
  //  1 === 2
  //  |   / |
  //  |  /  |
  //  | /   |
  //  0 === 3

  // Check setup
  EXPECT_EQ(4u, mesh_.n_vertices() ) << "Wrong number of vertices";
  EXPECT_EQ(2u, mesh_.n_faces() )    << "Wrong number of faces";

  // Add a double vertex property
  OpenMesh::VPropHandleT<double> doubleHandle;

  EXPECT_FALSE( mesh_.get_property_handle(doubleHandle,"doubleProp") );

  mesh_.add_property(doubleHandle,"doubleProp");

  EXPECT_TRUE(mesh_.get_property_handle(doubleHandle,"doubleProp"));

  // Fill property
  double index = 0.0;

  for ( Mesh::VertexIter v_it = mesh_.vertices_begin() ; v_it != mesh_.vertices_end(); ++v_it ) {
    mesh_.property(doubleHandle,v_it) = index;
    index += 1.0;
  }

  // Check if it is ok.
  Mesh::VertexIter v_it = mesh_.vertices_begin();
  EXPECT_EQ( mesh_.property(doubleHandle,v_it) , 0.0 ) << "Invalid double value for vertex 0";
  ++v_it;

  EXPECT_EQ( mesh_.property(doubleHandle,v_it) , 1.0 ) << "Invalid double value for vertex 1";
  ++v_it;

  EXPECT_EQ( mesh_.property(doubleHandle,v_it) , 2.0 ) << "Invalid double value for vertex 2";
  ++v_it;

  EXPECT_EQ( mesh_.property(doubleHandle,v_it) , 3.0 ) << "Invalid double value for vertex 3";

  // Try to get the stl iterators:
  std::vector<double>::iterator it=mesh_.property(doubleHandle).data_vector().begin();
  std::vector<double>::iterator end=mesh_.property(doubleHandle).data_vector().end();

  EXPECT_EQ( *it , 0.0 ) << "Invalid double value for vertex 0";
  ++it;

  EXPECT_EQ( *it , 1.0 ) << "Invalid double value for vertex 1";
  ++it;

  EXPECT_EQ( *it , 2.0 ) << "Invalid double value for vertex 2";
  ++it;

  EXPECT_EQ( *it , 3.0 ) << "Invalid double value for vertex 3";
  ++it;

  EXPECT_EQ( it, end ) << "End iterator not mathing!";

}

/* Creates a bool property and checks if it works
 */
TEST_F(OpenMeshProperties, VertexPropertyCheckBool) {

  mesh_.clear();

  // Add some vertices
  Mesh::VertexHandle vhandle[4];

  vhandle[0] = mesh_.add_vertex(Mesh::Point(0, 0, 0));
  vhandle[1] = mesh_.add_vertex(Mesh::Point(0, 1, 0));
  vhandle[2] = mesh_.add_vertex(Mesh::Point(1, 1, 0));
  vhandle[3] = mesh_.add_vertex(Mesh::Point(1, 0, 0));

  // Add two faces
  std::vector<Mesh::VertexHandle> face_vhandles;

  face_vhandles.push_back(vhandle[2]);
  face_vhandles.push_back(vhandle[1]);
  face_vhandles.push_back(vhandle[0]);
  mesh_.add_face(face_vhandles);

  face_vhandles.clear();

  face_vhandles.push_back(vhandle[2]);
  face_vhandles.push_back(vhandle[0]);
  face_vhandles.push_back(vhandle[3]);
  mesh_.add_face(face_vhandles);

  // Test setup:
  //  1 === 2
  //  |   / |
  //  |  /  |
  //  | /   |
  //  0 === 3

  // Check setup
  EXPECT_EQ(4u, mesh_.n_vertices() ) << "Wrong number of vertices";
  EXPECT_EQ(2u, mesh_.n_faces() )    << "Wrong number of faces";

  // Add a double vertex property
  OpenMesh::VPropHandleT<bool> boolHandle;

  EXPECT_FALSE( mesh_.get_property_handle(boolHandle,"boolProp") );

  mesh_.add_property(boolHandle,"boolProp");

  EXPECT_TRUE(mesh_.get_property_handle(boolHandle,"boolProp"));

  // Fill property
  bool current = true;

  for ( Mesh::VertexIter v_it = mesh_.vertices_begin() ; v_it != mesh_.vertices_end(); ++v_it ) {
    mesh_.property(boolHandle,v_it) = current;
    current = !current;
  }

  // Check if it is ok.
  Mesh::VertexIter v_it = mesh_.vertices_begin();
  EXPECT_TRUE( mesh_.property(boolHandle,v_it) ) << "Invalid bool value for vertex 0";
  ++v_it;

  EXPECT_FALSE( mesh_.property(boolHandle,v_it) ) << "Invalid bool value for vertex 1";
  ++v_it;

  EXPECT_TRUE( mesh_.property(boolHandle,v_it) ) << "Invalid bool value for vertex 2";
  ++v_it;

  EXPECT_FALSE( mesh_.property(boolHandle,v_it) ) << "Invalid bool value for vertex 3";

  // Try to get the stl iterators:
  std::vector<bool>::iterator it=mesh_.property(boolHandle).data_vector().begin();
  std::vector<bool>::iterator end=mesh_.property(boolHandle).data_vector().end();

  EXPECT_TRUE( *it ) << "Invalid bool value for vertex 0";
  ++it;

  EXPECT_FALSE( *it ) << "Invalid bool value for vertex 1";
  ++it;

  EXPECT_TRUE( *it ) << "Invalid bool value for vertex 2";
  ++it;

  EXPECT_FALSE( *it ) << "Invalid bool value for vertex 3";
  ++it;

  EXPECT_EQ( it, end ) << "End iterator not mathing!";

}

/*
 * Checking for deleted flags of halfedge and edge handles
 *
 * Checks if after deleting a face, all halfedges and edges are arked as deleted as well
*/
TEST_F(OpenMeshProperties, CheckStatusPropertiesHalfedgeEdgeAllDeleted) {

  mesh_.clear();

  mesh_.request_vertex_status();
  mesh_.request_face_status();
  mesh_.request_halfedge_status();
  mesh_.request_edge_status();

  // Define positions
  Mesh::Point p1 = Mesh::Point(0, 0, 0);
  Mesh::Point p2 = Mesh::Point(0, 1, 0);
  Mesh::Point p3 = Mesh::Point(1, 1, 0);
  Mesh::Point p4 = Mesh::Point(0, 0, 1);

  // Add some vertices
  Mesh::VertexHandle vh1 = mesh_.add_vertex(p1);
  Mesh::VertexHandle vh2 = mesh_.add_vertex(p2);
  Mesh::VertexHandle vh3 = mesh_.add_vertex(p3);
  Mesh::VertexHandle vh4 = mesh_.add_vertex(p4);

  // Add some faces
  Mesh::FaceHandle f1 = mesh_.add_face(vh1,vh3,vh2);
  Mesh::FaceHandle f2 = mesh_.add_face(vh1,vh2,vh4);
  Mesh::FaceHandle f3 = mesh_.add_face(vh2,vh3,vh4);
  Mesh::FaceHandle f4 = mesh_.add_face(vh3,vh1,vh4);

  // delete all faces
  mesh_.delete_face(f1);
  mesh_.delete_face(f2);
  mesh_.delete_face(f3);
  mesh_.delete_face(f4);

  for( Mesh::ConstHalfedgeIter he_it = mesh_.halfedges_begin(); he_it != mesh_.halfedges_end(); ++he_it)
  {
      EXPECT_TRUE( mesh_.status(mesh_.edge_handle(he_it.handle())).deleted()  ) << "Edge not deleted";
      EXPECT_TRUE( mesh_.status(he_it.handle()).deleted()                     ) << "Halfedge not deleted";
  }

}

#endif // INCLUDE GUARD
<|endoftext|>