<commit_before>#include "../cshared/shared.h"
#include "../cshared/disasm.h"
#include "../cshared/stream.h"

FILE *output = stdout;

struct DisasmContext
{
    std::vector<std::string> section_labels;
    std::map<int, std::string> labels;
};

struct StreamReader : public BaseReader
{
    Stream &stream;
    StreamReader(Stream &stream, uint64_t &position) : BaseReader(position), stream(stream)
    {
    }

    virtual uint64_t raw_read(void *buffer, uint64_t size) override
    {
        auto raw_data   = stream.raw_base_data();
        auto length     = stream.raw_base_length();
        auto offset     = position();
        auto max_length = std::min(size, length - offset);

        memcpy(buffer, raw_data + offset, (size_t)max_length);

        return max_length;
    }

    bool feof()
    {
        return stream.eof();
    }
};

void parse_substream(Stream &stream, uint64_t start, bool no_numbers)
{
    uint64_t                      position = 0;
    StreamReader                  reader(stream, position);
    DisasmProcessor<StreamReader> processor(reader);

    fprintf(stderr, "cdisasm: parse substream %d bytes\n", (int)stream.length());
    processor.go([start, no_numbers](uint64_t pos, std::string info) {
        if (no_numbers)
        {
            fprintf(output, "    ");
        }
        else
        {
            fprintf(output, "%8" PRIu64 ": ", start + pos);
        }
        fprintf(output, "%s\n", info.c_str());
    });
}

void parse_data_substream(Stream &input_stream, uint64_t start, bool no_numbers)
{
    uint64_t     position = 0;
    StreamReader reader(input_stream, position);

    AsmStream<StreamReader> stream(reader);

    std::string string;
    bool        use_string = false;
    uint64_t    string_pos = 0;

    while (true)
    {
        try
        {
            auto          pos   = stream.position();
            unsigned char byte  = stream.read_uint8();
            bool          ascii = byte >= 32 && byte <= 127;

            if (ascii)
            {
                if (!use_string)
                {
                    string_pos = pos;
                }
                use_string = true;
                string += byte;
            }
            else if (use_string)
            {
                use_string = false;
                if (byte == 0)
                {
                    if (!no_numbers)
                    {
                        fprintf(output, "%8" PRIu64 ": ", start + string_pos);
                    }
                    else
                    {
                        fprintf(output, "    ");
                    }
                    fprintf(output, "W_STRING \"%s\"\n", string.c_str());
                }
                else
                {
                    size_t i = 0;
                    for (auto ch : string)
                    {
                        if (!no_numbers)
                        {
                            fprintf(output, "%8" PRIu64 ": ", start + string_pos + i);
                        }
                        else
                        {
                            fprintf(output, "    ");
                        }
                        fprintf(output, "W_BYTE %d\n", (int)ch);
                        i++;
                    }

                    if (!no_numbers)
                    {
                        fprintf(output, "%8" PRIu64 ": ", start + string_pos);
                    }
                    else
                    {
                        fprintf(output, "    ");
                    }
                    fprintf(output, "W_BYTE %d\n", (int)byte);
                }
                string = "";
            }
            else
            {
                if (!no_numbers)
                {
                    fprintf(output, "%8" PRIu64 ": ", start + pos);
                }
                else
                {
                    fprintf(output, "    ");
                }
                fprintf(output, "W_BYTE %d\n", (int)byte);
            }
        }
        catch (EOFError)
        {
            assert(!use_string);
            break;
        }
    }
}

void parse_symbol_substream(Stream &input_stream, uint64_t start, bool no_numbers)
{
    uint64_t     position = 0;
    StreamReader reader(input_stream, position);

    AsmStream<StreamReader> stream(reader);

    while (true)
    {
        try
        {
            auto pos    = stream.position();
            auto symbol = stream.read_uint64();
            if (!no_numbers)
            {
                fprintf(output, "%8" PRIu64 ": ", start + pos);
            }
            else
            {
                fprintf(output, "    ");
            }
            fprintf(output, "W_SYMBOL %" PRIu64 "\n", symbol);
        }
        catch (EOFError)
        {
            break;
        }
    }
}

void parse_func_substream(Stream &input_stream)
{
    uint64_t     position = 0;
    StreamReader reader(input_stream, position);

    AsmStream<StreamReader> stream(reader);

    while (true)
    {
        try
        {
            auto symbol      = stream.read_uint16();
            auto class_index = stream.read_int16();
            auto address     = stream.read_uint64();
            fprintf(output, "    W_METHOD %" PRIu16 ", %" PRId16 ", %" PRIu64 "\n", symbol,
                    class_index, address);
        }
        catch (EOFError)
        {
            break;
        }
    }
}

// TODO: move to Stream
void read_stream(Stream &stream, FILE *input = stdin, bool close_input = false)
{
#ifdef DAB_PLATFORM_WINDOWS
    if (input == stdin)
    {
        freopen(NULL, "rb", input);
    }
#endif
    byte buffer[1024];
    while (!feof(input))
    {
        size_t bytes = fread(buffer, 1, 1024, input);
        if (bytes)
        {
            stream.append(buffer, bytes);
        }
    }
    if (close_input)
    {
        fclose(input);
    }
}

bool parse_bool_arg(int argc, char **argv, const std::string &arg)
{
    for (int i = 1; i < argc; i++)
    {
        if (arg == argv[i])
            return true;
    }
    return false;
}

void parse_headers(DisasmContext &context, BinHeader *base_header)
{
    auto *header   = &base_header->header;
    auto *sections = base_header->sections;

    fprintf(output, "/* disasm */\n");
    fprintf(output, "    W_HEADER %d\n", (int)header->version);
    fprintf(output, "    W_OFFSET %" PRIu64 "\n", (uint64_t)header->offset);
    for (size_t i = 0; i < header->section_count; i++)
    {
        auto section = sections[i];

        std::string label_name = std::string("_") + section.name;
        std::transform(label_name.begin(), label_name.end(), label_name.begin(), ::toupperc);

        auto base_label_name = label_name;
        int  label_counter   = 2;

        while (true)
        {
            if (!std::count(context.section_labels.begin(), context.section_labels.end(),
                            label_name))
            {
                break;
            }
            char number[8];
            snprintf(number, sizeof(number), "%d", label_counter++);
            label_name = base_label_name + number;
        }

        context.section_labels.push_back(label_name);

        fprintf(output, "    W_SECTION %s, \"%s\"\n", label_name.c_str(), section.name);
    }
    fprintf(output, "    W_END_HEADER\n\n");
}

int main(int argc, char **argv)
{
    DisasmContext context;

    bool raw          = parse_bool_arg(argc, argv, "--raw");
    bool with_headers = parse_bool_arg(argc, argv, "--with-headers");
    bool no_numbers   = parse_bool_arg(argc, argv, "--no-numbers");

    FILE *input       = stdin;
    bool  close_input = false;

    for (int argn = 1; argn < argc; argn++)
    {
        auto arg = argv[argn];
        if (strstr(arg, "--") == NULL)
        {
            input       = fopen(arg, "rb");
            close_input = true;
        }
    }

    Stream stream;
    read_stream(stream, input, close_input);

    if (raw)
    {
        parse_substream(stream, 0, no_numbers);
    }
    else
    {
        auto base_header = stream.peek_header();
        auto header      = &base_header->header;
        auto sections    = base_header->sections;

        fprintf(stderr, "cdisasm: %d sections\n", (int)header->section_count);
        if (with_headers)
        {
            parse_headers(context, base_header);
        }

        for (size_t i = 0; i < header->section_count; i++)
        {
            auto section = sections[i];
            fprintf(stderr, "cdisasm: section[%d] '%s'\n", (int)i, section.name);

            if (with_headers)
            {
                fprintf(output, "%s:\n", context.section_labels[i].c_str());
            }

            std::string section_name = section.name;
            auto        substream    = stream.section_stream(i);

            if (section_name == "code")
            {
                parse_substream(substream, section.pos, no_numbers);
            }
            else if (with_headers && (section_name == "data" || section_name == "symd"))
            {
                parse_data_substream(substream, section.pos, no_numbers);
            }
            else if (with_headers && section_name == "symb")
            {
                parse_symbol_substream(substream, section.pos, no_numbers);
            }
            else if (with_headers && section_name == "func")
            {
                parse_func_substream(substream);
            }

            if (with_headers)
            {
                fprintf(output, "\n");
            }
        }
    }

    return 0;
}
<commit_msg>disasm: error handling<commit_after>#include "../cshared/shared.h"
#include "../cshared/disasm.h"
#include "../cshared/stream.h"

FILE *output = stdout;

struct DisasmContext
{
    std::vector<std::string> section_labels;
    std::map<int, std::string> labels;
};

struct StreamReader : public BaseReader
{
    Stream &stream;
    StreamReader(Stream &stream, uint64_t &position) : BaseReader(position), stream(stream)
    {
    }

    virtual uint64_t raw_read(void *buffer, uint64_t size) override
    {
        auto raw_data   = stream.raw_base_data();
        auto length     = stream.raw_base_length();
        auto offset     = position();
        auto max_length = std::min(size, length - offset);

        memcpy(buffer, raw_data + offset, (size_t)max_length);

        return max_length;
    }

    bool feof()
    {
        return stream.eof();
    }
};

void parse_substream(Stream &stream, uint64_t start, bool no_numbers)
{
    uint64_t                      position = 0;
    StreamReader                  reader(stream, position);
    DisasmProcessor<StreamReader> processor(reader);

    fprintf(stderr, "cdisasm: parse substream %d bytes\n", (int)stream.length());
    processor.go([start, no_numbers](uint64_t pos, std::string info) {
        if (no_numbers)
        {
            fprintf(output, "    ");
        }
        else
        {
            fprintf(output, "%8" PRIu64 ": ", start + pos);
        }
        fprintf(output, "%s\n", info.c_str());
    });
}

void parse_data_substream(Stream &input_stream, uint64_t start, bool no_numbers)
{
    uint64_t     position = 0;
    StreamReader reader(input_stream, position);

    AsmStream<StreamReader> stream(reader);

    std::string string;
    bool        use_string = false;
    uint64_t    string_pos = 0;

    while (true)
    {
        try
        {
            auto          pos   = stream.position();
            unsigned char byte  = stream.read_uint8();
            bool          ascii = byte >= 32 && byte <= 127;

            if (ascii)
            {
                if (!use_string)
                {
                    string_pos = pos;
                }
                use_string = true;
                string += byte;
            }
            else if (use_string)
            {
                use_string = false;
                if (byte == 0)
                {
                    if (!no_numbers)
                    {
                        fprintf(output, "%8" PRIu64 ": ", start + string_pos);
                    }
                    else
                    {
                        fprintf(output, "    ");
                    }
                    fprintf(output, "W_STRING \"%s\"\n", string.c_str());
                }
                else
                {
                    size_t i = 0;
                    for (auto ch : string)
                    {
                        if (!no_numbers)
                        {
                            fprintf(output, "%8" PRIu64 ": ", start + string_pos + i);
                        }
                        else
                        {
                            fprintf(output, "    ");
                        }
                        fprintf(output, "W_BYTE %d\n", (int)ch);
                        i++;
                    }

                    if (!no_numbers)
                    {
                        fprintf(output, "%8" PRIu64 ": ", start + string_pos);
                    }
                    else
                    {
                        fprintf(output, "    ");
                    }
                    fprintf(output, "W_BYTE %d\n", (int)byte);
                }
                string = "";
            }
            else
            {
                if (!no_numbers)
                {
                    fprintf(output, "%8" PRIu64 ": ", start + pos);
                }
                else
                {
                    fprintf(output, "    ");
                }
                fprintf(output, "W_BYTE %d\n", (int)byte);
            }
        }
        catch (EOFError)
        {
            assert(!use_string);
            break;
        }
    }
}

void parse_symbol_substream(Stream &input_stream, uint64_t start, bool no_numbers)
{
    uint64_t     position = 0;
    StreamReader reader(input_stream, position);

    AsmStream<StreamReader> stream(reader);

    while (true)
    {
        try
        {
            auto pos    = stream.position();
            auto symbol = stream.read_uint64();
            if (!no_numbers)
            {
                fprintf(output, "%8" PRIu64 ": ", start + pos);
            }
            else
            {
                fprintf(output, "    ");
            }
            fprintf(output, "W_SYMBOL %" PRIu64 "\n", symbol);
        }
        catch (EOFError)
        {
            break;
        }
    }
}

void parse_func_substream(Stream &input_stream)
{
    uint64_t     position = 0;
    StreamReader reader(input_stream, position);

    AsmStream<StreamReader> stream(reader);

    while (true)
    {
        try
        {
            auto symbol      = stream.read_uint16();
            auto class_index = stream.read_int16();
            auto address     = stream.read_uint64();
            fprintf(output, "    W_METHOD %" PRIu16 ", %" PRId16 ", %" PRIu64 "\n", symbol,
                    class_index, address);
        }
        catch (EOFError)
        {
            break;
        }
    }
}

// TODO: move to Stream
void read_stream(Stream &stream, FILE *input = stdin, bool close_input = false)
{
#ifdef DAB_PLATFORM_WINDOWS
    if (input == stdin)
    {
        freopen(NULL, "rb", input);
    }
#endif
    byte buffer[1024];
    while (!feof(input))
    {
        size_t bytes = fread(buffer, 1, 1024, input);
        if (bytes)
        {
            stream.append(buffer, bytes);
        }
    }
    if (close_input)
    {
        fclose(input);
    }
}

bool parse_bool_arg(int argc, char **argv, const std::string &arg)
{
    for (int i = 1; i < argc; i++)
    {
        if (arg == argv[i])
            return true;
    }
    return false;
}

void parse_headers(DisasmContext &context, BinHeader *base_header)
{
    auto *header   = &base_header->header;
    auto *sections = base_header->sections;

    fprintf(output, "/* disasm */\n");
    fprintf(output, "    W_HEADER %d\n", (int)header->version);
    fprintf(output, "    W_OFFSET %" PRIu64 "\n", (uint64_t)header->offset);
    for (size_t i = 0; i < header->section_count; i++)
    {
        auto section = sections[i];

        std::string label_name = std::string("_") + section.name;
        std::transform(label_name.begin(), label_name.end(), label_name.begin(), ::toupperc);

        auto base_label_name = label_name;
        int  label_counter   = 2;

        while (true)
        {
            if (!std::count(context.section_labels.begin(), context.section_labels.end(),
                            label_name))
            {
                break;
            }
            char number[8];
            snprintf(number, sizeof(number), "%d", label_counter++);
            label_name = base_label_name + number;
        }

        context.section_labels.push_back(label_name);

        fprintf(output, "    W_SECTION %s, \"%s\"\n", label_name.c_str(), section.name);
    }
    fprintf(output, "    W_END_HEADER\n\n");
}

int main(int argc, char **argv)
{
    DisasmContext context;

    bool raw          = parse_bool_arg(argc, argv, "--raw");
    bool with_headers = parse_bool_arg(argc, argv, "--with-headers");
    bool no_numbers   = parse_bool_arg(argc, argv, "--no-numbers");

    FILE *input       = stdin;
    bool  close_input = false;

    for (int argn = 1; argn < argc; argn++)
    {
        auto arg = argv[argn];
        if (strstr(arg, "--") == NULL)
        {
            input       = fopen(arg, "rb");
            close_input = true;

            if (!input)
            {
                fprintf(stderr, "disasm: error: cannot open file <%s> for reading.\n", arg);
                exit(1);
            }
        }
    }

    Stream stream;
    read_stream(stream, input, close_input);

    if (raw)
    {
        parse_substream(stream, 0, no_numbers);
    }
    else
    {
        auto base_header = stream.peek_header();
        auto header      = &base_header->header;
        auto sections    = base_header->sections;

        fprintf(stderr, "cdisasm: %d sections\n", (int)header->section_count);
        if (with_headers)
        {
            parse_headers(context, base_header);
        }

        for (size_t i = 0; i < header->section_count; i++)
        {
            auto section = sections[i];
            fprintf(stderr, "cdisasm: section[%d] '%s'\n", (int)i, section.name);

            if (with_headers)
            {
                fprintf(output, "%s:\n", context.section_labels[i].c_str());
            }

            std::string section_name = section.name;
            auto        substream    = stream.section_stream(i);

            if (section_name == "code")
            {
                parse_substream(substream, section.pos, no_numbers);
            }
            else if (with_headers && (section_name == "data" || section_name == "symd"))
            {
                parse_data_substream(substream, section.pos, no_numbers);
            }
            else if (with_headers && section_name == "symb")
            {
                parse_symbol_substream(substream, section.pos, no_numbers);
            }
            else if (with_headers && section_name == "func")
            {
                parse_func_substream(substream);
            }

            if (with_headers)
            {
                fprintf(output, "\n");
            }
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "party.h"
#include "user.h"
#include "ccharserver.h"
#include "logconsole.h"

std::shared_ptr<Party> cache_fetch_party(uint32_t charId) {
  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyTable partyTable{};
  Core::PartyMembersTable partyMembersTable{};

  auto res = conn(sqlpp::select(sqlpp::all_of(partyTable)).from(
    partyMembersTable.join(partyTable).on(partyMembersTable.id == partyTable.id))
                  .where(partyMembersTable.memberId == charId));

  if (res.empty()) {
    return {};
  }
  auto& result = res.front();

  Party party;
  party.id = result.id;
  party.name = result.name;
  party.leader = result.leaderId;
  party.options = result.options;
  party.level = result.level;
  party.last_got_item_index = result.lastGotItemIndex;
  party.last_got_zuly_index = result.lastGotZulyIndex;
  party.last_got_etc_index = result.lastGotEtcIndex;

  // now we fetch all party members
  auto res2 = conn(sqlpp::select(partyMembersTable.memberId).from(partyMembersTable)
                   .where(partyMembersTable.id == party.id).order_by(partyMembersTable.rank.desc()));

  if (res.empty()) {
    return {};
  }

  for (const auto& r : res2) {
    party.members.push_back(r.memberId);
  }

  return std::make_shared<Party>(party);
}

void cache_create_party(std::shared_ptr<Party> party) {
  if (!party) return;

  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyTable partyTable{};

  conn(sqlpp::insert_into(partyTable)
       .set(partyTable.name = party->name,
       partyTable.leaderId = party->leader,
       partyTable.options = party->options,
       partyTable.level = party->level,
       partyTable.lastGotItemIndex = party->last_got_item_index,
       partyTable.lastGotEtcIndex = party->last_got_etc_index,
       partyTable.lastGotZulyIndex = party->last_got_zuly_index));
}

void cache_write_party(std::shared_ptr<Party> party) {
  if (!party) return;
  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyTable partyTable{};

  conn(sqlpp::update(partyTable)
       .set(partyTable.name = party->name,
       partyTable.leaderId = party->leader,
       partyTable.options = party->options,
       partyTable.level = party->level,
       partyTable.lastGotItemIndex = party->last_got_item_index,
       partyTable.lastGotEtcIndex = party->last_got_etc_index,
       partyTable.lastGotZulyIndex = party->last_got_zuly_index)
       .where(partyTable.id == party->id));
}

void cache_write_party_members(std::shared_ptr<Party> party) {
  if (!party) return;
  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyMembersTable partyMembersTable{};

  conn(sqlpp::remove_from(partyMembersTable).where(partyMembersTable.id == party->id));
  auto insert = sqlpp::insert_into(partyMembersTable).columns(partyMembersTable.id, partyMembersTable.memberId);
  for (auto m : party-> members) {
    insert.values.add(partyMembersTable.id = party->id, partyMembersTable.memberId = static_cast<int>(m));
  }
  conn(insert);
}

void cache_remove_party(std::shared_ptr<Party> party) {
  if (!party) return;
  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyTable partyTable{};

  conn(sqlpp::remove_from(partyTable).where(partyTable.id == party->id));
}

void party_request(const RoseCommon::Packet::CliPartyReq& packet, CCharServer& server, User& user) {
    auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();
    logger->trace("party_request({})", user.get_charId());

    using namespace RoseCommon::Packet;
    switch (packet.get_request()) {
        case CliPartyReq::MAKE: // idXorTag == id
        {
            auto other = server.get_user(packet.get_idXorTag(), user.get_mapId());
            if (!other) {
              logger->warn("User ({}, {}) doesn't exist", packet.get_idXorTag(), user.get_mapId());
              return;
            }
            logger->debug("{} wants to make a party with {}", user.get_name(), other.value()->get_name());
            break;
        }
        case CliPartyReq::JOIN: // idXorTag == id
        {
            auto other = server.get_user(packet.get_idXorTag(), user.get_mapId());
            if (!other) {
              logger->warn("User ({}, {}) doesn't exist", packet.get_idXorTag(), user.get_mapId());
              return;
            }
            logger->debug("{} wants to join {}'s party", user.get_name(), other.value()->get_name());
            break;
        }
        case CliPartyReq::LEFT: // idXorTag == tag
        {
            logger->debug("{} left the party", user.get_name());
            break;
        }
        case CliPartyReq::CHANGE_OWNER: // idXorTag == tag
        {
            auto other = server.get_user(packet.get_idXorTag());
            if (!other) {
              logger->warn("User {} doesn't exist", packet.get_idXorTag());
              return;
            }
            logger->debug("{} wants to make {} the owner", user.get_name(), other.value()->get_name());
            break;
        }
        case CliPartyReq::KICK: // idXorTag == tag
        {
            auto other = server.get_user(packet.get_idXorTag());
            if (!other) {
              logger->warn("User {} doesn't exist", packet.get_idXorTag());
              return;
            }
            logger->debug("{} wants kick {}", user.get_name(), other.value()->get_name());
            break;
        }
        default:
            logger->warn("Client {} sent a non valid request code {}", charId, packet.get_request());
    }
}
<commit_msg>Update party.cpp<commit_after>#include "party.h"
#include "user.h"
#include "ccharserver.h"
#include "logconsole.h"

std::shared_ptr<Party> cache_fetch_party(uint32_t charId) {
  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyTable partyTable{};
  Core::PartyMembersTable partyMembersTable{};

  auto res = conn(sqlpp::select(sqlpp::all_of(partyTable)).from(
    partyMembersTable.join(partyTable).on(partyMembersTable.id == partyTable.id))
                  .where(partyMembersTable.memberId == charId));

  if (res.empty()) {
    return {};
  }
  auto& result = res.front();

  Party party;
  party.id = result.id;
  party.name = result.name;
  party.leader = result.leaderId;
  party.options = result.options;
  party.level = result.level;
  party.last_got_item_index = result.lastGotItemIndex;
  party.last_got_zuly_index = result.lastGotZulyIndex;
  party.last_got_etc_index = result.lastGotEtcIndex;

  // now we fetch all party members
  auto res2 = conn(sqlpp::select(partyMembersTable.memberId).from(partyMembersTable)
                   .where(partyMembersTable.id == party.id).order_by(partyMembersTable.rank.desc()));

  if (res.empty()) {
    return {};
  }

  for (const auto& r : res2) {
    party.members.push_back(r.memberId);
  }

  return std::make_shared<Party>(party);
}

void cache_create_party(std::shared_ptr<Party> party) {
  if (!party) return;

  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyTable partyTable{};

  conn(sqlpp::insert_into(partyTable)
       .set(partyTable.name = party->name,
       partyTable.leaderId = party->leader,
       partyTable.options = party->options,
       partyTable.level = party->level,
       partyTable.lastGotItemIndex = party->last_got_item_index,
       partyTable.lastGotEtcIndex = party->last_got_etc_index,
       partyTable.lastGotZulyIndex = party->last_got_zuly_index));
}

void cache_write_party(std::shared_ptr<Party> party) {
  if (!party) return;
  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyTable partyTable{};

  conn(sqlpp::update(partyTable)
       .set(partyTable.name = party->name,
       partyTable.leaderId = party->leader,
       partyTable.options = party->options,
       partyTable.level = party->level,
       partyTable.lastGotItemIndex = party->last_got_item_index,
       partyTable.lastGotEtcIndex = party->last_got_etc_index,
       partyTable.lastGotZulyIndex = party->last_got_zuly_index)
       .where(partyTable.id == party->id));
}

void cache_write_party_members(std::shared_ptr<Party> party) {
  if (!party) return;
  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyMembersTable partyMembersTable{};

  conn(sqlpp::remove_from(partyMembersTable).where(partyMembersTable.id == party->id));
  auto insert = sqlpp::insert_into(partyMembersTable).columns(partyMembersTable.id, partyMembersTable.memberId);
  for (auto m : party-> members) {
    insert.values.add(partyMembersTable.id = party->id, partyMembersTable.memberId = static_cast<int>(m));
  }
  conn(insert);
}

void cache_remove_party(std::shared_ptr<Party> party) {
  if (!party) return;
  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyTable partyTable{};

  conn(sqlpp::remove_from(partyTable).where(partyTable.id == party->id));
}

void party_request(const RoseCommon::Packet::CliPartyReq& packet, CCharServer& server, User& user) {
    auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();
    logger->trace("party_request({})", user.get_name());

    using namespace RoseCommon::Packet;
    switch (packet.get_request()) {
        case CliPartyReq::MAKE: // idXorTag == id
        {
            auto other = server.get_user(packet.get_idXorTag(), user.get_mapId());
            if (!other) {
              logger->warn("User ({}, {}) doesn't exist", packet.get_idXorTag(), user.get_mapId());
              return;
            }
            logger->debug("{} wants to make a party with {}", user.get_name(), other.value()->get_name());
            break;
        }
        case CliPartyReq::JOIN: // idXorTag == id
        {
            auto other = server.get_user(packet.get_idXorTag(), user.get_mapId());
            if (!other) {
              logger->warn("User ({}, {}) doesn't exist", packet.get_idXorTag(), user.get_mapId());
              return;
            }
            logger->debug("{} wants to join {}'s party", user.get_name(), other.value()->get_name());
            break;
        }
        case CliPartyReq::LEFT: // idXorTag == tag
        {
            logger->debug("{} left the party", user.get_name());
            break;
        }
        case CliPartyReq::CHANGE_OWNER: // idXorTag == tag
        {
            auto other = server.get_user(packet.get_idXorTag());
            if (!other) {
              logger->warn("User {} doesn't exist", packet.get_idXorTag());
              return;
            }
            logger->debug("{} wants to make {} the owner", user.get_name(), other.value()->get_name());
            break;
        }
        case CliPartyReq::KICK: // idXorTag == tag
        {
            auto other = server.get_user(packet.get_idXorTag());
            if (!other) {
              logger->warn("User {} doesn't exist", packet.get_idXorTag());
              return;
            }
            logger->debug("{} wants to kick {}", user.get_name(), other.value()->get_name());
            break;
        }
        default:
            logger->warn("Client {} sent a non valid request code {}", charId, packet.get_request());
    }
}

void party_reply(const RoseCommon::Packet::CliPartyReq& packet, CCharServer& server, User& user) {
    auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();
    logger->trace("party_reply({})", user.get_name());

    auto* other;
    if (auto tmp = server.get_user(packet.get_idXorTag(), user.get_mapId()); !tmp) {
        logger->warn("Client {} replied to a party request of the non existing char {}", user.get_name(), packet.get_idXorTag());
        return;
    }

    using namespace RoseCommon::Packet;
    switch (packet.get_reply()) {
        case CliPartyReply::BUSY:
        case CliPartyReply::REJECT:
            logger->debug("{} refused {}'s party", other.value()->get_name(), user.get_name());
            break;
        case CliPartyReply::ACCEPT_MAKE:
        case CluPartyReply::ACCEPT_JOIN:
            logger->debug("{} accepted {}'s party", other.value()->get_name(), user.get_name());
            break;
    }
}
<|endoftext|>


<commit_before>/*
   Copyright (c) 2015, 2016, Andreas Fett
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   * Redistributions of source code must retain the above copyright notice, this
     list of conditions and the following disclaimer.

   * Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
   FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
   SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <cassert>
#include <cstdlib>
#include <cstring>

#include <iobuf.h>

void iobuf::fill(size_t size)
{
	assert(wstart_ + size <= capacity_);
	wstart_ += size;
}

size_t iobuf::rsize() const
{
	return wstart_ - rstart_;
}

void *iobuf::rstart() const
{
	return (char *)data_ + rstart_;
}

size_t iobuf::wsize() const
{
	return capacity_ - wstart_;
}

void *iobuf::wstart() const
{
	return (char *)data_ + wstart_;
}

void iobuf::drain(size_t size)
{
	assert(size <= rsize());

	rstart_ += size;
	if (rstart_ == wstart_) {
		wstart_ = 0;
		rstart_ = 0;
	}
}

iobuf::iobuf()
:
	data_(0),
	capacity_(0),
	rstart_(0),
	wstart_(0)
{ }

iobuf::iobuf(size_t size)
:
	data_(0),
	capacity_(0),
	rstart_(0),
	wstart_(0)
{
	grow(size);
}

iobuf::~iobuf()
{
	free(data_);
}

void iobuf::reserve(size_t size)
{
	if (size == 0) {
		return;
	}

	if (size <= wsize()) {
		return;
	}

	if (rstart_ != 0) {
		reclaim();
	}

	if (size <= wsize()) {
		return;
	}

	grow(capacity_ + (size - wsize()));
}

void iobuf::grow(size_t capacity)
{
	assert(capacity > capacity_);

	void *n(realloc(data_, capacity));
	if (n != NULL) {
		data_ = n;
		capacity_ = capacity;
	}
}

void iobuf::reclaim()
{
	size_t srsize(rsize());
	memmove(data_, rstart(), srsize);
	rstart_ = 0;
	wstart_ = srsize;
}
<commit_msg>iobuf: replace C style casts<commit_after>/*
   Copyright (c) 2015, 2016, Andreas Fett
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   * Redistributions of source code must retain the above copyright notice, this
     list of conditions and the following disclaimer.

   * Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
   FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
   SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <cassert>
#include <cstdlib>
#include <cstring>

#include <iobuf.h>

void iobuf::fill(size_t size)
{
	assert(wstart_ + size <= capacity_);
	wstart_ += size;
}

size_t iobuf::rsize() const
{
	return wstart_ - rstart_;
}

void *iobuf::rstart() const
{
	return static_cast<char *>(data_) + rstart_;
}

size_t iobuf::wsize() const
{
	return capacity_ - wstart_;
}

void *iobuf::wstart() const
{
	return static_cast<char *>(data_) + wstart_;
}

void iobuf::drain(size_t size)
{
	assert(size <= rsize());

	rstart_ += size;
	if (rstart_ == wstart_) {
		wstart_ = 0;
		rstart_ = 0;
	}
}

iobuf::iobuf()
:
	data_(0),
	capacity_(0),
	rstart_(0),
	wstart_(0)
{ }

iobuf::iobuf(size_t size)
:
	data_(0),
	capacity_(0),
	rstart_(0),
	wstart_(0)
{
	grow(size);
}

iobuf::~iobuf()
{
	free(data_);
}

void iobuf::reserve(size_t size)
{
	if (size == 0) {
		return;
	}

	if (size <= wsize()) {
		return;
	}

	if (rstart_ != 0) {
		reclaim();
	}

	if (size <= wsize()) {
		return;
	}

	grow(capacity_ + (size - wsize()));
}

void iobuf::grow(size_t capacity)
{
	assert(capacity > capacity_);

	void *n(realloc(data_, capacity));
	if (n != NULL) {
		data_ = n;
		capacity_ = capacity;
	}
}

void iobuf::reclaim()
{
	size_t srsize(rsize());
	memmove(data_, rstart(), srsize);
	rstart_ = 0;
	wstart_ = srsize;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include "GL/gl.h"
#include "foo.h"

using std::cout;
using std::endl;
using std::vector;

#include <GLFW/glfw3.h>

int main(void)
{
	GLFWwindow* window;

	/* Initialize the library */
	if (!glfwInit())
		return -1;

	/* Create a windowed mode window and its OpenGL context */
	window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
	if (!window)
	{
		glfwTerminate();
		return -1;
	}

	/* Make the window's context current */
	glfwMakeContextCurrent(window);

	/* Loop until the user closes the window */
	while (!glfwWindowShouldClose(window))
	{
		/* Render here */
		glClearColor(0.,0.,1.,0.);
		glClear(GL_COLOR_BUFFER_BIT);

		/* Swap front and back buffers */
		glfwSwapBuffers(window);

		/* Poll for and process events */
		glfwPollEvents();
	}

	glfwTerminate();
	return 0;
}<commit_msg>Enable Vsync<commit_after>#include <iostream>
#include <vector>
#include <list>
#include <functional>
#include "GL/gl.h"
#include "GL/wglext.h"
#include "GL/glu.h"
#include "foo.h"

using std::cout;
using std::cerr;
using std::endl;
using std::vector;
using std::list;
using std::function;

#include "GLFW/glfw3.h"

void ding(float x, float y) {
	float a = 0.1;
	float b = 0.15;
	float p[] = {
		x+a, y,
		x, y+b,
		x-a, y,
		x, y-b
	};
	glEnableClientState(GL_VERTEX_ARRAY);
	glVertexPointer(2, GL_FLOAT, 0, p);
	glDrawArrays(GL_LINE_LOOP, 0, 4);
}

struct vec2 {
	float x;
	float y;
};

std::list<std::function<void(int, int, int, int)>> on_key;
void keyfun(GLFWwindow * window, int key, int scancode, int action, int mods) {
	/*
	 * [in]	window	The window that received the event.
[in]	key	The keyboard key that was pressed or released.
[in]	scancode	The system-specific scancode of the key.
[in]	action	GLFW_PRESS, GLFW_RELEASE or GLFW_REPEAT.
[in]	mods	Bit field describing which modifier keys were held down
	 */
	for (auto x : on_key) {
		x(key, scancode, action, mods);
	}
}

void bind_key(int key, std::function<void()> callback) {
	on_key.push_back([=](int key2, int scancode, int action, int mods){
		if (key2 == key and action == GLFW_PRESS) {
			callback();
		}
	});
}

int SWAP_INTERVAL = 1;

int main(void)
{
	GLFWwindow* window;

	/* Initialize the library */
	if (!glfwInit())
		return -1;
	glfwWindowHint(GLFW_SAMPLES, 4);

	/* Create a windowed mode window and its OpenGL context */

	window = glfwCreateWindow(1366, 768, "Hello World", glfwGetPrimaryMonitor(), NULL);

	if (!window)
	{
		cout << "Could not create window" << endl;
		glfwTerminate();
		return -1;
	}
	glfwSetKeyCallback(window, keyfun);

	vector<vec2> objs = {
			{0, 0},
			{1, 1}
	};
	vector<vec2> speeds = {
			{0.2, 0},
			{0.2, 0.2}
	};

	bind_key(GLFW_KEY_SPACE, [&](){
		speeds[0].x *= -1;
	});

	list<function<void()>> queue;

	/* Make the window's context current */
	glfwMakeContextCurrent(window);
	double t0 = glfwGetTime();
	cout << glGetString(GL_VENDOR) << endl;
	cout << glGetString(GL_VERSION) << endl;
	cout << glGetString(GL_RENDERER) << endl;

	PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)glfwGetProcAddress("wglSwapIntervalEXT");
	if (wglSwapIntervalEXT) {
		cerr << "VSync not available" << endl;
	} else {
		wglSwapIntervalEXT(1);
	}

	/* Loop until the user closes the window */
	while (!glfwWindowShouldClose(window))
	{
		double t1 = glfwGetTime();
		float dt = (t1 - t0);
		t0 = t1;
		/* Render here */
		glClearColor(1,.98, 1 ,0);
		glClear(GL_COLOR_BUFFER_BIT);

		glColor3f(.5,.2,0);
		for (int i=0; i<objs.size(); ++i) {
			objs[i].x += speeds[i].x*dt;
			objs[i].y += speeds[i].y*dt;
			ding(objs[i].x, objs[i].y);
		}

		/* Swap front and back buffers */
		glfwSwapBuffers(window);

		/* Poll for and process events */
		glfwPollEvents();
	}

	glfwTerminate();
	return 0;
}

<|endoftext|>


<commit_before>#include <functional>
#include <iostream>

#include <spdlog/spdlog.h>
#include <docopt/docopt.h>

static constexpr auto USAGE =
  R"(Naval Fate.

    Usage:
          naval_fate ship new <name>...
          naval_fate ship <name> move <x> <y> [--speed=<kn>]
          naval_fate ship shoot <x> <y>
          naval_fate mine (set|remove) <x> <y> [--moored | --drifting]
          naval_fate (-h | --help)
          naval_fate --version
 Options:
          -h --help     Show this screen.
          --version     Show version.
          --speed=<kn>  Speed in knots [default: 10].
          --moored      Moored (anchored) mine.
          --drifting    Drifting mine.
)";

int main(int argc, const char **argv)
{
  std::map<std::string, docopt::value> args = docopt::docopt(USAGE,
    { std::next(argv), std::next(argv, argc) },
    true,// show help if requested
    "Naval Fate 2.0");// version string

  for (auto const &arg : args) {
    std::cout << arg.first << arg.second << std::endl;
  }

  //Use the default logger (stdout, multi-threaded, colored)
  spdlog::info("Hello, {}!", "World");

  fmt::print("Hello, from {}\n", "{fmt}");
}
<commit_msg>I had no prior experience with docopt, the default output would have been more clear by expressing the pair as key=value rather than keyvalue.<commit_after>#include <functional>
#include <iostream>

#include <spdlog/spdlog.h>
#include <docopt/docopt.h>

static constexpr auto USAGE =
  R"(Naval Fate.

    Usage:
          naval_fate ship new <name>...
          naval_fate ship <name> move <x> <y> [--speed=<kn>]
          naval_fate ship shoot <x> <y>
          naval_fate mine (set|remove) <x> <y> [--moored | --drifting]
          naval_fate (-h | --help)
          naval_fate --version
 Options:
          -h --help     Show this screen.
          --version     Show version.
          --speed=<kn>  Speed in knots [default: 10].
          --moored      Moored (anchored) mine.
          --drifting    Drifting mine.
)";

int main(int argc, const char **argv)
{
  std::map<std::string, docopt::value> args = docopt::docopt(USAGE,
    { std::next(argv), std::next(argv, argc) },
    true,// show help if requested
    "Naval Fate 2.0");// version string

  for (auto const &arg : args) {
    std::cout << arg.first << "=" << arg.second << std::endl;
  }

  //Use the default logger (stdout, multi-threaded, colored)
  spdlog::info("Hello, {}!", "World");

  fmt::print("Hello, from {}\n", "{fmt}");
}
<|endoftext|>


<commit_before>/*
 * Adventures in OpenCL tutorial series
 * Part 2
 *
 * author: Ian Johnson
 * htt://enja.org
 * code based on advisor Gordon Erlebacher's work
 * NVIDIA's examples
 * as well as various blogs and resources on the internet
 *
 * Ported to GL4 and GFLW by Lubosz Sarnecki <lubosz@gmail.com>
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include <iomanip>
#include <math.h>

#include <iostream>

#include <string>
#include <fstream>
#include <streambuf>

//OpenGL stuff
//#define GL_GLEXT_PROTOTYPES
//#include <GL/glcorearb.h>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

//Our OpenCL Particle Systemclass
#include "Simulator.h"
#include "Renderer.h"

#define NUM_PARTICLES 20000
Simulator* simulator;

//GL related variables
int window_width = 800;
int window_height = 600;
int glutWindowHandle = 0;
float translate_z = -1.f;
// mouse controls
int mouse_old_x, mouse_old_y;
int mouse_buttons = 0;
float rotate_x = 0.0, rotate_y = 0.0;

GLuint shader_programm;
GLuint vao = 0;

glm::mat4 model;
glm::mat4 projection;

std::vector<std::string> shaders;

//quick random function to distribute our initial points
float randomFloat(float mn, float mx)
{
    float r = random() / (float) RAND_MAX;
    return mn + (mx-mn)*r;
}

static void errorCallback(int error, const char* description)
{
    fputs(description, stderr);
}
static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
}

void buttonCallback(GLFWwindow* window, int button, int action, int mods)
{
    //handle mouse interaction for rotating/zooming the view
    if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
        mouse_buttons |= 1<<button;
    } else if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE) {
        mouse_buttons = 0;
    }

    double x, y;
    glfwGetCursorPos(window, &x, &y);

    mouse_old_x = x;
    mouse_old_y = y;
}

static void cursorCallback(GLFWwindow* window, double x, double y)
{
    //hanlde the mouse motion for zooming and rotating the view
    float dx, dy;
    dx = x - mouse_old_x;
    dy = y - mouse_old_y;

    if (mouse_buttons & 1) {
        rotate_x += dy * 0.2;
        rotate_y += dx * 0.2;
    } else if (mouse_buttons & 4) {
        translate_z += dy * 0.1;
    }

    mouse_old_x = x;
    mouse_old_y = y;

    // set view matrix
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    model = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, translate_z));
    model = glm::rotate(model, rotate_x, glm::vec3(1.0f, 0.0f, 0.0f));
    model = glm::rotate(model, rotate_y, glm::vec3(0.0f, 1.0f, 0.0f));
}

std::string readFile(const char* fileName) {
    std::ifstream stream(fileName);
    std::string source((std::istreambuf_iterator<char>(stream)),
                              std::istreambuf_iterator<char>());

    if (source.size() == 0) {
        std::cout << "ERROR: Could not load " << fileName << ".\n";
        return "";
    }

    return source;
}

void render()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glUseProgram (shader_programm);
    glBindVertexArray (vao);

    //this updates the particle system by calling the kernel
    simulator->runKernel();

    //render the particles from VBOs
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glPointSize(5.);

    glGenVertexArrays (1, &vao);
    glBindVertexArray (vao);
    glEnableVertexAttribArray (0);
    glBindBuffer(GL_ARRAY_BUFFER, simulator->p_vbo);
    glVertexAttribPointer (0, 4, GL_FLOAT, GL_FALSE, 0, NULL);

    glEnableVertexAttribArray (1);
    glBindBuffer(GL_ARRAY_BUFFER, simulator->c_vbo);
    glVertexAttribPointer (1, 4, GL_FLOAT, GL_FALSE, 0, NULL);

    glm::mat4 mvp = projection * model;

    GLint UniformMVP = glGetUniformLocation(shader_programm, "mvp");

    glUniformMatrix4fv(UniformMVP, 1, GL_FALSE, &mvp[0][0]);

    glDrawArrays(GL_POINTS, 0, simulator->num);

}

void initShaders() {
    shaders.push_back(readFile("gpu/MVP.vert"));
    shaders.push_back(readFile("gpu/color.frag"));

    const char* vertex[] = {shaders[0].c_str()};
    const char* fragment[] = {shaders[1].c_str()};

    GLuint vs = glCreateShader (GL_VERTEX_SHADER);
    glShaderSource (vs, 1, vertex, NULL);
    glCompileShader (vs);
    GLuint fs = glCreateShader (GL_FRAGMENT_SHADER);
    glShaderSource (fs, 1, fragment, NULL);
    glCompileShader (fs);

    shader_programm = glCreateProgram ();
    glAttachShader (shader_programm, fs);
    glAttachShader (shader_programm, vs);
    glLinkProgram (shader_programm);
}

void printContextInfo() {
    // get version info
    const GLubyte* renderer = glGetString (GL_RENDERER); // get renderer string
    const GLubyte* version = glGetString (GL_VERSION); // version as a string
    printf ("Renderer: %s\n", renderer);
    printf ("OpenGL version supported %s\n", version);
}

void initGL()
{
    glewExperimental = GL_TRUE;
    GLenum glewError = glewInit();
    if (glewError != GLEW_OK)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    glError;

    model = glm::mat4(1.0f);

    printContextInfo();
    initShaders();

    glClearColor(0.0, 0.0, 0.0, 1.0);
    glDisable(GL_DEPTH_TEST);

    // viewport
    glViewport(0, 0, window_width, window_height);
    projection = glm::perspective(90.0f,
                                  (GLfloat)window_width / (GLfloat) window_height,
                                  0.1f, 1000.f);

    // set view matrix
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    model = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, translate_z));
}

GLFWwindow* initGLFW() {
    GLFWwindow* window;
    glfwSetErrorCallback(errorCallback);
    if (!glfwInit())
        exit(EXIT_FAILURE);

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    window = glfwCreateWindow(window_width, window_height, "Universe Simulator", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);
    glfwSetKeyCallback(window, keyCallback);
    glfwSetMouseButtonCallback(window, buttonCallback);
    glfwSetCursorPosCallback(window, cursorCallback);

    return window;
}

void initParticles(Simulator * simulator) {
    //initialize our particle system with positions, velocities and color
    int num = NUM_PARTICLES;
    //int num = 1;
    std::vector<Vec4> pos(num);
    std::vector<Vec4> vel(num);
    std::vector<Vec4> color(num);

    //fill our vectors with initial data
    for(int i = 0; i < num; i++)
    {
        //distribute the particles in a random circle around z axis
        float rad = randomFloat(.2, .5);
        float x = rad*sin(2*3.14 * i/num);
        float z = 0.0f;// -.1 + .2f * i/num;
        float y = rad*cos(2*3.14 * i/num);
        pos[i] = Vec4(x, y, z, 1.0f);

        //give some initial velocity
        //float xr = rand_float(-.1, .1);
        //float yr = rand_float(1.f, 3.f);
        //the life is the lifetime of the particle: 1 = alive 0 = dead
        //as you will see in part2.cl we reset the particle when it dies
        float life_r = randomFloat(0.f, 1.f);
        vel[i] = Vec4(0.0, 0.0, 3.0f, life_r);

        //just make them red and full alpha
        color[i] = Vec4(1.0f, 0.0f,0.0f, 1.0f);
    }

    //our load data function sends our initial values to the GPU
    simulator->loadData(pos, vel, color);
}

int main(int argc, char** argv)
{
    GLFWwindow* window = initGLFW();
    //Setup OpenGL related things
    initGL();

    //initialize our CL object, this sets up the context
    simulator = new Simulator();

    std::string kernel_source = readFile("gpu/vortex.cl");

    simulator->loadProgram(kernel_source);

    initParticles(simulator);
    //initialize the kernel
    simulator->initKernel();

    while (!glfwWindowShouldClose(window))
    {
        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        glViewport(0, 0, width, height);

        projection = glm::perspective(90.0f,
                                      (GLfloat)window_width / (GLfloat) window_height,
                                      0.1f, 1000.f);

        render();

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
<commit_msg>increase some numbers<commit_after>/*
 * Adventures in OpenCL tutorial series
 * Part 2
 *
 * author: Ian Johnson
 * htt://enja.org
 * code based on advisor Gordon Erlebacher's work
 * NVIDIA's examples
 * as well as various blogs and resources on the internet
 *
 * Ported to GL4 and GFLW by Lubosz Sarnecki <lubosz@gmail.com>
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include <iomanip>
#include <math.h>

#include <iostream>

#include <string>
#include <fstream>
#include <streambuf>

//OpenGL stuff
//#define GL_GLEXT_PROTOTYPES
//#include <GL/glcorearb.h>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

//Our OpenCL Particle Systemclass
#include "Simulator.h"
#include "Renderer.h"

#define NUM_PARTICLES 200000
Simulator* simulator;

//GL related variables
int window_width = 1280;
int window_height = 720;
float translate_z = -1.f;
// mouse controls
int mouse_old_x, mouse_old_y;
int mouse_buttons = 0;
float rotate_x = 0.0, rotate_y = 0.0;

GLuint shader_programm;
GLuint vao = 0;

glm::mat4 model;
glm::mat4 projection;

std::vector<std::string> shaders;

//quick random function to distribute our initial points
float randomFloat(float mn, float mx)
{
    float r = random() / (float) RAND_MAX;
    return mn + (mx-mn)*r;
}

static void errorCallback(int error, const char* description)
{
    fputs(description, stderr);
}
static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
}

void buttonCallback(GLFWwindow* window, int button, int action, int mods)
{
    //handle mouse interaction for rotating/zooming the view
    if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
        mouse_buttons |= 1<<button;
    } else if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE) {
        mouse_buttons = 0;
    }

    double x, y;
    glfwGetCursorPos(window, &x, &y);

    mouse_old_x = x;
    mouse_old_y = y;
}

static void cursorCallback(GLFWwindow* window, double x, double y)
{
    //hanlde the mouse motion for zooming and rotating the view
    float dx, dy;
    dx = x - mouse_old_x;
    dy = y - mouse_old_y;

    if (mouse_buttons & 1) {
        rotate_x += dy * 0.2;
        rotate_y += dx * 0.2;
    } else if (mouse_buttons & 4) {
        translate_z += dy * 0.1;
    }

    mouse_old_x = x;
    mouse_old_y = y;

    // set view matrix
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    model = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, translate_z));
    model = glm::rotate(model, rotate_x, glm::vec3(1.0f, 0.0f, 0.0f));
    model = glm::rotate(model, rotate_y, glm::vec3(0.0f, 1.0f, 0.0f));
}

std::string readFile(const char* fileName) {
    std::ifstream stream(fileName);
    std::string source((std::istreambuf_iterator<char>(stream)),
                              std::istreambuf_iterator<char>());

    if (source.size() == 0) {
        std::cout << "ERROR: Could not load " << fileName << ".\n";
        return "";
    }

    return source;
}

void render()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glUseProgram (shader_programm);
    glBindVertexArray (vao);

    //this updates the particle system by calling the kernel
    simulator->runKernel();

    //render the particles from VBOs
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glPointSize(5.);

    glGenVertexArrays (1, &vao);
    glBindVertexArray (vao);
    glEnableVertexAttribArray (0);
    glBindBuffer(GL_ARRAY_BUFFER, simulator->p_vbo);
    glVertexAttribPointer (0, 4, GL_FLOAT, GL_FALSE, 0, NULL);

    glEnableVertexAttribArray (1);
    glBindBuffer(GL_ARRAY_BUFFER, simulator->c_vbo);
    glVertexAttribPointer (1, 4, GL_FLOAT, GL_FALSE, 0, NULL);

    glm::mat4 mvp = projection * model;

    GLint UniformMVP = glGetUniformLocation(shader_programm, "mvp");

    glUniformMatrix4fv(UniformMVP, 1, GL_FALSE, &mvp[0][0]);

    glDrawArrays(GL_POINTS, 0, simulator->num);

}

void initShaders() {
    shaders.push_back(readFile("gpu/MVP.vert"));
    shaders.push_back(readFile("gpu/color.frag"));

    const char* vertex[] = {shaders[0].c_str()};
    const char* fragment[] = {shaders[1].c_str()};

    GLuint vs = glCreateShader (GL_VERTEX_SHADER);
    glShaderSource (vs, 1, vertex, NULL);
    glCompileShader (vs);
    GLuint fs = glCreateShader (GL_FRAGMENT_SHADER);
    glShaderSource (fs, 1, fragment, NULL);
    glCompileShader (fs);

    shader_programm = glCreateProgram ();
    glAttachShader (shader_programm, fs);
    glAttachShader (shader_programm, vs);
    glLinkProgram (shader_programm);
}

void printContextInfo() {
    // get version info
    const GLubyte* renderer = glGetString (GL_RENDERER); // get renderer string
    const GLubyte* version = glGetString (GL_VERSION); // version as a string
    printf ("Renderer: %s\n", renderer);
    printf ("OpenGL version supported %s\n", version);
}

void initGL()
{
    glewExperimental = GL_TRUE;
    GLenum glewError = glewInit();
    if (glewError != GLEW_OK)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    glError;

    model = glm::mat4(1.0f);

    printContextInfo();
    initShaders();

    glClearColor(0.0, 0.0, 0.0, 1.0);
    glDisable(GL_DEPTH_TEST);

    // viewport
    glViewport(0, 0, window_width, window_height);
    projection = glm::perspective(90.0f,
                                  (GLfloat)window_width / (GLfloat) window_height,
                                  0.1f, 1000.f);

    // set view matrix
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    model = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, translate_z));
}

GLFWwindow* initGLFW() {
    GLFWwindow* window;
    glfwSetErrorCallback(errorCallback);
    if (!glfwInit())
        exit(EXIT_FAILURE);

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    window = glfwCreateWindow(window_width, window_height, "Universe Simulator", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);
    glfwSetKeyCallback(window, keyCallback);
    glfwSetMouseButtonCallback(window, buttonCallback);
    glfwSetCursorPosCallback(window, cursorCallback);

    return window;
}

void initParticles(Simulator * simulator) {
    //initialize our particle system with positions, velocities and color
    int num = NUM_PARTICLES;
    //int num = 1;
    std::vector<Vec4> pos(num);
    std::vector<Vec4> vel(num);
    std::vector<Vec4> color(num);

    //fill our vectors with initial data
    for(int i = 0; i < num; i++)
    {
        //distribute the particles in a random circle around z axis
        float rad = randomFloat(.2, .5);
        float x = rad*sin(2*3.14 * i/num);
        float z = 0.0f;// -.1 + .2f * i/num;
        float y = rad*cos(2*3.14 * i/num);
        pos[i] = Vec4(x, y, z, 1.0f);

        //give some initial velocity
        //float xr = rand_float(-.1, .1);
        //float yr = rand_float(1.f, 3.f);
        //the life is the lifetime of the particle: 1 = alive 0 = dead
        //as you will see in part2.cl we reset the particle when it dies
        float life_r = randomFloat(0.f, 1.f);
        vel[i] = Vec4(0.0, 0.0, 3.0f, life_r);

        //just make them red and full alpha
        color[i] = Vec4(1.0f, 0.0f,0.0f, 1.0f);
    }

    //our load data function sends our initial values to the GPU
    simulator->loadData(pos, vel, color);
}

int main(int argc, char** argv)
{
    GLFWwindow* window = initGLFW();
    //Setup OpenGL related things
    initGL();

    //initialize our CL object, this sets up the context
    simulator = new Simulator();

    std::string kernel_source = readFile("gpu/vortex.cl");

    simulator->loadProgram(kernel_source);

    initParticles(simulator);
    //initialize the kernel
    simulator->initKernel();

    while (!glfwWindowShouldClose(window))
    {
        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        glViewport(0, 0, width, height);

        projection = glm::perspective(90.0f,
                                      (GLfloat)window_width / (GLfloat) window_height,
                                      0.1f, 1000.f);

        render();

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <limits>
#include <AbstractPolygonFactory.h>

using namespace std;

/**
 * The purpose of this function is to validate the user's input
 *
 * @return bool True if validation is a success
 */
bool validateInput()
{
    bool isValid = cin.good();

    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    return isValid;
}

/**
 * The purpose of this method is to capture user input
 *
 * @return int The status code
 */
int main()
{
    char character;
    int height;

    do {
        cout << "Enter a character for your shape (only the first character will be used): " << endl;
        cin  >> character;

        if (!validateInput()) {
            cout << "You entered invalid values please try again." << endl;

            continue;
        }

        cout << "Enter a height for your shape: " << endl;
        cin  >> height;

        if (!validateInput()) {
            cout << "You entered invalid values please try again." << endl;

            continue;
        }

        AbstractPolygon * polygon = AbstractPolygonFactory::create("equilateral-triangle", character, height);
        polygon->draw();
    } while (height != -1);

    return 0;
}
<commit_msg>Bugfix to welcome user to the system as well as inform user how to terminate the program<commit_after>#include <iostream>
#include <limits>
#include <AbstractPolygonFactory.h>

using namespace std;

/**
 * The purpose of this function is to validate the user's input
 *
 * @return bool True if validation is a success
 */
bool validateInput()
{
    bool isValid = cin.good();

    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    return isValid;
}

/**
 * The purpose of this method is to capture user input
 *
 * @return int The status code
 */
int main()
{
    char character;
    int height;

    cout << "Welcome to iBonWe Triangle Memes Generator.\n"
            "This is an awesome Triangle Memes generator.\n"
            "You can create as many triangle memes as you want but if"
            "you want to stop at any time enter (-1) for height." << endl;

    do {
        cout << "Enter a character for your shape (only the first character will be used): " << endl;
        cin  >> character;

        if (!validateInput()) {
            cout << "You entered invalid values please try again." << endl;

            continue;
        }

        cout << "Enter a height for your shape (Type -1 to exit): " << endl;
        cin  >> height;

        if (!validateInput()) {
            cout << "You entered invalid values please try again." << endl;

            continue;
        }

        AbstractPolygon * polygon = AbstractPolygonFactory::create("equilateral-triangle", character, height);
        polygon->draw();
    } while (height != -1);

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <configuration.hpp>

#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
using std::fixed;
#include <string>
using std::string;
#include <exception>
using std::exception;
#include <fstream>
using std::ofstream;
#include <vector>
using std::vector;
#include <iomanip>
using std::setprecision;

#include <ArgumentList.hpp>
using isa::utils::ArgumentList;
#include <utils.hpp>
using isa::utils::giga;
#include <Observation.hpp>
using AstroData::Observation;
#include <ReadData.hpp>
using AstroData::readSIGPROC;
using AstroData::readLOFAR;
#include <Dedispersion.hpp>
using PulsarSearch::Dedispersion;
#include <Shifts.hpp>
using PulsarSearch::getShifts;
#include <Folding.hpp>
using PulsarSearch::Folding;
#include <SNR.hpp>
using PulsarSearch::SNR;
#include <CLData.hpp>
using isa::OpenCL::CLData;
#include <Exceptions.hpp>
using isa::Exceptions::OpenCLError;

int main(int argc, char * argv[]) {
	bool dataLOFAR = false;
	bool dataSIGPROC = false;
	unsigned int clPlatformID = 0;
	unsigned int clDeviceID = 0;
	string dataFile;
	string headerFile;
	string outputFile;
	// Observation object
	Observation< dataType > obs("PulsarSearch", dataName);

	try {
		ArgumentList args(argc, argv);

		clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
		clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");

		dataLOFAR = args.getSwitch("-lofar");
		dataSIGPROC = args.getSwitch("-sigproc");
		if ( dataLOFAR && dataSIGPROC ) {
			cerr << "-lofar and -sigproc are mutually exclusive." << endl;
			throw exception();
		} else if ( dataLOFAR ) {
			headerFile = args.getSwitchArgument< string >("-header");
			dataFile = args.getSwitchArgument< string >("-data");
		} else if ( dataSIGPROC ) {
			dataFile = args.getSwitchArgument< string >("-data");
		} else {
			cerr << "Need to specify the -header and -data arguments." << endl;
			throw exception();
		}
		outputFile = args.getSwitchArgument< string >("-output");

		obs.setFirstDM(args.getSwitchArgument< float >("-dm_first"));
		obs.setDMStep(args.getSwitchArgument< float >("-dm_step"));
		obs.setNrDMs(args.getSwitchArgument< unsigned int >("-dm_number"));
		obs.setFirstPeriod(args.getSwitchArgument< unsigned int >("-period_first"));
		obs.setNrPeriods(args.getSwitchArgument< unsigned int >("-period_number"));
		obs.setNrBins(args.getSwitchArgument< unsigned int >("-period_bins"));
		obs.setPeriodStep(obs.getNrBins());
	} catch ( exception &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	// Load observation data
	vector< CLData< dataType > * > * input = new vector< CLData< dataType > * >(1);
	if ( dataLOFAR ) {
		readLOFAR(headerFile, dataFile, obs, *input);
	} else if ( SIGPROC ) {
		// TODO: implement SIGPROC pipeline
	}

	// Initialize OpenCL
	cl::Context *clContext = new cl::Context();
	vector< cl::Platform > *clPlatforms = new vector< cl::Platform >();
	vector< cl::Device > *clDevices = new vector< cl::Device >();
	vector< vector< cl::CommandQueue > > *clQueues = new vector< vector < cl::CommandQueue > >();

	try {
		initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);
	} catch ( OpenCLError err ) {
		cerr << err.what() << endl;
		return 1;
	}

	// Memory allocation
	unsigned int nrSamplesPerChannel = 0;
	unsigned int secondsToBuffer = 0;
	CLData< unsigned int > * shifts = getShifts(obs);
	CLData< dataType > dispersedData("DispersedData", true);
	CLData< dataType > dedispersedData("DedispersedData", true);
	CLData< dataType > transposedData("TransposedData", true);
	CLData< dataType > foldedData("FoldedData", true);
	CLData< unsigned int > counterData("CounterData", true);
	CLData< dataType > snrTable("SNRTable", true);

	if ( ((obs.getNrSamplesPerSecond() + (*shifts)[((obs.getNrDMs() - 1) * obs.getNrPaddedChannels())]) % obs.getPadding()) != 0 ) {
		nrSamplesPerChannel = (obs.getNrSamplesPerSecond() + (*shifts)[((obs.getNrDMs() - 1) * obs.getNrPaddedChannels())]) + (obs.getPadding() - ((obs.getNrSamplesPerSecond() + (*shifts)[((obs.getNrDMs() - 1) * obs.getNrPaddedChannels())]) % obs.getPadding()));
	} else {
		nrSamplesPerChannel = (obs.getNrSamplesPerSecond() + (*shifts)[((obs.getNrDMs() - 1) * obs.getNrPaddedChannels())]);
	}
	secondsToBuffer = static_cast< unsigned int >(ceil(static_cast< float >(nrSamplesPerChannel) / obs.getNrSamplesPerPaddedSecond()));

	dispersedData.allocateHostData(secondsToBuffer * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond());
	snrTable.allocateHostData(obs.getNrPeriods() * obs.getNrPaddedDMs());

	try {
		shifts->setCLContext(clContext);
		shifts->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
		shifts->allocateDeviceData();
		shifts->copyHostToDevice(true);
		dispersedData.setCLContext(clContext);
		dispersedData.setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
		dispersedData.allocateDeviceData();
		dedispersedData.setCLContext(clContext);
		dedispersedData.setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
		dedispersedData.allocateDeviceData(obs.getNrDMs() * obs.getNrSamplesPerPaddedSecond());
		transposedData.setCLContext(clContext);
		transposedData.setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
		transposedData.allocateDeviceData(obs.getNrSamplesPerSecond() * obs.getNrPaddedDMs());
		foldedData.setCLContext(clContext);
		foldedData.setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
		foldedData.allocateDeviceData(obs.getNrBins() * obs.getNrPeriods() * obs.getNrPaddedDMs());
		foldedData.blankHostData();
		foldedData.allocateDeviceData();
		foldedData.copyHostToDevice();
		foldedData.deleteHostData();
		counterData.setCLContext(clContext);
		counterData.setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
		counterData.allocateDeviceData(obs.getNrBins() * obs.getNrPeriods() * obs.getNrPaddedDMs());
		counterData.blankHostData();
		counterData.allocateDeviceData();
		counterData.copyHostToDevice();
		counterData.deleteHostData();
	} catch ( OpenCLError err ) {
		cerr << err.what() << endl;
		return 1;
	}

	if ( DEBUG ) {
		double hostMemory = 0.0;
		double deviceMemory = 0.0;
		hostMemory += shifts.getHostDataSize() + dispersedData.getHostDataSize() + snrTable.getHostDataSize();
		deviceMemory += shifts.getDeviceDataSize() + dispersedData.getDeviceDataSize() + dedispersedData.getDeviceDataSize() + transposedData.getDeviceDataSize() + foldedData.getDeviceDataSize() + counterData.getDeviceDataSize() + snrTable.getDeviceDataSize();

		cout << "Allocated host memory: " << fixed << setprecision(3) << giga(hostMemory) << endl;
		cout << "Allocated device memory: " << fixed << setprecision(3) << giga(deviceMemory) << endl;
	}

	// Search loop
	for ( unsigned int second = 0; second < obs.getNrSeconds(); second++ ) {

	}

	// Store output
	try {
		snrTable.copyDeviceToHost();
	} catch ( OpenCLError err ) {
		cerr << err.what() << endl;
		return 1;
	}
	ofstream output;
	output.open(outputFile);
	for ( unsigned int period = 0; period < obs.getNrPeriods(); period++ ) {
		for ( unsigned int dm = 0; dm < obs.getNrDMs(); dm++ ) {
			output << period << " " << dm << " " << fixed << setprecision(3) << snrTable[(period * obs.getNrPaddedDMs()) + dm] << endl;
		}
	}
	output.close();

	return 0;
}
<commit_msg>Fixing some typos and mistakes.<commit_after>/*
 * Copyright (C) 2013
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
using std::fixed;
#include <string>
using std::string;
#include <exception>
using std::exception;
#include <fstream>
using std::ofstream;
#include <vector>
using std::vector;
#include <iomanip>
using std::setprecision;

#include <configuration.hpp>

#include <ArgumentList.hpp>
using isa::utils::ArgumentList;
#include <utils.hpp>
using isa::utils::giga;
#include <Observation.hpp>
using AstroData::Observation;
#include <ReadData.hpp>
using AstroData::readSIGPROC;
using AstroData::readLOFAR;
#include <Dedispersion.hpp>
using PulsarSearch::Dedispersion;
#include <Shifts.hpp>
using PulsarSearch::getShifts;
#include <Folding.hpp>
using PulsarSearch::Folding;
#include <SNR.hpp>
using PulsarSearch::SNR;
#include <CLData.hpp>
using isa::OpenCL::CLData;
#include <Exceptions.hpp>
using isa::Exceptions::OpenCLError;
#include <InitializeOpenCL.hpp>
using isa::OpenCL::initializeOpenCL;

int main(int argc, char * argv[]) {
	bool dataLOFAR = false;
	bool dataSIGPROC = false;
	unsigned int clPlatformID = 0;
	unsigned int clDeviceID = 0;
	string dataFile;
	string headerFile;
	string outputFile;
	// Observation object
	Observation< dataType > obs("PulsarSearch", dataName);

	try {
		ArgumentList args(argc, argv);

		clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
		clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");

		dataLOFAR = args.getSwitch("-lofar");
		dataSIGPROC = args.getSwitch("-sigproc");
		if ( dataLOFAR && dataSIGPROC ) {
			cerr << "-lofar and -sigproc are mutually exclusive." << endl;
			throw exception();
		} else if ( dataLOFAR ) {
			headerFile = args.getSwitchArgument< string >("-header");
			dataFile = args.getSwitchArgument< string >("-data");
		} else if ( dataSIGPROC ) {
			dataFile = args.getSwitchArgument< string >("-data");
		} else {
			cerr << "Need to specify the -header and -data arguments." << endl;
			throw exception();
		}
		outputFile = args.getSwitchArgument< string >("-output");

		obs.setFirstDM(args.getSwitchArgument< float >("-dm_first"));
		obs.setDMStep(args.getSwitchArgument< float >("-dm_step"));
		obs.setNrDMs(args.getSwitchArgument< unsigned int >("-dm_number"));
		obs.setFirstPeriod(args.getSwitchArgument< unsigned int >("-period_first"));
		obs.setNrPeriods(args.getSwitchArgument< unsigned int >("-period_number"));
		obs.setNrBins(args.getSwitchArgument< unsigned int >("-period_bins"));
		obs.setPeriodStep(obs.getNrBins());
	} catch ( exception &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	// Load observation data
	vector< CLData< dataType > * > * input = new vector< CLData< dataType > * >(1);
	if ( dataLOFAR ) {
		readLOFAR(headerFile, dataFile, obs, *input);
	} else if ( dataSIGPROC ) {
		// TODO: implement SIGPROC pipeline
	}

	// Initialize OpenCL
	cl::Context *clContext = new cl::Context();
	vector< cl::Platform > *clPlatforms = new vector< cl::Platform >();
	vector< cl::Device > *clDevices = new vector< cl::Device >();
	vector< vector< cl::CommandQueue > > *clQueues = new vector< vector < cl::CommandQueue > >();

	try {
		initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);
	} catch ( OpenCLError err ) {
		cerr << err.what() << endl;
		return 1;
	}

	// Memory allocation
	unsigned int nrSamplesPerChannel = 0;
	unsigned int secondsToBuffer = 0;
	CLData< unsigned int > * shifts = getShifts(obs);
	CLData< dataType > dispersedData("DispersedData", true);
	CLData< dataType > dedispersedData("DedispersedData", true);
	CLData< dataType > transposedData("TransposedData", true);
	CLData< dataType > foldedData("FoldedData", true);
	CLData< unsigned int > counterData("CounterData", true);
	CLData< dataType > snrTable("SNRTable", true);

	if ( ((obs.getNrSamplesPerSecond() + (*shifts)[((obs.getNrDMs() - 1) * obs.getNrPaddedChannels())]) % obs.getPadding()) != 0 ) {
		nrSamplesPerChannel = (obs.getNrSamplesPerSecond() + (*shifts)[((obs.getNrDMs() - 1) * obs.getNrPaddedChannels())]) + (obs.getPadding() - ((obs.getNrSamplesPerSecond() + (*shifts)[((obs.getNrDMs() - 1) * obs.getNrPaddedChannels())]) % obs.getPadding()));
	} else {
		nrSamplesPerChannel = (obs.getNrSamplesPerSecond() + (*shifts)[((obs.getNrDMs() - 1) * obs.getNrPaddedChannels())]);
	}
	secondsToBuffer = static_cast< unsigned int >(ceil(static_cast< float >(nrSamplesPerChannel) / obs.getNrSamplesPerPaddedSecond()));

	dispersedData.allocateHostData(secondsToBuffer * obs.getNrChannels() * obs.getNrSamplesPerPaddedSecond());
	snrTable.allocateHostData(obs.getNrPeriods() * obs.getNrPaddedDMs());

	try {
		shifts->setCLContext(clContext);
		shifts->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
		shifts->allocateDeviceData();
		shifts->copyHostToDevice(true);
		dispersedData.setCLContext(clContext);
		dispersedData.setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
		dispersedData.allocateDeviceData();
		dedispersedData.setCLContext(clContext);
		dedispersedData.setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
		dedispersedData.allocateDeviceData(obs.getNrDMs() * obs.getNrSamplesPerPaddedSecond());
		transposedData.setCLContext(clContext);
		transposedData.setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
		transposedData.allocateDeviceData(obs.getNrSamplesPerSecond() * obs.getNrPaddedDMs());
		foldedData.setCLContext(clContext);
		foldedData.setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
		foldedData.allocateDeviceData(obs.getNrBins() * obs.getNrPeriods() * obs.getNrPaddedDMs());
		foldedData.blankHostData();
		foldedData.allocateDeviceData();
		foldedData.copyHostToDevice();
		foldedData.deleteHostData();
		counterData.setCLContext(clContext);
		counterData.setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
		counterData.allocateDeviceData(obs.getNrBins() * obs.getNrPeriods() * obs.getNrPaddedDMs());
		counterData.blankHostData();
		counterData.allocateDeviceData();
		counterData.copyHostToDevice();
		counterData.deleteHostData();
	} catch ( OpenCLError err ) {
		cerr << err.what() << endl;
		return 1;
	}

	if ( DEBUG ) {
		double hostMemory = 0.0;
		double deviceMemory = 0.0;
		hostMemory += shifts->getHostDataSize() + dispersedData.getHostDataSize() + snrTable.getHostDataSize();
		deviceMemory += shifts->getDeviceDataSize() + dispersedData.getDeviceDataSize() + dedispersedData.getDeviceDataSize() + transposedData.getDeviceDataSize() + foldedData.getDeviceDataSize() + counterData.getDeviceDataSize() + snrTable.getDeviceDataSize();

		cout << "Allocated host memory: " << fixed << setprecision(3) << giga(hostMemory) << endl;
		cout << "Allocated device memory: " << fixed << setprecision(3) << giga(deviceMemory) << endl;
	}

	// Search loop
	for ( unsigned int second = 0; second < obs.getNrSeconds(); second++ ) {

	}

	// Store output
	try {
		snrTable.copyDeviceToHost();
	} catch ( OpenCLError err ) {
		cerr << err.what() << endl;
		return 1;
	}
	ofstream output;
	output.open(outputFile);
	for ( unsigned int period = 0; period < obs.getNrPeriods(); period++ ) {
		for ( unsigned int dm = 0; dm < obs.getNrDMs(); dm++ ) {
			output << period << " " << dm << " " << fixed << setprecision(3) << snrTable[(period * obs.getNrPaddedDMs()) + dm] << endl;
		}
	}
	output.close();

	return 0;
}
<|endoftext|>


<commit_before>#include <QApplication>
#include <QFileInfo>
#include <QFont>
#include <QSettings>
#include <QVariant>

#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <vector>

extern "C" {
#include <libxslt/xslt.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libexslt/exslt.h>
}

#include <DactApplication.hh>
#include <ProgramOptions.hh>

namespace {
    void usage(char const *progname)
    {
        std::cerr << "Usage: " << progname << " [OPTION] corpus ..." <<
          std::endl << std::endl <<
          "  -m filename\tMacro file, multiple files are separated by a colon (:)" << std::endl <<
          "  -u URI\tURI, for instance a query URI" << std::endl << std::endl;
        std::exit(1);
    }
}

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

    // EXSLT extensions
    exsltRegisterAll();

    // XPath
    xmlXPathInit();

    int r = 0;

    try {
        QCoreApplication::setOrganizationName("RUG");
        QCoreApplication::setOrganizationDomain("rug.nl");
        QCoreApplication::setApplicationName("Dact");

        QSettings settings;

#if defined(Q_WS_MAC)
        // Work around a bug (#56) where Qt 4.8.x on Mac OS X does not
        // invalidate the region of the popup when we hover as a result of
        // mouse scrolling.
        if (!settings.value("useNativeGraphicsSystem", false).toBool())
            QApplication::setGraphicsSystem("raster");

        // QTBUG-32789: GUI widgets use the wrong font on OS X Mavericks.
        if ( QSysInfo::MacintoshVersion > QSysInfo::MV_10_8 )
            QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
#endif

        QScopedPointer<DactApplication> a(new DactApplication(argc, argv));
        bool dactIsRunning = a->isRunning();

        QVariant fontValue = settings.value("appFont", qApp->font().toString());

#ifndef __APPLE__
        QFont appFont;
        appFont.fromString(fontValue.toString());
        a->setFont(appFont);
#endif

        a->init();

        QStringList corpusPaths, macroPaths;

        ProgramOptions options(argc, const_cast<char const **>(argv), "m:u:");

        // Process macros
        if (options.option('m'))
        {
            QString macros = QString::fromStdString(options.optionValue('m'));
            macroPaths = macros.split(':', QString::SkipEmptyParts);
        }

        // Corpus paths
        for (std::vector<std::string>::const_iterator iter = options.arguments().begin();
                iter != options.arguments().end(); ++iter)
        {
            QString corpus = QString::fromStdString(*iter);

            // Dact may have been started in a different directory.
            QFileInfo corpusFileInfo(corpus);
            corpusPaths.push_back(corpusFileInfo.absoluteFilePath());
        }

        // URI
        QString uri = options.option('u') ?
            QString::fromStdString(options.optionValue('u')) : QString();

        if (dactIsRunning) {
            if (corpusPaths.size() != 0)
                a->sendMessage(QString("%1%2").arg(CORPUS_OPEN_MESSAGE,
                      corpusPaths.join(CORPUS_SEPARATOR)));

            if (!uri.isNull())
                a->sendMessage(uri);

          return 0;
        }

        a->openMacros(macroPaths);

        if (corpusPaths.size() != 0)
          a->openCorpora(corpusPaths);

        if (!uri.isNull())
            a->openUrl(QUrl::fromUserInput(uri));

        r = a->exec();
    } catch (std::runtime_error &e) {
        std::cerr << e.what() << std::endl << std::endl;
        usage(argv[0]);
    } catch (std::logic_error const &e) {
        std::cerr << "dact: internal logic error: please report at\n"
                     "      https://github.com/rug-compling/dact/issues, citing"
                  << e.what()
                  << std::endl;
        r = 1;
    }

    // must be called after the DactApplication is deleted
    xsltCleanupGlobals();
    xmlCleanupParser();

    return r;
}
<commit_msg>Use a different identifier for sandboxed versions.<commit_after>#include <QApplication>
#include <QFileInfo>
#include <QFont>
#include <QSettings>
#include <QVariant>

#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <vector>

extern "C" {
#include <libxslt/xslt.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libexslt/exslt.h>
}

#include <DactApplication.hh>
#include <ProgramOptions.hh>

namespace {
    void usage(char const *progname)
    {
        std::cerr << "Usage: " << progname << " [OPTION] corpus ..." <<
          std::endl << std::endl <<
          "  -m filename\tMacro file, multiple files are separated by a colon (:)" << std::endl <<
          "  -u URI\tURI, for instance a query URI" << std::endl << std::endl;
        std::exit(1);
    }
}

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

    // EXSLT extensions
    exsltRegisterAll();

    // XPath
    xmlXPathInit();

    int r = 0;

    try {
#if defined(ENABLE_SANDBOXING)
        // Use different identifier for sandboxed version to avoid clashes
        // between application state (e.g. recent files).
        QCoreApplication::setOrganizationName("danieldk");
        QCoreApplication::setOrganizationDomain("danieldk.eu");
#else
        QCoreApplication::setOrganizationName("RUG");
        QCoreApplication::setOrganizationDomain("rug.nl");
#endif
        QCoreApplication::setApplicationName("Dact");

        QSettings settings;

#if defined(Q_WS_MAC)
        // Work around a bug (#56) where Qt 4.8.x on Mac OS X does not
        // invalidate the region of the popup when we hover as a result of
        // mouse scrolling.
        if (!settings.value("useNativeGraphicsSystem", false).toBool())
            QApplication::setGraphicsSystem("raster");

        // QTBUG-32789: GUI widgets use the wrong font on OS X Mavericks.
        if ( QSysInfo::MacintoshVersion > QSysInfo::MV_10_8 )
            QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
#endif

        QScopedPointer<DactApplication> a(new DactApplication(argc, argv));
        bool dactIsRunning = a->isRunning();

        QVariant fontValue = settings.value("appFont", qApp->font().toString());

#ifndef __APPLE__
        QFont appFont;
        appFont.fromString(fontValue.toString());
        a->setFont(appFont);
#endif

        a->init();

        QStringList corpusPaths, macroPaths;

        ProgramOptions options(argc, const_cast<char const **>(argv), "m:u:");

        // Process macros
        if (options.option('m'))
        {
            QString macros = QString::fromStdString(options.optionValue('m'));
            macroPaths = macros.split(':', QString::SkipEmptyParts);
        }

        // Corpus paths
        for (std::vector<std::string>::const_iterator iter = options.arguments().begin();
                iter != options.arguments().end(); ++iter)
        {
            QString corpus = QString::fromStdString(*iter);

            // Dact may have been started in a different directory.
            QFileInfo corpusFileInfo(corpus);
            corpusPaths.push_back(corpusFileInfo.absoluteFilePath());
        }

        // URI
        QString uri = options.option('u') ?
            QString::fromStdString(options.optionValue('u')) : QString();

        if (dactIsRunning) {
            if (corpusPaths.size() != 0)
                a->sendMessage(QString("%1%2").arg(CORPUS_OPEN_MESSAGE,
                      corpusPaths.join(CORPUS_SEPARATOR)));

            if (!uri.isNull())
                a->sendMessage(uri);

          return 0;
        }

        a->openMacros(macroPaths);

        if (corpusPaths.size() != 0)
          a->openCorpora(corpusPaths);

        if (!uri.isNull())
            a->openUrl(QUrl::fromUserInput(uri));

        r = a->exec();
    } catch (std::runtime_error &e) {
        std::cerr << e.what() << std::endl << std::endl;
        usage(argv[0]);
    } catch (std::logic_error const &e) {
        std::cerr << "dact: internal logic error: please report at\n"
                     "      https://github.com/rug-compling/dact/issues, citing"
                  << e.what()
                  << std::endl;
        r = 1;
    }

    // must be called after the DactApplication is deleted
    xsltCleanupGlobals();
    xmlCleanupParser();

    return r;
}
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------

Copyright (c) 2010 Nigel Atkinson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include <iostream>
#include <exception>
#include <engine.h>

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif

using namespace std;

int main()
{
    cout << "Staring engine." << endl;

    //try
    {
        Engine engine;

        if( engine.initialise() )
        {
            cout << endl << "Successfully started game engine." << endl << endl;
        }

        engine.run();
    }
/*
    catch( exception& e )
    {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
        MessageBox( NULL, e.what(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
        std::cerr << "An exception has occurred: " << e.what() << std::endl;
#endif
    }
*/
    return 0;
}

<commit_msg>Tidy up main.cpp<commit_after>/*
-----------------------------------------------------------------------------

Copyright (c) 2010 Nigel Atkinson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include <iostream>
#include <exception>
#include <engine.h>

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif

using namespace std;

int main()
{
    cout << "Staring engine." << endl;

    // Commented out to aid debugging.
    //try
    {
        Engine engine;

        if( engine.initialise() )
        {
            cout << endl << "Successfully initialised game engine." << endl << endl;

            engine.run();
        }
        else
            cout << endl << "Could not initialise game engine." << endl << endl;
    }
/*
    catch( exception& e )
    {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
        MessageBox( NULL, e.what(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
        std::cerr << "An exception has occurred: " << e.what() << std::endl;
#endif
    }
*/
    return 0;
}

<|endoftext|>


<commit_before>/**
 *  Copyright (C) 2014 3D Repo Ltd
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <QApplication>
#include <QResource>
#include <ctime>
#include <repo/repo_controller.h>
#include <repo/lib/repo_listener_abstract.h>

#include "repo/gui/repo_gui.h"
#include "repo/logger/repo_logger.h"

static std::string getTimeAsString()
{
  time_t rawtime;
  struct tm * timeinfo;
  char buffer[80];

  time (&rawtime);
  timeinfo = localtime(&rawtime);

  strftime(buffer,80,"%d-%m-%Y_%I:%M:%S",timeinfo);
  return std::string(buffer);

}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
//    a.setAttribute(Qt::AA_UseDesktopOpenGL); // Qt5.5 support
    a.setAttribute(Qt::AA_ShareOpenGLContexts); // https://blog.qt.io/blog/2014/09/10/qt-weekly-19-qopenglwidget/

    QCoreApplication::setOrganizationName("3D Repo");
    QCoreApplication::setOrganizationDomain("3drepo.org");
    QCoreApplication::setApplicationName("3D Repo GUI");
    QCoreApplication::setApplicationVersion("1.0.0b2");

	std::vector<repo::lib::RepoAbstractListener*> listeners;
	listeners.push_back(repo::logger::RepoLogger::getInstance());

	repo::RepoController *controller = new repo::RepoController(listeners);
    controller->logToFile( getTimeAsString() + ".log");

	//check env var to see whether a debug level is set
	char* debug = getenv("REPO_DEBUG");
	char* verbose = getenv("REPO_VERBOSE");

    controller->setLoggingLevel(repo::lib::RepoLog::RepoLogLevel::TRACE);

    if (verbose)
	{
		controller->setLoggingLevel(repo::lib::RepoLog::RepoLogLevel::TRACE);
	}
	else if (debug)
	{
		controller->setLoggingLevel(repo::lib::RepoLog::RepoLogLevel::DEBUG);
	}
	else
	{
		controller->setLoggingLevel(repo::lib::RepoLog::RepoLogLevel::INFO);
    }

	if (verbose) free(verbose);
	if (debug)   free(debug);

    repo::gui::RepoGUI w(controller);

    w.show();
    w.startup();

    repoLog(getTimeAsString());

    return a.exec();
}

<commit_msg>#124 fix crash with log to file<commit_after>/**
 *  Copyright (C) 2014 3D Repo Ltd
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <QApplication>
#include <QResource>
#include <ctime>
#include <repo/repo_controller.h>
#include <repo/lib/repo_listener_abstract.h>

#include "repo/gui/repo_gui.h"
#include "repo/logger/repo_logger.h"

static std::string getTimeAsString()
{
  time_t rawtime;
  struct tm * timeinfo;
  char buffer[80];

  time (&rawtime);
  timeinfo = localtime(&rawtime);

  strftime(buffer,80,"%d-%m-%Y_%Ih%Mm%S",timeinfo);
  return std::string(buffer);

}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
//    a.setAttribute(Qt::AA_UseDesktopOpenGL); // Qt5.5 support
    a.setAttribute(Qt::AA_ShareOpenGLContexts); // https://blog.qt.io/blog/2014/09/10/qt-weekly-19-qopenglwidget/

    QCoreApplication::setOrganizationName("3D Repo");
    QCoreApplication::setOrganizationDomain("3drepo.org");
    QCoreApplication::setApplicationName("3D Repo GUI");
    QCoreApplication::setApplicationVersion("1.0.0b2");

    std::vector<repo::lib::RepoAbstractListener*> listeners;
    listeners.push_back(repo::logger::RepoLogger::getInstance());

    repo::RepoController *controller = new repo::RepoController(listeners);
    controller->logToFile(getTimeAsString()+".log");

	//check env var to see whether a debug level is set
	char* debug = getenv("REPO_DEBUG");
	char* verbose = getenv("REPO_VERBOSE");

    controller->setLoggingLevel(repo::lib::RepoLog::RepoLogLevel::TRACE);

    if (verbose)
	{
		controller->setLoggingLevel(repo::lib::RepoLog::RepoLogLevel::TRACE);
	}
	else if (debug)
	{
		controller->setLoggingLevel(repo::lib::RepoLog::RepoLogLevel::DEBUG);
	}
	else
	{
		controller->setLoggingLevel(repo::lib::RepoLog::RepoLogLevel::INFO);
    }

	if (verbose) free(verbose);
	if (debug)   free(debug);

    repo::gui::RepoGUI w(controller);

    w.show();
    w.startup();
    return a.exec();
}

<|endoftext|>