<commit_before>#include "pushBrowserApp.h"

//--------------------------------------------------------------
void pushBrowserApp::setup(){

	ofBackground(0);
    ofSetFrameRate(FRAME_RATE);
    ofSetVerticalSync(VERTICAL_SYNC);
    ofSetLogLevel(LOG_LEVEL);

    bFullScreen = bUpdateURL = bQRControl = bBrowserLoaded = bUpdateQRCode = bHideCursor = false;
    currentURL = defaultURL = pushURL = QRCurrentURL = QRDefaultURL = QRPushURL = "";

    loadSettings();

    if (bFullScreen){ofSetFullscreen(bFullScreen); windowWidth = ofGetWindowWidth(); windowHeight = ofGetWindowHeight();}
    else {ofSetWindowShape(windowWidth, windowHeight); ofSetWindowPosition(30, 50);}

    URLReceiver.setup(oscReceivePort);

    ofHideCursor();
}

//--------------------------------------------------------------
void pushBrowserApp::update(){

    if ((bBrowserLoaded == false)&&(defaultURL != "")){
        browser.setup(windowWidth, windowHeight);
        browser.loadURL(currentURL);
        bBrowserLoaded = true;
		ofxAwesomium::clearSessionCache();
		ofxAwesomium::clearSessionCookies();
    } else {

        ofxAwesomium::updateCore();
        browser.update();
        ofSetWindowTitle(browser.getTitle());
    }

    while(URLReceiver.hasWaitingMessages()){

        ofxOscMessage m;
        URLReceiver.getNextMessage(&m);
        if(m.getAddress() == "/pushURL"){
            pushURL = m.getArgAsString(0);
            bUpdateURL = true;
        }
		if(m.getAddress() == "/pushQRURL"){
            QRPushURL = m.getArgAsString(0);
            bUpdateQRCode = true;
        }
    }

    if ((bBrowserLoaded)&&(bUpdateURL)) {

        browser.loadURL(pushURL);
        currentURL = pushURL;
        pushURL = "";
        bUpdateURL = false;
		ofxAwesomium::clearSessionCache();
		ofxAwesomium::clearSessionCookies();
	}

	if (bUpdateQRCode) {

		loadQRCode(QRPushURL, QRCurrentSize);
        QRCurrentURL = QRPushURL; QRPushURL = "";
        bUpdateQRCode = false;
	}

    if ((windowWidth != ofGetWindowWidth()) || (windowHeight != ofGetWindowHeight())){

		windowWidth = ofGetWindowWidth(); windowHeight = ofGetWindowHeight();
        browser.setup(windowWidth, windowHeight);
        browser.loadURL(currentURL);
    }
}

//--------------------------------------------------------------
void pushBrowserApp::draw(){

    if(browser.getIsLoading()) {ofSetColor(0); ofDrawBitmapString("Loading...", 10, 15);}
    ofSetColor(255);
    browser.draw(0, 0);

	if ((bQRControl) && (QRControlCode.isAllocated())){
		ofPushMatrix();
			if (QRCurrentHeight == QR_TOP) ofTranslate(0,(QRCurrentSize/2) + QRCurrentMargin,0);
			else if (QRCurrentHeight == QR_BOTTOM) ofTranslate(0,ofGetWindowHeight()-(QRCurrentSize/2)-QRCurrentMargin,0);
			else  ofTranslate(0,ofGetWindowHeight()/2,0);

			if ((QRCurrentSide == QR_LEFT) || (QRCurrentSide == QR_BOTH)) QRControlCode.draw((QRCurrentSize/2) + QRCurrentMargin,0);
			if ((QRCurrentSide == QR_RIGHT) || (QRCurrentSide == QR_BOTH)) QRControlCode.draw(ofGetWindowWidth()-(QRCurrentSize/2)-QRCurrentMargin,0);

		ofPopMatrix();
	}
}

//--------------------------------------------------------------
void pushBrowserApp::keyPressed(int key){ browser.keyPressed(key);}
//--------------------------------------------------------------
void pushBrowserApp::keyReleased(int key){ browser.keyReleased(key);}
//--------------------------------------------------------------
void pushBrowserApp::mouseMoved(int x, int y ){

    if (bHideCursor) ofHideCursor(); else ofShowCursor();
    browser.mouseMoved(x, y);
}
//--------------------------------------------------------------
void pushBrowserApp::mouseDragged(int x, int y, int button){ browser.mouseDragged(x, y, button);}
//--------------------------------------------------------------
void pushBrowserApp::mousePressed(int x, int y, int button){browser.mousePressed(x, y, button);}
//--------------------------------------------------------------
void pushBrowserApp::mouseReleased(int x, int y, int button){browser.mouseReleased(x, y, button);}
//--------------------------------------------------------------
void pushBrowserApp::mouseEntered(int x, int y){}
//--------------------------------------------------------------
void pushBrowserApp::mouseExited(int x, int y){}
//--------------------------------------------------------------
void pushBrowserApp::windowResized(int w, int h){}
//--------------------------------------------------------------
void pushBrowserApp::gotMessage(ofMessage msg){}
//--------------------------------------------------------------
void pushBrowserApp::dragEvent(ofDragInfo dragInfo){}

void pushBrowserApp::loadSettings(){

    ofxXmlSettings  settings;
    settings.loadFile(DEFAULT_SETTINGS);
    windowWidth = origWindowWidth = settings.getValue("SETTINGS:WINDOW:WIDTH", WINDOW_WIDTH_DEFAULT);
	windowHeight = origWindowHeight = settings.getValue("SETTINGS:WINDOW:HEIGHT", WINDOW_HEIGHT_DEFAULT);
    string _bFullScreen = ofToLower(settings.getValue("SETTINGS:WINDOW:FULLSCREEN", DEFAULT_FULLSCREEN));
    if (_bFullScreen == "true") bFullScreen = true; else bFullScreen = false;
	string _bHideCursor = ofToLower(settings.getValue("SETTINGS:WINDOW:HIDE_CURSOR", DEFAULT_HIDE_CURSOR));
    if (_bHideCursor == "true") bHideCursor = true; else bHideCursor = false;

	currentURL = defaultURL = settings.getValue("SETTINGS:DEFAULT_URL", DEFAULT_URL);

	QRCurrentURL = QRDefaultURL = settings.getValue("SETTINGS:QR_CONTROL:DEFAULT_QR_URL", DEFAULT_QR_URL);
	string _bQRControl = ofToLower(settings.getValue("SETTINGS:QR_CONTROL:QR_ON", DEFAULT_QR_ON));
    if (_bQRControl == "true") bQRControl = true; else bQRControl = false;
	string _QRSide = ofToLower(settings.getValue("SETTINGS:QR_CONTROL:QR_SIDE", DEFAULT_QR_SIDE));
    if (_QRSide == "left") QRCurrentSide = QR_LEFT; if (_QRSide == "right") QRCurrentSide = QR_RIGHT; if (_QRSide == "both") QRCurrentSide = QR_BOTH;
	string _QRHeight = ofToLower(settings.getValue("SETTINGS:QR_CONTROL:QR_HEIGHT", DEFAULT_QR_HEIGHT));
    if (_QRHeight == "top") QRCurrentHeight = QR_TOP; if (_QRHeight == "middle") QRCurrentHeight = QR_MIDDLE; if (_QRHeight == "bottom") QRCurrentHeight = QR_BOTTOM;
	QRCurrentSize = settings.getValue("SETTINGS:QR_CONTROL:QR_SIZE", DEFAULT_QR_SIZE);
	QRCurrentMargin = settings.getValue("SETTINGS:QR_CONTROL:QR_MARGIN", DEFAULT_QR_MARGIN);
	if (bQRControl) {loadQRCode(QRCurrentURL, QRCurrentSize);}
	oscReceivePort = ofToInt(settings.getValue("SETTINGS:OSC_RECEIVE_PORT", DEFAULT_OSC_RECEIVE_PORT));
}

void pushBrowserApp::loadQRCode(string url, int size){

	QRControlCode = QRCodeGenerator.generate(url, size);
	QRControlCode.setAnchorPercent(0.5, 0.5);
}<commit_msg>qr code case sensitive<commit_after>#include "pushBrowserApp.h"

//--------------------------------------------------------------
void pushBrowserApp::setup(){

	ofBackground(0);
    ofSetFrameRate(FRAME_RATE);
    ofSetVerticalSync(VERTICAL_SYNC);
    ofSetLogLevel(LOG_LEVEL);

    bFullScreen = bUpdateURL = bQRControl = bBrowserLoaded = bUpdateQRCode = bHideCursor = false;
    currentURL = defaultURL = pushURL = QRCurrentURL = QRDefaultURL = QRPushURL = "";

    loadSettings();

    if (bFullScreen){ofSetFullscreen(bFullScreen); windowWidth = ofGetWindowWidth(); windowHeight = ofGetWindowHeight();}
    else {ofSetWindowShape(windowWidth, windowHeight); ofSetWindowPosition(30, 50);}

    URLReceiver.setup(oscReceivePort);

    ofHideCursor();
}

//--------------------------------------------------------------
void pushBrowserApp::update(){

    if ((bBrowserLoaded == false)&&(defaultURL != "")){
        browser.setup(windowWidth, windowHeight);
        browser.loadURL(currentURL);
        bBrowserLoaded = true;
		ofxAwesomium::clearSessionCache();
		ofxAwesomium::clearSessionCookies();
    } else {

        ofxAwesomium::updateCore();
        browser.update();
        ofSetWindowTitle(browser.getTitle());
    }

    while(URLReceiver.hasWaitingMessages()){

        ofxOscMessage m;
        URLReceiver.getNextMessage(&m);
        if(m.getAddress() == "/pushURL"){
            pushURL = m.getArgAsString(0);
            bUpdateURL = true;
        }
		if(m.getAddress() == "/pushQRURL"){
            QRPushURL = m.getArgAsString(0);
            bUpdateQRCode = true;
        }
    }

    if ((bBrowserLoaded)&&(bUpdateURL)) {

        browser.loadURL(pushURL);
        currentURL = pushURL;
        pushURL = "";
        bUpdateURL = false;
		ofxAwesomium::clearSessionCache();
		ofxAwesomium::clearSessionCookies();
	}

	if (bUpdateQRCode) {

		loadQRCode(QRPushURL, QRCurrentSize);
        QRCurrentURL = QRPushURL; QRPushURL = "";
        bUpdateQRCode = false;
	}

    if ((windowWidth != ofGetWindowWidth()) || (windowHeight != ofGetWindowHeight())){

		windowWidth = ofGetWindowWidth(); windowHeight = ofGetWindowHeight();
        browser.setup(windowWidth, windowHeight);
        browser.loadURL(currentURL);
    }
}

//--------------------------------------------------------------
void pushBrowserApp::draw(){

    if(browser.getIsLoading()) {ofSetColor(0); ofDrawBitmapString("Loading...", 10, 15);}
    ofSetColor(255);
    browser.draw(0, 0);

	if ((bQRControl) && (QRControlCode.isAllocated())){
		ofPushMatrix();
			if (QRCurrentHeight == QR_TOP) ofTranslate(0,(QRCurrentSize/2) + QRCurrentMargin,0);
			else if (QRCurrentHeight == QR_BOTTOM) ofTranslate(0,ofGetWindowHeight()-(QRCurrentSize/2)-QRCurrentMargin,0);
			else  ofTranslate(0,ofGetWindowHeight()/2,0);

			if ((QRCurrentSide == QR_LEFT) || (QRCurrentSide == QR_BOTH)) QRControlCode.draw((QRCurrentSize/2) + QRCurrentMargin,0);
			if ((QRCurrentSide == QR_RIGHT) || (QRCurrentSide == QR_BOTH)) QRControlCode.draw(ofGetWindowWidth()-(QRCurrentSize/2)-QRCurrentMargin,0);

		ofPopMatrix();
	}
}

//--------------------------------------------------------------
void pushBrowserApp::keyPressed(int key){ browser.keyPressed(key);}
//--------------------------------------------------------------
void pushBrowserApp::keyReleased(int key){ browser.keyReleased(key);}
//--------------------------------------------------------------
void pushBrowserApp::mouseMoved(int x, int y ){

    if (bHideCursor) ofHideCursor(); else ofShowCursor();
    browser.mouseMoved(x, y);
}
//--------------------------------------------------------------
void pushBrowserApp::mouseDragged(int x, int y, int button){ browser.mouseDragged(x, y, button);}
//--------------------------------------------------------------
void pushBrowserApp::mousePressed(int x, int y, int button){browser.mousePressed(x, y, button);}
//--------------------------------------------------------------
void pushBrowserApp::mouseReleased(int x, int y, int button){browser.mouseReleased(x, y, button);}
//--------------------------------------------------------------
void pushBrowserApp::mouseEntered(int x, int y){}
//--------------------------------------------------------------
void pushBrowserApp::mouseExited(int x, int y){}
//--------------------------------------------------------------
void pushBrowserApp::windowResized(int w, int h){}
//--------------------------------------------------------------
void pushBrowserApp::gotMessage(ofMessage msg){}
//--------------------------------------------------------------
void pushBrowserApp::dragEvent(ofDragInfo dragInfo){}

void pushBrowserApp::loadSettings(){

    ofxXmlSettings  settings;
    settings.loadFile(DEFAULT_SETTINGS);
    windowWidth = origWindowWidth = settings.getValue("SETTINGS:WINDOW:WIDTH", WINDOW_WIDTH_DEFAULT);
	windowHeight = origWindowHeight = settings.getValue("SETTINGS:WINDOW:HEIGHT", WINDOW_HEIGHT_DEFAULT);
    string _bFullScreen = ofToLower(settings.getValue("SETTINGS:WINDOW:FULLSCREEN", DEFAULT_FULLSCREEN));
    if (_bFullScreen == "true") bFullScreen = true; else bFullScreen = false;
	string _bHideCursor = ofToLower(settings.getValue("SETTINGS:WINDOW:HIDE_CURSOR", DEFAULT_HIDE_CURSOR));
    if (_bHideCursor == "true") bHideCursor = true; else bHideCursor = false;

	currentURL = defaultURL = settings.getValue("SETTINGS:DEFAULT_URL", DEFAULT_URL);

	QRCurrentURL = QRDefaultURL = settings.getValue("SETTINGS:QR_CONTROL:DEFAULT_QR_URL", DEFAULT_QR_URL);
	string _bQRControl = ofToLower(settings.getValue("SETTINGS:QR_CONTROL:QR_ON", DEFAULT_QR_ON));
    if (_bQRControl == "true") bQRControl = true; else bQRControl = false;
	string _QRSide = ofToLower(settings.getValue("SETTINGS:QR_CONTROL:QR_SIDE", DEFAULT_QR_SIDE));
    if (_QRSide == "left") QRCurrentSide = QR_LEFT; if (_QRSide == "right") QRCurrentSide = QR_RIGHT; if (_QRSide == "both") QRCurrentSide = QR_BOTH;
	string _QRHeight = ofToLower(settings.getValue("SETTINGS:QR_CONTROL:QR_HEIGHT", DEFAULT_QR_HEIGHT));
    if (_QRHeight == "top") QRCurrentHeight = QR_TOP; if (_QRHeight == "middle") QRCurrentHeight = QR_MIDDLE; if (_QRHeight == "bottom") QRCurrentHeight = QR_BOTTOM;
	QRCurrentSize = settings.getValue("SETTINGS:QR_CONTROL:QR_SIZE", DEFAULT_QR_SIZE);
	QRCurrentMargin = settings.getValue("SETTINGS:QR_CONTROL:QR_MARGIN", DEFAULT_QR_MARGIN);
	if (bQRControl) {loadQRCode(QRCurrentURL, QRCurrentSize);}
	oscReceivePort = ofToInt(settings.getValue("SETTINGS:OSC_RECEIVE_PORT", DEFAULT_OSC_RECEIVE_PORT));
}

void pushBrowserApp::loadQRCode(string url, int size){

	QRControlCode = QRCodeGenerator.generate(url, size, true, false);
	QRControlCode.setAnchorPercent(0.5, 0.5);
}<|endoftext|>


<commit_before>#include "braincloud/internal/SaveDataHelper.h"

#if !defined(__APPLE__)

#if defined(WINDOWS) || defined(WIN32)
#include <Windows.h>
#endif

SaveDataHelper * SaveDataHelper::m_instance = NULL;

SaveDataHelper::SaveDataHelper()
: m_savePath("")
{

}

SaveDataHelper * SaveDataHelper::getInstance()
{
    if (m_instance == NULL)
    {
        m_instance = new SaveDataHelper();
    }

    return m_instance;
}

void SaveDataHelper::initialize(const char * companyName, const char * appName)
{
#if defined(WINDOWS) || defined(WIN32)
    if (companyName != NULL && appName != NULL)
    {
        std::string companyNameStr = companyName;
        std::string gameNameStr = appName;
        m_savePath = std::string("Software\\" + companyNameStr + "\\" + gameNameStr + "\\");
    }
#endif
}

void SaveDataHelper::saveData(const char * key, const char * data)
{
#if defined(WINDOWS) || defined(WIN32)
#if defined WINAPI_FAMILY && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)
    std::string skey = key;
    std::string sdata = data;
    std::wstring wskey;
    std::wstring wsdata;
    for (auto c : skey) {
        wskey += (wchar_t)c;
    }
    for (auto c : sdata) {
        wsdata += (wchar_t)c;
    }
    Windows::Storage::ApplicationDataContainer^ localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;
    auto values = localSettings->Values;
    values->Insert(
        ref new Platform::String(wskey.c_str()),
        dynamic_cast<Windows::Foundation::PropertyValue^>(Windows::Foundation::PropertyValue::CreateString(ref new Platform::String(wsdata.c_str()))));
#else
    if (m_savePath.empty())
    {
        return;
    }

    LONG status;
    HKEY hKey;

    status = RegOpenKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, KEY_ALL_ACCESS, &hKey);
    if ((status == ERROR_SUCCESS) && (hKey != NULL)) {
        status = RegSetValueExA(hKey, key, 0, REG_SZ, (BYTE*)data, ((DWORD)strlen(data) + 1)*sizeof(char));
        RegCloseKey(hKey);
    }
    else if (status == ERROR_FILE_NOT_FOUND) {
        // Key didn't exist, create it
        SECURITY_ATTRIBUTES sAttribs = { sizeof(SECURITY_ATTRIBUTES) };
        DWORD dwDisposition = 0;
        status = RegCreateKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, "", REG_OPTION_VOLATILE, KEY_ALL_ACCESS, &sAttribs, &hKey, &dwDisposition);
        if (status == ERROR_SUCCESS) {
            // Set it's value
            status = RegOpenKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, KEY_ALL_ACCESS, &hKey);
            if ((status == ERROR_SUCCESS) && (hKey != NULL)) {
                status = RegSetValueExA(hKey, key, 0, REG_SZ, (BYTE*)data, ((DWORD)strlen(data) + 1)*sizeof(char));
                RegCloseKey(hKey);
            }
        }
    }
#endif
#endif
}

std::string SaveDataHelper::readData(const char * key)
{
    std::string sdata;

#if defined(WINDOWS) || defined(WIN32)
#if defined WINAPI_FAMILY && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)
    std::string skey = key;
    std::wstring wskey;
    for (auto c : skey) {
        wskey += (wchar_t)c;
    }
    Windows::Storage::ApplicationDataContainer^ localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;
    auto values = localSettings->Values;
    Platform::String^ value = safe_cast<Platform::String^>(localSettings->Values->Lookup(ref new Platform::String(wskey.c_str())));
    if (!value) return "";
    std::wstring wsdata = value->Data();
    for (auto c : wsdata) {
        sdata += (char)c;
    }
#else
    if (m_savePath.empty())
    {
        return "";
    }

    LONG status;
    HKEY hKey;
    status = RegOpenKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, KEY_READ, &hKey);
    if ((status == ERROR_SUCCESS) && (hKey != NULL)) {
        unsigned long type = REG_SZ, size = 1024;
        char res[1024] = "";

        status = RegQueryValueExA(hKey,
            key, NULL, &type, (LPBYTE)&res[0], &size);

        RegCloseKey(hKey);

        if (status == ERROR_SUCCESS) {
            sdata = res;
        }
    }
#endif
#else
    // android/linux implementation?
#endif

    return sdata;
}

void SaveDataHelper::deleteData(const char * key)
{
#if defined(WINDOWS) || defined(WIN32)
#if defined WINAPI_FAMILY && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)
    std::string skey = key;
    std::wstring wskey;
    for (auto c : skey) {
        wskey += (wchar_t)c;
    }
    Windows::Storage::ApplicationDataContainer^ localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;
    auto values = localSettings->Values;
    values->Remove(ref new Platform::String(wskey.c_str()));
#else
    if (m_savePath.empty())
    {
        return;
    }

    std::string data;

    LONG status;
    HKEY hKey;
    status = RegOpenKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, KEY_SET_VALUE, &hKey);
    if ((status == ERROR_SUCCESS) && (hKey != NULL)) {
        unsigned long type = REG_SZ, size = 1024;
        char res[1024] = "";

        status = RegDeleteValueA(hKey, key);
        RegCloseKey(hKey);
    }
#endif
#endif
}

#endif //__APPLE__
<commit_msg>Adding missing header fix for Linux build<commit_after>#include "braincloud/internal/SaveDataHelper.h"

#if !defined(__APPLE__)

#if defined(WINDOWS) || defined(WIN32)
#include <Windows.h>
#endif

SaveDataHelper * SaveDataHelper::m_instance = NULL;

SaveDataHelper::SaveDataHelper()
: m_savePath("")
{

}

SaveDataHelper * SaveDataHelper::getInstance()
{
    if (m_instance == NULL)
    {
        m_instance = new SaveDataHelper();
    }

    return m_instance;
}

void SaveDataHelper::initialize(const char * companyName, const char * appName, const char * wrapperName)
{
#if defined(WINDOWS) || defined(WIN32)
    if (companyName != NULL && appName != NULL)
    {
        std::string companyNameStr = companyName;
        std::string gameNameStr = appName;
        m_savePath = std::string("Software\\" + companyNameStr + "\\" + gameNameStr + "\\");
    }
#endif
}

void SaveDataHelper::saveData(const char * key, const char * data)
{
#if defined(WINDOWS) || defined(WIN32)
#if defined WINAPI_FAMILY && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)
    std::string skey = key;
    std::string sdata = data;
    std::wstring wskey;
    std::wstring wsdata;
    for (auto c : skey) {
        wskey += (wchar_t)c;
    }
    for (auto c : sdata) {
        wsdata += (wchar_t)c;
    }
    Windows::Storage::ApplicationDataContainer^ localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;
    auto values = localSettings->Values;
    values->Insert(
        ref new Platform::String(wskey.c_str()),
        dynamic_cast<Windows::Foundation::PropertyValue^>(Windows::Foundation::PropertyValue::CreateString(ref new Platform::String(wsdata.c_str()))));
#else
    if (m_savePath.empty())
    {
        return;
    }

    LONG status;
    HKEY hKey;

    status = RegOpenKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, KEY_ALL_ACCESS, &hKey);
    if ((status == ERROR_SUCCESS) && (hKey != NULL)) {
        status = RegSetValueExA(hKey, key, 0, REG_SZ, (BYTE*)data, ((DWORD)strlen(data) + 1)*sizeof(char));
        RegCloseKey(hKey);
    }
    else if (status == ERROR_FILE_NOT_FOUND) {
        // Key didn't exist, create it
        SECURITY_ATTRIBUTES sAttribs = { sizeof(SECURITY_ATTRIBUTES) };
        DWORD dwDisposition = 0;
        status = RegCreateKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, "", REG_OPTION_VOLATILE, KEY_ALL_ACCESS, &sAttribs, &hKey, &dwDisposition);
        if (status == ERROR_SUCCESS) {
            // Set it's value
            status = RegOpenKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, KEY_ALL_ACCESS, &hKey);
            if ((status == ERROR_SUCCESS) && (hKey != NULL)) {
                status = RegSetValueExA(hKey, key, 0, REG_SZ, (BYTE*)data, ((DWORD)strlen(data) + 1)*sizeof(char));
                RegCloseKey(hKey);
            }
        }
    }
#endif
#endif
}

std::string SaveDataHelper::readData(const char * key)
{
    std::string sdata;

#if defined(WINDOWS) || defined(WIN32)
#if defined WINAPI_FAMILY && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)
    std::string skey = key;
    std::wstring wskey;
    for (auto c : skey) {
        wskey += (wchar_t)c;
    }
    Windows::Storage::ApplicationDataContainer^ localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;
    auto values = localSettings->Values;
    Platform::String^ value = safe_cast<Platform::String^>(localSettings->Values->Lookup(ref new Platform::String(wskey.c_str())));
    if (!value) return "";
    std::wstring wsdata = value->Data();
    for (auto c : wsdata) {
        sdata += (char)c;
    }
#else
    if (m_savePath.empty())
    {
        return "";
    }

    LONG status;
    HKEY hKey;
    status = RegOpenKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, KEY_READ, &hKey);
    if ((status == ERROR_SUCCESS) && (hKey != NULL)) {
        unsigned long type = REG_SZ, size = 1024;
        char res[1024] = "";

        status = RegQueryValueExA(hKey,
            key, NULL, &type, (LPBYTE)&res[0], &size);

        RegCloseKey(hKey);

        if (status == ERROR_SUCCESS) {
            sdata = res;
        }
    }
#endif
#else
    // android/linux implementation?
#endif

    return sdata;
}

void SaveDataHelper::deleteData(const char * key)
{
#if defined(WINDOWS) || defined(WIN32)
#if defined WINAPI_FAMILY && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)
    std::string skey = key;
    std::wstring wskey;
    for (auto c : skey) {
        wskey += (wchar_t)c;
    }
    Windows::Storage::ApplicationDataContainer^ localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;
    auto values = localSettings->Values;
    values->Remove(ref new Platform::String(wskey.c_str()));
#else
    if (m_savePath.empty())
    {
        return;
    }

    std::string data;

    LONG status;
    HKEY hKey;
    status = RegOpenKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, KEY_SET_VALUE, &hKey);
    if ((status == ERROR_SUCCESS) && (hKey != NULL)) {
        unsigned long type = REG_SZ, size = 1024;
        char res[1024] = "";

        status = RegDeleteValueA(hKey, key);
        RegCloseKey(hKey);
    }
#endif
#endif
}

#endif //__APPLE__
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qgeomappingmanagerengine_nokia.h"
#include "qgeomapreply_nokia.h"

#include <qgeotiledmaprequest.h>

#include <QNetworkAccessManager>
#include <QNetworkDiskCache>
#include <QNetworkProxy>
#include <QSize>
#include <QDir>
#include <QDateTime>

#include <QDebug>

#define LARGE_TILE_DIMENSION 256
#define PI 3.14159265
#include <math.h>

QGeoMappingManagerEngineNokia::QGeoMappingManagerEngineNokia(const QMap<QString, QVariant> &parameters, QGeoServiceProvider::Error *error, QString *errorString)
        : QGeoTiledMappingManagerEngine(parameters),
        m_host("loc.desktop.maps.svc.ovi.com")
{
    setTileSize(QSize(128,128));
    setMinimumZoomLevel(0.0);
    setMaximumZoomLevel(18.0);

    QList<QGeoMapWidget::MapType> types;
    types << QGeoMapWidget::StreetMap;
    types << QGeoMapWidget::SatelliteMapDay;
    types << QGeoMapWidget::TerrainMap;
    setSupportedMapTypes(types);

    m_nam = new QNetworkAccessManager(this);
    m_cache = new QNetworkDiskCache(this);

    QDir dir = QDir::temp();
    dir.mkdir("maptiles");
    dir.cd("maptiles");

    m_cache->setCacheDirectory(dir.path());

    QList<QString> keys = parameters.keys();

    if (keys.contains("mapping.proxy")) {
        QString proxy = parameters.value("mapping.proxy").toString();
        if (!proxy.isEmpty())
            m_nam->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, proxy, 8080));
    }

    if (keys.contains("mapping.host")) {
        QString host = parameters.value("mapping.host").toString();
        if (!host.isEmpty())
            m_host = host;
    }

    if (keys.contains("mapping.cache.directory")) {
        QString cacheDir = parameters.value("mapping.cache.directory").toString();
        if (!cacheDir.isEmpty())
            m_cache->setCacheDirectory(cacheDir);
    }

    if (keys.contains("mapping.cache.size")) {
        bool ok = false;
        qint64 cacheSize = parameters.value("mapping.cache.size").toString().toLongLong(&ok);
        if (ok)
            m_cache->setMaximumCacheSize(cacheSize);
    }

    m_nam->setCache(m_cache);
}

QGeoMappingManagerEngineNokia::~QGeoMappingManagerEngineNokia() {}

QGeoTiledMapReply* QGeoMappingManagerEngineNokia::getTileImage(const QGeoTiledMapRequest &request)
{
    QString rawRequest = getRequestString(request);

    QNetworkRequest netRequest = QNetworkRequest(QUrl(rawRequest));
    netRequest.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);
    m_cache->metaData(netRequest.url()).setLastModified(QDateTime::currentDateTime());

    QNetworkReply* netReply = m_nam->get(netRequest);

    QGeoTiledMapReply* mapReply = new QGeoMapReplyNokia(netReply, request, this);

        // TODO goes badly on linux
    //qDebug() << "request: " << QString::number(reinterpret_cast<int>(mapReply), 16) << " " << request.row() << "," << request.column();
    return mapReply;
}

QString QGeoMappingManagerEngineNokia::getRequestString(const QGeoTiledMapRequest &request) const
{
    QString requestString = "http://";
    requestString += m_host;
    requestString += "/maptiler/maptile/newest/";
    requestString += mapTypeToStr(request.mapType());
    requestString += '/';
    requestString += QString::number(request.zoomLevel());
    requestString += '/';
    requestString += QString::number(request.column());
    requestString += '/';
    requestString += QString::number(request.row());
    requestString += '/';
    requestString += sizeToStr(tileSize());
    requestString += '/';
    requestString += "png";

    if (!m_token.isEmpty()) {
        requestString += "?token=";
        requestString += m_token;

        if (!m_referrer.isEmpty()) {
            requestString += "&referrer=";
            requestString += m_referrer;
        }
    } else if (!m_referrer.isEmpty()) {
        requestString += "?referrer=";
        requestString += m_referrer;
    }

    return requestString;
}

QString QGeoMappingManagerEngineNokia::sizeToStr(const QSize &size)
{
    if (size.height() >= LARGE_TILE_DIMENSION ||
            size.width() >= LARGE_TILE_DIMENSION)
        return "256";
    else
        return "128";
}

QString QGeoMappingManagerEngineNokia::mapTypeToStr(QGeoMapWidget::MapType type)
{
    if (type == QGeoMapWidget::StreetMap)
        return "normal.day";
    else if (type == QGeoMapWidget::SatelliteMapDay ||
             type == QGeoMapWidget::SatelliteMapNight) {
        return "satellite.day";
    } else if (type == QGeoMapWidget::TerrainMap)
        return "terrain.day";
    else
        return "normal.day";
}

<commit_msg>QGeoMappingManagerEngineNokia::getTileImage: Simplified something, added an alternative qDebug line<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qgeomappingmanagerengine_nokia.h"
#include "qgeomapreply_nokia.h"

#include <qgeotiledmaprequest.h>

#include <QNetworkAccessManager>
#include <QNetworkDiskCache>
#include <QNetworkProxy>
#include <QSize>
#include <QDir>
#include <QDateTime>

#include <QDebug>

#define LARGE_TILE_DIMENSION 256
#define PI 3.14159265
#include <math.h>

QGeoMappingManagerEngineNokia::QGeoMappingManagerEngineNokia(const QMap<QString, QVariant> &parameters, QGeoServiceProvider::Error *error, QString *errorString)
        : QGeoTiledMappingManagerEngine(parameters),
        m_host("loc.desktop.maps.svc.ovi.com")
{
    setTileSize(QSize(128,128));
    setMinimumZoomLevel(0.0);
    setMaximumZoomLevel(18.0);

    QList<QGeoMapWidget::MapType> types;
    types << QGeoMapWidget::StreetMap;
    types << QGeoMapWidget::SatelliteMapDay;
    types << QGeoMapWidget::TerrainMap;
    setSupportedMapTypes(types);

    m_nam = new QNetworkAccessManager(this);
    m_cache = new QNetworkDiskCache(this);

    QDir dir = QDir::temp();
    dir.mkdir("maptiles");
    dir.cd("maptiles");

    m_cache->setCacheDirectory(dir.path());

    QList<QString> keys = parameters.keys();

    if (keys.contains("mapping.proxy")) {
        QString proxy = parameters.value("mapping.proxy").toString();
        if (!proxy.isEmpty())
            m_nam->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, proxy, 8080));
    }

    if (keys.contains("mapping.host")) {
        QString host = parameters.value("mapping.host").toString();
        if (!host.isEmpty())
            m_host = host;
    }

    if (keys.contains("mapping.cache.directory")) {
        QString cacheDir = parameters.value("mapping.cache.directory").toString();
        if (!cacheDir.isEmpty())
            m_cache->setCacheDirectory(cacheDir);
    }

    if (keys.contains("mapping.cache.size")) {
        bool ok = false;
        qint64 cacheSize = parameters.value("mapping.cache.size").toString().toLongLong(&ok);
        if (ok)
            m_cache->setMaximumCacheSize(cacheSize);
    }

    m_nam->setCache(m_cache);
}

QGeoMappingManagerEngineNokia::~QGeoMappingManagerEngineNokia() {}

QGeoTiledMapReply* QGeoMappingManagerEngineNokia::getTileImage(const QGeoTiledMapRequest &request)
{
    QString rawRequest = getRequestString(request);

    QNetworkRequest netRequest((QUrl(rawRequest))); // The extra pair of parens disambiguates this from a function declaration
    netRequest.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);
    m_cache->metaData(netRequest.url()).setLastModified(QDateTime::currentDateTime());

    QNetworkReply* netReply = m_nam->get(netRequest);

    QGeoTiledMapReply* mapReply = new QGeoMapReplyNokia(netReply, request, this);

    // TODO goes badly on linux
    //qDebug() << "request: " << QString::number(reinterpret_cast<int>(mapReply), 16) << " " << request.row() << "," << request.column();
    // this one might work better. It follows defined behaviour, unlike reinterpret_cast
    //qDebug("request: %p %i,%i @ %i", mapReply, request.row(), request.column(), request.zoomLevel());
    return mapReply;
}

QString QGeoMappingManagerEngineNokia::getRequestString(const QGeoTiledMapRequest &request) const
{
    QString requestString = "http://";
    requestString += m_host;
    requestString += "/maptiler/maptile/newest/";
    requestString += mapTypeToStr(request.mapType());
    requestString += '/';
    requestString += QString::number(request.zoomLevel());
    requestString += '/';
    requestString += QString::number(request.column());
    requestString += '/';
    requestString += QString::number(request.row());
    requestString += '/';
    requestString += sizeToStr(tileSize());
    requestString += '/';
    requestString += "png";

    if (!m_token.isEmpty()) {
        requestString += "?token=";
        requestString += m_token;

        if (!m_referrer.isEmpty()) {
            requestString += "&referrer=";
            requestString += m_referrer;
        }
    } else if (!m_referrer.isEmpty()) {
        requestString += "?referrer=";
        requestString += m_referrer;
    }

    return requestString;
}

QString QGeoMappingManagerEngineNokia::sizeToStr(const QSize &size)
{
    if (size.height() >= LARGE_TILE_DIMENSION ||
            size.width() >= LARGE_TILE_DIMENSION)
        return "256";
    else
        return "128";
}

QString QGeoMappingManagerEngineNokia::mapTypeToStr(QGeoMapWidget::MapType type)
{
    if (type == QGeoMapWidget::StreetMap)
        return "normal.day";
    else if (type == QGeoMapWidget::SatelliteMapDay ||
             type == QGeoMapWidget::SatelliteMapNight) {
        return "satellite.day";
    } else if (type == QGeoMapWidget::TerrainMap)
        return "terrain.day";
    else
        return "normal.day";
}

<|endoftext|>


<commit_before>#include "MainGUI.moc"

#include <cstdlib>
#include <QPushButton>

#include "../assemble.h"

MainGUI::MainGUI(std::string world_string)
          : bf(NULL) {
  QGroupBox *groupBox = new QGroupBox("select world");
  radio1 = new QRadioButton(tr("World 1"));
  radio2 = new QRadioButton(tr("World 2"));
  radio3 = new QRadioButton(tr("World 3"));
  radio4 = new QRadioButton(tr("World 4"));
  radio5 = new QRadioButton(tr("World 5"));
  QRadioButton* radio6 = new QRadioButton(tr("custom"));
  custom_world = new QLineEdit;
  radio1->setEnabled(nbt::exist_world(1));
  radio2->setEnabled(nbt::exist_world(2));
  radio3->setEnabled(nbt::exist_world(3));
  radio4->setEnabled(nbt::exist_world(4));
  radio5->setEnabled(nbt::exist_world(5));
  QVBoxLayout *vbox = new QVBoxLayout;
  vbox->addWidget(radio1);
  vbox->addWidget(radio2);
  vbox->addWidget(radio3);
  vbox->addWidget(radio4);
  vbox->addWidget(radio5);
  vbox->addWidget(radio6);
  groupBox->setLayout(vbox);
  custom_world->setMaximumWidth(groupBox->sizeHint().width());
  custom_world->setEnabled(false);
  vbox->addWidget(custom_world);
  connect(radio6, SIGNAL(toggled(bool)), custom_world, SLOT(setEnabled(bool)));
  connect(radio6, SIGNAL(clicked()), this, SLOT(load_custom_world()));

  QGroupBox* renderBox = new QGroupBox("render mode");
  QRadioButton* render1 = new QRadioButton("top down");
  QRadioButton* render2 = new QRadioButton("oblique");
  QRadioButton* render3 = new QRadioButton("isometric");
  render1->setChecked(true);
  QVBoxLayout *vbox_render = new QVBoxLayout;
  vbox_render->addWidget(render1);
  vbox_render->addWidget(render2);
  vbox_render->addWidget(render3);
  renderBox->setLayout(vbox_render);
  QSignalMapper* render_mapper = new QSignalMapper(this);
  connect(render1, SIGNAL(clicked()), render_mapper, SLOT(map()));
  connect(render2, SIGNAL(clicked()), render_mapper, SLOT(map()));
  connect(render3, SIGNAL(clicked()), render_mapper, SLOT(map()));
  render_mapper->setMapping(render1, 0);
  render_mapper->setMapping(render2, 1);
  render_mapper->setMapping(render3, 2);
  connect(render_mapper, SIGNAL(mapped(int)), this, SLOT(set_render_mode(int)));

  QGroupBox* shadowBox = new QGroupBox("shadow quality");
  QRadioButton* shadow1 = new QRadioButton("normal");
  QRadioButton* shadow2 = new QRadioButton("high");
  QRadioButton* shadow3 = new QRadioButton("ultra");
  shadow1->setChecked(true);
  QVBoxLayout *vbox_shadow = new QVBoxLayout;
  vbox_shadow->addWidget(shadow1);
  vbox_shadow->addWidget(shadow2);
  vbox_shadow->addWidget(shadow3);
  shadowBox->setLayout(vbox_shadow);
  QSignalMapper* shadow_mapper = new QSignalMapper(this);
  connect(shadow1, SIGNAL(clicked()), shadow_mapper, SLOT(map()));
  connect(shadow2, SIGNAL(clicked()), shadow_mapper, SLOT(map()));
  connect(shadow3, SIGNAL(clicked()), shadow_mapper, SLOT(map()));
  shadow_mapper->setMapping(shadow1, 0);
  shadow_mapper->setMapping(shadow2, 1);
  shadow_mapper->setMapping(shadow3, 2);
  connect(shadow_mapper, SIGNAL(mapped(int)), this, SLOT(set_shadow_quality(int)));

  QGroupBox *lightBox = new QGroupBox("sun direction");
  QRadioButton* light0 = new QRadioButton();
  QRadioButton* light1 = new QRadioButton();
  QRadioButton* light2 = new QRadioButton();
  QRadioButton* light3 = new QRadioButton();
  QRadioButton* light4 = new QRadioButton();
  QRadioButton* light5 = new QRadioButton();
  QRadioButton* light6 = new QRadioButton();
  QRadioButton* light7 = new QRadioButton();
  QGridLayout *light_grid = new QGridLayout;
  light_grid->addWidget(light0, 0, 0);
  light_grid->addWidget(light1, 1, 0);
  light_grid->addWidget(light2, 2, 0);
  light_grid->addWidget(light3, 2, 1);
  light_grid->addWidget(light4, 2, 2);
  light_grid->addWidget(light5, 1, 2);
  light_grid->addWidget(light6, 0, 2);
  light_grid->addWidget(light7, 0, 1);
  lightBox->setLayout(light_grid);
  QSignalMapper* light_mapper = new QSignalMapper(this);
  connect(light0, SIGNAL(clicked()), light_mapper, SLOT(map()));
  connect(light1, SIGNAL(clicked()), light_mapper, SLOT(map()));
  connect(light2, SIGNAL(clicked()), light_mapper, SLOT(map()));
  connect(light3, SIGNAL(clicked()), light_mapper, SLOT(map()));
  connect(light4, SIGNAL(clicked()), light_mapper, SLOT(map()));
  connect(light5, SIGNAL(clicked()), light_mapper, SLOT(map()));
  connect(light6, SIGNAL(clicked()), light_mapper, SLOT(map()));
  connect(light7, SIGNAL(clicked()), light_mapper, SLOT(map()));
  light_mapper->setMapping(light0, 0);
  light_mapper->setMapping(light1, 1);
  light_mapper->setMapping(light2, 2);
  light_mapper->setMapping(light3, 3);
  light_mapper->setMapping(light4, 4);
  light_mapper->setMapping(light5, 5);
  light_mapper->setMapping(light6, 6);
  light_mapper->setMapping(light7, 7);
  connect(light_mapper, SIGNAL(mapped(int)), this, SLOT(set_sun_direction(int)));
  light0->click();

  QGroupBox *rotateBox = new QGroupBox("rotation");
  QRadioButton* rotate0 = new QRadioButton();
  QRadioButton* rotate1 = new QRadioButton();
  QRadioButton* rotate2 = new QRadioButton();
  QRadioButton* rotate3 = new QRadioButton();
  QGridLayout *rotate_grid = new QGridLayout;
  rotate_grid->addWidget(rotate0, 0, 1);
  rotate_grid->addWidget(rotate1, 1, 0);
  rotate_grid->addWidget(rotate2, 2, 1);
  rotate_grid->addWidget(rotate3, 1, 2);
  rotateBox->setLayout(rotate_grid);
  QSignalMapper* rotate_mapper = new QSignalMapper(this);
  connect(rotate0, SIGNAL(clicked()), rotate_mapper, SLOT(map()));
  connect(rotate1, SIGNAL(clicked()), rotate_mapper, SLOT(map()));
  connect(rotate2, SIGNAL(clicked()), rotate_mapper, SLOT(map()));
  connect(rotate3, SIGNAL(clicked()), rotate_mapper, SLOT(map()));
  rotate_mapper->setMapping(rotate0, 1);
  rotate_mapper->setMapping(rotate1, 0);
  rotate_mapper->setMapping(rotate2, 3);
  rotate_mapper->setMapping(rotate3, 2);
  connect(rotate_mapper, SIGNAL(mapped(int)), this, SLOT(set_rotate(int)));
  rotate0->click();

  QSpinBox* relief_strength = new QSpinBox(this);
  connect(relief_strength, SIGNAL(valueChanged(int)), this, SLOT(set_relief_strength(int)));
  relief_strength->setValue(10);
  QSpinBox* shadow_strength = new QSpinBox(this);
  connect(shadow_strength, SIGNAL(valueChanged(int)), this, SLOT(set_shadow_strength(int)));
  shadow_strength->setValue(60);
  QLabel* relief_label = new QLabel("relief strength:");
  QLabel* shadow_label = new QLabel("shadow strength:");

  QBoxLayout* global = new QHBoxLayout(this);
  QScrollArea* left_scroll_area = new QScrollArea;
  left_scroll_area->setFrameStyle(QFrame::NoFrame | QFrame::Plain);
  left_scroll_area->setLineWidth(0);
  QBoxLayout* left_side = new QVBoxLayout;
  left_side->addWidget(groupBox);
  left_side->addWidget(renderBox);
  left_side->addWidget(relief_label);
  left_side->addWidget(relief_strength);
  left_side->addWidget(shadow_label);
  left_side->addWidget(shadow_strength);
  left_side->addWidget(shadowBox);
  left_side->addWidget(lightBox);
  left_side->addWidget(rotateBox);
  QCheckBox* night_mode_box = new QCheckBox("night mode");
  left_side->addWidget(night_mode_box);
  connect(night_mode_box, SIGNAL(stateChanged(int)), this, SLOT(set_night_mode(int)));
  left_side->addStretch(1);
  QWidget* left_widget = new QWidget;
  left_widget->setLayout(left_side);
  left_scroll_area->setWidget(left_widget);
  QVBoxLayout* left_side_all = new QVBoxLayout;
  left_side_all->addWidget(left_scroll_area);
  start_button = new QPushButton("Start rendering", this);
  left_side_all->addWidget(start_button);
  left_side_all->setContentsMargins(0, 0, 0, 0);
  QWidget* left_side_all_widget = new QWidget;
  left_side_all_widget->setLayout(left_side_all);
  left_side_all_widget->setFixedWidth(left_side_all_widget->sizeHint().width()
                                    + left_scroll_area->verticalScrollBar()
                                                      ->sizeHint().width() + 3);
  global->addWidget(left_side_all_widget);

  mf = new MainForm(&scene, bf);
  global->addWidget(mf);

  connect(start_button, SIGNAL(clicked()), this, SLOT(set_new_world()));
  connect(&new_world_setup_watcher, SIGNAL(finished()), this, SLOT(toggle_rendering()));
  connect(&watcher, SIGNAL(finished()), this, SLOT(handle_finished()));
}

void MainGUI::set_relief_strength(int value) {
  set.relief = set.relief_strength = value;
}

void MainGUI::set_shadow_strength(int value) {
  set.shadow = set.shadow_strength = value;
}

void MainGUI::set_sun_direction(int value) {
  value = (value + 1) % 8;
  set.sun_direction = value;
}

void MainGUI::set_render_mode(int value) {
  if (value == 0) {
    set.topview = true;
    set.oblique = false;
    set.isometric = false;
  } else if (value == 1) {
    set.topview = false;
    set.oblique = true;
    set.isometric = false;
  } else if (value == 2) {
    set.topview = false;
    set.oblique = false;
    set.isometric = true;
  }
}

void MainGUI::set_rotate(int value) {
  set.rotate = value;
}

void MainGUI::set_night_mode(int value) {
  set.nightmode = value;
}

void MainGUI::set_shadow_quality(int value) {
  if (value == 0) {
    set.shadow_quality = false;
    set.shadow_quality_ultra = false;
  } else if (value == 1) {
    set.shadow_quality = true;
    set.shadow_quality_ultra = false;
  } else if (value == 2) {
    set.shadow_quality = true;
    set.shadow_quality_ultra = true;
  }
}

void MainGUI::load_custom_world() {
  QString dir = QFileDialog::getExistingDirectory(this, tr("Open world"),
                                                 QString(),
                                                 QFileDialog::ShowDirsOnly);
  if (dir != QString()) {
    custom_world->setText(dir);
  }
}

int MainGUI::current_world() {
  if (radio1->isChecked()) {
    return 1;
  } else if (radio2->isChecked()) {
    return 2;
  } else if (radio3->isChecked()) {
    return 3;
  } else if (radio4->isChecked()) {
    return 4;
  } else if (radio5->isChecked()) {
    return 5;
  } else {
    return 0;
  }
}

void MainGUI::new_bf() {
  if (!current_world()) {
    bf = new nbt(custom_world->text().toStdString());
  } else {
    bf = new nbt(current_world());
  }
}

void MainGUI::set_new_world() {
  if (start_button->text() == "Start rendering") {
    if (bf) {
      delete bf;
      bf = NULL;
    }
    if (!current_world() && custom_world->text() == QString()) return;
    start_button->setText("Loading world...");
    start_button->setEnabled(false);
    new_world_setup = QFuture<void>(QtConcurrent::run(this, &MainGUI::new_bf));
    new_world_setup_watcher.setFuture(new_world_setup);
  } else {
    mf->StopPopulateScene();
    start_button->setEnabled(false);
  }
}

void MainGUI::toggle_rendering() {
  if (bf->bad_world) {
    handle_finished();
    return;
  }
  std::cout << bf->string();
  bf->setSettings(set);
  mf->set_nbt(bf);
  scene.clear();

  start_button->setText("Abort rendering");
  start_button->setEnabled(true);
  worker = QFuture<void>(QtConcurrent::run(mf, &MainForm::populateScene));
  watcher.setFuture(worker);
}

void MainGUI::handle_finished() {
  start_button->setText("Start rendering");
  start_button->setEnabled(true);
}
<commit_msg>reorder widgets<commit_after>#include "MainGUI.moc"

#include <cstdlib>
#include <QPushButton>

#include "../assemble.h"

MainGUI::MainGUI(std::string world_string)
          : bf(NULL) {
  QGroupBox *groupBox = new QGroupBox("select world");
  radio1 = new QRadioButton(tr("World 1"));
  radio2 = new QRadioButton(tr("World 2"));
  radio3 = new QRadioButton(tr("World 3"));
  radio4 = new QRadioButton(tr("World 4"));
  radio5 = new QRadioButton(tr("World 5"));
  QRadioButton* radio6 = new QRadioButton(tr("custom"));
  custom_world = new QLineEdit;
  radio1->setEnabled(nbt::exist_world(1));
  radio2->setEnabled(nbt::exist_world(2));
  radio3->setEnabled(nbt::exist_world(3));
  radio4->setEnabled(nbt::exist_world(4));
  radio5->setEnabled(nbt::exist_world(5));
  QVBoxLayout *vbox = new QVBoxLayout;
  vbox->addWidget(radio1);
  vbox->addWidget(radio2);
  vbox->addWidget(radio3);
  vbox->addWidget(radio4);
  vbox->addWidget(radio5);
  vbox->addWidget(radio6);
  groupBox->setLayout(vbox);
  custom_world->setMaximumWidth(groupBox->sizeHint().width());
  custom_world->setEnabled(false);
  vbox->addWidget(custom_world);
  connect(radio6, SIGNAL(toggled(bool)), custom_world, SLOT(setEnabled(bool)));
  connect(radio6, SIGNAL(clicked()), this, SLOT(load_custom_world()));

  QGroupBox* renderBox = new QGroupBox("render mode");
  QRadioButton* render1 = new QRadioButton("top down");
  QRadioButton* render2 = new QRadioButton("oblique");
  QRadioButton* render3 = new QRadioButton("isometric");
  render1->setChecked(true);
  QVBoxLayout *vbox_render = new QVBoxLayout;
  vbox_render->addWidget(render1);
  vbox_render->addWidget(render2);
  vbox_render->addWidget(render3);
  renderBox->setLayout(vbox_render);
  QSignalMapper* render_mapper = new QSignalMapper(this);
  connect(render1, SIGNAL(clicked()), render_mapper, SLOT(map()));
  connect(render2, SIGNAL(clicked()), render_mapper, SLOT(map()));
  connect(render3, SIGNAL(clicked()), render_mapper, SLOT(map()));
  render_mapper->setMapping(render1, 0);
  render_mapper->setMapping(render2, 1);
  render_mapper->setMapping(render3, 2);
  connect(render_mapper, SIGNAL(mapped(int)), this, SLOT(set_render_mode(int)));

  QGroupBox* shadowBox = new QGroupBox("shadow quality");
  QRadioButton* shadow1 = new QRadioButton("normal");
  QRadioButton* shadow2 = new QRadioButton("high");
  QRadioButton* shadow3 = new QRadioButton("ultra");
  shadow1->setChecked(true);
  QVBoxLayout *vbox_shadow = new QVBoxLayout;
  vbox_shadow->addWidget(shadow1);
  vbox_shadow->addWidget(shadow2);
  vbox_shadow->addWidget(shadow3);
  shadowBox->setLayout(vbox_shadow);
  QSignalMapper* shadow_mapper = new QSignalMapper(this);
  connect(shadow1, SIGNAL(clicked()), shadow_mapper, SLOT(map()));
  connect(shadow2, SIGNAL(clicked()), shadow_mapper, SLOT(map()));
  connect(shadow3, SIGNAL(clicked()), shadow_mapper, SLOT(map()));
  shadow_mapper->setMapping(shadow1, 0);
  shadow_mapper->setMapping(shadow2, 1);
  shadow_mapper->setMapping(shadow3, 2);
  connect(shadow_mapper, SIGNAL(mapped(int)), this, SLOT(set_shadow_quality(int)));

  QGroupBox *lightBox = new QGroupBox("sun direction");
  QRadioButton* light0 = new QRadioButton();
  QRadioButton* light1 = new QRadioButton();
  QRadioButton* light2 = new QRadioButton();
  QRadioButton* light3 = new QRadioButton();
  QRadioButton* light4 = new QRadioButton();
  QRadioButton* light5 = new QRadioButton();
  QRadioButton* light6 = new QRadioButton();
  QRadioButton* light7 = new QRadioButton();
  QGridLayout *light_grid = new QGridLayout;
  light_grid->addWidget(light0, 0, 0);
  light_grid->addWidget(light1, 1, 0);
  light_grid->addWidget(light2, 2, 0);
  light_grid->addWidget(light3, 2, 1);
  light_grid->addWidget(light4, 2, 2);
  light_grid->addWidget(light5, 1, 2);
  light_grid->addWidget(light6, 0, 2);
  light_grid->addWidget(light7, 0, 1);
  lightBox->setLayout(light_grid);
  QSignalMapper* light_mapper = new QSignalMapper(this);
  connect(light0, SIGNAL(clicked()), light_mapper, SLOT(map()));
  connect(light1, SIGNAL(clicked()), light_mapper, SLOT(map()));
  connect(light2, SIGNAL(clicked()), light_mapper, SLOT(map()));
  connect(light3, SIGNAL(clicked()), light_mapper, SLOT(map()));
  connect(light4, SIGNAL(clicked()), light_mapper, SLOT(map()));
  connect(light5, SIGNAL(clicked()), light_mapper, SLOT(map()));
  connect(light6, SIGNAL(clicked()), light_mapper, SLOT(map()));
  connect(light7, SIGNAL(clicked()), light_mapper, SLOT(map()));
  light_mapper->setMapping(light0, 0);
  light_mapper->setMapping(light1, 1);
  light_mapper->setMapping(light2, 2);
  light_mapper->setMapping(light3, 3);
  light_mapper->setMapping(light4, 4);
  light_mapper->setMapping(light5, 5);
  light_mapper->setMapping(light6, 6);
  light_mapper->setMapping(light7, 7);
  connect(light_mapper, SIGNAL(mapped(int)), this, SLOT(set_sun_direction(int)));
  light0->click();

  QGroupBox *rotateBox = new QGroupBox("rotation");
  QRadioButton* rotate0 = new QRadioButton();
  QRadioButton* rotate1 = new QRadioButton();
  QRadioButton* rotate2 = new QRadioButton();
  QRadioButton* rotate3 = new QRadioButton();
  QGridLayout *rotate_grid = new QGridLayout;
  rotate_grid->addWidget(rotate0, 0, 1);
  rotate_grid->addWidget(rotate1, 1, 0);
  rotate_grid->addWidget(rotate2, 2, 1);
  rotate_grid->addWidget(rotate3, 1, 2);
  rotateBox->setLayout(rotate_grid);
  QSignalMapper* rotate_mapper = new QSignalMapper(this);
  connect(rotate0, SIGNAL(clicked()), rotate_mapper, SLOT(map()));
  connect(rotate1, SIGNAL(clicked()), rotate_mapper, SLOT(map()));
  connect(rotate2, SIGNAL(clicked()), rotate_mapper, SLOT(map()));
  connect(rotate3, SIGNAL(clicked()), rotate_mapper, SLOT(map()));
  rotate_mapper->setMapping(rotate0, 1);
  rotate_mapper->setMapping(rotate1, 0);
  rotate_mapper->setMapping(rotate2, 3);
  rotate_mapper->setMapping(rotate3, 2);
  connect(rotate_mapper, SIGNAL(mapped(int)), this, SLOT(set_rotate(int)));
  rotate0->click();

  QSpinBox* relief_strength = new QSpinBox(this);
  connect(relief_strength, SIGNAL(valueChanged(int)), this, SLOT(set_relief_strength(int)));
  relief_strength->setValue(10);
  QSpinBox* shadow_strength = new QSpinBox(this);
  connect(shadow_strength, SIGNAL(valueChanged(int)), this, SLOT(set_shadow_strength(int)));
  shadow_strength->setValue(60);
  QLabel* relief_label = new QLabel("relief strength:");
  QLabel* shadow_label = new QLabel("shadow strength:");

  QBoxLayout* global = new QHBoxLayout(this);
  QScrollArea* left_scroll_area = new QScrollArea;
  left_scroll_area->setFrameStyle(QFrame::NoFrame | QFrame::Plain);
  left_scroll_area->setLineWidth(0);
  QBoxLayout* left_side = new QVBoxLayout;
  left_side->addWidget(groupBox);
  left_side->addWidget(renderBox);
  left_side->addWidget(shadowBox);
  left_side->addWidget(shadow_label);
  left_side->addWidget(shadow_strength);
  left_side->addWidget(relief_label);
  left_side->addWidget(relief_strength);
  left_side->addWidget(lightBox);
  left_side->addWidget(rotateBox);
  QCheckBox* night_mode_box = new QCheckBox("night mode");
  left_side->addWidget(night_mode_box);
  connect(night_mode_box, SIGNAL(stateChanged(int)), this, SLOT(set_night_mode(int)));
  left_side->addStretch(1);
  QWidget* left_widget = new QWidget;
  left_widget->setLayout(left_side);
  left_scroll_area->setWidget(left_widget);
  QVBoxLayout* left_side_all = new QVBoxLayout;
  left_side_all->addWidget(left_scroll_area);
  start_button = new QPushButton("Start rendering", this);
  left_side_all->addWidget(start_button);
  left_side_all->setContentsMargins(0, 0, 0, 0);
  QWidget* left_side_all_widget = new QWidget;
  left_side_all_widget->setLayout(left_side_all);
  left_side_all_widget->setFixedWidth(left_side_all_widget->sizeHint().width()
                                    + left_scroll_area->verticalScrollBar()
                                                      ->sizeHint().width() + 3);
  global->addWidget(left_side_all_widget);

  mf = new MainForm(&scene, bf);
  global->addWidget(mf);

  connect(start_button, SIGNAL(clicked()), this, SLOT(set_new_world()));
  connect(&new_world_setup_watcher, SIGNAL(finished()), this, SLOT(toggle_rendering()));
  connect(&watcher, SIGNAL(finished()), this, SLOT(handle_finished()));
}

void MainGUI::set_relief_strength(int value) {
  set.relief = set.relief_strength = value;
}

void MainGUI::set_shadow_strength(int value) {
  set.shadow = set.shadow_strength = value;
}

void MainGUI::set_sun_direction(int value) {
  value = (value + 1) % 8;
  set.sun_direction = value;
}

void MainGUI::set_render_mode(int value) {
  if (value == 0) {
    set.topview = true;
    set.oblique = false;
    set.isometric = false;
  } else if (value == 1) {
    set.topview = false;
    set.oblique = true;
    set.isometric = false;
  } else if (value == 2) {
    set.topview = false;
    set.oblique = false;
    set.isometric = true;
  }
}

void MainGUI::set_rotate(int value) {
  set.rotate = value;
}

void MainGUI::set_night_mode(int value) {
  set.nightmode = value;
}

void MainGUI::set_shadow_quality(int value) {
  if (value == 0) {
    set.shadow_quality = false;
    set.shadow_quality_ultra = false;
  } else if (value == 1) {
    set.shadow_quality = true;
    set.shadow_quality_ultra = false;
  } else if (value == 2) {
    set.shadow_quality = true;
    set.shadow_quality_ultra = true;
  }
}

void MainGUI::load_custom_world() {
  QString dir = QFileDialog::getExistingDirectory(this, tr("Open world"),
                                                 QString(),
                                                 QFileDialog::ShowDirsOnly);
  if (dir != QString()) {
    custom_world->setText(dir);
  }
}

int MainGUI::current_world() {
  if (radio1->isChecked()) {
    return 1;
  } else if (radio2->isChecked()) {
    return 2;
  } else if (radio3->isChecked()) {
    return 3;
  } else if (radio4->isChecked()) {
    return 4;
  } else if (radio5->isChecked()) {
    return 5;
  } else {
    return 0;
  }
}

void MainGUI::new_bf() {
  if (!current_world()) {
    bf = new nbt(custom_world->text().toStdString());
  } else {
    bf = new nbt(current_world());
  }
}

void MainGUI::set_new_world() {
  if (start_button->text() == "Start rendering") {
    if (bf) {
      delete bf;
      bf = NULL;
    }
    if (!current_world() && custom_world->text() == QString()) return;
    start_button->setText("Loading world...");
    start_button->setEnabled(false);
    new_world_setup = QFuture<void>(QtConcurrent::run(this, &MainGUI::new_bf));
    new_world_setup_watcher.setFuture(new_world_setup);
  } else {
    mf->StopPopulateScene();
    start_button->setEnabled(false);
  }
}

void MainGUI::toggle_rendering() {
  if (bf->bad_world) {
    handle_finished();
    return;
  }
  std::cout << bf->string();
  bf->setSettings(set);
  mf->set_nbt(bf);
  scene.clear();

  start_button->setText("Abort rendering");
  start_button->setEnabled(true);
  worker = QFuture<void>(QtConcurrent::run(mf, &MainForm::populateScene));
  watcher.setFuture(worker);
}

void MainGUI::handle_finished() {
  start_button->setText("Start rendering");
  start_button->setEnabled(true);
}
<|endoftext|>


<commit_before>#include "TalisScene.h"

#include <Fractal\include\graphics\Vertex.h>
#include <Fractal\include\helpers\Singleton.h>
#include <Fractal\include\scene\SceneManager.h>
#include <Fractal\include\core\systems\Input.h>
#include <Fractal\include\graphics\Mesh.h>
#include <Fractal\include\scene\components\MeshComponent.h>

#include <Fractal\include\scene\components\TerrainComponent.h>
#include <Fractal\include\scene\components\TransformComponent.h>
#include <Fractal\include\scene\components\PhysicsBodyComponent.h>
#include <Fractal\include\scene\components\PhysicsShapeComponent.h>

#include <FractalPhysics\include\shapes\PhysicsBox.h>
#include <Fractal\include\utils\LoadOBJ.h>
#include <Fractal\include\core\systems\manager\SystemManager.h>

TalisScene::TalisScene():
Scene("TalisScene"), test1(nullptr)
{
}

TalisScene::~TalisScene()
{
}

bool TalisScene::initialize() {
	using namespace fractal;
	using namespace fscene;
	using namespace fmath;
	using namespace fgraphics;
	terrain = new SceneObject("terrain");

	terrain->addComponent(new TerrainComponent());

	addGameObject(terrain);
	test1 = new SceneObject("test1");
	test1->addComponent(new MeshComponent(LoadOBJ::load("meshes/dragon")));
	test1->addComponent(new fphysics::PhysicsBodyComponent(new fphysics::PhysicsBody()));
	test1->getComponent<fphysics::PhysicsBodyComponent>()->SetAngularVelocity(Vector3(1.0f, 0.0f, 0.0f));
	test1->getComponent<fphysics::PhysicsBodyComponent>()->SetGravityScale(0.0f);
	camera = new FreeCamera("MainCamera");
	//camera->addComponent(new MeshComponent(LoadOBJ::load("cyl")));
	addGameObject(test1);
	addGameObject(camera);
	return Scene::initialize();
}

void TalisScene::update() {

	using namespace fractal;
	using namespace fscene;
	using namespace fmath;
	using namespace fgraphics;
	Scene::update();
}

bool TalisScene::shutdown() {
	return Scene::shutdown();
}

void TalisScene::setupInput(fractal::fcore::Input * input)
{
	camera->setupInput(input);
}
<commit_msg>name of the object changed<commit_after>#include "TalisScene.h"

#include <Fractal\include\graphics\Vertex.h>
#include <Fractal\include\helpers\Singleton.h>
#include <Fractal\include\scene\SceneManager.h>
#include <Fractal\include\core\systems\Input.h>
#include <Fractal\include\graphics\Mesh.h>
#include <Fractal\include\scene\components\MeshComponent.h>

#include <Fractal\include\scene\components\TerrainComponent.h>
#include <Fractal\include\scene\components\TransformComponent.h>
#include <Fractal\include\scene\components\PhysicsBodyComponent.h>
#include <Fractal\include\scene\components\PhysicsShapeComponent.h>

#include <FractalPhysics\include\shapes\PhysicsBox.h>
#include <Fractal\include\utils\LoadOBJ.h>
#include <Fractal\include\core\systems\manager\SystemManager.h>

TalisScene::TalisScene():
Scene("TalisScene"), test1(nullptr)
{
}

TalisScene::~TalisScene()
{
}

bool TalisScene::initialize() {
	using namespace fractal;
	using namespace fscene;
	using namespace fmath;
	using namespace fgraphics;
	terrain = new SceneObject("terrain");

	terrain->addComponent(new TerrainComponent());

	addGameObject(terrain);
	test1 = new SceneObject("test1");
	test1->addComponent(new MeshComponent(LoadOBJ::load("meshes/cyl")));
	test1->addComponent(new fphysics::PhysicsBodyComponent(new fphysics::PhysicsBody()));
	test1->getComponent<fphysics::PhysicsBodyComponent>()->SetAngularVelocity(Vector3(1.0f, 0.0f, 0.0f));
	test1->getComponent<fphysics::PhysicsBodyComponent>()->SetGravityScale(0.0f);
	camera = new FreeCamera("MainCamera");
	//camera->addComponent(new MeshComponent(LoadOBJ::load("cyl")));
	addGameObject(test1);
	addGameObject(camera);
	return Scene::initialize();
}

void TalisScene::update() {

	using namespace fractal;
	using namespace fscene;
	using namespace fmath;
	using namespace fgraphics;
	Scene::update();
}

bool TalisScene::shutdown() {
	return Scene::shutdown();
}

void TalisScene::setupInput(fractal::fcore::Input * input)
{
	camera->setupInput(input);
}
<|endoftext|>


<commit_before>//=================================================================================================
//                    Copyright (C) 2017 Olivier Mallet - All Rights Reserved
//=================================================================================================

#ifndef GENETICALGORITHM_HPP
#define GENETICALGORITHM_HPP

namespace galgo {

//=================================================================================================

template <typename T, int N = 16>
class GeneticAlgorithm
{
   static_assert(std::is_same<float,T>::value || std::is_same<double,T>::value, "variable type can only be float or double, please amend.");
   static_assert(N > 0 && N <= 64, "number of bits cannot be ouside interval [1,64], please choose an integer within this interval.");

   template <typename K, int S>
   friend class Population;
   template <typename K, int S>
   friend class Chromosome;

   template <typename K>
   using Func = std::vector<K> (*)(const std::vector<K>&);

private:
   Population<T,N> pop;       // population of chromosomes

public:
   std::vector<T> lowerBound; // parameter(s) lower bound
   std::vector<T> upperBound; // parameter(s) upper bound
   std::vector<T> initialSet; // initial set of parameter(s)

private:
   mutable std::uniform_int_distribution<uint64_t> udistrib;  // generate uniform random unsigned long long integers
   static constexpr uint64_t MAXVAL = MAXVALUE<N>::value - 1; // maximum unsigned integral value obtained from N bits, evaluated at compile time

public:
   // objective function pointer
   Func<T> Objective;
   // selection method functor initialized to roulette wheel selection
   void (*Selection)(Population<T,N>&) = RWS;
   // cross-over method functor initialized to 1-point cross-over
   void (*CrossOver)(const Population<T,N>&, CHR<T,N>&, CHR<T,N>&) = P1XO;
   // mutation method functor initialized to single-point mutation
   void (*Mutation)(CHR<T,N>&) = SPM;
   // adaptation to constraint(s) method
   void (*Adaptation)(Population<T,N>&) = nullptr;
   // constraint(s)
   std::vector<T> (*Constraint)(const std::vector<T>&) = nullptr;

   T covrate = .50;   // cross-over rate
   T mutrate = .05;   // mutation rate
   T SP = 1.5;        // selective pressure for RSP selection method
   T tolerance = 0.0; // terminal condition (inactive if equal to zero)

   int elitpop = 1;   // elit population size
   int matsize;       // mating pool size, set to popsize by default
   int tntsize = 10;  // tournament size
   int genstep = 10;  // generation step for outputting results
   int precision = 5; // precision for outputting results

   // constructor
   GeneticAlgorithm(Func<T> objective, int popsize, const std::vector<T>& lowerBound, const std::vector<T>& upperBound, int nbgen, bool output = false);
   // run genetic algorithm
   void run();
   // return best chromosome
   const CHR<T,N>& result() const;

private:
   int nbgen;     // number of generations
   int nogen = 0; // numero of generation
   int nbparam;   // number of parameters to be estimated
   int popsize;   // population size
   bool output;   // control if results must be outputted

   // check inputs validity
   bool check() const ;
   // print results for each new generation
   void print() const;
};

/*-------------------------------------------------------------------------------------------------*/

// constructor
template <typename T, int N>
GeneticAlgorithm<T,N>::GeneticAlgorithm(Func<T> objective, int popsize, const std::vector<T>& lowerBound, const std::vector<T>& upperBound, int nbgen, bool output)
{
   this->Objective = objective;
   this->nbparam = upperBound.size();
   this->popsize = popsize;
   this->matsize = popsize;
   this->lowerBound = lowerBound;
   this->upperBound = upperBound;
   this->nbgen = nbgen;
   this->output = output;
   // initializing uniform distribution generating random unsigned integers
   udistrib = std::uniform_int_distribution<uint64_t>(0, MAXVAL);
}

/*-------------------------------------------------------------------------------------------------*/

// check inputs validity
template <typename T, int N>
bool GeneticAlgorithm<T,N>::check() const
{
   if (!initialSet.empty()) {
      for (int i = 0; i < nbparam; ++i) {
         if (initialSet[i] < lowerBound[i] || initialSet[i] > upperBound[i]) {
            std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, initial set of parameters (initialSet) cannot be outside [lowerBound,upperBound], please choose a set within these boundaries.\n";
            return false;
         }
      }
      if (initialSet.size() != (unsigned)nbparam) {
         std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, initial set of parameters (initialSet) does not have the same dimension than the number of parameters, please adjust.\n";
         return false;
      }
   }
   if (lowerBound.size() != upperBound.size()) {
      std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, lower bound (lowerBound) and upper bound (upperBound) must be of same dimension, please adjust.\n";
      return false;
   }
   for (int i = 0; i < nbparam; ++i) {
      if (lowerBound[i] >= upperBound[i]) {
         std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, lower bound (lowerBound) cannot be equal or greater than upper bound (upperBound), please amend.\n";
         return false;
      }
   }
   if (SP < 1.0 || SP > 2.0) {
      std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, selective pressure (SP) cannot be outside [1.0,2.0], please choose a real value within this interval.\n";
      return false;
   }
   if (elitpop > popsize || elitpop < 0) {
      std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, elit population (elitpop) cannot outside [0,popsize], please choose an integral value within this interval.\n";
      return false;
   }
   if (covrate < 0.0 || covrate > 1.0) {
      std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, cross-over rate (covrate) cannot outside [0.0,1.0], please choose a real value within this interval.\n";
      return false;
   }
   if (genstep <= 0) {
      std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, generation step (genstep) cannot be <= 0, please choose an integral value > 0.\n";
      return false;
   }
   return true;
}

/*-------------------------------------------------------------------------------------------------*/

// run genetic algorithm
template <typename T, int N>
void GeneticAlgorithm<T,N>::run()
{
   // checking inputs validity
   if (!check()) {
      return;
   }

   // setting adaptation method to default if needed
   if (Constraint != nullptr && Adaptation == nullptr) {
      Adaptation = DAC;
   }

   // initializing population
   pop = Population<T,N>(*this);

   if (output) {
      std::cout << "\n Running Genetic Algorithm...\n";
      std::cout << " ----------------------------\n";
   }

   // creating population
   pop.creation();
   // initializing best result and previous best result
   T bestResult = pop(0)->getTotal();
   T prevBestResult = bestResult;
   // outputting results
   if (output) print();

   // starting population evolution
   for (nogen = 1; nogen <= nbgen; ++nogen) {
      // evolving population
      pop.evolution();
      // getting best current result
      bestResult = pop(0)->getTotal();
      // outputting results
      if (output) print();
      // checking convergence
      if (tolerance != 0.0) {
         if (fabs(bestResult - prevBestResult) < fabs(tolerance)) {
            break;
         }
         prevBestResult = bestResult;
      }
   }

   // outputting contraint value
   if (Constraint != nullptr) {
      // getting best parameter(s) constraint value(s)
      std::vector<T> cst = pop(0)->getConstraint();
      if (output) {
         std::cout << "\n Constraint(s)\n";
         std::cout << " -------------\n";
         for (unsigned i = 0; i < cst.size(); ++i) {
            std::cout << " C";
            if (nbparam > 1) {
               std::cout << std::to_string(i + 1);
            }
            std::cout << "(x) = " << std::setw(6) << std::fixed << std::setprecision(precision) << cst[i] << "\n";
         }
         std::cout << "\n";
      }
   }
}

/*-------------------------------------------------------------------------------------------------*/

// return best chromosome
template <typename T, int N>
inline const CHR<T,N>& GeneticAlgorithm<T,N>::result() const
{
   return pop(0);
}

/*-------------------------------------------------------------------------------------------------*/

// print results for each new generation
template <typename T, int N>
void GeneticAlgorithm<T,N>::print() const
{
   // getting best parameter(s) from best chromosome
   std::vector<T> bestParam = pop(0)->getParam();
   std::vector<T> bestResult = pop(0)->getResult();

   if (nogen % genstep == 0) {
      std::cout << " Generation = " << std::setw(std::to_string(nbgen).size()) << nogen << " |";
      for (int i = 0; i < nbparam; ++i) {
	      std::cout << " X";
         if (nbparam > 1) {
            std::cout << std::to_string(i + 1);
         }
         std::cout << " = "  << std::setw(9) << std::fixed << std::setprecision(precision) << bestParam[i] << " |";
	   }
      for (unsigned i = 0; i < bestResult.size(); ++i) {
	      std::cout << " F";
         if (bestResult.size() > 1) {
            std::cout << std::to_string(i + 1);
         }
         std::cout << "(x) = " << std::setw(12) << std::fixed << std::setprecision(precision) << bestResult[i];
         if (i < bestResult.size() - 1) {
            std::cout << " |";
         } else {
            std::cout << "\n";
         }
	   }

   }
}

//=================================================================================================

}

#endif
<commit_msg>Update GeneticAlgorithm.hpp<commit_after>//=================================================================================================
//                    Copyright (C) 2017 Olivier Mallet - All Rights Reserved
//=================================================================================================

#ifndef GENETICALGORITHM_HPP
#define GENETICALGORITHM_HPP

namespace galgo {

//=================================================================================================

template <typename T, int N = 16>
class GeneticAlgorithm
{
   static_assert(std::is_same<float,T>::value || std::is_same<double,T>::value, "variable type can only be float or double, please amend.");
   static_assert(N > 0 && N <= 64, "number of bits cannot be ouside interval [1,64], please choose an integer within this interval.");

   template <typename K, int S>
   friend class Population;
   template <typename K, int S>
   friend class Chromosome;

   template <typename K>
   using Func = std::vector<K> (*)(const std::vector<K>&);

private:
   Population<T,N> pop;       // population of chromosomes

public:
   std::vector<T> lowerBound; // parameter(s) lower bound
   std::vector<T> upperBound; // parameter(s) upper bound
   std::vector<T> initialSet; // initial set of parameter(s)

private:
   mutable std::uniform_int_distribution<uint64_t> udistrib;  // generate uniform random unsigned long long integers
   static constexpr uint64_t MAXVAL = MAXVALUE<N>::value - 1; // maximum unsigned integral value obtained from N bits, evaluated at compile time

public:
   // objective function pointer
   Func<T> Objective;
   // selection method initialized to roulette wheel selection
   void (*Selection)(Population<T,N>&) = RWS;
   // cross-over method initialized to 1-point cross-over
   void (*CrossOver)(const Population<T,N>&, CHR<T,N>&, CHR<T,N>&) = P1XO;
   // mutation method initialized to single-point mutation
   void (*Mutation)(CHR<T,N>&) = SPM;
   // adaptation to constraint(s) method
   void (*Adaptation)(Population<T,N>&) = nullptr;
   // constraint(s)
   std::vector<T> (*Constraint)(const std::vector<T>&) = nullptr;

   T covrate = .50;   // cross-over rate
   T mutrate = .05;   // mutation rate
   T SP = 1.5;        // selective pressure for RSP selection method
   T tolerance = 0.0; // terminal condition (inactive if equal to zero)

   int elitpop = 1;   // elit population size
   int matsize;       // mating pool size, set to popsize by default
   int tntsize = 10;  // tournament size
   int genstep = 10;  // generation step for outputting results
   int precision = 5; // precision for outputting results

   // constructor
   GeneticAlgorithm(Func<T> objective, int popsize, const std::vector<T>& lowerBound, const std::vector<T>& upperBound, int nbgen, bool output = false);
   // run genetic algorithm
   void run();
   // return best chromosome
   const CHR<T,N>& result() const;

private:
   int nbgen;     // number of generations
   int nogen = 0; // numero of generation
   int nbparam;   // number of parameters to be estimated
   int popsize;   // population size
   bool output;   // control if results must be outputted

   // check inputs validity
   bool check() const ;
   // print results for each new generation
   void print() const;
};

/*-------------------------------------------------------------------------------------------------*/

// constructor
template <typename T, int N>
GeneticAlgorithm<T,N>::GeneticAlgorithm(Func<T> objective, int popsize, const std::vector<T>& lowerBound, const std::vector<T>& upperBound, int nbgen, bool output)
{
   this->Objective = objective;
   this->nbparam = upperBound.size();
   this->popsize = popsize;
   this->matsize = popsize;
   this->lowerBound = lowerBound;
   this->upperBound = upperBound;
   this->nbgen = nbgen;
   this->output = output;
   // initializing uniform distribution generating random unsigned integers
   udistrib = std::uniform_int_distribution<uint64_t>(0, MAXVAL);
}

/*-------------------------------------------------------------------------------------------------*/

// check inputs validity
template <typename T, int N>
bool GeneticAlgorithm<T,N>::check() const
{
   if (!initialSet.empty()) {
      for (int i = 0; i < nbparam; ++i) {
         if (initialSet[i] < lowerBound[i] || initialSet[i] > upperBound[i]) {
            std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, initial set of parameters (initialSet) cannot be outside [lowerBound,upperBound], please choose a set within these boundaries.\n";
            return false;
         }
      }
      if (initialSet.size() != (unsigned)nbparam) {
         std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, initial set of parameters (initialSet) does not have the same dimension than the number of parameters, please adjust.\n";
         return false;
      }
   }
   if (lowerBound.size() != upperBound.size()) {
      std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, lower bound (lowerBound) and upper bound (upperBound) must be of same dimension, please adjust.\n";
      return false;
   }
   for (int i = 0; i < nbparam; ++i) {
      if (lowerBound[i] >= upperBound[i]) {
         std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, lower bound (lowerBound) cannot be equal or greater than upper bound (upperBound), please amend.\n";
         return false;
      }
   }
   if (SP < 1.0 || SP > 2.0) {
      std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, selective pressure (SP) cannot be outside [1.0,2.0], please choose a real value within this interval.\n";
      return false;
   }
   if (elitpop > popsize || elitpop < 0) {
      std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, elit population (elitpop) cannot outside [0,popsize], please choose an integral value within this interval.\n";
      return false;
   }
   if (covrate < 0.0 || covrate > 1.0) {
      std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, cross-over rate (covrate) cannot outside [0.0,1.0], please choose a real value within this interval.\n";
      return false;
   }
   if (genstep <= 0) {
      std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, generation step (genstep) cannot be <= 0, please choose an integral value > 0.\n";
      return false;
   }
   return true;
}

/*-------------------------------------------------------------------------------------------------*/

// run genetic algorithm
template <typename T, int N>
void GeneticAlgorithm<T,N>::run()
{
   // checking inputs validity
   if (!check()) {
      return;
   }

   // setting adaptation method to default if needed
   if (Constraint != nullptr && Adaptation == nullptr) {
      Adaptation = DAC;
   }

   // initializing population
   pop = Population<T,N>(*this);

   if (output) {
      std::cout << "\n Running Genetic Algorithm...\n";
      std::cout << " ----------------------------\n";
   }

   // creating population
   pop.creation();
   // initializing best result and previous best result
   T bestResult = pop(0)->getTotal();
   T prevBestResult = bestResult;
   // outputting results
   if (output) print();

   // starting population evolution
   for (nogen = 1; nogen <= nbgen; ++nogen) {
      // evolving population
      pop.evolution();
      // getting best current result
      bestResult = pop(0)->getTotal();
      // outputting results
      if (output) print();
      // checking convergence
      if (tolerance != 0.0) {
         if (fabs(bestResult - prevBestResult) < fabs(tolerance)) {
            break;
         }
         prevBestResult = bestResult;
      }
   }

   // outputting contraint value
   if (Constraint != nullptr) {
      // getting best parameter(s) constraint value(s)
      std::vector<T> cst = pop(0)->getConstraint();
      if (output) {
         std::cout << "\n Constraint(s)\n";
         std::cout << " -------------\n";
         for (unsigned i = 0; i < cst.size(); ++i) {
            std::cout << " C";
            if (nbparam > 1) {
               std::cout << std::to_string(i + 1);
            }
            std::cout << "(x) = " << std::setw(6) << std::fixed << std::setprecision(precision) << cst[i] << "\n";
         }
         std::cout << "\n";
      }
   }
}

/*-------------------------------------------------------------------------------------------------*/

// return best chromosome
template <typename T, int N>
inline const CHR<T,N>& GeneticAlgorithm<T,N>::result() const
{
   return pop(0);
}

/*-------------------------------------------------------------------------------------------------*/

// print results for each new generation
template <typename T, int N>
void GeneticAlgorithm<T,N>::print() const
{
   // getting best parameter(s) from best chromosome
   std::vector<T> bestParam = pop(0)->getParam();
   std::vector<T> bestResult = pop(0)->getResult();

   if (nogen % genstep == 0) {
      std::cout << " Generation = " << std::setw(std::to_string(nbgen).size()) << nogen << " |";
      for (int i = 0; i < nbparam; ++i) {
	      std::cout << " X";
         if (nbparam > 1) {
            std::cout << std::to_string(i + 1);
         }
         std::cout << " = "  << std::setw(9) << std::fixed << std::setprecision(precision) << bestParam[i] << " |";
	   }
      for (unsigned i = 0; i < bestResult.size(); ++i) {
	      std::cout << " F";
         if (bestResult.size() > 1) {
            std::cout << std::to_string(i + 1);
         }
         std::cout << "(x) = " << std::setw(12) << std::fixed << std::setprecision(precision) << bestResult[i];
         if (i < bestResult.size() - 1) {
            std::cout << " |";
         } else {
            std::cout << "\n";
         }
	   }

   }
}

//=================================================================================================

}

#endif
<|endoftext|>