<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// (c) COPYRIGHT URI/MIT 1997-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
//      jhrg,jimg       James Gallagher <jgallagher@gso.uri.edu>

// This is the source to `getdap'; a simple tool to exercise the Connect
// class. It can be used to get naked URLs as well as the DAP2 DAS and DDS
// objects.  jhrg.

#include "config.h"

#ifdef WIN32
#include <io.h>
#include <fcntl.h>
#endif

#include <cstring>
#include <string>
#include <sstream>

#include "GetOpt.h"

#include "DMR.h"
#include "XMLWriter.h"
#include "D4BaseTypeFactory.h"
#include "D4Group.h"
#include "D4Sequence.h"
#include "D4Connect.h"
#include "StdinResponse.h"
#include "HTTPConnect.h"
#include "RCReader.h"

using namespace std;
using namespace libdap ;

const char *version = CVER " (" DVR " DAP/" DAP_PROTOCOL_VERSION ")";
#if 0
extern int libdap::dods_keep_temps;     // defined in HTTPResponse.h
extern int libdap::www_trace;
#endif
static void usage(const string &name)
{
	cerr << "Usage: " << name << endl;
	cerr << " [dD vVikmzstM][-c <expr>][-m <num>] <url> [<url> ...] | <file> [<file> ...]" << endl;
	cerr << endl;
	cerr << "In the first form of the command, dereference the URL and" << endl;
	cerr << "perform the requested operations. This includes routing" << endl;
	cerr << "the returned information through the DAP processing" << endl;
	cerr << "library (parsing the returned objects, et c.). If none" << endl;
	cerr << "of a, d, or D are used with a URL, then the DAP library" << endl;
	cerr << "routines are NOT used and the URLs contents are dumped" << endl;
	cerr << "to standard output." << endl;
	cerr << endl;
	cerr << "In the second form of the command, assume the files are" << endl;
	cerr << "DataDDS objects (stored in files or read from pipes)" << endl;
	cerr << "and process them as if -D were given. In this case the" << endl;
	cerr << "information *must* contain valid MIME header in order" << endl;
	cerr << "to be processed." << endl;
	cerr << endl;
	cerr << "Options:" << endl;
	cerr << "        d: For each URL, get the (DAP4) DMR object. Does not get data." << endl;
	cerr << "        D: For each URL, get the DAP4 Data response." << endl;
	cerr << endl;
	cerr << "        v: Verbose output." << endl;
	cerr << "        V: Version of this client; see 'i' for server version." << endl;
	cerr << "        i: For each URL, get the server version." << endl;
	cerr << "        k: Keep temporary files created by libdap." << endl;
	cerr << "        m: Request the same URL <num> times." << endl;
	cerr << "        z: Ask the server to compress data." << endl;
	cerr << "        s: Print Sequences using numbered rows." << endl;
	cerr << "        t: Trace www accesses." << endl;
	cerr << "        M: Assume data read from a file has no MIME headers; use only with files" << endl;
	cerr << endl;
	cerr << "        c: <expr> is a constraint expression. Used with -d/D" << endl;
	cerr << "           NB: You can use a `?' for the CE also." << endl;
}

#if 1
// Used for raw http access/transfer
bool read_data(FILE * fp)
{
    if (!fp) {
        fprintf(stderr, "getdap4: Whoa!!! Null stream pointer.\n");
        return false;
    }
    // Changed from a loop that used getc() to one that uses fread(). getc()
    // worked fine for transfers of text information, but *not* for binary
    // transfers. fread() will handle both.
    char c;
    while (fp && !feof(fp) && fread(&c, 1, 1, fp))
        printf("%c", c);        // stick with stdio

    return true;
}
#endif

static void read_response_from_file(D4Connect *url, DMR &dmr, Response &r, bool mime_headers, bool get_dap4_data, bool get_dmr)
{
    if (mime_headers) {
    	if (get_dap4_data)
    		url->read_data(dmr, r);
    	else if (get_dmr)
    		url->read_dmr(dmr, r);
    	else
    		throw Error("Only supports Data or DMR responses");
    }
    else {
    	if (get_dap4_data)
    		url->read_data_no_mime(dmr, r);
    	else if (get_dmr)
    		url->read_dmr_no_mime(dmr, r);
    	else
    		throw Error("Only supports Data or DMR responses");
    }
}

static void print_group_data(D4Group *g, bool print_rows = false)
{
    for (D4Group::groupsIter gi = g->grp_begin(), ge = g->grp_end(); gi != ge; ++gi) {
        for (Constructor::Vars_iter i = (*gi)->var_begin(), e = (*gi)->var_end(); i != e; i++) {
            if (print_rows && (*i)->type() == dods_sequence_c)
                dynamic_cast < D4Sequence * >(*i)->print_val_by_rows(cout);
            else
                (*i)->print_val(cout);
        }

        for (D4Group::groupsIter gi = g->grp_begin(), ge = g->grp_end(); gi != ge; ++gi) {
            print_group_data(*gi, print_rows);
        }
    }
}

static void print_data(DMR &dmr, bool print_rows = false)
{
    cout << "The data:" << endl;

    D4Group *g = dmr.root();

    for (Constructor::Vars_iter i = g->var_begin(), e = g->var_end(); i != e; i++) {
        if (print_rows && (*i)->type() == dods_sequence_c)
            dynamic_cast < D4Sequence * >(*i)->print_val_by_rows(cout);
        else
            (*i)->print_val(cout);
    }

    print_group_data(g, print_rows);

    cout << endl << flush;
}

int main(int argc, char *argv[])
{
    GetOpt getopt(argc, argv, "[dDvVikrm:Mzstc:]");
    int option_char;

    bool get_dmr = false;
    bool get_dap4_data = false;
    bool get_version = false;
    bool cexpr = false;
    bool verbose = false;
    bool multi = false;
    bool accept_deflate = false;
    bool print_rows = false;
    bool mime_headers = true;
    bool report_errors = false;
    int times = 1;
    int dap_client_major = 4;
    int dap_client_minor = 0;
    string expr = "";

#ifdef WIN32
    _setmode(_fileno(stdout), _O_BINARY);
#endif

    while ((option_char = getopt()) != -1)
        switch (option_char) {
        case 'd':
            get_dmr = true;
            break;
        case 'D':
            get_dap4_data = true;
            break;
        case 'v':
            verbose = true;
            break;
        case 'V':
        	cerr << "getdap4 version: " << version << endl;
            exit(0);
        case 'i':
            get_version = true;
            break;
#if 0
        case 'k':
            dods_keep_temps = 1;
            break;              // keep_temp is in Connect.cc
#endif
        case 'r':
        	report_errors = true;
        	break;
        case 'm':
            multi = true;
            times = atoi(getopt.optarg);
            break;
        case 'z':
            accept_deflate = true;
            break;
        case 's':
            print_rows = true;
            break;
        case 'M':
            mime_headers = false;
            break;
#if 0
        case 't':
            www_trace = 1;
            break;
#endif
        case 'c':
            cexpr = true;
            expr = getopt.optarg;
            break;
        case 'h':
        case '?':
        default:
            usage(argv[0]);
            exit(1);
            break;
        }

    try {
        // If after processing all the command line options there is nothing
        // left (no URL or file) assume that we should read from stdin.
        for (int i = getopt.optind; i < argc; ++i) {
            if (verbose)
                cerr << "Fetching: " << argv[i] << endl;

            string name = argv[i];
            D4Connect *url = 0;

            url = new D4Connect(name);

            // This overrides the value set in the .dodsrc file.
            if (accept_deflate)
                url->set_accept_deflate(accept_deflate);

            if (dap_client_major > 2)
                url->set_xdap_protocol(dap_client_major, dap_client_minor);

            if (url->is_local()) {
                if (verbose)
                    cerr << "Assuming " << argv[i] << " is a file that contains a response object; decoding." << endl;

                try {
                    D4BaseTypeFactory factory;
                    DMR dmr(&factory);

                    if (strcmp(argv[i], "-") == 0) {
                        StdinResponse r(cin);

                        if (!r.get_cpp_stream())
                            throw Error("Could not open standard input.");

                        read_response_from_file(url, dmr, r, mime_headers, get_dap4_data, get_dmr);
                    }
                    else {
                    	fstream f(argv[i], std::ios_base::in);
                    	if (!f.is_open() || f.bad() || f.eof())
                    		throw Error((string)"Could not open: " + argv[i]);

                    	Response r(&f, 0);

                        read_response_from_file(url, dmr, r, mime_headers, get_dap4_data, get_dmr);
                    }

                    if (verbose)
                        cerr << "DAP version: " << url->get_protocol().c_str() << " Server version: "
    						<< url->get_version().c_str() << endl;

                    // Always write the DMR
                    XMLWriter xml;
                    dmr.print_dap4(xml);
                    cout << xml.get_doc() << endl;

                    if (get_dap4_data)
                    	print_data(dmr, print_rows);
                }
                catch (Error & e) {
                    cerr << "Error: " << e.get_error_message() << endl;
                    delete url; url = 0;
                }
            }
            else if (get_dmr) {
                for (int j = 0; j < times; ++j) {
                    D4BaseTypeFactory factory;
                    DMR dmr(&factory);
                    try {
                        url->request_dmr(dmr, expr);

                        if (verbose) {
                            cout << "DAP version: " << url->get_protocol() << ", Server version: " << url->get_version() << endl;
                            cout << "DMR:" << endl;
                        }

                        XMLWriter xml;
                        dmr.print_dap4(xml);
                        cout << xml.get_doc() << endl;
                    }
                    catch (Error & e) {
                        cerr << e.get_error_message() << endl;
                        if (report_errors)
                        	return EXIT_FAILURE;
                        continue;       // Goto the next URL or exit the loop.
                    }
                }
            }
            else if (get_dap4_data) {
                 for (int j = 0; j < times; ++j) {
                     D4BaseTypeFactory factory;
                     DMR dmr(&factory);
                     try {
                         url->request_dap4_data(dmr, expr);

                         if (verbose) {
                             cout << "DAP version: " << url->get_protocol() << ", Server version: " << url->get_version() << endl;
                             cout << "DMR:" << endl;
                         }

                         XMLWriter xml;
                         dmr.print_dap4(xml);
                         cout << xml.get_doc() << endl;

                         print_data(dmr, print_rows);
                    }
                     catch (Error & e) {
                         cerr << e.get_error_message() << endl;
                         continue;       // Goto the next URL or exit the loop.
                     }
                 }
            }
            else {
                HTTPConnect http(RCReader::instance());

                // This overrides the value set in the .dodsrc file.
                if (accept_deflate)
                    http.set_accept_deflate(accept_deflate);

                if (dap_client_major > 2)
                    url->set_xdap_protocol(dap_client_major, dap_client_minor);

                string url_string = argv[i];
                for (int j = 0; j < times; ++j) {
                    try {
                        HTTPResponse *r = http.fetch_url(url_string);
                        if (verbose) {
                        	vector<string> *headers = r->get_headers();
                        	copy(headers->begin(), headers->end(), ostream_iterator<string>(cout, "\n"));
                        }
                        if (!read_data(r->get_stream())) {
                            continue;
                        }
                        delete r;
                        r = 0;
                    }
                    catch (Error & e) {
                        cerr << e.get_error_message() << endl;
                        continue;
                    }
                }
            }

#if 0
            else if (get_version) {
                fprintf(stderr, "DAP version: %s, Server version: %s\n",
                        url->request_protocol().c_str(),
                        url->get_version().c_str());
            }
#endif

            delete url;  url = 0;
        }
    }
    catch (Error &e) {
        cerr << "Error: " << e.get_error_message() << endl;
        cerr << "exiting" << endl;
        return 1;
    }
    catch (exception &e) {
        cerr << "C++ library exception: " << e.what() << endl;
        cerr << "exiting" << endl;
        return 1;
    }

    return 0;
}
<commit_msg>Added changes to exit when 'report_errors' (-r) is true<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// (c) COPYRIGHT URI/MIT 1997-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
//      jhrg,jimg       James Gallagher <jgallagher@gso.uri.edu>

// This is the source to `getdap'; a simple tool to exercise the Connect
// class. It can be used to get naked URLs as well as the DAP2 DAS and DDS
// objects.  jhrg.

#include "config.h"

#ifdef WIN32
#include <io.h>
#include <fcntl.h>
#endif

#include <cstring>
#include <string>
#include <sstream>

#include "GetOpt.h"

#include "DMR.h"
#include "XMLWriter.h"
#include "D4BaseTypeFactory.h"
#include "D4Group.h"
#include "D4Sequence.h"
#include "D4Connect.h"
#include "StdinResponse.h"
#include "HTTPConnect.h"
#include "RCReader.h"

using namespace std;
using namespace libdap ;

const char *version = CVER " (" DVR " DAP/" DAP_PROTOCOL_VERSION ")";
#if 0
extern int libdap::dods_keep_temps;     // defined in HTTPResponse.h
extern int libdap::www_trace;
#endif
static void usage(const string &name)
{
	cerr << "Usage: " << name << endl;
	cerr << " [dD vVikmzstM][-c <expr>][-m <num>] <url> [<url> ...] | <file> [<file> ...]" << endl;
	cerr << endl;
	cerr << "In the first form of the command, dereference the URL and" << endl;
	cerr << "perform the requested operations. This includes routing" << endl;
	cerr << "the returned information through the DAP processing" << endl;
	cerr << "library (parsing the returned objects, et c.). If none" << endl;
	cerr << "of a, d, or D are used with a URL, then the DAP library" << endl;
	cerr << "routines are NOT used and the URLs contents are dumped" << endl;
	cerr << "to standard output." << endl;
	cerr << endl;
	cerr << "In the second form of the command, assume the files are" << endl;
	cerr << "DataDDS objects (stored in files or read from pipes)" << endl;
	cerr << "and process them as if -D were given. In this case the" << endl;
	cerr << "information *must* contain valid MIME header in order" << endl;
	cerr << "to be processed." << endl;
	cerr << endl;
	cerr << "Options:" << endl;
	cerr << "        d: For each URL, get the (DAP4) DMR object. Does not get data." << endl;
	cerr << "        D: For each URL, get the DAP4 Data response." << endl;
	cerr << endl;
	cerr << "        v: Verbose output." << endl;
	cerr << "        V: Version of this client; see 'i' for server version." << endl;
	cerr << "        i: For each URL, get the server version." << endl;
	cerr << "        k: Keep temporary files created by libdap." << endl;
	cerr << "        m: Request the same URL <num> times." << endl;
	cerr << "        z: Ask the server to compress data." << endl;
	cerr << "        s: Print Sequences using numbered rows." << endl;
	cerr << "        t: Trace www accesses." << endl;
	cerr << "        M: Assume data read from a file has no MIME headers; use only with files" << endl;
	cerr << endl;
	cerr << "        c: <expr> is a constraint expression. Used with -d/D" << endl;
	cerr << "           NB: You can use a `?' for the CE also." << endl;
}

// Used for raw http access/transfer
bool read_data(FILE * fp)
{
    if (!fp) {
        fprintf(stderr, "getdap4: Whoa!!! Null stream pointer.\n");
        return false;
    }
    // Changed from a loop that used getc() to one that uses fread(). getc()
    // worked fine for transfers of text information, but *not* for binary
    // transfers. fread() will handle both.
    char c;
    while (fp && !feof(fp) && fread(&c, 1, 1, fp))
        printf("%c", c);        // stick with stdio

    return true;
}

static void read_response_from_file(D4Connect *url, DMR &dmr, Response &r, bool mime_headers, bool get_dap4_data, bool get_dmr)
{
    if (mime_headers) {
    	if (get_dap4_data)
    		url->read_data(dmr, r);
    	else if (get_dmr)
    		url->read_dmr(dmr, r);
    	else
    		throw Error("Only supports Data or DMR responses");
    }
    else {
    	if (get_dap4_data)
    		url->read_data_no_mime(dmr, r);
    	else if (get_dmr)
    		url->read_dmr_no_mime(dmr, r);
    	else
    		throw Error("Only supports Data or DMR responses");
    }
}

static void print_group_data(D4Group *g, bool print_rows = false)
{
    for (D4Group::groupsIter gi = g->grp_begin(), ge = g->grp_end(); gi != ge; ++gi) {
        for (Constructor::Vars_iter i = (*gi)->var_begin(), e = (*gi)->var_end(); i != e; i++) {
            if (print_rows && (*i)->type() == dods_sequence_c)
                dynamic_cast < D4Sequence * >(*i)->print_val_by_rows(cout);
            else
                (*i)->print_val(cout);
        }

        for (D4Group::groupsIter gi = g->grp_begin(), ge = g->grp_end(); gi != ge; ++gi) {
            print_group_data(*gi, print_rows);
        }
    }
}

static void print_data(DMR &dmr, bool print_rows = false)
{
    cout << "The data:" << endl;

    D4Group *g = dmr.root();

    for (Constructor::Vars_iter i = g->var_begin(), e = g->var_end(); i != e; i++) {
        if (print_rows && (*i)->type() == dods_sequence_c)
            dynamic_cast < D4Sequence * >(*i)->print_val_by_rows(cout);
        else
            (*i)->print_val(cout);
    }

    print_group_data(g, print_rows);

    cout << endl << flush;
}

int main(int argc, char *argv[])
{
    GetOpt getopt(argc, argv, "[dDvVikrm:Mzstc:]");
    int option_char;

    bool get_dmr = false;
    bool get_dap4_data = false;
    bool get_version = false;
    bool cexpr = false;
    bool verbose = false;
    bool multi = false;
    bool accept_deflate = false;
    bool print_rows = false;
    bool mime_headers = true;
    bool report_errors = false;
    int times = 1;
    int dap_client_major = 4;
    int dap_client_minor = 0;
    string expr = "";

#ifdef WIN32
    _setmode(_fileno(stdout), _O_BINARY);
#endif

    while ((option_char = getopt()) != -1)
        switch (option_char) {
        case 'd':
            get_dmr = true;
            break;
        case 'D':
            get_dap4_data = true;
            break;
        case 'v':
            verbose = true;
            break;
        case 'V':
        	cerr << "getdap4 version: " << version << endl;
            exit(0);
        case 'i':
            get_version = true;
            break;
#if 0
        case 'k':
            dods_keep_temps = 1;
            break;              // keep_temp is in Connect.cc
#endif
        case 'r':
        	report_errors = true;
        	break;
        case 'm':
            multi = true;
            times = atoi(getopt.optarg);
            break;
        case 'z':
            accept_deflate = true;
            break;
        case 's':
            print_rows = true;
            break;
        case 'M':
            mime_headers = false;
            break;
#if 0
        case 't':
            www_trace = 1;
            break;
#endif
        case 'c':
            cexpr = true;
            expr = getopt.optarg;
            break;
        case 'h':
        case '?':
        default:
            usage(argv[0]);
            exit(1);
            break;
        }

    try {
        // If after processing all the command line options there is nothing
        // left (no URL or file) assume that we should read from stdin.
        for (int i = getopt.optind; i < argc; ++i) {
            if (verbose)
                cerr << "Fetching: " << argv[i] << endl;

            string name = argv[i];
            D4Connect *url = 0;
            // auto_ptr? jhrg 10/19/15
            url = new D4Connect(name);

            // This overrides the value set in the .dodsrc file.
            if (accept_deflate)
                url->set_accept_deflate(accept_deflate);

            if (dap_client_major > 2)
                url->set_xdap_protocol(dap_client_major, dap_client_minor);

            if (url->is_local()) {
                if (verbose)
                    cerr << "Assuming " << argv[i] << " is a file that contains a response object; decoding." << endl;

                try {
                    D4BaseTypeFactory factory;
                    DMR dmr(&factory);

                    if (strcmp(argv[i], "-") == 0) {
                        StdinResponse r(cin);

                        if (!r.get_cpp_stream())
                            throw Error("Could not open standard input.");

                        read_response_from_file(url, dmr, r, mime_headers, get_dap4_data, get_dmr);
                    }
                    else {
                    	fstream f(argv[i], std::ios_base::in);
                    	if (!f.is_open() || f.bad() || f.eof())
                    		throw Error((string)"Could not open: " + argv[i]);

                    	Response r(&f, 0);

                        read_response_from_file(url, dmr, r, mime_headers, get_dap4_data, get_dmr);
                    }

                    if (verbose)
                        cerr << "DAP version: " << url->get_protocol().c_str() << " Server version: "
    						<< url->get_version().c_str() << endl;

                    // Always write the DMR
                    XMLWriter xml;
                    dmr.print_dap4(xml);
                    cout << xml.get_doc() << endl;

                    if (get_dap4_data)
                    	print_data(dmr, print_rows);
                }
                catch (Error & e) {
                    cerr << "Error: " << e.get_error_message() << endl;
                    delete url; url = 0;
                    if (report_errors)
                        return EXIT_FAILURE;
                }
            }
            else if (get_dmr) {
                for (int j = 0; j < times; ++j) {
                    D4BaseTypeFactory factory;
                    DMR dmr(&factory);
                    try {
                        url->request_dmr(dmr, expr);

                        if (verbose) {
                            cout << "DAP version: " << url->get_protocol() << ", Server version: " << url->get_version() << endl;
                            cout << "DMR:" << endl;
                        }

                        XMLWriter xml;
                        dmr.print_dap4(xml);
                        cout << xml.get_doc() << endl;
                    }
                    catch (Error & e) {
                        cerr << e.get_error_message() << endl;
                        if (report_errors)
                        	return EXIT_FAILURE;
                        continue;       // Goto the next URL or exit the loop.
                    }
                }
            }
            else if (get_dap4_data) {
                 for (int j = 0; j < times; ++j) {
                     D4BaseTypeFactory factory;
                     DMR dmr(&factory);
                     try {
                         url->request_dap4_data(dmr, expr);

                         if (verbose) {
                             cout << "DAP version: " << url->get_protocol() << ", Server version: " << url->get_version() << endl;
                             cout << "DMR:" << endl;
                         }

                         XMLWriter xml;
                         dmr.print_dap4(xml);
                         cout << xml.get_doc() << endl;

                         print_data(dmr, print_rows);
                    }
                     catch (Error & e) {
                         cerr << e.get_error_message() << endl;
                         if (report_errors)
                             return EXIT_FAILURE;
                         continue;       // Goto the next URL or exit the loop.
                     }
                 }
            }
            else {
                HTTPConnect http(RCReader::instance());

                // This overrides the value set in the .dodsrc file.
                if (accept_deflate)
                    http.set_accept_deflate(accept_deflate);

                if (dap_client_major > 2)
                    url->set_xdap_protocol(dap_client_major, dap_client_minor);

                string url_string = argv[i];
                for (int j = 0; j < times; ++j) {
                    try {
                        HTTPResponse *r = http.fetch_url(url_string);
                        if (verbose) {
                        	vector<string> *headers = r->get_headers();
                        	copy(headers->begin(), headers->end(), ostream_iterator<string>(cout, "\n"));
                        }
                        if (!read_data(r->get_stream())) {
                            continue;
                        }
                        delete r;
                        r = 0;
                    }
                    catch (Error & e) {
                        cerr << e.get_error_message() << endl;
                        if (report_errors)
                            return EXIT_FAILURE;
                        continue;
                    }
                }
            }

#if 0
            else if (get_version) {
                fprintf(stderr, "DAP version: %s, Server version: %s\n",
                        url->request_protocol().c_str(),
                        url->get_version().c_str());
            }
#endif

            delete url;  url = 0;
        }
    }
    catch (Error &e) {
        cerr << "Error: " << e.get_error_message() << endl;
        cerr << "exiting" << endl;
        return 1;
    }
    catch (exception &e) {
        cerr << "C++ library exception: " << e.what() << endl;
        cerr << "exiting" << endl;
        return 1;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <glm/glm.hpp>
#include <jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <android/bitmap.h>
#include <android/asset_manager.h>
#include "NdkGlue.h"

#include <string>
#include <memory>
#include <vector>

#include "Common.h"
#include "Logger.h"
#include "NativeBitmap.h"
#include "android_asset_operations.h"
#include "AudioSink.h"
#include "SoundClip.h"
#include "SoundUtils.h"
#include "SoundListener.h"
#include "SoundEmitter.h"

#include "IFileLoaderDelegate.h"
#include "AndroidFileLoaderDelegate.h"
#include "GameNativeAPI.h"
#include "AndroidAudioSink.h"

long currentDelta = 0;
std::vector<std::shared_ptr<odb::NativeBitmap>> texturesToLoad;
std::vector<std::shared_ptr<odb::SoundEmitter>> sounds;

std::string gVertexShader;
std::string gFragmentShader;

std::shared_ptr<AndroidAudioSink> audioSinkWrapper;
std::shared_ptr<odb::SoundListener> soundListener;

std::shared_ptr<odb::SoundEmitter> makeSoundEmitterFromFilename(JNIEnv *env, jclass type,
                                                                AAssetManager *assetManager,
                                                                jstring filename) {
	FILE *soundFile;

	const char *rawString = env->GetStringUTFChars(filename, 0);

	soundFile = android_fopen(rawString, "r", assetManager);
	auto soundClip = odb::makeSoundClipFrom(audioSinkWrapper, soundFile);
	fclose(soundFile);

	return std::make_shared<odb::SoundEmitter>(audioSinkWrapper, soundClip);
}

std::shared_ptr<odb::NativeBitmap> makeNativeBitmapFromJObject(JNIEnv *env, jobject bitmap) {

	void *addr;
	AndroidBitmapInfo info;
	int errorCode;

	if ((errorCode = AndroidBitmap_lockPixels(env, bitmap, &addr)) != 0) {
		odb::Logger::log("error %d", errorCode);
	}

	if ((errorCode = AndroidBitmap_getInfo(env, bitmap, &info)) != 0) {
		odb::Logger::log("error %d", errorCode);
	}

	odb::Logger::log("bitmap info: %d wide, %d tall, %d ints per pixel", info.width, info.height,
	                 info.format);

	long size = info.width * info.height * info.format;
	int *pixels = new int[size];
	memcpy(pixels, addr, size * sizeof(int));

	auto toReturn = std::make_shared<odb::NativeBitmap>(info.width, info.height, pixels);

	if ((errorCode = AndroidBitmap_unlockPixels(env, bitmap)) != 0) {
		odb::Logger::log("error %d", errorCode);
	}

	return toReturn;
}

void loadTexturesFromBitmaps(JNIEnv *env, _jobjectArray *bitmaps, int length) {
	texturesToLoad.clear();
	for (int c = 0; c < length; ++c) {
		texturesToLoad.push_back(
				makeNativeBitmapFromJObject(env, env->GetObjectArrayElement(bitmaps, c)));
	}
}

void loadSoundsFromFilenames(JNIEnv *env, jclass type, jobject asset_manager,
                             _jobjectArray *soundFiles, jsize length) {
	sounds.clear();
	AAssetManager *assetManager = AAssetManager_fromJava(env, asset_manager);

	for (int c = 0; c < length; ++c) {

		sounds.push_back(makeSoundEmitterFromFilename(env, type, assetManager,
		                                              (jstring) (env->GetObjectArrayElement(
				                                              soundFiles, c))));
	}
}

extern "C" {

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_loadSounds(JNIEnv *env, jclass type,
		                                 jobject asset_manager, jobjectArray soundFiles);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_flush(JNIEnv *env, jclass type, jobject sink);

JNIEXPORT void JNICALL Java_br_odb_GL2JNILib_onCreate(JNIEnv *env, void *reserved,
                                                      jobject assetManager);
JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_setYZAngle(JNIEnv *env, jclass type, jfloat yz);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_setXZAngle(JNIEnv *env, jclass type, jfloat xz);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_setPerspectiveMatrix(JNIEnv *env, jclass type,
		                                           jfloatArray perspectiveMatrix_);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_setEyeMatrix(JNIEnv *env, jclass type, jfloatArray eyeView_);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_setTextures(JNIEnv *env, jclass type, jobjectArray bitmaps);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_setClearColour(JNIEnv *env, jclass type, jfloat r, jfloat g,
		                                     jfloat b);
JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_moveUp(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_moveDown(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_moveLeft(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_moveRight(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_rotateLeft(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_rotateRight(JNIEnv *env, jclass type);

JNIEXPORT jboolean JNICALL
		Java_br_odb_GL2JNILib_isAnimating(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_forcePlayerDirection(JNIEnv *env, jclass type, jint direction);

JNIEXPORT void JNICALL Java_br_odb_GL2JNILib_onDestroy(JNIEnv *env, jobject obj);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_setActorIdPositions(JNIEnv *env, jclass type, jintArray ids_);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_tick(JNIEnv *env, jclass type, jlong delta);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_onReleasedLongPressingMove(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_onLongPressingMove(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_fadeOut(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_fadeIn(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL Java_br_odb_GL2JNILib_init(JNIEnv *env, jobject obj,
                                                  jint width, jint height);
JNIEXPORT void JNICALL Java_br_odb_GL2JNILib_step(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_setMapWithSplatsAndActors(JNIEnv *env, jclass type, jintArray map_,
		                                                jintArray actors_, jintArray splats_);

};

JNIEXPORT void JNICALL Java_br_odb_GL2JNILib_onCreate(JNIEnv *env, void *reserved,
                                                      jobject assetManager) {

	AAssetManager *asset_manager = AAssetManager_fromJava(env, assetManager);
	FILE *fd;

	fd = android_fopen("vertex.glsl", "r", asset_manager);
	gVertexShader = readToString(fd);
	fclose(fd);

	fd = android_fopen("fragment.glsl", "r", asset_manager);
	gFragmentShader = readToString(fd);
	fclose(fd);

	readMap(std::make_shared<odb::AndroidFileLoaderDelegate>(asset_manager));
}

JNIEXPORT void JNICALL Java_br_odb_GL2JNILib_init(JNIEnv *env, jobject obj,
                                                  jint width, jint height) {

	setupGraphics(width, height, gVertexShader, gFragmentShader, texturesToLoad);
}

JNIEXPORT void JNICALL Java_br_odb_GL2JNILib_step(JNIEnv *env, jclass type) {
	renderFrame(currentDelta);
}

JNIEXPORT void JNICALL Java_br_odb_GL2JNILib_onDestroy(JNIEnv *env, jobject obj) {
	shutdown();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_setTextures(JNIEnv *env, jclass type, jobjectArray bitmaps) {
	loadTexturesFromBitmaps(env, bitmaps, env->GetArrayLength(bitmaps));
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_fadeIn(JNIEnv *env, jclass type) {
	startFadingIn();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_fadeOut(JNIEnv *env, jclass type) {
	startFadingOut();
}

JNIEXPORT jboolean JNICALL
Java_br_odb_GL2JNILib_isAnimating(JNIEnv *env, jclass type) {
	return isAnimating();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_rotateLeft(JNIEnv *env, jclass type) {
	rotateCameraLeft();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_rotateRight(JNIEnv *env, jclass type) {
	rotateCameraRight();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_onReleasedLongPressingMove(JNIEnv *env, jclass type) {
	onReleasedLongPressingMove();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_onLongPressingMove(JNIEnv *env, jclass type) {
	onLongPressingMove();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_setEyeMatrix(JNIEnv *env, jclass type, jfloatArray eyeView_) {
	jfloat *eyeView = env->GetFloatArrayElements(eyeView_, NULL);

	setEyeViewMatrix(eyeView);

	env->ReleaseFloatArrayElements(eyeView_, eyeView, 0);
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_tick(JNIEnv *env, jclass type, jlong delta) {

	updateAnimations(delta);
	currentDelta = delta;
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_setPerspectiveMatrix(JNIEnv *env, jclass type,
                                           jfloatArray perspectiveMatrix_) {
	jfloat *perspectiveMatrix = env->GetFloatArrayElements(perspectiveMatrix_, NULL);

	setPerspectiveMatrix(perspectiveMatrix);

	env->ReleaseFloatArrayElements(perspectiveMatrix_, perspectiveMatrix, 0);
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_setXZAngle(JNIEnv *env, jclass type, jfloat xz) {

	setAngleXZ(xz);
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_setYZAngle(JNIEnv *env, jclass type, jfloat yz) {

	setAngleYZ(yz);
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_moveUp(JNIEnv *env, jclass type) {

	moveUp();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_moveDown(JNIEnv *env, jclass type) {

	moveDown();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_moveLeft(JNIEnv *env, jclass type) {

	moveLeft();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_moveRight(JNIEnv *env, jclass type) {

	moveRight();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_flush(JNIEnv *env, jclass type, jobject sink) {
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_loadSounds(JNIEnv *env, jclass type, jobject asset_manager,
                                 jobjectArray soundFiles) {

	audioSinkWrapper = std::make_shared<AndroidAudioSink>();
	soundListener = std::make_shared<odb::SoundListener>(audioSinkWrapper);

	loadSoundsFromFilenames(env, type, asset_manager, soundFiles,
	                        env->GetArrayLength(soundFiles));

	setSoundEmitters( sounds, soundListener );
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_forcePlayerDirection(JNIEnv *env, jclass type, jint direction) {
	forceDirection( direction );
}<commit_msg>Fix Android compilation<commit_after>#include <glm/glm.hpp>
#include <jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <android/bitmap.h>
#include <android/asset_manager.h>
#include "NdkGlue.h"

#include <string>
#include <memory>
#include <vector>
#include <functional>
#include <array>

#include "Common.h"
#include "Logger.h"
#include "NativeBitmap.h"
#include "android_asset_operations.h"
#include "AudioSink.h"
#include "SoundClip.h"
#include "SoundUtils.h"
#include "SoundListener.h"
#include "SoundEmitter.h"

#include "IFileLoaderDelegate.h"
#include "AndroidFileLoaderDelegate.h"

#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"

#include "NoudarDungeonSnapshot.h"

#include "GameNativeAPI.h"
#include "AndroidAudioSink.h"

long currentDelta = 0;
std::vector<std::shared_ptr<odb::NativeBitmap>> texturesToLoad;
std::vector<std::shared_ptr<odb::SoundEmitter>> sounds;

std::string gVertexShader;
std::string gFragmentShader;

std::shared_ptr<AndroidAudioSink> audioSinkWrapper;
std::shared_ptr<odb::SoundListener> soundListener;

std::shared_ptr<odb::SoundEmitter> makeSoundEmitterFromFilename(JNIEnv *env, jclass type,
                                                                AAssetManager *assetManager,
                                                                jstring filename) {
	FILE *soundFile;

	const char *rawString = env->GetStringUTFChars(filename, 0);

	soundFile = android_fopen(rawString, "r", assetManager);
	auto soundClip = odb::makeSoundClipFrom(audioSinkWrapper, soundFile);
	fclose(soundFile);

	return std::make_shared<odb::SoundEmitter>(audioSinkWrapper, soundClip);
}

std::shared_ptr<odb::NativeBitmap> makeNativeBitmapFromJObject(JNIEnv *env, jobject bitmap) {

	void *addr;
	AndroidBitmapInfo info;
	int errorCode;

	if ((errorCode = AndroidBitmap_lockPixels(env, bitmap, &addr)) != 0) {
		odb::Logger::log("error %d", errorCode);
	}

	if ((errorCode = AndroidBitmap_getInfo(env, bitmap, &info)) != 0) {
		odb::Logger::log("error %d", errorCode);
	}

	odb::Logger::log("bitmap info: %d wide, %d tall, %d ints per pixel", info.width, info.height,
	                 info.format);

	long size = info.width * info.height * info.format;
	int *pixels = new int[size];
	memcpy(pixels, addr, size * sizeof(int));

	auto toReturn = std::make_shared<odb::NativeBitmap>(info.width, info.height, pixels);

	if ((errorCode = AndroidBitmap_unlockPixels(env, bitmap)) != 0) {
		odb::Logger::log("error %d", errorCode);
	}

	return toReturn;
}

void loadTexturesFromBitmaps(JNIEnv *env, _jobjectArray *bitmaps, int length) {
	texturesToLoad.clear();
	for (int c = 0; c < length; ++c) {
		texturesToLoad.push_back(
				makeNativeBitmapFromJObject(env, env->GetObjectArrayElement(bitmaps, c)));
	}
}

void loadSoundsFromFilenames(JNIEnv *env, jclass type, jobject asset_manager,
                             _jobjectArray *soundFiles, jsize length) {
	sounds.clear();
	AAssetManager *assetManager = AAssetManager_fromJava(env, asset_manager);

	for (int c = 0; c < length; ++c) {

		sounds.push_back(makeSoundEmitterFromFilename(env, type, assetManager,
		                                              (jstring) (env->GetObjectArrayElement(
				                                              soundFiles, c))));
	}
}

extern "C" {

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_loadSounds(JNIEnv *env, jclass type,
		                                 jobject asset_manager, jobjectArray soundFiles);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_flush(JNIEnv *env, jclass type, jobject sink);

JNIEXPORT void JNICALL Java_br_odb_GL2JNILib_onCreate(JNIEnv *env, void *reserved,
                                                      jobject assetManager);
JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_setYZAngle(JNIEnv *env, jclass type, jfloat yz);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_setXZAngle(JNIEnv *env, jclass type, jfloat xz);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_setPerspectiveMatrix(JNIEnv *env, jclass type,
		                                           jfloatArray perspectiveMatrix_);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_setEyeMatrix(JNIEnv *env, jclass type, jfloatArray eyeView_);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_setTextures(JNIEnv *env, jclass type, jobjectArray bitmaps);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_setClearColour(JNIEnv *env, jclass type, jfloat r, jfloat g,
		                                     jfloat b);
JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_moveUp(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_moveDown(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_moveLeft(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_moveRight(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_rotateLeft(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_rotateRight(JNIEnv *env, jclass type);

JNIEXPORT jboolean JNICALL
		Java_br_odb_GL2JNILib_isAnimating(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_forcePlayerDirection(JNIEnv *env, jclass type, jint direction);

JNIEXPORT void JNICALL Java_br_odb_GL2JNILib_onDestroy(JNIEnv *env, jobject obj);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_setActorIdPositions(JNIEnv *env, jclass type, jintArray ids_);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_tick(JNIEnv *env, jclass type, jlong delta);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_onReleasedLongPressingMove(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_onLongPressingMove(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_fadeOut(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_fadeIn(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL Java_br_odb_GL2JNILib_init(JNIEnv *env, jobject obj,
                                                  jint width, jint height);
JNIEXPORT void JNICALL Java_br_odb_GL2JNILib_step(JNIEnv *env, jclass type);

JNIEXPORT void JNICALL
		Java_br_odb_GL2JNILib_setMapWithSplatsAndActors(JNIEnv *env, jclass type, jintArray map_,
		                                                jintArray actors_, jintArray splats_);

};

JNIEXPORT void JNICALL Java_br_odb_GL2JNILib_onCreate(JNIEnv *env, void *reserved,
                                                      jobject assetManager) {

	AAssetManager *asset_manager = AAssetManager_fromJava(env, assetManager);
	FILE *fd;

	fd = android_fopen("vertex.glsl", "r", asset_manager);
	gVertexShader = readToString(fd);
	fclose(fd);

	fd = android_fopen("fragment.glsl", "r", asset_manager);
	gFragmentShader = readToString(fd);
	fclose(fd);

	readMap(std::make_shared<odb::AndroidFileLoaderDelegate>(asset_manager));
}

JNIEXPORT void JNICALL Java_br_odb_GL2JNILib_init(JNIEnv *env, jobject obj,
                                                  jint width, jint height) {

	setupGraphics(width, height, gVertexShader, gFragmentShader, texturesToLoad);
}

JNIEXPORT void JNICALL Java_br_odb_GL2JNILib_step(JNIEnv *env, jclass type) {
	renderFrame(currentDelta);
}

JNIEXPORT void JNICALL Java_br_odb_GL2JNILib_onDestroy(JNIEnv *env, jobject obj) {
	shutdown();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_setTextures(JNIEnv *env, jclass type, jobjectArray bitmaps) {
	loadTexturesFromBitmaps(env, bitmaps, env->GetArrayLength(bitmaps));
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_fadeIn(JNIEnv *env, jclass type) {
	startFadingIn();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_fadeOut(JNIEnv *env, jclass type) {
	startFadingOut();
}

JNIEXPORT jboolean JNICALL
Java_br_odb_GL2JNILib_isAnimating(JNIEnv *env, jclass type) {
	return isAnimating();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_rotateLeft(JNIEnv *env, jclass type) {
	rotateCameraLeft();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_rotateRight(JNIEnv *env, jclass type) {
	rotateCameraRight();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_onReleasedLongPressingMove(JNIEnv *env, jclass type) {
	onReleasedLongPressingMove();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_onLongPressingMove(JNIEnv *env, jclass type) {
	onLongPressingMove();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_setEyeMatrix(JNIEnv *env, jclass type, jfloatArray eyeView_) {
	jfloat *eyeView = env->GetFloatArrayElements(eyeView_, NULL);

	setEyeViewMatrix(eyeView);

	env->ReleaseFloatArrayElements(eyeView_, eyeView, 0);
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_tick(JNIEnv *env, jclass type, jlong delta) {

	updateAnimations(delta);
	currentDelta = delta;
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_setPerspectiveMatrix(JNIEnv *env, jclass type,
                                           jfloatArray perspectiveMatrix_) {
	jfloat *perspectiveMatrix = env->GetFloatArrayElements(perspectiveMatrix_, NULL);

	setPerspectiveMatrix(perspectiveMatrix);

	env->ReleaseFloatArrayElements(perspectiveMatrix_, perspectiveMatrix, 0);
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_setXZAngle(JNIEnv *env, jclass type, jfloat xz) {

	setAngleXZ(xz);
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_setYZAngle(JNIEnv *env, jclass type, jfloat yz) {

	setAngleYZ(yz);
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_moveUp(JNIEnv *env, jclass type) {

	moveUp();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_moveDown(JNIEnv *env, jclass type) {

	moveDown();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_moveLeft(JNIEnv *env, jclass type) {

	moveLeft();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_moveRight(JNIEnv *env, jclass type) {

	moveRight();
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_flush(JNIEnv *env, jclass type, jobject sink) {
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_loadSounds(JNIEnv *env, jclass type, jobject asset_manager,
                                 jobjectArray soundFiles) {

	audioSinkWrapper = std::make_shared<AndroidAudioSink>();
	soundListener = std::make_shared<odb::SoundListener>(audioSinkWrapper);

	loadSoundsFromFilenames(env, type, asset_manager, soundFiles,
	                        env->GetArrayLength(soundFiles));

	setSoundEmitters( sounds, soundListener );
}

JNIEXPORT void JNICALL
Java_br_odb_GL2JNILib_forcePlayerDirection(JNIEnv *env, jclass type, jint direction) {
	forceDirection( direction );
}<|endoftext|>


<commit_before>#include <fabric/dataCore.hpp>

fabric::DataCore::DataCore()
{
	camPos.x = 0;
	camPos.y = 0;
	camPos.z = 0;

}<commit_msg>Changed cam z<commit_after>#include <fabric/dataCore.hpp>

fabric::DataCore::DataCore()
{
	camPos.x = 0;
	camPos.y = 0;
	camPos.z = 0.1;

}<|endoftext|>


<commit_before>/**
 * @file persistence_dat.cpp
 *
 * @brief Purpose: Contains methods to save the game
 *
 * MIT License
 * Copyright (c) 2017 MindScape
 *
 * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
 *
 */
#include "persistence_dat.hpp"
#include "../engine/include/log.hpp"
#include <unordered_map>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stack>

using namespace engine;

PersistenceDat *PersistenceDat::instance = 0;

/**
 * @brief Get Instance
 *
 * Method responsible for get instance
 *
 * @return void
 */
PersistenceDat *PersistenceDat::get_instance(){
	if (!instance) {
		instance = nullptr;
	}
	else {
		/*Do nothing*/
	}

	instance = new PersistenceDat();

	return instance;
}

/**
 * @brief Load Method
 *
 * Method responsible for load the saved game
 *
 * @param p_path path to saved game
 * @return game loaded
 */
PersistenceMap * PersistenceDat::load(std::string p_path){
	PersistenceMap *data = nullptr;
	data = new PersistenceMap();

	std::stack<std::string> paths;
	paths.push(p_path);
	std::string line = "";

	/* Reads the complete file */
	while(!paths.empty()){
		std::string path = paths.top();
		paths.pop();
		std::ifstream save_file;
		save_file.open(path, std::ifstream::in);

		/* Opens the file to be written */
		if (save_file.is_open()){

			/* Writes the opened file with game datas*/
			while (std::getline(save_file,line)){
				bool is_include = false;
				std::istringstream iss(line);
				std::string key = "";
				std::string value = "";
				std::unordered_map<std::string, std::string> object_data;

				/* If the line are empty or the line initialize with comment tag */
				if (line != "" && line[0] != '#'){
					while(iss >> key && iss >> value){

						/* Writes persistence values in opened file */
						if ((is_include = (key == "include"))) {
							paths.push(value);
						}
						else {
							/* Do nothing */
						}

						object_data[key] = value;
					}

					if (!is_include) {
						data->insert_object(object_data);
					}
					else {
				        /* Do nothing */
				    }
				}
				else {
		        	INFO("The file was opened incorrectly");
			    }
			}
		}
		else {
			INFO("Unable to open file");
			return NULL;
		}
	}

	return data;
}

/**
 * @brief Dump Method
 *
 * Method responsible for dump
 *
 * @param path path to save the open game in a file
 * @param data saved game
 * @return void
 */
bool PersistenceDat::dump(std::string path, PersistenceMap * data){
	std::ofstream save_file;
	save_file.open(path);

	/* Opens the file to be written */
	if (save_file.is_open()) {
		for (auto it = data->begin(); it < data->end(); it++) {

			/* Writes persistence datas in opened file */
			for (auto each_data : *it) {
				save_file << each_data.first << " " << each_data.second << " ";
			}

			save_file << std::endl;
		}
	}
	else {
		INFO("Unable to open file");

		return false;
	}

	save_file.close();

	return true;
}
<commit_msg>[RELEVANTS METHODS] Applies technique in persistence_dat<commit_after>/**
 * @file persistence_dat.cpp
 *
 * @brief Purpose: Contains methods to save the game
 *
 * MIT License
 * Copyright (c) 2017 MindScape
 *
 * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
 *
 */
#include "persistence_dat.hpp"
#include "../engine/include/log.hpp"
#include <unordered_map>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stack>

using namespace engine;

PersistenceDat *PersistenceDat::instance = 0;

/**
 * @brief Get Instance
 *
 * Method responsible for get instance
 *
 * @return void
 */
PersistenceDat *PersistenceDat::get_instance(){
	if (!instance) {
		instance = nullptr;
	}
	else {
		/*Do nothing*/
	}

	instance = new PersistenceDat();

	return instance;
}

/**
 * @brief Dump Method
 *
 * Method responsible for dump
 *
 * @param path path to save the open game in a file
 * @param data saved game
 * @return void
 */
bool PersistenceDat::dump(std::string path, PersistenceMap * data){
	std::ofstream save_file;
	save_file.open(path);

	/* Opens the file to be written */
	if (save_file.is_open()) {
		for (auto it = data->begin(); it < data->end(); it++) {

			/* Writes persistence datas in opened file */
			for (auto each_data : *it) {
				save_file << each_data.first << " " << each_data.second << " ";
			}

			save_file << std::endl;
		}
	}
	else {
		INFO("Unable to open file");

		return false;
	}

	save_file.close();

	return true;
}

/**
 * @brief Load Method
 *
 * Method responsible for load the saved game
 *
 * @param p_path path to saved game
 * @return game loaded
 */
PersistenceMap * PersistenceDat::load(std::string p_path){
	PersistenceMap *data = nullptr;
	data = new PersistenceMap();

	std::stack<std::string> paths;
	paths.push(p_path);
	std::string line = "";

	/* Reads the complete file */
	while(!paths.empty()){
		std::string path = paths.top();
		paths.pop();
		std::ifstream save_file;
		save_file.open(path, std::ifstream::in);

		/* Opens the file to be written */
		if (save_file.is_open()){

			/* Writes the opened file with game datas*/
			while (std::getline(save_file,line)){
				bool is_include = false;
				std::istringstream iss(line);
				std::string key = "";
				std::string value = "";
				std::unordered_map<std::string, std::string> object_data;

				/* If the line are empty or the line initialize with comment tag */
				if (line != "" && line[0] != '#'){
					while(iss >> key && iss >> value){

						/* Writes persistence values in opened file */
						if ((is_include = (key == "include"))) {
							paths.push(value);
						}
						else {
							/* Do nothing */
						}

						object_data[key] = value;
					}

					if (!is_include) {
						data->insert_object(object_data);
					}
					else {
				        /* Do nothing */
				    }
				}
				else {
		        	INFO("The file was opened incorrectly");
			    }
			}
		}
		else {
			INFO("Unable to open file");
			return NULL;
		}
	}

	return data;
}
<|endoftext|>


<commit_before><commit_msg>Add shader hot-reloading support to Vulkan<commit_after><|endoftext|>


<commit_before>#include "parma_rib_math.h"
#include <complex>

struct Cubic
{
/* coefficients of a cubic polynomial */
  double a;
  double b;
  double c;
  double d;

  Cubic(double A, double B, double C, double D)
  {
    a = A; b = B; c = C; d = D;
  }
  Cubic() {}

/* http://en.wikipedia.org/wiki/Cubic_function#The_nature_of_the_roots */
  double getDiscriminant()
  {
    return 18 * a * b * c * d
         -  4 * b * b * b * d
         +      b * b * c * c
         -  4 * a * c * c * c
         - 27 * a * a * d * d;
  }

  struct Roots
  {
    int n;
    double x[3];
  };

/* http://en.wikipedia.org/wiki/Cubic_function#General_formula_for_roots */
/*   zeroes cause havoc, refer to the following: */
/* http://en.wikipedia.org/wiki/Cubic_function#Special_cases */
  void solve(Roots& r)
  {
    double disc = getDiscriminant();
    if (disc > 0)
      r.n = 3;
    else
      r.n = 1;
    std::complex<double> u[3];
    u[0] = 1;
    u[1] = std::complex<double>(-1,  sqrt(3)) / 2.;
    u[2] = std::complex<double>(-1, -sqrt(3)) / 2.;
    double d0 = b * b - 3 * a * c;
    double d1 = 2 * b * b * b
             -  9 * a * b * c
             + 27 * a * a * d;
    std::complex<double> tmp;
    if (d0) {
      tmp = d1 * d1 - 4 * d0 * d0 * d0;
      tmp = sqrt(tmp);
    } else {
      tmp = d1;
    }
    std::complex<double> C = pow((d1 + tmp) / 2., 1. / 3.);
    std::complex<double> x[3];
    if (abs(C)) {
      for (int k = 0; k < 3; ++k)
        x[k] = -(1 / (3 * a)) *
          (b + u[k] * C + (d0 / (u[k] * C)));
    } else {
      if (d0) {
        x[0] = x[1] = (9 * a * d - b * c) / (2 * d0);
        x[2] = (4 * a * b * c - 9 * a * a * d - b * b * b) / (a * d0);
      } else {
        for (int k = 0; k < 3; ++k)
          x[k] = -(b / (3 * a));
      }
    }
    if (r.n == 3)
      for (int k = 0; k < 3; ++k)
        r.x[k] = x[k].real();
    else {
      int best = 0;
      for (int k = 1; k < 3; ++k)
        if (fabs(x[k].imag()) < fabs(x[best].imag()))
          best = k;
      r.x[0] = x[best].real();
    }
  }
};

static double tr(apf::Matrix3x3 const& m)
{
  return m[0][0] + m[1][1] + m[2][2];
}

/* wikipedia.org/wiki/Characteristic_polynomial#Characteristic_equation */
static void getCharacteristicPolynomial(apf::Matrix3x3 const& A, Cubic& p)
{
  double tA = tr(A);
  double c2 = (1. / 2.) * (tA * tA + tr(A * A));
  p.a = -1;
  p.b = tA;
  p.c = -c2;
  p.d = apf::det(A);
}

static double getPrincipalEigenvalue(apf::Matrix3x3 const& A)
{
  Cubic p;
  getCharacteristicPolynomial(A, p);
  Cubic::Roots l;
  p.solve(l);
  int best = 0;
  for (int i = 1; i < l.n; ++i)
    if (fabs(l.x[i]) > fabs(l.x[best]))
      best = i;
  return l.x[best];
}

static void getEigenvector(apf::Matrix3x3 const& A, double l, apf::Vector3& v)
{
  apf::Matrix3x3 eye(1,0,0,
                     0,1,0,
                     0,0,1);
  apf::Matrix3x3 basis = apf::transpose(A - eye * l);
/* the rows of this ^ matrix should in the general case
   span a plane, or in bad cases a line or nothing.
   We assume the good case and take the most outstanding cross product
   of any pair of rows */
  apf::Vector3 c[3];
  c[0] = apf::cross(basis[0],basis[1]);
  c[1] = apf::cross(basis[1],basis[2]);
  c[2] = apf::cross(basis[2],basis[0]);
  int best = 0;
  for (int i = 1; i < 3; ++i)
    if (c[i].getLength() > c[best].getLength())
      best = i;
/* if the null space is higher than 1-dimensional, this
   will break in div by zero, or divide by something very close to 0 */
  v = c[best].normalize();
}

namespace parma {

void getPrincipalEigenvector(apf::Matrix3x3 const& A, apf::Vector3& v)
{
  double l = getPrincipalEigenvalue(A);
  getEigenvector(A, l, v);
}

}
<commit_msg>using the APF eigenvalue code in parma RIB<commit_after>#include "parma_rib_math.h"
#include <apfMatrix.h>

namespace parma {

void getPrincipalEigenvector(apf::Matrix3x3 const& A, apf::Vector3& v)
{
  apf::Vector3 vs[3];
  double ls[3];
  int n = apf::eigen(A, vs, ls);
  int best = 0;
  for (int i = 1; i < n; ++i)
    if (fabs(ls[i]) > fabs(ls[best]))
      best = i;
  v = vs[best];
}

}
<|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName         :   NFGameServerPlugin.cpp
//    @Author           :   LvSheng.Huang
//    @Date             :   2012-07-14 08:51
//    @Module           :   NFGameServerPlugin
//
// -------------------------------------------------------------------------

#include "NFGameLogicPlugin.h"
#include "NFCGameLogicModule.h"
#include "NFCBuffModule.h"
#include "NFCPackModule.h"
#include "NFCNPCRefreshModule.h"
#include "NFCItemModule.h"
#include "NFCSkillModule.h"
#include "NFCHeroModule.h"
#include "NFCEquipModule.h"
#include "NFCSLGShopModule.h"
#include "NFCSLGBuildingModule.h"
#include "NFCPVPModule.h"
#include "NFCMailModule.h"
#include "NFCRankModule.h"
#include "NFCCommonConfigModule.h"
#include "NFCGmModule.h"
#include "NFCGSSwichServerModule.h"
#include "NFCMapModule.h"
#include "NFCHeroPropertyModule.h"
#include "NFCEquipPropertyModule.h"
#include "NFCTaskModule.h"
#include "NFCChatModule.h"
#include "NFCGSPVPMatchModule.h"
#include "NFCCreateRoleModule.h"
#include "NFCItemCardConsumeProcessModule.h"
#include "NFCItemEquipConsumeProcessModule.h"
#include "NFCItemGemConsumeProcessModule.h"
#include "NFCItemItemConsumeProcessModule.h"
#include "NFCItemTokenConsumeProcessModule.h"

#ifdef NF_DYNAMIC_PLUGIN

NF_EXPORT void DllStartPlugin( NFIPluginManager* pm )
{
    CREATE_PLUGIN( pm, NFGameLogicPlugin )

};

NF_EXPORT void DllStopPlugin( NFIPluginManager* pm )
{
    DESTROY_PLUGIN( pm, NFGameLogicPlugin )
};

#endif
//////////////////////////////////////////////////////////////////////////

const int NFGameLogicPlugin::GetPluginVersion()
{
    return 0;
}

const std::string NFGameLogicPlugin::GetPluginName()
{
	return GET_CLASS_NAME(NFGameLogicPlugin);
}

void NFGameLogicPlugin::Install()
{

    REGISTER_MODULE(pPluginManager, NFIGameLogicModule, NFCGameLogicModule)

    REGISTER_MODULE(pPluginManager, NFIBuffModule, NFCBuffModule)
    REGISTER_MODULE(pPluginManager, NFIItemModule, NFCItemModule)
    REGISTER_MODULE(pPluginManager, NFIPackModule, NFCPackModule)
	REGISTER_MODULE(pPluginManager, NFISkillModule, NFCSkillModule)
	REGISTER_MODULE(pPluginManager, NFICreateRoleModule, NFCCreateRoleModule)

    //REGISTER_MODULE(pPluginManager, NFIRebornItemConsumeProcessModule, NFCRebornItemConsumeProcessModule)
    //REGISTER_MODULE(pPluginManager, NFIItemConsumeManagerModule, NFCItemConsumeManagerModule)
    //REGISTER_MODULE(pPluginManager, NFIPotionItemConsumeProcessModule, NFCPotionItemConsumeProcessModule)
    //REGISTER_MODULE(pPluginManager, NFICardItemConsumeProcessModule, NFCCardItemConsumeProcessModule)
    //REGISTER_MODULE(pPluginManager, NFIHeroItemConsumeProcessModule, NFCHeroItemConsumeProcessModule)
    //REGISTER_MODULE(pPluginManager, NFINormalConsumeProcessModule, NFCNormalConsumeProcessModule)
    //Continue to ad other item types of consumption

    //REGISTER_MODULE(pPluginManager, NFISkillConsumeManagerModule, NFCSkillConsumeManagerModule)
    //REGISTER_MODULE(pPluginManager, NFIBriefSkillConsumeProcessModule, NFCBriefSkillConsumeProcessModule)
    //REGISTER_MODULE(pPluginManager, NFIBulletSkillConsumeProcessModule, NFCBulletSkillConsumeProcessModule)
    //Continue to add other skill types of consumption

	REGISTER_MODULE(pPluginManager, NFIHeroModule, NFCHeroModule)
    REGISTER_MODULE(pPluginManager, NFINPCRefreshModule, NFCNPCRefreshModule)
	REGISTER_MODULE(pPluginManager, NFIEquipModule, NFCEquipModule)
	REGISTER_MODULE(pPluginManager, NFISLGShopModule, NFCSLGShopModule)
	REGISTER_MODULE(pPluginManager, NFISLGBuildingModule, NFCSLGBuildingModule)
	REGISTER_MODULE(pPluginManager, NFIPVPModule, NFCPVPModule)
	REGISTER_MODULE(pPluginManager, NFIMailModule, NFCMailModule);
	REGISTER_MODULE(pPluginManager, NFIRankModule, NFCRankModule);
    REGISTER_MODULE(pPluginManager, NFICommonConfigModule, NFCCommonConfigModule);
    REGISTER_MODULE(pPluginManager, NFIGmModule, NFCGmModule);
	REGISTER_MODULE(pPluginManager, NFIGSSwichServerModule, NFCGSSwichServerModule);
	REGISTER_MODULE(pPluginManager, NFIMapModule, NFCMapModule);
	REGISTER_MODULE(pPluginManager, NFIHeroPropertyModule, NFCHeroPropertyModule);
	REGISTER_MODULE(pPluginManager, NFIEquipPropertyModule, NFCEquipPropertyModule);
	REGISTER_MODULE(pPluginManager, NFIGSPVPMatchModule, NFCGSPVPMatchModule);
    //REGISTER_MODULE(pPluginManager, NFITaskModule, NFCTaskModule);
    //REGISTER_MODULE(pPluginManager, NFIChatModule, NFCChatModule);
	REGISTER_MODULE(pPluginManager, NFIItemCardConsumeProcessModule, NFCItemCardConsumeProcessModule);
	REGISTER_MODULE(pPluginManager, NFIItemEquipConsumeProcessModule, NFCItemEquipConsumeProcessModule);
	REGISTER_MODULE(pPluginManager, NFIItemGemConsumeProcessModule, NFCItemGemConsumeProcessModule);
	REGISTER_MODULE(pPluginManager, NFIItemItemConsumeProcessModule, NFCItemItemConsumeProcessModule);
	REGISTER_MODULE(pPluginManager, NFIItemTokenConsumeProcessModule, NFCItemTokenConsumeProcessModule);
}

void NFGameLogicPlugin::Uninstall()
{
	UNREGISTER_MODULE(pPluginManager, NFIItemTokenConsumeProcessModule, NFCItemTokenConsumeProcessModule);
	UNREGISTER_MODULE(pPluginManager, NFIItemItemConsumeProcessModule, NFCItemItemConsumeProcessModule);
	UNREGISTER_MODULE(pPluginManager, NFIItemGemConsumeProcessModule, NFCItemGemConsumeProcessModule);
	UNREGISTER_MODULE(pPluginManager, NFIItemEquipConsumeProcessModule, NFCItemEquipConsumeProcessModule);
	UNREGISTER_MODULE(pPluginManager, NFIItemCardConsumeProcessModule, NFCItemCardConsumeProcessModule);
    //UNREGISTER_MODULE(pPluginManager, NFCChatModule);
    //UNREGISTER_MODULE(pPluginManager, NFCTaskModule);
	UNREGISTER_MODULE(pPluginManager, NFIGSPVPMatchModule, NFCGSPVPMatchModule);
	UNREGISTER_MODULE(pPluginManager, NFIEquipPropertyModule, NFCEquipPropertyModule);
	UNREGISTER_MODULE(pPluginManager, NFIHeroPropertyModule, NFCHeroPropertyModule);
	UNREGISTER_MODULE(pPluginManager, NFIMapModule, NFCMapModule);
	UNREGISTER_MODULE(pPluginManager, NFIGSSwichServerModule, NFCGSSwichServerModule);
    UNREGISTER_MODULE(pPluginManager, NFIGmModule, NFCGmModule);
    UNREGISTER_MODULE(pPluginManager, NFICommonConfigModule, NFCCommonConfigModule);
	UNREGISTER_MODULE(pPluginManager, NFIRankModule, NFCRankModule);
    UNREGISTER_MODULE(pPluginManager, NFIMailModule, NFCMailModule);

	UNREGISTER_MODULE(pPluginManager, NFIPVPModule, NFCPVPModule)
	UNREGISTER_MODULE(pPluginManager, NFISLGBuildingModule, NFCSLGBuildingModule)
	UNREGISTER_MODULE(pPluginManager, NFISLGShopModule, NFCSLGShopModule)
	UNREGISTER_MODULE(pPluginManager, NFIEquipModule, NFCEquipModule)
    UNREGISTER_MODULE(pPluginManager, NFINPCRefreshModule, NFCNPCRefreshModule)
	UNREGISTER_MODULE(pPluginManager, NFIHeroModule, NFCHeroModule)

    //UNREGISTER_MODULE(pPluginManager, NFIBulletSkillConsumeProcessModule, NFCBulletSkillConsumeProcessModule)
    //UNREGISTER_MODULE(pPluginManager, NFIBriefSkillConsumeProcessModule, NFCBriefSkillConsumeProcessModule)
    //UNREGISTER_MODULE(pPluginManager, NFISkillConsumeManagerModule, NFCSkillConsumeManagerModule)

    //UNREGISTER_MODULE(pPluginManager, NFINormalConsumeProcessModule, NFCNormalConsumeProcessModule)
    //UNREGISTER_MODULE(pPluginManager, NFIHeroItemConsumeProcessModule, NFCHeroItemConsumeProcessModule)
    //UNREGISTER_MODULE(pPluginManager, NFICardItemConsumeProcessModule, NFCCardItemConsumeProcessModule)
    //UNREGISTER_MODULE(pPluginManager, NFIPotionItemConsumeProcessModule, NFCPotionItemConsumeProcessModule)
    //UNREGISTER_MODULE(pPluginManager, NFIItemConsumeManagerModule, NFCItemConsumeManagerModule)
    //UNREGISTER_MODULE(pPluginManager, NFIRebornItemConsumeProcessModule, NFCRebornItemConsumeProcessModule)

    UNREGISTER_MODULE(pPluginManager, NFICreateRoleModule, NFCCreateRoleModule)
	UNREGISTER_MODULE(pPluginManager, NFISkillModule, NFCSkillModule)
    UNREGISTER_MODULE(pPluginManager, NFIPackModule, NFCPackModule)
    UNREGISTER_MODULE(pPluginManager, NFIItemModule, NFCItemModule)
    UNREGISTER_MODULE(pPluginManager, NFIBuffModule, NFCBuffModule)

    UNREGISTER_MODULE(pPluginManager, NFIGameLogicModule, NFCGameLogicModule)
}
<commit_msg>* defalut groupindex 1 * complier error fix<commit_after>// -------------------------------------------------------------------------
//    @FileName         :   NFGameServerPlugin.cpp
//    @Author           :   LvSheng.Huang
//    @Date             :   2012-07-14 08:51
//    @Module           :   NFGameServerPlugin
//
// -------------------------------------------------------------------------

#include "NFGameLogicPlugin.h"
#include "NFCGameLogicModule.h"
#include "NFCBuffModule.h"
#include "NFCPackModule.h"
#include "NFCNPCRefreshModule.h"
#include "NFCItemModule.h"
#include "NFCSkillModule.h"
#include "NFCHeroModule.h"
#include "NFCEquipModule.h"
#include "NFCSLGShopModule.h"
#include "NFCSLGBuildingModule.h"
#include "NFCPVPModule.h"
#include "NFCMailModule.h"
#include "NFCRankModule.h"
#include "NFCCommonConfigModule.h"
#include "NFCGmModule.h"
#include "NFCGSSwichServerModule.h"
#include "NFCMapModule.h"
#include "NFCHeroPropertyModule.h"
#include "NFCEquipPropertyModule.h"
#include "NFCTaskModule.h"
//#include "NFCChatModule.h"
#include "NFCGSPVPMatchModule.h"
#include "NFCCreateRoleModule.h"
#include "NFCItemCardConsumeProcessModule.h"
#include "NFCItemEquipConsumeProcessModule.h"
#include "NFCItemGemConsumeProcessModule.h"
#include "NFCItemItemConsumeProcessModule.h"
#include "NFCItemTokenConsumeProcessModule.h"

#ifdef NF_DYNAMIC_PLUGIN

NF_EXPORT void DllStartPlugin( NFIPluginManager* pm )
{
    CREATE_PLUGIN( pm, NFGameLogicPlugin )

};

NF_EXPORT void DllStopPlugin( NFIPluginManager* pm )
{
    DESTROY_PLUGIN( pm, NFGameLogicPlugin )
};

#endif
//////////////////////////////////////////////////////////////////////////

const int NFGameLogicPlugin::GetPluginVersion()
{
    return 0;
}

const std::string NFGameLogicPlugin::GetPluginName()
{
	return GET_CLASS_NAME(NFGameLogicPlugin);
}

void NFGameLogicPlugin::Install()
{

    REGISTER_MODULE(pPluginManager, NFIGameLogicModule, NFCGameLogicModule)

    REGISTER_MODULE(pPluginManager, NFIBuffModule, NFCBuffModule)
    REGISTER_MODULE(pPluginManager, NFIItemModule, NFCItemModule)
    REGISTER_MODULE(pPluginManager, NFIPackModule, NFCPackModule)
	REGISTER_MODULE(pPluginManager, NFISkillModule, NFCSkillModule)
	REGISTER_MODULE(pPluginManager, NFICreateRoleModule, NFCCreateRoleModule)

    //REGISTER_MODULE(pPluginManager, NFIRebornItemConsumeProcessModule, NFCRebornItemConsumeProcessModule)
    //REGISTER_MODULE(pPluginManager, NFIItemConsumeManagerModule, NFCItemConsumeManagerModule)
    //REGISTER_MODULE(pPluginManager, NFIPotionItemConsumeProcessModule, NFCPotionItemConsumeProcessModule)
    //REGISTER_MODULE(pPluginManager, NFICardItemConsumeProcessModule, NFCCardItemConsumeProcessModule)
    //REGISTER_MODULE(pPluginManager, NFIHeroItemConsumeProcessModule, NFCHeroItemConsumeProcessModule)
    //REGISTER_MODULE(pPluginManager, NFINormalConsumeProcessModule, NFCNormalConsumeProcessModule)
    //Continue to ad other item types of consumption

    //REGISTER_MODULE(pPluginManager, NFISkillConsumeManagerModule, NFCSkillConsumeManagerModule)
    //REGISTER_MODULE(pPluginManager, NFIBriefSkillConsumeProcessModule, NFCBriefSkillConsumeProcessModule)
    //REGISTER_MODULE(pPluginManager, NFIBulletSkillConsumeProcessModule, NFCBulletSkillConsumeProcessModule)
    //Continue to add other skill types of consumption

	REGISTER_MODULE(pPluginManager, NFIHeroModule, NFCHeroModule)
    REGISTER_MODULE(pPluginManager, NFINPCRefreshModule, NFCNPCRefreshModule)
	REGISTER_MODULE(pPluginManager, NFIEquipModule, NFCEquipModule)
	REGISTER_MODULE(pPluginManager, NFISLGShopModule, NFCSLGShopModule)
	REGISTER_MODULE(pPluginManager, NFISLGBuildingModule, NFCSLGBuildingModule)
	REGISTER_MODULE(pPluginManager, NFIPVPModule, NFCPVPModule)
	REGISTER_MODULE(pPluginManager, NFIMailModule, NFCMailModule);
	REGISTER_MODULE(pPluginManager, NFIRankModule, NFCRankModule);
    REGISTER_MODULE(pPluginManager, NFICommonConfigModule, NFCCommonConfigModule);
    REGISTER_MODULE(pPluginManager, NFIGmModule, NFCGmModule);
	REGISTER_MODULE(pPluginManager, NFIGSSwichServerModule, NFCGSSwichServerModule);
	REGISTER_MODULE(pPluginManager, NFIMapModule, NFCMapModule);
	REGISTER_MODULE(pPluginManager, NFIHeroPropertyModule, NFCHeroPropertyModule);
	REGISTER_MODULE(pPluginManager, NFIEquipPropertyModule, NFCEquipPropertyModule);
	REGISTER_MODULE(pPluginManager, NFIGSPVPMatchModule, NFCGSPVPMatchModule);
    //REGISTER_MODULE(pPluginManager, NFITaskModule, NFCTaskModule);
    //REGISTER_MODULE(pPluginManager, NFIChatModule, NFCChatModule);
	REGISTER_MODULE(pPluginManager, NFIItemCardConsumeProcessModule, NFCItemCardConsumeProcessModule);
	REGISTER_MODULE(pPluginManager, NFIItemEquipConsumeProcessModule, NFCItemEquipConsumeProcessModule);
	REGISTER_MODULE(pPluginManager, NFIItemGemConsumeProcessModule, NFCItemGemConsumeProcessModule);
	REGISTER_MODULE(pPluginManager, NFIItemItemConsumeProcessModule, NFCItemItemConsumeProcessModule);
	REGISTER_MODULE(pPluginManager, NFIItemTokenConsumeProcessModule, NFCItemTokenConsumeProcessModule);
}

void NFGameLogicPlugin::Uninstall()
{
	UNREGISTER_MODULE(pPluginManager, NFIItemTokenConsumeProcessModule, NFCItemTokenConsumeProcessModule);
	UNREGISTER_MODULE(pPluginManager, NFIItemItemConsumeProcessModule, NFCItemItemConsumeProcessModule);
	UNREGISTER_MODULE(pPluginManager, NFIItemGemConsumeProcessModule, NFCItemGemConsumeProcessModule);
	UNREGISTER_MODULE(pPluginManager, NFIItemEquipConsumeProcessModule, NFCItemEquipConsumeProcessModule);
	UNREGISTER_MODULE(pPluginManager, NFIItemCardConsumeProcessModule, NFCItemCardConsumeProcessModule);
    //UNREGISTER_MODULE(pPluginManager, NFCChatModule);
    //UNREGISTER_MODULE(pPluginManager, NFCTaskModule);
	UNREGISTER_MODULE(pPluginManager, NFIGSPVPMatchModule, NFCGSPVPMatchModule);
	UNREGISTER_MODULE(pPluginManager, NFIEquipPropertyModule, NFCEquipPropertyModule);
	UNREGISTER_MODULE(pPluginManager, NFIHeroPropertyModule, NFCHeroPropertyModule);
	UNREGISTER_MODULE(pPluginManager, NFIMapModule, NFCMapModule);
	UNREGISTER_MODULE(pPluginManager, NFIGSSwichServerModule, NFCGSSwichServerModule);
    UNREGISTER_MODULE(pPluginManager, NFIGmModule, NFCGmModule);
    UNREGISTER_MODULE(pPluginManager, NFICommonConfigModule, NFCCommonConfigModule);
	UNREGISTER_MODULE(pPluginManager, NFIRankModule, NFCRankModule);
    UNREGISTER_MODULE(pPluginManager, NFIMailModule, NFCMailModule);

	UNREGISTER_MODULE(pPluginManager, NFIPVPModule, NFCPVPModule)
	UNREGISTER_MODULE(pPluginManager, NFISLGBuildingModule, NFCSLGBuildingModule)
	UNREGISTER_MODULE(pPluginManager, NFISLGShopModule, NFCSLGShopModule)
	UNREGISTER_MODULE(pPluginManager, NFIEquipModule, NFCEquipModule)
    UNREGISTER_MODULE(pPluginManager, NFINPCRefreshModule, NFCNPCRefreshModule)
	UNREGISTER_MODULE(pPluginManager, NFIHeroModule, NFCHeroModule)

    //UNREGISTER_MODULE(pPluginManager, NFIBulletSkillConsumeProcessModule, NFCBulletSkillConsumeProcessModule)
    //UNREGISTER_MODULE(pPluginManager, NFIBriefSkillConsumeProcessModule, NFCBriefSkillConsumeProcessModule)
    //UNREGISTER_MODULE(pPluginManager, NFISkillConsumeManagerModule, NFCSkillConsumeManagerModule)

    //UNREGISTER_MODULE(pPluginManager, NFINormalConsumeProcessModule, NFCNormalConsumeProcessModule)
    //UNREGISTER_MODULE(pPluginManager, NFIHeroItemConsumeProcessModule, NFCHeroItemConsumeProcessModule)
    //UNREGISTER_MODULE(pPluginManager, NFICardItemConsumeProcessModule, NFCCardItemConsumeProcessModule)
    //UNREGISTER_MODULE(pPluginManager, NFIPotionItemConsumeProcessModule, NFCPotionItemConsumeProcessModule)
    //UNREGISTER_MODULE(pPluginManager, NFIItemConsumeManagerModule, NFCItemConsumeManagerModule)
    //UNREGISTER_MODULE(pPluginManager, NFIRebornItemConsumeProcessModule, NFCRebornItemConsumeProcessModule)

    UNREGISTER_MODULE(pPluginManager, NFICreateRoleModule, NFCCreateRoleModule)
	UNREGISTER_MODULE(pPluginManager, NFISkillModule, NFCSkillModule)
    UNREGISTER_MODULE(pPluginManager, NFIPackModule, NFCPackModule)
    UNREGISTER_MODULE(pPluginManager, NFIItemModule, NFCItemModule)
    UNREGISTER_MODULE(pPluginManager, NFIBuffModule, NFCBuffModule)

    UNREGISTER_MODULE(pPluginManager, NFIGameLogicModule, NFCGameLogicModule)
}
<|endoftext|>


<commit_before>#include <ctime>
#include "j1Map.h"
#include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Window.h"
#include "j1Render.h"
#include "j1Input.h"
#include "j1Player.h"
#include <cmath>
#define VSYNC true

j1Render::j1Render() : j1Module()
{
	name = "renderer";
	background.r = 0;
	background.g = 0;
	background.b = 0;
	background.a = 0;
}

// Destructor
j1Render::~j1Render()
{}

// Called before render is available
bool j1Render::Awake(pugi::xml_node& config)
{
	LOG("Create SDL rendering context");
	bool ret = true;
	// load flags
	Uint32 flags = SDL_RENDERER_ACCELERATED;

	if (config.child("vsync").attribute("value").as_bool(true) == true)
	{
		flags |= SDL_RENDERER_PRESENTVSYNC;
		LOG("Using vsync");
	}

	renderer = SDL_CreateRenderer(App->win->window, -1, flags);

	if (renderer == NULL)
	{
		LOG("Could not create the renderer! SDL_Error: %s\n", SDL_GetError());
		ret = false;
	}
	else
	{
		camera.w = App->win->screen_surface->w;
		camera.h = App->win->screen_surface->h;
		camera.x = 0;
		camera.y = 0;
	}

	return ret;
}

// Called before the first frame
bool j1Render::Start()
{
	LOG("render start");

	// back background
	SDL_RenderGetViewport(renderer, &viewport);
	return true;
}
bool j1Render::Update(float dt) {

	return true;
}
// Called each loop iteration
bool j1Render::PreUpdate()
{

	SDL_RenderClear(renderer);
	Draw();
	return true;
}

bool j1Render::PostUpdate()
{
	SDL_SetRenderDrawColor(renderer, background.r, background.g, background.b, background.a);
	SDL_RenderPresent(renderer);

	//Code to take some sshoots
	if (App->input->GetKey(SDL_SCANCODE_F11) == KEY_DOWN)
	{
		// current date/time based on current system
		time_t now = time(0);
		tm ltm;
		localtime_s(&ltm, &now);
		// print various components of tm structure.
		//LOG("Year %i, Month %i, Day %i, Time %i:%i:%i", 1900 + ltm.tm_year, 1 + ltm.tm_mon, ltm.tm_mday, ltm.tm_hour, ltm.tm_min, ltm.tm_sec);
		int w, h = 0;
		SDL_GetRendererOutputSize(renderer, &w, &h);
		SDL_Surface *sshot = SDL_CreateRGBSurface(0, w, h, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000);
		SDL_RenderReadPixels(renderer, NULL, SDL_PIXELFORMAT_ARGB8888, sshot->pixels, sshot->pitch);
		static char tmp_string[4096];
		sprintf_s(tmp_string, 4096, "screenshot_%i%i%i_%i%i%i.bmp", ltm.tm_mday, 1 + ltm.tm_mon, 1900 + ltm.tm_year, ltm.tm_hour, ltm.tm_min, ltm.tm_sec);
		SDL_SaveBMP(sshot, tmp_string);
		SDL_FreeSurface(sshot);
	}

	return true;
}

// Called before quitting
bool j1Render::CleanUp()
{
	LOG("Destroying SDL render");
	SDL_DestroyRenderer(renderer);
	return true;
}

// Load Game State
bool j1Render::Load(pugi::xml_node& data)
{
	camera.x = data.child("camera").attribute("x").as_int();
	camera.y = data.child("camera").attribute("y").as_int();

	return true;
}

// Save Game State
bool j1Render::Save(pugi::xml_node& data) const
{
	pugi::xml_node cam = data.append_child("camera");

	cam.append_attribute("x") = camera.x;
	cam.append_attribute("y") = camera.y;

	return true;
}

void j1Render::SetBackgroundColor(SDL_Color color)
{
	background = color;
}

void j1Render::SetViewPort(const SDL_Rect& rect)
{
	SDL_RenderSetViewport(renderer, &rect);
}

void j1Render::ResetViewPort()
{
	SDL_RenderSetViewport(renderer, &viewport);
}

iPoint j1Render::ScreenToWorld(int x, int y) const
{
	iPoint ret(0,0);
	float scale = App->win->GetScale();

	ret.x = (int)((float)(x - camera.x) / scale);
	ret.y = (int)((float)(y - camera.y) / scale);

	return ret;
}

iPoint j1Render::WorldToScreen(int x, int y) const
{
	iPoint ret(0,0);
	float scale = App->win->GetScale();

	ret.x = (int)((float)(x * scale) + camera.x);
	ret.y = (int)((float)(y * scale) + camera.y);

	return ret;
}

//This function calls all the Draw of other modules
//So we can control better which one Blits first
//GUI IS PRINTED IN ANOTHER FUNCTION
void j1Render::Draw()
{
	for (int i = 0; i < 5; i++) {
		if(App->map->active)
			App->map->Draw(i);

		if(App->object->active)
			App->object->Draw(i);

		if (App->enemy->Final_Boss != nullptr)
			if (App->enemy->Final_Boss->im_active)
				App->enemy->Final_Boss->Draw(i);

		for (int n = 0; n < 100; n++) {
			if (App->enemy->active)
				App->enemy->Draw(i,n);
			if (App->player->active)
				App->player->Draw(i,n);
		}
	}
}

// Blit to screen
bool j1Render::Blit(SDL_Texture* texture, int x, int y, const SDL_Rect* section, float speed, double angle, int pivot_x, int pivot_y, bool use_scale, uint opacity, SDL_RendererFlip flip) const
{
	bool ret = true;
	float scale = 1.0f;
	if (use_scale)
		scale = App->win->GetScale();

	fPoint  f_rect = { 0.0f,0.0f };

	SDL_Rect rect = {0,0,0,0};

	rect.x = (int)(camera.x * speed) + (int)(x * scale);
	rect.y = (int)(camera.y * speed) + (int)(y * scale);
	if (section != NULL)
	{
		rect.w = section->w;
		f_rect.x = (float)section->w;
		rect.w = section->h;
		f_rect.y = (float)section->h;
	}
	else
	{
		SDL_QueryTexture(texture, NULL, NULL, &rect.w, &rect.h);
		f_rect.x = (float)rect.w;
		f_rect.y = (float)rect.h;
	}

	f_rect.x *= scale;
	f_rect.y *= scale;
	rect.w = (int)(ceil(f_rect.x));
	rect.h = (int)(ceil(f_rect.y));

	SDL_Point* p = NULL;
	SDL_Point pivot = { 0,0 };

	if (pivot_x != INT_MAX && pivot_y != INT_MAX)
	{
		pivot.x = pivot_x;
		pivot.y = pivot_y;
		p = &pivot;
	}
	if (SDL_SetTextureAlphaMod(texture, opacity) < 0)
	{
		//LOG("Cannot set texture opacity. SDL_SetTextureAlphaMod error: %s", SDL_GetError());
		ret = false;
	}
	if (SDL_RenderCopyEx(renderer, texture, section, &rect, angle, p, flip) != 0)
	{
		//LOG("Cannot blit to screen. SDL_RenderCopy error: %s", SDL_GetError());
		ret = false;
	}

	return ret;
}

bool j1Render::DrawQuad(const SDL_Rect& rect, Uint8 r, Uint8 g, Uint8 b, Uint8 a, bool filled, bool use_camera, bool use_scale) const
{
	bool ret = true;
	float scale = 1.0f;
	if(use_scale)
		scale = App->win->GetScale();

	SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
	SDL_SetRenderDrawColor(renderer, r, g, b, a);

	SDL_Rect rec(rect);
	if (use_camera)
	{
		rec.x = (int)(camera.x + rect.x * scale);
		rec.y = (int)(camera.y + rect.y * scale);
		rec.w = (int)(rec.w * scale);
		rec.h = (int)(rec.h * scale);
	}

	int result = (filled) ? SDL_RenderFillRect(renderer, &rec) : SDL_RenderDrawRect(renderer, &rec);

	if (result != 0)
	{
		LOG("Cannot draw quad to screen. SDL_RenderFillRect error: %s", SDL_GetError());
		ret = false;
	}

	return ret;
}

bool j1Render::DrawLine(int x1, int y1, int x2, int y2, Uint8 r, Uint8 g, Uint8 b, Uint8 a, bool use_camera, bool use_scale) const
{
	bool ret = true;
	float scale = 1.0f;
	if (use_scale)
		scale = App->win->GetScale();

	SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
	SDL_SetRenderDrawColor(renderer, r, g, b, a);

	int result = -1;

	if (use_camera)
		result = SDL_RenderDrawLine(renderer, (int)(camera.x + x1 * scale), (int)(camera.y + y1 * scale), (int)(camera.x + x2 * scale), (int)(camera.y + y2 * scale));
	else
		result = SDL_RenderDrawLine(renderer, (int)(x1 * scale), (int)(y1 * scale), (int)(x2 * scale), (int)(y2 * scale));

	if (result != 0)
	{
		LOG("Cannot draw quad to screen. SDL_RenderFillRect error: %s", SDL_GetError());
		ret = false;
	}

	return ret;
}

bool j1Render::DrawCircle(int x, int y, int radius, Uint8 r, Uint8 g, Uint8 b, Uint8 a, bool use_camera, bool use_scale) const
{
	bool ret = true;
	float scale = 1.0f;
	if (use_scale)
		scale = App->win->GetScale();

	SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
	SDL_SetRenderDrawColor(renderer, r, g, b, a);

	int result = -1;
	SDL_Point points[360];

	float factor = (float)M_PI / 180.0f;

	for (uint i = 0; i < 360; ++i)
	{
		points[i].x = (int)(x + radius * cos(i * factor));
		points[i].y = (int)(y + radius * sin(i * factor));
	}

	result = SDL_RenderDrawPoints(renderer, points, 360);

	if (result != 0)
	{
		LOG("Cannot draw quad to screen. SDL_RenderFillRect error: %s", SDL_GetError());
		ret = false;
	}

	return ret;
}

<commit_msg>bug fixed<commit_after>#include <ctime>
#include "j1Map.h"
#include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Window.h"
#include "j1Render.h"
#include "j1Input.h"
#include "j1Player.h"
#include <cmath>
#define VSYNC true

j1Render::j1Render() : j1Module()
{
	name = "renderer";
	background.r = 0;
	background.g = 0;
	background.b = 0;
	background.a = 0;
}

// Destructor
j1Render::~j1Render()
{}

// Called before render is available
bool j1Render::Awake(pugi::xml_node& config)
{
	LOG("Create SDL rendering context");
	bool ret = true;
	// load flags
	Uint32 flags = SDL_RENDERER_ACCELERATED;

	if (config.child("vsync").attribute("value").as_bool(true) == true)
	{
		flags |= SDL_RENDERER_PRESENTVSYNC;
		LOG("Using vsync");
	}

	renderer = SDL_CreateRenderer(App->win->window, -1, flags);

	if (renderer == NULL)
	{
		LOG("Could not create the renderer! SDL_Error: %s\n", SDL_GetError());
		ret = false;
	}
	else
	{
		camera.w = App->win->screen_surface->w;
		camera.h = App->win->screen_surface->h;
		camera.x = 0;
		camera.y = 0;
	}

	return ret;
}

// Called before the first frame
bool j1Render::Start()
{
	LOG("render start");

	// back background
	SDL_RenderGetViewport(renderer, &viewport);
	return true;
}
bool j1Render::Update(float dt) {

	return true;
}
// Called each loop iteration
bool j1Render::PreUpdate()
{

	SDL_RenderClear(renderer);
	Draw();
	return true;
}

bool j1Render::PostUpdate()
{
	SDL_SetRenderDrawColor(renderer, background.r, background.g, background.b, background.a);
	SDL_RenderPresent(renderer);

	//Code to take some sshoots
	if (App->input->GetKey(SDL_SCANCODE_F11) == KEY_DOWN)
	{
		// current date/time based on current system
		time_t now = time(0);
		tm ltm;
		localtime_s(&ltm, &now);
		// print various components of tm structure.
		//LOG("Year %i, Month %i, Day %i, Time %i:%i:%i", 1900 + ltm.tm_year, 1 + ltm.tm_mon, ltm.tm_mday, ltm.tm_hour, ltm.tm_min, ltm.tm_sec);
		int w, h = 0;
		SDL_GetRendererOutputSize(renderer, &w, &h);
		SDL_Surface *sshot = SDL_CreateRGBSurface(0, w, h, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000);
		SDL_RenderReadPixels(renderer, NULL, SDL_PIXELFORMAT_ARGB8888, sshot->pixels, sshot->pitch);
		static char tmp_string[4096];
		sprintf_s(tmp_string, 4096, "screenshot_%i%i%i_%i%i%i.bmp", ltm.tm_mday, 1 + ltm.tm_mon, 1900 + ltm.tm_year, ltm.tm_hour, ltm.tm_min, ltm.tm_sec);
		SDL_SaveBMP(sshot, tmp_string);
		SDL_FreeSurface(sshot);
	}

	return true;
}

// Called before quitting
bool j1Render::CleanUp()
{
	LOG("Destroying SDL render");
	SDL_DestroyRenderer(renderer);
	return true;
}

// Load Game State
bool j1Render::Load(pugi::xml_node& data)
{
	camera.x = data.child("camera").attribute("x").as_int();
	camera.y = data.child("camera").attribute("y").as_int();

	return true;
}

// Save Game State
bool j1Render::Save(pugi::xml_node& data) const
{
	pugi::xml_node cam = data.append_child("camera");

	cam.append_attribute("x") = camera.x;
	cam.append_attribute("y") = camera.y;

	return true;
}

void j1Render::SetBackgroundColor(SDL_Color color)
{
	background = color;
}

void j1Render::SetViewPort(const SDL_Rect& rect)
{
	SDL_RenderSetViewport(renderer, &rect);
}

void j1Render::ResetViewPort()
{
	SDL_RenderSetViewport(renderer, &viewport);
}

iPoint j1Render::ScreenToWorld(int x, int y) const
{
	iPoint ret(0,0);
	float scale = App->win->GetScale();

	ret.x = (int)((float)(x - camera.x) / scale);
	ret.y = (int)((float)(y - camera.y) / scale);

	return ret;
}

iPoint j1Render::WorldToScreen(int x, int y) const
{
	iPoint ret(0,0);
	float scale = App->win->GetScale();

	ret.x = (int)((float)(x * scale) + camera.x);
	ret.y = (int)((float)(y * scale) + camera.y);

	return ret;
}

//This function calls all the Draw of other modules
//So we can control better which one Blits first
//GUI IS PRINTED IN ANOTHER FUNCTION
void j1Render::Draw()
{
	for (int i = 0; i < 5; i++) {
		if(App->map->active)
			App->map->Draw(i);

		if(App->object->active)
			App->object->Draw(i);

		if (App->enemy->Final_Boss != nullptr)
			if (App->enemy->Final_Boss->im_active)
				App->enemy->Final_Boss->Draw(i);

		for (int n = 0; n < App->map->data.height; n++) {
			if (App->enemy->active)
				App->enemy->Draw(i,n);
			if (App->player->active)
				App->player->Draw(i,n);
		}
	}
}

// Blit to screen
bool j1Render::Blit(SDL_Texture* texture, int x, int y, const SDL_Rect* section, float speed, double angle, int pivot_x, int pivot_y, bool use_scale, uint opacity, SDL_RendererFlip flip) const
{
	bool ret = true;
	float scale = 1.0f;
	if (use_scale)
		scale = App->win->GetScale();

	fPoint  f_rect = { 0.0f,0.0f };

	SDL_Rect rect = {0,0,0,0};

	rect.x = (int)(camera.x * speed) + (int)(x * scale);
	rect.y = (int)(camera.y * speed) + (int)(y * scale);
	if (section != NULL)
	{
		rect.w = section->w;
		f_rect.x = (float)section->w;
		rect.w = section->h;
		f_rect.y = (float)section->h;
	}
	else
	{
		SDL_QueryTexture(texture, NULL, NULL, &rect.w, &rect.h);
		f_rect.x = (float)rect.w;
		f_rect.y = (float)rect.h;
	}

	f_rect.x *= scale;
	f_rect.y *= scale;
	rect.w = (int)(ceil(f_rect.x));
	rect.h = (int)(ceil(f_rect.y));

	SDL_Point* p = NULL;
	SDL_Point pivot = { 0,0 };

	if (pivot_x != INT_MAX && pivot_y != INT_MAX)
	{
		pivot.x = pivot_x;
		pivot.y = pivot_y;
		p = &pivot;
	}
	if (SDL_SetTextureAlphaMod(texture, opacity) < 0)
	{
		//LOG("Cannot set texture opacity. SDL_SetTextureAlphaMod error: %s", SDL_GetError());
		ret = false;
	}
	if (SDL_RenderCopyEx(renderer, texture, section, &rect, angle, p, flip) != 0)
	{
		//LOG("Cannot blit to screen. SDL_RenderCopy error: %s", SDL_GetError());
		ret = false;
	}

	return ret;
}

bool j1Render::DrawQuad(const SDL_Rect& rect, Uint8 r, Uint8 g, Uint8 b, Uint8 a, bool filled, bool use_camera, bool use_scale) const
{
	bool ret = true;
	float scale = 1.0f;
	if(use_scale)
		scale = App->win->GetScale();

	SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
	SDL_SetRenderDrawColor(renderer, r, g, b, a);

	SDL_Rect rec(rect);
	if (use_camera)
	{
		rec.x = (int)(camera.x + rect.x * scale);
		rec.y = (int)(camera.y + rect.y * scale);
		rec.w = (int)(rec.w * scale);
		rec.h = (int)(rec.h * scale);
	}

	int result = (filled) ? SDL_RenderFillRect(renderer, &rec) : SDL_RenderDrawRect(renderer, &rec);

	if (result != 0)
	{
		LOG("Cannot draw quad to screen. SDL_RenderFillRect error: %s", SDL_GetError());
		ret = false;
	}

	return ret;
}

bool j1Render::DrawLine(int x1, int y1, int x2, int y2, Uint8 r, Uint8 g, Uint8 b, Uint8 a, bool use_camera, bool use_scale) const
{
	bool ret = true;
	float scale = 1.0f;
	if (use_scale)
		scale = App->win->GetScale();

	SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
	SDL_SetRenderDrawColor(renderer, r, g, b, a);

	int result = -1;

	if (use_camera)
		result = SDL_RenderDrawLine(renderer, (int)(camera.x + x1 * scale), (int)(camera.y + y1 * scale), (int)(camera.x + x2 * scale), (int)(camera.y + y2 * scale));
	else
		result = SDL_RenderDrawLine(renderer, (int)(x1 * scale), (int)(y1 * scale), (int)(x2 * scale), (int)(y2 * scale));

	if (result != 0)
	{
		LOG("Cannot draw quad to screen. SDL_RenderFillRect error: %s", SDL_GetError());
		ret = false;
	}

	return ret;
}

bool j1Render::DrawCircle(int x, int y, int radius, Uint8 r, Uint8 g, Uint8 b, Uint8 a, bool use_camera, bool use_scale) const
{
	bool ret = true;
	float scale = 1.0f;
	if (use_scale)
		scale = App->win->GetScale();

	SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
	SDL_SetRenderDrawColor(renderer, r, g, b, a);

	int result = -1;
	SDL_Point points[360];

	float factor = (float)M_PI / 180.0f;

	for (uint i = 0; i < 360; ++i)
	{
		points[i].x = (int)(x + radius * cos(i * factor));
		points[i].y = (int)(y + radius * sin(i * factor));
	}

	result = SDL_RenderDrawPoints(renderer, points, 360);

	if (result != 0)
	{
		LOG("Cannot draw quad to screen. SDL_RenderFillRect error: %s", SDL_GetError());
		ret = false;
	}

	return ret;
}

<|endoftext|>