<commit_before>
#include "qmljs_objects.h"
#include "qv4codegen_p.h"
#include "qv4isel_p.h"
#include "qv4isel_x86_64_p.h"
#include "qv4syntaxchecker_p.h"
#include "qv4ecmaobjects_p.h"

#include <QtCore>
#include <private/qqmljsengine_p.h>
#include <private/qqmljslexer_p.h>
#include <private/qqmljsparser_p.h>
#include <private/qqmljsast_p.h>

#include <sys/mman.h>
#include <iostream>

#ifndef QMLJS_NO_LLVM
#  include "qv4isel_llvm_p.h"

#  include <llvm/PassManager.h>
#  include <llvm/Analysis/Passes.h>
#  include <llvm/Transforms/Scalar.h>
#  include <llvm/Transforms/IPO.h>
#  include <llvm/Assembly/PrintModulePass.h>
#  include <llvm/Support/raw_ostream.h>
#  include <llvm/Support/FormattedStream.h>
#  include <llvm/Support/Host.h>
#  include <llvm/Support/TargetRegistry.h>
#  include <llvm/Support/TargetSelect.h>
#  include <llvm/Target/TargetMachine.h>
#  include <llvm/Target/TargetData.h>
#endif

static inline bool protect(const void *addr, size_t size)
{
    size_t pageSize = sysconf(_SC_PAGESIZE);
    size_t iaddr = reinterpret_cast<size_t>(addr);
    size_t roundAddr = iaddr & ~(pageSize - static_cast<size_t>(1));
    int mode = PROT_READ | PROT_WRITE | PROT_EXEC;
    return mprotect(reinterpret_cast<void*>(roundAddr), size + (iaddr - roundAddr), mode) == 0;
}

namespace builtins {

using namespace QQmlJS::VM;

struct Print: FunctionObject
{
    Print(Context *scope): FunctionObject(scope) {}

    virtual void call(Context *ctx)
    {
        for (unsigned int i = 0; i < ctx->argumentCount; ++i) {
            String *s = ctx->argument(i).toString(ctx);
            if (i)
                std::cout << ' ';
            std::cout << qPrintable(s->toQString());
        }
        std::cout << std::endl;
    }
};

} // builtins

#ifndef QMLJS_NO_LLVM
void compile(const QString &fileName, const QString &source)
{
    using namespace QQmlJS;

    IR::Module module;
    QQmlJS::Engine ee, *engine = ⅇ
    Lexer lexer(engine);
    lexer.setCode(source, 1, false);
    Parser parser(engine);

    const bool parsed = parser.parseProgram();

    foreach (const DiagnosticMessage &m, parser.diagnosticMessages()) {
        std::cerr << qPrintable(fileName) << ':' << m.loc.startLine << ':' << m.loc.startColumn
                  << ": error: " << qPrintable(m.message) << std::endl;
    }

    if (parsed) {
        using namespace AST;
        Program *program = AST::cast<Program *>(parser.rootNode());

        Codegen cg;
        /*IR::Function *globalCode =*/ cg(program, &module);

        LLVMInstructionSelection llvmIsel(llvm::getGlobalContext());
        if (llvm::Module *llvmModule = llvmIsel.getLLVMModule(&module)) {
            llvm::PassManager PM;

            const std::string triple = llvm::sys::getDefaultTargetTriple();

            LLVMInitializeX86TargetInfo();
            LLVMInitializeX86Target();
            LLVMInitializeX86AsmPrinter();
            LLVMInitializeX86AsmParser();
            LLVMInitializeX86Disassembler();
            LLVMInitializeX86TargetMC();

            std::string err;
            const llvm::Target *target = llvm::TargetRegistry::lookupTarget(triple, err);
            if (! err.empty()) {
                std::cerr << err << ", triple: " << triple << std::endl;
                assert(!"cannot create target for the host triple");
            }

            std::string cpu;
            std::string features;
            llvm::TargetOptions options;
            llvm::TargetMachine *targetMachine = target->createTargetMachine(triple, cpu, features, options, llvm::Reloc::PIC_);
            assert(targetMachine);

            llvm::formatted_raw_ostream out(llvm::outs());
            PM.add(llvm::createScalarReplAggregatesPass());
            PM.add(llvm::createInstructionCombiningPass());
            PM.add(llvm::createGlobalOptimizerPass());
            PM.add(llvm::createFunctionInliningPass(25));
            targetMachine->addPassesToEmitFile(PM, out, llvm::TargetMachine::CGFT_AssemblyFile);
            PM.run(*llvmModule);
            delete llvmModule;
        }
    }
}

int compileFiles(const QStringList &files)
{
    foreach (const QString &fileName, files) {
        QFile file(fileName);
        if (file.open(QFile::ReadOnly)) {
            QString source = QString::fromUtf8(file.readAll());
            compile(fileName, source);
        }
    }
    return 0;
}

int evaluateCompiledCode(const QStringList &files)
{
    using namespace QQmlJS;

    foreach (const QString &libName, files) {
        QLibrary lib(libName);
        lib.load();
        QFunctionPointer ptr = lib.resolve("_25_entry");
        void (*code)(VM::Context *) = (void (*)(VM::Context *)) ptr;

        VM::ExecutionEngine vm;
        VM::Context *ctx = vm.rootContext;

        QQmlJS::VM::Object *globalObject = vm.globalObject.objectValue;
        globalObject->setProperty(ctx, vm.identifier(QStringLiteral("print")),
                                  QQmlJS::VM::Value::fromObject(new builtins::Print(ctx)));

        code(ctx);

        if (ctx->hasUncaughtException) {
            if (VM::ErrorObject *e = ctx->result.asErrorObject())
                std::cerr << "Uncaught exception: " << qPrintable(e->value.toString(ctx)->toQString()) << std::endl;
            else
                std::cerr << "Uncaught exception: " << qPrintable(ctx->result.toString(ctx)->toQString()) << std::endl;
        }
    }
    return 0;
}

#endif

void evaluate(QQmlJS::VM::ExecutionEngine *vm, const QString &fileName, const QString &source)
{
    using namespace QQmlJS;

    IR::Module module;
    IR::Function *globalCode = 0;

    const size_t codeSize = 30 * getpagesize();
    uchar *code = (uchar *) malloc(codeSize);
    assert(! (size_t(code) & 15));

    {
        QQmlJS::Engine ee, *engine = ⅇ
        Lexer lexer(engine);
        lexer.setCode(source, 1, false);
        Parser parser(engine);

        const bool parsed = parser.parseProgram();

        foreach (const DiagnosticMessage &m, parser.diagnosticMessages()) {
            std::cerr << qPrintable(fileName) << ':' << m.loc.startLine << ':' << m.loc.startColumn
                      << ": error: " << qPrintable(m.message) << std::endl;
        }

        if (parsed) {
            using namespace AST;
            Program *program = AST::cast<Program *>(parser.rootNode());

            Codegen cg;
            globalCode = cg(program, &module);

            x86_64::InstructionSelection isel(vm, &module, code);
            foreach (IR::Function *function, module.functions) {
                isel(function);
            }
        }
    }

    if (! protect(code, codeSize))
        Q_UNREACHABLE();

    VM::Object *globalObject = vm->globalObject.objectValue;
    VM::Context *ctx = vm->rootContext;

    globalObject->setProperty(ctx, vm->identifier(QStringLiteral("print")),
                              VM::Value::fromObject(new builtins::Print(ctx)));

    ctx->varCount = globalCode->locals.size();
    if (ctx->varCount) {
        ctx->locals = new VM::Value[ctx->varCount];
        ctx->vars = new VM::String*[ctx->varCount];
        std::fill(ctx->locals, ctx->locals + ctx->varCount, VM::Value::undefinedValue());
        for (unsigned int i = 0; i < ctx->varCount; ++i)
            ctx->vars[i] = ctx->engine->identifier(*globalCode->locals.at(i));
    }

    globalCode->code(ctx);

    if (ctx->hasUncaughtException) {
        if (VM::ErrorObject *e = ctx->result.asErrorObject())
            std::cerr << "Uncaught exception: " << qPrintable(e->value.toString(ctx)->toQString()) << std::endl;
        else
            std::cerr << "Uncaught exception: " << qPrintable(ctx->result.toString(ctx)->toQString()) << std::endl;
    }

    delete[] ctx->locals;
    delete[] ctx->vars;
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QStringList args = app.arguments();
    args.removeFirst();

#ifndef QMLJS_NO_LLVM
    if (args.isEmpty()) {
        std::cerr << "Usage: v4 [--compile|--aot] file..." << std::endl;
        return 0;
    }

    if (args.first() == QLatin1String("--compile")) {
        args.removeFirst();
        return compileFiles(args);
    } else if (args.first() == QLatin1String("--aot")) {
        args.removeFirst();
        return evaluateCompiledCode(args);
    }
#endif

    foreach (const QString &fn, args) {
        QFile file(fn);
        if (file.open(QFile::ReadOnly)) {
            const QString code = QString::fromUtf8(file.readAll());
            file.close();
            QQmlJS::VM::ExecutionEngine vm;
            QQmlJS::VM::Context *ctx = vm.rootContext;

            QQmlJS::VM::Object *globalObject = vm.globalObject.objectValue;
            globalObject->setProperty(ctx, vm.identifier(QStringLiteral("print")),
                                      QQmlJS::VM::Value::fromObject(new builtins::Print(ctx)));

            evaluate(&vm, fn, code);
        }
    }
}
<commit_msg>Resolve the library name<commit_after>
#include "qmljs_objects.h"
#include "qv4codegen_p.h"
#include "qv4isel_p.h"
#include "qv4isel_x86_64_p.h"
#include "qv4syntaxchecker_p.h"
#include "qv4ecmaobjects_p.h"

#include <QtCore>
#include <private/qqmljsengine_p.h>
#include <private/qqmljslexer_p.h>
#include <private/qqmljsparser_p.h>
#include <private/qqmljsast_p.h>

#include <sys/mman.h>
#include <iostream>

#ifndef QMLJS_NO_LLVM
#  include "qv4isel_llvm_p.h"

#  include <llvm/PassManager.h>
#  include <llvm/Analysis/Passes.h>
#  include <llvm/Transforms/Scalar.h>
#  include <llvm/Transforms/IPO.h>
#  include <llvm/Assembly/PrintModulePass.h>
#  include <llvm/Support/raw_ostream.h>
#  include <llvm/Support/FormattedStream.h>
#  include <llvm/Support/Host.h>
#  include <llvm/Support/TargetRegistry.h>
#  include <llvm/Support/TargetSelect.h>
#  include <llvm/Target/TargetMachine.h>
#  include <llvm/Target/TargetData.h>
#endif

static inline bool protect(const void *addr, size_t size)
{
    size_t pageSize = sysconf(_SC_PAGESIZE);
    size_t iaddr = reinterpret_cast<size_t>(addr);
    size_t roundAddr = iaddr & ~(pageSize - static_cast<size_t>(1));
    int mode = PROT_READ | PROT_WRITE | PROT_EXEC;
    return mprotect(reinterpret_cast<void*>(roundAddr), size + (iaddr - roundAddr), mode) == 0;
}

namespace builtins {

using namespace QQmlJS::VM;

struct Print: FunctionObject
{
    Print(Context *scope): FunctionObject(scope) {}

    virtual void call(Context *ctx)
    {
        for (unsigned int i = 0; i < ctx->argumentCount; ++i) {
            String *s = ctx->argument(i).toString(ctx);
            if (i)
                std::cout << ' ';
            std::cout << qPrintable(s->toQString());
        }
        std::cout << std::endl;
    }
};

} // builtins

#ifndef QMLJS_NO_LLVM
void compile(const QString &fileName, const QString &source)
{
    using namespace QQmlJS;

    IR::Module module;
    QQmlJS::Engine ee, *engine = ⅇ
    Lexer lexer(engine);
    lexer.setCode(source, 1, false);
    Parser parser(engine);

    const bool parsed = parser.parseProgram();

    foreach (const DiagnosticMessage &m, parser.diagnosticMessages()) {
        std::cerr << qPrintable(fileName) << ':' << m.loc.startLine << ':' << m.loc.startColumn
                  << ": error: " << qPrintable(m.message) << std::endl;
    }

    if (parsed) {
        using namespace AST;
        Program *program = AST::cast<Program *>(parser.rootNode());

        Codegen cg;
        /*IR::Function *globalCode =*/ cg(program, &module);

        LLVMInstructionSelection llvmIsel(llvm::getGlobalContext());
        if (llvm::Module *llvmModule = llvmIsel.getLLVMModule(&module)) {
            llvm::PassManager PM;

            const std::string triple = llvm::sys::getDefaultTargetTriple();

            LLVMInitializeX86TargetInfo();
            LLVMInitializeX86Target();
            LLVMInitializeX86AsmPrinter();
            LLVMInitializeX86AsmParser();
            LLVMInitializeX86Disassembler();
            LLVMInitializeX86TargetMC();

            std::string err;
            const llvm::Target *target = llvm::TargetRegistry::lookupTarget(triple, err);
            if (! err.empty()) {
                std::cerr << err << ", triple: " << triple << std::endl;
                assert(!"cannot create target for the host triple");
            }

            std::string cpu;
            std::string features;
            llvm::TargetOptions options;
            llvm::TargetMachine *targetMachine = target->createTargetMachine(triple, cpu, features, options, llvm::Reloc::PIC_);
            assert(targetMachine);

            llvm::formatted_raw_ostream out(llvm::outs());
            PM.add(llvm::createScalarReplAggregatesPass());
            PM.add(llvm::createInstructionCombiningPass());
            PM.add(llvm::createGlobalOptimizerPass());
            PM.add(llvm::createFunctionInliningPass(25));
            targetMachine->addPassesToEmitFile(PM, out, llvm::TargetMachine::CGFT_AssemblyFile);
            PM.run(*llvmModule);
            delete llvmModule;
        }
    }
}

int compileFiles(const QStringList &files)
{
    foreach (const QString &fileName, files) {
        QFile file(fileName);
        if (file.open(QFile::ReadOnly)) {
            QString source = QString::fromUtf8(file.readAll());
            compile(fileName, source);
        }
    }
    return 0;
}

int evaluateCompiledCode(const QStringList &files)
{
    using namespace QQmlJS;

    foreach (const QString &libName, files) {
        QFileInfo libInfo(libName);
        QLibrary lib(libInfo.absoluteFilePath());
        lib.load();
        QFunctionPointer ptr = lib.resolve("_25_entry");
        void (*code)(VM::Context *) = (void (*)(VM::Context *)) ptr;

        VM::ExecutionEngine vm;
        VM::Context *ctx = vm.rootContext;

        QQmlJS::VM::Object *globalObject = vm.globalObject.objectValue;
        globalObject->setProperty(ctx, vm.identifier(QStringLiteral("print")),
                                  QQmlJS::VM::Value::fromObject(new builtins::Print(ctx)));

        code(ctx);

        if (ctx->hasUncaughtException) {
            if (VM::ErrorObject *e = ctx->result.asErrorObject())
                std::cerr << "Uncaught exception: " << qPrintable(e->value.toString(ctx)->toQString()) << std::endl;
            else
                std::cerr << "Uncaught exception: " << qPrintable(ctx->result.toString(ctx)->toQString()) << std::endl;
        }
    }
    return 0;
}

#endif

void evaluate(QQmlJS::VM::ExecutionEngine *vm, const QString &fileName, const QString &source)
{
    using namespace QQmlJS;

    IR::Module module;
    IR::Function *globalCode = 0;

    const size_t codeSize = 30 * getpagesize();
    uchar *code = (uchar *) malloc(codeSize);
    assert(! (size_t(code) & 15));

    {
        QQmlJS::Engine ee, *engine = ⅇ
        Lexer lexer(engine);
        lexer.setCode(source, 1, false);
        Parser parser(engine);

        const bool parsed = parser.parseProgram();

        foreach (const DiagnosticMessage &m, parser.diagnosticMessages()) {
            std::cerr << qPrintable(fileName) << ':' << m.loc.startLine << ':' << m.loc.startColumn
                      << ": error: " << qPrintable(m.message) << std::endl;
        }

        if (parsed) {
            using namespace AST;
            Program *program = AST::cast<Program *>(parser.rootNode());

            Codegen cg;
            globalCode = cg(program, &module);

            x86_64::InstructionSelection isel(vm, &module, code);
            foreach (IR::Function *function, module.functions) {
                isel(function);
            }
        }
    }

    if (! protect(code, codeSize))
        Q_UNREACHABLE();

    VM::Object *globalObject = vm->globalObject.objectValue;
    VM::Context *ctx = vm->rootContext;

    globalObject->setProperty(ctx, vm->identifier(QStringLiteral("print")),
                              VM::Value::fromObject(new builtins::Print(ctx)));

    ctx->varCount = globalCode->locals.size();
    if (ctx->varCount) {
        ctx->locals = new VM::Value[ctx->varCount];
        ctx->vars = new VM::String*[ctx->varCount];
        std::fill(ctx->locals, ctx->locals + ctx->varCount, VM::Value::undefinedValue());
        for (unsigned int i = 0; i < ctx->varCount; ++i)
            ctx->vars[i] = ctx->engine->identifier(*globalCode->locals.at(i));
    }

    globalCode->code(ctx);

    if (ctx->hasUncaughtException) {
        if (VM::ErrorObject *e = ctx->result.asErrorObject())
            std::cerr << "Uncaught exception: " << qPrintable(e->value.toString(ctx)->toQString()) << std::endl;
        else
            std::cerr << "Uncaught exception: " << qPrintable(ctx->result.toString(ctx)->toQString()) << std::endl;
    }

    delete[] ctx->locals;
    delete[] ctx->vars;
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QStringList args = app.arguments();
    args.removeFirst();

#ifndef QMLJS_NO_LLVM
    if (args.isEmpty()) {
        std::cerr << "Usage: v4 [--compile|--aot] file..." << std::endl;
        return 0;
    }

    if (args.first() == QLatin1String("--compile")) {
        args.removeFirst();
        return compileFiles(args);
    } else if (args.first() == QLatin1String("--aot")) {
        args.removeFirst();
        return evaluateCompiledCode(args);
    }
#endif

    foreach (const QString &fn, args) {
        QFile file(fn);
        if (file.open(QFile::ReadOnly)) {
            const QString code = QString::fromUtf8(file.readAll());
            file.close();
            QQmlJS::VM::ExecutionEngine vm;
            QQmlJS::VM::Context *ctx = vm.rootContext;

            QQmlJS::VM::Object *globalObject = vm.globalObject.objectValue;
            globalObject->setProperty(ctx, vm.identifier(QStringLiteral("print")),
                                      QQmlJS::VM::Value::fromObject(new builtins::Print(ctx)));

            evaluate(&vm, fn, code);
        }
    }
}
<|endoftext|>


<commit_before>be143c1c-4b02-11e5-a2e9-28cfe9171a43<commit_msg>Initial commit.2<commit_after>be21ac3a-4b02-11e5-bf19-28cfe9171a43<|endoftext|>


<commit_before>c78a4411-4b02-11e5-806e-28cfe9171a43<commit_msg>For bobby to integrate at some point<commit_after>c7972997-4b02-11e5-ad74-28cfe9171a43<|endoftext|>


<commit_before>6df1291e-ad59-11e7-8a0c-ac87a332f658<commit_msg>Introduced random NullPointerException bug<commit_after>6ea378d1-ad59-11e7-9bc2-ac87a332f658<|endoftext|>


<commit_before>#include "XmlRpcHttpd.h"

int  opterr = 1;
int  optind = 1;
int  optopt;
char *optarg;

static int getopt(int argc, char** argv, const char* opts) {
	static int sp = 1;
	register int c;
	register char *cp;

	if(sp == 1) {
		if(optind >= argc ||
				argv[optind][0] != '-' || argv[optind][1] == '\0')
			return(EOF);
		else if(strcmp(argv[optind], "--") == 0) {
			optind++;
			return(EOF);
		}
	}
	optopt = c = argv[optind][sp];
	if(c == ':' || (cp=strchr(opts, c)) == NULL) {
		if(argv[optind][++sp] == '\0') {
			optind++;
			sp = 1;
		}
		return('?');
	}
	if(*++cp == ':') {
		if(argv[optind][sp+1] != '\0')
			optarg = &argv[optind++][sp+1];
		else if(++optind >= argc) {
			sp = 1;
			return('?');
		} else
			optarg = argv[optind++];
		sp = 1;
	} else {
		if(argv[optind][++sp] == '\0') {
			sp = 1;
			optind++;
		}
		optarg = NULL;
	}
	return(c);
}

int main(int argc, char* argv[]) {
	int c;
	char* root = "./public_html";
	unsigned short port = 80;

#ifdef _WIN32
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif

	opterr = 0;
	while ((c = getopt(argc, (char**)argv, "p:d:") != -1)) {
		switch (optopt) {
		case 'p': port = (unsigned short)atol(optarg); break;
		case 'd': root = optarg; break;
		case '?': break;
		default:
			argc = 0;
			break;
		}
		optarg = NULL;
	}
	XmlRpc::XmlRpcHttpd httpd(port);
	httpd.bindRoot(root);
	httpd.mime_types["cgi"] = "@c:/strawberry/perl/bin/perl.exe";
	httpd.start();
	httpd.wait();
	// Ctrl-C to break
}
<commit_msg>added example for php.<commit_after>#include "XmlRpcHttpd.h"

int  opterr = 1;
int  optind = 1;
int  optopt;
char *optarg;

static int getopt(int argc, char** argv, const char* opts) {
	static int sp = 1;
	register int c;
	register char *cp;

	if(sp == 1) {
		if(optind >= argc ||
				argv[optind][0] != '-' || argv[optind][1] == '\0')
			return(EOF);
		else if(strcmp(argv[optind], "--") == 0) {
			optind++;
			return(EOF);
		}
	}
	optopt = c = argv[optind][sp];
	if(c == ':' || (cp=strchr(opts, c)) == NULL) {
		if(argv[optind][++sp] == '\0') {
			optind++;
			sp = 1;
		}
		return('?');
	}
	if(*++cp == ':') {
		if(argv[optind][sp+1] != '\0')
			optarg = &argv[optind++][sp+1];
		else if(++optind >= argc) {
			sp = 1;
			return('?');
		} else
			optarg = argv[optind++];
		sp = 1;
	} else {
		if(argv[optind][++sp] == '\0') {
			sp = 1;
			optind++;
		}
		optarg = NULL;
	}
	return(c);
}

int main(int argc, char* argv[]) {
	int c;
	char* root = "./public_html";
	unsigned short port = 80;

#ifdef _WIN32
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif

	opterr = 0;
	while ((c = getopt(argc, (char**)argv, "p:d:") != -1)) {
		switch (optopt) {
		case 'p': port = (unsigned short)atol(optarg); break;
		case 'd': root = optarg; break;
		case '?': break;
		default:
			argc = 0;
			break;
		}
		optarg = NULL;
	}
	XmlRpc::XmlRpcHttpd httpd(port);
	httpd.bindRoot(root);
	httpd.mime_types["cgi"] = "@c:/strawberry/perl/bin/perl.exe";
	httpd.mime_types["php"] = "@c:/progra~1/php/php.exe";
	httpd.start();
	httpd.wait();
	// Ctrl-C to break
}
<|endoftext|>


<commit_before>#include <QCoreApplication>
#include <QVariant>
#include <QDebug>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QJsonDocument>

using std::endl;
int main(int argc, char *argv[])
{
    qint64 li = 123;
    QVariant data(li);
    QJsonDocument doc;
    qDebug() << "doc isEmpty:" << doc.isEmpty() << " isNull:" << doc.isNull();
    qDebug() << data << endl;
    qDebug() << data.type() << endl;
    return 0;
}
<commit_msg>main: small test case<commit_after>#include <QCoreApplication>
#include <QDebug>
#include "qbencodedocument.h"

using std::endl;
int main(int argc, char *argv[])
{
    QByteArray bencode("li12e4:abcde");
    QBencodeParseError err;
    QBencodeDocument doc = QBencodeDocument::fromBencode(bencode, &err);

    qDebug() << err.errorString();
    qDebug() << doc;
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
using namespace std;

#include <Windows.h>

#define _USE_MATH_DEFINES
#include <math.h>

class Timer
{
public:
	void Start()
	{
		QueryPerformanceCounter(&startCounter);
	}

	void Stop()
	{
		LARGE_INTEGER endCounter, frequency;

		QueryPerformanceCounter(&endCounter);
		QueryPerformanceFrequency(&frequency);

		elapsedTimeUs = (endCounter.QuadPart - startCounter.QuadPart) * 1000000 / frequency.QuadPart;
	}

	long long ElapsedTimeUs()
	{
		return elapsedTimeUs;
	}

private:
	LARGE_INTEGER startCounter;
	long long elapsedTimeUs;
};

static const int fastSinTabLog2Size = 10; // size = 1024
static const int fastSinTabSize = (1 << fastSinTabLog2Size);
static double fastSinTab[fastSinTabSize];

void initFastSin()
{
	for (int i = 0; i < fastSinTabSize; i++)
	{
		double phase = (double)i / fastSinTabSize * M_PI;
		fastSinTab[i] = sin(phase);
	}
}

double fastSin(double x)
{
	const int fastSinTabMask = fastSinTabSize - 1;

	const int fractBits = 16;
	const int fractScale = 1 << fractBits;
	const int fractMask = fractScale - 1;

	double phase = x * ((double)fastSinTabSize / M_PI * (double)fractScale);
	unsigned long long phaseQuantized = (unsigned long long)(long long)phase;

	unsigned int whole = (unsigned int)phaseQuantized >> fractBits;
	unsigned int fract = (unsigned int)phaseQuantized & fractMask;

	int leftIndex = whole & fastSinTabMask;
	int rightIndex = (whole + 1) & fastSinTabMask;

	double left = fastSinTab[leftIndex];
	double right = fastSinTab[rightIndex];

	double fractMix = (double)fract * (1.0 / (double)fractScale);
	double result = left + (right - left) * fractMix;

	const int invertMask = fastSinTabSize;
	bool invert = (whole & invertMask) != 0;

	return invert ? -result : result;
}

double fastCos(double x)
{
	return fastSin(x + M_PI_2);
}

double func(double x)
{
	return sin(x + sin(x * 0.02f));
}

double fastFunc(double x)
{
	return fastSin(x + fastSin(x * 0.02f));
}

int main(int argc, char **argv)
{
	const int numIterations = 20000000;

	Timer timer;

	// Table init
	cout << "Table init: ";
	timer.Start();

	initFastSin();

	timer.Stop();
	cout << timer.ElapsedTimeUs() << "us" << endl;

	// Original timing
	cout << "Orig function: ";
	timer.Start();

	for (int i = 0; i < numIterations; i++)
	{
		volatile double res = func((double)(i - numIterations / 2));
	}

	timer.Stop();
	long long origTimeUs = timer.ElapsedTimeUs();
	cout << origTimeUs << "us" << endl;

	// Fast timing
	cout << "Fast function: ";
	timer.Start();

	for (int i = 0; i < numIterations; i++)
	{
		volatile double res = fastFunc((double)(i - numIterations / 2));
	}

	timer.Stop();
	long long fastTimeUs = timer.ElapsedTimeUs();
	cout << fastTimeUs << "us" << endl;

	// Improvement
	double improvement = (double)(origTimeUs - fastTimeUs) / (double)origTimeUs;
	cout << "Improvement: " << (improvement * 100.0) << "%" << endl;

	// Total error
	cout << "Total error: ";
	double totalError = 0.0;
	double maxError = 0.0;
	for (int i = 0; i < numIterations; i++)
	{
		double x = (double)i;
		double orig = func(x);
		double fast = fastFunc(x);
		double error = abs(fast - orig);
		totalError += error;
		maxError = max(maxError, error);
	}
	cout << totalError << endl;
	// Average error is total error / num iterations / range of func (in this case 1 - (-1) == 2)
	//  Not sure if this makes sense but it's some metric to optimize for at least :)
	double averageError = totalError / (double)numIterations / 2.0;
	cout << "Average error: " << (averageError * 100.0) << "%" << endl;
	cout << "Max error: " << maxError << endl;

	// Draw fn
	cout << "Graph:" << endl;
	const int gridWidth = 100;
	const int gridHeight = 20;
	const int gridSize = gridWidth * gridHeight;
	bool grid[gridSize];
	memset(grid, 0, gridSize * sizeof(bool));
	for (int i = 0; i < gridWidth; i++)
	{
		double phase = ((double)i / (double)gridWidth * 2.0 - 1.0) * (M_PI * 2.0);
		double res = fastSin(phase) * 0.5 + 0.5;
		int y = (int)(res * (double)(gridHeight - 1));
		grid[(gridHeight - 1 - y) * gridWidth + i] = true;
	}
	for (int y = 0; y < gridHeight; y++)
	{
		for (int x = 0; x < gridWidth; x++)
		{
			cout << string(grid[y * gridWidth + x] ? "*" : (x == gridWidth / 2 ? "|" : (y == gridHeight / 2 ? "-" : " ")));
		}
		cout << endl;
	}

	return 0;
}<commit_msg>drop pointless cast<commit_after>#include <iostream>
#include <string>
using namespace std;

#include <Windows.h>

#define _USE_MATH_DEFINES
#include <math.h>

class Timer
{
public:
	void Start()
	{
		QueryPerformanceCounter(&startCounter);
	}

	void Stop()
	{
		LARGE_INTEGER endCounter, frequency;

		QueryPerformanceCounter(&endCounter);
		QueryPerformanceFrequency(&frequency);

		elapsedTimeUs = (endCounter.QuadPart - startCounter.QuadPart) * 1000000 / frequency.QuadPart;
	}

	long long ElapsedTimeUs()
	{
		return elapsedTimeUs;
	}

private:
	LARGE_INTEGER startCounter;
	long long elapsedTimeUs;
};

static const int fastSinTabLog2Size = 10; // size = 1024
static const int fastSinTabSize = (1 << fastSinTabLog2Size);
static double fastSinTab[fastSinTabSize];

void initFastSin()
{
	for (int i = 0; i < fastSinTabSize; i++)
	{
		double phase = (double)i / fastSinTabSize * M_PI;
		fastSinTab[i] = sin(phase);
	}
}

double fastSin(double x)
{
	const int fastSinTabMask = fastSinTabSize - 1;

	const int fractBits = 16;
	const int fractScale = 1 << fractBits;
	const int fractMask = fractScale - 1;

	double phase = x * ((double)fastSinTabSize / M_PI * (double)fractScale);
	unsigned long long phaseQuantized = (unsigned long long)(long long)phase;

	unsigned int whole = (unsigned int)phaseQuantized >> fractBits;
	unsigned int fract = (unsigned int)phaseQuantized & fractMask;

	int leftIndex = whole & fastSinTabMask;
	int rightIndex = (whole + 1) & fastSinTabMask;

	double left = fastSinTab[leftIndex];
	double right = fastSinTab[rightIndex];

	double fractMix = (double)fract * (1.0 / fractScale);
	double result = left + (right - left) * fractMix;

	const int invertMask = fastSinTabSize;
	bool invert = (whole & invertMask) != 0;

	return invert ? -result : result;
}

double fastCos(double x)
{
	return fastSin(x + M_PI_2);
}

double func(double x)
{
	return sin(x + sin(x * 0.02f));
}

double fastFunc(double x)
{
	return fastSin(x + fastSin(x * 0.02f));
}

int main(int argc, char **argv)
{
	const int numIterations = 20000000;

	Timer timer;

	// Table init
	cout << "Table init: ";
	timer.Start();

	initFastSin();

	timer.Stop();
	cout << timer.ElapsedTimeUs() << "us" << endl;

	// Original timing
	cout << "Orig function: ";
	timer.Start();

	for (int i = 0; i < numIterations; i++)
	{
		volatile double res = func((double)(i - numIterations / 2));
	}

	timer.Stop();
	long long origTimeUs = timer.ElapsedTimeUs();
	cout << origTimeUs << "us" << endl;

	// Fast timing
	cout << "Fast function: ";
	timer.Start();

	for (int i = 0; i < numIterations; i++)
	{
		volatile double res = fastFunc((double)(i - numIterations / 2));
	}

	timer.Stop();
	long long fastTimeUs = timer.ElapsedTimeUs();
	cout << fastTimeUs << "us" << endl;

	// Improvement
	double improvement = (double)(origTimeUs - fastTimeUs) / (double)origTimeUs;
	cout << "Improvement: " << (improvement * 100.0) << "%" << endl;

	// Total error
	cout << "Total error: ";
	double totalError = 0.0;
	double maxError = 0.0;
	for (int i = 0; i < numIterations; i++)
	{
		double x = (double)i;
		double orig = func(x);
		double fast = fastFunc(x);
		double error = abs(fast - orig);
		totalError += error;
		maxError = max(maxError, error);
	}
	cout << totalError << endl;
	// Average error is total error / num iterations / range of func (in this case 1 - (-1) == 2)
	//  Not sure if this makes sense but it's some metric to optimize for at least :)
	double averageError = totalError / (double)numIterations / 2.0;
	cout << "Average error: " << (averageError * 100.0) << "%" << endl;
	cout << "Max error: " << maxError << endl;

	// Draw fn
	cout << "Graph:" << endl;
	const int gridWidth = 100;
	const int gridHeight = 20;
	const int gridSize = gridWidth * gridHeight;
	bool grid[gridSize];
	memset(grid, 0, gridSize * sizeof(bool));
	for (int i = 0; i < gridWidth; i++)
	{
		double phase = ((double)i / (double)gridWidth * 2.0 - 1.0) * (M_PI * 2.0);
		double res = fastSin(phase) * 0.5 + 0.5;
		int y = (int)(res * (double)(gridHeight - 1));
		grid[(gridHeight - 1 - y) * gridWidth + i] = true;
	}
	for (int y = 0; y < gridHeight; y++)
	{
		for (int x = 0; x < gridWidth; x++)
		{
			cout << string(grid[y * gridWidth + x] ? "*" : (x == gridWidth / 2 ? "|" : (y == gridHeight / 2 ? "-" : " ")));
		}
		cout << endl;
	}

	return 0;
}<|endoftext|>


<commit_before>d88f7517-4b02-11e5-a831-28cfe9171a43<commit_msg>#BUG723 uncommitted code found on my computer Monday morning<commit_after>d89ced5e-4b02-11e5-8a94-28cfe9171a43<|endoftext|>


<commit_before>bfd08b45-4b02-11e5-bc65-28cfe9171a43<commit_msg>I hope I am done<commit_after>bfda328f-4b02-11e5-88c8-28cfe9171a43<|endoftext|>


<commit_before>9c69f2e1-2747-11e6-8585-e0f84713e7b8<commit_msg>I'm done<commit_after>9c79b6bd-2747-11e6-be6e-e0f84713e7b8<|endoftext|>


<commit_before>#include "Engine.h"
#include "interface.h"
#include "GameMain.h"

#include "Console.h"
#include "direct.h"
#include "HMDWrapper.h"

#include "EngineConsole.h"
#include "FileSystem.h"

int main(int argc, char* argv[])
{
#ifdef USE_HMD
	g_pHMD->Init();
	int useHmd = g_pHMD->GetUseHMD();
	if (useHmd)
	{
		//ͷ3d
		render_stereo = 2;

		//Զ崰ڷֱ ͷֱһֱ
		video_mode = -1;
		video_width = 2160;
		video_height = 1200;

		// ȫʽ 0    1ȫ
		video_fullscreen = 0;

		video_resizable = 0;
		video_vsync = 0;
	}
	else
	{
		//ͷ
		render_stereo = 0;

		//Զ崰ڷֱ
		video_mode = -1;
		video_fullscreen = 0;
		video_width = 1280;
		video_height = 720;
		video_resizable = 0;
		video_vsync = 0;
	}
#else
	render_stereo = 0;

	video_mode = -1;
	video_fullscreen = 0;
	video_width = 1280;
	video_height = 720;
	video_resizable = 0;
	video_vsync = 0;
#endif

	char pAppPath[260];
	getcwd(pAppPath, 260);
	strcat(pAppPath, "\\");

	CGameMain t_Game;

	CInterfaceBase *pInit = MakeInterface(&t_Game, &CGameMain::Init);
	CInterfaceBase *pUpdate = MakeInterface(&t_Game, &CGameMain::Update);
	CInterfaceBase *pShutdown = MakeInterface(&t_Game, &CGameMain::ShutDown);
	CInterfaceBase *pRender = MakeInterface(&t_Game, &CGameMain::Render);

	char *pArg[3] = { NULL, "-engine_config", "data/TestProject.cfg" };	//ʲôõģ
	g_Engine.pEngine = new CEngine(NULL, pAppPath, NULL, NULL, 3, pArg, NULL, "1123581321", pInit);	//CEngineĳʼԼֵ

}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "Engine.h"
#include "interface.h"
#include "GameMain.h"

#include "Console.h"
#include "direct.h"
#include "HMDWrapper.h"

#include "EngineConsole.h"
#include "FileSystem.h"

int main(int argc, char* argv[])
{
#ifdef USE_HMD
	g_pHMD->Init();
	int useHmd = g_pHMD->GetUseHMD();
	if (useHmd)
	{
		//ͷ3d
		render_stereo = 2;

		//Զ崰ڷֱ ͷֱһֱ
		video_mode = -1;
		video_width = 2160;
		video_height = 1200;

		// ȫʽ 0    1ȫ
		video_fullscreen = 0;

		video_resizable = 0;
		video_vsync = 0;
	}
	else
	{
		//ͷ
		render_stereo = 0;

		//Զ崰ڷֱ
		video_mode = -1;
		video_fullscreen = 0;
		video_width = 1280;
		video_height = 720;
		video_resizable = 0;
		video_vsync = 0;
	}
#else
	render_stereo = 0;

	video_mode = -1;
	video_fullscreen = 0;
	video_width = 1280;
	video_height = 720;
	video_resizable = 0;
	video_vsync = 0;
#endif

	char pAppPath[260];
	getcwd(pAppPath, 260);
	strcat(pAppPath, "\\");

	CGameMain t_Game;

	CInterfaceBase *pInit = MakeInterface(&t_Game, &CGameMain::Init);
	CInterfaceBase *pUpdate = MakeInterface(&t_Game, &CGameMain::Update);
	CInterfaceBase *pShutdown = MakeInterface(&t_Game, &CGameMain::ShutDown);
	CInterfaceBase *pRender = MakeInterface(&t_Game, &CGameMain::Render);

	char *pArg[3] = { NULL, "-engine_config", "data/TestProject.cfg" };
	g_Engine.pEngine = new CEngine(NULL, pAppPath, NULL, NULL, 3, pArg, NULL, "1123581321", pInit);

}<|endoftext|>


<commit_before>725aee2e-4b02-11e5-abb8-28cfe9171a43<commit_msg>roselyn broke it<commit_after>7269052b-4b02-11e5-a47c-28cfe9171a43<|endoftext|>


<commit_before>/***********************************************************************
 *                                                                   _
 *       _____  _                           ____  _                 |_|
 *      |  _  |/ \   ____  ____ __ ___     / ___\/ \   __   _  ____  _
 *      | |_| || |  / __ \/ __ \\ '_  \ _ / /    | |___\ \ | |/ __ \| |
 *      |  _  || |__. ___/. ___/| | | ||_|\ \___ |  _  | |_| |. ___/| |
 *      |_/ \_|\___/\____|\____||_| |_|    \____/|_| |_|_____|\____||_|
 *
 *      ================================================================
 *                 More than a coder, More than a designer
 *      ================================================================
 *
 *
 *      - Document: image.cpp
 *      - Author: aleen42
 *      - Description: image class for all the image obj
 *      - Create Time: Nov 29th, 2015
 *      - Update Time: Feb 17th, 2016
 *
 **********************************************************************/

#include "opencv_main.h"
#include "common.h"

class Image
{
protected:
	Mat img;											// the container of the image
	const char* path;									// the local path of the image

	/* calculate the angle according to 3 points */
	double angle(Point pt1, Point pt2, Point pt0) {
		double dx1 = pt1.x - pt0.x;
		double dy1 = pt1.y - pt0.y;
		double dx2 = pt2.x - pt0.x;
		double dy2 = pt2.y - pt0.y;
		return (dx1 * dx2 + dy1 * dy2) / sqrt((dx1 * dx1 + dy1 * dy1) * (dx2 * dx2 + dy2 * dy2) + 1e-10);
	}

	/* show the detection of squares */
	void debugSquares(vector<vector<Point> > points) {

		for (int i = 0; i < points[0].size(); i++) {
			printf("Point%d: (%d, %d)\n", i, points[0][i].x, points[0][i].y);
		}

		drawContours(img, points, 0, Scalar(255, 0, 0), 1, 8, vector<Vec4i>(), 0, Point());
		// for (int i = 0; i < points.size(); i++) {
		// 	/* draw contour */
		// 	drawContours(img, points, i, Scalar(255, 0, 0), 1, 8, vector<Vec4i>(), 0, Point());

		// 	/* draw bounding rect */
		// 	Rect rect = boundingRect(Mat(points[i]));
		// 	rectangle(img, rect.tl(), rect.br(), cv::Scalar(255, 0, 0), 2, 8, 0);

		// 	/* draw rotated rect */
		// 	RotatedRect minRect = minAreaRect(Mat(points[i]));
		// 	Point2f rect_points[4];
		// 	minRect.points(rect_points);
		// 	for (int j = 0; j < 4; j++) {
		// 		line(img, rect_points[j], rect_points[(j + 1) % 4], Scalar(0, 0, 255), 1, 8);
		// 	}
		// }
	}
public:
	/* constructors of the class */
	Image() {}
	Image(Mat img) : img(img){}

	/* read the image from a local path */
	void readImage(const char* path) {
		/* set the path */
		this->path = path;
		/* read the image according to the path */
		this->img = imread(path);
		/* check existence */
		if (this->img.empty()) {
			ostringstream os;
			os << "Cannot load image from" << path;
			Common::errorPrint(os.str().c_str());
			/* exit */
			exit(-1);
		}
	}

	/* threshold algorithm */
	void thresholdImage(THRESHOLD_TYPE type) {
		Mat gray;
		const double threshold_value = 0.0;
		const double max_binary_value = 255.0;

		/* convert gray */
		cvtColor(this->img, gray, CV_BGR2GRAY);

		threshold(gray, this->img, threshold_value, max_binary_value, type);
	}

	/* detect squares algorithm by karlphillip */
	vector<vector<Point> > detectSquare(bool debug = false) {
		/* blur will enhance edge detection */
		Mat blurred(this->img);

		medianBlur(this->img, blurred, 9);

		Mat gray0(blurred.size(), CV_8U), gray;

		/* reserved Points array */
		vector<vector<Point> > reserved;
		/* contours Points array*/
		vector<vector<Point> > contours;

		/* find squares in every color plane of the image */
		for (int c = 0; c < 3; c++) {
			int ch[] = { c, 0 };

			/* canny ratio which is recommended as 3 by Canny */
			int ratio = 2;
			int lowThreshold = 10;

			mixChannels(&blurred, 1, &gray0, 1, ch, 1);

			/* try several threshold level */
			const int threshold_level = 2;
			for (int l = 0; l < threshold_level; l++) {
				/* Use Canny instead of zero threshold level */
				/* Canny helps to catch squares with gradient shading */
				if (l == 0) {
					Canny(gray0, gray, lowThreshold, ratio * lowThreshold, 3);

					/* Dilage helps to remove potential holes between edge segments */
					dilate(gray, gray, Mat(), Point(-1, -1));
				} else {
					gray = gray0 >= (l + 1) * 255 / threshold_level;
				}

				vector<Vec4i> hierarchy;
				/* find contours and store them in a list */
				findContours(gray, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

				/* draw contours to improve accuracy */
				for (size_t i = 0; i < contours.size(); i++) {
					drawContours(this->img, contours, i, Scalar(0, 0, 0), 1, 8, hierarchy, 0, Point());
				}

				/* test contours */
				vector<Point> approx;
				for (size_t i = 0; i < contours.size(); i++) {
					/* approximate contour with accuracy proportional to the contour perimeter */
					approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true) * 0.02, true);

					/*
					 * Note: absolute value of an area is used becuase
					 *       area may be positive or negative, in accordance
					 *		 with the contour orientation
					 */
					// cout << "size: " << approx.size() << endl;
					// cout << "area: " << fabs(contourArea(Mat(approx))) << endl;
					if (approx.size() == 4 && fabs(contourArea(Mat(approx))) > 1000 && isContourConvex(Mat(approx))) {
						double maxCosine = 0;

						for (int j = 2; j < 5; j++) {
							double cosine = fabs(angle(approx[j % 4], approx[j - 2], approx[j - 1]));
							maxCosine = MAX(maxCosine, cosine);
						}

						reserved.push_back(approx);

						//if (maxCosine < 0.3) {
						//	reserved.push_back(approx);
						//}
					}
				}
			}
		}

		/* check debug option */
 		if (debug && reserved.size() > 0) {
			debugSquares(reserved);
		}

		return reserved;
	}

	/* detect corner */
	vector<Point2f> detectCorner(bool debug = false) {
		vector<Point2f> Corners;

		/* parameters */
		const int maxCorners = 200;
		const double qualityLevels = 0.001;
		const double minDistance = 10;
		const int blockSize = 10;
		const bool useHarrisDetector = false;
		const int r = 5;

		Mat gray;
		cvtColor(this->img, gray, COLOR_BGR2GRAY);

		goodFeaturesToTrack(gray, Corners, maxCorners, qualityLevels, minDistance, Mat(), blockSize, useHarrisDetector);

		if (debug) {
			for (size_t i = 0; i < Corners.size(); i++) {
				ostringstream os;
				os << " (" << Corners[i].x << ", " << Corners[i].y << ")";
				circle(this->img, Corners[i], r, Scalar(255, 255, 255), 2, 8);
				putText(this->img, os.str(), Corners[i], FONT_HERSHEY_SCRIPT_SIMPLEX, 0.6, Scalar(0, 0, 255), 1, 8);
			}
		}

		return Corners;
	}

	void fastDetectCorner(bool debug = false) {
		vector<KeyPoint> keyPoints;

		FAST(this->img, keyPoints, 10, true, FastFeatureDetector::TYPE_7_12);

		if (debug) {
			drawKeypoints(this->img, keyPoints, this->img, Scalar(255, 255, 255), DrawMatchesFlags::DRAW_OVER_OUTIMG);
		}
	}

	/* write the image to the local path */
	void writeImage(const char* path) {
		/* save the image */
		imwrite(path, this->img);
	}

	/* a mothod to show the image */
	void showImage() {
		/* open the image */
		imshow("image", this->img);
		/* wait for the return */
		waitKey();
	}

	/* container */
	/* image */
	Mat getImage() {
		return this->img;
	}

	/* properties */
	/* width */
	int getWidth() {
		return this->img.cols;
	}

	/* height */
	int getHeight() {
		return this->img.rows;
	}

	/* size */
	Size getSize() {
		return this->img.size();
	}

	/* pointer to the matrix */
	uchar* getPtr(int n) {
		return this->img.ptr<uchar>(n);
	}
};
<commit_msg>update<commit_after>/***********************************************************************
 *                                                                   _
 *       _____  _                           ____  _                 |_|
 *      |  _  |/ \   ____  ____ __ ___     / ___\/ \   __   _  ____  _
 *      | |_| || |  / __ \/ __ \\ '_  \ _ / /    | |___\ \ | |/ __ \| |
 *      |  _  || |__. ___/. ___/| | | ||_|\ \___ |  _  | |_| |. ___/| |
 *      |_/ \_|\___/\____|\____||_| |_|    \____/|_| |_|_____|\____||_|
 *
 *      ================================================================
 *                 More than a coder, More than a designer
 *      ================================================================
 *
 *
 *      - Document: image.cpp
 *      - Author: aleen42
 *      - Description: image class for all the image obj
 *      - Create Time: Nov 29th, 2015
 *      - Update Time: Feb 17th, 2016
 *
 **********************************************************************/

#include "opencv_main.h"
#include "common.h"

class Image
{
protected:
	Mat img;											// the container of the image
	const char* path;									// the local path of the image

	/* calculate the angle according to 3 points */
	double angle(Point pt1, Point pt2, Point pt0) {
		double dx1 = pt1.x - pt0.x;
		double dy1 = pt1.y - pt0.y;
		double dx2 = pt2.x - pt0.x;
		double dy2 = pt2.y - pt0.y;
		return (dx1 * dx2 + dy1 * dy2) / sqrt((dx1 * dx1 + dy1 * dy1) * (dx2 * dx2 + dy2 * dy2) + 1e-10);
	}

	/* show the detection of squares */
	void debugSquares(vector<vector<Point> > points) {

		for (int i = 0; i < points[0].size(); i++) {
			printf("Point%d: (%d, %d)\n", i, points[0][i].x, points[0][i].y);
		}

		drawContours(img, points, 0, Scalar(255, 0, 0), 1, 8, vector<Vec4i>(), 0, Point());
		// for (int i = 0; i < points.size(); i++) {
		// 	/* draw contour */
		// 	drawContours(img, points, i, Scalar(255, 0, 0), 1, 8, vector<Vec4i>(), 0, Point());

		// 	/* draw bounding rect */
		// 	Rect rect = boundingRect(Mat(points[i]));
		// 	rectangle(img, rect.tl(), rect.br(), cv::Scalar(255, 0, 0), 2, 8, 0);

		// 	/* draw rotated rect */
		// 	RotatedRect minRect = minAreaRect(Mat(points[i]));
		// 	Point2f rect_points[4];
		// 	minRect.points(rect_points);
		// 	for (int j = 0; j < 4; j++) {
		// 		line(img, rect_points[j], rect_points[(j + 1) % 4], Scalar(0, 0, 255), 1, 8);
		// 	}
		// }
	}
public:
	/* constructors of the class */
	Image() {}
	Image(Mat img) : img(img){}

	/* read the image from a local path */
	void readImage(const char* path) {
		/* set the path */
		this->path = path;
		/* read the image according to the path */
		this->img = imread(path);
		/* check existence */
		if (this->img.empty()) {
			ostringstream os;
			os << "Cannot load image from" << path;
			Common::errorPrint(os.str().c_str());
			/* exit */
			exit(-1);
		}
	}

	/* threshold algorithm */
	void thresholdImage(THRESHOLD_TYPE type) {
		Mat gray;
		const double threshold_value = 0.0;
		const double max_binary_value = 255.0;

		/* convert gray */
		cvtColor(this->img, gray, CV_BGR2GRAY);

		threshold(gray, this->img, threshold_value, max_binary_value, type);
	}

	/* detect squares algorithm by karlphillip */
	vector<vector<Point> > detectSquare(bool debug = false) {
		/* blur will enhance edge detection */
		Mat blurred(this->img);

		medianBlur(this->img, blurred, 9);

		Mat gray0(blurred.size(), CV_8U), gray;

		/* reserved Points array */
		vector<vector<Point> > reserved;
		/* contours Points array*/
		vector<vector<Point> > contours;

		/* find squares in every color plane of the image */
		for (int c = 0; c < 3; c++) {
			int ch[] = { c, 0 };

			/* canny ratio which is recommended as 3 by Canny */
			int ratio = 2;
			int lowThreshold = 10;

			mixChannels(&blurred, 1, &gray0, 1, ch, 1);

			/* try several threshold level */
			const int threshold_level = 2;
			for (int l = 0; l < threshold_level; l++) {
				/* Use Canny instead of zero threshold level */
				/* Canny helps to catch squares with gradient shading */
				if (l == 0) {
					Canny(gray0, gray, lowThreshold, ratio * lowThreshold, 3);

					/* Dilage helps to remove potential holes between edge segments */
					dilate(gray, gray, Mat(), Point(-1, -1));
				} else {
					gray = gray0 >= (l + 1) * 255 / threshold_level;
				}

				vector<Vec4i> hierarchy;
				/* find contours and store them in a list */
				findContours(gray, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

				/* draw contours to improve accuracy */
				for (size_t i = 0; i < contours.size(); i++) {
					drawContours(this->img, contours, i, Scalar(0, 0, 0), 1, 8, hierarchy, 0, Point());
				}

				/* test contours */
				vector<Point> approx;
				for (size_t i = 0; i < contours.size(); i++) {
					/* approximate contour with accuracy proportional to the contour perimeter */
					approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true) * 0.02, true);

					/*
					 * Note: absolute value of an area is used becuase
					 *       area may be positive or negative, in accordance
					 *		 with the contour orientation
					 */
					// cout << "size: " << approx.size() << endl;
					// cout << "area: " << fabs(contourArea(Mat(approx))) << endl;
					if (approx.size() == 4 && fabs(contourArea(Mat(approx))) > 1000 && isContourConvex(Mat(approx))) {
						double maxCosine = 0;

						for (int j = 2; j < 5; j++) {
							double cosine = fabs(angle(approx[j % 4], approx[j - 2], approx[j - 1]));
							maxCosine = MAX(maxCosine, cosine);
						}

						reserved.push_back(approx);

						//if (maxCosine < 0.3) {
						//	reserved.push_back(approx);
						//}
					}
				}
			}
		}

		/* check debug option */
 		if (debug && reserved.size() > 0) {
			debugSquares(reserved);
		}

		return reserved;
	}

	/* detect corner */
	vector<Point2f> detectCorner(bool debug = false, const char* path = "data.json") {
		/* clock */
		time_t start = clock();

		vector<Point2f> Corners;

		/* parameters */
		const int maxCorners = 200;
		const double qualityLevels = 0.001;
		const double minDistance = 10;
		const int blockSize = 10;
		const bool useHarrisDetector = false;
		const int r = 5;

		Mat gray;
		cvtColor(this->img, gray, COLOR_BGR2GRAY);

		goodFeaturesToTrack(gray, Corners, maxCorners, qualityLevels, minDistance, Mat(), blockSize, useHarrisDetector);

		cJSON* pointsArray = cJSON_CreateArray();

		for (size_t i = 0; i < Corners.size(); i++) {
			if (debug) {
				ostringstream os;
				os << " (" << Corners[i].x << ", " << Corners[i].y << ")";
				circle(this->img, Corners[i], r, Scalar(255, 255, 255), 2, 8);
				putText(this->img, os.str(), Corners[i], FONT_HERSHEY_SCRIPT_SIMPLEX, 0.6, Scalar(0, 0, 255), 1, 8);
			}

			/* create json */
			cJSON* item = cJSON_CreateObject();
			cJSON_AddNumberToObject(item, "x", x);
			cJSON_AddNumberToObject(item, "y", y);

			cJSON_AddItemToArray(pointsArray, item);
		}

		time_t end = clock();
		cJSON* data = cJSON_CreateObject();
		const char* duration = (Common::doubleToStr(double(end - start) / CLOCKS_PER_SEC) + "s").c_str();
		cJSON_AddStringToObject(data, "time", duration);

		/* write the data.json */
		ofstream file;
		file.open(path, ios::out);

		if (file.is_open()) {
			file << cJSON_Print(pointsArray);
			cJSON_AddItemToObject(data, "data", pointsArray);
			file.close();
		}

		Common::successPrint(data);

		return Corners;
	}

	void fastDetectCorner(bool debug = false) {
		vector<KeyPoint> keyPoints;

		FAST(this->img, keyPoints, 10, true, FastFeatureDetector::TYPE_7_12);

		if (debug) {
			drawKeypoints(this->img, keyPoints, this->img, Scalar(255, 255, 255), DrawMatchesFlags::DRAW_OVER_OUTIMG);
		}
	}

	/* write the image to the local path */
	void writeImage(const char* path) {
		/* save the image */
		imwrite(path, this->img);
	}

	/* a mothod to show the image */
	void showImage() {
		/* open the image */
		imshow("image", this->img);
		/* wait for the return */
		waitKey();
	}

	/* container */
	/* image */
	Mat getImage() {
		return this->img;
	}

	/* properties */
	/* width */
	int getWidth() {
		return this->img.cols;
	}

	/* height */
	int getHeight() {
		return this->img.rows;
	}

	/* size */
	Size getSize() {
		return this->img.size();
	}

	/* pointer to the matrix */
	uchar* getPtr(int n) {
		return this->img.ptr<uchar>(n);
	}
};
<|endoftext|>


<commit_before>#include "ImageImporter2D.hpp"
#include "ImageStreamer2D.hpp"
#include "DeviceManager.hpp"
using namespace fast;

Image2D::Ptr create() {
    // Example of importing one 2D image
    ImageImporter2D::Ptr importer = ImageImporter2D::New();
    importer->setFilename("lena.jpg");
    Image2D::Ptr image = importer->getOutput();
    importer->getOutput();
    return importer->getOutput();
}

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

    // Get a GPU device and set it as the default device
    DeviceManager& deviceManager = DeviceManager::getInstance();
    deviceManager.setDefaultDevice(deviceManager.getOneGPUDevice());

    // Example of importing one 2D image
    ImageImporter2D::Ptr importer = ImageImporter2D::New();
    importer->setFilename("lena.jpg");
    Image2D::Ptr image = importer->getOutput();
    image->update();

    // Example of creating a pipeline in another scope and updating afterwards
    Image2D::Ptr image2 = create();
    std::cout << "after create" << std::endl;
    image2->update();

    // Example of streaming 2D images
    ImageStreamer2D::Ptr streamer = ImageStreamer2D::New();
    streamer->setFilenameFormat("test_#.jpg");
    Image2Dt::Ptr dynamicImage = streamer->getOutput();
    dynamicImage->update();
}
<commit_msg>removed some unnecessary code<commit_after>#include "ImageImporter2D.hpp"
#include "ImageStreamer2D.hpp"
#include "DeviceManager.hpp"
using namespace fast;

Image2D::Ptr create() {
    // Example of importing one 2D image
    ImageImporter2D::Ptr importer = ImageImporter2D::New();
    importer->setFilename("lena.jpg");
    return importer->getOutput();
}

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

    // Get a GPU device and set it as the default device
    DeviceManager& deviceManager = DeviceManager::getInstance();
    deviceManager.setDefaultDevice(deviceManager.getOneGPUDevice());

    // Example of importing one 2D image
    ImageImporter2D::Ptr importer = ImageImporter2D::New();
    importer->setFilename("lena.jpg");
    Image2D::Ptr image = importer->getOutput();
    image->update();

    // Example of creating a pipeline in another scope and updating afterwards
    Image2D::Ptr image2 = create();
    std::cout << "after create" << std::endl;
    image2->update();

    // Example of streaming 2D images
    ImageStreamer2D::Ptr streamer = ImageStreamer2D::New();
    streamer->setFilenameFormat("test_#.jpg");
    Image2Dt::Ptr dynamicImage = streamer->getOutput();
    dynamicImage->update();
}
<|endoftext|>


<commit_before>//
// Created by morgan on 07.06.2017.
//

#include "Definitions.h"
#include "pool/ThreadPool.h"
#include "pool/CachedThreadPool.h"
#include <iostream>
#include <thread>
#include <chrono>
#include "timer/Timer.h"

std::mutex consoleLock;
auto start = async::Clock::now();

void DummyJob2(int count)
{
    auto enterDTime = async::Clock::now() - start;
    auto threadId = std::this_thread::get_id();
    std::unique_lock<std::mutex> lock(consoleLock);
    std::cout << "Job " << count
              << " on thread " << threadId
              << " delta " << std::chrono::duration_cast<std::chrono::milliseconds>(enterDTime).count()
              << std::endl;
}

void DummyJob()
{
	auto threadId = std::this_thread::get_id();
	std::unique_lock<std::mutex> lock(consoleLock);
	std::cout << "Job on thread " << threadId << std::endl;
}

void TestThreadPool()
{
    async::pool::ThreadPool pool(8);

    for (auto i = 0; i < 10; ++i)
    {
        pool.AddJob(std::bind(DummyJob2, i));
    }
}

void TestCachedThreadPool()
{
    async::pool::CachedThreadPool pool;

    for (auto i = 0; i < 10; ++i)
    {
        pool.AddJob(std::bind(DummyJob2, i));
    }

    {
        std::unique_lock<std::mutex> lock(consoleLock);
        std::cout << "Pool concurrency level is " << pool.GetConcurrencyLevel() << std::endl;
    }

    std::this_thread::sleep_for(std::chrono::milliseconds(500));

    for (auto i = 0; i < 5; ++i)
    {
        pool.AddJob(std::bind(DummyJob2, i));
    }

    {
        std::unique_lock<std::mutex> lock(consoleLock);
        std::cout << "Pool concurrency level is " << pool.GetConcurrencyLevel() << std::endl;
    }
}

void TestTimers()
{
    async::timer::Timer t1(std::bind(DummyJob2, 1), 500, 800);
    async::timer::Timer t2(std::bind(DummyJob2, 2), 0, 1500);
    //async::timer::Timer t3(std::bind(DummyJob2, 3), 100, 100);

    std::this_thread::sleep_for(std::chrono::milliseconds(10000));
}

int main()
{
    TestThreadPool();

	char c;
	std::cin >> c;

    return 0;
}

<commit_msg>examples<commit_after>//
// Created by morgan on 07.06.2017.
//

#include "Definitions.h"
#include "pool/ThreadPool.h"
#include "pool/CachedThreadPool.h"
#include <iostream>
#include <thread>
#include <chrono>
#include "timer/Timer.h"

std::mutex consoleLock;
auto start = async::Clock::now();

void DummyJob(int count)
{
    auto enterDTime = async::Clock::now() - start;
    auto threadId = std::this_thread::get_id();
    std::unique_lock<std::mutex> lock(consoleLock);

    std::cout << "Job " << count
              << " on thread " << threadId
              //<< " delta " << std::chrono::duration_cast<std::chrono::milliseconds>(enterDTime).count()
              << std::endl;
}

void TestThreadPool()
{
    int workersCount = std::thread::hardware_concurrency();
    int jobsCount = workersCount * 2;
    async::pool::ThreadPool pool(workersCount);

    std::cout << "WorkersCount = " << workersCount << std::endl;
    std::cout << "JobsCount = " << jobsCount << std::endl;

    for (auto i = 0; i < jobsCount; ++i)
    {
        pool.AddJob(std::bind(DummyJob, i));
    }
}

void TestCachedThreadPool()
{
    int logicalCoresCount = std::thread::hardware_concurrency();
    int jobsCountFirst = logicalCoresCount * 2;
    int jobsCountSecond = logicalCoresCount / 2;
    async::pool::CachedThreadPool pool;

    std::cout << "LogicalCoresCount = " << logicalCoresCount << std::endl;
    std::cout << "JobsCountFirst = " << jobsCountFirst << std::endl;
    std::cout << "JobsCountSecond = " << jobsCountSecond << std::endl;

    for (auto i = 0; i < jobsCountFirst; ++i)
    {
        pool.AddJob(std::bind(DummyJob, i));
    }

    {
        std::unique_lock<std::mutex> lock(consoleLock);
        std::cout << "Pool concurrency level is " << pool.GetConcurrencyLevel() << std::endl;
    }

    //ensure some workers are expired
    std::this_thread::sleep_for(std::chrono::milliseconds(async::pool::WorkerDestroyDelay + 100));

    for (auto i = 0; i < jobsCountSecond; ++i)
    {
        pool.AddJob(std::bind(DummyJob, i));
    }

    {
        std::unique_lock<std::mutex> lock(consoleLock);
        std::cout << "Pool concurrency level is " << pool.GetConcurrencyLevel() << std::endl;
    }
}

void TestTimers()
{
    async::timer::Timer t1(std::bind(DummyJob, 1), 500, 100); // wait 500 ms and then fire each 100 ms
    async::timer::Timer t2(std::bind(DummyJob, 2), 0, 1500); // nowait, fire each 1,5 sec

    std::this_thread::sleep_for(std::chrono::milliseconds(3000));
}

int main()
{
    TestCachedThreadPool();

    system("pause");
}

<|endoftext|>


<commit_before>/*
 * main.cpp
 *
 *  Created on: Apr 22, 2014
 *      Author: Pimenta
 */

#include <SDL_net.h>
#include <cstdio>

int main(int argc, char* argv[]) {
  SDL_version compile_version;
  const SDL_version *link_version=SDLNet_Linked_Version();
  SDL_NET_VERSION(&compile_version);
  printf("compiled with SDL_net version: %d.%d.%d\n",
          compile_version.major,
          compile_version.minor,
          compile_version.patch);
  printf("running with SDL_net version: %d.%d.%d\n",
          link_version->major,
          link_version->minor,
          link_version->patch);

  return 0;
}
<commit_msg>Testing TCP<commit_after>/*
 * main.cpp
 *
 *  Created on: Apr 22, 2014
 *      Author: Pimenta
 */

#include <SDL.h>
#include <SDL_error.h>
#include <SDL_main.h>
#include <SDL_net.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>

using namespace std;

void init() {
  if (SDL_Init(0)) {
    fprintf(stderr, "SDL_Init: %s\n", SDL_GetError());
    exit(0);
  }

  if (SDLNet_Init()) {
    fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
    exit(0);
  }
}

void close() {
  SDLNet_Quit();
  SDL_Quit();
}

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

  // create a listening TCP socket on port 8080 (server)
  IPaddress ip;
  TCPsocket tcpsock;

  if(SDLNet_ResolveHost(&ip,NULL,8080)==-1) {
      printf("SDLNet_ResolveHost: %s\n", SDLNet_GetError());
      exit(1);
  }

  tcpsock=SDLNet_TCP_Open(&ip);
  if(!tcpsock) {
      printf("SDLNet_TCP_Open: %s\n", SDLNet_GetError());
      exit(2);
  }

  char * headers =
      "HTTP 1.1 200 OK\n"
      "Content-Type: text/html;\n"
      "Server: rosettaNaBoletta 0.1;\n"
      "\n";
  char* msg = "hello world";

  while (true) {
    TCPsocket client = SDLNet_TCP_Accept(tcpsock);
    if (client == nullptr)
      continue;
    else
      printf("olha q maravilha\n");
    SDLNet_TCP_Send(client, headers, strlen(headers));
    SDLNet_TCP_Send(client, msg, strlen(msg));
    SDLNet_TCP_Close(client);
  }

  SDLNet_TCP_Close(tcpsock);

  close();

  return 0;
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2015,
Dan Bethell, Johannes Saam, Vahan Sosoyan.
All rights reserved. See Copyright.txt for more details.
 */

#include "Client.h"
#include <boost/lexical_cast.hpp>
#include <stdexcept>
#include <iostream>

using namespace aton;
using boost::asio::ip::tcp;

Client::Client(std::string hostname, int port) :
               mHost(hostname),
               mPort(port),
               mImageId(-1),
               mSocket(mIoService)
{
}

void Client::connect(std::string hostname, int port)
{
    bool result = true;
    tcp::resolver resolver(mIoService);
    tcp::resolver::query query(hostname.c_str(), boost::lexical_cast<std::string>(port).c_str());
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    tcp::resolver::iterator end;
    boost::system::error_code error = boost::asio::error::host_not_found;
    while (error && endpoint_iterator != end)
    {
        mSocket.close();
        mSocket.connect(*endpoint_iterator++, error);
    }
    if (error)
        throw boost::system::system_error(error);
}

void Client::disconnect()
{
    mSocket.close();
}

Client::~Client()
{
    disconnect();
}

void Client::openImage(Data& header)
{
    // connect to port!
    connect(mHost, mPort);

    // send image header message with image desc information
    int key = 0;
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int)));

    // read our imageid
    boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&mImageId), sizeof(int)));

    // send our width & height
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mWidth), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mHeight), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mRArea), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mVersion), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mCurrentFrame), sizeof(float)));
}

void Client::sendPixels(Data& data)
{
    if (mImageId < 0)
    {
        throw std::runtime_error("Could not send data - image id is not valid!");
    }

    // send data for image_id
    int key = 1;
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&mImageId), sizeof(int)));

    // get size of the aov name in bytes
    size_t aov_size = strlen(data.mAovName)+1;

    // send pixel data
    int num_samples = data.mWidth * data.mHeight * data.mSpp;
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mX), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mY), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mWidth), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mHeight), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mRArea), sizeof(long long)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mVersion), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mCurrentFrame), sizeof(float)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mSpp), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mRam), sizeof(long long)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mTime), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&aov_size), sizeof(size_t)));
    boost::asio::write(mSocket, boost::asio::buffer(data.mAovName, aov_size));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mpData[0]), sizeof(float)*num_samples));
}

void Client::closeImage()
{
    // send image complete message for image_id
    int key = 2;
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int)));

    // tell the server which image we're closing
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&mImageId), sizeof(int)));

    // disconnect from port!
    disconnect();
}

void Client::quit()
{
    connect(mHost, mPort);
    int key = 9;
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int)));
    disconnect();
}
<commit_msg>Polish<commit_after>/*
Copyright (c) 2015,
Dan Bethell, Johannes Saam, Vahan Sosoyan.
All rights reserved. See Copyright.txt for more details.
 */

#include "Client.h"
#include <boost/lexical_cast.hpp>
#include <stdexcept>
#include <iostream>

using namespace aton;
using boost::asio::ip::tcp;

Client::Client(std::string hostname, int port) :
               mHost(hostname),
               mPort(port),
               mImageId(-1),
               mSocket(mIoService)
{
}

void Client::connect(std::string hostname, int port)
{
    tcp::resolver resolver(mIoService);
    tcp::resolver::query query(hostname.c_str(), boost::lexical_cast<std::string>(port).c_str());
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    tcp::resolver::iterator end;
    boost::system::error_code error = boost::asio::error::host_not_found;
    while (error && endpoint_iterator != end)
    {
        mSocket.close();
        mSocket.connect(*endpoint_iterator++, error);
    }
    if (error)
        throw boost::system::system_error(error);
}

void Client::disconnect()
{
    mSocket.close();
}

Client::~Client()
{
    disconnect();
}

void Client::openImage(Data& header)
{
    // connect to port!
    connect(mHost, mPort);

    // send image header message with image desc information
    int key = 0;
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int)));

    // read our imageid
    boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&mImageId), sizeof(int)));

    // send our width & height
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mWidth), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mHeight), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mRArea), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mVersion), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mCurrentFrame), sizeof(float)));
}

void Client::sendPixels(Data& data)
{
    if (mImageId < 0)
    {
        throw std::runtime_error("Could not send data - image id is not valid!");
    }

    // send data for image_id
    int key = 1;
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&mImageId), sizeof(int)));

    // get size of the aov name in bytes
    size_t aov_size = strlen(data.mAovName)+1;

    // send pixel data
    int num_samples = data.mWidth * data.mHeight * data.mSpp;
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mX), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mY), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mWidth), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mHeight), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mRArea), sizeof(long long)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mVersion), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mCurrentFrame), sizeof(float)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mSpp), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mRam), sizeof(long long)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mTime), sizeof(int)));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&aov_size), sizeof(size_t)));
    boost::asio::write(mSocket, boost::asio::buffer(data.mAovName, aov_size));
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mpData[0]), sizeof(float)*num_samples));
}

void Client::closeImage()
{
    // send image complete message for image_id
    int key = 2;
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int)));

    // tell the server which image we're closing
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&mImageId), sizeof(int)));

    // disconnect from port!
    disconnect();
}

void Client::quit()
{
    connect(mHost, mPort);
    int key = 9;
    boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int)));
    disconnect();
}
<|endoftext|>


<commit_before>//==============================================================================
// Include
//==============================================================================

#include "celib/allocator.h"
#include "celib/map.inl"
#include "celib/buffer.inl"

#include "cetech/kernel/hashlib.h"
#include "cetech/kernel/memory.h"
#include "cetech/kernel/api_system.h"
#include "cetech/kernel/log.h"
#include "cetech/kernel/path.h"
#include "cetech/kernel/vio.h"
#include "cetech/kernel/resource.h"
#include <cetech/kernel/module.h>
#include <cetech/modules/playground//asset_property.h>
#include <cetech/modules/debugui/debugui.h>
#include <cetech/modules/renderer/texture.h>
#include <cetech/modules/playground//entity_property.h>
#include <cetech/modules/entity/entity.h>
#include <cetech/modules/transform/transform.h>
#include <cfloat>
#include <celib/fpumath.h>
#include <cetech/kernel/ydb.h>
#include <cetech/modules/playground/command_system.h>

using namespace celib;
using namespace buffer;

//==============================================================================
// GLobals
//==============================================================================

#define _G TextureResourceGlobals
static struct _G {
} _G;

CETECH_DECL_API(ct_memory_a0);
CETECH_DECL_API(ct_resource_a0);
CETECH_DECL_API(ct_path_a0);
CETECH_DECL_API(ct_vio_a0);
CETECH_DECL_API(ct_log_a0);
CETECH_DECL_API(ct_hash_a0);
CETECH_DECL_API(ct_asset_property_a0);
CETECH_DECL_API(ct_debugui_a0);
CETECH_DECL_API(ct_texture_a0);
CETECH_DECL_API(ct_entity_property_a0);
CETECH_DECL_API(ct_transform_a0);
CETECH_DECL_API(ct_ydb_a0);
CETECH_DECL_API(ct_yng_a0);
CETECH_DECL_API(ct_cmd_system_a0);

struct set_pos_cmd_s {
    ct_cmd header;

    // ENT
    ct_world world;
    ct_entity entity;

    // ENT YAML
    const char* filename;
    uint64_t keys[32];
    uint32_t keys_count;

    // VALUES
    float new_value[3];
    float old_value[3];
};

static void set_pos_cmd(const struct ct_cmd *cmd,
                        bool inverse) {
    const struct set_pos_cmd_s *pos_cmd = (const set_pos_cmd_s*)cmd;

    const float* value = inverse ? pos_cmd->old_value : pos_cmd->new_value;

    ct_ydb_a0.set_vec3(pos_cmd->filename, pos_cmd->keys, pos_cmd->keys_count, (float*)value);

    ct_transform t = ct_transform_a0.get(pos_cmd->world, pos_cmd->entity);
    ct_transform_a0.set_position(t, (float*)value);
}

static void on_component(struct ct_world world,
                         struct ct_entity entity,
                         const char *filename,
                         uint64_t *keys,
                         uint32_t keys_count) {

    if (!ct_transform_a0.has(world, entity)) {
        return;
    }
    ct_transform t = ct_transform_a0.get(world, entity);

    float pos[3];
    float pos_new[3];
    uint64_t tmp_keys[keys_count + 1];
    memcpy(tmp_keys, keys, sizeof(uint64_t) * keys_count);

    tmp_keys[keys_count] = ct_yng_a0.calc_key("position");
    ct_ydb_a0.get_vec3(filename, tmp_keys, keys_count + 1,
                       pos_new, (float[3]) {0.0f});

    vec3_move(pos, pos_new);

    if (ct_debugui_a0.DragFloat3("position", pos_new, 1.0f, -FLT_MAX, FLT_MAX,
                                 "%.3f", 1.0f)) {

        struct set_pos_cmd_s cmd = {
                .header.size = sizeof(struct set_pos_cmd_s),
                .header.type = ct_hash_a0.id64_from_str("transform_set_position"),
                .header.description = {"set transformation position"},
                .world = world,
                .entity = entity,
                .filename = filename,
                .keys_count = keys_count  + 1,
                .new_value = {pos_new[0], pos_new[1], pos_new[2]},
                .old_value = {pos[0], pos[1], pos[2]},
        };
        memcpy(cmd.keys, tmp_keys, sizeof(uint64_t) * cmd.keys_count);
        ct_cmd_system_a0.execute(&cmd.header);
    }

    float rot[4];
    float norm_rot[4];
    float tmp_rot[3];
    ct_transform_a0.get_rotation(t, rot);
    quat_norm(norm_rot, rot);
    quat_to_euler(tmp_rot, norm_rot);
    vec3_mul(tmp_rot, tmp_rot, RAD_TO_DEG);

    tmp_keys[keys_count] = ct_yng_a0.calc_key("rotation");
    ct_ydb_a0.get_vec3(filename, tmp_keys, keys_count + 1, tmp_rot,
                       (float[3]) {0.0f});
    if (ct_debugui_a0.DragFloat3("rotation", tmp_rot, 1.0f, 0, 360, "%.5f",
                                 1.0f)) {
        ct_ydb_a0.set_vec3(filename, tmp_keys, keys_count + 1, tmp_rot);

        float rad_rot[3];
        float q[4];
        vec3_mul(rad_rot, tmp_rot, DEG_TO_RAD);
        quat_from_euler(q, rad_rot[0], rad_rot[1], rad_rot[2]);
        quat_norm(norm_rot, q);
        ct_transform_a0.set_rotation(t, norm_rot);
    }

    float scale[3];
    tmp_keys[keys_count] = ct_yng_a0.calc_key("scale");
    ct_ydb_a0.get_vec3(filename, tmp_keys, keys_count + 1, scale,
                       (float[3]) {1.0f});
    if (ct_debugui_a0.DragFloat3("scale", scale, 1.0f,
                                 -FLT_MAX, FLT_MAX,
                                 "%.3f", 1.0f)) {

        ct_transform_a0.set_scale(t, scale);
        ct_ydb_a0.set_vec3(filename, tmp_keys, keys_count + 1, scale);
    }
}

static int _init(ct_api_a0 *api) {
    CEL_UNUSED(api);

    _G = {};

    ct_entity_property_a0.register_component(
            ct_hash_a0.id64_from_str("transform"), on_component);

    ct_cmd_system_a0.register_cmd_execute(
            ct_hash_a0.id64_from_str("transform_set_position"),
            set_pos_cmd);

    return 1;
}

static void _shutdown() {

    ct_entity_property_a0.unregister_component(
            ct_hash_a0.id64_from_str("transform"));

    _G = {};
}

CETECH_MODULE_DEF(
        transform_property,
        {
            CETECH_GET_API(api, ct_memory_a0);
            CETECH_GET_API(api, ct_resource_a0);
            CETECH_GET_API(api, ct_path_a0);
            CETECH_GET_API(api, ct_vio_a0);
            CETECH_GET_API(api, ct_log_a0);
            CETECH_GET_API(api, ct_hash_a0);
            CETECH_GET_API(api, ct_asset_property_a0);
            CETECH_GET_API(api, ct_debugui_a0);
            CETECH_GET_API(api, ct_texture_a0);
            CETECH_GET_API(api, ct_entity_property_a0);
            CETECH_GET_API(api, ct_transform_a0);
            CETECH_GET_API(api, ct_ydb_a0);
            CETECH_GET_API(api, ct_yng_a0);
            CETECH_GET_API(api, ct_cmd_system_a0);
        },
        {
            CEL_UNUSED(reload);
            _init(api);
        },
        {
            CEL_UNUSED(reload);
            CEL_UNUSED(api);

            _shutdown();
        }
)<commit_msg>PLAYGR-50 - New playground - cmd for rotation and scale<commit_after>//==============================================================================
// Include
//==============================================================================

#include "celib/allocator.h"
#include "celib/map.inl"
#include "celib/buffer.inl"

#include "cetech/kernel/hashlib.h"
#include "cetech/kernel/memory.h"
#include "cetech/kernel/api_system.h"
#include "cetech/kernel/log.h"
#include "cetech/kernel/path.h"
#include "cetech/kernel/vio.h"
#include "cetech/kernel/resource.h"
#include <cetech/kernel/module.h>
#include <cetech/modules/playground//asset_property.h>
#include <cetech/modules/debugui/debugui.h>
#include <cetech/modules/renderer/texture.h>
#include <cetech/modules/playground//entity_property.h>
#include <cetech/modules/entity/entity.h>
#include <cetech/modules/transform/transform.h>
#include <cfloat>
#include <celib/fpumath.h>
#include <cetech/kernel/ydb.h>
#include <cetech/modules/playground/command_system.h>

using namespace celib;
using namespace buffer;

//==============================================================================
// GLobals
//==============================================================================

#define _G TextureResourceGlobals
static struct _G {
} _G;

CETECH_DECL_API(ct_memory_a0);
CETECH_DECL_API(ct_resource_a0);
CETECH_DECL_API(ct_path_a0);
CETECH_DECL_API(ct_vio_a0);
CETECH_DECL_API(ct_log_a0);
CETECH_DECL_API(ct_hash_a0);
CETECH_DECL_API(ct_asset_property_a0);
CETECH_DECL_API(ct_debugui_a0);
CETECH_DECL_API(ct_texture_a0);
CETECH_DECL_API(ct_entity_property_a0);
CETECH_DECL_API(ct_transform_a0);
CETECH_DECL_API(ct_ydb_a0);
CETECH_DECL_API(ct_yng_a0);
CETECH_DECL_API(ct_cmd_system_a0);

struct ct_ent_cmd_s {
    // ENT
    ct_world world;
    ct_entity entity;

    // ENT YAML
    const char* filename;
    uint64_t keys[32];
    uint32_t keys_count;
};

struct ct_ent_cmd_vec3_s {
    ct_cmd header;
    ct_ent_cmd_s ent;

    // VALUES
    float new_value[3];
    float old_value[3];
};

struct ct_ent_cmd_str_s {
    ct_cmd header;
    ct_ent_cmd_s ent;

    // VALUES
    char new_value[128];
    char old_value[128];
};

static void set_pos_cmd(const struct ct_cmd *cmd,
                        bool inverse) {
    const struct ct_ent_cmd_vec3_s *pos_cmd = (const ct_ent_cmd_vec3_s*)cmd;

    const float* value = inverse ? pos_cmd->old_value : pos_cmd->new_value;

    ct_ydb_a0.set_vec3(pos_cmd->ent.filename, pos_cmd->ent.keys, pos_cmd->ent.keys_count, (float*)value);

    ct_transform t = ct_transform_a0.get(pos_cmd->ent.world, pos_cmd->ent.entity);
    ct_transform_a0.set_position(t, (float*)value);
}

static void set_scale_cmd(const struct ct_cmd *cmd,
                         bool inverse) {
    const struct ct_ent_cmd_vec3_s *pos_cmd = (const ct_ent_cmd_vec3_s*)cmd;

    const float* value = inverse ? pos_cmd->old_value : pos_cmd->new_value;

    ct_ydb_a0.set_vec3(pos_cmd->ent.filename, pos_cmd->ent.keys, pos_cmd->ent.keys_count, (float*)value);

    ct_transform t = ct_transform_a0.get(pos_cmd->ent.world, pos_cmd->ent.entity);
    ct_transform_a0.set_scale(t, (float*)value);
}

static void set_rotation_cmd(const struct ct_cmd *cmd,
                          bool inverse) {
    const struct ct_ent_cmd_vec3_s *pos_cmd = (const ct_ent_cmd_vec3_s*)cmd;

    const float* value = inverse ? pos_cmd->old_value : pos_cmd->new_value;

    ct_ydb_a0.set_vec3(pos_cmd->ent.filename,
                       pos_cmd->ent.keys,
                       pos_cmd->ent.keys_count,
                       (float*)value);

    float rad_rot[3];
    float norm_rot[3];
    float q[4];
    vec3_mul(rad_rot, value, DEG_TO_RAD);
    quat_from_euler(q, rad_rot[0], rad_rot[1], rad_rot[2]);
    quat_norm(norm_rot, q);

    ct_transform t = ct_transform_a0.get(pos_cmd->ent.world, pos_cmd->ent.entity);
    ct_transform_a0.set_rotation(t, norm_rot);
}

static void on_component(struct ct_world world,
                         struct ct_entity entity,
                         const char *filename,
                         uint64_t *keys,
                         uint32_t keys_count) {

    if (!ct_transform_a0.has(world, entity)) {
        return;
    }
    ct_transform t = ct_transform_a0.get(world, entity);

    //==========================================================================
    // Position
    //==========================================================================
    float pos[3];
    float pos_new[3];
    uint64_t tmp_keys[keys_count + 1];
    memcpy(tmp_keys, keys, sizeof(uint64_t) * keys_count);

    tmp_keys[keys_count] = ct_yng_a0.calc_key("position");
    ct_ydb_a0.get_vec3(filename, tmp_keys, keys_count + 1,
                       pos_new, (float[3]) {0.0f});

    vec3_move(pos, pos_new);

    if (ct_debugui_a0.DragFloat3("position", pos_new, 1.0f, -FLT_MAX, FLT_MAX,
                                 "%.3f", 1.0f)) {

        struct ct_ent_cmd_vec3_s cmd = {
                .header = {
                    .description = {"set entity position"},
                    .size = sizeof(struct ct_ent_cmd_vec3_s),
                    .type = ct_hash_a0.id64_from_str("transform_set_position"),
                },
                .ent = {
                    .world = world,
                    .entity = entity,
                    .filename = filename,
                    .keys_count = keys_count + 1,
                },
                .new_value = {pos_new[0], pos_new[1], pos_new[2]},
                .old_value = {pos[0], pos[1], pos[2]},
        };
        memcpy(cmd.ent.keys, tmp_keys, sizeof(uint64_t) * cmd.ent.keys_count);
        ct_cmd_system_a0.execute(&cmd.header);
    }

    //==========================================================================
    // Rotation
    //==========================================================================
    float rot[4];
    float norm_rot[4];
    float tmp_rot[3];

    ct_transform_a0.get_rotation(t, rot);
    quat_norm(norm_rot, rot);
    quat_to_euler(rot, norm_rot);
    vec3_mul(tmp_rot, rot, RAD_TO_DEG);

    tmp_keys[keys_count] = ct_yng_a0.calc_key("rotation");
    ct_ydb_a0.get_vec3(filename, tmp_keys, keys_count + 1, tmp_rot,
                       (float[3]) {0.0f});

    vec3_move(rot, tmp_rot);
    if (ct_debugui_a0.DragFloat3("rotation", tmp_rot, 1.0f, 0, 360, "%.5f",
                                 1.0f)) {

        struct ct_ent_cmd_vec3_s cmd = {
                .header = {
                        .description = {"set entity rotation"},
                        .size = sizeof(struct ct_ent_cmd_vec3_s),
                        .type = ct_hash_a0.id64_from_str("transform_set_rotation"),
                },
                .ent = {
                        .world = world,
                        .entity = entity,
                        .filename = filename,
                        .keys_count = keys_count + 1,
                },
                .new_value = {tmp_rot[0], tmp_rot[1], tmp_rot[2]},
                .old_value = {rot[0], rot[1], rot[2]},
        };
        memcpy(cmd.ent.keys, tmp_keys, sizeof(uint64_t) * cmd.ent.keys_count);
        ct_cmd_system_a0.execute(&cmd.header);
    }

    //==========================================================================
    // Scale
    //==========================================================================
    float scale[3];
    float scale_new[3];
    tmp_keys[keys_count] = ct_yng_a0.calc_key("scale");
    ct_ydb_a0.get_vec3(filename, tmp_keys, keys_count + 1, scale_new,
                       (float[3]) {1.0f});

    vec3_move(scale, scale_new);
    if (ct_debugui_a0.DragFloat3("scale", scale_new, 1.0f,
                                 -FLT_MAX, FLT_MAX,
                                 "%.3f", 1.0f)) {

        struct ct_ent_cmd_vec3_s cmd = {
                .header = {
                        .description = {"set entity scale"},
                        .size = sizeof(struct ct_ent_cmd_vec3_s),
                        .type = ct_hash_a0.id64_from_str("transform_set_scale"),
                },
                .ent = {
                        .world = world,
                        .entity = entity,
                        .filename = filename,
                        .keys_count = keys_count + 1,
                },
                .new_value = {scale_new[0], scale_new[1], scale_new[2]},
                .old_value = {scale[0], scale[1], scale[2]},
        };
        memcpy(cmd.ent.keys, tmp_keys, sizeof(uint64_t) * cmd.ent.keys_count);
        ct_cmd_system_a0.execute(&cmd.header);
    }
}

static int _init(ct_api_a0 *api) {
    CEL_UNUSED(api);

    _G = {};

    ct_entity_property_a0.register_component(
            ct_hash_a0.id64_from_str("transform"),
            on_component);

    ct_cmd_system_a0.register_cmd_execute(
            ct_hash_a0.id64_from_str("transform_set_position"),
            set_pos_cmd);

    ct_cmd_system_a0.register_cmd_execute(
            ct_hash_a0.id64_from_str("transform_set_scale"),
            set_scale_cmd);

    ct_cmd_system_a0.register_cmd_execute(
            ct_hash_a0.id64_from_str("transform_set_rotation"),
            set_rotation_cmd);

    return 1;
}

static void _shutdown() {

    ct_entity_property_a0.unregister_component(
            ct_hash_a0.id64_from_str("transform"));

    _G = {};
}

CETECH_MODULE_DEF(
        transform_property,
        {
            CETECH_GET_API(api, ct_memory_a0);
            CETECH_GET_API(api, ct_resource_a0);
            CETECH_GET_API(api, ct_path_a0);
            CETECH_GET_API(api, ct_vio_a0);
            CETECH_GET_API(api, ct_log_a0);
            CETECH_GET_API(api, ct_hash_a0);
            CETECH_GET_API(api, ct_asset_property_a0);
            CETECH_GET_API(api, ct_debugui_a0);
            CETECH_GET_API(api, ct_texture_a0);
            CETECH_GET_API(api, ct_entity_property_a0);
            CETECH_GET_API(api, ct_transform_a0);
            CETECH_GET_API(api, ct_ydb_a0);
            CETECH_GET_API(api, ct_yng_a0);
            CETECH_GET_API(api, ct_cmd_system_a0);
        },
        {
            CEL_UNUSED(reload);
            _init(api);
        },
        {
            CEL_UNUSED(reload);
            CEL_UNUSED(api);

            _shutdown();
        }
)<|endoftext|>


<commit_before>ba4e942e-4b02-11e5-9e58-28cfe9171a43<commit_msg>Did a thing<commit_after>ba5b6a45-4b02-11e5-a98b-28cfe9171a43<|endoftext|>


<commit_before>e2934054-ad59-11e7-a0cc-ac87a332f658<commit_msg>almost working<commit_after>e343a187-ad59-11e7-8c4b-ac87a332f658<|endoftext|>


<commit_before>725507eb-2749-11e6-972e-e0f84713e7b8<commit_msg>TODO: Add a beter commit message<commit_after>7265954c-2749-11e6-8e11-e0f84713e7b8<|endoftext|>


<commit_before>#ifdef _DEBUG
#include "testdatapath.h"
#endif

#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>

using namespace std;

int showImage(const cv::Mat& image, int wait = 0){
	static const string wname("EBookChecker");

	cv::imshow(wname, image);
	return cv::waitKey(wait);
}

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

#ifndef _DEBUG
	string commandArgs =
		"@input |  | processing one image or image named serial number"
		;

	cv::CommandLineParser parser(argc, argv, commandArgs);

	string src = parser.get<string>(0);
#endif
	string src = TEST_DATA_0;

	cout << "input file:" << src << endl;

	cv::Mat image = cv::imread(src, CV_LOAD_IMAGE_GRAYSCALE);
	CV_Assert(image.channels() == 1 && image.type() == CV_8UC1);
	showImage(image);

	cv::Mat binary;
	int binaryMax = 255;
	int binaryThreshold = 128;
	cv::threshold(image, binary, binaryThreshold, binaryMax, cv::THRESH_BINARY_INV);
	CV_Assert(binary.channels() == 1 && image.type() == CV_8UC1);
	showImage(binary);
}<commit_msg>append to process integral image append to save result image<commit_after>#ifdef _DEBUG
#include "testdatapath.h"
#endif

#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>

using namespace std;

int showImage(const cv::Mat& image, int wait = 0){
	static const string wname("EBookChecker");

	cv::imshow(wname, image);
	return cv::waitKey(wait);
}

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

#ifndef _DEBUG
	string commandArgs =
		"@input |  | processing one image or image named serial number"
		;

	cv::CommandLineParser parser(argc, argv, commandArgs);

	string src = parser.get<string>(0);
#endif
	string src = TEST_DATA_0;

	cout << "input file:" << src << endl;

	cv::Mat image = cv::imread(src, CV_LOAD_IMAGE_GRAYSCALE);
	CV_Assert(image.channels() == 1 && image.type() == CV_8UC1);
	showImage(image);

	cv::Mat binary;
	int binaryMax = 255;
	int binaryThreshold = 128;
	cv::threshold(image, binary, binaryThreshold, binaryMax, cv::THRESH_BINARY_INV);
	CV_Assert(binary.channels() == 1 && image.type() == CV_8UC1);
	showImage(binary);
	cv::imwrite("binary.jpg", binary);

	cv::Mat integral;
	cv::integral(binary, integral);
	CV_Assert(integral.channels() == 1 && integral.type() == CV_32SC1);
	showImage(integral);
	cv::imwrite("integral.jpg", integral);
}<|endoftext|>