text
stringlengths
54
60.6k
<commit_before>// <<<<<<< HEAD // #include "game.hpp" // #include "component_drawable.hpp" // #include "component_position.hpp" // #include "strapon/resource_manager/resource_manager.hpp" // #include "entityx/entityx.h" // #include <glm/vec2.hpp> // #include <SDL2/SDL.h> // #include <SDL2/SDL_image.h> // // class DrawSystem : public entityx::System<DrawSystem> // { // public: // DrawSystem(Game *game) : m_game(game) { // int w, h; // SDL_RenderGetLogicalSize(game->get_renderer(), &w, &h); // m_camera = SDL_Rect{0, 0, w, h}; // } // void update(entityx::EntityManager &es, entityx::EventManager &events, entityx::TimeDelta dt) override // { // SDL_SetRenderDrawColor(m_game->get_renderer(), 0, 100, 200, 255); // SDL_RenderClear(m_game->get_renderer()); // entityx::ComponentHandle<Drawable> drawable; // entityx::ComponentHandle<Position> position; // for (entityx::Entity entity : es.entities_with_components(drawable, position)) // { // (void)entity; // SDL_Rect dest; // dest.x = position->get_position()[0]; // std::cout << position->get_position()[0] << std::endl; // dest.y = position->get_position()[1]; // std::cout << position->get_position()[1] << std::endl; // dest.w = drawable->get_width(); // std::cout << drawable->get_width() << std::endl; // dest.h = drawable->get_height(); // std::cout << drawable->get_height() << std::endl; // SDL_RenderCopy(m_game->get_renderer(), // m_game->get_res_manager().get_texture(drawable->get_texture_key()), // NULL, // &dest); // } // SDL_SetRenderDrawColor(m_game->get_renderer(), 255, 100, 200, 255); // SDL_Rect rect{0, 0, 400, 400}; // SDL_RenderFillRect(m_game->get_renderer(), &rect); // SDL_RenderPresent(m_game->get_renderer()); // } // private: // Game *m_game; // SDL_Rect m_camera; // }; // ======= #include "game.hpp" #include "component_drawable.hpp" #include "component_position.hpp" #include "strapon/resource_manager/resource_manager.hpp" #include "entityx/entityx.h" #include <glm/vec2.hpp> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> class DrawSystem : public entityx::System<DrawSystem> { public: DrawSystem(Game *game) : m_game(game) { int w, h; SDL_RenderGetLogicalSize(game->get_renderer(), &w, &h); m_camera = SDL_Rect{0, 0, w, h}; m_drawtex = SDL_CreateTexture(game->get_renderer(), SDL_PIXELTYPE_UNKNOWN, SDL_TEXTUREACCESS_TARGET, game->get_worldsize().w, game->get_worldsize().h); } ~DrawSystem() { SDL_DestroyTexture(m_drawtex); } void update(entityx::EntityManager &es, entityx::EventManager &events, entityx::TimeDelta dt) override { SDL_SetRenderTarget(m_game->get_renderer(), m_drawtex); SDL_SetRenderDrawColor(m_game->get_renderer(), 0, 100, 200, 255); SDL_RenderClear(m_game->get_renderer()); entityx::ComponentHandle<Drawable> drawable; entityx::ComponentHandle<Position> position; for (entityx::Entity entity : es.entities_with_components(drawable, position)) { (void)entity; SDL_Rect dest; dest.x = position->get_position()[0]; std::cout << position->get_position()[0] << std::endl; dest.y = position->get_position()[1]; std::cout << position->get_position()[1] << std::endl; dest.w = drawable->get_width(); std::cout << drawable->get_width() << std::endl; dest.h = drawable->get_height(); std::cout << drawable->get_height() << std::endl; SDL_RenderCopy(m_game->get_renderer(), m_game->get_res_manager().get_texture(drawable->get_texture_key()), NULL, &dest); } SDL_SetRenderDrawColor(m_game->get_renderer(), 255, 100, 200, 255); SDL_Rect rect{0, 0, 400, 400}; SDL_RenderFillRect(m_game->get_renderer(), &rect); int x, y; SDL_GetMouseState(&x, &y); m_camera.x = x - m_camera.w/2; m_camera.y = y - m_camera.h/2; if (m_camera.x < 0) m_camera.x = 0; else if (m_camera.x > m_game->get_worldsize().w - m_camera.w) m_camera.x = m_game->get_worldsize().w - m_camera.w; if (m_camera.y < 0) m_camera.y = 0; else if (m_camera.y > m_game->get_worldsize().h - m_camera.h) m_camera.y = m_game->get_worldsize().h - m_camera.h; std::cout << m_camera.x << " " << m_camera.y << std::endl; SDL_SetRenderTarget(m_game->get_renderer(), nullptr); SDL_RenderCopy(m_game->get_renderer(), m_drawtex, &m_camera, nullptr); SDL_RenderPresent(m_game->get_renderer()); } private: Game *m_game; SDL_Rect m_camera; SDL_Texture *m_drawtex; }; <commit_msg>camera now follows the player<commit_after>// <<<<<<< HEAD // #include "game.hpp" // #include "component_drawable.hpp" // #include "component_position.hpp" // #include "strapon/resource_manager/resource_manager.hpp" // #include "entityx/entityx.h" // #include <glm/vec2.hpp> // #include <SDL2/SDL.h> // #include <SDL2/SDL_image.h> // // class DrawSystem : public entityx::System<DrawSystem> // { // public: // DrawSystem(Game *game) : m_game(game) { // int w, h; // SDL_RenderGetLogicalSize(game->get_renderer(), &w, &h); // m_camera = SDL_Rect{0, 0, w, h}; // } // void update(entityx::EntityManager &es, entityx::EventManager &events, entityx::TimeDelta dt) override // { // SDL_SetRenderDrawColor(m_game->get_renderer(), 0, 100, 200, 255); // SDL_RenderClear(m_game->get_renderer()); // entityx::ComponentHandle<Drawable> drawable; // entityx::ComponentHandle<Position> position; // for (entityx::Entity entity : es.entities_with_components(drawable, position)) // { // (void)entity; // SDL_Rect dest; // dest.x = position->get_position()[0]; // std::cout << position->get_position()[0] << std::endl; // dest.y = position->get_position()[1]; // std::cout << position->get_position()[1] << std::endl; // dest.w = drawable->get_width(); // std::cout << drawable->get_width() << std::endl; // dest.h = drawable->get_height(); // std::cout << drawable->get_height() << std::endl; // SDL_RenderCopy(m_game->get_renderer(), // m_game->get_res_manager().get_texture(drawable->get_texture_key()), // NULL, // &dest); // } // SDL_SetRenderDrawColor(m_game->get_renderer(), 255, 100, 200, 255); // SDL_Rect rect{0, 0, 400, 400}; // SDL_RenderFillRect(m_game->get_renderer(), &rect); // SDL_RenderPresent(m_game->get_renderer()); // } // private: // Game *m_game; // SDL_Rect m_camera; // }; // ======= #include "game.hpp" #include "component_drawable.hpp" #include "component_position.hpp" #include "strapon/resource_manager/resource_manager.hpp" #include "entityx/entityx.h" #include <glm/vec2.hpp> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> class DrawSystem : public entityx::System<DrawSystem> { public: DrawSystem(Game *game) : m_game(game) { int w, h; SDL_RenderGetLogicalSize(game->get_renderer(), &w, &h); m_camera = SDL_Rect{0, 0, w, h}; m_drawtex = SDL_CreateTexture(game->get_renderer(), SDL_PIXELTYPE_UNKNOWN, SDL_TEXTUREACCESS_TARGET, game->get_worldsize().w, game->get_worldsize().h); } ~DrawSystem() { SDL_DestroyTexture(m_drawtex); } void update(entityx::EntityManager &es, entityx::EventManager &events, entityx::TimeDelta dt) override { SDL_SetRenderTarget(m_game->get_renderer(), m_drawtex); SDL_SetRenderDrawColor(m_game->get_renderer(), 0, 100, 200, 255); SDL_RenderClear(m_game->get_renderer()); entityx::ComponentHandle<Drawable> drawable; entityx::ComponentHandle<Position> position; entityx::ComponentHandle<Controlable> controlable; for (entityx::Entity entity : es.entities_with_components(drawable, position)) { (void)entity; SDL_Rect dest; dest.x = position->get_position()[0]; std::cout << position->get_position()[0] << std::endl; dest.y = position->get_position()[1]; std::cout << position->get_position()[1] << std::endl; dest.w = drawable->get_width(); std::cout << drawable->get_width() << std::endl; dest.h = drawable->get_height(); std::cout << drawable->get_height() << std::endl; SDL_RenderCopy(m_game->get_renderer(), m_game->get_res_manager().get_texture(drawable->get_texture_key()), NULL, &dest); } SDL_SetRenderDrawColor(m_game->get_renderer(), 255, 100, 200, 255); SDL_Rect rect{0, 0, 400, 400}; SDL_RenderFillRect(m_game->get_renderer(), &rect); for (entityx::Entity player : es.entities_with_components(controlable, position)) { (void)player; //SDL_GetMouseState(&x, &y); m_camera.x = position->get_position()[0] - m_camera.w/2; m_camera.y = position->get_position()[1] - m_camera.h/2; if (m_camera.x < 0) m_camera.x = 0; else if (m_camera.x > m_game->get_worldsize().w - m_camera.w) m_camera.x = m_game->get_worldsize().w - m_camera.w; if (m_camera.y < 0) m_camera.y = 0; else if (m_camera.y > m_game->get_worldsize().h - m_camera.h) m_camera.y = m_game->get_worldsize().h - m_camera.h; std::cout << m_camera.x << " " << m_camera.y << std::endl; } SDL_SetRenderTarget(m_game->get_renderer(), nullptr); SDL_RenderCopy(m_game->get_renderer(), m_drawtex, &m_camera, nullptr); SDL_RenderPresent(m_game->get_renderer()); } private: Game *m_game; SDL_Rect m_camera; SDL_Texture *m_drawtex; }; <|endoftext|>
<commit_before>#include "tarsnaptask.h" #include "utils.h" #include "debug.h" #if defined Q_OS_UNIX #include <signal.h> #endif #define DEFAULT_TIMEOUT_MS 5000 #define LOG_MAX_LENGTH 10240 TarsnapTask::TarsnapTask() : QObject(), _process(nullptr), _truncateLogOutput(false) { } TarsnapTask::~TarsnapTask() { } void TarsnapTask::run() { _process = new QProcess(); if(_standardOutFile.isEmpty()) _process->setProcessChannelMode(QProcess::MergedChannels); else _process->setStandardOutputFile(_standardOutFile); _process->setProgram(_command); _process->setArguments(_arguments); LOG << tr("Executing command:\n[%1 %2]") .arg(_process->program()) .arg(Utils::quoteCommandLine(_process->arguments())); _process->start(); if(_process->waitForStarted(DEFAULT_TIMEOUT_MS)) { emit started(_data); } else { processError(); goto cleanup; } if(!_standardIn.isEmpty()) { QByteArray password(_standardIn.toUtf8()); _process->write(password.data(), password.size()); _process->closeWriteChannel(); } if(_process->waitForFinished(-1)) { readProcessOutput(); processFinished(); } else { processError(); goto cleanup; } cleanup: delete _process; _process = nullptr; emit dequeue(); } void TarsnapTask::stop(bool kill) { if(_process->state() == QProcess::Running) { _process->terminate(); if(kill && (false == _process->waitForFinished(DEFAULT_TIMEOUT_MS))) _process->kill(); } } void TarsnapTask::interrupt() { #if defined Q_OS_UNIX kill(_process->pid(), SIGQUIT); #endif } void TarsnapTask::cancel() { emit canceled(_data); } bool TarsnapTask::waitForTask() { return _process->waitForFinished(-1); } QProcess::ProcessState TarsnapTask::taskStatus() { return _process->state(); } QString TarsnapTask::command() const { return _command; } void TarsnapTask::setCommand(const QString &command) { _command = command; } QStringList TarsnapTask::arguments() const { return _arguments; } void TarsnapTask::setArguments(const QStringList &arguments) { _arguments = arguments; } QString TarsnapTask::standardIn() const { return _standardIn; } void TarsnapTask::setStandardIn(const QString &standardIn) { _standardIn = standardIn; } void TarsnapTask::setStandardOutputFile(const QString &fileName) { _standardOutFile = fileName; } QVariant TarsnapTask::data() const { return _data; } void TarsnapTask::setData(const QVariant &data) { _data = data; } bool TarsnapTask::truncateLogOutput() const { return _truncateLogOutput; } void TarsnapTask::setTruncateLogOutput(bool truncateLogOutput) { _truncateLogOutput = truncateLogOutput; } void TarsnapTask::readProcessOutput() { if(_process->processChannelMode() == QProcess::MergedChannels) _processOutput.append(_process->readAll()); else _processOutput.append(_process->readAllStandardError()); } void TarsnapTask::processFinished() { switch(_process->exitStatus()) { case QProcess::NormalExit: { QString output(_processOutput); output = output.trimmed(); emit finished(_data, _process->exitCode(), output); if(!output.isEmpty()) { if(_truncateLogOutput && (output.size() > LOG_MAX_LENGTH)) { output.truncate(LOG_MAX_LENGTH); output.append(tr("\n...\n-- Output truncated by Tarsnap GUI --")); } LOG << tr("Command finished with exit code %3 and output:\n[%1 %2]\n%4") .arg(_command) .arg(Utils::quoteCommandLine(_arguments)) .arg(_process->exitCode()) .arg(output); } else { LOG << tr("Command finished with exit code %3 and no output:\n[%1 %2]") .arg(_command) .arg(Utils::quoteCommandLine(_arguments)) .arg(_process->exitCode()); } } break; case QProcess::CrashExit: processError(); break; } } void TarsnapTask::processError() { LOG << tr("Tarsnap process error %1 (%2) occured (exit code %3):\n%4") .arg(_process->error()) .arg(_process->errorString()) .arg(_process->exitCode()) .arg(QString(_processOutput).trimmed()); cancel(); } <commit_msg>Add missing command-line to log message.<commit_after>#include "tarsnaptask.h" #include "utils.h" #include "debug.h" #if defined Q_OS_UNIX #include <signal.h> #endif #define DEFAULT_TIMEOUT_MS 5000 #define LOG_MAX_LENGTH 10240 TarsnapTask::TarsnapTask() : QObject(), _process(nullptr), _truncateLogOutput(false) { } TarsnapTask::~TarsnapTask() { } void TarsnapTask::run() { _process = new QProcess(); if(_standardOutFile.isEmpty()) _process->setProcessChannelMode(QProcess::MergedChannels); else _process->setStandardOutputFile(_standardOutFile); _process->setProgram(_command); _process->setArguments(_arguments); LOG << tr("Executing command:\n[%1 %2]") .arg(_process->program()) .arg(Utils::quoteCommandLine(_process->arguments())); _process->start(); if(_process->waitForStarted(DEFAULT_TIMEOUT_MS)) { emit started(_data); } else { processError(); goto cleanup; } if(!_standardIn.isEmpty()) { QByteArray password(_standardIn.toUtf8()); _process->write(password.data(), password.size()); _process->closeWriteChannel(); } if(_process->waitForFinished(-1)) { readProcessOutput(); processFinished(); } else { processError(); goto cleanup; } cleanup: delete _process; _process = nullptr; emit dequeue(); } void TarsnapTask::stop(bool kill) { if(_process->state() == QProcess::Running) { _process->terminate(); if(kill && (false == _process->waitForFinished(DEFAULT_TIMEOUT_MS))) _process->kill(); } } void TarsnapTask::interrupt() { #if defined Q_OS_UNIX kill(_process->pid(), SIGQUIT); #endif } void TarsnapTask::cancel() { emit canceled(_data); } bool TarsnapTask::waitForTask() { return _process->waitForFinished(-1); } QProcess::ProcessState TarsnapTask::taskStatus() { return _process->state(); } QString TarsnapTask::command() const { return _command; } void TarsnapTask::setCommand(const QString &command) { _command = command; } QStringList TarsnapTask::arguments() const { return _arguments; } void TarsnapTask::setArguments(const QStringList &arguments) { _arguments = arguments; } QString TarsnapTask::standardIn() const { return _standardIn; } void TarsnapTask::setStandardIn(const QString &standardIn) { _standardIn = standardIn; } void TarsnapTask::setStandardOutputFile(const QString &fileName) { _standardOutFile = fileName; } QVariant TarsnapTask::data() const { return _data; } void TarsnapTask::setData(const QVariant &data) { _data = data; } bool TarsnapTask::truncateLogOutput() const { return _truncateLogOutput; } void TarsnapTask::setTruncateLogOutput(bool truncateLogOutput) { _truncateLogOutput = truncateLogOutput; } void TarsnapTask::readProcessOutput() { if(_process->processChannelMode() == QProcess::MergedChannels) _processOutput.append(_process->readAll()); else _processOutput.append(_process->readAllStandardError()); } void TarsnapTask::processFinished() { switch(_process->exitStatus()) { case QProcess::NormalExit: { QString output(_processOutput); output = output.trimmed(); emit finished(_data, _process->exitCode(), output); if(!output.isEmpty()) { if(_truncateLogOutput && (output.size() > LOG_MAX_LENGTH)) { output.truncate(LOG_MAX_LENGTH); output.append(tr("\n...\n-- Output truncated by Tarsnap GUI --")); } LOG << tr("Command finished with exit code %3 and output:\n[%1 %2]\n%4") .arg(_command) .arg(Utils::quoteCommandLine(_arguments)) .arg(_process->exitCode()) .arg(output); } else { LOG << tr("Command finished with exit code %3 and no output:\n[%1 %2]") .arg(_command) .arg(Utils::quoteCommandLine(_arguments)) .arg(_process->exitCode()); } } break; case QProcess::CrashExit: processError(); break; } } void TarsnapTask::processError() { LOG << tr("Tarsnap process error %3 (%4) occured (exit code %5):\n[%1 %2]\n%6") .arg(_command) .arg(Utils::quoteCommandLine(_arguments)) .arg(_process->error()) .arg(_process->errorString()) .arg(_process->exitCode()) .arg(QString(_processOutput).trimmed()); cancel(); } <|endoftext|>
<commit_before>#ifndef __TEXT_SERVER_H__ #define __TEXT_SERVER_H__ #include "connection.hpp" #include <arpa/inet.h> #include <errno.h> #include <string.h> // memset #include <unistd.h> #include <thread> namespace httptth { class scoped_fd { public: explicit scoped_fd(int descriptor) : fd(descriptor) {} ~scoped_fd() { close(fd); } scoped_fd(const scoped_fd &) = delete; scoped_fd(scoped_fd &&that) : fd(that.fd) { that.fd = -1; } scoped_fd &operator =(const scoped_fd &) = delete; inline operator int() { return fd; } private: int fd; }; // generic line-based text server template<typename handler> class text_server { public: explicit text_server(const handler &h) : prototype(h), stop_requested(false) {} explicit text_server(handler &&h) : prototype(std::move(h)), stop_requested(false) {} text_server(const text_server &) = delete; text_server &operator =(const text_server &) = delete; text_server(const text_server &&) = delete; text_server &operator =(const text_server &&) = delete; void listen(const char *address, int port); inline void stop() { stop_requested = true; } protected: struct context { handler h; connection conn; // context must always copy the handler context(int fd, const handler &hdl) : h(hdl), conn(fd, ([&](const char *s, size_t l) { return h(s, l); })) {} }; private: handler prototype; bool stop_requested; static const time_t timeout = 5; void process_client(int fd); }; template<typename handler> void text_server<handler>::listen(const char *address, int port) { sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(port); if (address) { int status = inet_pton(AF_INET, address, &addr.sin_addr); if (status <= 0) { throw generic_exception(); } } else { addr.sin_addr.s_addr = htonl(INADDR_ANY); } scoped_fd listenfd(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); if (listenfd < 0) { perror("socket"); throw network_exception(); } int e = 1; int rc = setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &e, sizeof e); if (rc < 0) { dprintf(logger::ERR, "setsockopt"); throw network_exception(); } rc = bind(listenfd, (sockaddr *)&addr, sizeof(addr)); if (rc < 0) { perror("bind"); throw network_exception(); } rc = ::listen(listenfd, 128); if (rc < 0) { perror("listen"); throw network_exception(); } // trivial event loop // later: init "listen thread" and detach it struct timeval tv; tv.tv_sec = timeout; tv.tv_usec = 0; stop_requested = false; while (true) { // TODO: loop exit condition if (stop_requested) { // possibly log something later break; } sockaddr_in client_addr; socklen_t l = sizeof(client_addr); int fd = accept(listenfd, (sockaddr *)&client_addr, &l); if (fd < 0) { perror("accept failed"); continue; } setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval)); // status: read() times out, but this is not handled yet std::thread t(&text_server<handler>::process_client, this, fd); t.detach(); } // while (true } template<typename handler> void text_server<handler>::process_client(int fd) { try { dprintf(logger::DEBUG, "client fd=%d", fd); context ctx(fd, prototype); // bind the third parameter (or use std::bind instead) auto read_handler = [&ctx](const char *line, size_t length) { dprintf(logger::DEBUG, "\\(l=%zu) %.*s", length, (int)length, line); ctx.h(line, length, ctx.conn); }; readable::handler_type f(std::ref(read_handler)); // actually, that could be enough: // while (ctx.conn.read_line(f) == readable::status::ok) ; while (true) { readable::status status = ctx.conn.read_line(f); if (status == readable::status::eof) { break; } if (status == readable::status::again) { // consider this a timeout // a problem: some leftover bytes might still be in the buffer // but do we care, as we are about to disconnect this client? dprintf(logger::DEBUG, "client %d timed out", fd); break; } } // while (true) dprintf(logger::DEBUG, "client fd=%d: done", fd); // close (and therefore flush) should be called automatically } catch (generic_exception &e) { dprintf(logger::WARNING, "excpetion: %s", e.what()); } catch (std::exception &e) { dprintf(logger::WARNING, "std::excpetion: %s", e.what()); } } // default implementation (with triggering on each new line) // a handler that is a pure function, without a trigger using stateless_handler = std::function<void(const char *, size_t, writable &)>; // handler_type implementation that triggers client function on each new line struct on_new_line { on_new_line(const stateless_handler &f) : h(f) {} on_new_line(stateless_handler &&f) : h(std::move(f)) {} void operator()(const char *s, size_t l, writable &dst) { h(s, l, dst); } bool operator()(const char *s, size_t l) { return s[l - 1] == '\n'; } stateless_handler h; }; // text server with on_new_line handler class line_feed_text_server : public text_server<on_new_line> { public: line_feed_text_server(stateless_handler h) : text_server<on_new_line>(on_new_line(h)) {} }; } // namespace httptth #endif // __TEXT_SERVER_H__ <commit_msg>separate constructors for const lvalue and rvalue references in line feed server, length check in on new line trigger<commit_after>#ifndef __TEXT_SERVER_H__ #define __TEXT_SERVER_H__ #include "connection.hpp" #include <arpa/inet.h> #include <errno.h> #include <string.h> // memset #include <unistd.h> #include <thread> namespace httptth { class scoped_fd { public: explicit scoped_fd(int descriptor) : fd(descriptor) {} ~scoped_fd() { close(fd); } scoped_fd(const scoped_fd &) = delete; scoped_fd(scoped_fd &&that) : fd(that.fd) { that.fd = -1; } scoped_fd &operator =(const scoped_fd &) = delete; inline operator int() { return fd; } private: int fd; }; // generic line-based text server template<typename handler> class text_server { public: explicit text_server(const handler &h) : prototype(h), stop_requested(false) {} explicit text_server(handler &&h) : prototype(std::move(h)), stop_requested(false) {} text_server(const text_server &) = delete; text_server &operator =(const text_server &) = delete; text_server(const text_server &&) = delete; text_server &operator =(const text_server &&) = delete; void listen(const char *address, int port); inline void stop() { stop_requested = true; } protected: struct context { handler h; connection conn; // context must always copy the handler context(int fd, const handler &hdl) : h(hdl), conn(fd, ([&](const char *s, size_t l) { return h(s, l); })) {} }; private: handler prototype; bool stop_requested; static const time_t timeout = 5; void process_client(int fd); }; template<typename handler> void text_server<handler>::listen(const char *address, int port) { sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(port); if (address) { int status = inet_pton(AF_INET, address, &addr.sin_addr); if (status <= 0) { throw generic_exception(); } } else { addr.sin_addr.s_addr = htonl(INADDR_ANY); } scoped_fd listenfd(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); if (listenfd < 0) { perror("socket"); throw network_exception(); } int e = 1; int rc = setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &e, sizeof e); if (rc < 0) { dprintf(logger::ERR, "setsockopt"); throw network_exception(); } rc = bind(listenfd, (sockaddr *)&addr, sizeof(addr)); if (rc < 0) { perror("bind"); throw network_exception(); } rc = ::listen(listenfd, 128); if (rc < 0) { perror("listen"); throw network_exception(); } // trivial event loop // later: init "listen thread" and detach it struct timeval tv; tv.tv_sec = timeout; tv.tv_usec = 0; stop_requested = false; while (true) { // TODO: loop exit condition if (stop_requested) { // possibly log something later break; } sockaddr_in client_addr; socklen_t l = sizeof(client_addr); int fd = accept(listenfd, (sockaddr *)&client_addr, &l); if (fd < 0) { perror("accept failed"); continue; } setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval)); // status: read() times out, but this is not handled yet std::thread t(&text_server<handler>::process_client, this, fd); t.detach(); } // while (true } template<typename handler> void text_server<handler>::process_client(int fd) { try { dprintf(logger::DEBUG, "client fd=%d", fd); context ctx(fd, prototype); // bind the third parameter (or use std::bind instead) auto read_handler = [&ctx](const char *line, size_t length) { dprintf(logger::DEBUG, "\\(l=%zu) %.*s", length, (int)length, line); ctx.h(line, length, ctx.conn); }; readable::handler_type f(std::ref(read_handler)); // actually, that could be enough: // while (ctx.conn.read_line(f) == readable::status::ok) ; while (true) { readable::status status = ctx.conn.read_line(f); if (status == readable::status::eof) { break; } if (status == readable::status::again) { // consider this a timeout // a problem: some leftover bytes might still be in the buffer // but do we care, as we are about to disconnect this client? dprintf(logger::DEBUG, "client %d timed out", fd); break; } } // while (true) dprintf(logger::DEBUG, "client fd=%d: done", fd); // close (and therefore flush) should be called automatically } catch (generic_exception &e) { dprintf(logger::WARNING, "excpetion: %s", e.what()); } catch (std::exception &e) { dprintf(logger::WARNING, "std::excpetion: %s", e.what()); } } // default implementation (with triggering on each new line) // a handler that is a pure function, without a trigger using stateless_handler = std::function<void(const char *, size_t, writable &)>; // handler_type implementation that triggers client function on each new line struct on_new_line { on_new_line(const stateless_handler &f) : h(f) {} on_new_line(stateless_handler &&f) : h(std::move(f)) {} void operator()(const char *s, size_t l, writable &dst) { h(s, l, dst); } bool operator()(const char *s, size_t l) { return l && s[l - 1] == '\n'; } stateless_handler h; }; // text server with on_new_line handler class line_feed_text_server : public text_server<on_new_line> { public: line_feed_text_server(const stateless_handler &h) : text_server<on_new_line>(on_new_line(h)) {} line_feed_text_server(stateless_handler &&h) : text_server<on_new_line>(on_new_line(std::move(h))) {} }; } // namespace httptth #endif // __TEXT_SERVER_H__ <|endoftext|>
<commit_before>// // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Wed Nov 30 01:02:57 PST 2016 // Last Modified: Fri Dec 2 03:45:34 PST 2016 // Filename: tool-filter.cpp // URL: https://github.com/craigsapp/minHumdrum/blob/master/src/tool-filter.cpp // Syntax: C++11 // vim: syntax=cpp ts=3 noexpandtab nowrap // // Description: Example of extracting a 2D pitch grid from // a score for dissonance analysis. // #include "tool-filter.h" // tools which filter can process: #include "tool-autobeam.h" #include "tool-autostem.h" #include "tool-extract.h" #include "tool-recip.h" #include "tool-satb2gs.h" #include "tool-metlev.h" #include "tool-transpose.h" #include "HumRegex.h" #include <algorithm> #include <cmath> using namespace std; namespace hum { // START_MERGE #define RUNTOOL(NAME, INFILE, COMMAND, STATUS) \ Tool_##NAME *tool = new Tool_##NAME; \ tool->process(COMMAND); \ tool->run(INFILE); \ if (tool->hasError()) { \ status = false; \ tool->getError(cerr); \ delete tool; \ break; \ } else if (tool->hasHumdrumText()) { \ INFILE.readString(tool->getHumdrumText()); \ } \ delete tool; //////////////////////////////// // // Tool_filter::Tool_filter -- Set the recognized options for the tool. // Tool_filter::Tool_filter(void) { define("debug=b", "print debug statement"); } ///////////////////////////////// // // Tool_filter::run -- Primary interfaces to the tool. // bool Tool_filter::run(const string& indata, ostream& out) { HumdrumFile infile(indata); bool status = run(infile); if (hasAnyText()) { getAllText(out); } else { out << infile; } return status; } bool Tool_filter::run(HumdrumFile& infile, ostream& out) { int status = run(infile); if (hasAnyText()) { getAllText(out); } else { out << infile; } return status; } // // In-place processing of file: // bool Tool_filter::run(HumdrumFile& infile) { initialize(infile); bool status = true; vector<pair<string, string> > commands; getCommandList(commands, infile); for (int i=0; i<(int)commands.size(); i++) { if (commands[i].first == "autobeam") { RUNTOOL(autobeam, infile, commands[i].second, status); } else if (commands[i].first == "autostem") { RUNTOOL(autostem, infile, commands[i].second, status); } else if (commands[i].first == "extract") { RUNTOOL(extract, infile, commands[i].second, status); } else if (commands[i].first == "metlev") { RUNTOOL(metlev, infile, commands[i].second, status); } else if (commands[i].first == "satb2gs") { RUNTOOL(satb2gs, infile, commands[i].second, status); } else if (commands[i].first == "recip") { RUNTOOL(recip, infile, commands[i].second, status); } else if (commands[i].first == "transpose") { RUNTOOL(transpose, infile, commands[i].second, status); } } // Re-load the text for each line from their tokens in case any // updates are needed from token changes. infile.createLinesFromTokens(); return status; } ////////////////////////////// // // Tool_filter::getCommandList -- // void Tool_filter::getCommandList(vector<pair<string, string> >& commands, HumdrumFile& infile) { vector<HumdrumLine*> refs = infile.getReferenceRecords(); pair<string, string> entry; string tag = "filter"; vector<string> clist; HumRegex hre; if (m_variant.size() > 0) { tag += "-"; tag += m_variant; } for (int i=0; i<(int)refs.size(); i++) { if (refs[i]->getReferenceKey() != tag) { continue; } string command = refs[i]->getReferenceValue(); hre.split(clist, command, "\\s*\\|\\s*"); for (int j=0; j<(int)clist.size(); j++) { if (hre.search(clist[j], "^\\s*([^\\s]+)")) { entry.first = hre.getMatch(1); entry.second = clist[j]; commands.push_back(entry); } } } } ////////////////////////////// // // Tool_filter::initialize -- extract time signature lines for // each **kern spine in file. // void Tool_filter::initialize(HumdrumFile& infile) { m_debugQ = getBoolean("debug"); } // END_MERGE } // end namespace hum <commit_msg>Added myank to filter.<commit_after>// // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Wed Nov 30 01:02:57 PST 2016 // Last Modified: Fri Dec 2 03:45:34 PST 2016 // Filename: tool-filter.cpp // URL: https://github.com/craigsapp/minHumdrum/blob/master/src/tool-filter.cpp // Syntax: C++11 // vim: syntax=cpp ts=3 noexpandtab nowrap // // Description: Example of extracting a 2D pitch grid from // a score for dissonance analysis. // #include "tool-filter.h" // tools which filter can process: #include "tool-autobeam.h" #include "tool-autostem.h" #include "tool-extract.h" #include "tool-recip.h" #include "tool-satb2gs.h" #include "tool-metlev.h" #include "tool-myank.h" #include "tool-transpose.h" #include "HumRegex.h" #include <algorithm> #include <cmath> using namespace std; namespace hum { // START_MERGE #define RUNTOOL(NAME, INFILE, COMMAND, STATUS) \ Tool_##NAME *tool = new Tool_##NAME; \ tool->process(COMMAND); \ tool->run(INFILE); \ if (tool->hasError()) { \ status = false; \ tool->getError(cerr); \ delete tool; \ break; \ } else if (tool->hasHumdrumText()) { \ INFILE.readString(tool->getHumdrumText()); \ } \ delete tool; //////////////////////////////// // // Tool_filter::Tool_filter -- Set the recognized options for the tool. // Tool_filter::Tool_filter(void) { define("debug=b", "print debug statement"); } ///////////////////////////////// // // Tool_filter::run -- Primary interfaces to the tool. // bool Tool_filter::run(const string& indata, ostream& out) { HumdrumFile infile(indata); bool status = run(infile); if (hasAnyText()) { getAllText(out); } else { out << infile; } return status; } bool Tool_filter::run(HumdrumFile& infile, ostream& out) { int status = run(infile); if (hasAnyText()) { getAllText(out); } else { out << infile; } return status; } // // In-place processing of file: // bool Tool_filter::run(HumdrumFile& infile) { initialize(infile); bool status = true; vector<pair<string, string> > commands; getCommandList(commands, infile); for (int i=0; i<(int)commands.size(); i++) { if (commands[i].first == "autobeam") { RUNTOOL(autobeam, infile, commands[i].second, status); } else if (commands[i].first == "autostem") { RUNTOOL(autostem, infile, commands[i].second, status); } else if (commands[i].first == "extract") { RUNTOOL(extract, infile, commands[i].second, status); } else if (commands[i].first == "metlev") { RUNTOOL(metlev, infile, commands[i].second, status); } else if (commands[i].first == "satb2gs") { RUNTOOL(satb2gs, infile, commands[i].second, status); } else if (commands[i].first == "recip") { RUNTOOL(recip, infile, commands[i].second, status); } else if (commands[i].first == "transpose") { RUNTOOL(transpose, infile, commands[i].second, status); } else if (commands[i].first == "myank") { RUNTOOL(myank, infile, commands[i].second, status); } } // Re-load the text for each line from their tokens in case any // updates are needed from token changes. infile.createLinesFromTokens(); return status; } ////////////////////////////// // // Tool_filter::getCommandList -- // void Tool_filter::getCommandList(vector<pair<string, string> >& commands, HumdrumFile& infile) { vector<HumdrumLine*> refs = infile.getReferenceRecords(); pair<string, string> entry; string tag = "filter"; vector<string> clist; HumRegex hre; if (m_variant.size() > 0) { tag += "-"; tag += m_variant; } for (int i=0; i<(int)refs.size(); i++) { if (refs[i]->getReferenceKey() != tag) { continue; } string command = refs[i]->getReferenceValue(); hre.split(clist, command, "\\s*\\|\\s*"); for (int j=0; j<(int)clist.size(); j++) { if (hre.search(clist[j], "^\\s*([^\\s]+)")) { entry.first = hre.getMatch(1); entry.second = clist[j]; commands.push_back(entry); } } } } ////////////////////////////// // // Tool_filter::initialize -- extract time signature lines for // each **kern spine in file. // void Tool_filter::initialize(HumdrumFile& infile) { m_debugQ = getBoolean("debug"); } // END_MERGE } // end namespace hum <|endoftext|>
<commit_before>/* * Copyright 2017-2018 Tom van Dijk, Johannes Kepler University Linz * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <fstream> #include "game.hpp" using namespace pg; int main(int argc, char **argv) { Game game; if (argc >= 2) { std::ifstream file(argv[1]); game.parse_pgsolver(file, false); file.close(); } else { game.parse_pgsolver(std::cin); } if (argc >= 3) { std::ofstream file(argv[2]); game.write_dot(file); file.close(); } else { game.write_dot(std::cout); } return 0; } <commit_msg>Ensure dotty doesn't apply optimizations<commit_after>/* * Copyright 2017-2018 Tom van Dijk, Johannes Kepler University Linz * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <fstream> #include "game.hpp" using namespace pg; int main(int argc, char **argv) { Game game; if (argc >= 2) { std::ifstream file(argv[1]); game.parse_pgsolver(file, false); file.close(); } else { game.parse_pgsolver(std::cin, false); } if (argc >= 3) { std::ofstream file(argv[2]); game.write_dot(file); file.close(); } else { game.write_dot(std::cout); } return 0; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2016 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdexcept> #include "polyfill.h" #include "trace_buffer.h" TraceBufferChunk::TraceBufferChunk(size_t _generation, size_t _buffer_index) : thread_id(std::this_thread::get_id()), generation(_generation), buffer_index(_buffer_index), next_free(0) { } bool TraceBufferChunk::isFull() const { return next_free == chunk.max_size(); } size_t TraceBufferChunk::count() const { return next_free; } size_t TraceBufferChunk::getIndex() const { return buffer_index; } size_t TraceBufferChunk::getGeneration() const { return generation; } void TraceBufferChunk::addEvent(TraceEvent&& event) { if(isFull()) { throw std::out_of_range("All events in chunk have been used"); } chunk[next_free++] = event; } TraceEvent& TraceBufferChunk::addEvent() { if(isFull()) { throw std::out_of_range("All events in chunk have been used"); } return chunk[next_free++]; } const TraceEvent& TraceBufferChunk::operator[] (const int index) const { return chunk[index]; } /** * TraceBuffer implementation that stores events in a fixed-size * vector of unique pointers to BufferChunks. */ class FixedTraceBuffer : public TraceBuffer { public: FixedTraceBuffer(size_t generation_, size_t buffer_size_) : generation(generation_), buffer_size(buffer_size_) { buffer.reserve(buffer_size); } ~FixedTraceBuffer() override { } std::unique_ptr<TraceBufferChunk> getChunk() override { if(isFull()) { throw std::out_of_range("The TraceBuffer is full"); } auto index(buffer.size()); buffer.push_back(nullptr); return make_unique<TraceBufferChunk>(generation, index); } void returnChunk(chunk_ptr&& chunk) override { if(chunk->getGeneration() != generation) { throw std::invalid_argument("Chunk is not from this buffer"); } buffer.at(chunk->getIndex()) = std::move(chunk); } bool isFull() const override { return buffer.size() >= buffer_size; } size_t getGeneration() const override { return generation; } TraceEventIterator begin() const override { std::cerr << buffer.size() << std::endl; return TraceEventIterator(buffer.begin()); } TraceEventIterator end() const override { return TraceEventIterator(buffer.end()); } protected: std::vector<chunk_ptr> buffer; size_t generation; size_t buffer_size; }; std::unique_ptr<TraceBuffer> make_fixed_buffer(size_t generation, size_t buffer_size) { return make_unique<FixedTraceBuffer>(generation, buffer_size); } <commit_msg>Remove debug logging in trace_buffer<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2016 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdexcept> #include "polyfill.h" #include "trace_buffer.h" TraceBufferChunk::TraceBufferChunk(size_t _generation, size_t _buffer_index) : thread_id(std::this_thread::get_id()), generation(_generation), buffer_index(_buffer_index), next_free(0) { } bool TraceBufferChunk::isFull() const { return next_free == chunk.max_size(); } size_t TraceBufferChunk::count() const { return next_free; } size_t TraceBufferChunk::getIndex() const { return buffer_index; } size_t TraceBufferChunk::getGeneration() const { return generation; } void TraceBufferChunk::addEvent(TraceEvent&& event) { if(isFull()) { throw std::out_of_range("All events in chunk have been used"); } chunk[next_free++] = event; } TraceEvent& TraceBufferChunk::addEvent() { if(isFull()) { throw std::out_of_range("All events in chunk have been used"); } return chunk[next_free++]; } const TraceEvent& TraceBufferChunk::operator[] (const int index) const { return chunk[index]; } /** * TraceBuffer implementation that stores events in a fixed-size * vector of unique pointers to BufferChunks. */ class FixedTraceBuffer : public TraceBuffer { public: FixedTraceBuffer(size_t generation_, size_t buffer_size_) : generation(generation_), buffer_size(buffer_size_) { buffer.reserve(buffer_size); } ~FixedTraceBuffer() override { } std::unique_ptr<TraceBufferChunk> getChunk() override { if(isFull()) { throw std::out_of_range("The TraceBuffer is full"); } auto index(buffer.size()); buffer.push_back(nullptr); return make_unique<TraceBufferChunk>(generation, index); } void returnChunk(chunk_ptr&& chunk) override { if(chunk->getGeneration() != generation) { throw std::invalid_argument("Chunk is not from this buffer"); } buffer.at(chunk->getIndex()) = std::move(chunk); } bool isFull() const override { return buffer.size() >= buffer_size; } size_t getGeneration() const override { return generation; } TraceEventIterator begin() const override { return TraceEventIterator(buffer.begin()); } TraceEventIterator end() const override { return TraceEventIterator(buffer.end()); } protected: std::vector<chunk_ptr> buffer; size_t generation; size_t buffer_size; }; std::unique_ptr<TraceBuffer> make_fixed_buffer(size_t generation, size_t buffer_size) { return make_unique<FixedTraceBuffer>(generation, buffer_size); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2013 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "ep_engine.h" #include "upr-stream.h" UprConsumer::UprConsumer(EventuallyPersistentEngine &e, const void *cookie, const std::string &n) : Consumer(e), opaqueCounter(0) { conn_ = new Connection(this, cookie, n); conn_->setSupportAck(true); conn_->setLogHeader("UPR (Consumer) " + conn_->getName() + " -"); setReserved(false); } ENGINE_ERROR_CODE UprConsumer::addStream(uint32_t opaque, uint16_t vbucket, uint32_t flags) { LockHolder lh(streamMutex); RCPtr<VBucket> vb = engine_.getVBucket(vbucket); if (!vb) { return ENGINE_NOT_MY_VBUCKET; } uint64_t start_seqno = vb->getHighSeqno(); uint64_t end_seqno = std::numeric_limits<uint64_t>::max(); uint64_t vbucket_uuid = 0; uint64_t high_seqno = start_seqno; uint32_t new_opaque = ++opaqueCounter; std::map<uint16_t, PassiveStream*>::iterator itr = streams_.find(vbucket); if (itr != streams_.end() && itr->second->isActive()) { return ENGINE_KEY_EEXISTS; } else if (itr != streams_.end()) { delete itr->second; streams_.erase(itr); } streams_[vbucket] = new PassiveStream(conn_->name, flags, new_opaque, vbucket, start_seqno, end_seqno, vbucket_uuid, high_seqno); opaqueMap_[new_opaque] = std::make_pair(opaque, vbucket); return ENGINE_SUCCESS; } ENGINE_ERROR_CODE UprConsumer::closeStream(uint32_t opaque, uint16_t vbucket) { LockHolder lh(streamMutex); opaque_map::iterator oitr = opaqueMap_.find(opaque); if (oitr != opaqueMap_.end()) { opaqueMap_.erase(oitr); } std::map<uint16_t, PassiveStream*>::iterator itr; if ((itr = streams_.find(vbucket)) == streams_.end()) { return ENGINE_KEY_ENOENT; } if (itr->second->getOpaque() != opaque) { return ENGINE_KEY_EEXISTS; } itr->second->setDead(); return ENGINE_SUCCESS; } ENGINE_ERROR_CODE UprConsumer::streamEnd(uint32_t opaque, uint16_t vbucket, uint32_t flags) { if (closeStream(opaque, vbucket) == ENGINE_SUCCESS) { LOG(EXTENSION_LOG_WARNING, "%s end stream received with reason %d", logHeader(), flags); } else { LOG(EXTENSION_LOG_WARNING, "%s end stream received but vbucket %d with" " opaque %d does not exist", logHeader(), vbucket, opaque); } return ENGINE_SUCCESS; } ENGINE_ERROR_CODE UprConsumer::mutation(uint32_t opaque, const void* key, uint16_t nkey, const void* value, uint32_t nvalue, uint64_t cas, uint16_t vbucket, uint32_t flags, uint8_t datatype, uint32_t locktime, uint64_t bySeqno, uint64_t revSeqno, uint32_t exptime, uint8_t nru, const void* meta, uint16_t nmeta) { ENGINE_ERROR_CODE ret = ENGINE_SUCCESS; if (!isValidOpaque(opaque, vbucket)) { return ENGINE_FAILED; } std::string key_str(static_cast<const char*>(key), nkey); value_t vblob(Blob::New(static_cast<const char*>(value), nvalue, NULL, 0)); Item *item = new Item(key_str, flags, exptime, vblob, cas, bySeqno, vbucket, revSeqno); if (isBackfillPhase(vbucket)) { ret = engine_.getEpStore()->addTAPBackfillItem(*item, meta, nru); } else { ret = engine_.getEpStore()->setWithMeta(*item, 0, conn_->cookie, true, true, nru); } return ret; } ENGINE_ERROR_CODE UprConsumer::deletion(uint32_t opaque, const void* key, uint16_t nkey, uint64_t cas, uint16_t vbucket, uint64_t bySeqno, uint64_t revSeqno, const void* meta, uint16_t nmeta) { ENGINE_ERROR_CODE ret; if (!isValidOpaque(opaque, vbucket)) { return ENGINE_FAILED; } uint64_t delCas = 0; ItemMetaData itemMeta(cas, revSeqno, 0, 0); std::string key_str((const char*)key, nkey); ret = engine_.getEpStore()->deleteWithMeta(key_str, &delCas, vbucket, conn_->cookie, true, &itemMeta, isBackfillPhase(vbucket)); if (ret == ENGINE_KEY_ENOENT) { ret = ENGINE_SUCCESS; } return ENGINE_SUCCESS; } ENGINE_ERROR_CODE UprConsumer::expiration(uint32_t opaque, const void* key, uint16_t nkey, uint64_t cas, uint16_t vbucket, uint64_t bySeqno, uint64_t revSeqno, const void* meta, uint16_t nmeta) { return ENGINE_ENOTSUP; } ENGINE_ERROR_CODE UprConsumer::snapshotMarker(uint32_t opaque, uint16_t vbucket) { (void) opaque; (void) vbucket; return ENGINE_SUCCESS; } ENGINE_ERROR_CODE UprConsumer::flush(uint32_t opaque, uint16_t vbucket) { (void) opaque; (void) vbucket; return ENGINE_ENOTSUP; } ENGINE_ERROR_CODE UprConsumer::setVBucketState(uint32_t opaque, uint16_t vbucket, vbucket_state_t state) { if (isValidOpaque(opaque, vbucket)) { return Consumer::setVBucketState(opaque, vbucket, state); } else { LOG(EXTENSION_LOG_WARNING, "Invalid opaque value for UPR-CONSUMER"); return ENGINE_FAILED; } } ENGINE_ERROR_CODE UprConsumer::step(struct upr_message_producers* producers) { UprResponse *resp = getNextItem(); if (resp == NULL) { return ENGINE_SUCCESS; // Change to tmpfail once mcd layer is fixed } switch (resp->getEvent()) { case UPR_ADD_STREAM: { AddStreamResponse *as = static_cast<AddStreamResponse*>(resp); producers->add_stream_rsp(conn_->cookie, as->getOpaque(), as->getStreamOpaque(), as->getStatus()); break; } case UPR_STREAM_REQ: { StreamRequest *sr = static_cast<StreamRequest*> (resp); producers->stream_req(conn_->cookie, sr->getOpaque(), sr->getVBucket(), sr->getFlags(), sr->getStartSeqno(), sr->getEndSeqno(), sr->getVBucketUUID(), sr->getHighSeqno()); break; } default: LOG(EXTENSION_LOG_WARNING, "Unknown consumer event, " "disconnecting"); return ENGINE_DISCONNECT; } delete resp; return ENGINE_SUCCESS; } ENGINE_ERROR_CODE UprConsumer::handleResponse( protocol_binary_response_header *resp) { uint8_t opcode = resp->response.opcode; if (opcode == PROTOCOL_BINARY_CMD_UPR_STREAM_REQ) { protocol_binary_response_upr_stream_req* pkt = reinterpret_cast<protocol_binary_response_upr_stream_req*>(resp); uint16_t status = ntohs(pkt->message.header.response.status); uint32_t opaque = pkt->message.header.response.opaque; uint64_t bodylen = ntohl(pkt->message.header.response.bodylen); uint8_t* body = pkt->bytes + sizeof(protocol_binary_response_header); if (status == ENGINE_ROLLBACK) { assert(bodylen == sizeof(uint64_t)); uint64_t rollbackSeqno = 0; memcpy(&rollbackSeqno, body, sizeof(uint64_t)); rollbackSeqno = ntohll(rollbackSeqno); return ENGINE_ENOTSUP; } streamAccepted(opaque, status, body, bodylen); return ENGINE_SUCCESS; } LOG(EXTENSION_LOG_WARNING, "%s Trying to handle an unknown response %d, " "disconnecting", logHeader(), opcode); return ENGINE_DISCONNECT; } void UprConsumer::addStats(ADD_STAT add_stat, const void *c) { ConnHandler::addStats(add_stat, c); LockHolder lh(streamMutex); std::map<uint16_t, PassiveStream*>::iterator itr; for (itr = streams_.begin(); itr != streams_.end(); ++itr) { itr->second->addStats(add_stat, c); } } UprResponse* UprConsumer::getNextItem() { LockHolder lh(streamMutex); std::map<uint16_t, PassiveStream*>::iterator itr = streams_.begin(); for (; itr != streams_.end(); ++itr) { UprResponse* op = itr->second->next(); if (!op) { continue; } switch (op->getEvent()) { case UPR_STREAM_REQ: case UPR_ADD_STREAM: break; default: LOG(EXTENSION_LOG_WARNING, "%s Consumer is attempting to write" " an unexpected event %d", logHeader(), op->getEvent()); abort(); } return op; } return NULL; } void UprConsumer::streamAccepted(uint32_t opaque, uint16_t status, uint8_t* body, uint32_t bodylen) { LockHolder lh(streamMutex); opaque_map::iterator oitr = opaqueMap_.find(opaque); if (oitr != opaqueMap_.end()) { uint32_t add_opaque = oitr->second.first; uint16_t vbucket = oitr->second.second; std::map<uint16_t, PassiveStream*>::iterator sitr = streams_.find(vbucket); if (sitr != streams_.end() && sitr->second->getOpaque() == opaque && sitr->second->getState() == STREAM_PENDING) { if (status == ENGINE_SUCCESS) { RCPtr<VBucket> vb = engine_.getVBucket(vbucket); vb->failovers->replaceFailoverLog(body, bodylen); EventuallyPersistentStore* st = engine_.getEpStore(); st->scheduleVBSnapshot(Priority::VBucketPersistHighPriority, st->getVBuckets().getShard(vbucket)->getId()); } sitr->second->acceptStream(status, add_opaque); } else { LOG(EXTENSION_LOG_WARNING, "%s Trying to add stream, but none " "exists (opaque: %d, add_opaque: %d)", logHeader(), opaque, add_opaque); } opaqueMap_.erase(opaque); } else { LOG(EXTENSION_LOG_WARNING, "%s No opaque for add stream response", logHeader()); } } bool UprConsumer::isValidOpaque(uint32_t opaque, uint16_t vbucket) { LockHolder lh(streamMutex); std::map<uint16_t, PassiveStream*>::iterator itr = streams_.find(vbucket); return itr != streams_.end() && itr->second->getOpaque() == opaque; } <commit_msg>MB-9892: Add correct vb uuid and high seqno to consumer stream req<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2013 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "ep_engine.h" #include "upr-stream.h" UprConsumer::UprConsumer(EventuallyPersistentEngine &e, const void *cookie, const std::string &n) : Consumer(e), opaqueCounter(0) { conn_ = new Connection(this, cookie, n); conn_->setSupportAck(true); conn_->setLogHeader("UPR (Consumer) " + conn_->getName() + " -"); setReserved(false); } ENGINE_ERROR_CODE UprConsumer::addStream(uint32_t opaque, uint16_t vbucket, uint32_t flags) { LockHolder lh(streamMutex); RCPtr<VBucket> vb = engine_.getVBucket(vbucket); if (!vb) { return ENGINE_NOT_MY_VBUCKET; } failover_entry_t entry = vb->failovers->getLatestEntry(); uint64_t start_seqno = vb->getHighSeqno(); uint64_t end_seqno = std::numeric_limits<uint64_t>::max(); uint64_t vbucket_uuid = entry.vb_uuid; uint64_t high_seqno = entry.by_seqno; uint32_t new_opaque = ++opaqueCounter; std::map<uint16_t, PassiveStream*>::iterator itr = streams_.find(vbucket); if (itr != streams_.end() && itr->second->isActive()) { return ENGINE_KEY_EEXISTS; } else if (itr != streams_.end()) { delete itr->second; streams_.erase(itr); } streams_[vbucket] = new PassiveStream(conn_->name, flags, new_opaque, vbucket, start_seqno, end_seqno, vbucket_uuid, high_seqno); opaqueMap_[new_opaque] = std::make_pair(opaque, vbucket); return ENGINE_SUCCESS; } ENGINE_ERROR_CODE UprConsumer::closeStream(uint32_t opaque, uint16_t vbucket) { LockHolder lh(streamMutex); opaque_map::iterator oitr = opaqueMap_.find(opaque); if (oitr != opaqueMap_.end()) { opaqueMap_.erase(oitr); } std::map<uint16_t, PassiveStream*>::iterator itr; if ((itr = streams_.find(vbucket)) == streams_.end()) { return ENGINE_KEY_ENOENT; } if (itr->second->getOpaque() != opaque) { return ENGINE_KEY_EEXISTS; } itr->second->setDead(); return ENGINE_SUCCESS; } ENGINE_ERROR_CODE UprConsumer::streamEnd(uint32_t opaque, uint16_t vbucket, uint32_t flags) { if (closeStream(opaque, vbucket) == ENGINE_SUCCESS) { LOG(EXTENSION_LOG_WARNING, "%s end stream received with reason %d", logHeader(), flags); } else { LOG(EXTENSION_LOG_WARNING, "%s end stream received but vbucket %d with" " opaque %d does not exist", logHeader(), vbucket, opaque); } return ENGINE_SUCCESS; } ENGINE_ERROR_CODE UprConsumer::mutation(uint32_t opaque, const void* key, uint16_t nkey, const void* value, uint32_t nvalue, uint64_t cas, uint16_t vbucket, uint32_t flags, uint8_t datatype, uint32_t locktime, uint64_t bySeqno, uint64_t revSeqno, uint32_t exptime, uint8_t nru, const void* meta, uint16_t nmeta) { ENGINE_ERROR_CODE ret = ENGINE_SUCCESS; if (!isValidOpaque(opaque, vbucket)) { return ENGINE_FAILED; } std::string key_str(static_cast<const char*>(key), nkey); value_t vblob(Blob::New(static_cast<const char*>(value), nvalue, NULL, 0)); Item *item = new Item(key_str, flags, exptime, vblob, cas, bySeqno, vbucket, revSeqno); if (isBackfillPhase(vbucket)) { ret = engine_.getEpStore()->addTAPBackfillItem(*item, meta, nru); } else { ret = engine_.getEpStore()->setWithMeta(*item, 0, conn_->cookie, true, true, nru); } return ret; } ENGINE_ERROR_CODE UprConsumer::deletion(uint32_t opaque, const void* key, uint16_t nkey, uint64_t cas, uint16_t vbucket, uint64_t bySeqno, uint64_t revSeqno, const void* meta, uint16_t nmeta) { ENGINE_ERROR_CODE ret; if (!isValidOpaque(opaque, vbucket)) { return ENGINE_FAILED; } uint64_t delCas = 0; ItemMetaData itemMeta(cas, revSeqno, 0, 0); std::string key_str((const char*)key, nkey); ret = engine_.getEpStore()->deleteWithMeta(key_str, &delCas, vbucket, conn_->cookie, true, &itemMeta, isBackfillPhase(vbucket)); if (ret == ENGINE_KEY_ENOENT) { ret = ENGINE_SUCCESS; } return ENGINE_SUCCESS; } ENGINE_ERROR_CODE UprConsumer::expiration(uint32_t opaque, const void* key, uint16_t nkey, uint64_t cas, uint16_t vbucket, uint64_t bySeqno, uint64_t revSeqno, const void* meta, uint16_t nmeta) { return ENGINE_ENOTSUP; } ENGINE_ERROR_CODE UprConsumer::snapshotMarker(uint32_t opaque, uint16_t vbucket) { (void) opaque; (void) vbucket; return ENGINE_SUCCESS; } ENGINE_ERROR_CODE UprConsumer::flush(uint32_t opaque, uint16_t vbucket) { (void) opaque; (void) vbucket; return ENGINE_ENOTSUP; } ENGINE_ERROR_CODE UprConsumer::setVBucketState(uint32_t opaque, uint16_t vbucket, vbucket_state_t state) { if (isValidOpaque(opaque, vbucket)) { return Consumer::setVBucketState(opaque, vbucket, state); } else { LOG(EXTENSION_LOG_WARNING, "Invalid opaque value for UPR-CONSUMER"); return ENGINE_FAILED; } } ENGINE_ERROR_CODE UprConsumer::step(struct upr_message_producers* producers) { UprResponse *resp = getNextItem(); if (resp == NULL) { return ENGINE_SUCCESS; // Change to tmpfail once mcd layer is fixed } switch (resp->getEvent()) { case UPR_ADD_STREAM: { AddStreamResponse *as = static_cast<AddStreamResponse*>(resp); producers->add_stream_rsp(conn_->cookie, as->getOpaque(), as->getStreamOpaque(), as->getStatus()); break; } case UPR_STREAM_REQ: { StreamRequest *sr = static_cast<StreamRequest*> (resp); producers->stream_req(conn_->cookie, sr->getOpaque(), sr->getVBucket(), sr->getFlags(), sr->getStartSeqno(), sr->getEndSeqno(), sr->getVBucketUUID(), sr->getHighSeqno()); break; } default: LOG(EXTENSION_LOG_WARNING, "Unknown consumer event, " "disconnecting"); return ENGINE_DISCONNECT; } delete resp; return ENGINE_SUCCESS; } ENGINE_ERROR_CODE UprConsumer::handleResponse( protocol_binary_response_header *resp) { uint8_t opcode = resp->response.opcode; if (opcode == PROTOCOL_BINARY_CMD_UPR_STREAM_REQ) { protocol_binary_response_upr_stream_req* pkt = reinterpret_cast<protocol_binary_response_upr_stream_req*>(resp); uint16_t status = ntohs(pkt->message.header.response.status); uint32_t opaque = pkt->message.header.response.opaque; uint64_t bodylen = ntohl(pkt->message.header.response.bodylen); uint8_t* body = pkt->bytes + sizeof(protocol_binary_response_header); if (status == ENGINE_ROLLBACK) { assert(bodylen == sizeof(uint64_t)); uint64_t rollbackSeqno = 0; memcpy(&rollbackSeqno, body, sizeof(uint64_t)); rollbackSeqno = ntohll(rollbackSeqno); return ENGINE_ENOTSUP; } streamAccepted(opaque, status, body, bodylen); return ENGINE_SUCCESS; } LOG(EXTENSION_LOG_WARNING, "%s Trying to handle an unknown response %d, " "disconnecting", logHeader(), opcode); return ENGINE_DISCONNECT; } void UprConsumer::addStats(ADD_STAT add_stat, const void *c) { ConnHandler::addStats(add_stat, c); LockHolder lh(streamMutex); std::map<uint16_t, PassiveStream*>::iterator itr; for (itr = streams_.begin(); itr != streams_.end(); ++itr) { itr->second->addStats(add_stat, c); } } UprResponse* UprConsumer::getNextItem() { LockHolder lh(streamMutex); std::map<uint16_t, PassiveStream*>::iterator itr = streams_.begin(); for (; itr != streams_.end(); ++itr) { UprResponse* op = itr->second->next(); if (!op) { continue; } switch (op->getEvent()) { case UPR_STREAM_REQ: case UPR_ADD_STREAM: break; default: LOG(EXTENSION_LOG_WARNING, "%s Consumer is attempting to write" " an unexpected event %d", logHeader(), op->getEvent()); abort(); } return op; } return NULL; } void UprConsumer::streamAccepted(uint32_t opaque, uint16_t status, uint8_t* body, uint32_t bodylen) { LockHolder lh(streamMutex); opaque_map::iterator oitr = opaqueMap_.find(opaque); if (oitr != opaqueMap_.end()) { uint32_t add_opaque = oitr->second.first; uint16_t vbucket = oitr->second.second; std::map<uint16_t, PassiveStream*>::iterator sitr = streams_.find(vbucket); if (sitr != streams_.end() && sitr->second->getOpaque() == opaque && sitr->second->getState() == STREAM_PENDING) { if (status == ENGINE_SUCCESS) { RCPtr<VBucket> vb = engine_.getVBucket(vbucket); vb->failovers->replaceFailoverLog(body, bodylen); EventuallyPersistentStore* st = engine_.getEpStore(); st->scheduleVBSnapshot(Priority::VBucketPersistHighPriority, st->getVBuckets().getShard(vbucket)->getId()); } sitr->second->acceptStream(status, add_opaque); } else { LOG(EXTENSION_LOG_WARNING, "%s Trying to add stream, but none " "exists (opaque: %d, add_opaque: %d)", logHeader(), opaque, add_opaque); } opaqueMap_.erase(opaque); } else { LOG(EXTENSION_LOG_WARNING, "%s No opaque for add stream response", logHeader()); } } bool UprConsumer::isValidOpaque(uint32_t opaque, uint16_t vbucket) { LockHolder lh(streamMutex); std::map<uint16_t, PassiveStream*>::iterator itr = streams_.find(vbucket); return itr != streams_.end() && itr->second->getOpaque() == opaque; } <|endoftext|>
<commit_before>#include "qtfirebaseremoteconfig.h" namespace remote_config = ::firebase::remote_config; QtFirebaseRemoteConfig *QtFirebaseRemoteConfig::self = 0; QtFirebaseRemoteConfig::QtFirebaseRemoteConfig(QObject *parent) : QObject(parent), _ready(false), _initializing(false), _cacheExpirationTime(firebase::remote_config::kDefaultCacheExpiration*1000), // milliseconds __appId(nullptr) { __QTFIREBASE_ID = QString().sprintf("%8p", this); if(self == 0) { self = this; qDebug() << self << "::QtFirebaseRemoteConfig" << "singleton"; } #if defined(Q_OS_ANDROID) if (GooglePlayServices::available()) { qDebug() << this << " Google Play Services is available, now init remote_config" ; //Call init outside of constructor, otherwise signal readyChanged not emited QTimer::singleShot(500, this, SLOT(delayedInit())); connect(qFirebase,&QtFirebase::futureEvent, this, &QtFirebaseRemoteConfig::onFutureEvent); } else { qDebug() << this << " Google Play Services is NOT available, CANNOT use remote_config" ; } #else //Call init outside of constructor, otherwise signal readyChanged not emited QTimer::singleShot(500, this, SLOT(delayedInit())); connect(qFirebase,&QtFirebase::futureEvent, this, &QtFirebaseRemoteConfig::onFutureEvent); #endif } QtFirebaseRemoteConfig::~QtFirebaseRemoteConfig() { if(_ready) remote_config::Terminate(); } bool QtFirebaseRemoteConfig::checkInstance(const char *function) { bool b = (QtFirebaseRemoteConfig::self != 0); if(!b) qWarning("QtFirebaseRemoteConfig::%s:", function); return b; } void QtFirebaseRemoteConfig::addParameterInternal(const QString &name, const QVariant &defaultValue) { _parameters[name] = defaultValue; } void QtFirebaseRemoteConfig::delayedInit() { if(qFirebase->ready()) { qDebug() << this << "::delayedInit : QtFirebase is ready, calling init" ; init(); } else { qDebug() << this << "::delayedInit : QtFirebase not ready, connecting to its readyChanged signal" ; connect(qFirebase,&QtFirebase::readyChanged, this, &QtFirebaseRemoteConfig::init); qFirebase->requestInit(); } } QVariant QtFirebaseRemoteConfig::getParameterValue(const QString &name) const { if(_parameters.contains(name)) { return _parameters[name]; } return _parameters[name]; } bool QtFirebaseRemoteConfig::ready() { return _ready; } void QtFirebaseRemoteConfig::setReady(bool ready) { qDebug() << this << "::setReady before:" << _ready << "now:" << ready; if (_ready != ready) { _ready = ready; emit readyChanged(); } } QVariantMap QtFirebaseRemoteConfig::parameters() const { return _parameters; } void QtFirebaseRemoteConfig::setParameters(const QVariantMap &map) { _parameters = map; emit parametersChanged(); } long long QtFirebaseRemoteConfig::cacheExpirationTime() const { return _cacheExpirationTime; } void QtFirebaseRemoteConfig::setCacheExpirationTime(long long timeMs) { _cacheExpirationTime = timeMs; emit cacheExpirationTimeChanged(); } void QtFirebaseRemoteConfig::addParameter(const QString &name, long long defaultValue) { addParameterInternal(name, defaultValue); } void QtFirebaseRemoteConfig::addParameter(const QString &name, double defaultValue) { addParameterInternal(name, defaultValue); } void QtFirebaseRemoteConfig::addParameter(const QString &name, const QString &defaultValue) { addParameterInternal(name, defaultValue); } void QtFirebaseRemoteConfig::addParameter(const QString &name, bool defaultValue) { addParameterInternal(name, defaultValue); } void QtFirebaseRemoteConfig::init() { qDebug() << self << "::init" << "called"; if(!qFirebase->ready()) { qDebug() << self << "::init" << "base not ready"; return; } if(!_ready && !_initializing) { _initializing = true; ::firebase::ModuleInitializer initializer; auto future = initializer.Initialize(qFirebase->firebaseApp(), nullptr, [](::firebase::App* app, void*) { qDebug() << self << "::init" << "try to initialize Remote Config"; return ::firebase::remote_config::Initialize(*app); }); qFirebase->addFuture(__QTFIREBASE_ID + QStringLiteral(".config.init"), future); } } void QtFirebaseRemoteConfig::onFutureEvent(QString eventId, firebase::FutureBase future) { if(!eventId.startsWith(__QTFIREBASE_ID)) return; qDebug() << self << "::onFutureEvent" << eventId; if(eventId == __QTFIREBASE_ID + QStringLiteral(".config.fetch")) onFutureEventFetch(future); else if( eventId == __QTFIREBASE_ID + QStringLiteral(".config.init") ) onFutureEventInit(future); } void QtFirebaseRemoteConfig::onFutureEventInit(firebase::FutureBase &future) { if (future.error() != firebase::kFutureStatusComplete) { qDebug() << this << "::onFutureEvent" << "initializing failed." << "ERROR: Action failed with error code and message: " << future.error() << future.error_message(); _initializing = false; return; } qDebug() << this << "::onFutureEvent initialized ok"; _initializing = false; setReady(true); } void QtFirebaseRemoteConfig::onFutureEventFetch(firebase::FutureBase &future) { if(future.status() != firebase::kFutureStatusComplete) { qDebug() << this << "::onFutureEvent initializing failed." << "ERROR: Action failed with error code and message: " << future.error() << future.error_message(); _initializing = false; return; } qDebug() << this << "::onFutureEvent initialized ok"; _initializing = false; bool fetchActivated = remote_config::ActivateFetched(); //On first run even if we have activateResult failed we still can get cached values qDebug() << self << QString(QStringLiteral("ActivateFetched %1")).arg(fetchActivated ? QStringLiteral("succeeded") : QStringLiteral("failed")); const remote_config::ConfigInfo& info = remote_config::GetInfo(); qDebug() << self << QString(QStringLiteral("Info last_fetch_time_ms=%1 fetch_status=%2 failure_reason=%3")) .arg(QString::number(info.fetch_time)) .arg(info.last_fetch_status) .arg(info.last_fetch_failure_reason); if(info.last_fetch_status == remote_config::kLastFetchStatusSuccess) { QVariantMap updatedParameters; for(QVariantMap::const_iterator it = _parameters.begin(); it!=_parameters.end();++it) { const QVariant& value = it.value(); Q_ASSERT(value.type() == QVariant::Bool || value.type() == QVariant::LongLong || value.type() == QVariant::Int || value.type() == QVariant::Double || value.type() == QVariant::String); if(value.type() == QVariant::Bool) { updatedParameters[it.key()] = remote_config::GetBoolean(it.key().toUtf8().constData()); } else if(value.type() == QVariant::LongLong) { updatedParameters[it.key()] = remote_config::GetLong(it.key().toUtf8().constData()); } else if(value.type() == QVariant::Int) { updatedParameters[it.key()] = remote_config::GetLong(it.key().toUtf8().constData()); } else if(value.type() == QVariant::Double) { updatedParameters[it.key()] = remote_config::GetDouble(it.key().toUtf8().constData()); } else if(value.type() == QVariant::String) { std::string result = remote_config::GetString(it.key().toUtf8().constData()); updatedParameters[it.key()] = QString(QString::fromUtf8(result.c_str())); //Code for data type /*std::vector<unsigned char> out = remote_config::GetData(it.key().toUtf8().constData()); QByteArray data; for (size_t i = 0; i < out.size(); ++i) { data.append(out[i]); } updatedParameters[it.key()] = QString(data);*/ } } //SDK code to print out the keys /*std::vector<std::string> keys = remote_config::GetKeys(); qDebug() << "QtFirebaseRemoteConfig GetKeys:"; for (auto s = keys.begin(); s != keys.end(); ++s) { qDebug() << s->c_str(); } keys = remote_config::GetKeysByPrefix("TestD"); printf("GetKeysByPrefix(\"TestD\"):"); for (auto s = keys.begin(); s != keys.end(); ++s) { printf(" %s", s->c_str()); }*/ setParameters(updatedParameters); } else { if(info.last_fetch_failure_reason == remote_config::kFetchFailureReasonInvalid) { emit error(FetchFailureReasonInvalid, QStringLiteral("The fetch has not yet failed.")); } else if(info.last_fetch_failure_reason == remote_config::kFetchFailureReasonThrottled) { emit error(FetchFailureReasonThrottled, QStringLiteral("Throttled by the server. You are sending too many fetch requests in too short a time.")); } else { emit error(FetchFailureReasonError, QStringLiteral("Failure reason is unknown")); } } future.Release(); } void QtFirebaseRemoteConfig::fetch() { fetch(_cacheExpirationTime<1000 ? 0 : _cacheExpirationTime/1000); } void QtFirebaseRemoteConfig::fetch(long long cacheExpirationInSeconds) { if(_parameters.size() == 0) { qDebug() << self << "::fetch not started, parameters were not initialized"; return; } qDebug() << self <<"::fetch with expirationtime" << cacheExpirationInSeconds << "seconds"; QVariantMap filteredMap; for(QVariantMap::const_iterator it = _parameters.begin(); it!=_parameters.end();++it) { const QVariant& value = it.value(); if(value.type() == QVariant::Bool || value.type() == QVariant::LongLong || value.type() == QVariant::Int || value.type() == QVariant::Double || value.type() == QVariant::String) { filteredMap[it.key()] = value; } else { qWarning() << self << "Data type:" << value.typeName() << " not supported"; } } // From <memory> include std::unique_ptr<remote_config::ConfigKeyValueVariant[]> defaults( new remote_config::ConfigKeyValueVariant[filteredMap.size()]); __defaultsByteArrayList.clear(); uint index = 0; for(QVariantMap::const_iterator it = filteredMap.begin(); it!=filteredMap.end();++it) { const QVariant& value = it.value(); __defaultsByteArrayList.insert(index,QByteArray(it.key().toUtf8().data())); if(value.type() == QVariant::Bool) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toBool()}; } else if(value.type() == QVariant::LongLong) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toLongLong()}; } else if(value.type() == QVariant::Int) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toInt()}; } else if(value.type() == QVariant::Double) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toDouble()}; } else if(value.type() == QVariant::String) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toString().toUtf8().constData()}; //Code for data type /*QByteArray data = value.toString().toUtf8(); defaults[cnt] = remote_config::ConfigKeyValueVariant{ it.key().toUtf8().constData(), firebase::Variant::FromMutableBlob(data.constData(), data.size())};*/ } index++; } remote_config::SetDefaults(defaults.get(), filteredMap.size()); /*remote_config::SetConfigSetting(remote_config::kConfigSettingDeveloperMode, "1"); if ((*remote_config::GetConfigSetting(remote_config::kConfigSettingDeveloperMode) .c_str()) != '1') { qDebug()<<"Failed to enable developer mode"; }*/ qDebug() << self << "::fetch" << "run fetching..."; auto future = remote_config::Fetch(cacheExpirationInSeconds); qFirebase->addFuture(__QTFIREBASE_ID + QStringLiteral(".config.fetch"), future); } void QtFirebaseRemoteConfig::fetchNow() { fetch(0); } <commit_msg>Fix RemoteConfig life-cycle re-initialization bug. This should close #42<commit_after>#include "qtfirebaseremoteconfig.h" namespace remote_config = ::firebase::remote_config; QtFirebaseRemoteConfig *QtFirebaseRemoteConfig::self = 0; QtFirebaseRemoteConfig::QtFirebaseRemoteConfig(QObject *parent) : QObject(parent), _ready(false), _initializing(false), _cacheExpirationTime(firebase::remote_config::kDefaultCacheExpiration*1000), // milliseconds __appId(nullptr) { __QTFIREBASE_ID = QString().sprintf("%8p", this); if(self == 0) { self = this; qDebug() << self << "::QtFirebaseRemoteConfig" << "singleton"; } #if defined(Q_OS_ANDROID) if (GooglePlayServices::available()) { qDebug() << this << " Google Play Services is available, now init remote_config" ; //Call init outside of constructor, otherwise signal readyChanged not emited QTimer::singleShot(500, this, SLOT(delayedInit())); connect(qFirebase,&QtFirebase::futureEvent, this, &QtFirebaseRemoteConfig::onFutureEvent); } else { qDebug() << this << " Google Play Services is NOT available, CANNOT use remote_config" ; } #else //Call init outside of constructor, otherwise signal readyChanged not emited QTimer::singleShot(500, this, SLOT(delayedInit())); connect(qFirebase,&QtFirebase::futureEvent, this, &QtFirebaseRemoteConfig::onFutureEvent); #endif } QtFirebaseRemoteConfig::~QtFirebaseRemoteConfig() { if(_ready) remote_config::Terminate(); } bool QtFirebaseRemoteConfig::checkInstance(const char *function) { bool b = (QtFirebaseRemoteConfig::self != 0); if(!b) qWarning("QtFirebaseRemoteConfig::%s:", function); return b; } void QtFirebaseRemoteConfig::addParameterInternal(const QString &name, const QVariant &defaultValue) { _parameters[name] = defaultValue; } void QtFirebaseRemoteConfig::delayedInit() { if(qFirebase->ready()) { qDebug() << this << "::delayedInit : QtFirebase is ready, calling init" ; init(); } else { qDebug() << this << "::delayedInit : QtFirebase not ready, connecting to its readyChanged signal" ; connect(qFirebase,&QtFirebase::readyChanged, this, &QtFirebaseRemoteConfig::init); qFirebase->requestInit(); } } QVariant QtFirebaseRemoteConfig::getParameterValue(const QString &name) const { if(_parameters.contains(name)) { return _parameters[name]; } return _parameters[name]; } bool QtFirebaseRemoteConfig::ready() { return _ready; } void QtFirebaseRemoteConfig::setReady(bool ready) { qDebug() << this << "::setReady before:" << _ready << "now:" << ready; if (_ready != ready) { _ready = ready; emit readyChanged(); } } QVariantMap QtFirebaseRemoteConfig::parameters() const { return _parameters; } void QtFirebaseRemoteConfig::setParameters(const QVariantMap &map) { _parameters = map; emit parametersChanged(); } long long QtFirebaseRemoteConfig::cacheExpirationTime() const { return _cacheExpirationTime; } void QtFirebaseRemoteConfig::setCacheExpirationTime(long long timeMs) { _cacheExpirationTime = timeMs; emit cacheExpirationTimeChanged(); } void QtFirebaseRemoteConfig::addParameter(const QString &name, long long defaultValue) { addParameterInternal(name, defaultValue); } void QtFirebaseRemoteConfig::addParameter(const QString &name, double defaultValue) { addParameterInternal(name, defaultValue); } void QtFirebaseRemoteConfig::addParameter(const QString &name, const QString &defaultValue) { addParameterInternal(name, defaultValue); } void QtFirebaseRemoteConfig::addParameter(const QString &name, bool defaultValue) { addParameterInternal(name, defaultValue); } void QtFirebaseRemoteConfig::init() { qDebug() << this << "::init" << "called"; if(!qFirebase->ready()) { qDebug() << this << "::init" << "base not ready"; return; } if(!_ready && !_initializing) { _initializing = true; ::firebase::ModuleInitializer initializer; auto future = initializer.Initialize(qFirebase->firebaseApp(), nullptr, [](::firebase::App* app, void*) { // NOTE only write debug output here when developing // Causes crash on re-initialization (probably the "self" reference. And "this" can't be used in a lambda) //qDebug() << self << "::init" << "try to initialize Remote Config"; return ::firebase::remote_config::Initialize(*app); }); qFirebase->addFuture(__QTFIREBASE_ID + QStringLiteral(".config.init"), future); } } void QtFirebaseRemoteConfig::onFutureEvent(QString eventId, firebase::FutureBase future) { if(!eventId.startsWith(__QTFIREBASE_ID)) return; qDebug() << this << "::onFutureEvent" << eventId; if(eventId == __QTFIREBASE_ID + QStringLiteral(".config.fetch")) onFutureEventFetch(future); else if( eventId == __QTFIREBASE_ID + QStringLiteral(".config.init") ) onFutureEventInit(future); } void QtFirebaseRemoteConfig::onFutureEventInit(firebase::FutureBase &future) { if (future.error() != firebase::kFutureStatusComplete) { qDebug() << this << "::onFutureEvent" << "initializing failed." << "ERROR: Action failed with error code and message: " << future.error() << future.error_message(); _initializing = false; return; } qDebug() << this << "::onFutureEvent initialized ok"; _initializing = false; setReady(true); } void QtFirebaseRemoteConfig::onFutureEventFetch(firebase::FutureBase &future) { if(future.status() != firebase::kFutureStatusComplete) { qDebug() << this << "::onFutureEvent initializing failed." << "ERROR: Action failed with error code and message: " << future.error() << future.error_message(); _initializing = false; return; } qDebug() << this << "::onFutureEvent initialized ok"; _initializing = false; bool fetchActivated = remote_config::ActivateFetched(); //On first run even if we have activateResult failed we still can get cached values qDebug() << this << QString(QStringLiteral("ActivateFetched %1")).arg(fetchActivated ? QStringLiteral("succeeded") : QStringLiteral("failed")); const remote_config::ConfigInfo& info = remote_config::GetInfo(); qDebug() << this << QString(QStringLiteral("Info last_fetch_time_ms=%1 fetch_status=%2 failure_reason=%3")) .arg(QString::number(info.fetch_time)) .arg(info.last_fetch_status) .arg(info.last_fetch_failure_reason); if(info.last_fetch_status == remote_config::kLastFetchStatusSuccess) { QVariantMap updatedParameters; for(QVariantMap::const_iterator it = _parameters.begin(); it!=_parameters.end();++it) { const QVariant& value = it.value(); Q_ASSERT(value.type() == QVariant::Bool || value.type() == QVariant::LongLong || value.type() == QVariant::Int || value.type() == QVariant::Double || value.type() == QVariant::String); if(value.type() == QVariant::Bool) { updatedParameters[it.key()] = remote_config::GetBoolean(it.key().toUtf8().constData()); } else if(value.type() == QVariant::LongLong) { updatedParameters[it.key()] = remote_config::GetLong(it.key().toUtf8().constData()); } else if(value.type() == QVariant::Int) { updatedParameters[it.key()] = remote_config::GetLong(it.key().toUtf8().constData()); } else if(value.type() == QVariant::Double) { updatedParameters[it.key()] = remote_config::GetDouble(it.key().toUtf8().constData()); } else if(value.type() == QVariant::String) { std::string result = remote_config::GetString(it.key().toUtf8().constData()); updatedParameters[it.key()] = QString(QString::fromUtf8(result.c_str())); //Code for data type /*std::vector<unsigned char> out = remote_config::GetData(it.key().toUtf8().constData()); QByteArray data; for (size_t i = 0; i < out.size(); ++i) { data.append(out[i]); } updatedParameters[it.key()] = QString(data);*/ } } //SDK code to print out the keys /*std::vector<std::string> keys = remote_config::GetKeys(); qDebug() << "QtFirebaseRemoteConfig GetKeys:"; for (auto s = keys.begin(); s != keys.end(); ++s) { qDebug() << s->c_str(); } keys = remote_config::GetKeysByPrefix("TestD"); printf("GetKeysByPrefix(\"TestD\"):"); for (auto s = keys.begin(); s != keys.end(); ++s) { printf(" %s", s->c_str()); }*/ setParameters(updatedParameters); } else { if(info.last_fetch_failure_reason == remote_config::kFetchFailureReasonInvalid) { emit error(FetchFailureReasonInvalid, QStringLiteral("The fetch has not yet failed.")); } else if(info.last_fetch_failure_reason == remote_config::kFetchFailureReasonThrottled) { emit error(FetchFailureReasonThrottled, QStringLiteral("Throttled by the server. You are sending too many fetch requests in too short a time.")); } else { emit error(FetchFailureReasonError, QStringLiteral("Failure reason is unknown")); } } future.Release(); } void QtFirebaseRemoteConfig::fetch() { fetch(_cacheExpirationTime<1000 ? 0 : _cacheExpirationTime/1000); } void QtFirebaseRemoteConfig::fetch(long long cacheExpirationInSeconds) { if(_parameters.size() == 0) { qDebug() << this << "::fetch not started, parameters were not initialized"; return; } qDebug() << this <<"::fetch with expirationtime" << cacheExpirationInSeconds << "seconds"; QVariantMap filteredMap; for(QVariantMap::const_iterator it = _parameters.begin(); it!=_parameters.end();++it) { const QVariant& value = it.value(); if(value.type() == QVariant::Bool || value.type() == QVariant::LongLong || value.type() == QVariant::Int || value.type() == QVariant::Double || value.type() == QVariant::String) { filteredMap[it.key()] = value; } else { qWarning() << this << "Data type:" << value.typeName() << " not supported"; } } // From <memory> include std::unique_ptr<remote_config::ConfigKeyValueVariant[]> defaults( new remote_config::ConfigKeyValueVariant[filteredMap.size()]); __defaultsByteArrayList.clear(); uint index = 0; for(QVariantMap::const_iterator it = filteredMap.begin(); it!=filteredMap.end();++it) { const QVariant& value = it.value(); __defaultsByteArrayList.insert(index,QByteArray(it.key().toUtf8().data())); if(value.type() == QVariant::Bool) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toBool()}; } else if(value.type() == QVariant::LongLong) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toLongLong()}; } else if(value.type() == QVariant::Int) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toInt()}; } else if(value.type() == QVariant::Double) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toDouble()}; } else if(value.type() == QVariant::String) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toString().toUtf8().constData()}; //Code for data type /*QByteArray data = value.toString().toUtf8(); defaults[cnt] = remote_config::ConfigKeyValueVariant{ it.key().toUtf8().constData(), firebase::Variant::FromMutableBlob(data.constData(), data.size())};*/ } index++; } remote_config::SetDefaults(defaults.get(), filteredMap.size()); /*remote_config::SetConfigSetting(remote_config::kConfigSettingDeveloperMode, "1"); if ((*remote_config::GetConfigSetting(remote_config::kConfigSettingDeveloperMode) .c_str()) != '1') { qDebug()<<"Failed to enable developer mode"; }*/ qDebug() << this << "::fetch" << "run fetching..."; auto future = remote_config::Fetch(cacheExpirationInSeconds); qFirebase->addFuture(__QTFIREBASE_ID + QStringLiteral(".config.fetch"), future); } void QtFirebaseRemoteConfig::fetchNow() { fetch(0); } <|endoftext|>
<commit_before>#include "qtfirebaseremoteconfig.h" namespace remote_config = ::firebase::remote_config; QtFirebaseRemoteConfig *QtFirebaseRemoteConfig::self = 0; QtFirebaseRemoteConfig::QtFirebaseRemoteConfig(QObject *parent) : QObject(parent), _ready(false), _initializing(false), _cacheExpirationTime(firebase::remote_config::kDefaultCacheExpiration*1000),//milliseconds __appId(nullptr) { __QTFIREBASE_ID = QString().sprintf("%8p", this); if(self == 0) { self = this; qDebug() << self << "::QtFirebaseRemoteConfig" << "singleton"; } #if defined(Q_OS_ANDROID) if (PlatformUtils::googleServicesAvailable()) { qDebug() << this << " Google Services is available, now init remote_config" ; //Call init outside of constructor, otherwise signal readyChanged not emited QTimer::singleShot(500, this, SLOT(delayedInit())); connect(qFirebase,&QtFirebase::futureEvent, this, &QtFirebaseRemoteConfig::onFutureEvent); } else { qDebug() << this << " Google Services is NOT available, CANNOT use remote_config" ; } #else //Call init outside of constructor, otherwise signal readyChanged not emited QTimer::singleShot(500, this, SLOT(delayedInit())); connect(qFirebase,&QtFirebase::futureEvent, this, &QtFirebaseRemoteConfig::onFutureEvent); #endif } bool QtFirebaseRemoteConfig::checkInstance(const char *function) { bool b = (QtFirebaseRemoteConfig::self != 0); if(!b) qWarning("QtFirebaseRemoteConfig::%s:", function); return b; } void QtFirebaseRemoteConfig::addParameterInternal(const QString &name, const QVariant &defaultValue) { _parameters[name] = defaultValue; } void QtFirebaseRemoteConfig::delayedInit() { if(qFirebase->ready()) { qDebug() << this << "::delayedInit : QtFirebase is ready, calling init" ; init(); } else { qDebug() << this << "::delayedInit : QtFirebase not ready, connecting to its readyChanged signal" ; connect(qFirebase,&QtFirebase::readyChanged, this, &QtFirebaseRemoteConfig::init); qFirebase->requestInit(); } } QVariant QtFirebaseRemoteConfig::getParameterValue(const QString &name) const { if(_parameters.contains(name)) { return _parameters[name]; } return _parameters[name]; } bool QtFirebaseRemoteConfig::ready() { return _ready; } void QtFirebaseRemoteConfig::setReady(bool ready) { qDebug() << this << "::setReady before:" << _ready << "now:" << ready; if (_ready != ready) { _ready = ready; emit readyChanged(); } } QVariantMap QtFirebaseRemoteConfig::parameters() const { return _parameters; } void QtFirebaseRemoteConfig::setParameters(const QVariantMap &map) { _parameters = map; emit parametersChanged(); } long long QtFirebaseRemoteConfig::cacheExpirationTime() const { return _cacheExpirationTime; } void QtFirebaseRemoteConfig::setCacheExpirationTime(long long timeMs) { _cacheExpirationTime = timeMs; emit cacheExpirationTimeChanged(); } void QtFirebaseRemoteConfig::addParameter(const QString &name, long long defaultValue) { addParameterInternal(name, defaultValue); } void QtFirebaseRemoteConfig::addParameter(const QString &name, double defaultValue) { addParameterInternal(name, defaultValue); } void QtFirebaseRemoteConfig::addParameter(const QString &name, const QString &defaultValue) { addParameterInternal(name, defaultValue); } void QtFirebaseRemoteConfig::addParameter(const QString &name, bool defaultValue) { addParameterInternal(name, defaultValue); } void QtFirebaseRemoteConfig::init() { qDebug() << self << "::init" << "called"; if(!qFirebase->ready()) { qDebug() << self << "::init" << "base not ready"; return; } if(!_ready && !_initializing) { _initializing = true; ::firebase::ModuleInitializer initializer; auto future = initializer.Initialize(qFirebase->firebaseApp(), nullptr, [](::firebase::App* app, void*) { qDebug() << self << "::init" << "try to initialize Remote Config"; return ::firebase::remote_config::Initialize(*app); }); qFirebase->addFuture(__QTFIREBASE_ID + QStringLiteral(".config.init"), future); } } void QtFirebaseRemoteConfig::onFutureEvent(QString eventId, firebase::FutureBase future) { if(!eventId.startsWith(__QTFIREBASE_ID)) return; qDebug() << self << "::onFutureEvent" << eventId; if(eventId == __QTFIREBASE_ID + QStringLiteral(".config.fetch")) onFutureEventFetch(future); else if( eventId == __QTFIREBASE_ID + QStringLiteral(".config.init") ) onFutureEventInit(future); } void QtFirebaseRemoteConfig::onFutureEventInit(firebase::FutureBase &future) { if (future.error() != firebase::kFutureStatusComplete) { qDebug() << this << "::onFutureEvent" << "initializing failed." << "ERROR: Action failed with error code and message: " << future.error() << future.error_message(); _initializing = false; return; } qDebug() << this << "::onFutureEvent initialized ok"; _initializing = false; setReady(true); } void QtFirebaseRemoteConfig::onFutureEventFetch(firebase::FutureBase &future) { if(future.status() != firebase::kFutureStatusComplete) { qDebug() << this << "::onFutureEvent initializing failed." << "ERROR: Action failed with error code and message: " << future.error() << future.error_message(); _initializing = false; return; } qDebug() << this << "::onFutureEvent initialized ok"; _initializing = false; bool fetchActivated = remote_config::ActivateFetched(); //On first run even if we have activateResult failed we still can get cached values qDebug() << self << QString(QStringLiteral("ActivateFetched %1")).arg(fetchActivated ? QStringLiteral("succeeded") : QStringLiteral("failed")); const remote_config::ConfigInfo& info = remote_config::GetInfo(); qDebug() << self << QString(QStringLiteral("Info last_fetch_time_ms=%1 fetch_status=%2 failure_reason=%3")) .arg(QString::number(info.fetch_time)) .arg(info.last_fetch_status) .arg(info.last_fetch_failure_reason); if(info.last_fetch_status == remote_config::kLastFetchStatusSuccess) { QVariantMap updatedParameters; for(QVariantMap::const_iterator it = _parameters.begin(); it!=_parameters.end();++it) { const QVariant& value = it.value(); Q_ASSERT(value.type() == QVariant::Bool || value.type() == QVariant::LongLong || value.type() == QVariant::Int || value.type() == QVariant::Double || value.type() == QVariant::String); if(value.type() == QVariant::Bool) { updatedParameters[it.key()] = remote_config::GetBoolean(it.key().toUtf8().constData()); } else if(value.type() == QVariant::LongLong) { updatedParameters[it.key()] = remote_config::GetLong(it.key().toUtf8().constData()); } else if(value.type() == QVariant::Int) { updatedParameters[it.key()] = remote_config::GetLong(it.key().toUtf8().constData()); } else if(value.type() == QVariant::Double) { updatedParameters[it.key()] = remote_config::GetDouble(it.key().toUtf8().constData()); } else if(value.type() == QVariant::String) { std::string result = remote_config::GetString(it.key().toUtf8().constData()); updatedParameters[it.key()] = QString(QString::fromUtf8(result.c_str())); //Code for data type /*std::vector<unsigned char> out = remote_config::GetData(it.key().toUtf8().constData()); QByteArray data; for (size_t i = 0; i < out.size(); ++i) { data.append(out[i]); } updatedParameters[it.key()] = QString(data);*/ } } //SDK code to print out the keys /*std::vector<std::string> keys = remote_config::GetKeys(); qDebug() << "QtFirebaseRemoteConfig GetKeys:"; for (auto s = keys.begin(); s != keys.end(); ++s) { qDebug() << s->c_str(); } keys = remote_config::GetKeysByPrefix("TestD"); printf("GetKeysByPrefix(\"TestD\"):"); for (auto s = keys.begin(); s != keys.end(); ++s) { printf(" %s", s->c_str()); }*/ setParameters(updatedParameters); } else { if(info.last_fetch_failure_reason == remote_config::kFetchFailureReasonInvalid) { emit error(kFetchFailureReasonInvalid, QStringLiteral("The fetch has not yet failed.")); } else if(info.last_fetch_failure_reason == remote_config::kFetchFailureReasonThrottled) { emit error(kFetchFailureReasonThrottled, QStringLiteral("Throttled by the server. You are sending too many fetch requests in too short a time.")); } else { emit error(kFetchFailureReasonError, QStringLiteral("Failure reason is unknown")); } } future.Release(); } void QtFirebaseRemoteConfig::fetch() { fetch(_cacheExpirationTime<1000 ? 0 : _cacheExpirationTime/1000); } void QtFirebaseRemoteConfig::fetch(long long cacheExpirationInSeconds) { if(_parameters.size() == 0) { qDebug() << self << "::fetch not started, parameters were not initialized"; return; } qDebug() << self <<"::fetch with expirationtime" << cacheExpirationInSeconds << "seconds"; QVariantMap filteredMap; for(QVariantMap::const_iterator it = _parameters.begin(); it!=_parameters.end();++it) { const QVariant& value = it.value(); if(value.type() == QVariant::Bool || value.type() == QVariant::LongLong || value.type() == QVariant::Int || value.type() == QVariant::Double || value.type() == QVariant::String) { filteredMap[it.key()] = value; } else { qWarning() << self << "Data type:" << value.typeName() << " not supported"; } } std::unique_ptr<remote_config::ConfigKeyValueVariant[]> defaults( new remote_config::ConfigKeyValueVariant[filteredMap.size()]); __defaultsByteArrayList.clear(); uint index = 0; for(QVariantMap::const_iterator it = filteredMap.begin(); it!=filteredMap.end();++it) { const QVariant& value = it.value(); __defaultsByteArrayList.insert(index,QByteArray(it.key().toUtf8().data())); if(value.type() == QVariant::Bool) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toBool()}; } else if(value.type() == QVariant::LongLong) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toLongLong()}; } else if(value.type() == QVariant::Int) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toInt()}; } else if(value.type() == QVariant::Double) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toDouble()}; } else if(value.type() == QVariant::String) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toString().toUtf8().constData()}; //Code for data type /*QByteArray data = value.toString().toUtf8(); defaults[cnt] = remote_config::ConfigKeyValueVariant{ it.key().toUtf8().constData(), firebase::Variant::FromMutableBlob(data.constData(), data.size())};*/ } index++; } // NOTE crash on iOS with Firebase 4.1.0 remote_config::SetDefaults(defaults.get(), filteredMap.size()); /*remote_config::SetConfigSetting(remote_config::kConfigSettingDeveloperMode, "1"); if ((*remote_config::GetConfigSetting(remote_config::kConfigSettingDeveloperMode) .c_str()) != '1') { qDebug()<<"Failed to enable developer mode"; }*/ qDebug() << self << "::fetch" << "run fetching..."; auto future = remote_config::Fetch(cacheExpirationInSeconds); qFirebase->addFuture(__QTFIREBASE_ID + QStringLiteral(".config.fetch"), future); } void QtFirebaseRemoteConfig::fetchNow() { fetch(0); } <commit_msg>Fixed crash in RemoteConfig<commit_after>#include "qtfirebaseremoteconfig.h" namespace remote_config = ::firebase::remote_config; QtFirebaseRemoteConfig *QtFirebaseRemoteConfig::self = 0; QtFirebaseRemoteConfig::QtFirebaseRemoteConfig(QObject *parent) : QObject(parent), _ready(false), _initializing(false), _cacheExpirationTime(firebase::remote_config::kDefaultCacheExpiration*1000),//milliseconds __appId(nullptr) { __QTFIREBASE_ID = QString().sprintf("%8p", this); if(self == 0) { self = this; qDebug() << self << "::QtFirebaseRemoteConfig" << "singleton"; } #if defined(Q_OS_ANDROID) if (PlatformUtils::googleServicesAvailable()) { qDebug() << this << " Google Services is available, now init remote_config" ; //Call init outside of constructor, otherwise signal readyChanged not emited QTimer::singleShot(500, this, SLOT(delayedInit())); connect(qFirebase,&QtFirebase::futureEvent, this, &QtFirebaseRemoteConfig::onFutureEvent); } else { qDebug() << this << " Google Services is NOT available, CANNOT use remote_config" ; } #else //Call init outside of constructor, otherwise signal readyChanged not emited QTimer::singleShot(500, this, SLOT(delayedInit())); connect(qFirebase,&QtFirebase::futureEvent, this, &QtFirebaseRemoteConfig::onFutureEvent); #endif } bool QtFirebaseRemoteConfig::checkInstance(const char *function) { bool b = (QtFirebaseRemoteConfig::self != 0); if(!b) qWarning("QtFirebaseRemoteConfig::%s:", function); return b; } void QtFirebaseRemoteConfig::addParameterInternal(const QString &name, const QVariant &defaultValue) { _parameters[name] = defaultValue; } void QtFirebaseRemoteConfig::delayedInit() { if(qFirebase->ready()) { qDebug() << this << "::delayedInit : QtFirebase is ready, calling init" ; init(); } else { qDebug() << this << "::delayedInit : QtFirebase not ready, connecting to its readyChanged signal" ; connect(qFirebase,&QtFirebase::readyChanged, this, &QtFirebaseRemoteConfig::init); qFirebase->requestInit(); } } QVariant QtFirebaseRemoteConfig::getParameterValue(const QString &name) const { if(_parameters.contains(name)) { return _parameters[name]; } return _parameters[name]; } bool QtFirebaseRemoteConfig::ready() { return _ready; } void QtFirebaseRemoteConfig::setReady(bool ready) { qDebug() << this << "::setReady before:" << _ready << "now:" << ready; if (_ready != ready) { _ready = ready; emit readyChanged(); } } QVariantMap QtFirebaseRemoteConfig::parameters() const { return _parameters; } void QtFirebaseRemoteConfig::setParameters(const QVariantMap &map) { _parameters = map; emit parametersChanged(); } long long QtFirebaseRemoteConfig::cacheExpirationTime() const { return _cacheExpirationTime; } void QtFirebaseRemoteConfig::setCacheExpirationTime(long long timeMs) { _cacheExpirationTime = timeMs; emit cacheExpirationTimeChanged(); } void QtFirebaseRemoteConfig::addParameter(const QString &name, long long defaultValue) { addParameterInternal(name, defaultValue); } void QtFirebaseRemoteConfig::addParameter(const QString &name, double defaultValue) { addParameterInternal(name, defaultValue); } void QtFirebaseRemoteConfig::addParameter(const QString &name, const QString &defaultValue) { addParameterInternal(name, defaultValue); } void QtFirebaseRemoteConfig::addParameter(const QString &name, bool defaultValue) { addParameterInternal(name, defaultValue); } void QtFirebaseRemoteConfig::init() { qDebug() << self << "::init" << "called"; if(!qFirebase->ready()) { qDebug() << self << "::init" << "base not ready"; return; } if(!_ready && !_initializing) { _initializing = true; ::firebase::ModuleInitializer initializer; auto future = initializer.Initialize(qFirebase->firebaseApp(), nullptr, [](::firebase::App* app, void*) { qDebug() << self << "::init" << "try to initialize Remote Config"; return ::firebase::remote_config::Initialize(*app); }); qFirebase->addFuture(__QTFIREBASE_ID + QStringLiteral(".config.init"), future); } } void QtFirebaseRemoteConfig::onFutureEvent(QString eventId, firebase::FutureBase future) { if(!eventId.startsWith(__QTFIREBASE_ID)) return; qDebug() << self << "::onFutureEvent" << eventId; if(eventId == __QTFIREBASE_ID + QStringLiteral(".config.fetch")) onFutureEventFetch(future); else if( eventId == __QTFIREBASE_ID + QStringLiteral(".config.init") ) onFutureEventInit(future); } void QtFirebaseRemoteConfig::onFutureEventInit(firebase::FutureBase &future) { if (future.error() != firebase::kFutureStatusComplete) { qDebug() << this << "::onFutureEvent" << "initializing failed." << "ERROR: Action failed with error code and message: " << future.error() << future.error_message(); _initializing = false; return; } qDebug() << this << "::onFutureEvent initialized ok"; _initializing = false; setReady(true); } void QtFirebaseRemoteConfig::onFutureEventFetch(firebase::FutureBase &future) { if(future.status() != firebase::kFutureStatusComplete) { qDebug() << this << "::onFutureEvent initializing failed." << "ERROR: Action failed with error code and message: " << future.error() << future.error_message(); _initializing = false; return; } qDebug() << this << "::onFutureEvent initialized ok"; _initializing = false; bool fetchActivated = remote_config::ActivateFetched(); //On first run even if we have activateResult failed we still can get cached values qDebug() << self << QString(QStringLiteral("ActivateFetched %1")).arg(fetchActivated ? QStringLiteral("succeeded") : QStringLiteral("failed")); const remote_config::ConfigInfo& info = remote_config::GetInfo(); qDebug() << self << QString(QStringLiteral("Info last_fetch_time_ms=%1 fetch_status=%2 failure_reason=%3")) .arg(QString::number(info.fetch_time)) .arg(info.last_fetch_status) .arg(info.last_fetch_failure_reason); if(info.last_fetch_status == remote_config::kLastFetchStatusSuccess) { QVariantMap updatedParameters; for(QVariantMap::const_iterator it = _parameters.begin(); it!=_parameters.end();++it) { const QVariant& value = it.value(); Q_ASSERT(value.type() == QVariant::Bool || value.type() == QVariant::LongLong || value.type() == QVariant::Int || value.type() == QVariant::Double || value.type() == QVariant::String); if(value.type() == QVariant::Bool) { updatedParameters[it.key()] = remote_config::GetBoolean(it.key().toUtf8().constData()); } else if(value.type() == QVariant::LongLong) { updatedParameters[it.key()] = remote_config::GetLong(it.key().toUtf8().constData()); } else if(value.type() == QVariant::Int) { updatedParameters[it.key()] = remote_config::GetLong(it.key().toUtf8().constData()); } else if(value.type() == QVariant::Double) { updatedParameters[it.key()] = remote_config::GetDouble(it.key().toUtf8().constData()); } else if(value.type() == QVariant::String) { std::string result = remote_config::GetString(it.key().toUtf8().constData()); updatedParameters[it.key()] = QString(QString::fromUtf8(result.c_str())); //Code for data type /*std::vector<unsigned char> out = remote_config::GetData(it.key().toUtf8().constData()); QByteArray data; for (size_t i = 0; i < out.size(); ++i) { data.append(out[i]); } updatedParameters[it.key()] = QString(data);*/ } } //SDK code to print out the keys /*std::vector<std::string> keys = remote_config::GetKeys(); qDebug() << "QtFirebaseRemoteConfig GetKeys:"; for (auto s = keys.begin(); s != keys.end(); ++s) { qDebug() << s->c_str(); } keys = remote_config::GetKeysByPrefix("TestD"); printf("GetKeysByPrefix(\"TestD\"):"); for (auto s = keys.begin(); s != keys.end(); ++s) { printf(" %s", s->c_str()); }*/ setParameters(updatedParameters); } else { if(info.last_fetch_failure_reason == remote_config::kFetchFailureReasonInvalid) { emit error(kFetchFailureReasonInvalid, QStringLiteral("The fetch has not yet failed.")); } else if(info.last_fetch_failure_reason == remote_config::kFetchFailureReasonThrottled) { emit error(kFetchFailureReasonThrottled, QStringLiteral("Throttled by the server. You are sending too many fetch requests in too short a time.")); } else { emit error(kFetchFailureReasonError, QStringLiteral("Failure reason is unknown")); } } future.Release(); } void QtFirebaseRemoteConfig::fetch() { fetch(_cacheExpirationTime<1000 ? 0 : _cacheExpirationTime/1000); } void QtFirebaseRemoteConfig::fetch(long long cacheExpirationInSeconds) { if(_parameters.size() == 0) { qDebug() << self << "::fetch not started, parameters were not initialized"; return; } qDebug() << self <<"::fetch with expirationtime" << cacheExpirationInSeconds << "seconds"; QVariantMap filteredMap; for(QVariantMap::const_iterator it = _parameters.begin(); it!=_parameters.end();++it) { const QVariant& value = it.value(); if(value.type() == QVariant::Bool || value.type() == QVariant::LongLong || value.type() == QVariant::Int || value.type() == QVariant::Double || value.type() == QVariant::String) { filteredMap[it.key()] = value; } else { qWarning() << self << "Data type:" << value.typeName() << " not supported"; } } std::unique_ptr<remote_config::ConfigKeyValueVariant[]> defaults( new remote_config::ConfigKeyValueVariant[filteredMap.size()]); __defaultsByteArrayList.clear(); uint index = 0; for(QVariantMap::const_iterator it = filteredMap.begin(); it!=filteredMap.end();++it) { const QVariant& value = it.value(); __defaultsByteArrayList.insert(index,QByteArray(it.key().toUtf8().data())); if(value.type() == QVariant::Bool) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toBool()}; } else if(value.type() == QVariant::LongLong) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toLongLong()}; } else if(value.type() == QVariant::Int) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toInt()}; } else if(value.type() == QVariant::Double) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toDouble()}; } else if(value.type() == QVariant::String) { defaults[index] = remote_config::ConfigKeyValueVariant{__defaultsByteArrayList.at(index).constData(), value.toString().toUtf8().constData()}; //Code for data type /*QByteArray data = value.toString().toUtf8(); defaults[cnt] = remote_config::ConfigKeyValueVariant{ it.key().toUtf8().constData(), firebase::Variant::FromMutableBlob(data.constData(), data.size())};*/ } index++; } remote_config::SetDefaults(defaults.get(), filteredMap.size()); /*remote_config::SetConfigSetting(remote_config::kConfigSettingDeveloperMode, "1"); if ((*remote_config::GetConfigSetting(remote_config::kConfigSettingDeveloperMode) .c_str()) != '1') { qDebug()<<"Failed to enable developer mode"; }*/ qDebug() << self << "::fetch" << "run fetching..."; auto future = remote_config::Fetch(cacheExpirationInSeconds); qFirebase->addFuture(__QTFIREBASE_ID + QStringLiteral(".config.fetch"), future); } void QtFirebaseRemoteConfig::fetchNow() { fetch(0); } <|endoftext|>
<commit_before>// // File: ShaderModule.cpp // Author: Hongtae Kim (tiff2766@gmail.com) // // Copyright (c) 2016-2017 Hongtae Kim. All rights reserved. // #include "../GraphicsAPI.h" #if DKGL_ENABLE_VULKAN #include "Extensions.h" #include "Types.h" #include "ShaderModule.h" #include "ShaderFunction.h" #include "GraphicsDevice.h" using namespace DKFramework; using namespace DKFramework::Private::Vulkan; ShaderModule::ShaderModule(DKGraphicsDevice* d, VkShaderModule s, const void* data, size_t size, DKShader::StageType st) : device(d) , module(s) , pushConstantLayout({}) { switch (st) { case DKShader::StageType::Vertex: stage = VK_SHADER_STAGE_VERTEX_BIT; break; case DKShader::StageType::Fragment: stage = VK_SHADER_STAGE_FRAGMENT_BIT; break; case DKShader::StageType::Compute: stage = VK_SHADER_STAGE_COMPUTE_BIT; break; default: DKASSERT_DEBUG(0); break; } GraphicsDevice* dev = (GraphicsDevice*)DKGraphicsDeviceInterface::Instance(device); spirv_cross::Compiler compiler(reinterpret_cast<const uint32_t*>(data), size / sizeof(uint32_t)); auto active = compiler.get_active_interface_variables(); spirv_cross::ShaderResources resources = compiler.get_shader_resources(); auto GetResource = [&compiler, &active](const spirv_cross::Resource& resource, bool writable)->DKShaderResource { DKShaderResource out = {}; out.set = compiler.get_decoration(resource.id, spv::DecorationDescriptorSet); out.binding = compiler.get_decoration(resource.id, spv::DecorationBinding); out.name = compiler.get_name(resource.id).c_str(); out.stride = compiler.get_decoration(resource.id, spv::DecorationArrayStride); out.enabled = active.find(resource.id) != active.end(); if (writable) out.access = DKShaderResource::AccessReadWrite; else out.access = DKShaderResource::AccessReadOnly; const spirv_cross::SPIRType& type = compiler.get_type(resource.type_id); out.count = 1; for (auto n : type.array) out.count = out.count * n; switch (type.basetype) { case spirv_cross::SPIRType::Image: out.type = DKShaderResource::TypeTexture; break; case spirv_cross::SPIRType::SampledImage: out.type = DKShaderResource::TypeSampledTexture; break; case spirv_cross::SPIRType::Sampler: out.type = DKShaderResource::TypeSampler; break; case spirv_cross::SPIRType::Struct: out.type = DKShaderResource::TypeBuffer; out.typeInfo.buffer.dataType = DKShaderDataType::Struct; out.typeInfo.buffer.alignment = compiler.get_decoration(resource.id, spv::DecorationAlignment); out.typeInfo.buffer.size = compiler.get_declared_struct_size(type); break; default: DKASSERT_DESC_DEBUG(0, "Should implement this!"); DKLogE("ERROR: Unsupported SPIR-V type!"); } if (out.type == DKShaderResource::TypeBuffer) { struct GetStructMembers { DKShaderResource& base; // buffer resource (base) spirv_cross::Compiler& compiler; auto operator () (const DKString& name, const spirv_cross::SPIRType& spType) -> DKShaderResourceStruct { DKShaderResourceStruct rst = {}; // get struct members! rst.members.Reserve(spType.member_types.size()); for (uint32_t i = 0; i < spType.member_types.size(); ++i) { DKShaderResourceStructMember member; uint32_t type = spType.member_types.at(i); const spirv_cross::SPIRType& memberType = compiler.get_type(type); member.dataType = ShaderDataTypeFromSPIRType(memberType); DKASSERT_DEBUG(member.dataType != DKShaderDataType::Unknown); DKASSERT_DEBUG(member.dataType != DKShaderDataType::None); if (member.dataType == DKShaderDataType::Struct) { member.typeInfoKey = DKString(name).Append(".").Append(member.name); GetStructMembers getMembers = { base, compiler }; DKShaderResourceStruct memberStruct = getMembers(member.typeInfoKey, memberType); base.structTypeMemberMap.Update(member.typeInfoKey, memberStruct); } member.count = 1; for (auto n : spType.array) member.count = member.count * n; member.name = compiler.get_member_name(spType.self, i).c_str(); member.offset = compiler.type_struct_member_offset(spType, i); //member.size = (memberType.width >> 3) * memberType.vecsize * memberType.columns; member.size = compiler.get_declared_struct_member_size(spType, i); DKASSERT_DEBUG(member.size > 0); if (member.count > 1) member.stride = compiler.type_struct_member_array_stride(spType, i); else member.stride = 0; rst.members.Add(member); } rst.members.ShrinkToFit(); return rst; } }; out.typeInfoKey = out.name; GetStructMembers getMembers = { out, compiler }; DKShaderResourceStruct rst = getMembers(out.typeInfoKey, compiler.get_type(resource.base_type_id)); out.structTypeMemberMap.Update(out.typeInfoKey, std::move(rst)); } return out; }; auto GetDescriptorBinding = [&compiler](const spirv_cross::Resource& resource, VkDescriptorType type)->DescriptorBinding { DescriptorBinding binding = {}; binding.type = type; binding.set = compiler.get_decoration(resource.id, spv::DecorationDescriptorSet); binding.binding = compiler.get_decoration(resource.id, spv::DecorationBinding); const spirv_cross::SPIRType& spType = compiler.get_type_from_variable(resource.id); // get item count! (array size) binding.count = 1; if (spType.array.size() > 0) { for (auto i : spType.array) binding.count *= i; } return binding; }; // https://github.com/KhronosGroup/SPIRV-Cross/wiki/Reflection-API-user-guide // uniform_buffers for (const spirv_cross::Resource& resource : resources.uniform_buffers) { this->resources.Add(GetResource(resource, false)); this->descriptorBindings.Add(GetDescriptorBinding(resource, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER)); } // storage_buffers for (const spirv_cross::Resource& resource : resources.storage_buffers) { this->resources.Add(GetResource(resource, true)); this->descriptorBindings.Add(GetDescriptorBinding(resource, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER)); } // storage_images for (const spirv_cross::Resource& resource : resources.storage_images) { this->resources.Add(GetResource(resource, true)); this->descriptorBindings.Add(GetDescriptorBinding(resource, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE)); } // sampled_images (sampler2D) for (const spirv_cross::Resource& resource : resources.sampled_images) { this->resources.Add(GetResource(resource, false)); this->descriptorBindings.Add(GetDescriptorBinding(resource, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)); } // separate_images for (const spirv_cross::Resource& resource : resources.separate_images) { const spirv_cross::SPIRType& spType = compiler.get_type_from_variable(resource.id); VkDescriptorType type = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; if (spType.image.dim == spv::DimBuffer) { type = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; } this->resources.Add(GetResource(resource, false)); this->descriptorBindings.Add(GetDescriptorBinding(resource, type)); } // separate_samplers for (const spirv_cross::Resource& resource : resources.separate_samplers) { this->resources.Add(GetResource(resource, false)); this->descriptorBindings.Add(GetDescriptorBinding(resource, VK_DESCRIPTOR_TYPE_SAMPLER)); } // stage inputs this->stageInputAttributes.Reserve(resources.stage_inputs.size()); for (const spirv_cross::Resource& resource : resources.stage_inputs) { uint32_t location = compiler.get_decoration(resource.id, spv::DecorationLocation); DKStringU8 name = ""; if (resource.name.size() > 0) name = resource.name.c_str(); else name = compiler.get_fallback_name(resource.id).c_str(); const spirv_cross::SPIRType& spType = compiler.get_type(resource.type_id); DKShaderDataType dataType = ShaderDataTypeFromSPIRType(spType); DKASSERT_DEBUG(dataType != DKShaderDataType::Unknown); // get item count! (array size) uint32_t count = 1; if (spType.array.size() > 0) { for (auto i : spType.array) count *= i; } DKShaderAttribute attr = {}; attr.location = location; attr.name = name; attr.type = dataType; attr.active = true; this->stageInputAttributes.Add(attr); } // get pushConstant range. if (resources.push_constant_buffers.size() > 0) { const spirv_cross::Resource& resource = resources.push_constant_buffers[0]; std::vector<spirv_cross::BufferRange> ranges = compiler.get_active_buffer_ranges(resource.id); this->pushConstantLayout.memberLayouts.Reserve(ranges.size()); uint32_t pushConstantOffset = (uint32_t)ranges[0].offset; uint32_t pushConstantSize = 0; for (spirv_cross::BufferRange &range : ranges) { // get range. PushConstantLayout layout; layout.name = compiler.get_member_name(resource.id, range.index).c_str(); layout.offset = range.offset; layout.size = range.range; pushConstantSize = (layout.offset - pushConstantOffset) + layout.size; this->pushConstantLayout.memberLayouts.Add(std::move(layout)); } if (pushConstantSize % 4) // size must be a multiple of 4 { pushConstantSize += 4 - (pushConstantSize % 4); } DKASSERT_DEBUG((pushConstantOffset % 4) == 0); DKASSERT_DEBUG((pushConstantSize % 4) == 0); DKASSERT_DEBUG(pushConstantSize > 0); DKASSERT_DEBUG(pushConstantOffset < dev->properties.limits.maxPushConstantsSize); DKASSERT_DEBUG((pushConstantOffset + pushConstantSize) < dev->properties.limits.maxPushConstantsSize); this->pushConstantLayout.offset = pushConstantOffset; this->pushConstantLayout.size = pushConstantSize; this->pushConstantLayout.name = compiler.get_name(resource.id).c_str(); //const spirv_cross::SPIRType& spType = compiler.get_type_from_variable(resource.id); } // get module entry points std::vector<spirv_cross::EntryPoint> entryPoints = compiler.get_entry_points_and_stages(); for (spirv_cross::EntryPoint& ep : entryPoints) { functionNames.Add(ep.name.c_str()); } // specialization constants std::vector<spirv_cross::SpecializationConstant> spConsts = compiler.get_specialization_constants(); for (spirv_cross::SpecializationConstant& sc : spConsts) { // } // sort bindings this->descriptorBindings.Sort([](const DescriptorBinding& a, const DescriptorBinding& b) { if (a.set == b.set) return a.binding < b.binding; return a.set < b.set; }); this->descriptorBindings.ShrinkToFit(); this->resources.ShrinkToFit(); this->stageInputAttributes.ShrinkToFit(); } ShaderModule::~ShaderModule() { GraphicsDevice* dev = (GraphicsDevice*)DKGraphicsDeviceInterface::Instance(device); vkDestroyShaderModule(dev->device, module, 0); } DKObject<DKShaderFunction> ShaderModule::CreateFunction(const DKString& name) const { for (const DKString& fname : functionNames) { if (fname.Compare(name) == 0) { DKObject<ShaderFunction> func = DKOBJECT_NEW ShaderFunction(const_cast<ShaderModule*>(this), DKStringU8(name), 0, 0); return func.SafeCast<DKShaderFunction>(); } } return NULL; } DKObject<DKShaderFunction> ShaderModule::CreateSpecializedFunction(const DKString& name, const DKShaderSpecialization* values, size_t numValues) const { if (values && numValues > 0) { // TODO: verify values with SPIR-V Cross reflection } return NULL; } #endif //#if DKGL_ENABLE_VULKAN <commit_msg>no message<commit_after>// // File: ShaderModule.cpp // Author: Hongtae Kim (tiff2766@gmail.com) // // Copyright (c) 2016-2017 Hongtae Kim. All rights reserved. // #include "../GraphicsAPI.h" #if DKGL_ENABLE_VULKAN #include "Extensions.h" #include "Types.h" #include "ShaderModule.h" #include "ShaderFunction.h" #include "GraphicsDevice.h" using namespace DKFramework; using namespace DKFramework::Private::Vulkan; ShaderModule::ShaderModule(DKGraphicsDevice* d, VkShaderModule s, const void* data, size_t size, DKShader::StageType st) : device(d) , module(s) , pushConstantLayout({}) { switch (st) { case DKShader::StageType::Vertex: stage = VK_SHADER_STAGE_VERTEX_BIT; break; case DKShader::StageType::Fragment: stage = VK_SHADER_STAGE_FRAGMENT_BIT; break; case DKShader::StageType::Compute: stage = VK_SHADER_STAGE_COMPUTE_BIT; break; default: DKASSERT_DEBUG(0); break; } GraphicsDevice* dev = (GraphicsDevice*)DKGraphicsDeviceInterface::Instance(device); spirv_cross::Compiler compiler(reinterpret_cast<const uint32_t*>(data), size / sizeof(uint32_t)); auto active = compiler.get_active_interface_variables(); spirv_cross::ShaderResources resources = compiler.get_shader_resources(); auto GetResource = [&compiler, &active](const spirv_cross::Resource& resource, bool writable)->DKShaderResource { DKShaderResource out = {}; out.set = compiler.get_decoration(resource.id, spv::DecorationDescriptorSet); out.binding = compiler.get_decoration(resource.id, spv::DecorationBinding); out.name = compiler.get_name(resource.id).c_str(); out.stride = compiler.get_decoration(resource.id, spv::DecorationArrayStride); out.enabled = active.find(resource.id) != active.end(); if (writable) out.access = DKShaderResource::AccessReadWrite; else out.access = DKShaderResource::AccessReadOnly; const spirv_cross::SPIRType& type = compiler.get_type(resource.type_id); out.count = 1; for (auto n : type.array) out.count = out.count * n; switch (type.basetype) { case spirv_cross::SPIRType::Image: out.type = DKShaderResource::TypeTexture; break; case spirv_cross::SPIRType::SampledImage: out.type = DKShaderResource::TypeSampledTexture; break; case spirv_cross::SPIRType::Sampler: out.type = DKShaderResource::TypeSampler; break; case spirv_cross::SPIRType::Struct: out.type = DKShaderResource::TypeBuffer; out.typeInfo.buffer.dataType = DKShaderDataType::Struct; out.typeInfo.buffer.alignment = compiler.get_decoration(resource.id, spv::DecorationAlignment); out.typeInfo.buffer.size = compiler.get_declared_struct_size(type); break; default: DKASSERT_DESC_DEBUG(0, "Should implement this!"); DKLogE("ERROR: Unsupported SPIR-V type!"); } if (out.type == DKShaderResource::TypeBuffer) { struct GetStructMembers { DKShaderResource& base; // buffer resource (base) spirv_cross::Compiler& compiler; auto operator () (const DKString& name, const spirv_cross::SPIRType& spType) -> DKShaderResourceStruct { DKShaderResourceStruct rst = {}; // get struct members! rst.members.Reserve(spType.member_types.size()); for (uint32_t i = 0; i < spType.member_types.size(); ++i) { DKShaderResourceStructMember member; uint32_t type = spType.member_types.at(i); const spirv_cross::SPIRType& memberType = compiler.get_type(type); member.dataType = ShaderDataTypeFromSPIRType(memberType); DKASSERT_DEBUG(member.dataType != DKShaderDataType::Unknown); DKASSERT_DEBUG(member.dataType != DKShaderDataType::None); if (member.dataType == DKShaderDataType::Struct) { member.typeInfoKey = DKString(name).Append(".").Append(member.name); GetStructMembers getMembers = { base, compiler }; DKShaderResourceStruct memberStruct = getMembers(member.typeInfoKey, memberType); base.structTypeMemberMap.Update(member.typeInfoKey, memberStruct); } member.count = 1; for (auto n : memberType.array) member.count = member.count * n; member.name = compiler.get_member_name(spType.self, i).c_str(); member.offset = compiler.type_struct_member_offset(spType, i); //member.size = (memberType.width >> 3) * memberType.vecsize * memberType.columns; member.size = compiler.get_declared_struct_member_size(spType, i); DKASSERT_DEBUG(member.size > 0); if (member.count > 1) member.stride = compiler.type_struct_member_array_stride(spType, i); else member.stride = 0; rst.members.Add(member); } rst.members.ShrinkToFit(); return rst; } }; out.typeInfoKey = out.name; GetStructMembers getMembers = { out, compiler }; DKShaderResourceStruct rst = getMembers(out.typeInfoKey, compiler.get_type(resource.base_type_id)); out.structTypeMemberMap.Update(out.typeInfoKey, std::move(rst)); } return out; }; auto GetDescriptorBinding = [&compiler](const spirv_cross::Resource& resource, VkDescriptorType type)->DescriptorBinding { DescriptorBinding binding = {}; binding.type = type; binding.set = compiler.get_decoration(resource.id, spv::DecorationDescriptorSet); binding.binding = compiler.get_decoration(resource.id, spv::DecorationBinding); const spirv_cross::SPIRType& spType = compiler.get_type_from_variable(resource.id); // get item count! (array size) binding.count = 1; if (spType.array.size() > 0) { for (auto i : spType.array) binding.count *= i; } return binding; }; // https://github.com/KhronosGroup/SPIRV-Cross/wiki/Reflection-API-user-guide // uniform_buffers for (const spirv_cross::Resource& resource : resources.uniform_buffers) { this->resources.Add(GetResource(resource, false)); this->descriptorBindings.Add(GetDescriptorBinding(resource, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER)); } // storage_buffers for (const spirv_cross::Resource& resource : resources.storage_buffers) { this->resources.Add(GetResource(resource, true)); this->descriptorBindings.Add(GetDescriptorBinding(resource, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER)); } // storage_images for (const spirv_cross::Resource& resource : resources.storage_images) { this->resources.Add(GetResource(resource, true)); this->descriptorBindings.Add(GetDescriptorBinding(resource, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE)); } // sampled_images (sampler2D) for (const spirv_cross::Resource& resource : resources.sampled_images) { this->resources.Add(GetResource(resource, false)); this->descriptorBindings.Add(GetDescriptorBinding(resource, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)); } // separate_images for (const spirv_cross::Resource& resource : resources.separate_images) { const spirv_cross::SPIRType& spType = compiler.get_type_from_variable(resource.id); VkDescriptorType type = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; if (spType.image.dim == spv::DimBuffer) { type = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; } this->resources.Add(GetResource(resource, false)); this->descriptorBindings.Add(GetDescriptorBinding(resource, type)); } // separate_samplers for (const spirv_cross::Resource& resource : resources.separate_samplers) { this->resources.Add(GetResource(resource, false)); this->descriptorBindings.Add(GetDescriptorBinding(resource, VK_DESCRIPTOR_TYPE_SAMPLER)); } // stage inputs this->stageInputAttributes.Reserve(resources.stage_inputs.size()); for (const spirv_cross::Resource& resource : resources.stage_inputs) { uint32_t location = compiler.get_decoration(resource.id, spv::DecorationLocation); DKStringU8 name = ""; if (resource.name.size() > 0) name = resource.name.c_str(); else name = compiler.get_fallback_name(resource.id).c_str(); const spirv_cross::SPIRType& spType = compiler.get_type(resource.type_id); DKShaderDataType dataType = ShaderDataTypeFromSPIRType(spType); DKASSERT_DEBUG(dataType != DKShaderDataType::Unknown); // get item count! (array size) uint32_t count = 1; if (spType.array.size() > 0) { for (auto i : spType.array) count *= i; } DKShaderAttribute attr = {}; attr.location = location; attr.name = name; attr.type = dataType; attr.active = true; this->stageInputAttributes.Add(attr); } // get pushConstant range. if (resources.push_constant_buffers.size() > 0) { const spirv_cross::Resource& resource = resources.push_constant_buffers[0]; std::vector<spirv_cross::BufferRange> ranges = compiler.get_active_buffer_ranges(resource.id); this->pushConstantLayout.memberLayouts.Reserve(ranges.size()); uint32_t pushConstantOffset = (uint32_t)ranges[0].offset; uint32_t pushConstantSize = 0; for (spirv_cross::BufferRange &range : ranges) { // get range. PushConstantLayout layout; layout.name = compiler.get_member_name(resource.id, range.index).c_str(); layout.offset = range.offset; layout.size = range.range; pushConstantSize = (layout.offset - pushConstantOffset) + layout.size; this->pushConstantLayout.memberLayouts.Add(std::move(layout)); } if (pushConstantSize % 4) // size must be a multiple of 4 { pushConstantSize += 4 - (pushConstantSize % 4); } DKASSERT_DEBUG((pushConstantOffset % 4) == 0); DKASSERT_DEBUG((pushConstantSize % 4) == 0); DKASSERT_DEBUG(pushConstantSize > 0); DKASSERT_DEBUG(pushConstantOffset < dev->properties.limits.maxPushConstantsSize); DKASSERT_DEBUG((pushConstantOffset + pushConstantSize) < dev->properties.limits.maxPushConstantsSize); this->pushConstantLayout.offset = pushConstantOffset; this->pushConstantLayout.size = pushConstantSize; this->pushConstantLayout.name = compiler.get_name(resource.id).c_str(); //const spirv_cross::SPIRType& spType = compiler.get_type_from_variable(resource.id); } // get module entry points std::vector<spirv_cross::EntryPoint> entryPoints = compiler.get_entry_points_and_stages(); for (spirv_cross::EntryPoint& ep : entryPoints) { functionNames.Add(ep.name.c_str()); } // specialization constants std::vector<spirv_cross::SpecializationConstant> spConsts = compiler.get_specialization_constants(); for (spirv_cross::SpecializationConstant& sc : spConsts) { // } // sort bindings this->descriptorBindings.Sort([](const DescriptorBinding& a, const DescriptorBinding& b) { if (a.set == b.set) return a.binding < b.binding; return a.set < b.set; }); this->descriptorBindings.ShrinkToFit(); this->resources.ShrinkToFit(); this->stageInputAttributes.ShrinkToFit(); } ShaderModule::~ShaderModule() { GraphicsDevice* dev = (GraphicsDevice*)DKGraphicsDeviceInterface::Instance(device); vkDestroyShaderModule(dev->device, module, 0); } DKObject<DKShaderFunction> ShaderModule::CreateFunction(const DKString& name) const { for (const DKString& fname : functionNames) { if (fname.Compare(name) == 0) { DKObject<ShaderFunction> func = DKOBJECT_NEW ShaderFunction(const_cast<ShaderModule*>(this), DKStringU8(name), 0, 0); return func.SafeCast<DKShaderFunction>(); } } return NULL; } DKObject<DKShaderFunction> ShaderModule::CreateSpecializedFunction(const DKString& name, const DKShaderSpecialization* values, size_t numValues) const { if (values && numValues > 0) { // TODO: verify values with SPIR-V Cross reflection } return NULL; } #endif //#if DKGL_ENABLE_VULKAN <|endoftext|>
<commit_before>/* * Neighbors.cc * * Copyright (C) 2014 OpenCog Foundation * * Author: William Ma <https://github.com/williampma> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <iostream> #include <opencog/atomspace/Link.h> #include <opencog/atomspace/Node.h> #include "Neighbors.h" namespace opencog { HandleSeq get_target_neighbors(const Handle& h, Type desiredLinkType) { HandleSeq answer; for (const LinkPtr& link : h->getIncomingSet()) { if (link->getType() != desiredLinkType) continue; if (classserver().isA(link->getType(), UNORDERED_LINK)) continue; if (link->getOutgoingAtom(0) != h) continue; for (const Handle& handle : link->getOutgoingSet()) { if (handle == h) continue; answer.emplace_back(handle); } } return answer; } HandleSeq get_source_neighbors(const Handle& h, Type desiredLinkType) { HandleSeq answer; for (const LinkPtr& link : h->getIncomingSet()) { if (link->getType() != desiredLinkType) continue; if (classserver().isA(link->getType(), UNORDERED_LINK)) continue; if (link->getOutgoingAtom(0) == h) continue; for (const Handle& handle : link->getOutgoingSet()) { if (handle == h) continue; answer.emplace_back(handle); } } return answer; } HandleSeq get_all_neighbors(const Handle& h, Type desiredLinkType) { HandleSeq answer; for (const LinkPtr& link : h->getIncomingSet()) { Type linkType = link->getType(); if (linkType == desiredLinkType) { for (const Handle& handle : link->getOutgoingSet()) { if (handle == h) continue; answer.emplace_back(handle); } } } return answer; } /* Tail-recursive helper function. We mark it static, so that * gcc can optimize this, i.e. call it without buying the stack * frame. */ static void get_distant_neighbors_rec(const Handle& h, UnorderedHandleSet& res, int dist) { res.insert(h); // Recursive calls if (dist != 0) { // 1. Fetch incomings for (const LinkPtr& in_l : h->getIncomingSet()) { Handle in_h = in_l->getHandle(); if (res.find(in_h) == res.cend()) // Do not re-explore get_distant_neighbors_rec(in_h, res, dist - 1); } // 2. Fetch outgoings LinkPtr link = LinkCast(h); if (link) { for (const Handle& out_h : link->getOutgoingSet()) { if (res.find(out_h) == res.cend()) // Do not re-explore get_distant_neighbors_rec(out_h, res, dist - 1); } } } } UnorderedHandleSet get_distant_neighbors(const Handle& h, int dist) { UnorderedHandleSet results; get_distant_neighbors_rec(h, results, dist); results.erase(h); return results; } } // namespace OpenCog <commit_msg>More optimization<commit_after>/* * Neighbors.cc * * Copyright (C) 2014 OpenCog Foundation * * Author: William Ma <https://github.com/williampma> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <iostream> #include <opencog/atomspace/Link.h> #include <opencog/atomspace/Node.h> #include "Neighbors.h" namespace opencog { HandleSeq get_target_neighbors(const Handle& h, Type desiredLinkType) { if (classserver().isA(desiredLinkType, UNORDERED_LINK)) return HandleSeq(); HandleSeq answer; for (const LinkPtr& link : h->getIncomingSet()) { if (link->getType() != desiredLinkType) continue; if (link->getOutgoingAtom(0) != h) continue; for (const Handle& handle : link->getOutgoingSet()) { if (handle == h) continue; answer.emplace_back(handle); } } return answer; } HandleSeq get_source_neighbors(const Handle& h, Type desiredLinkType) { if (classserver().isA(desiredLinkType, UNORDERED_LINK)) return HandleSeq(); HandleSeq answer; for (const LinkPtr& link : h->getIncomingSet()) { if (link->getType() != desiredLinkType) continue; if (link->getOutgoingAtom(0) == h) continue; for (const Handle& handle : link->getOutgoingSet()) { if (handle == h) continue; answer.emplace_back(handle); } } return answer; } HandleSeq get_all_neighbors(const Handle& h, Type desiredLinkType) { HandleSeq answer; for (const LinkPtr& link : h->getIncomingSet()) { Type linkType = link->getType(); if (linkType == desiredLinkType) { for (const Handle& handle : link->getOutgoingSet()) { if (handle == h) continue; answer.emplace_back(handle); } } } return answer; } /* Tail-recursive helper function. We mark it static, so that * gcc can optimize this, i.e. call it without buying the stack * frame. */ static void get_distant_neighbors_rec(const Handle& h, UnorderedHandleSet& res, int dist) { res.insert(h); // Recursive calls if (dist != 0) { // 1. Fetch incomings for (const LinkPtr& in_l : h->getIncomingSet()) { Handle in_h = in_l->getHandle(); if (res.find(in_h) == res.cend()) // Do not re-explore get_distant_neighbors_rec(in_h, res, dist - 1); } // 2. Fetch outgoings LinkPtr link = LinkCast(h); if (link) { for (const Handle& out_h : link->getOutgoingSet()) { if (res.find(out_h) == res.cend()) // Do not re-explore get_distant_neighbors_rec(out_h, res, dist - 1); } } } } UnorderedHandleSet get_distant_neighbors(const Handle& h, int dist) { UnorderedHandleSet results; get_distant_neighbors_rec(h, results, dist); results.erase(h); return results; } } // namespace OpenCog <|endoftext|>
<commit_before>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2018 Ryo Suzuki // Copyright (c) 2016-2018 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <type_traits> # include <tuple> namespace s3d { template <class Tag, class Type> class NamedParameter { private: Type m_value; public: constexpr NamedParameter() : m_value() {} explicit constexpr NamedParameter(Type value) : m_value(value) {} template <class U, class V = Type, std::enable_if_t<std::is_convertible_v<U, V>>* = nullptr> constexpr NamedParameter(const NamedParameter<Tag, U>& other) : m_value(other.value()) {} template <class... Args, class V = Type, std::enable_if_t<std::is_constructible_v<V, Args...>>* = nullptr> constexpr NamedParameter(const NamedParameter<Tag, std::tuple<Args...>>& tuple) : m_value(std::make_from_tuple<Type>(tuple.value())) {} constexpr const Type* operator ->() const { return std::addressof(m_value); } [[nodiscard]] constexpr const Type& operator *() const { return m_value; } [[nodiscard]] constexpr const Type& value() const { return m_value; } }; template <class Tag, class Type> class NamedParameter<Tag, Type&> { private: Type* m_ref; public: constexpr NamedParameter() noexcept : m_ref(nullptr) {} constexpr NamedParameter(Type& value) noexcept : m_ref(std::addressof(value)) {} constexpr Type* operator ->() const { return m_ref; } [[nodiscard]] constexpr Type& operator *() const { return *m_ref; } [[nodiscard]] constexpr Type& value() const { return *m_ref; } }; template <class Tag> struct NamedParameterHelper { template <class Type> using named_argument_type = NamedParameter<Tag, Type>; template <class Type> constexpr NamedParameter<Tag, std::decay_t<Type>> operator= (Type&& value) const { return NamedParameter<Tag, std::decay_t<Type>>(std::forward<Type>(value)); } template <class... Args> constexpr NamedParameter<Tag, std::tuple<Args...>> operator() (const Args&... args) const { return NamedParameter<Tag, std::tuple<Args...>>(std::make_tuple(args...)); } template <class Type> constexpr NamedParameter<Tag, Type&> operator= (std::reference_wrapper<Type> value) const { return NamedParameter<Tag, Type&>(value.get()); } template <class Type> constexpr NamedParameter<Tag, Type&> operator() (std::reference_wrapper<Type> value) const { return NamedParameter<Tag, Type&>(value.get()); } }; # define SIV3D_NAMED_PARAMETER(name) \ constexpr auto name = NamedParameterHelper<struct name##_tag>{};\ template <class Type> using name##_ = NamedParameterHelper<struct name##_tag>::named_argument_type<Type> } namespace s3d { namespace Arg { SIV3D_NAMED_PARAMETER(generator); SIV3D_NAMED_PARAMETER(generator0_1); SIV3D_NAMED_PARAMETER(radix); SIV3D_NAMED_PARAMETER(upperCase); SIV3D_NAMED_PARAMETER(r); SIV3D_NAMED_PARAMETER(theta); SIV3D_NAMED_PARAMETER(phi); SIV3D_NAMED_PARAMETER(y); SIV3D_NAMED_PARAMETER(center); SIV3D_NAMED_PARAMETER(topLeft); SIV3D_NAMED_PARAMETER(topRight); SIV3D_NAMED_PARAMETER(bottomLeft); SIV3D_NAMED_PARAMETER(bottomRight); SIV3D_NAMED_PARAMETER(left); SIV3D_NAMED_PARAMETER(right); SIV3D_NAMED_PARAMETER(top); SIV3D_NAMED_PARAMETER(bottom); SIV3D_NAMED_PARAMETER(topCenter); SIV3D_NAMED_PARAMETER(bottomCenter); SIV3D_NAMED_PARAMETER(leftCenter); SIV3D_NAMED_PARAMETER(rightCenter); SIV3D_NAMED_PARAMETER(source); SIV3D_NAMED_PARAMETER(loop); SIV3D_NAMED_PARAMETER(loopBegin); SIV3D_NAMED_PARAMETER(loopEnd); SIV3D_NAMED_PARAMETER(code); SIV3D_NAMED_PARAMETER(samplingRate); } } <commit_msg>fix #297<commit_after>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2018 Ryo Suzuki // Copyright (c) 2016-2018 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <type_traits> # include <tuple> namespace s3d { template <class Tag, class Type> class NamedParameter { private: Type m_value; public: constexpr NamedParameter() : m_value() {} explicit constexpr NamedParameter(Type value) : m_value(value) {} template <class U, class V = Type, std::enable_if_t<std::is_convertible_v<U, V>>* = nullptr> constexpr NamedParameter(const NamedParameter<Tag, U>& other) : m_value(other.value()) {} template <class... Args, class V = Type, std::enable_if_t<std::is_constructible_v<V, Args...>>* = nullptr> constexpr NamedParameter(const NamedParameter<Tag, std::tuple<Args...>>& tuple) : m_value(std::make_from_tuple<Type>(tuple.value())) {} constexpr const Type* operator ->() const { return std::addressof(m_value); } [[nodiscard]] constexpr const Type& operator *() const { return m_value; } [[nodiscard]] constexpr const Type& value() const { return m_value; } }; template <class Tag, class Type> class NamedParameter<Tag, Type&> { private: Type* m_ref; public: constexpr NamedParameter() noexcept : m_ref(nullptr) {} constexpr NamedParameter(Type& value) noexcept : m_ref(std::addressof(value)) {} constexpr Type* operator ->() const { return m_ref; } [[nodiscard]] constexpr Type& operator *() const { return *m_ref; } [[nodiscard]] constexpr Type& value() const { return *m_ref; } }; template <class Tag> struct NamedParameterHelper { template <class Type> using named_argument_type = NamedParameter<Tag, Type>; template <class Type> constexpr NamedParameter<Tag, std::decay_t<Type>> operator= (Type&& value) const { return NamedParameter<Tag, std::decay_t<Type>>(std::forward<Type>(value)); } template <class... Args> constexpr NamedParameter<Tag, std::tuple<Args...>> operator() (const Args&... args) const { return NamedParameter<Tag, std::tuple<Args...>>(std::make_tuple(args...)); } template <class Type> constexpr NamedParameter<Tag, Type&> operator= (std::reference_wrapper<Type> value) const { return NamedParameter<Tag, Type&>(value.get()); } template <class Type> constexpr NamedParameter<Tag, Type&> operator() (std::reference_wrapper<Type> value) const { return NamedParameter<Tag, Type&>(value.get()); } }; # define SIV3D_NAMED_PARAMETER(name) \ constexpr auto name = NamedParameterHelper<struct name##_tag>{};\ template <class Type> using name##_ = typename NamedParameterHelper<struct name##_tag>::template named_argument_type<Type> } namespace s3d { namespace Arg { SIV3D_NAMED_PARAMETER(generator); SIV3D_NAMED_PARAMETER(generator0_1); SIV3D_NAMED_PARAMETER(radix); SIV3D_NAMED_PARAMETER(upperCase); SIV3D_NAMED_PARAMETER(r); SIV3D_NAMED_PARAMETER(theta); SIV3D_NAMED_PARAMETER(phi); SIV3D_NAMED_PARAMETER(y); SIV3D_NAMED_PARAMETER(center); SIV3D_NAMED_PARAMETER(topLeft); SIV3D_NAMED_PARAMETER(topRight); SIV3D_NAMED_PARAMETER(bottomLeft); SIV3D_NAMED_PARAMETER(bottomRight); SIV3D_NAMED_PARAMETER(left); SIV3D_NAMED_PARAMETER(right); SIV3D_NAMED_PARAMETER(top); SIV3D_NAMED_PARAMETER(bottom); SIV3D_NAMED_PARAMETER(topCenter); SIV3D_NAMED_PARAMETER(bottomCenter); SIV3D_NAMED_PARAMETER(leftCenter); SIV3D_NAMED_PARAMETER(rightCenter); SIV3D_NAMED_PARAMETER(source); SIV3D_NAMED_PARAMETER(loop); SIV3D_NAMED_PARAMETER(loopBegin); SIV3D_NAMED_PARAMETER(loopEnd); SIV3D_NAMED_PARAMETER(code); SIV3D_NAMED_PARAMETER(samplingRate); } } <|endoftext|>
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved. #include "rdb_protocol/terms/terms.hpp" #include "rdb_protocol/error.hpp" #include "rdb_protocol/op.hpp" namespace ql { template<int (*const F)(int)> const char *case_name(); template<> const char *case_name<::toupper>() { return "upcase"; } template<> const char *case_name<::tolower>() { return "downcase"; } template<int (*const F)(int)> class case_term_t : public op_term_t { public: case_term_t(compile_env_t *env, const protob_t<const Term> &term) : op_term_t(env, term, argspec_t(1)) { } private: virtual counted_t<val_t> eval_impl(scope_env_t *env, UNUSED eval_flags_t flags) { debugf("%s\n", name()); std::string s = arg(env, 0)->as_str(); std::transform(s.begin(), s.end(), s.begin(), F); return new_val(make_counted<const datum_t>(std::move(s))); } virtual const char *name() const { return case_name<F>(); } }; counted_t<term_t> make_upcase_term(compile_env_t *env, const protob_t<const Term> &term) { return make_counted<case_term_t<::toupper> >(env, term); } counted_t<term_t> make_downcase_term(compile_env_t *env, const protob_t<const Term> &term) { return make_counted<case_term_t<::tolower> >(env, term); } } <commit_msg>switched to using templates<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved. #include "rdb_protocol/terms/terms.hpp" #include "rdb_protocol/error.hpp" #include "rdb_protocol/op.hpp" namespace ql { template<int (*const F)(int)> const char *case_name(); template<> const char *case_name<::toupper>() { return "upcase"; } template<> const char *case_name<::tolower>() { return "downcase"; } template<int (*const F)(int)> class case_term_t : public op_term_t { public: case_term_t(compile_env_t *env, const protob_t<const Term> &term) : op_term_t(env, term, argspec_t(1)) { } private: virtual counted_t<val_t> eval_impl(scope_env_t *env, UNUSED eval_flags_t flags) { std::string s = arg(env, 0)->as_str(); std::transform(s.begin(), s.end(), s.begin(), F); return new_val(make_counted<const datum_t>(std::move(s))); } virtual const char *name() const { return case_name<F>(); } }; counted_t<term_t> make_upcase_term(compile_env_t *env, const protob_t<const Term> &term) { return make_counted<case_term_t<::toupper> >(env, term); } counted_t<term_t> make_downcase_term(compile_env_t *env, const protob_t<const Term> &term) { return make_counted<case_term_t<::tolower> >(env, term); } } <|endoftext|>
<commit_before>/** * OpenAL cross platform audio library * Copyright (C) 2018 by Raul Herraiz. * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * Or go to http://www.gnu.org/copyleft/lgpl.html */ #include "config.h" #include <cmath> #include <cstdlib> #include <array> #include <complex> #include <algorithm> #include "al/auxeffectslot.h" #include "alcmain.h" #include "alcontext.h" #include "alu.h" #include "alcomplex.h" namespace { using complex_d = std::complex<double>; #define HIL_SIZE 1024 #define OVERSAMP (1<<2) #define HIL_STEP (HIL_SIZE / OVERSAMP) #define FIFO_LATENCY (HIL_STEP * (OVERSAMP-1)) /* Define a Hann window, used to filter the HIL input and output. */ /* Making this constexpr seems to require C++14. */ std::array<ALdouble,HIL_SIZE> InitHannWindow() { std::array<ALdouble,HIL_SIZE> ret; /* Create lookup table of the Hann window for the desired size, i.e. HIL_SIZE */ for(ALsizei i{0};i < HIL_SIZE>>1;i++) { ALdouble val = std::sin(al::MathDefs<double>::Pi() * i / ALdouble{HIL_SIZE-1}); ret[i] = ret[HIL_SIZE-1-i] = val * val; } return ret; } alignas(16) const std::array<ALdouble,HIL_SIZE> HannWindow = InitHannWindow(); struct FshifterState final : public EffectState { /* Effect parameters */ ALsizei mCount{}; ALsizei mPhaseStep[2]{}; ALsizei mPhase[2]{}; ALdouble mSign[2]{}; /*Effects buffers*/ ALfloat mInFIFO[HIL_SIZE]{}; complex_d mOutFIFO[HIL_SIZE]{}; complex_d mOutputAccum[HIL_SIZE]{}; complex_d mAnalytic[HIL_SIZE]{}; complex_d mOutdata[BUFFERSIZE]{}; alignas(16) ALfloat mBufferOut[BUFFERSIZE]{}; /* Effect gains for each output channel */ struct { ALfloat Current[MAX_OUTPUT_CHANNELS]{}; ALfloat Target[MAX_OUTPUT_CHANNELS]{}; }mGains[2]; ALboolean deviceUpdate(const ALCdevice *device) override; void update(const ALCcontext *context, const ALeffectslot *slot, const EffectProps *props, const EffectTarget target) override; void process(const ALsizei samplesToDo, const FloatBufferLine *RESTRICT samplesIn, const ALsizei numInput, const al::span<FloatBufferLine> samplesOut) override; DEF_NEWDEL(FshifterState) }; ALboolean FshifterState::deviceUpdate(const ALCdevice*) { /* (Re-)initializing parameters and clear the buffers. */ mCount = FIFO_LATENCY; std::fill(std::begin(mPhaseStep), std::end(mPhaseStep), 0); std::fill(std::begin(mPhase), std::end(mPhase), 0); std::fill(std::begin(mSign), std::end(mSign), 1.0); std::fill(std::begin(mInFIFO), std::end(mInFIFO), 0.0f); std::fill(std::begin(mOutFIFO), std::end(mOutFIFO), complex_d{}); std::fill(std::begin(mOutputAccum), std::end(mOutputAccum), complex_d{}); std::fill(std::begin(mAnalytic), std::end(mAnalytic), complex_d{}); for (auto &gain : mGains) { std::fill(std::begin(gain.Current), std::end(gain.Current), 0.0f); std::fill(std::begin(gain.Target), std::end(gain.Target), 0.0f); } return AL_TRUE; } void FshifterState::update(const ALCcontext *context, const ALeffectslot *slot, const EffectProps *props, const EffectTarget target) { const ALCdevice *device{context->mDevice.get()}; ALfloat step{props->Fshifter.Frequency / static_cast<ALfloat>(device->Frequency)}; mPhaseStep[0] = mPhaseStep[1] = fastf2i(minf(step, 0.5f) * FRACTIONONE); switch(props->Fshifter.LeftDirection) { case AL_FREQUENCY_SHIFTER_DIRECTION_DOWN: mSign[0] = -1.0; break; case AL_FREQUENCY_SHIFTER_DIRECTION_UP: mSign[0] = 1.0; break; case AL_FREQUENCY_SHIFTER_DIRECTION_OFF: mPhase[0] = 0; mPhaseStep[0] = 0; break; } switch (props->Fshifter.RightDirection) { case AL_FREQUENCY_SHIFTER_DIRECTION_DOWN: mSign[1] = -1.0; break; case AL_FREQUENCY_SHIFTER_DIRECTION_UP: mSign[1] = 1.0; break; case AL_FREQUENCY_SHIFTER_DIRECTION_OFF: mPhase[1] = 0; mPhaseStep[1] = 0; break; } ALfloat coeffs[2][MAX_AMBI_CHANNELS]; CalcDirectionCoeffs({-1.0f, 0.0f, -1.0f}, 0.0f, coeffs[0]); CalcDirectionCoeffs({1.0f, 0.0f, -1.0f }, 0.0f, coeffs[1]); mOutTarget = target.Main->Buffer; ComputePanGains(target.Main, coeffs[0], slot->Params.Gain, mGains[0].Target); ComputePanGains(target.Main, coeffs[1], slot->Params.Gain, mGains[1].Target); } void FshifterState::process(const ALsizei samplesToDo, const FloatBufferLine *RESTRICT samplesIn, const ALsizei /*numInput*/, const al::span<FloatBufferLine> samplesOut) { static constexpr complex_d complex_zero{0.0, 0.0}; ALfloat *RESTRICT BufferOut = mBufferOut; ALsizei j, k, base; for(base = 0;base < samplesToDo;) { const ALsizei todo{mini(HIL_SIZE-mCount, samplesToDo-base)}; ASSUME(todo > 0); /* Fill FIFO buffer with samples data */ k = mCount; for(j = 0;j < todo;j++,k++) { mInFIFO[k] = samplesIn[0][base+j]; mOutdata[base+j] = mOutFIFO[k-FIFO_LATENCY]; } mCount += todo; base += todo; /* Check whether FIFO buffer is filled */ if(mCount < HIL_SIZE) continue; mCount = FIFO_LATENCY; /* Real signal windowing and store in Analytic buffer */ for(k = 0;k < HIL_SIZE;k++) { mAnalytic[k].real(mInFIFO[k] * HannWindow[k]); mAnalytic[k].imag(0.0); } /* Processing signal by Discrete Hilbert Transform (analytical signal). */ complex_hilbert(mAnalytic); /* Windowing and add to output accumulator */ for(k = 0;k < HIL_SIZE;k++) mOutputAccum[k] += 2.0/OVERSAMP*HannWindow[k]*mAnalytic[k]; /* Shift accumulator, input & output FIFO */ for(k = 0;k < HIL_STEP;k++) mOutFIFO[k] = mOutputAccum[k]; for(j = 0;k < HIL_SIZE;k++,j++) mOutputAccum[j] = mOutputAccum[k]; for(;j < HIL_SIZE;j++) mOutputAccum[j] = complex_zero; for(k = 0;k < FIFO_LATENCY;k++) mInFIFO[k] = mInFIFO[k+HIL_STEP]; } /* Process frequency shifter using the analytic signal obtained. */ for (ALsizei c{0}; c < 2; c++) { for (k = 0; k < samplesToDo; k++) { double phase = mPhase[c] * ((1.0 / FRACTIONONE) * al::MathDefs<double>::Tau()); BufferOut[k] = static_cast<float>(mOutdata[k].real()*std::cos(phase) + mOutdata[k].imag()*std::sin(phase)*mSign[c]); mPhase[c] += mPhaseStep[c]; mPhase[c] &= FRACTIONMASK; } /* Now, mix the processed sound data to the output. */ MixSamples(BufferOut, samplesOut, mGains[c].Current, mGains[c].Target, maxi(samplesToDo, 512), 0, samplesToDo); } } void Fshifter_setParamf(EffectProps *props, ALCcontext *context, ALenum param, ALfloat val) { switch(param) { case AL_FREQUENCY_SHIFTER_FREQUENCY: if(!(val >= AL_FREQUENCY_SHIFTER_MIN_FREQUENCY && val <= AL_FREQUENCY_SHIFTER_MAX_FREQUENCY)) SETERR_RETURN(context, AL_INVALID_VALUE,,"Frequency shifter frequency out of range"); props->Fshifter.Frequency = val; break; default: context->setError(AL_INVALID_ENUM, "Invalid frequency shifter float property 0x%04x", param); } } void Fshifter_setParamfv(EffectProps *props, ALCcontext *context, ALenum param, const ALfloat *vals) { Fshifter_setParamf(props, context, param, vals[0]); } void Fshifter_setParami(EffectProps *props, ALCcontext *context, ALenum param, ALint val) { switch(param) { case AL_FREQUENCY_SHIFTER_LEFT_DIRECTION: if(!(val >= AL_FREQUENCY_SHIFTER_MIN_LEFT_DIRECTION && val <= AL_FREQUENCY_SHIFTER_MAX_LEFT_DIRECTION)) SETERR_RETURN(context, AL_INVALID_VALUE,,"Frequency shifter left direction out of range"); props->Fshifter.LeftDirection = val; break; case AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION: if(!(val >= AL_FREQUENCY_SHIFTER_MIN_RIGHT_DIRECTION && val <= AL_FREQUENCY_SHIFTER_MAX_RIGHT_DIRECTION)) SETERR_RETURN(context, AL_INVALID_VALUE,,"Frequency shifter right direction out of range"); props->Fshifter.RightDirection = val; break; default: context->setError(AL_INVALID_ENUM, "Invalid frequency shifter integer property 0x%04x", param); } } void Fshifter_setParamiv(EffectProps *props, ALCcontext *context, ALenum param, const ALint *vals) { Fshifter_setParami(props, context, param, vals[0]); } void Fshifter_getParami(const EffectProps *props, ALCcontext *context, ALenum param, ALint *val) { switch(param) { case AL_FREQUENCY_SHIFTER_LEFT_DIRECTION: *val = props->Fshifter.LeftDirection; break; case AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION: *val = props->Fshifter.RightDirection; break; default: context->setError(AL_INVALID_ENUM, "Invalid frequency shifter integer property 0x%04x", param); } } void Fshifter_getParamiv(const EffectProps *props, ALCcontext *context, ALenum param, ALint *vals) { Fshifter_getParami(props, context, param, vals); } void Fshifter_getParamf(const EffectProps *props, ALCcontext *context, ALenum param, ALfloat *val) { switch(param) { case AL_FREQUENCY_SHIFTER_FREQUENCY: *val = props->Fshifter.Frequency; break; default: context->setError(AL_INVALID_ENUM, "Invalid frequency shifter float property 0x%04x", param); } } void Fshifter_getParamfv(const EffectProps *props, ALCcontext *context, ALenum param, ALfloat *vals) { Fshifter_getParamf(props, context, param, vals); } DEFINE_ALEFFECT_VTABLE(Fshifter); struct FshifterStateFactory final : public EffectStateFactory { EffectState *create() override { return new FshifterState{}; } EffectProps getDefaultProps() const noexcept override; const EffectVtable *getEffectVtable() const noexcept override { return &Fshifter_vtable; } }; EffectProps FshifterStateFactory::getDefaultProps() const noexcept { EffectProps props{}; props.Fshifter.Frequency = AL_FREQUENCY_SHIFTER_DEFAULT_FREQUENCY; props.Fshifter.LeftDirection = AL_FREQUENCY_SHIFTER_DEFAULT_LEFT_DIRECTION; props.Fshifter.RightDirection = AL_FREQUENCY_SHIFTER_DEFAULT_RIGHT_DIRECTION; return props; } } // namespace EffectStateFactory *FshifterStateFactory_getFactory() { static FshifterStateFactory FshifterFactory{}; return &FshifterFactory; } <commit_msg>Formatting cleanup<commit_after>/** * OpenAL cross platform audio library * Copyright (C) 2018 by Raul Herraiz. * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * Or go to http://www.gnu.org/copyleft/lgpl.html */ #include "config.h" #include <cmath> #include <cstdlib> #include <array> #include <complex> #include <algorithm> #include "al/auxeffectslot.h" #include "alcmain.h" #include "alcontext.h" #include "alu.h" #include "alcomplex.h" namespace { using complex_d = std::complex<double>; #define HIL_SIZE 1024 #define OVERSAMP (1<<2) #define HIL_STEP (HIL_SIZE / OVERSAMP) #define FIFO_LATENCY (HIL_STEP * (OVERSAMP-1)) /* Define a Hann window, used to filter the HIL input and output. */ /* Making this constexpr seems to require C++14. */ std::array<ALdouble,HIL_SIZE> InitHannWindow() { std::array<ALdouble,HIL_SIZE> ret; /* Create lookup table of the Hann window for the desired size, i.e. HIL_SIZE */ for(ALsizei i{0};i < HIL_SIZE>>1;i++) { ALdouble val = std::sin(al::MathDefs<double>::Pi() * i / ALdouble{HIL_SIZE-1}); ret[i] = ret[HIL_SIZE-1-i] = val * val; } return ret; } alignas(16) const std::array<ALdouble,HIL_SIZE> HannWindow = InitHannWindow(); struct FshifterState final : public EffectState { /* Effect parameters */ ALsizei mCount{}; ALsizei mPhaseStep[2]{}; ALsizei mPhase[2]{}; ALdouble mSign[2]{}; /*Effects buffers*/ ALfloat mInFIFO[HIL_SIZE]{}; complex_d mOutFIFO[HIL_SIZE]{}; complex_d mOutputAccum[HIL_SIZE]{}; complex_d mAnalytic[HIL_SIZE]{}; complex_d mOutdata[BUFFERSIZE]{}; alignas(16) ALfloat mBufferOut[BUFFERSIZE]{}; /* Effect gains for each output channel */ struct { ALfloat Current[MAX_OUTPUT_CHANNELS]{}; ALfloat Target[MAX_OUTPUT_CHANNELS]{}; } mGains[2]; ALboolean deviceUpdate(const ALCdevice *device) override; void update(const ALCcontext *context, const ALeffectslot *slot, const EffectProps *props, const EffectTarget target) override; void process(const ALsizei samplesToDo, const FloatBufferLine *RESTRICT samplesIn, const ALsizei numInput, const al::span<FloatBufferLine> samplesOut) override; DEF_NEWDEL(FshifterState) }; ALboolean FshifterState::deviceUpdate(const ALCdevice*) { /* (Re-)initializing parameters and clear the buffers. */ mCount = FIFO_LATENCY; std::fill(std::begin(mPhaseStep), std::end(mPhaseStep), 0); std::fill(std::begin(mPhase), std::end(mPhase), 0); std::fill(std::begin(mSign), std::end(mSign), 1.0); std::fill(std::begin(mInFIFO), std::end(mInFIFO), 0.0f); std::fill(std::begin(mOutFIFO), std::end(mOutFIFO), complex_d{}); std::fill(std::begin(mOutputAccum), std::end(mOutputAccum), complex_d{}); std::fill(std::begin(mAnalytic), std::end(mAnalytic), complex_d{}); for(auto &gain : mGains) { std::fill(std::begin(gain.Current), std::end(gain.Current), 0.0f); std::fill(std::begin(gain.Target), std::end(gain.Target), 0.0f); } return AL_TRUE; } void FshifterState::update(const ALCcontext *context, const ALeffectslot *slot, const EffectProps *props, const EffectTarget target) { const ALCdevice *device{context->mDevice.get()}; ALfloat step{props->Fshifter.Frequency / static_cast<ALfloat>(device->Frequency)}; mPhaseStep[0] = mPhaseStep[1] = fastf2i(minf(step, 0.5f) * FRACTIONONE); switch(props->Fshifter.LeftDirection) { case AL_FREQUENCY_SHIFTER_DIRECTION_DOWN: mSign[0] = -1.0; break; case AL_FREQUENCY_SHIFTER_DIRECTION_UP: mSign[0] = 1.0; break; case AL_FREQUENCY_SHIFTER_DIRECTION_OFF: mPhase[0] = 0; mPhaseStep[0] = 0; break; } switch (props->Fshifter.RightDirection) { case AL_FREQUENCY_SHIFTER_DIRECTION_DOWN: mSign[1] = -1.0; break; case AL_FREQUENCY_SHIFTER_DIRECTION_UP: mSign[1] = 1.0; break; case AL_FREQUENCY_SHIFTER_DIRECTION_OFF: mPhase[1] = 0; mPhaseStep[1] = 0; break; } ALfloat coeffs[2][MAX_AMBI_CHANNELS]; CalcDirectionCoeffs({-1.0f, 0.0f, -1.0f}, 0.0f, coeffs[0]); CalcDirectionCoeffs({ 1.0f, 0.0f, -1.0f}, 0.0f, coeffs[1]); mOutTarget = target.Main->Buffer; ComputePanGains(target.Main, coeffs[0], slot->Params.Gain, mGains[0].Target); ComputePanGains(target.Main, coeffs[1], slot->Params.Gain, mGains[1].Target); } void FshifterState::process(const ALsizei samplesToDo, const FloatBufferLine *RESTRICT samplesIn, const ALsizei /*numInput*/, const al::span<FloatBufferLine> samplesOut) { static constexpr complex_d complex_zero{0.0, 0.0}; ALfloat *RESTRICT BufferOut = mBufferOut; ALsizei j, k, base; for(base = 0;base < samplesToDo;) { const ALsizei todo{mini(HIL_SIZE-mCount, samplesToDo-base)}; ASSUME(todo > 0); /* Fill FIFO buffer with samples data */ k = mCount; for(j = 0;j < todo;j++,k++) { mInFIFO[k] = samplesIn[0][base+j]; mOutdata[base+j] = mOutFIFO[k-FIFO_LATENCY]; } mCount += todo; base += todo; /* Check whether FIFO buffer is filled */ if(mCount < HIL_SIZE) continue; mCount = FIFO_LATENCY; /* Real signal windowing and store in Analytic buffer */ for(k = 0;k < HIL_SIZE;k++) { mAnalytic[k].real(mInFIFO[k] * HannWindow[k]); mAnalytic[k].imag(0.0); } /* Processing signal by Discrete Hilbert Transform (analytical signal). */ complex_hilbert(mAnalytic); /* Windowing and add to output accumulator */ for(k = 0;k < HIL_SIZE;k++) mOutputAccum[k] += 2.0/OVERSAMP*HannWindow[k]*mAnalytic[k]; /* Shift accumulator, input & output FIFO */ for(k = 0;k < HIL_STEP;k++) mOutFIFO[k] = mOutputAccum[k]; for(j = 0;k < HIL_SIZE;k++,j++) mOutputAccum[j] = mOutputAccum[k]; for(;j < HIL_SIZE;j++) mOutputAccum[j] = complex_zero; for(k = 0;k < FIFO_LATENCY;k++) mInFIFO[k] = mInFIFO[k+HIL_STEP]; } /* Process frequency shifter using the analytic signal obtained. */ for(ALsizei c{0};c < 2;++c) { for(k = 0;k < samplesToDo;++k) { double phase = mPhase[c] * ((1.0 / FRACTIONONE) * al::MathDefs<double>::Tau()); BufferOut[k] = static_cast<float>(mOutdata[k].real()*std::cos(phase) + mOutdata[k].imag()*std::sin(phase)*mSign[c]); mPhase[c] += mPhaseStep[c]; mPhase[c] &= FRACTIONMASK; } /* Now, mix the processed sound data to the output. */ MixSamples(BufferOut, samplesOut, mGains[c].Current, mGains[c].Target, maxi(samplesToDo, 512), 0, samplesToDo); } } void Fshifter_setParamf(EffectProps *props, ALCcontext *context, ALenum param, ALfloat val) { switch(param) { case AL_FREQUENCY_SHIFTER_FREQUENCY: if(!(val >= AL_FREQUENCY_SHIFTER_MIN_FREQUENCY && val <= AL_FREQUENCY_SHIFTER_MAX_FREQUENCY)) SETERR_RETURN(context, AL_INVALID_VALUE,,"Frequency shifter frequency out of range"); props->Fshifter.Frequency = val; break; default: context->setError(AL_INVALID_ENUM, "Invalid frequency shifter float property 0x%04x", param); } } void Fshifter_setParamfv(EffectProps *props, ALCcontext *context, ALenum param, const ALfloat *vals) { Fshifter_setParamf(props, context, param, vals[0]); } void Fshifter_setParami(EffectProps *props, ALCcontext *context, ALenum param, ALint val) { switch(param) { case AL_FREQUENCY_SHIFTER_LEFT_DIRECTION: if(!(val >= AL_FREQUENCY_SHIFTER_MIN_LEFT_DIRECTION && val <= AL_FREQUENCY_SHIFTER_MAX_LEFT_DIRECTION)) SETERR_RETURN(context, AL_INVALID_VALUE,,"Frequency shifter left direction out of range"); props->Fshifter.LeftDirection = val; break; case AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION: if(!(val >= AL_FREQUENCY_SHIFTER_MIN_RIGHT_DIRECTION && val <= AL_FREQUENCY_SHIFTER_MAX_RIGHT_DIRECTION)) SETERR_RETURN(context, AL_INVALID_VALUE,,"Frequency shifter right direction out of range"); props->Fshifter.RightDirection = val; break; default: context->setError(AL_INVALID_ENUM, "Invalid frequency shifter integer property 0x%04x", param); } } void Fshifter_setParamiv(EffectProps *props, ALCcontext *context, ALenum param, const ALint *vals) { Fshifter_setParami(props, context, param, vals[0]); } void Fshifter_getParami(const EffectProps *props, ALCcontext *context, ALenum param, ALint *val) { switch(param) { case AL_FREQUENCY_SHIFTER_LEFT_DIRECTION: *val = props->Fshifter.LeftDirection; break; case AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION: *val = props->Fshifter.RightDirection; break; default: context->setError(AL_INVALID_ENUM, "Invalid frequency shifter integer property 0x%04x", param); } } void Fshifter_getParamiv(const EffectProps *props, ALCcontext *context, ALenum param, ALint *vals) { Fshifter_getParami(props, context, param, vals); } void Fshifter_getParamf(const EffectProps *props, ALCcontext *context, ALenum param, ALfloat *val) { switch(param) { case AL_FREQUENCY_SHIFTER_FREQUENCY: *val = props->Fshifter.Frequency; break; default: context->setError(AL_INVALID_ENUM, "Invalid frequency shifter float property 0x%04x", param); } } void Fshifter_getParamfv(const EffectProps *props, ALCcontext *context, ALenum param, ALfloat *vals) { Fshifter_getParamf(props, context, param, vals); } DEFINE_ALEFFECT_VTABLE(Fshifter); struct FshifterStateFactory final : public EffectStateFactory { EffectState *create() override { return new FshifterState{}; } EffectProps getDefaultProps() const noexcept override; const EffectVtable *getEffectVtable() const noexcept override { return &Fshifter_vtable; } }; EffectProps FshifterStateFactory::getDefaultProps() const noexcept { EffectProps props{}; props.Fshifter.Frequency = AL_FREQUENCY_SHIFTER_DEFAULT_FREQUENCY; props.Fshifter.LeftDirection = AL_FREQUENCY_SHIFTER_DEFAULT_LEFT_DIRECTION; props.Fshifter.RightDirection = AL_FREQUENCY_SHIFTER_DEFAULT_RIGHT_DIRECTION; return props; } } // namespace EffectStateFactory *FshifterStateFactory_getFactory() { static FshifterStateFactory FshifterFactory{}; return &FshifterFactory; } <|endoftext|>
<commit_before>/* * VRJuggler * Copyright (C) 1997,1998,1999,2000 * Iowa State University Research Foundation, Inc. * All Rights Reserved * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- */ #include <vjConfig.h> #include <Kernel/GL/vjGlPipe.h> #include <Kernel/GL/vjGlApp.h> #include <Threads/vjThread.h> #include <Sync/vjGuard.h> #include <Kernel/vjDebug.h> #include <Kernel/vjSurfaceDisplay.h> #include <Kernel/vjSimDisplay.h> //**//#include <Environment/vjEnvironmentManager.h> #include <GL/gl.h> //: Start the pipe running //! POST: The pipe has it's own thread of control and is ready to operate int vjGlPipe::start() { vjASSERT(mThreadRunning == false); // We should not be running yet // Create a new thread to handle the control loop vjThreadMemberFunctor<vjGlPipe>* memberFunctor = new vjThreadMemberFunctor<vjGlPipe>(this, &vjGlPipe::controlLoop, NULL); mActiveThread = new vjThread(memberFunctor, 0); vjDEBUG(vjDBG_DRAW_MGR,1) << "vjGlPipe::start: Started control loop. " << mActiveThread << endl << vjDEBUG_FLUSH; return 1; } //: Trigger rendering of the pipe to start //! POST: The pipe has be told to start rendering void vjGlPipe::triggerRender() { //vjASSERT(mThreadRunning == true); // We must be running while(!mThreadRunning) { vjDEBUG(vjDBG_DRAW_MGR,3) << "Waiting in for thread to start triggerRender.\n" << vjDEBUG_FLUSH; } renderTriggerSema.release(); } //: Blocks until rendering of the windows is completed //! POST: The pipe has completed its rendering void vjGlPipe::completeRender() { vjASSERT(mThreadRunning == true); // We must be running renderCompleteSema.acquire(); } //: Trigger swapping of all pipe's windows void vjGlPipe::triggerSwap() { vjASSERT(mThreadRunning == true); swapTriggerSema.release(); } //: Blocks until swapping of the windows is completed void vjGlPipe::completeSwap() { vjASSERT(mThreadRunning == true); swapCompleteSema.acquire(); } /// Add a GLWindow to the window list // Control loop must now open the window on the next frame void vjGlPipe::addWindow(vjGlWindow* win) { vjGuard<vjMutex> guardNew(newWinLock); // Protect the data vjDEBUG(vjDBG_DRAW_MGR,3) << "vjGlPipe::addWindow: Pipe: " << mPipeNum << " adding window (to new wins):\n" << win << endl << vjDEBUG_FLUSH; newWins.push_back(win); } //: Remove a GLWindow from the window list //! NOTE: The window is not actually removed until the next draw trigger void vjGlPipe::removeWindow(vjGlWindow* win) { vjGuard<vjMutex> guardClosing(mClosingWinLock); vjDEBUG(vjDBG_DRAW_MGR,3) << "vjGlPipe:: removeWindow: Pipe: " << mPipeNum << " window added to closingWins.\n" << win << endl << vjDEBUG_FLUSH; mClosingWins.push_back(win); } // The main loop routine // while running <br> // - Check for windows to open/close <br> // - Wait for render signal <br> // - Render all the windows <br> // - Signal render completed <br> // - Wait for swap signal <br> // - Swap all windows <br> // - Signal swap completed <br> // void vjGlPipe::controlLoop(void* nullParam) { mThreadRunning = true; // We are running so set flag // this should really not be here... //**// vjKernel::instance()->getEnvironmentManager()->addPerfDataBuffer (mPerfBuffer); while (!controlExit) { checkForWindowsToClose(); // Checks for closing windows checkForNewWindows(); // Checks for new windows to open // --- handle EVENTS for the windows --- // // XXX: This may have to be here because of need to get open window event (Win32) // otherwise I would like to move it to being after the swap to get better performance { for(unsigned int winId=0;winId<openWins.size();winId++) openWins[winId]->checkEvents(); } // --- RENDER the windows ---- // { renderTriggerSema.acquire(); vjGlApp* theApp = glManager->getApp(); mPerfBuffer->set(mPerfPhase = 0); // --- pipe PRE-draw function ---- // theApp->pipePreDraw(); // Can't get a context since I may not be guaranteed a window mPerfBuffer->set(++mPerfPhase); // Render the windows for (unsigned int winId=0;winId < openWins.size();winId++) renderWindow(openWins[winId]); renderCompleteSema.release(); mPerfBuffer->set(35); } // ----- SWAP the windows ------ // { swapTriggerSema.acquire(); // Swap all the windows for(unsigned int winId=0;winId < openWins.size();winId++) swapWindowBuffers(openWins[winId]); swapCompleteSema.release(); } } mThreadRunning = false; // We are not running } // Closes all the windows in the list of windows to close //! POST: The window to close is removed from the list of open windows //+ and the list of newWins void vjGlPipe::checkForWindowsToClose() { if(mClosingWins.size() > 0) // If there are windows to close { vjGuard<vjMutex> guardClosing(mClosingWinLock); vjGuard<vjMutex> guardNew(newWinLock); vjGuard<vjMutex> guardOpen(openWinLock); for(unsigned int i=0;i<mClosingWins.size();i++) { vjGlWindow* win = mClosingWins[i]; // Call contextClose vjGlApp* theApp = glManager->getApp(); // Get application for easy access vjDisplay* theDisplay = win->getDisplay(); // Get the display for easy access glManager->setCurrentContext(win->getId()); // Set TS data of context id glManager->currentUserData()->setUser(theDisplay->getUser()); // Set user data glManager->currentUserData()->setProjection(NULL); win->makeCurrent(); // Make the context current theApp->contextClose(); // Call context close function // Close the window win->close(); // Remove it from the lists newWins.erase(std::remove(newWins.begin(), newWins.end(), win), newWins.end()); openWins.erase(std::remove(openWins.begin(), openWins.end(), win), openWins.end()); // Delete the window delete win; mClosingWins[i] = NULL; } mClosingWins.erase(mClosingWins.begin(), mClosingWins.end()); vjASSERT(mClosingWins.size() == 0);; } } //: Checks for any new windows to add to the pipe //! POST: Any new windows will be opened and added to the pipe's rendering list void vjGlPipe::checkForNewWindows() { if (newWins.size() > 0) // If there are new windows added { vjGuard<vjMutex> guardNew(newWinLock); vjGuard<vjMutex> guardOpen(openWinLock); for (unsigned int winNum=0; winNum<newWins.size(); winNum++) { newWins[winNum]->open(); newWins[winNum]->makeCurrent(); vjDEBUG(vjDBG_DRAW_MGR,1) << "vjGlPipe::checkForNewWindows: Just opened window:\n" << newWins[winNum] << endl << vjDEBUG_FLUSH; openWins.push_back(newWins[winNum]); } newWins.erase(newWins.begin(), newWins.end()); vjASSERT(newWins.size() == 0); } } //: Renders the window using OpenGL //! POST: win is rendered (In stereo if it is a stereo window) void vjGlPipe::renderWindow(vjGlWindow* win) { vjGlApp* theApp = glManager->getApp(); // Get application for easy access vjDisplay* theDisplay = win->getDisplay(); // Get the display for easy access glManager->setCurrentContext(win->getId()); // Set TSS data of context id vjDEBUG(vjDBG_DRAW_MGR,5) << "vjGlPipe::renderWindow: Set context to: " << vjGlDrawManager::instance()->getCurrentContext() << endl << vjDEBUG_FLUSH; mPerfBuffer->set(++mPerfPhase); // --- SET CONTEXT --- // win->makeCurrent(); // CONTEXT INIT(): Check if we need to call contextInit() if(win->hasDirtyContext()) { // Have dirty context glManager->currentUserData()->setUser(theDisplay->getUser()); // Set user data glManager->currentUserData()->setProjection(NULL); theApp->contextInit(); // Call context init function win->setDirtyContext(false); // All clean now } mPerfBuffer->set(++mPerfPhase); theApp->contextPreDraw(); // Do any context pre-drawing mPerfBuffer->set(++mPerfPhase); // ---- SURFACE --- // if (theDisplay->isSurface()) { vjSurfaceDisplay* surface_disp = dynamic_cast<vjSurfaceDisplay*>(theDisplay); vjDisplay::DisplayView view = theDisplay->getView(); // Get the view we are rendering if((vjDisplay::STEREO == view) || (vjDisplay::LEFT_EYE == view)) { win->setLeftEyeProjection(); mPerfBuffer->set(++mPerfPhase); glManager->currentUserData()->setUser(surface_disp->getUser()); // Set user data glManager->currentUserData()->setProjection(surface_disp->getLeftProj()); mPerfBuffer->set(++mPerfPhase); theApp->draw(); mPerfBuffer->set(4); glManager->drawObjects(); mPerfBuffer->set(5); } if ((vjDisplay::STEREO == view) || (vjDisplay::RIGHT_EYE == theDisplay->getView())) { win->setRightEyeProjection(); glManager->currentUserData()->setUser(surface_disp->getUser()); // Set user data glManager->currentUserData()->setProjection(surface_disp->getRightProj()); mPerfBuffer->set(++mPerfPhase); theApp->draw(); mPerfBuffer->set(++mPerfPhase); glManager->drawObjects(); } else mPerfPhase += 2; } // ---- SIMULATOR ---------- // else if(theDisplay->isSimulator()) { vjSimDisplay* sim_disp = dynamic_cast<vjSimDisplay*>(theDisplay); win->setCameraProjection(); glManager->currentUserData()->setUser(sim_disp->getUser()); // Set user data glManager->currentUserData()->setProjection(sim_disp->getCameraProj()); mPerfBuffer->set(++mPerfPhase); theApp->draw(); mPerfBuffer->set(++mPerfPhase); mPerfPhase += 2; glManager->drawObjects(); glManager->drawSimulator(sim_disp); } } //: Swaps the buffers of the given window // Make the context current, and swap the window void vjGlPipe::swapWindowBuffers(vjGlWindow* win) { win->makeCurrent(); // Set correct context win->swapBuffers(); // Implicitly calls a glFlush //vjTimeStamp* stamp = win->getDisplay()->getUser()->getHeadUpdateTime(); //cout << "timestamp time is: " << stamp->usecs() << " usecs" << endl; } <commit_msg>tweaked performance measuring datapoints<commit_after>/* * VRJuggler * Copyright (C) 1997,1998,1999,2000 * Iowa State University Research Foundation, Inc. * All Rights Reserved * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- */ #include <vjConfig.h> #include <Kernel/GL/vjGlPipe.h> #include <Kernel/GL/vjGlApp.h> #include <Threads/vjThread.h> #include <Sync/vjGuard.h> #include <Kernel/vjDebug.h> #include <Kernel/vjSurfaceDisplay.h> #include <Kernel/vjSimDisplay.h> #include <Environment/vjEnvironmentManager.h> #include <GL/gl.h> //: Start the pipe running //! POST: The pipe has it's own thread of control and is ready to operate int vjGlPipe::start() { vjASSERT(mThreadRunning == false); // We should not be running yet // Create a new thread to handle the control loop vjThreadMemberFunctor<vjGlPipe>* memberFunctor = new vjThreadMemberFunctor<vjGlPipe>(this, &vjGlPipe::controlLoop, NULL); mActiveThread = new vjThread(memberFunctor, 0); vjDEBUG(vjDBG_DRAW_MGR,1) << "vjGlPipe::start: Started control loop. " << mActiveThread << endl << vjDEBUG_FLUSH; return 1; } //: Trigger rendering of the pipe to start //! POST: The pipe has be told to start rendering void vjGlPipe::triggerRender() { //vjASSERT(mThreadRunning == true); // We must be running while(!mThreadRunning) { vjDEBUG(vjDBG_DRAW_MGR,3) << "Waiting in for thread to start triggerRender.\n" << vjDEBUG_FLUSH; } renderTriggerSema.release(); } //: Blocks until rendering of the windows is completed //! POST: The pipe has completed its rendering void vjGlPipe::completeRender() { vjASSERT(mThreadRunning == true); // We must be running renderCompleteSema.acquire(); } //: Trigger swapping of all pipe's windows void vjGlPipe::triggerSwap() { vjASSERT(mThreadRunning == true); swapTriggerSema.release(); } //: Blocks until swapping of the windows is completed void vjGlPipe::completeSwap() { vjASSERT(mThreadRunning == true); swapCompleteSema.acquire(); } /// Add a GLWindow to the window list // Control loop must now open the window on the next frame void vjGlPipe::addWindow(vjGlWindow* win) { vjGuard<vjMutex> guardNew(newWinLock); // Protect the data vjDEBUG(vjDBG_DRAW_MGR,3) << "vjGlPipe::addWindow: Pipe: " << mPipeNum << " adding window (to new wins):\n" << win << endl << vjDEBUG_FLUSH; newWins.push_back(win); } //: Remove a GLWindow from the window list //! NOTE: The window is not actually removed until the next draw trigger void vjGlPipe::removeWindow(vjGlWindow* win) { vjGuard<vjMutex> guardClosing(mClosingWinLock); vjDEBUG(vjDBG_DRAW_MGR,3) << "vjGlPipe:: removeWindow: Pipe: " << mPipeNum << " window added to closingWins.\n" << win << endl << vjDEBUG_FLUSH; mClosingWins.push_back(win); } // The main loop routine // while running <br> // - Check for windows to open/close <br> // - Wait for render signal <br> // - Render all the windows <br> // - Signal render completed <br> // - Wait for swap signal <br> // - Swap all windows <br> // - Signal swap completed <br> // void vjGlPipe::controlLoop(void* nullParam) { mThreadRunning = true; // We are running so set flag // this should really not be here... vjKernel::instance()->getEnvironmentManager()->addPerfDataBuffer (mPerfBuffer); while (!controlExit) { checkForWindowsToClose(); // Checks for closing windows checkForNewWindows(); // Checks for new windows to open // --- handle EVENTS for the windows --- // // XXX: This may have to be here because of need to get open window event (Win32) // otherwise I would like to move it to being after the swap to get better performance { for(unsigned int winId=0;winId<openWins.size();winId++) openWins[winId]->checkEvents(); } // --- RENDER the windows ---- // { renderTriggerSema.acquire(); vjGlApp* theApp = glManager->getApp(); mPerfBuffer->set(mPerfPhase = 0); // --- pipe PRE-draw function ---- // theApp->pipePreDraw(); // Can't get a context since I may not be guaranteed a window mPerfBuffer->set(++mPerfPhase); // Render the windows for (unsigned int winId=0;winId < openWins.size();winId++) renderWindow(openWins[winId]); renderCompleteSema.release(); mPerfBuffer->set(35); } // ----- SWAP the windows ------ // { swapTriggerSema.acquire(); // Swap all the windows for(unsigned int winId=0;winId < openWins.size();winId++) swapWindowBuffers(openWins[winId]); swapCompleteSema.release(); } } mThreadRunning = false; // We are not running } // Closes all the windows in the list of windows to close //! POST: The window to close is removed from the list of open windows //+ and the list of newWins void vjGlPipe::checkForWindowsToClose() { if(mClosingWins.size() > 0) // If there are windows to close { vjGuard<vjMutex> guardClosing(mClosingWinLock); vjGuard<vjMutex> guardNew(newWinLock); vjGuard<vjMutex> guardOpen(openWinLock); for(unsigned int i=0;i<mClosingWins.size();i++) { vjGlWindow* win = mClosingWins[i]; // Call contextClose vjGlApp* theApp = glManager->getApp(); // Get application for easy access vjDisplay* theDisplay = win->getDisplay(); // Get the display for easy access glManager->setCurrentContext(win->getId()); // Set TS data of context id glManager->currentUserData()->setUser(theDisplay->getUser()); // Set user data glManager->currentUserData()->setProjection(NULL); win->makeCurrent(); // Make the context current theApp->contextClose(); // Call context close function // Close the window win->close(); // Remove it from the lists newWins.erase(std::remove(newWins.begin(), newWins.end(), win), newWins.end()); openWins.erase(std::remove(openWins.begin(), openWins.end(), win), openWins.end()); // Delete the window delete win; mClosingWins[i] = NULL; } mClosingWins.erase(mClosingWins.begin(), mClosingWins.end()); vjASSERT(mClosingWins.size() == 0);; } } //: Checks for any new windows to add to the pipe //! POST: Any new windows will be opened and added to the pipe's rendering list void vjGlPipe::checkForNewWindows() { if (newWins.size() > 0) // If there are new windows added { vjGuard<vjMutex> guardNew(newWinLock); vjGuard<vjMutex> guardOpen(openWinLock); for (unsigned int winNum=0; winNum<newWins.size(); winNum++) { newWins[winNum]->open(); newWins[winNum]->makeCurrent(); vjDEBUG(vjDBG_DRAW_MGR,1) << "vjGlPipe::checkForNewWindows: Just opened window:\n" << newWins[winNum] << endl << vjDEBUG_FLUSH; openWins.push_back(newWins[winNum]); } newWins.erase(newWins.begin(), newWins.end()); vjASSERT(newWins.size() == 0); } } //: Renders the window using OpenGL //! POST: win is rendered (In stereo if it is a stereo window) void vjGlPipe::renderWindow(vjGlWindow* win) { vjGlApp* theApp = glManager->getApp(); // Get application for easy access vjDisplay* theDisplay = win->getDisplay(); // Get the display for easy access glManager->setCurrentContext(win->getId()); // Set TSS data of context id vjDEBUG(vjDBG_DRAW_MGR,5) << "vjGlPipe::renderWindow: Set context to: " << vjGlDrawManager::instance()->getCurrentContext() << endl << vjDEBUG_FLUSH; mPerfBuffer->set(++mPerfPhase); // --- SET CONTEXT --- // win->makeCurrent(); // CONTEXT INIT(): Check if we need to call contextInit() if(win->hasDirtyContext()) { // Have dirty context glManager->currentUserData()->setUser(theDisplay->getUser()); // Set user data glManager->currentUserData()->setProjection(NULL); theApp->contextInit(); // Call context init function win->setDirtyContext(false); // All clean now } mPerfBuffer->set(++mPerfPhase); theApp->contextPreDraw(); // Do any context pre-drawing mPerfBuffer->set(++mPerfPhase); // ---- SURFACE --- // if (theDisplay->isSurface()) { vjSurfaceDisplay* surface_disp = dynamic_cast<vjSurfaceDisplay*>(theDisplay); vjDisplay::DisplayView view = theDisplay->getView(); // Get the view we are rendering if((vjDisplay::STEREO == view) || (vjDisplay::LEFT_EYE == view)) { win->setLeftEyeProjection(); mPerfBuffer->set(++mPerfPhase); glManager->currentUserData()->setUser(surface_disp->getUser()); // Set user data glManager->currentUserData()->setProjection(surface_disp->getLeftProj()); mPerfBuffer->set(++mPerfPhase); theApp->draw(); mPerfBuffer->set(++mPerfPhase); glManager->drawObjects(); mPerfBuffer->set(++mPerfPhase); } if ((vjDisplay::STEREO == view) || (vjDisplay::RIGHT_EYE == theDisplay->getView())) { win->setRightEyeProjection(); glManager->currentUserData()->setUser(surface_disp->getUser()); // Set user data glManager->currentUserData()->setProjection(surface_disp->getRightProj()); mPerfBuffer->set(++mPerfPhase); theApp->draw(); mPerfBuffer->set(++mPerfPhase); glManager->drawObjects(); } else mPerfPhase += 2; } // ---- SIMULATOR ---------- // else if(theDisplay->isSimulator()) { vjSimDisplay* sim_disp = dynamic_cast<vjSimDisplay*>(theDisplay); win->setCameraProjection(); glManager->currentUserData()->setUser(sim_disp->getUser()); // Set user data glManager->currentUserData()->setProjection(sim_disp->getCameraProj()); mPerfBuffer->set(++mPerfPhase); theApp->draw(); mPerfBuffer->set(++mPerfPhase); glManager->drawObjects(); glManager->drawSimulator(sim_disp); mPerfBuffer->set (++mPerfPhase); mPerfPhase += 3; } } //: Swaps the buffers of the given window // Make the context current, and swap the window void vjGlPipe::swapWindowBuffers(vjGlWindow* win) { win->makeCurrent(); // Set correct context win->swapBuffers(); // Implicitly calls a glFlush //vjTimeStamp* stamp = win->getDisplay()->getUser()->getHeadUpdateTime(); //cout << "timestamp time is: " << stamp->usecs() << " usecs" << endl; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <climits> #include <ctime> #define minVal adj[i][j].value < min && adj[i][j].value != -1 #define setMin min = adj[i][j].value; k = i; l = j; const char* nn = "ABCDEFG"; // node names using namespace std; //const static int n = 40; const static int n = 7; struct data { bool marked, connected; int value; data(){marked = connected = 0; value = -1;}; }; data adj[n][n]; //Adjacency Matrix Searching O(|V|^2) void print_adj() { for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { cout << adj[i][j].value << "|"; if(adj[i][j].connected) cout << "1|"; else cout << "0|"; if(adj[i][j].marked) cout << "1"; else cout << "0"; if(j + 1 < n) cout << " " ; else cout << "\n"; } } } void initialize(int & initial) { char temp; ifstream in; in.open("n2.txt"); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { temp = in.peek(); if(temp == '-')in >> temp; else { in >> adj[i][j].value; initial += adj[i][j].value; } j == n - 1 ? in.ignore(1, '\n') : in >> temp; } } in.close(); } bool connected() { for(int i = 0; i < n; i++) if(!adj[0][i].connected) return false; return true; } void markConnected(const int & jj, const int & ll) { for(int i = 0; i < n; i++) { if(i == jj) for(int j = 0; j < n; j++) adj[i][j].marked = true; adj[i][ll].connected = true; } } void optimize(int & pruned, int & k, int & l) { int i, j, min; do{ min = INT_MAX; for(i = 0; i < n; i++) { if(adj[i][0].marked) { for(j = 1; j < n; j++) if(!adj[i][j].connected && minVal){setMin} } } pruned += min; cout << "Add Edge: " << nn[k] << "--" << nn[l] << " weight: " << min << " total weight: " << pruned << endl; adj[k][l].value = -1; markConnected(l, l); }while(!connected()); } /** * Main Implements Prims Algorithm For MST (GREEDY) * * -,2,4,6,-,-,- * 2,-,2,-,6,-,- * 4,2,-,1,3,-,- * 6,-,1,-,2,3,- * -,6,3,2,-,-,5 * -,-,-,3,-,-,4 * -,-,-,-,5,4,- * * B----E----G * G = |\ /| | * | C | | * | / \| | * A----D----F * * 0 1 2 3 4 5 6 * A B C D E F G **/ int main() { clock_t start, end; int initial = 0, pruned = 0, i = 0, j = 0, min, k, l; start = clock(); initialize(initial); while(adj[i++][j].value == -1) setMin for(i; i < n; i++) if(minVal){setMin} adj[k][l].value = -1; markConnected(0, l); optimize(pruned, k, l); return 0; } <commit_msg>Update prims.cpp<commit_after>#include <iostream> #include <fstream> #include <climits> #include <ctime> #define minVal adj[i][j].value < min && adj[i][j].value != -1 #define setMin min = adj[i][j].value; k = i; l = j; const char* nn = "ABCDEFG"; // node names using namespace std; //const static int n = 40; const static int n = 7; struct data { bool marked, connected; int value; data(){marked = connected = 0; value = -1;}; }; data adj[n][n]; //Adjacency Matrix Searching O(|V|^2) void print_adj() { for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { cout << adj[i][j].value << "|"; if(adj[i][j].connected) cout << "1|"; else cout << "0|"; if(adj[i][j].marked) cout << "1"; else cout << "0"; if(j + 1 < n) cout << " " ; else cout << "\n"; } } } void initialize(int & initial) { char temp; ifstream in; in.open("n2.txt"); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { temp = in.peek(); if(temp == '-')in >> temp; else { in >> adj[i][j].value; initial += adj[i][j].value; } j == n - 1 ? in.ignore(1, '\n') : in >> temp; } } in.close(); } bool connected() { for(int i = 0; i < n; i++) if(!adj[0][i].connected) return false; return true; } void markConnected(const int & jj, const int & ll) { for(int i = 0; i < n; i++) { if(i == jj) for(int j = 0; j < n; j++) adj[i][j].marked = true; adj[i][ll].connected = true; } } void optimize(int & pruned, int & k, int & l) { int i, j, min; do{ min = INT_MAX; for(i = 0; i < n; i++) { if(adj[i][0].marked) { for(j = 1; j < n; j++) if(!adj[i][j].connected && minVal){setMin} } } pruned += min; cout << "Add Edge: " << nn[k] << "--" << nn[l] << " weight: " << min << " total weight: " << pruned << endl; adj[k][l].value = -1; markConnected(l, l); }while(!connected()); } /** * Main Implements Prims Algorithm For MST (GREEDY) * A B C D E F G * A -,2,4,6,-,-,- * B 2,-,2,-,6,-,- * C 4,2,-,1,3,-,- * D 6,-,1,-,2,3,- * E -,6,3,2,-,-,5 * F -,-,-,3,-,-,4 * G -,-,-,-,5,4,- * * B----E----G * G = |\ /| | * | C | | * | / \| | * A----D----F * * 0 1 2 3 4 5 6 * A B C D E F G * http://en.wikipedia.org/wiki/Prim%27s_algorithm **/ int main() { clock_t start, end; int initial = 0, pruned = 0, i = 0, j = 0, min, k, l; start = clock(); initialize(initial); while(adj[i++][j].value == -1) setMin for(i; i < n; i++) if(minVal){setMin} adj[k][l].value = -1; markConnected(0, l); optimize(pruned, k, l); return 0; } <|endoftext|>
<commit_before>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #pragma once #if !defined(RXCPP_RX_SUBSCRIPTION_HPP) #define RXCPP_RX_SUBSCRIPTION_HPP #include "rx-includes.hpp" namespace rxcpp { namespace detail { template<class F> struct is_unsubscribe_function { struct not_void {}; template<class CF> static auto check(int) -> decltype((*(CF*)nullptr)()); template<class CF> static not_void check(...); static const bool value = std::is_same<decltype(check<typename std::decay<F>::type>(0)), void>::value; }; } struct tag_subscription {}; struct subscription_base {typedef tag_subscription subscription_tag;}; template<class T> class is_subscription { template<class C> static typename C::subscription_tag* check(int); template<class C> static void check(...); public: static const bool value = std::is_convertible<decltype(check<typename std::decay<T>::type>(0)), tag_subscription*>::value; }; template<class Unsubscribe> class static_subscription { typedef typename std::decay<Unsubscribe>::type unsubscribe_call_type; unsubscribe_call_type unsubscribe_call; static_subscription() { } public: static_subscription(const static_subscription& o) : unsubscribe_call(o.unsubscribe_call) { } static_subscription(static_subscription&& o) : unsubscribe_call(std::move(o.unsubscribe_call)) { } static_subscription(unsubscribe_call_type s) : unsubscribe_call(std::move(s)) { } void unsubscribe() const { unsubscribe_call(); } }; class subscription : public subscription_base { class base_subscription_state : public std::enable_shared_from_this<base_subscription_state> { base_subscription_state(); public: explicit base_subscription_state(bool initial) : issubscribed(initial) { } virtual void unsubscribe() { } std::atomic<bool> issubscribed; }; public: typedef std::weak_ptr<base_subscription_state> weak_state_type; private: template<class I> struct subscription_state : public base_subscription_state { typedef typename std::decay<I>::type inner_t; subscription_state(inner_t i) : base_subscription_state(true) , inner(std::move(i)) { } virtual void unsubscribe() { if (issubscribed.exchange(false)) { trace_activity().unsubscribe_enter(*this); inner.unsubscribe(); trace_activity().unsubscribe_return(*this); } } inner_t inner; }; protected: std::shared_ptr<base_subscription_state> state; friend bool operator<(const subscription&, const subscription&); friend bool operator==(const subscription&, const subscription&); private: subscription(weak_state_type w) : state(w.lock()) { if (!state) { abort(); } } public: subscription() : state(std::make_shared<base_subscription_state>(false)) { if (!state) { abort(); } } template<class U> explicit subscription(U u, typename std::enable_if<!is_subscription<U>::value, void**>::type = nullptr) : state(std::make_shared<subscription_state<U>>(std::move(u))) { if (!state) { abort(); } } template<class U> explicit subscription(U u, typename std::enable_if<!std::is_same<subscription, U>::value && is_subscription<U>::value, void**>::type = nullptr) // intentionally slice : state(std::move((*static_cast<subscription*>(&u)).state)) { if (!state) { abort(); } } subscription(const subscription& o) : state(o.state) { if (!state) { abort(); } } subscription(subscription&& o) : state(std::move(o.state)) { if (!state) { abort(); } } subscription& operator=(subscription o) { state = std::move(o.state); return *this; } bool is_subscribed() const { if (!state) { abort(); } return state->issubscribed; } void unsubscribe() const { if (!state) { abort(); } auto keepAlive = state; state->unsubscribe(); } weak_state_type get_weak() { return state; } static subscription lock(weak_state_type w) { return subscription(w); } }; inline bool operator<(const subscription& lhs, const subscription& rhs) { return lhs.state < rhs.state; } inline bool operator==(const subscription& lhs, const subscription& rhs) { return lhs.state == rhs.state; } inline bool operator!=(const subscription& lhs, const subscription& rhs) { return !(lhs == rhs); } inline auto make_subscription() -> subscription { return subscription(); } template<class I> auto make_subscription(I&& i) -> typename std::enable_if<!is_subscription<I>::value && !detail::is_unsubscribe_function<I>::value, subscription>::type { return subscription(std::forward<I>(i)); } template<class Unsubscribe> auto make_subscription(Unsubscribe&& u) -> typename std::enable_if<detail::is_unsubscribe_function<Unsubscribe>::value, subscription>::type { return subscription(static_subscription<Unsubscribe>(std::forward<Unsubscribe>(u))); } namespace detail { struct tag_composite_subscription_empty {}; class composite_subscription_inner { private: typedef subscription::weak_state_type weak_subscription; struct composite_subscription_state : public std::enable_shared_from_this<composite_subscription_state> { std::set<subscription> subscriptions; std::mutex lock; std::atomic<bool> issubscribed; ~composite_subscription_state() { std::unique_lock<decltype(lock)> guard(lock); subscriptions.clear(); } composite_subscription_state() : issubscribed(true) { } composite_subscription_state(tag_composite_subscription_empty) : issubscribed(false) { } inline weak_subscription add(subscription s) { if (!issubscribed) { s.unsubscribe(); } else if (s.is_subscribed()) { std::unique_lock<decltype(lock)> guard(lock); subscriptions.insert(s); } return s.get_weak(); } inline void remove(weak_subscription w) { if (issubscribed && !w.expired()) { auto s = subscription::lock(w); std::unique_lock<decltype(lock)> guard(lock); subscriptions.erase(std::move(s)); } } inline void clear() { if (issubscribed) { std::unique_lock<decltype(lock)> guard(lock); std::set<subscription> v(std::move(subscriptions)); guard.unlock(); std::for_each(v.begin(), v.end(), [](const subscription& s) { s.unsubscribe(); }); } } inline void unsubscribe() { if (issubscribed.exchange(false)) { std::unique_lock<decltype(lock)> guard(lock); std::set<subscription> v(std::move(subscriptions)); guard.unlock(); std::for_each(v.begin(), v.end(), [](const subscription& s) { s.unsubscribe(); }); } } }; public: typedef std::shared_ptr<composite_subscription_state> shared_state_type; protected: mutable shared_state_type state; public: composite_subscription_inner() : state(std::make_shared<composite_subscription_state>()) { } composite_subscription_inner(tag_composite_subscription_empty et) : state(std::make_shared<composite_subscription_state>(et)) { } composite_subscription_inner(const composite_subscription_inner& o) : state(o.state) { if (!state) { abort(); } } composite_subscription_inner(composite_subscription_inner&& o) : state(std::move(o.state)) { if (!state) { abort(); } } composite_subscription_inner& operator=(composite_subscription_inner o) { state = std::move(o.state); if (!state) { abort(); } return *this; } inline weak_subscription add(subscription s) const { if (!state) { abort(); } return state->add(std::move(s)); } inline void remove(weak_subscription w) const { if (!state) { abort(); } state->remove(std::move(w)); } inline void clear() const { if (!state) { abort(); } state->clear(); } inline void unsubscribe() { if (!state) { abort(); } state->unsubscribe(); } }; } class composite_subscription : protected detail::composite_subscription_inner , public subscription { typedef detail::composite_subscription_inner inner_type; public: typedef subscription::weak_state_type weak_subscription; static composite_subscription shared_empty; composite_subscription(detail::tag_composite_subscription_empty et) : inner_type(et) , subscription() // use empty base { } public: composite_subscription() : inner_type() , subscription(*static_cast<const inner_type* const>(this)) { } composite_subscription(const composite_subscription& o) : inner_type(o) , subscription(static_cast<const subscription&>(o)) { } composite_subscription(composite_subscription&& o) : inner_type(std::move(o)) , subscription(std::move(static_cast<subscription&>(o))) { } composite_subscription& operator=(composite_subscription o) { inner_type::operator=(std::move(o)); subscription::operator=(std::move(*static_cast<subscription*>(&o))); return *this; } static inline composite_subscription empty() { return shared_empty; } using subscription::is_subscribed; using subscription::unsubscribe; using inner_type::clear; inline weak_subscription add(subscription s) const { if (s == static_cast<const subscription&>(*this)) { // do not nest the same subscription abort(); //return s.get_weak(); } auto that = this->subscription::state.get(); trace_activity().subscription_add_enter(*that, s); auto w = inner_type::add(std::move(s)); trace_activity().subscription_add_return(*that); return w; } template<class F> auto add(F f) const -> typename std::enable_if<detail::is_unsubscribe_function<F>::value, weak_subscription>::type { return add(make_subscription(std::move(f))); } inline void remove(weak_subscription w) const { auto that = this->subscription::state.get(); trace_activity().subscription_remove_enter(*that, w); inner_type::remove(w); trace_activity().subscription_remove_return(*that); } }; inline bool operator<(const composite_subscription& lhs, const composite_subscription& rhs) { return static_cast<const subscription&>(lhs) < static_cast<const subscription&>(rhs); } inline bool operator==(const composite_subscription& lhs, const composite_subscription& rhs) { return static_cast<const subscription&>(lhs) == static_cast<const subscription&>(rhs); } inline bool operator!=(const composite_subscription& lhs, const composite_subscription& rhs) { return !(lhs == rhs); } //static RXCPP_SELECT_ANY composite_subscription composite_subscription::shared_empty = composite_subscription(detail::tag_composite_subscription_empty()); template<class T> class resource : public subscription_base { public: typedef typename composite_subscription::weak_subscription weak_subscription; resource(T t = T(), composite_subscription cs = composite_subscription()) : lifetime(std::move(cs)) , value(std::make_shared<std::unique_ptr<T>>(std::unique_ptr<T>(new T(std::move(t))))) { auto localValue = value; lifetime.add( [localValue](){ localValue->reset(); } ); } T& get() { return *value.get()->get(); } composite_subscription& get_subscription() { return lifetime; } bool is_subscribed() const { return lifetime.is_subscribed(); } weak_subscription add(subscription s) const { return lifetime.add(std::move(s)); } template<class F> auto add(F f) const -> typename std::enable_if<detail::is_unsubscribe_function<F>::value, weak_subscription>::type { return lifetime.add(make_subscription(std::move(f))); } void remove(weak_subscription w) const { return lifetime.remove(std::move(w)); } void clear() const { return lifetime.clear(); } void unsubscribe() const { return lifetime.unsubscribe(); } protected: composite_subscription lifetime; std::shared_ptr<std::unique_ptr<T>> value; }; } #endif <commit_msg>Small changes on resource class<commit_after>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #pragma once #if !defined(RXCPP_RX_SUBSCRIPTION_HPP) #define RXCPP_RX_SUBSCRIPTION_HPP #include "rx-includes.hpp" namespace rxcpp { namespace detail { template<class F> struct is_unsubscribe_function { struct not_void {}; template<class CF> static auto check(int) -> decltype((*(CF*)nullptr)()); template<class CF> static not_void check(...); static const bool value = std::is_same<decltype(check<typename std::decay<F>::type>(0)), void>::value; }; } struct tag_subscription {}; struct subscription_base {typedef tag_subscription subscription_tag;}; template<class T> class is_subscription { template<class C> static typename C::subscription_tag* check(int); template<class C> static void check(...); public: static const bool value = std::is_convertible<decltype(check<typename std::decay<T>::type>(0)), tag_subscription*>::value; }; template<class Unsubscribe> class static_subscription { typedef typename std::decay<Unsubscribe>::type unsubscribe_call_type; unsubscribe_call_type unsubscribe_call; static_subscription() { } public: static_subscription(const static_subscription& o) : unsubscribe_call(o.unsubscribe_call) { } static_subscription(static_subscription&& o) : unsubscribe_call(std::move(o.unsubscribe_call)) { } static_subscription(unsubscribe_call_type s) : unsubscribe_call(std::move(s)) { } void unsubscribe() const { unsubscribe_call(); } }; class subscription : public subscription_base { class base_subscription_state : public std::enable_shared_from_this<base_subscription_state> { base_subscription_state(); public: explicit base_subscription_state(bool initial) : issubscribed(initial) { } virtual void unsubscribe() { } std::atomic<bool> issubscribed; }; public: typedef std::weak_ptr<base_subscription_state> weak_state_type; private: template<class I> struct subscription_state : public base_subscription_state { typedef typename std::decay<I>::type inner_t; subscription_state(inner_t i) : base_subscription_state(true) , inner(std::move(i)) { } virtual void unsubscribe() { if (issubscribed.exchange(false)) { trace_activity().unsubscribe_enter(*this); inner.unsubscribe(); trace_activity().unsubscribe_return(*this); } } inner_t inner; }; protected: std::shared_ptr<base_subscription_state> state; friend bool operator<(const subscription&, const subscription&); friend bool operator==(const subscription&, const subscription&); private: subscription(weak_state_type w) : state(w.lock()) { if (!state) { abort(); } } public: subscription() : state(std::make_shared<base_subscription_state>(false)) { if (!state) { abort(); } } template<class U> explicit subscription(U u, typename std::enable_if<!is_subscription<U>::value, void**>::type = nullptr) : state(std::make_shared<subscription_state<U>>(std::move(u))) { if (!state) { abort(); } } template<class U> explicit subscription(U u, typename std::enable_if<!std::is_same<subscription, U>::value && is_subscription<U>::value, void**>::type = nullptr) // intentionally slice : state(std::move((*static_cast<subscription*>(&u)).state)) { if (!state) { abort(); } } subscription(const subscription& o) : state(o.state) { if (!state) { abort(); } } subscription(subscription&& o) : state(std::move(o.state)) { if (!state) { abort(); } } subscription& operator=(subscription o) { state = std::move(o.state); return *this; } bool is_subscribed() const { if (!state) { abort(); } return state->issubscribed; } void unsubscribe() const { if (!state) { abort(); } auto keepAlive = state; state->unsubscribe(); } weak_state_type get_weak() { return state; } static subscription lock(weak_state_type w) { return subscription(w); } }; inline bool operator<(const subscription& lhs, const subscription& rhs) { return lhs.state < rhs.state; } inline bool operator==(const subscription& lhs, const subscription& rhs) { return lhs.state == rhs.state; } inline bool operator!=(const subscription& lhs, const subscription& rhs) { return !(lhs == rhs); } inline auto make_subscription() -> subscription { return subscription(); } template<class I> auto make_subscription(I&& i) -> typename std::enable_if<!is_subscription<I>::value && !detail::is_unsubscribe_function<I>::value, subscription>::type { return subscription(std::forward<I>(i)); } template<class Unsubscribe> auto make_subscription(Unsubscribe&& u) -> typename std::enable_if<detail::is_unsubscribe_function<Unsubscribe>::value, subscription>::type { return subscription(static_subscription<Unsubscribe>(std::forward<Unsubscribe>(u))); } namespace detail { struct tag_composite_subscription_empty {}; class composite_subscription_inner { private: typedef subscription::weak_state_type weak_subscription; struct composite_subscription_state : public std::enable_shared_from_this<composite_subscription_state> { std::set<subscription> subscriptions; std::mutex lock; std::atomic<bool> issubscribed; ~composite_subscription_state() { std::unique_lock<decltype(lock)> guard(lock); subscriptions.clear(); } composite_subscription_state() : issubscribed(true) { } composite_subscription_state(tag_composite_subscription_empty) : issubscribed(false) { } inline weak_subscription add(subscription s) { if (!issubscribed) { s.unsubscribe(); } else if (s.is_subscribed()) { std::unique_lock<decltype(lock)> guard(lock); subscriptions.insert(s); } return s.get_weak(); } inline void remove(weak_subscription w) { if (issubscribed && !w.expired()) { auto s = subscription::lock(w); std::unique_lock<decltype(lock)> guard(lock); subscriptions.erase(std::move(s)); } } inline void clear() { if (issubscribed) { std::unique_lock<decltype(lock)> guard(lock); std::set<subscription> v(std::move(subscriptions)); guard.unlock(); std::for_each(v.begin(), v.end(), [](const subscription& s) { s.unsubscribe(); }); } } inline void unsubscribe() { if (issubscribed.exchange(false)) { std::unique_lock<decltype(lock)> guard(lock); std::set<subscription> v(std::move(subscriptions)); guard.unlock(); std::for_each(v.begin(), v.end(), [](const subscription& s) { s.unsubscribe(); }); } } }; public: typedef std::shared_ptr<composite_subscription_state> shared_state_type; protected: mutable shared_state_type state; public: composite_subscription_inner() : state(std::make_shared<composite_subscription_state>()) { } composite_subscription_inner(tag_composite_subscription_empty et) : state(std::make_shared<composite_subscription_state>(et)) { } composite_subscription_inner(const composite_subscription_inner& o) : state(o.state) { if (!state) { abort(); } } composite_subscription_inner(composite_subscription_inner&& o) : state(std::move(o.state)) { if (!state) { abort(); } } composite_subscription_inner& operator=(composite_subscription_inner o) { state = std::move(o.state); if (!state) { abort(); } return *this; } inline weak_subscription add(subscription s) const { if (!state) { abort(); } return state->add(std::move(s)); } inline void remove(weak_subscription w) const { if (!state) { abort(); } state->remove(std::move(w)); } inline void clear() const { if (!state) { abort(); } state->clear(); } inline void unsubscribe() { if (!state) { abort(); } state->unsubscribe(); } }; } class composite_subscription : protected detail::composite_subscription_inner , public subscription { typedef detail::composite_subscription_inner inner_type; public: typedef subscription::weak_state_type weak_subscription; static composite_subscription shared_empty; composite_subscription(detail::tag_composite_subscription_empty et) : inner_type(et) , subscription() // use empty base { } public: composite_subscription() : inner_type() , subscription(*static_cast<const inner_type* const>(this)) { } composite_subscription(const composite_subscription& o) : inner_type(o) , subscription(static_cast<const subscription&>(o)) { } composite_subscription(composite_subscription&& o) : inner_type(std::move(o)) , subscription(std::move(static_cast<subscription&>(o))) { } composite_subscription& operator=(composite_subscription o) { inner_type::operator=(std::move(o)); subscription::operator=(std::move(*static_cast<subscription*>(&o))); return *this; } static inline composite_subscription empty() { return shared_empty; } using subscription::is_subscribed; using subscription::unsubscribe; using inner_type::clear; inline weak_subscription add(subscription s) const { if (s == static_cast<const subscription&>(*this)) { // do not nest the same subscription abort(); //return s.get_weak(); } auto that = this->subscription::state.get(); trace_activity().subscription_add_enter(*that, s); auto w = inner_type::add(std::move(s)); trace_activity().subscription_add_return(*that); return w; } template<class F> auto add(F f) const -> typename std::enable_if<detail::is_unsubscribe_function<F>::value, weak_subscription>::type { return add(make_subscription(std::move(f))); } inline void remove(weak_subscription w) const { auto that = this->subscription::state.get(); trace_activity().subscription_remove_enter(*that, w); inner_type::remove(w); trace_activity().subscription_remove_return(*that); } }; inline bool operator<(const composite_subscription& lhs, const composite_subscription& rhs) { return static_cast<const subscription&>(lhs) < static_cast<const subscription&>(rhs); } inline bool operator==(const composite_subscription& lhs, const composite_subscription& rhs) { return static_cast<const subscription&>(lhs) == static_cast<const subscription&>(rhs); } inline bool operator!=(const composite_subscription& lhs, const composite_subscription& rhs) { return !(lhs == rhs); } //static RXCPP_SELECT_ANY composite_subscription composite_subscription::shared_empty = composite_subscription(detail::tag_composite_subscription_empty()); template<class T> class resource : public subscription_base { public: typedef typename composite_subscription::weak_subscription weak_subscription; resource() : lifetime(composite_subscription()) , value(std::make_shared<rxu::detail::maybe<T>>()) { } explicit resource(T t, composite_subscription cs = composite_subscription()) : lifetime(std::move(cs)) , value(std::make_shared<rxu::detail::maybe<T>>(rxu::detail::maybe<T>(std::move(t)))) { auto localValue = value; lifetime.add( [localValue](){ localValue->reset(); } ); } T& get() { return value.get()->get(); } composite_subscription& get_subscription() { return lifetime; } bool is_subscribed() const { return lifetime.is_subscribed(); } weak_subscription add(subscription s) const { return lifetime.add(std::move(s)); } template<class F> auto add(F f) const -> typename std::enable_if<detail::is_unsubscribe_function<F>::value, weak_subscription>::type { return lifetime.add(make_subscription(std::move(f))); } void remove(weak_subscription w) const { return lifetime.remove(std::move(w)); } void clear() const { return lifetime.clear(); } void unsubscribe() const { return lifetime.unsubscribe(); } protected: composite_subscription lifetime; std::shared_ptr<rxu::detail::maybe<T>> value; }; } #endif <|endoftext|>
<commit_before>/*** * Copyright (c) 2013, Dan Hasting * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the organization nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "thegamesdbscraper.h" #include "../global.h" #include "../common.h" #include <QDir> #include <QEventLoop> #include <QJsonDocument> #include <QJsonArray> #include <QJsonObject> #include <QMessageBox> #include <QTextStream> #include <QTimer> #include <QUrl> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkReply> #include <QtNetwork/QNetworkRequest> TheGamesDBScraper::TheGamesDBScraper(QWidget *parent, bool force) : QObject(parent) { this->parent = parent; this->force = force; this->keepGoing = true; } QString TheGamesDBScraper::convertIDs(QJsonObject foundGame, QString typeName, QString listName) { QJsonArray idArray = foundGame.value(typeName).toArray(); QString cacheFileString = getDataLocation() + "/cache/" + typeName + ".json"; QFile cacheFile(cacheFileString); cacheFile.open(QIODevice::ReadOnly); QString data = cacheFile.readAll(); cacheFile.close(); QJsonDocument document = QJsonDocument::fromJson(data.toUtf8()); QJsonObject cache = document.object(); QString result = ""; foreach (QJsonValue id, idArray) { QString entryID = QString::number(id.toInt()); QString entryName = cache.value(entryID).toObject().value("name").toString(); if (entryName == "") { updateListCache(&cacheFile, listName); cacheFile.open(QIODevice::ReadOnly); data = cacheFile.readAll(); cacheFile.close(); document = QJsonDocument::fromJson(data.toUtf8()); entryName = cache.value(entryID).toObject().value("name").toString(); } if (entryName != "") result += entryName + ", "; } int pos = result.lastIndexOf(QChar(',')); return result.left(pos); } void TheGamesDBScraper::deleteGameInfo(QString fileName, QString identifier) { QString text; text = QString(tr("<b>NOTE:</b> If you are deleting this game's information because the game doesn't ")) + tr("exist on TheGamesDB and <AppName> pulled the information for different game, it's ") + tr("better to create an account on")+" <a href=\"http://thegamesdb.net/\">TheGamesDB</a> " + tr("and add the game so other users can benefit as well.") + "<br /><br />" + tr("This will cause <AppName> to not update the information for this game until you ") + tr("force it with \"Download/Update Info...\"") + "<br /><br />" + tr("Delete the current information for") + " <b>" + fileName + "</b>?"; text.replace("<AppName>",AppName); int answer = QMessageBox::question(parent, tr("Delete Game Information"), text, QMessageBox::Yes | QMessageBox::No); if (answer == QMessageBox::Yes) { QString gameCache = getDataLocation() + "/cache/" + identifier.toLower(); QString dataFile = gameCache + "/data.xml"; QFile file(dataFile); // Remove game information file.open(QIODevice::WriteOnly); QTextStream stream(&file); stream << "NULL"; file.close(); // Remove cover image QString coverFile = gameCache + "/boxart-front."; QFile coverJPG(coverFile + "jpg"); QFile coverPNG(coverFile + "png"); if (coverJPG.exists()) coverJPG.remove(); if (coverPNG.exists()) coverPNG.remove(); coverJPG.open(QIODevice::WriteOnly); QTextStream streamImage(&coverJPG); streamImage << ""; coverJPG.close(); } } void TheGamesDBScraper::downloadGameInfo(QString identifier, QString searchName, QString gameID) { if (keepGoing && identifier != "") { if (force) parent->setEnabled(false); bool updated = false; QString gameCache = getDataLocation() + "/cache/" + identifier.toLower(); QDir cache(gameCache); if (!cache.exists()) { cache.mkpath(gameCache); } QString genreCache = getDataLocation() + "/cache/genres.json"; QFile genres(genreCache); if (!genres.exists()) updateListCache(&genres, "Genres"); QString developerCache = getDataLocation() + "/cache/developers.json"; QFile developers(developerCache); if (!developers.exists()) updateListCache(&developers, "Developers"); QString publisherCache = getDataLocation() + "/cache/publishers.json"; QFile publishers(publisherCache); if (!publishers.exists()) updateListCache(&publishers, "Publishers"); //Get game JSON info from thegamesdb.net QString dataFile = gameCache + "/data.json"; QFile file(dataFile); if (!file.exists() || file.size() == 0 || force) { QUrl url; //Remove [!], (U), etc. from GoodName for searching searchName.remove(QRegExp("\\W*(\\(|\\[).+(\\)|\\])\\W*")); //Few game specific hacks //TODO: Contact thegamesdb.net and see if these can be fixed on their end if (searchName == "Legend of Zelda, The - Majora's Mask") searchName = "Majora's Mask"; else if (searchName == "Legend of Zelda, The - Ocarina of Time" || searchName == "THE LEGEND OF ZELDA") searchName = "The Legend of Zelda: Ocarina of Time"; else if (searchName == "Tsumi to Batsu - Hoshi no Keishousha") searchName = "Sin and Punishment"; else if (searchName == "1080 Snowboarding") searchName = "1080: TenEighty Snowboarding"; else if (searchName == "Extreme-G XG2") searchName = "Extreme-G 2"; else if (searchName.contains("Pokemon")) searchName.replace("Pokemon", "Pokémon"); else if (searchName.toLower() == "f-zero x") gameID = "10836"; QString apiFilter = "&filter[platform]=3&include=boxart&fields=game_title,release_date,"; apiFilter += "developers,publishers,genres,overview,rating,players"; //If user submits gameID, use that if (gameID != "") url.setUrl("https://api.thegamesdb.net/Games/ByGameID?apikey=" + TheGamesDBAPIKey + "&id=" + gameID + apiFilter); else url.setUrl("https://api.thegamesdb.net/Games/ByGameName?apikey=" + TheGamesDBAPIKey + "&name=" + searchName + apiFilter); QString data = getUrlContents(url); QJsonDocument document = QJsonDocument::fromJson(data.toUtf8()); QJsonObject json = document.object(); if (json.value("code").toInt() != 200 && json.value("code").toInt() != 0) { QString status = json.value("status").toString(); QString message; message = QString(tr("The following error from TheGamesDB occured while downloading:")) + "<br /><br />" + status; QMessageBox::information(parent, QObject::tr("Download Error"), message); if (force) parent->setEnabled(true); return; } QJsonValue games = json.value("data").toObject().value("games"); QJsonArray gamesArray = games.toArray(); int count = 0, found = 0; foreach (QJsonValue game, gamesArray) { QJsonValue title = game.toObject().value("game_title"); if (force) { //from user dialog QJsonValue date = game.toObject().value("release_date"); QString check = "Game: " + title.toString(); check.remove(QRegExp(QString("[^A-Za-z 0-9 \\.,\\?'""!@#\\$%\\^&\\*\\") + "(\\)-_=\\+;:<>\\/\\\\|\\}\\{\\[\\]`~]*")); if (date.toString() != "") check += "\n" + tr("Released on: ") + date.toString(); check += "\n\n" + tr("Does this look correct?"); int answer = QMessageBox::question(parent, QObject::tr("Game Information Download"), check, QMessageBox::Yes | QMessageBox::No); if (answer == QMessageBox::Yes) { found = count; updated = true; break; } } else { //We only want one game, so search for a perfect match in the GameTitle element. //Otherwise this will default to 0 (the first game found) if(title.toString() == searchName) found = count; } count++; } if (!force || updated) { QJsonObject foundGame = gamesArray.at(found).toObject(); QJsonObject saveData; QString gameID = QString::number(foundGame.value("id").toInt()); QJsonObject boxart = json.value("include").toObject().value("boxart").toObject(); QString thumbURL = boxart.value("base_url").toObject().value("thumb").toString(); QJsonArray imgArray = boxart.value("data").toObject().value(gameID).toArray(); QString frontImg = ""; foreach (QJsonValue img, imgArray) { QString type = img.toObject().value("type").toString(); QString side = img.toObject().value("side").toString(); QString filename = img.toObject().value("filename").toString(); if (type == "boxart" && side == "front") frontImg = thumbURL + filename; } //Convert IDs from API to text names QString genresString = convertIDs(foundGame, "genres", "Genres"); QString developerString = convertIDs(foundGame, "developers", "Developers"); QString publisherString = convertIDs(foundGame, "publishers", "Publishers"); saveData.insert("game_title", foundGame.value("game_title")); saveData.insert("release_date", foundGame.value("release_date")); saveData.insert("rating", foundGame.value("rating")); saveData.insert("overview", foundGame.value("overview")); saveData.insert("players", foundGame.value("players")); saveData.insert("boxart", frontImg); saveData.insert("genres", genresString); saveData.insert("developer", developerString); saveData.insert("publisher", publisherString); QJsonDocument document(saveData); file.open(QIODevice::WriteOnly); file.write(document.toJson()); file.close(); } if (force && !updated) { QString message; if (count == 0) message = QObject::tr("No results found."); else message = QObject::tr("No more results found."); QMessageBox::information(parent, QObject::tr("Game Information Download"), message); } } //Get front cover QString boxartURL = ""; QString boxartExt = ""; QString coverFile = gameCache + "/boxart-front."; QFile coverJPG(coverFile + "jpg"); QFile coverPNG(coverFile + "png"); if ((!coverJPG.exists() && !coverPNG.exists()) || (force && updated)) { file.open(QIODevice::ReadOnly); QString data = file.readAll(); file.close(); QJsonDocument document = QJsonDocument::fromJson(data.toUtf8()); QJsonObject json = document.object(); QString boxartURL = json.value("boxart").toString(); if (boxartURL != "") { QUrl url(boxartURL); //Delete current box art QFile::remove(coverFile + "jpg"); QFile::remove(coverFile + "png"); //Check to save as JPG or PNG boxartExt = QFileInfo(boxartURL).completeSuffix().toLower(); QFile cover(coverFile + boxartExt); cover.open(QIODevice::WriteOnly); cover.write(getUrlContents(url)); cover.close(); } } if (updated) QMessageBox::information(parent, QObject::tr("Game Information Download"), QObject::tr("Download Complete!")); if (force) parent->setEnabled(true); } } QByteArray TheGamesDBScraper::getUrlContents(QUrl url) { QNetworkAccessManager *manager = new QNetworkAccessManager; QNetworkRequest request; request.setUrl(url); request.setRawHeader("User-Agent", AppName.toUtf8().constData()); QNetworkReply *reply = manager->get(request); QTimer timer; timer.setSingleShot(true); QEventLoop loop; connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); int time = SETTINGS.value("Other/networktimeout", 10).toInt(); if (time == 0) time = 10; time *= 1000; timer.start(time); loop.exec(); if(timer.isActive()) { //Got reply timer.stop(); if(reply->error() > 0) showError(reply->errorString()); else return reply->readAll(); } else //Request timed out showError(tr("Request timed out. Check your network settings.")); return QByteArray(); } void TheGamesDBScraper::showError(QString error) { QString question = "\n\n" + tr("Continue scraping information?"); if (force) QMessageBox::information(parent, tr("Network Error"), error); else { int answer = QMessageBox::question(parent, tr("Network Error"), error + question, QMessageBox::Yes | QMessageBox::No); if (answer == QMessageBox::No) keepGoing = false; } } void TheGamesDBScraper::updateListCache(QFile *file, QString list) { QUrl url; url.setUrl("https://api.thegamesdb.net/" + list + "?apikey=" + TheGamesDBAPIKey); QString data = getUrlContents(url); QJsonDocument document = QJsonDocument::fromJson(data.toUtf8()); QJsonDocument result(document.object().value("data").toObject().value(list.toLower()).toObject()); file->open(QIODevice::WriteOnly); file->write(result.toJson()); file->close(); } <commit_msg>Use showError method and fill in empty strings for missing information<commit_after>/*** * Copyright (c) 2013, Dan Hasting * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the organization nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "thegamesdbscraper.h" #include "../global.h" #include "../common.h" #include <QDir> #include <QEventLoop> #include <QJsonDocument> #include <QJsonArray> #include <QJsonObject> #include <QMessageBox> #include <QTextStream> #include <QTimer> #include <QUrl> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkReply> #include <QtNetwork/QNetworkRequest> TheGamesDBScraper::TheGamesDBScraper(QWidget *parent, bool force) : QObject(parent) { this->parent = parent; this->force = force; this->keepGoing = true; } QString TheGamesDBScraper::convertIDs(QJsonObject foundGame, QString typeName, QString listName) { QJsonArray idArray = foundGame.value(typeName).toArray(); QString cacheFileString = getDataLocation() + "/cache/" + typeName + ".json"; QFile cacheFile(cacheFileString); cacheFile.open(QIODevice::ReadOnly); QString data = cacheFile.readAll(); cacheFile.close(); QJsonDocument document = QJsonDocument::fromJson(data.toUtf8()); QJsonObject cache = document.object(); QString result = ""; foreach (QJsonValue id, idArray) { QString entryID = QString::number(id.toInt()); QString entryName = cache.value(entryID).toObject().value("name").toString(); if (entryName == "") { updateListCache(&cacheFile, listName); cacheFile.open(QIODevice::ReadOnly); data = cacheFile.readAll(); cacheFile.close(); document = QJsonDocument::fromJson(data.toUtf8()); entryName = cache.value(entryID).toObject().value("name").toString(); } if (entryName != "") result += entryName + ", "; } int pos = result.lastIndexOf(QChar(',')); return result.left(pos); } void TheGamesDBScraper::deleteGameInfo(QString fileName, QString identifier) { QString text; text = QString(tr("<b>NOTE:</b> If you are deleting this game's information because the game doesn't ")) + tr("exist on TheGamesDB and <AppName> pulled the information for different game, it's ") + tr("better to create an account on")+" <a href=\"http://thegamesdb.net/\">TheGamesDB</a> " + tr("and add the game so other users can benefit as well.") + "<br /><br />" + tr("This will cause <AppName> to not update the information for this game until you ") + tr("force it with \"Download/Update Info...\"") + "<br /><br />" + tr("Delete the current information for") + " <b>" + fileName + "</b>?"; text.replace("<AppName>",AppName); int answer = QMessageBox::question(parent, tr("Delete Game Information"), text, QMessageBox::Yes | QMessageBox::No); if (answer == QMessageBox::Yes) { QString gameCache = getDataLocation() + "/cache/" + identifier.toLower(); QString dataFile = gameCache + "/data.xml"; QFile file(dataFile); // Remove game information file.open(QIODevice::WriteOnly); QTextStream stream(&file); stream << "NULL"; file.close(); // Remove cover image QString coverFile = gameCache + "/boxart-front."; QFile coverJPG(coverFile + "jpg"); QFile coverPNG(coverFile + "png"); if (coverJPG.exists()) coverJPG.remove(); if (coverPNG.exists()) coverPNG.remove(); coverJPG.open(QIODevice::WriteOnly); QTextStream streamImage(&coverJPG); streamImage << ""; coverJPG.close(); } } void TheGamesDBScraper::downloadGameInfo(QString identifier, QString searchName, QString gameID) { if (keepGoing && identifier != "") { if (force) parent->setEnabled(false); bool updated = false; QString gameCache = getDataLocation() + "/cache/" + identifier.toLower(); QDir cache(gameCache); if (!cache.exists()) { cache.mkpath(gameCache); } QString genreCache = getDataLocation() + "/cache/genres.json"; QFile genres(genreCache); if (!genres.exists()) updateListCache(&genres, "Genres"); QString developerCache = getDataLocation() + "/cache/developers.json"; QFile developers(developerCache); if (!developers.exists()) updateListCache(&developers, "Developers"); QString publisherCache = getDataLocation() + "/cache/publishers.json"; QFile publishers(publisherCache); if (!publishers.exists()) updateListCache(&publishers, "Publishers"); //Get game JSON info from thegamesdb.net QString dataFile = gameCache + "/data.json"; QFile file(dataFile); if (!file.exists() || file.size() == 0 || force) { QUrl url; //Remove [!], (U), etc. from GoodName for searching searchName.remove(QRegExp("\\W*(\\(|\\[).+(\\)|\\])\\W*")); //Few game specific hacks //TODO: Contact thegamesdb.net and see if these can be fixed on their end if (searchName == "Legend of Zelda, The - Majora's Mask") searchName = "Majora's Mask"; else if (searchName == "Legend of Zelda, The - Ocarina of Time" || searchName == "THE LEGEND OF ZELDA") searchName = "The Legend of Zelda: Ocarina of Time"; else if (searchName == "Tsumi to Batsu - Hoshi no Keishousha") searchName = "Sin and Punishment"; else if (searchName == "1080 Snowboarding") searchName = "1080: TenEighty Snowboarding"; else if (searchName == "Extreme-G XG2") searchName = "Extreme-G 2"; else if (searchName.contains("Pokemon")) searchName.replace("Pokemon", "Pokémon"); else if (searchName.toLower() == "f-zero x") gameID = "10836"; QString apiFilter = "&filter[platform]=3&include=boxart&fields=game_title,release_date,"; apiFilter += "developers,publishers,genres,overview,rating,players"; //If user submits gameID, use that if (gameID != "") url.setUrl("https://api.thegamesdb.net/Games/ByGameID?apikey=" + TheGamesDBAPIKey + "&id=" + gameID + apiFilter); else url.setUrl("https://api.thegamesdb.net/Games/ByGameName?apikey=" + TheGamesDBAPIKey + "&name=" + searchName + apiFilter); QString data = getUrlContents(url); QJsonDocument document = QJsonDocument::fromJson(data.toUtf8()); QJsonObject json = document.object(); if (json.value("code").toInt() != 200 && json.value("code").toInt() != 0) { QString status = json.value("status").toString(); QString message; message = QString(tr("The following error from TheGamesDB occured while downloading:")) + "<br /><br />" + status + "<br /><br />"; showError(message); if (force) parent->setEnabled(true); return; } QJsonValue games = json.value("data").toObject().value("games"); QJsonArray gamesArray = games.toArray(); int count = 0, found = 0; foreach (QJsonValue game, gamesArray) { QJsonValue title = game.toObject().value("game_title"); if (force) { //from user dialog QJsonValue date = game.toObject().value("release_date"); QString check = "Game: " + title.toString(); check.remove(QRegExp(QString("[^A-Za-z 0-9 \\.,\\?'""!@#\\$%\\^&\\*\\") + "(\\)-_=\\+;:<>\\/\\\\|\\}\\{\\[\\]`~]*")); if (date.toString() != "") check += "\n" + tr("Released on: ") + date.toString(); check += "\n\n" + tr("Does this look correct?"); int answer = QMessageBox::question(parent, QObject::tr("Game Information Download"), check, QMessageBox::Yes | QMessageBox::No); if (answer == QMessageBox::Yes) { found = count; updated = true; break; } } else { //We only want one game, so search for a perfect match in the GameTitle element. //Otherwise this will default to 0 (the first game found) if(title.toString() == searchName) found = count; } count++; } if (!force || updated) { QJsonObject foundGame = gamesArray.at(found).toObject(); QJsonObject saveData; QString gameID = QString::number(foundGame.value("id").toInt()); QJsonObject boxart = json.value("include").toObject().value("boxart").toObject(); QString thumbURL = boxart.value("base_url").toObject().value("thumb").toString(); QJsonArray imgArray = boxart.value("data").toObject().value(gameID).toArray(); QString frontImg = ""; foreach (QJsonValue img, imgArray) { QString type = img.toObject().value("type").toString(); QString side = img.toObject().value("side").toString(); QString filename = img.toObject().value("filename").toString(); if (type == "boxart" && side == "front") frontImg = thumbURL + filename; } //Convert IDs from API to text names QString genresString = convertIDs(foundGame, "genres", "Genres"); QString developerString = convertIDs(foundGame, "developers", "Developers"); QString publisherString = convertIDs(foundGame, "publishers", "Publishers"); saveData.insert("game_title", foundGame.value("game_title").toString()); saveData.insert("release_date", foundGame.value("release_date").toString()); saveData.insert("rating", foundGame.value("rating").toString()); saveData.insert("overview", foundGame.value("overview").toString()); saveData.insert("players", QString::number(foundGame.value("players").toInt())); saveData.insert("boxart", frontImg); saveData.insert("genres", genresString); saveData.insert("developer", developerString); saveData.insert("publisher", publisherString); QJsonDocument document(saveData); file.open(QIODevice::WriteOnly); file.write(document.toJson()); file.close(); } if (force && !updated) { QString message; if (count == 0) message = QObject::tr("No results found."); else message = QObject::tr("No more results found."); QMessageBox::information(parent, QObject::tr("Game Information Download"), message); } } //Get front cover QString boxartURL = ""; QString boxartExt = ""; QString coverFile = gameCache + "/boxart-front."; QFile coverJPG(coverFile + "jpg"); QFile coverPNG(coverFile + "png"); if ((!coverJPG.exists() && !coverPNG.exists()) || (force && updated)) { file.open(QIODevice::ReadOnly); QString data = file.readAll(); file.close(); QJsonDocument document = QJsonDocument::fromJson(data.toUtf8()); QJsonObject json = document.object(); QString boxartURL = json.value("boxart").toString(); if (boxartURL != "") { QUrl url(boxartURL); //Delete current box art QFile::remove(coverFile + "jpg"); QFile::remove(coverFile + "png"); //Check to save as JPG or PNG boxartExt = QFileInfo(boxartURL).completeSuffix().toLower(); QFile cover(coverFile + boxartExt); cover.open(QIODevice::WriteOnly); cover.write(getUrlContents(url)); cover.close(); } } if (updated) QMessageBox::information(parent, QObject::tr("Game Information Download"), QObject::tr("Download Complete!")); if (force) parent->setEnabled(true); } } QByteArray TheGamesDBScraper::getUrlContents(QUrl url) { QNetworkAccessManager *manager = new QNetworkAccessManager; QNetworkRequest request; request.setUrl(url); request.setRawHeader("User-Agent", AppName.toUtf8().constData()); QNetworkReply *reply = manager->get(request); QTimer timer; timer.setSingleShot(true); QEventLoop loop; connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); int time = SETTINGS.value("Other/networktimeout", 10).toInt(); if (time == 0) time = 10; time *= 1000; timer.start(time); loop.exec(); if(timer.isActive()) { //Got reply timer.stop(); if(reply->error() > 0) showError(reply->errorString()); else return reply->readAll(); } else //Request timed out showError(tr("Request timed out. Check your network settings.")); return QByteArray(); } void TheGamesDBScraper::showError(QString error) { QString question = "\n\n" + tr("Continue scraping information?"); if (force) QMessageBox::information(parent, tr("Network Error"), error); else { int answer = QMessageBox::question(parent, tr("Network Error"), error + question, QMessageBox::Yes | QMessageBox::No); if (answer == QMessageBox::No) keepGoing = false; } } void TheGamesDBScraper::updateListCache(QFile *file, QString list) { QUrl url; url.setUrl("https://api.thegamesdb.net/" + list + "?apikey=" + TheGamesDBAPIKey); QString data = getUrlContents(url); QJsonDocument document = QJsonDocument::fromJson(data.toUtf8()); QJsonDocument result(document.object().value("data").toObject().value(list.toLower()).toObject()); file->open(QIODevice::WriteOnly); file->write(result.toJson()); file->close(); } <|endoftext|>
<commit_before>#include "stdafx.h" #include "util/fixes.h" #include "dispatcher.h" #include "condition.h" #include "gamesystems/objects/objsystem.h" #include "ui/ui_systems.h" #include "ui/ui_legacysystems.h" #define CONDFIX(fname) static int fname ## (DispatcherCallbackArgs args); #define HOOK_ORG(fname) static int (__cdecl* org ##fname)(DispatcherCallbackArgs) = replaceFunction<int(__cdecl)(DispatcherCallbackArgs)> class GeneralConditionFixes : public TempleFix { public: static int WeaponKeenQuery(DispatcherCallbackArgs args); void apply() override { { // Fix for duplicate Blackguard tooltip when fallen paladin SubDispDefNew sdd; sdd.dispKey = DK_NONE; sdd.dispType = dispTypeEffectTooltip; sdd.dispCallback = [](DispatcherCallbackArgs args) { GET_DISPIO(dispIOTypeEffectTooltip, DispIoEffectTooltip); if (objects.StatLevelGet(args.objHndCaller, stat_level_blackguard)) return 0; dispIo->Append(args.GetData1(), -1, nullptr); return 0; }; write(0x102E7400, &sdd, sizeof(sdd)); } replaceFunction(0x100FF670, WeaponKeenQuery); } } genCondFixes; int GeneralConditionFixes::WeaponKeenQuery(DispatcherCallbackArgs args){ GET_DISPIO(dispIOTypeQuery, DispIoD20Query); dispIo->return_val = 2; // default auto itemHndl = uiSystems->GetChar().GetTooltipItem(); if (!itemHndl || !objSystem->IsValidHandle(itemHndl)) return 0; // meh, it doesn't have a handle /*auto invIdx = args.GetCondArg(2); auto itemHndl = inventory.GetItemAtInvIdx(args.objHndCaller, invIdx); if (!itemHndl || !objSystem->IsValidHandle(itemHndl)) return 0; */ auto item = objSystem->GetObject(itemHndl); auto critRange = item->GetInt32(obj_f_weapon_crit_range); dispIo->return_val = critRange; return 0; } <commit_msg>Fixed bad Fallen Paladin effect tooltip<commit_after>#include "stdafx.h" #include "util/fixes.h" #include "dispatcher.h" #include "condition.h" #include "gamesystems/objects/objsystem.h" #include "ui/ui_systems.h" #include "ui/ui_legacysystems.h" #define CONDFIX(fname) static int fname ## (DispatcherCallbackArgs args); #define HOOK_ORG(fname) static int (__cdecl* org ##fname)(DispatcherCallbackArgs) = replaceFunction<int(__cdecl)(DispatcherCallbackArgs)> class GeneralConditionFixes : public TempleFix { public: static int WeaponKeenQuery(DispatcherCallbackArgs args); void apply() override { { // Fix for duplicate Blackguard tooltip when fallen paladin SubDispDefNew sdd; sdd.dispKey = DK_NONE; sdd.dispType = dispTypeEffectTooltip; sdd.dispCallback = [](DispatcherCallbackArgs args) { GET_DISPIO(dispIOTypeEffectTooltip, DispIoEffectTooltip); if (objects.StatLevelGet(args.objHndCaller, stat_level_blackguard)) return 0; dispIo->Append(args.GetData1(), -1, nullptr); return 0; }; sdd.data1.sVal = 0xAF; write(0x102E7400, &sdd, sizeof(sdd)); } replaceFunction(0x100FF670, WeaponKeenQuery); } } genCondFixes; int GeneralConditionFixes::WeaponKeenQuery(DispatcherCallbackArgs args){ GET_DISPIO(dispIOTypeQuery, DispIoD20Query); dispIo->return_val = 2; // default auto itemHndl = uiSystems->GetChar().GetTooltipItem(); if (!itemHndl || !objSystem->IsValidHandle(itemHndl)) return 0; // meh, it doesn't have a handle /*auto invIdx = args.GetCondArg(2); auto itemHndl = inventory.GetItemAtInvIdx(args.objHndCaller, invIdx); if (!itemHndl || !objSystem->IsValidHandle(itemHndl)) return 0; */ auto item = objSystem->GetObject(itemHndl); auto critRange = item->GetInt32(obj_f_weapon_crit_range); dispIo->return_val = critRange; return 0; } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd 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 "ZipArchiveTests.h" #include "OgreZip.h" #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE #include "macUtils.h" #endif using namespace Ogre; // Register the suite CPPUNIT_TEST_SUITE_REGISTRATION( ZipArchiveTests ); void ZipArchiveTests::setUp() { #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE testPath = macBundlePath() + "/Contents/Resources/Media/misc/ArchiveTest.zip"; #elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32 testPath = "./Tests/OgreMain/misc/ArchiveTest.zip"; #else testPath = "../Tests/OgreMain/misc/ArchiveTest.zip"; #endif } void ZipArchiveTests::tearDown() { } void ZipArchiveTests::testListNonRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); StringVectorPtr vec = arch.list(false); CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size()); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(0)); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(1)); } void ZipArchiveTests::testListRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); StringVectorPtr vec = arch.list(true); CPPUNIT_ASSERT_EQUAL((size_t)6, vec->size()); CPPUNIT_ASSERT_EQUAL(String("file.material"), vec->at(0)); CPPUNIT_ASSERT_EQUAL(String("file2.material"), vec->at(1)); CPPUNIT_ASSERT_EQUAL(String("file3.material"), vec->at(2)); CPPUNIT_ASSERT_EQUAL(String("file4.material"), vec->at(3)); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(4)); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(5)); } void ZipArchiveTests::testListFileInfoNonRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); FileInfoListPtr vec = arch.listFileInfo(false); CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size()); FileInfo& fi1 = vec->at(0); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path); CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize); FileInfo& fi2 = vec->at(1); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path); CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize); } void ZipArchiveTests::testListFileInfoRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); FileInfoListPtr vec = arch.listFileInfo(true); CPPUNIT_ASSERT_EQUAL((size_t)6, vec->size()); FileInfo& fi3 = vec->at(0); CPPUNIT_ASSERT_EQUAL(String("file.material"), fi3.filename); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi3.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.uncompressedSize); FileInfo& fi4 = vec->at(1); CPPUNIT_ASSERT_EQUAL(String("file2.material"), fi4.filename); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi4.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.uncompressedSize); FileInfo& fi5 = vec->at(2); CPPUNIT_ASSERT_EQUAL(String("file3.material"), fi5.filename); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi5.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.uncompressedSize); FileInfo& fi6 = vec->at(3); CPPUNIT_ASSERT_EQUAL(String("file4.material"), fi6.filename); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi6.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.uncompressedSize); FileInfo& fi1 = vec->at(4); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path); CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize); FileInfo& fi2 = vec->at(5); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path); CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize); } void ZipArchiveTests::testFindNonRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); StringVectorPtr vec = arch.find("*.txt", false); CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size()); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(0)); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(1)); } void ZipArchiveTests::testFindRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); StringVectorPtr vec = arch.find("*.material", true); CPPUNIT_ASSERT_EQUAL((size_t)4, vec->size()); CPPUNIT_ASSERT_EQUAL(String("file.material"), vec->at(0)); CPPUNIT_ASSERT_EQUAL(String("file2.material"), vec->at(1)); CPPUNIT_ASSERT_EQUAL(String("file3.material"), vec->at(2)); CPPUNIT_ASSERT_EQUAL(String("file4.material"), vec->at(3)); } void ZipArchiveTests::testFindFileInfoNonRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); FileInfoListPtr vec = arch.findFileInfo("*.txt", false); CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size()); FileInfo& fi1 = vec->at(0); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path); CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize); FileInfo& fi2 = vec->at(1); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path); CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize); } void ZipArchiveTests::testFindFileInfoRecursive() { ZipArchive arch(testPath, "Zip"); arch.load(); FileInfoListPtr vec = arch.findFileInfo("*.material", true); CPPUNIT_ASSERT_EQUAL((size_t)4, vec->size()); FileInfo& fi3 = vec->at(0); CPPUNIT_ASSERT_EQUAL(String("file.material"), fi3.filename); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi3.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.uncompressedSize); FileInfo& fi4 = vec->at(1); CPPUNIT_ASSERT_EQUAL(String("file2.material"), fi4.filename); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi4.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.uncompressedSize); FileInfo& fi5 = vec->at(2); CPPUNIT_ASSERT_EQUAL(String("file3.material"), fi5.filename); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi5.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.uncompressedSize); FileInfo& fi6 = vec->at(3); CPPUNIT_ASSERT_EQUAL(String("file4.material"), fi6.filename); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi6.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.uncompressedSize); } void ZipArchiveTests::testFileRead() { ZipArchive arch(testPath, "Zip"); arch.load(); DataStreamPtr stream = arch.open("rootfile.txt"); CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 1"), stream->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 1"), stream->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 1"), stream->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 1"), stream->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 1"), stream->getLine()); CPPUNIT_ASSERT(stream->eof()); } void ZipArchiveTests::testReadInterleave() { // Test overlapping reads from same archive ZipArchive arch(testPath, "Zip"); arch.load(); // File 1 DataStreamPtr stream1 = arch.open("rootfile.txt"); CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 1"), stream1->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 1"), stream1->getLine()); // File 2 DataStreamPtr stream2 = arch.open("rootfile2.txt"); CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 2"), stream2->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 2"), stream2->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 2"), stream2->getLine()); // File 1 CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 1"), stream1->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 1"), stream1->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 1"), stream1->getLine()); CPPUNIT_ASSERT(stream1->eof()); // File 2 CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 2"), stream2->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 2"), stream2->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 6 in file 2"), stream2->getLine()); CPPUNIT_ASSERT(stream2->eof()); } <commit_msg>Add fallback path for ZipArchiveTests.<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd 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 "ZipArchiveTests.h" #include "OgreZip.h" #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE #include "macUtils.h" #endif using namespace Ogre; // Register the suite CPPUNIT_TEST_SUITE_REGISTRATION( ZipArchiveTests ); void ZipArchiveTests::setUp() { #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE testPath = macBundlePath() + "/Contents/Resources/Media/misc/ArchiveTest.zip"; #elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32 testPath = "./Tests/OgreMain/misc/ArchiveTest.zip"; #else testPath = "../Tests/OgreMain/misc/ArchiveTest.zip"; #endif } void ZipArchiveTests::tearDown() { } void ZipArchiveTests::testListNonRecursive() { ZipArchive arch(testPath, "Zip"); try { arch.load(); } catch (Ogre::Exception e) { // If it starts in build/bin/debug arch = ZipArchive("../../../" + testPath, "Zip"); arch.load(); } StringVectorPtr vec = arch.list(false); CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size()); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(0)); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(1)); } void ZipArchiveTests::testListRecursive() { ZipArchive arch(testPath, "Zip"); try { arch.load(); } catch (Ogre::Exception e) { // If it starts in build/bin/debug arch = ZipArchive("../../../" + testPath, "Zip"); arch.load(); } StringVectorPtr vec = arch.list(true); CPPUNIT_ASSERT_EQUAL((size_t)6, vec->size()); CPPUNIT_ASSERT_EQUAL(String("file.material"), vec->at(0)); CPPUNIT_ASSERT_EQUAL(String("file2.material"), vec->at(1)); CPPUNIT_ASSERT_EQUAL(String("file3.material"), vec->at(2)); CPPUNIT_ASSERT_EQUAL(String("file4.material"), vec->at(3)); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(4)); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(5)); } void ZipArchiveTests::testListFileInfoNonRecursive() { ZipArchive arch(testPath, "Zip"); try { arch.load(); } catch (Ogre::Exception e) { // If it starts in build/bin/debug arch = ZipArchive("../../../" + testPath, "Zip"); arch.load(); } FileInfoListPtr vec = arch.listFileInfo(false); CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size()); FileInfo& fi1 = vec->at(0); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path); CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize); FileInfo& fi2 = vec->at(1); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path); CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize); } void ZipArchiveTests::testListFileInfoRecursive() { ZipArchive arch(testPath, "Zip"); try { arch.load(); } catch (Ogre::Exception e) { // If it starts in build/bin/debug arch = ZipArchive("../../../" + testPath, "Zip"); arch.load(); } FileInfoListPtr vec = arch.listFileInfo(true); CPPUNIT_ASSERT_EQUAL((size_t)6, vec->size()); FileInfo& fi3 = vec->at(0); CPPUNIT_ASSERT_EQUAL(String("file.material"), fi3.filename); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi3.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.uncompressedSize); FileInfo& fi4 = vec->at(1); CPPUNIT_ASSERT_EQUAL(String("file2.material"), fi4.filename); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi4.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.uncompressedSize); FileInfo& fi5 = vec->at(2); CPPUNIT_ASSERT_EQUAL(String("file3.material"), fi5.filename); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi5.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.uncompressedSize); FileInfo& fi6 = vec->at(3); CPPUNIT_ASSERT_EQUAL(String("file4.material"), fi6.filename); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi6.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.uncompressedSize); FileInfo& fi1 = vec->at(4); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path); CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize); FileInfo& fi2 = vec->at(5); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path); CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize); } void ZipArchiveTests::testFindNonRecursive() { ZipArchive arch(testPath, "Zip"); try { arch.load(); } catch (Ogre::Exception e) { // If it starts in build/bin/debug arch = ZipArchive("../../../" + testPath, "Zip"); arch.load(); } StringVectorPtr vec = arch.find("*.txt", false); CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size()); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(0)); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(1)); } void ZipArchiveTests::testFindRecursive() { ZipArchive arch(testPath, "Zip"); try { arch.load(); } catch (Ogre::Exception e) { // If it starts in build/bin/debug arch = ZipArchive("../../../" + testPath, "Zip"); arch.load(); } StringVectorPtr vec = arch.find("*.material", true); CPPUNIT_ASSERT_EQUAL((size_t)4, vec->size()); CPPUNIT_ASSERT_EQUAL(String("file.material"), vec->at(0)); CPPUNIT_ASSERT_EQUAL(String("file2.material"), vec->at(1)); CPPUNIT_ASSERT_EQUAL(String("file3.material"), vec->at(2)); CPPUNIT_ASSERT_EQUAL(String("file4.material"), vec->at(3)); } void ZipArchiveTests::testFindFileInfoNonRecursive() { ZipArchive arch(testPath, "Zip"); try { arch.load(); } catch (Ogre::Exception e) { // If it starts in build/bin/debug arch = ZipArchive("../../../" + testPath, "Zip"); arch.load(); } FileInfoListPtr vec = arch.findFileInfo("*.txt", false); CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size()); FileInfo& fi1 = vec->at(0); CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path); CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize); FileInfo& fi2 = vec->at(1); CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename); CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path); CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize); } void ZipArchiveTests::testFindFileInfoRecursive() { ZipArchive arch(testPath, "Zip"); try { arch.load(); } catch (Ogre::Exception e) { // If it starts in build/bin/debug arch = ZipArchive("../../../" + testPath, "Zip"); arch.load(); } FileInfoListPtr vec = arch.findFileInfo("*.material", true); CPPUNIT_ASSERT_EQUAL((size_t)4, vec->size()); FileInfo& fi3 = vec->at(0); CPPUNIT_ASSERT_EQUAL(String("file.material"), fi3.filename); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi3.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.uncompressedSize); FileInfo& fi4 = vec->at(1); CPPUNIT_ASSERT_EQUAL(String("file2.material"), fi4.filename); CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi4.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.uncompressedSize); FileInfo& fi5 = vec->at(2); CPPUNIT_ASSERT_EQUAL(String("file3.material"), fi5.filename); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi5.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.uncompressedSize); FileInfo& fi6 = vec->at(3); CPPUNIT_ASSERT_EQUAL(String("file4.material"), fi6.filename); CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi6.path); CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.compressedSize); CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.uncompressedSize); } void ZipArchiveTests::testFileRead() { ZipArchive arch(testPath, "Zip"); try { arch.load(); } catch (Ogre::Exception e) { // If it starts in build/bin/debug arch = ZipArchive("../../../" + testPath, "Zip"); arch.load(); } DataStreamPtr stream = arch.open("rootfile.txt"); CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 1"), stream->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 1"), stream->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 1"), stream->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 1"), stream->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 1"), stream->getLine()); CPPUNIT_ASSERT(stream->eof()); } void ZipArchiveTests::testReadInterleave() { // Test overlapping reads from same archive ZipArchive arch(testPath, "Zip"); try { arch.load(); } catch (Ogre::Exception e) { // If it starts in build/bin/debug arch = ZipArchive("../../../" + testPath, "Zip"); arch.load(); } // File 1 DataStreamPtr stream1 = arch.open("rootfile.txt"); CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 1"), stream1->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 1"), stream1->getLine()); // File 2 DataStreamPtr stream2 = arch.open("rootfile2.txt"); CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 2"), stream2->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 2"), stream2->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 2"), stream2->getLine()); // File 1 CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 1"), stream1->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 1"), stream1->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 1"), stream1->getLine()); CPPUNIT_ASSERT(stream1->eof()); // File 2 CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 2"), stream2->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 2"), stream2->getLine()); CPPUNIT_ASSERT_EQUAL(String("this is line 6 in file 2"), stream2->getLine()); CPPUNIT_ASSERT(stream2->eof()); } <|endoftext|>
<commit_before>#include <ContentForgeTool.h> #include <Utils.h> //#include <ParamsUtils.h> //#include <CLI11.hpp> #include <Recast.h> #include <DetourNavMesh.h> // For max vertices per polygon constant #include <DetourNavMeshBuilder.h> namespace fs = std::filesystem; // Set working directory to $(TargetDir) // Example args: // -s src/FIXME class CNavmeshTool : public CContentForgeTool { protected: public: CNavmeshTool(const std::string& Name, const std::string& Desc, CVersion Version) : CContentForgeTool(Name, Desc, Version) { } virtual bool SupportsMultithreading() const override { // FIXME: must handle duplicate targets (for example 2 metafiles writing the same resulting file, like depth_atest_ps) // FIXME: CStrID return false; } virtual int Init() override { return 0; } virtual void ProcessCommandLine(CLI::App& CLIApp) override { CContentForgeTool::ProcessCommandLine(CLIApp); } virtual bool ProcessTask(CContentForgeTask& Task) override { // TODO: check whether the metafile can be processed by this tool const std::string TaskName = GetValidResourceName(Task.TaskID.ToString()); //???use level + world or incoming data must be a ready-made list of .scn + root world tfm for each? //can feed from game or editor, usiversal, requires no ECS knowledge and suports ofmeshes well // iterate all scn with static data for the level // collect collision shapes and/or visible geometry // add geometry from static entities (static is a flag in a CSceneComponent) // add offmesh links // add typed areas constexpr int MAX_CONVEXVOL_PTS = 12; struct CConvexVolume { float verts[MAX_CONVEXVOL_PTS*3]; float hmin, hmax; int nverts; int areaId; }; static const int MAX_OFFMESH_CONNECTIONS = 256; float offMeshConVerts[MAX_OFFMESH_CONNECTIONS*3*2]; float offMeshConRads[MAX_OFFMESH_CONNECTIONS]; unsigned char offMeshConDirs[MAX_OFFMESH_CONNECTIONS]; unsigned char offMeshConAreas[MAX_OFFMESH_CONNECTIONS]; unsigned short offMeshConFlags[MAX_OFFMESH_CONNECTIONS]; unsigned int offMeshConId[MAX_OFFMESH_CONNECTIONS]; int offMeshConCount = 0; const float* verts = nullptr; const int nverts = 0; const int* tris = nullptr; const int ntris = 0; std::vector<CConvexVolume> vols; float bmax[3]; float bmin[3]; // NB: the code below is copied from RecastDemo (Sample_SoloMesh.cpp) with slight changes // Step 1. Initialize build config. rcContext ctx; //!!!build navmesh for each agent's R+h! agent selects all h >= its h and from them the closest R >= its R const float agentHeight = 1.8f; const float agentRadius = 0.3f; const float agentMaxClimb = 0.2f; //!!!level's interactive bounds must be used! also can use rcCalcBounds const float MaxHorzBound = std::max(bmax[0] - bmin[0], bmax[2] - bmin[2]); //!!!TODO: most of these things must be in settings! const float cellSize = MaxHorzBound * 0.00029f; //???how to choose good value? demo has 0.1 to 1.0, default 0.3 const float cellHeight = 0.2f; const float edgeMaxLen = 12.f; const float edgeMaxError = 1.3f; const int regionMinSize = (int)(MaxHorzBound * 0.0075f + 0.5f); // 0.5f to round 1.5 to 2; demo has 0 to 150, default 8 const int regionMergeSize = 20; // demo has 0 to 150, default 20 const float detailSampleDist = 6.f; const float detailSampleMaxError = 1.f; rcConfig cfg; memset(&cfg, 0, sizeof(cfg)); cfg.cs = cellSize; cfg.ch = cellHeight; cfg.walkableSlopeAngle = 60.f; cfg.walkableHeight = (int)ceilf(agentHeight / cfg.ch); cfg.walkableClimb = (int)floorf(agentMaxClimb / cfg.ch); cfg.walkableRadius = (int)ceilf(agentRadius / cfg.cs); cfg.maxEdgeLen = (int)(edgeMaxLen / cfg.cs); cfg.maxSimplificationError = edgeMaxError; cfg.minRegionArea = rcSqr(regionMinSize); // Note: area = size*size cfg.mergeRegionArea = rcSqr(regionMergeSize); // Note: area = size*size cfg.maxVertsPerPoly = DT_VERTS_PER_POLYGON; cfg.detailSampleDist = detailSampleDist < 0.9f ? 0.f : cfg.cs * detailSampleDist; cfg.detailSampleMaxError = cfg.ch * detailSampleMaxError; //!!!level's interactive bounds must be used! rcVcopy(cfg.bmin, bmin); rcVcopy(cfg.bmax, bmax); rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height); // Step 2. Rasterize input polygon soup. auto solid = rcAllocHeightfield(); if (!rcCreateHeightfield(&ctx, *solid, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch)) { //ctx->log(RC_LOG_ERROR, "buildNavigation: Could not create solid heightfield."); return false; } std::unique_ptr<unsigned char[]> triareas(new unsigned char[ntris]); memset(triareas.get(), 0, ntris * sizeof(unsigned char)); rcMarkWalkableTriangles(&ctx, cfg.walkableSlopeAngle, verts, nverts, tris, ntris, triareas.get()); if (!rcRasterizeTriangles(&ctx, verts, nverts, tris, triareas.get(), ntris, *solid, cfg.walkableClimb)) { //ctx->log(RC_LOG_ERROR, "buildNavigation: Could not rasterize triangles."); return false; } triareas.reset(); // Step 3. Filter walkables surfaces. rcFilterLowHangingWalkableObstacles(&ctx, cfg.walkableClimb, *solid); rcFilterLedgeSpans(&ctx, cfg.walkableHeight, cfg.walkableClimb, *solid); rcFilterWalkableLowHeightSpans(&ctx, cfg.walkableHeight, *solid); // Step 4. Partition walkable surface to simple regions. auto chf = rcAllocCompactHeightfield(); if (!rcBuildCompactHeightfield(&ctx, cfg.walkableHeight, cfg.walkableClimb, *solid, *chf)) { //ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build compact data."); return false; } rcFreeHeightField(solid); if (!rcErodeWalkableArea(&ctx, cfg.walkableRadius, *chf)) { //ctx->log(RC_LOG_ERROR, "buildNavigation: Could not erode."); return false; } for (const auto& vol : vols) rcMarkConvexPolyArea(&ctx, vol.verts, vol.nverts, vol.hmin, vol.hmax, (unsigned char)vol.areaId, *chf); if (!rcBuildDistanceField(&ctx, *chf)) { //ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build distance field."); return false; } if (!rcBuildRegions(&ctx, *chf, 0, cfg.minRegionArea, cfg.mergeRegionArea)) { //ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build watershed regions."); return false; } // Step 5. Trace and simplify region contours. auto cset = rcAllocContourSet(); if (!rcBuildContours(&ctx, *chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *cset)) { //ctx->log(RC_LOG_ERROR, "buildNavigation: Could not create contours."); return false; } // Step 6. Build polygons mesh from contours. auto pmesh = rcAllocPolyMesh(); if (!rcBuildPolyMesh(&ctx, *cset, cfg.maxVertsPerPoly, *pmesh)) { //ctx->log(RC_LOG_ERROR, "buildNavigation: Could not triangulate contours."); return false; } // Step 7. Create detail mesh which allows to access approximate height on each polygon. //???optional? auto dmesh = rcAllocPolyMeshDetail(); if (!rcBuildPolyMeshDetail(&ctx, *pmesh, *chf, cfg.detailSampleDist, cfg.detailSampleMaxError, *dmesh)) { //ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build detail mesh."); return false; } rcFreeCompactHeightfield(chf); rcFreeContourSet(cset); // (Optional) Step 8. Create Detour data from Recast poly mesh. // Update poly flags from areas. for (int i = 0; i < pmesh->npolys; ++i) { /* if (pmesh->areas[i] == RC_WALKABLE_AREA) pmesh->areas[i] = SAMPLE_POLYAREA_GROUND; if (pmesh->areas[i] == SAMPLE_POLYAREA_GROUND || pmesh->areas[i] == SAMPLE_POLYAREA_GRASS || pmesh->areas[i] == SAMPLE_POLYAREA_ROAD) { pmesh->flags[i] = SAMPLE_POLYFLAGS_WALK; } else if (pmesh->areas[i] == SAMPLE_POLYAREA_WATER) { pmesh->flags[i] = SAMPLE_POLYFLAGS_SWIM; } else if (pmesh->areas[i] == SAMPLE_POLYAREA_DOOR) { pmesh->flags[i] = SAMPLE_POLYFLAGS_WALK | SAMPLE_POLYFLAGS_DOOR; } */ } dtNavMeshCreateParams params; memset(&params, 0, sizeof(params)); params.verts = pmesh->verts; params.vertCount = pmesh->nverts; params.polys = pmesh->polys; params.polyAreas = pmesh->areas; params.polyFlags = pmesh->flags; params.polyCount = pmesh->npolys; params.nvp = pmesh->nvp; params.detailMeshes = dmesh->meshes; params.detailVerts = dmesh->verts; params.detailVertsCount = dmesh->nverts; params.detailTris = dmesh->tris; params.detailTriCount = dmesh->ntris; params.offMeshConVerts = offMeshConVerts; params.offMeshConRad = offMeshConRads; params.offMeshConDir = offMeshConDirs; params.offMeshConAreas = offMeshConAreas; params.offMeshConFlags = offMeshConFlags; params.offMeshConUserID = offMeshConId; params.offMeshConCount = offMeshConCount; params.walkableHeight = agentHeight; params.walkableRadius = agentRadius; params.walkableClimb = agentMaxClimb; rcVcopy(params.bmin, pmesh->bmin); rcVcopy(params.bmax, pmesh->bmax); params.cs = cfg.cs; params.ch = cfg.ch; params.buildBvTree = true; unsigned char* navData = nullptr; int navDataSize = 0; if (!dtCreateNavMeshData(&params, &navData, &navDataSize)) { //ctx->log(RC_LOG_ERROR, "Could not build Detour navmesh."); return false; } // create output folder // save separate nm file for each R+h // Old format was: // Magic // Version // NM count // Per NM: // R // h // Data size // Data // Named region count // Per named convex volume: // Poly count // Poly refs dtFree(navData); return true; } }; int main(int argc, const char** argv) { CNavmeshTool Tool("cf-navmesh", "Navigation mesh generator for static level geometry", { 0, 1, 0 }); return Tool.Execute(argc, argv); } <commit_msg>Tools: navmesh config reading<commit_after>#include <ContentForgeTool.h> #include <Utils.h> #include <ParamsUtils.h> //#include <CLI11.hpp> #include <Recast.h> #include <DetourNavMesh.h> // For max vertices per polygon constant #include <DetourNavMeshBuilder.h> namespace fs = std::filesystem; // Set working directory to $(TargetDir) // Example args: // -s src/game/levels class CNavmeshTool : public CContentForgeTool { protected: public: CNavmeshTool(const std::string& Name, const std::string& Desc, CVersion Version) : CContentForgeTool(Name, Desc, Version) { } virtual bool SupportsMultithreading() const override { // FIXME: must handle duplicate targets (for example 2 metafiles writing the same resulting file, like depth_atest_ps) // FIXME: CStrID return false; } virtual int Init() override { return 0; } virtual void ProcessCommandLine(CLI::App& CLIApp) override { CContentForgeTool::ProcessCommandLine(CLIApp); } virtual bool ProcessTask(CContentForgeTask& Task) override { // TODO: check whether the metafile can be processed by this tool if (ParamsUtils::GetParam(Task.Params, "Tools", std::string{}) != "cf-navmesh") { // FIXME: skip sliently without error. To CF tool base class??? return false; } const std::string TaskName = GetValidResourceName(Task.TaskID.ToString()); // Read navmesh source HRD Data::CParams Desc; if (!ParamsUtils::LoadParamsFromHRD(Task.SrcFilePath.string().c_str(), Desc)) { if (_LogVerbosity >= EVerbosity::Errors) Task.Log.LogError(Task.SrcFilePath.generic_string() + " HRD loading or parsing error"); return false; } //???use level + world or incoming data must be a ready-made list of .scn + root world tfm for each? //can feed from game or editor, usiversal, requires no ECS knowledge and suports ofmeshes well // iterate all scn with static data for the level // collect collision shapes and/or visible geometry // add geometry from static entities (static is a flag in a CSceneComponent) // add offmesh links // add typed areas constexpr int MAX_CONVEXVOL_PTS = 12; struct CConvexVolume { float verts[MAX_CONVEXVOL_PTS*3]; float hmin, hmax; int nverts; int areaId; }; static const int MAX_OFFMESH_CONNECTIONS = 256; float offMeshConVerts[MAX_OFFMESH_CONNECTIONS*3*2]; float offMeshConRads[MAX_OFFMESH_CONNECTIONS]; unsigned char offMeshConDirs[MAX_OFFMESH_CONNECTIONS]; unsigned char offMeshConAreas[MAX_OFFMESH_CONNECTIONS]; unsigned short offMeshConFlags[MAX_OFFMESH_CONNECTIONS]; unsigned int offMeshConId[MAX_OFFMESH_CONNECTIONS]; int offMeshConCount = 0; const float* verts = nullptr; const int nverts = 0; const int* tris = nullptr; const int ntris = 0; std::vector<CConvexVolume> vols; //!!!level's interactive bounds must be used! also can use rcCalcBounds float bmax[3]; float bmin[3]; // NB: the code below is copied from RecastDemo (Sample_SoloMesh.cpp) with slight changes // Step 1. Initialize build config. rcContext ctx; //!!!build navmesh for each agent's R+h! agent selects all h >= its h and from them the closest R >= its R const float agentHeight = ParamsUtils::GetParam(Desc, "AgentHeight", 1.8f); const float agentRadius = ParamsUtils::GetParam(Desc, "AgentRadius", 0.3f); const float agentMaxClimb = ParamsUtils::GetParam(Desc, "AgentMaxClimb", 0.2f); const float agentWalkableSlope = ParamsUtils::GetParam(Desc, "AgentWalkableSlope", 60.f); //!!!TODO: most of these things must be in settings! const float cellSize = ParamsUtils::GetParam(Desc, "CellSize", agentRadius / 3.f); const float cellHeight = ParamsUtils::GetParam(Desc, "CellHeight", cellSize); const float edgeMaxLen = ParamsUtils::GetParam(Desc, "EdgeMaxLength", 12.f); const float edgeMaxError = ParamsUtils::GetParam(Desc, "EdgeMaxError", 1.3f); const int regionMinSize = ParamsUtils::GetParam(Desc, "RegionMinSize", 8); const int regionMergeSize = ParamsUtils::GetParam(Desc, "RegionMergeSize", 8); const float detailSampleDist = ParamsUtils::GetParam(Desc, "DetailSampleDistance", 6.f); const float detailSampleMaxError = ParamsUtils::GetParam(Desc, "DetailSampleMaxError", 1.f); rcConfig cfg; memset(&cfg, 0, sizeof(cfg)); cfg.cs = cellSize; cfg.ch = cellHeight; cfg.walkableSlopeAngle = agentWalkableSlope; cfg.walkableHeight = (int)ceilf(agentHeight / cfg.ch); cfg.walkableClimb = (int)floorf(agentMaxClimb / cfg.ch); cfg.walkableRadius = (int)ceilf(agentRadius / cfg.cs); cfg.maxEdgeLen = (int)(edgeMaxLen / cfg.cs); cfg.maxSimplificationError = edgeMaxError; cfg.minRegionArea = rcSqr(regionMinSize); // Note: area = size*size cfg.mergeRegionArea = rcSqr(regionMergeSize); // Note: area = size*size cfg.maxVertsPerPoly = DT_VERTS_PER_POLYGON; cfg.detailSampleDist = detailSampleDist < 0.9f ? 0.f : cfg.cs * detailSampleDist; cfg.detailSampleMaxError = cfg.ch * detailSampleMaxError; rcVcopy(cfg.bmin, bmin); rcVcopy(cfg.bmax, bmax); rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height); // Step 2. Rasterize input polygon soup. auto solid = rcAllocHeightfield(); if (!rcCreateHeightfield(&ctx, *solid, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch)) { Task.Log.LogError("buildNavigation: Could not create solid heightfield."); return false; } std::unique_ptr<unsigned char[]> triareas(new unsigned char[ntris]); memset(triareas.get(), 0, ntris * sizeof(unsigned char)); rcMarkWalkableTriangles(&ctx, cfg.walkableSlopeAngle, verts, nverts, tris, ntris, triareas.get()); if (!rcRasterizeTriangles(&ctx, verts, nverts, tris, triareas.get(), ntris, *solid, cfg.walkableClimb)) { Task.Log.LogError("buildNavigation: Could not rasterize triangles."); return false; } triareas.reset(); // Step 3. Filter walkables surfaces. rcFilterLowHangingWalkableObstacles(&ctx, cfg.walkableClimb, *solid); rcFilterLedgeSpans(&ctx, cfg.walkableHeight, cfg.walkableClimb, *solid); rcFilterWalkableLowHeightSpans(&ctx, cfg.walkableHeight, *solid); // Step 4. Partition walkable surface to simple regions. auto chf = rcAllocCompactHeightfield(); if (!rcBuildCompactHeightfield(&ctx, cfg.walkableHeight, cfg.walkableClimb, *solid, *chf)) { Task.Log.LogError("buildNavigation: Could not build compact data."); return false; } rcFreeHeightField(solid); if (!rcErodeWalkableArea(&ctx, cfg.walkableRadius, *chf)) { Task.Log.LogError("buildNavigation: Could not erode."); return false; } for (const auto& vol : vols) rcMarkConvexPolyArea(&ctx, vol.verts, vol.nverts, vol.hmin, vol.hmax, (unsigned char)vol.areaId, *chf); if (!rcBuildDistanceField(&ctx, *chf)) { Task.Log.LogError("buildNavigation: Could not build distance field."); return false; } if (!rcBuildRegions(&ctx, *chf, 0, cfg.minRegionArea, cfg.mergeRegionArea)) { Task.Log.LogError("buildNavigation: Could not build watershed regions."); return false; } // Step 5. Trace and simplify region contours. auto cset = rcAllocContourSet(); if (!rcBuildContours(&ctx, *chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *cset)) { Task.Log.LogError("buildNavigation: Could not create contours."); return false; } // Step 6. Build polygons mesh from contours. auto pmesh = rcAllocPolyMesh(); if (!rcBuildPolyMesh(&ctx, *cset, cfg.maxVertsPerPoly, *pmesh)) { Task.Log.LogError("buildNavigation: Could not triangulate contours."); return false; } // Step 7. Create detail mesh which allows to access approximate height on each polygon. //???optional? auto dmesh = rcAllocPolyMeshDetail(); if (!rcBuildPolyMeshDetail(&ctx, *pmesh, *chf, cfg.detailSampleDist, cfg.detailSampleMaxError, *dmesh)) { Task.Log.LogError("buildNavigation: Could not build detail mesh."); return false; } rcFreeCompactHeightfield(chf); rcFreeContourSet(cset); // (Optional) Step 8. Create Detour data from Recast poly mesh. // Update poly flags from areas. for (int i = 0; i < pmesh->npolys; ++i) { /* if (pmesh->areas[i] == RC_WALKABLE_AREA) pmesh->areas[i] = SAMPLE_POLYAREA_GROUND; if (pmesh->areas[i] == SAMPLE_POLYAREA_GROUND || pmesh->areas[i] == SAMPLE_POLYAREA_GRASS || pmesh->areas[i] == SAMPLE_POLYAREA_ROAD) { pmesh->flags[i] = SAMPLE_POLYFLAGS_WALK; } else if (pmesh->areas[i] == SAMPLE_POLYAREA_WATER) { pmesh->flags[i] = SAMPLE_POLYFLAGS_SWIM; } else if (pmesh->areas[i] == SAMPLE_POLYAREA_DOOR) { pmesh->flags[i] = SAMPLE_POLYFLAGS_WALK | SAMPLE_POLYFLAGS_DOOR; } */ } dtNavMeshCreateParams params; memset(&params, 0, sizeof(params)); params.verts = pmesh->verts; params.vertCount = pmesh->nverts; params.polys = pmesh->polys; params.polyAreas = pmesh->areas; params.polyFlags = pmesh->flags; params.polyCount = pmesh->npolys; params.nvp = pmesh->nvp; params.detailMeshes = dmesh->meshes; params.detailVerts = dmesh->verts; params.detailVertsCount = dmesh->nverts; params.detailTris = dmesh->tris; params.detailTriCount = dmesh->ntris; params.offMeshConVerts = offMeshConVerts; params.offMeshConRad = offMeshConRads; params.offMeshConDir = offMeshConDirs; params.offMeshConAreas = offMeshConAreas; params.offMeshConFlags = offMeshConFlags; params.offMeshConUserID = offMeshConId; params.offMeshConCount = offMeshConCount; params.walkableHeight = agentHeight; params.walkableRadius = agentRadius; params.walkableClimb = agentMaxClimb; rcVcopy(params.bmin, pmesh->bmin); rcVcopy(params.bmax, pmesh->bmax); params.cs = cfg.cs; params.ch = cfg.ch; params.buildBvTree = true; unsigned char* navData = nullptr; int navDataSize = 0; if (!dtCreateNavMeshData(&params, &navData, &navDataSize)) { Task.Log.LogError("Could not build Detour navmesh."); return false; } // create output folder // save separate nm file for each R+h // Old format was: // Magic // Version // NM count // Per NM: // R // h // Data size // Data // Named region count // Per named convex volume: // Poly count // Poly refs dtFree(navData); return true; } }; int main(int argc, const char** argv) { CNavmeshTool Tool("cf-navmesh", "Navigation mesh generator for static level geometry", { 0, 1, 0 }); return Tool.Execute(argc, argv); } <|endoftext|>
<commit_before>/* * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SocketAddress.h" #include "NetworkInterface.h" #include "NetworkStack.h" #include <string.h> #include "mbed.h" static bool ipv6_is_valid(const char *addr) { return false; } static int ipv6_scan_chunk(uint16_t *shorts, const char *chunk) { return 0; } SocketAddress::SocketAddress(nsapi_addr_t addr, uint16_t port) { } SocketAddress::SocketAddress(const char *addr, uint16_t port) { } SocketAddress::SocketAddress(const void *bytes, nsapi_version_t version, uint16_t port) { } SocketAddress::SocketAddress(const SocketAddress &addr) { } SocketAddress::~SocketAddress() { } bool SocketAddress::set_ip_address(const char *addr) { return false; } void SocketAddress::set_ip_bytes(const void *bytes, nsapi_version_t version) { } void SocketAddress::set_addr(nsapi_addr_t addr) { } void SocketAddress::set_port(uint16_t port) { } const char *SocketAddress::get_ip_address() const { return NULL; } const void *SocketAddress::get_ip_bytes() const { return NULL; } nsapi_version_t SocketAddress::get_ip_version() const { nsapi_version_t ver = NSAPI_IPv6; return ver; } nsapi_addr_t SocketAddress::get_addr() const { nsapi_addr_t addr; addr.version = NSAPI_IPv6; return _addr; } uint16_t SocketAddress::get_port() const { return 0; } SocketAddress::operator bool() const { return false; } SocketAddress &SocketAddress::operator=(const SocketAddress &addr) { set_addr(addr.get_addr()); set_port(addr.get_port()); return *this; } bool operator==(const SocketAddress &a, const SocketAddress &b) { return false; } bool operator!=(const SocketAddress &a, const SocketAddress &b) { return false; } <commit_msg>Netsocket: Fix SocketAddress stub for new API<commit_after>/* * Copyright (c) , Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SocketAddress.h" SocketAddress::SocketAddress(const nsapi_addr_t &addr, uint16_t port) { } SocketAddress::SocketAddress(const char *addr, uint16_t port) { } SocketAddress::SocketAddress(const void *bytes, nsapi_version_t version, uint16_t port) { } SocketAddress::SocketAddress(const SocketAddress &addr) { } bool SocketAddress::set_ip_address(const char *addr) { return false; } void SocketAddress::set_ip_bytes(const void *bytes, nsapi_version_t version) { } void SocketAddress::set_addr(const nsapi_addr_t &addr) { } const char *SocketAddress::get_ip_address() const { return NULL; } SocketAddress::operator bool() const { return false; } SocketAddress &SocketAddress::operator=(const SocketAddress &addr) { set_addr(addr.get_addr()); set_port(addr.get_port()); return *this; } bool operator==(const SocketAddress &a, const SocketAddress &b) { return false; } bool operator!=(const SocketAddress &a, const SocketAddress &b) { return false; } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2009, Distributed Systems Architecture Group, Universidad */ /* Complutense de Madrid (dsa-research.org) */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); you may */ /* not use this file except in compliance with the License. You may obtain */ /* a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ #include <limits.h> #include <string.h> #include <iostream> #include <sstream> #include "SchedulerHost.h" #include "Scheduler.h" /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void SchedulerHost::get_capacity(int& cpu, int& memory, int threshold) { int total_cpu; memory = get_share_free_mem(); cpu = get_share_free_cpu(); total_cpu = get_share_max_cpu(); /* eg. 96.7 >= 0.9 * 100, We need to round */ if ( cpu >= threshold * total_cpu ) { cpu = (int) ceil((float)cpu/100.0) * 100; } } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int SchedulerHost::insert(SqliteDB *db) { Scheduler::log("HOST",Log::ERROR, "Scheduler can not insert hosts in database"); return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int SchedulerHost::update(SqliteDB *db) { Scheduler::log("HOST",Log::ERROR, "Scheduler can not update hosts in database"); return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int SchedulerHost::drop(SqliteDB *db) { Scheduler::log("HOST",Log::ERROR, "Scheduler can not delete hosts from database"); return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int SchedulerHostPool::allocate( PoolObjectSQL *objsql) { Scheduler::log("HOST",Log::ERROR, "Scheduler can not allocate hosts in database"); return -1; }; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void SchedulerHostPool::bootstrap() { Scheduler::log("HOST",Log::ERROR, "Scheduler can not bootstrap database"); } /* ************************************************************************** */ /* SchedulerHostPool */ /* ************************************************************************** */ extern "C" { static int set_up_cb ( void * _hids, int num, char ** values, char ** names) { vector<int> * hids; hids = static_cast<vector<int> *>(_hids); if ((hids==0)||(num<=0)||(values[0]==0)) { return -1; } hids->push_back(atoi(values[0])); return 0; }; } /* -------------------------------------------------------------------------- */ int SchedulerHostPool::set_up() { ostringstream oss; int rc; // ------------------------------------------------------------------------- // Clean the pool to get updated data from db // ------------------------------------------------------------------------- clean(); hids.clear(); // ------------------------------------------------------------------------- // Load the ids (to get an updated list of hosts) // ------------------------------------------------------------------------- lock(); oss << "SELECT oid FROM " << Host::table << " WHERE state != " << Host::DISABLED; rc = db->exec(oss,set_up_cb,(void *) &hids); if ( rc != 0 ) { unlock(); return -1; } oss.str(""); oss << "Discovered Hosts (enabled):"; for (unsigned int i=0 ; i < hids.size() ; i++) { oss << " " << hids[i]; } Scheduler::log("HOST",Log::DEBUG,oss); unlock(); return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ <commit_msg>#136: Only look for enabled and non-error hosts to schedule VMs<commit_after>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2009, Distributed Systems Architecture Group, Universidad */ /* Complutense de Madrid (dsa-research.org) */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); you may */ /* not use this file except in compliance with the License. You may obtain */ /* a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ #include <limits.h> #include <string.h> #include <iostream> #include <sstream> #include "SchedulerHost.h" #include "Scheduler.h" /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void SchedulerHost::get_capacity(int& cpu, int& memory, int threshold) { int total_cpu; memory = get_share_free_mem(); cpu = get_share_free_cpu(); total_cpu = get_share_max_cpu(); /* eg. 96.7 >= 0.9 * 100, We need to round */ if ( cpu >= threshold * total_cpu ) { cpu = (int) ceil((float)cpu/100.0) * 100; } } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int SchedulerHost::insert(SqliteDB *db) { Scheduler::log("HOST",Log::ERROR, "Scheduler can not insert hosts in database"); return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int SchedulerHost::update(SqliteDB *db) { Scheduler::log("HOST",Log::ERROR, "Scheduler can not update hosts in database"); return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int SchedulerHost::drop(SqliteDB *db) { Scheduler::log("HOST",Log::ERROR, "Scheduler can not delete hosts from database"); return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int SchedulerHostPool::allocate( PoolObjectSQL *objsql) { Scheduler::log("HOST",Log::ERROR, "Scheduler can not allocate hosts in database"); return -1; }; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void SchedulerHostPool::bootstrap() { Scheduler::log("HOST",Log::ERROR, "Scheduler can not bootstrap database"); } /* ************************************************************************** */ /* SchedulerHostPool */ /* ************************************************************************** */ extern "C" { static int set_up_cb ( void * _hids, int num, char ** values, char ** names) { vector<int> * hids; hids = static_cast<vector<int> *>(_hids); if ((hids==0)||(num<=0)||(values[0]==0)) { return -1; } hids->push_back(atoi(values[0])); return 0; }; } /* -------------------------------------------------------------------------- */ int SchedulerHostPool::set_up() { ostringstream oss; int rc; // ------------------------------------------------------------------------- // Clean the pool to get updated data from db // ------------------------------------------------------------------------- clean(); hids.clear(); // ------------------------------------------------------------------------- // Load the ids (to get an updated list of hosts) // ------------------------------------------------------------------------- lock(); oss << "SELECT oid FROM " << Host::table << " WHERE state != " << Host::DISABLED << " AND state != " << Host::ERROR; rc = db->exec(oss,set_up_cb,(void *) &hids); if ( rc != 0 ) { unlock(); return -1; } oss.str(""); oss << "Discovered Hosts (enabled):"; for (unsigned int i=0 ; i < hids.size() ; i++) { oss << " " << hids[i]; } Scheduler::log("HOST",Log::DEBUG,oss); unlock(); return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Copyright (c) 2014-2019 The DigiByte Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <init.h> #include <interfaces/chain.h> #include <net.h> #include <scheduler.h> #include <outputtype.h> #include <util/error.h> #include <util/system.h> #include <util/moneystr.h> #include <validation.h> #include <walletinitinterface.h> #include <wallet/rpcwallet.h> #include <wallet/wallet.h> #include <wallet/walletutil.h> class WalletInit : public WalletInitInterface { public: //! Return the wallets help message. void AddWalletOptions() const override; //! Was the wallet component compiled in. bool HasWalletSupport() const override {return true;} //! Wallets parameter interaction bool ParameterInteraction() const override; //! Add wallets that should be opened to list of init interfaces. void Construct(InitInterfaces& interfaces) const override; }; const WalletInitInterface& g_wallet_init_interface = WalletInit(); void WalletInit::AddWalletOptions() const { gArgs.AddArg("-addresstype", strprintf("What type of addresses to use (\"legacy\", \"p2sh-segwit\", or \"bech32\", default: \"%s\")", FormatOutputType(DEFAULT_ADDRESS_TYPE)), false, OptionsCategory::WALLET); gArgs.AddArg("-avoidpartialspends", strprintf("Group outputs by address, selecting all or none, instead of selecting on a per-output basis. Privacy is improved as an address is only used once (unless someone sends to it after spending from it), but may result in slightly higher fees as suboptimal coin selection may result due to the added limitation (default: %u)", DEFAULT_AVOIDPARTIALSPENDS), false, OptionsCategory::WALLET); gArgs.AddArg("-changetype", "What type of change to use (\"legacy\", \"p2sh-segwit\", or \"bech32\"). Default is same as -addresstype, except when -addresstype=p2sh-segwit a native segwit output is used when sending to a native segwit address)", false, OptionsCategory::WALLET); gArgs.AddArg("-disablewallet", "Do not load the wallet and disable wallet RPC calls", false, OptionsCategory::WALLET); gArgs.AddArg("-discardfee=<amt>", strprintf("The fee rate (in %s/kB) that indicates your tolerance for discarding change by adding it to the fee (default: %s). " "Note: An output is discarded if it is dust at this rate, but we will always discard up to the dust relay fee and a discard fee above that is limited by the fee estimate for the longest target", CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE)), false, OptionsCategory::WALLET); gArgs.AddArg("-fallbackfee=<amt>", strprintf("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)), false, OptionsCategory::WALLET); gArgs.AddArg("-keypool=<n>", strprintf("Set key pool size to <n> (default: %u)", DEFAULT_KEYPOOL_SIZE), false, OptionsCategory::WALLET); gArgs.AddArg("-maxtxfee=<amt>", strprintf("Maximum total fees (in %s) to use in a single wallet transaction; setting this too low may abort large transactions (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)), false, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-mintxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)), false, OptionsCategory::WALLET); gArgs.AddArg("-paytxfee=<amt>", strprintf("Fee (in %s/kB) to add to transactions you send (default: %s)", CURRENCY_UNIT, FormatMoney(CFeeRate{DEFAULT_PAY_TX_FEE}.GetFeePerK())), false, OptionsCategory::WALLET); gArgs.AddArg("-rescan", "Rescan the block chain for missing wallet transactions on startup", false, OptionsCategory::WALLET); gArgs.AddArg("-salvagewallet", "Attempt to recover private keys from a corrupt wallet on startup", false, OptionsCategory::WALLET); gArgs.AddArg("-spendzeroconfchange", strprintf("Spend unconfirmed change when sending transactions (default: %u)", DEFAULT_SPEND_ZEROCONF_CHANGE), false, OptionsCategory::WALLET); gArgs.AddArg("-txconfirmtarget=<n>", strprintf("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)", DEFAULT_TX_CONFIRM_TARGET), false, OptionsCategory::WALLET); gArgs.AddArg("-upgradewallet", "Upgrade wallet to latest format on startup", false, OptionsCategory::WALLET); gArgs.AddArg("-wallet=<path>", "Specify wallet database path. Can be specified multiple times to load multiple wallets. Path is interpreted relative to <walletdir> if it is not absolute, and will be created if it does not exist (as a directory containing a wallet.dat file and log files). For backwards compatibility this will also accept names of existing data files in <walletdir>.)", false, OptionsCategory::WALLET); gArgs.AddArg("-walletbroadcast", strprintf("Make the wallet broadcast transactions (default: %u)", DEFAULT_WALLETBROADCAST), false, OptionsCategory::WALLET); gArgs.AddArg("-walletdir=<dir>", "Specify directory to hold wallets (default: <datadir>/wallets if it exists, otherwise <datadir>)", false, OptionsCategory::WALLET); gArgs.AddArg("-walletnotify=<cmd>", "Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)", false, OptionsCategory::WALLET); gArgs.AddArg("-walletrbf", strprintf("Send transactions with full-RBF opt-in enabled (RPC only, default: %u)", DEFAULT_WALLET_RBF), false, OptionsCategory::WALLET); gArgs.AddArg("-zapwallettxes=<mode>", "Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup" " (1 = keep tx meta data e.g. payment request information, 2 = drop tx meta data)", false, OptionsCategory::WALLET); gArgs.AddArg("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE), true, OptionsCategory::WALLET_DEBUG_TEST); gArgs.AddArg("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET), true, OptionsCategory::WALLET_DEBUG_TEST); gArgs.AddArg("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB), true, OptionsCategory::WALLET_DEBUG_TEST); gArgs.AddArg("-walletrejectlongchains", strprintf("Wallet will not create transactions that violate mempool chain limits (default: %u)", DEFAULT_WALLET_REJECT_LONG_CHAINS), true, OptionsCategory::WALLET_DEBUG_TEST); } bool WalletInit::ParameterInteraction() const { if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) { for (const std::string& wallet : gArgs.GetArgs("-wallet")) { LogPrintf("%s: parameter interaction: -disablewallet -> ignoring -wallet=%s\n", __func__, wallet); } return true; } const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1; if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && gArgs.SoftSetBoolArg("-walletbroadcast", false)) { LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__); } if (gArgs.GetBoolArg("-salvagewallet", false)) { if (is_multiwallet) { return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet")); } // Rewrite just private keys: rescan to find transactions if (gArgs.SoftSetBoolArg("-rescan", true)) { LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__); } } bool zapwallettxes = gArgs.GetBoolArg("-zapwallettxes", false); // -zapwallettxes implies dropping the mempool on startup if (zapwallettxes && gArgs.SoftSetBoolArg("-persistmempool", false)) { LogPrintf("%s: parameter interaction: -zapwallettxes enabled -> setting -persistmempool=0\n", __func__); } // -zapwallettxes implies a rescan if (zapwallettxes) { if (is_multiwallet) { return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes")); } if (gArgs.SoftSetBoolArg("-rescan", true)) { LogPrintf("%s: parameter interaction: -zapwallettxes enabled -> setting -rescan=1\n", __func__); } } if (is_multiwallet) { if (gArgs.GetBoolArg("-upgradewallet", false)) { return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet")); } } if (gArgs.GetBoolArg("-sysperms", false)) return InitError("-sysperms is not allowed in combination with enabled wallet functionality"); if (gArgs.GetArg("-prune", 0) && gArgs.GetBoolArg("-rescan", false)) return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again.")); return true; } void WalletInit::Construct(InitInterfaces& interfaces) const { if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) { LogPrintf("Wallet disabled!\n"); return; } gArgs.SoftSetArg("-wallet", ""); interfaces.chain_clients.emplace_back(interfaces::MakeWalletClient(*interfaces.chain, gArgs.GetArgs("-wallet"))); }<commit_msg>Bitcoin: 5ebc6b0eb267e0552c66fffc5e5afe7df8becf80 (bitcoind: update -avoidpartialspends description to account for auto-enable for avoid_reuse wallets).<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Copyright (c) 2014-2019 The DigiByte Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <init.h> #include <interfaces/chain.h> #include <net.h> #include <scheduler.h> #include <outputtype.h> #include <util/error.h> #include <util/system.h> #include <util/moneystr.h> #include <validation.h> #include <walletinitinterface.h> #include <wallet/rpcwallet.h> #include <wallet/wallet.h> #include <wallet/walletutil.h> class WalletInit : public WalletInitInterface { public: //! Return the wallets help message. void AddWalletOptions() const override; //! Was the wallet component compiled in. bool HasWalletSupport() const override {return true;} //! Wallets parameter interaction bool ParameterInteraction() const override; //! Add wallets that should be opened to list of init interfaces. void Construct(InitInterfaces& interfaces) const override; }; const WalletInitInterface& g_wallet_init_interface = WalletInit(); void WalletInit::AddWalletOptions() const { gArgs.AddArg("-addresstype", strprintf("What type of addresses to use (\"legacy\", \"p2sh-segwit\", or \"bech32\", default: \"%s\")", FormatOutputType(DEFAULT_ADDRESS_TYPE)), false, OptionsCategory::WALLET); gArgs.AddArg("-avoidpartialspends", strprintf("Group outputs by address, selecting all or none, instead of selecting on a per-output basis. Privacy is improved as an address is only used once (unless someone sends to it after spending from it), but may result in slightly higher fees as suboptimal coin selection may result due to the added limitation (default: %u (always enabled for wallets with \"avoid_reuse\" enabled))", DEFAULT_AVOIDPARTIALSPENDS), false, OptionsCategory::WALLET); gArgs.AddArg("-changetype", "What type of change to use (\"legacy\", \"p2sh-segwit\", or \"bech32\"). Default is same as -addresstype, except when -addresstype=p2sh-segwit a native segwit output is used when sending to a native segwit address)", false, OptionsCategory::WALLET); gArgs.AddArg("-disablewallet", "Do not load the wallet and disable wallet RPC calls", false, OptionsCategory::WALLET); gArgs.AddArg("-discardfee=<amt>", strprintf("The fee rate (in %s/kB) that indicates your tolerance for discarding change by adding it to the fee (default: %s). " "Note: An output is discarded if it is dust at this rate, but we will always discard up to the dust relay fee and a discard fee above that is limited by the fee estimate for the longest target", CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE)), false, OptionsCategory::WALLET); gArgs.AddArg("-fallbackfee=<amt>", strprintf("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)), false, OptionsCategory::WALLET); gArgs.AddArg("-keypool=<n>", strprintf("Set key pool size to <n> (default: %u)", DEFAULT_KEYPOOL_SIZE), false, OptionsCategory::WALLET); gArgs.AddArg("-maxtxfee=<amt>", strprintf("Maximum total fees (in %s) to use in a single wallet transaction; setting this too low may abort large transactions (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)), false, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-mintxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)), false, OptionsCategory::WALLET); gArgs.AddArg("-paytxfee=<amt>", strprintf("Fee (in %s/kB) to add to transactions you send (default: %s)", CURRENCY_UNIT, FormatMoney(CFeeRate{DEFAULT_PAY_TX_FEE}.GetFeePerK())), false, OptionsCategory::WALLET); gArgs.AddArg("-rescan", "Rescan the block chain for missing wallet transactions on startup", false, OptionsCategory::WALLET); gArgs.AddArg("-salvagewallet", "Attempt to recover private keys from a corrupt wallet on startup", false, OptionsCategory::WALLET); gArgs.AddArg("-spendzeroconfchange", strprintf("Spend unconfirmed change when sending transactions (default: %u)", DEFAULT_SPEND_ZEROCONF_CHANGE), false, OptionsCategory::WALLET); gArgs.AddArg("-txconfirmtarget=<n>", strprintf("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)", DEFAULT_TX_CONFIRM_TARGET), false, OptionsCategory::WALLET); gArgs.AddArg("-upgradewallet", "Upgrade wallet to latest format on startup", false, OptionsCategory::WALLET); gArgs.AddArg("-wallet=<path>", "Specify wallet database path. Can be specified multiple times to load multiple wallets. Path is interpreted relative to <walletdir> if it is not absolute, and will be created if it does not exist (as a directory containing a wallet.dat file and log files). For backwards compatibility this will also accept names of existing data files in <walletdir>.)", false, OptionsCategory::WALLET); gArgs.AddArg("-walletbroadcast", strprintf("Make the wallet broadcast transactions (default: %u)", DEFAULT_WALLETBROADCAST), false, OptionsCategory::WALLET); gArgs.AddArg("-walletdir=<dir>", "Specify directory to hold wallets (default: <datadir>/wallets if it exists, otherwise <datadir>)", false, OptionsCategory::WALLET); gArgs.AddArg("-walletnotify=<cmd>", "Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)", false, OptionsCategory::WALLET); gArgs.AddArg("-walletrbf", strprintf("Send transactions with full-RBF opt-in enabled (RPC only, default: %u)", DEFAULT_WALLET_RBF), false, OptionsCategory::WALLET); gArgs.AddArg("-zapwallettxes=<mode>", "Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup" " (1 = keep tx meta data e.g. payment request information, 2 = drop tx meta data)", false, OptionsCategory::WALLET); gArgs.AddArg("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE), true, OptionsCategory::WALLET_DEBUG_TEST); gArgs.AddArg("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET), true, OptionsCategory::WALLET_DEBUG_TEST); gArgs.AddArg("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB), true, OptionsCategory::WALLET_DEBUG_TEST); gArgs.AddArg("-walletrejectlongchains", strprintf("Wallet will not create transactions that violate mempool chain limits (default: %u)", DEFAULT_WALLET_REJECT_LONG_CHAINS), true, OptionsCategory::WALLET_DEBUG_TEST); } bool WalletInit::ParameterInteraction() const { if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) { for (const std::string& wallet : gArgs.GetArgs("-wallet")) { LogPrintf("%s: parameter interaction: -disablewallet -> ignoring -wallet=%s\n", __func__, wallet); } return true; } const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1; if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && gArgs.SoftSetBoolArg("-walletbroadcast", false)) { LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__); } if (gArgs.GetBoolArg("-salvagewallet", false)) { if (is_multiwallet) { return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet")); } // Rewrite just private keys: rescan to find transactions if (gArgs.SoftSetBoolArg("-rescan", true)) { LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__); } } bool zapwallettxes = gArgs.GetBoolArg("-zapwallettxes", false); // -zapwallettxes implies dropping the mempool on startup if (zapwallettxes && gArgs.SoftSetBoolArg("-persistmempool", false)) { LogPrintf("%s: parameter interaction: -zapwallettxes enabled -> setting -persistmempool=0\n", __func__); } // -zapwallettxes implies a rescan if (zapwallettxes) { if (is_multiwallet) { return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes")); } if (gArgs.SoftSetBoolArg("-rescan", true)) { LogPrintf("%s: parameter interaction: -zapwallettxes enabled -> setting -rescan=1\n", __func__); } } if (is_multiwallet) { if (gArgs.GetBoolArg("-upgradewallet", false)) { return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet")); } } if (gArgs.GetBoolArg("-sysperms", false)) return InitError("-sysperms is not allowed in combination with enabled wallet functionality"); if (gArgs.GetArg("-prune", 0) && gArgs.GetBoolArg("-rescan", false)) return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again.")); return true; } void WalletInit::Construct(InitInterfaces& interfaces) const { if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) { LogPrintf("Wallet disabled!\n"); return; } gArgs.SoftSetArg("-wallet", ""); interfaces.chain_clients.emplace_back(interfaces::MakeWalletClient(*interfaces.chain, gArgs.GetArgs("-wallet"))); }<|endoftext|>
<commit_before>/* * Qt4 bitcoin GUI. * * W.J. van der Laan 2011-2012 * The Bitcoin Developers 2011-2013 */ #include "walletstack.h" #include "walletview.h" #include "bitcoingui.h" #include <QMap> #include <QMessageBox> WalletStack::WalletStack(QWidget *parent) : QStackedWidget(parent), clientModel(0), bOutOfSync(true) { } WalletStack::~WalletStack() { } bool WalletStack::addWalletView(const QString& name, WalletModel *walletModel) { if (!gui || !clientModel || mapWalletViews.count(name) > 0) return false; WalletView *walletView = new WalletView(this, gui); walletView->setBitcoinGUI(gui); walletView->setClientModel(clientModel); walletView->setWalletModel(walletModel); walletView->showOutOfSyncWarning(bOutOfSync); addWidget(walletView); mapWalletViews[name] = walletView; return true; } bool WalletStack::removeWalletView(const QString& name) { if (mapWalletViews.count(name) == 0) return false; WalletView *walletView = mapWalletViews.take(name); removeWidget(walletView); return true; } bool WalletStack::handleURI(const QString &uri) { WalletView *walletView = (WalletView*)currentWidget(); if (!walletView) return false; return walletView->handleURI(uri); } void WalletStack::showOutOfSyncWarning(bool fShow) { bOutOfSync = fShow; QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->showOutOfSyncWarning(fShow); } void WalletStack::gotoOverviewPage() { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoOverviewPage(); } void WalletStack::gotoHistoryPage(bool fExportOnly, bool fExportConnect, bool fExportFirstTime) { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) { if ((WalletView*)currentWidget() == i.value()) i.value()->gotoHistoryPage(false, true, false); else i.value()->gotoHistoryPage(false, false, false); } } void WalletStack::gotoAddressBookPage(bool fExportOnly, bool fExportConnect, bool fExportFirstTime) { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) { if ((WalletView*)currentWidget() == i.value()) i.value()->gotoAddressBookPage(false, true, false); else i.value()->gotoAddressBookPage(false, false, false); } } void WalletStack::gotoReceiveCoinsPage(bool fExportOnly, bool fExportConnect, bool fExportFirstTime) { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) { if ((WalletView*)currentWidget() == i.value()) i.value()->gotoReceiveCoinsPage(false, true, false); else i.value()->gotoReceiveCoinsPage(false, false, false); } } void WalletStack::gotoSendCoinsPage() { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoSendCoinsPage(); } void WalletStack::gotoSignMessageTab(QString addr) { WalletView *walletView = (WalletView*)currentWidget(); if (walletView) walletView->gotoSignMessageTab(addr); } void WalletStack::gotoVerifyMessageTab(QString addr) { WalletView *walletView = (WalletView*)currentWidget(); if (walletView) walletView->gotoVerifyMessageTab(addr); } void WalletStack::encryptWallet(bool status) { WalletView *walletView = (WalletView*)currentWidget(); if (walletView) walletView->encryptWallet(status); } void WalletStack::backupWallet() { WalletView *walletView = (WalletView*)currentWidget(); if (walletView) walletView->backupWallet(); } void WalletStack::changePassphrase() { WalletView *walletView = (WalletView*)currentWidget(); if (walletView) walletView->changePassphrase(); } void WalletStack::unlockWallet() { WalletView *walletView = (WalletView*)currentWidget(); if (walletView) walletView->unlockWallet(); } void WalletStack::setEncryptionStatus() { WalletView *walletView = (WalletView*)currentWidget(); if (walletView) walletView->setEncryptionStatus(); } QString WalletStack::getCurrentWallet() { return QString (mapWalletViews.key((WalletView*)currentWidget())); } void WalletStack::setCurrentWalletView(const QString& name) { if (mapWalletViews.count(name) == 0) return; WalletView *walletView = mapWalletViews.value(name); setCurrentWidget(walletView); walletView->setEncryptionStatus(); //Call the pages that have export and only set that connect QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) { bool x; if ( mapWalletViews.constBegin() == (i) ) x=true; else x=false; if ((WalletView*)currentWidget() == i.value()) { i.value()->gotoReceiveCoinsPage(true, true, x); i.value()->gotoHistoryPage(true, true, x); i.value()->gotoAddressBookPage(true, true, x); } else { i.value()->gotoReceiveCoinsPage(true, false, x); i.value()->gotoHistoryPage(true, false, x); i.value()->gotoAddressBookPage(true, false, x ); } } } <commit_msg>V1.3<commit_after>/* * Qt4 bitcoin GUI. * * W.J. van der Laan 2011-2012 * The Bitcoin Developers 2011-2013 */ #include "walletstack.h" #include "walletview.h" #include "bitcoingui.h" #include <QMap> #include <QMessageBox> WalletStack::WalletStack(QWidget *parent) : QStackedWidget(parent), gui(0), clientModel(0), bOutOfSync(true) { } WalletStack::~WalletStack() { } bool WalletStack::addWalletView(const QString& name, WalletModel *walletModel) { if (!gui || !clientModel || mapWalletViews.count(name) > 0) return false; WalletView *walletView = new WalletView(this, gui); walletView->setBitcoinGUI(gui); walletView->setClientModel(clientModel); walletView->setWalletModel(walletModel); walletView->showOutOfSyncWarning(bOutOfSync); addWidget(walletView); mapWalletViews[name] = walletView; // Ensure a walletView is able to show the main window connect(walletView, SIGNAL(showNormalIfMinimized()), gui, SLOT(showNormalIfMinimized())); return true; } bool WalletStack::removeWalletView(const QString& name) { if (mapWalletViews.count(name) == 0) return false; WalletView *walletView = mapWalletViews.take(name); removeWidget(walletView); return true; } bool WalletStack::handleURI(const QString &uri) { WalletView *walletView = (WalletView*)currentWidget(); if (!walletView) return false; return walletView->handleURI(uri); } void WalletStack::showOutOfSyncWarning(bool fShow) { bOutOfSync = fShow; QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->showOutOfSyncWarning(fShow); } void WalletStack::gotoOverviewPage() { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoOverviewPage(); } void WalletStack::gotoHistoryPage(bool fExportOnly, bool fExportConnect, bool fExportFirstTime) { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) { if ((WalletView*)currentWidget() == i.value()) i.value()->gotoHistoryPage(false, true, false); else i.value()->gotoHistoryPage(false, false, false); } } void WalletStack::gotoAddressBookPage(bool fExportOnly, bool fExportConnect, bool fExportFirstTime) { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) { if ((WalletView*)currentWidget() == i.value()) i.value()->gotoAddressBookPage(false, true, false); else i.value()->gotoAddressBookPage(false, false, false); } } void WalletStack::gotoReceiveCoinsPage(bool fExportOnly, bool fExportConnect, bool fExportFirstTime) { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) { if ((WalletView*)currentWidget() == i.value()) i.value()->gotoReceiveCoinsPage(false, true, false); else i.value()->gotoReceiveCoinsPage(false, false, false); } } void WalletStack::gotoSendCoinsPage() { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoSendCoinsPage(); } void WalletStack::gotoSignMessageTab(QString addr) { WalletView *walletView = (WalletView*)currentWidget(); if (walletView) walletView->gotoSignMessageTab(addr); } void WalletStack::gotoVerifyMessageTab(QString addr) { WalletView *walletView = (WalletView*)currentWidget(); if (walletView) walletView->gotoVerifyMessageTab(addr); } void WalletStack::encryptWallet(bool status) { WalletView *walletView = (WalletView*)currentWidget(); if (walletView) walletView->encryptWallet(status); } void WalletStack::backupWallet() { WalletView *walletView = (WalletView*)currentWidget(); if (walletView) walletView->backupWallet(); } void WalletStack::changePassphrase() { WalletView *walletView = (WalletView*)currentWidget(); if (walletView) walletView->changePassphrase(); } void WalletStack::unlockWallet() { WalletView *walletView = (WalletView*)currentWidget(); if (walletView) walletView->unlockWallet(); } void WalletStack::setEncryptionStatus() { WalletView *walletView = (WalletView*)currentWidget(); if (walletView) walletView->setEncryptionStatus(); } QString WalletStack::getCurrentWallet() { return QString (mapWalletViews.key((WalletView*)currentWidget())); } void WalletStack::setCurrentWalletView(const QString& name) { if (mapWalletViews.count(name) == 0) return; WalletView *walletView = mapWalletViews.value(name); setCurrentWidget(walletView); walletView->setEncryptionStatus(); //Call the pages that have export and only set that connect QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) { bool x; if ( mapWalletViews.constBegin() == (i) ) x=true; else x=false; if ((WalletView*)currentWidget() == i.value()) { i.value()->gotoReceiveCoinsPage(true, true, x); i.value()->gotoHistoryPage(true, true, x); i.value()->gotoAddressBookPage(true, true, x); } else { i.value()->gotoReceiveCoinsPage(true, false, x); i.value()->gotoHistoryPage(true, false, x); i.value()->gotoAddressBookPage(true, false, x ); } } } <|endoftext|>
<commit_before>#include "clstm.h" #include <assert.h> #include <math.h> #include <fstream> #include <iostream> #include <iostream> #include <memory> #include <regex> #include <set> #include <sstream> #include <vector> #include "clstmhl.h" #include "extras.h" #include "pstring.h" #include "utils.h" using namespace Eigen; using namespace ocropus; using std::vector; using std::map; using std::make_pair; using std::shared_ptr; using std::unique_ptr; using std::cout; using std::ifstream; using std::set; using std::to_string; using std_string = std::string; using std_wstring = std::wstring; using std::regex; using std::regex_replace; #define string std_string #define wstring std_wstring #ifndef NODISPLAY void show(PyServer &py, Sequence &s, int subplot = 0, int batch = 0) { Tensor<float, 2> temp; temp.resize(s.size(), s.rows()); for (int i = 0; i < s.size(); i++) for (int j = 0; j < s.rows(); j++) temp(i, j) = s[i].v(j, batch); if (subplot > 0) py.evalf("subplot(%d)", subplot); py.imshowT(temp, "cmap=cm.hot"); } #endif wstring separate_chars(const wstring &s, const wstring &charsep) { if (charsep == L"") return s; wstring result; for (int i = 0; i < s.size(); i++) { if (i > 0) result.push_back(charsep[0]); result.push_back(s[i]); } return result; } struct Dataset { vector<string> fnames; wstring charsep = utf8_to_utf32(getsenv("charsep", "")); int size() { return fnames.size(); } Dataset() {} Dataset(string file_list) { readFileList(file_list); } void readFileList(string file_list) { read_lines(fnames, file_list); } void getCodec(Codec &codec) { vector<string> gtnames; for (auto s : fnames) gtnames.push_back(basename(s) + ".gt.txt"); codec.build(gtnames, charsep); } string readSample(Tensor2 &raw, wstring &gt, int index, bool drouOut = false) { string fname = fnames[index]; try{ string base = basename(fname); gt = separate_chars(read_text32(base + ".gt.txt"), charsep); read_png(raw, fname.c_str()); raw() = -raw() + Float(1); if( drouOut ) { int N = raw.dimension(0); int d = raw.dimension(1); for (int t = 0; t < N; t++) for (int i = 0; i < d; i++){ if(lrand48() % 10 > 5) raw(t, i) = 0; } } }catch(...){ std::cout << "Bad sample: " << fname << std::endl; } return fname; } }; pair<double, double> test_set_error(CLSTMOCR &clstm, Dataset &testset, double& test50) { double count = 0.0; double errors = 0.0; test50 = 0; double count50; for (int test = 0; test < testset.size(); test++) { Tensor2 raw; wstring gt; testset.readSample(raw, gt, test); wstring pred = clstm.predict(raw()); count += gt.size(); int dist = levenshtein(pred, gt); errors += dist; if( test < 50 ){ test50 += dist; count50 += gt.size(); } } test50 /= count50; return make_pair(errors, count); } int main1(int argc, char **argv) { int ntrain = getienv("ntrain", 10000000); string save_name = getsenv("save_name", "_ocr"); int report_time = getienv("report_time", 0); if (argc < 2 || argc > 3) THROW("... training [testing]"); Dataset trainingset(argv[1]); assert(trainingset.size() > 0); Dataset testset; if (argc > 2) testset.readFileList(argv[2]); print("got", trainingset.size(), "files,", testset.size(), "tests"); string load_name = getsenv("load", ""); CLSTMOCR clstm; if (load_name != "") { clstm.load(load_name); } else { Codec codec; trainingset.getCodec(codec); print("got", codec.size(), "classes"); clstm.target_height = int(getrenv("target_height", 48)); clstm.createBidi2(codec.codec, getienv("nhidden", 100)); clstm.setLearningRate(getdenv("lrate", 1e-4), getdenv("momentum", 0.9)); } network_info(clstm.net); double test_error = 9999.0; double best_error = 1e38; double best_test50 = 1e38; #ifndef NODISPLAY PyServer py; if (display_every > 0) py.open(); #endif double start_time = now(); int start = clstm.net->attr.get("trial", getienv("start", -1)) + 1; if (start > 0) print("start", start); Trigger test_trigger(getienv("test_every", 10000), -1, start); test_trigger.skip0(); Trigger save_trigger(getienv("save_every", 10000), ntrain, start); save_trigger.enable(save_name != "").skip0(); Trigger report_trigger(getienv("report_every", 100), ntrain, start); Trigger display_trigger(getienv("display_every", 0), ntrain, start); int fromSamples = 450 + 10000; for (int trial = start; trial < ntrain; trial++) { int sample = lrand48() % trainingset.size(); if( true ) { fromSamples += 1; fromSamples = std::min(fromSamples, trainingset.size() ); sample = lrand48() % fromSamples; } Tensor2 raw; wstring gt; string fname = trainingset.readSample(raw, gt, sample); wstring pred = clstm.train(raw(), gt); if (report_trigger(trial)) { std::cout << fname << std::endl; double dist = levenshtein(pred, gt); print(trial); print("TRU", gt); print("ALN", clstm.aligned_utf8()); print("OUT", utf32_to_utf8(pred), dist / gt.size()); if (trial > 0 && report_time) print("steptime", (now() - start_time) / report_trigger.since()); start_time = now(); } #ifndef NODISPLAY if (display_trigger(trial)) { py.evalf("clf"); show(py, clstm.net->inputs, 411); show(py, clstm.net->outputs, 412); show(py, clstm.targets, 413); show(py, clstm.aligned, 414); } #endif if (test_trigger(trial) && trial > start + 1) { double test50; auto tse = test_set_error(clstm, testset, test50); double errors = tse.first; double count = tse.second; test_error = errors / count; print("ERROR", trial, test_error, " ", errors, count, errors/(float)count, test50); if (test_error < best_error) { best_error = test_error; string fname = save_name + ".clstm"; print("saving best performing network so far", fname, "error rate: ", best_error, test50); clstm.net->attr.set("trial", trial); clstm.save(fname); best_test50 = std::min(test50, best_test50); }else if( test50 < best_test50 ) { string fname = save_name + ".clstm"; print("saving best performing network so far", fname, "error rate: ", best_error, test50); clstm.net->attr.set("trial", trial); clstm.save(fname); best_test50 = test50; } } /* if (save_trigger(trial)) { string fname = save_name + "-" + to_string(trial) + ".clstm"; print("saving", fname); clstm.net->attr.set("trial", trial); clstm.save(fname); }*/ } return 0; } int main(int argc, char **argv) { TRY { main1(argc, argv); } CATCH(const char *message) { cerr << "FATAL: " << message << endl; } } <commit_msg>test dropout<commit_after>#include "clstm.h" #include <assert.h> #include <math.h> #include <fstream> #include <iostream> #include <iostream> #include <memory> #include <regex> #include <set> #include <sstream> #include <vector> #include "clstmhl.h" #include "extras.h" #include "pstring.h" #include "utils.h" using namespace Eigen; using namespace ocropus; using std::vector; using std::map; using std::make_pair; using std::shared_ptr; using std::unique_ptr; using std::cout; using std::ifstream; using std::set; using std::to_string; using std_string = std::string; using std_wstring = std::wstring; using std::regex; using std::regex_replace; #define string std_string #define wstring std_wstring #ifndef NODISPLAY void show(PyServer &py, Sequence &s, int subplot = 0, int batch = 0) { Tensor<float, 2> temp; temp.resize(s.size(), s.rows()); for (int i = 0; i < s.size(); i++) for (int j = 0; j < s.rows(); j++) temp(i, j) = s[i].v(j, batch); if (subplot > 0) py.evalf("subplot(%d)", subplot); py.imshowT(temp, "cmap=cm.hot"); } #endif wstring separate_chars(const wstring &s, const wstring &charsep) { if (charsep == L"") return s; wstring result; for (int i = 0; i < s.size(); i++) { if (i > 0) result.push_back(charsep[0]); result.push_back(s[i]); } return result; } struct Dataset { vector<string> fnames; wstring charsep = utf8_to_utf32(getsenv("charsep", "")); int size() { return fnames.size(); } Dataset() {} Dataset(string file_list) { readFileList(file_list); } void readFileList(string file_list) { read_lines(fnames, file_list); } void getCodec(Codec &codec) { vector<string> gtnames; for (auto s : fnames) gtnames.push_back(basename(s) + ".gt.txt"); codec.build(gtnames, charsep); } string readSample(Tensor2 &raw, wstring &gt, int index, bool drouOut = false) { string fname = fnames[index]; try{ string base = basename(fname); gt = separate_chars(read_text32(base + ".gt.txt"), charsep); read_png(raw, fname.c_str()); raw() = -raw() + Float(1); if( drouOut ) { int N = raw.dimension(0); int d = raw.dimension(1); for (int t = 0; t < N; t++) for (int i = 0; i < d; i++){ if(lrand48() % 10 > 5) raw(t, i) = 0; } } }catch(...){ std::cout << "Bad sample: " << fname << std::endl; } return fname; } }; pair<double, double> test_set_error(CLSTMOCR &clstm, Dataset &testset, double& test50) { double count = 0.0; double errors = 0.0; test50 = 0; double count50; for (int test = 0; test < testset.size(); test++) { Tensor2 raw; wstring gt; testset.readSample(raw, gt, test); wstring pred = clstm.predict(raw()); count += gt.size(); int dist = levenshtein(pred, gt); errors += dist; if( test < 50 ){ test50 += dist; count50 += gt.size(); } } test50 /= count50; return make_pair(errors, count); } int main1(int argc, char **argv) { int ntrain = getienv("ntrain", 10000000); string save_name = getsenv("save_name", "_ocr"); int report_time = getienv("report_time", 0); if (argc < 2 || argc > 3) THROW("... training [testing]"); Dataset trainingset(argv[1]); assert(trainingset.size() > 0); Dataset testset; if (argc > 2) testset.readFileList(argv[2]); print("got", trainingset.size(), "files,", testset.size(), "tests"); string load_name = getsenv("load", ""); CLSTMOCR clstm; if (load_name != "") { clstm.load(load_name); } else { Codec codec; trainingset.getCodec(codec); print("got", codec.size(), "classes"); clstm.target_height = int(getrenv("target_height", 48)); clstm.createBidi2(codec.codec, getienv("nhidden", 100)); clstm.setLearningRate(getdenv("lrate", 1e-4), getdenv("momentum", 0.9)); } network_info(clstm.net); double test_error = 9999.0; double best_error = 1e38; double best_test50 = 1e38; #ifndef NODISPLAY PyServer py; if (display_every > 0) py.open(); #endif double start_time = now(); int start = clstm.net->attr.get("trial", getienv("start", -1)) + 1; if (start > 0) print("start", start); Trigger test_trigger(getienv("test_every", 10000), -1, start); test_trigger.skip0(); Trigger save_trigger(getienv("save_every", 10000), ntrain, start); save_trigger.enable(save_name != "").skip0(); Trigger report_trigger(getienv("report_every", 100), ntrain, start); Trigger display_trigger(getienv("display_every", 0), ntrain, start); int fromSamples = 450 + 10000; for (int trial = start; trial < ntrain; trial++) { int sample = lrand48() % trainingset.size(); if( true ) { fromSamples += 1; fromSamples = std::min(fromSamples, trainingset.size() ); sample = lrand48() % fromSamples; } Tensor2 raw; wstring gt; string fname = trainingset.readSample(raw, gt, sample, true); wstring pred = clstm.train(raw(), gt); if (report_trigger(trial)) { std::cout << fname << std::endl; double dist = levenshtein(pred, gt); print(trial); print("TRU", gt); print("ALN", clstm.aligned_utf8()); print("OUT", utf32_to_utf8(pred), dist / gt.size()); if (trial > 0 && report_time) print("steptime", (now() - start_time) / report_trigger.since()); start_time = now(); } #ifndef NODISPLAY if (display_trigger(trial)) { py.evalf("clf"); show(py, clstm.net->inputs, 411); show(py, clstm.net->outputs, 412); show(py, clstm.targets, 413); show(py, clstm.aligned, 414); } #endif if (test_trigger(trial) && trial > start + 1) { double test50; auto tse = test_set_error(clstm, testset, test50); double errors = tse.first; double count = tse.second; test_error = errors / count; print("ERROR", trial, test_error, " ", errors, count, errors/(float)count, test50); if (test_error < best_error) { best_error = test_error; string fname = save_name + ".clstm"; print("saving best performing network so far", fname, "error rate: ", best_error, test50); clstm.net->attr.set("trial", trial); clstm.save(fname); best_test50 = std::min(test50, best_test50); }else if( test50 < best_test50 ) { string fname = save_name + ".clstm"; print("saving best performing network so far", fname, "error rate: ", best_error, test50); clstm.net->attr.set("trial", trial); clstm.save(fname); best_test50 = test50; } } /* if (save_trigger(trial)) { string fname = save_name + "-" + to_string(trial) + ".clstm"; print("saving", fname); clstm.net->attr.set("trial", trial); clstm.save(fname); }*/ } return 0; } int main(int argc, char **argv) { TRY { main1(argc, argv); } CATCH(const char *message) { cerr << "FATAL: " << message << endl; } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsensormanager.h" #include <QDebug> #include "qsensorpluginloader_p.h" #include "qsensorplugin.h" #include <QSettings> #include "sensorlog_p.h" #include <QTimer> QTM_BEGIN_NAMESPACE Q_GLOBAL_STATIC(QSensorPluginLoader, pluginLoader) typedef QHash<QByteArray,QSensorBackendFactory*> FactoryForIdentifierMap; typedef QHash<QByteArray,FactoryForIdentifierMap> BackendIdentifiersForTypeMap; class QSensorManagerPrivate : public QObject { friend class QSensorManager; Q_OBJECT public: QSensorManagerPrivate() : pluginsLoaded(false) , sensorsChanged(false) { } bool pluginsLoaded; QList<CreatePluginFunc> staticRegistrations; // Holds a mapping from type to available identifiers (and from there to the factory) BackendIdentifiersForTypeMap backendsByType; // Holds the first identifier for each type QHash<QByteArray, QByteArray> firstIdentifierForType; bool sensorsChanged; QList<QSensorChangesInterface*> changeListeners; Q_SIGNALS: void availableSensorsChanged(); public Q_SLOTS: void emitSensorsChanged() { static bool alreadyRunning = false; if (!pluginsLoaded || alreadyRunning) { // We're busy. // Just note that a registration changed and exit. // Someone up the call stack will deal with this. sensorsChanged = true; return; } // Set a flag so any recursive calls doesn't cause a loop. alreadyRunning = true; // Since one [un]registration may cause other [un]registrations and since // the order in which we do things matters we just do a cascading update // until things stop changing. do { sensorsChanged = false; Q_FOREACH (QSensorChangesInterface *changes, changeListeners) { changes->sensorsChanged(); } } while (sensorsChanged); // We're going away now so clear the flag alreadyRunning = false; // Notify the client of the changes Q_EMIT availableSensorsChanged(); } }; Q_GLOBAL_STATIC(QSensorManagerPrivate, sensorManagerPrivate) // The unit test needs to change the behaviour of the library. It does this // through an exported but undocumented function. static void initPlugin(QObject *plugin); static bool settings_use_user_scope = false; static bool load_external_plugins = true; Q_SENSORS_EXPORT void sensors_unit_test_hook(int index) { QSensorManagerPrivate *d = sensorManagerPrivate(); switch (index) { case 0: Q_ASSERT(d->pluginsLoaded == false); settings_use_user_scope = true; load_external_plugins = false; break; case 1: Q_ASSERT(load_external_plugins == false); Q_ASSERT(d->pluginsLoaded == true); SENSORLOG() << "initializing plugins"; Q_FOREACH (QObject *plugin, pluginLoader()->plugins()) { initPlugin(plugin); } break; default: break; } } static void initPlugin(QObject *o) { if (!o) return; QSensorManagerPrivate *d = sensorManagerPrivate(); QSensorPluginInterface *plugin = qobject_cast<QSensorPluginInterface*>(o); if (plugin) plugin->registerSensors(); QSensorChangesInterface *changes = qobject_cast<QSensorChangesInterface*>(o); if (changes) d->changeListeners << changes; } static void loadPlugins() { QSensorManagerPrivate *d = sensorManagerPrivate(); d->pluginsLoaded = true; SENSORLOG() << "initializing static plugins"; Q_FOREACH (CreatePluginFunc func, d->staticRegistrations) { QSensorPluginInterface *plugin = func(); plugin->registerSensors(); } if (load_external_plugins) { SENSORLOG() << "initializing plugins"; Q_FOREACH (QObject *plugin, pluginLoader()->plugins()) { initPlugin(plugin); } } if (d->sensorsChanged) { // Notify the app that the available sensor list has changed. // This may cause recursive calls! d->emitSensorsChanged(); } } // ===================================================================== /*! \class QSensorManager \ingroup sensors_backend \inmodule QtSensors \brief The QSensorManager class handles registration and creation of sensor backends. Sensor plugins register backends using the registerBackend() function. When QSensor::connectToBackend() is called, the createBackend() function will be called. */ /*! Register a sensor for \a type. The \a identifier must be unique. The \a factory will be asked to create instances of the backend. */ void QSensorManager::registerBackend(const QByteArray &type, const QByteArray &identifier, QSensorBackendFactory *factory) { QSensorManagerPrivate *d = sensorManagerPrivate(); if (!d->backendsByType.contains(type)) { (void)d->backendsByType[type]; d->firstIdentifierForType[type] = identifier; } else if (d->firstIdentifierForType[type].startsWith("generic.")) { // Don't let a generic backend be the default when some other backend exists! d->firstIdentifierForType[type] = identifier; } FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[type]; if (factoryByIdentifier.contains(identifier)) { qWarning() << "A backend with type" << type << "and identifier" << identifier << "has already been registered!"; return; } SENSORLOG() << "registering backend for type" << type << "identifier" << identifier;// << "factory" << QString().sprintf("0x%08x", (unsigned int)factory); factoryByIdentifier[identifier] = factory; // Notify the app that the available sensor list has changed. // This may cause recursive calls! d->emitSensorsChanged(); } /*! Unregister the backend for \a type with \a identifier. Note that this only prevents new instance of the backend from being created. It does not invalidate the existing instances of the backend. The backend code should handle the disappearance of the underlying hardware itself. */ void QSensorManager::unregisterBackend(const QByteArray &type, const QByteArray &identifier) { QSensorManagerPrivate *d = sensorManagerPrivate(); if (!d->backendsByType.contains(type)) { qWarning() << "No backends of type" << type << "are registered"; return; } FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[type]; if (!factoryByIdentifier.contains(identifier)) { qWarning() << "Identifier" << identifier << "is not registered"; return; } (void)factoryByIdentifier.take(identifier); // we don't own this pointer anyway if (d->firstIdentifierForType[type] == identifier) { if (factoryByIdentifier.count()) { d->firstIdentifierForType[type] = factoryByIdentifier.begin().key(); if (d->firstIdentifierForType[type].startsWith("generic.")) { // Don't let a generic backend be the default when some other backend exists! for (FactoryForIdentifierMap::const_iterator it = factoryByIdentifier.begin()++; it != factoryByIdentifier.end(); it++) { const QByteArray &identifier(it.key()); if (!identifier.startsWith("generic.")) { d->firstIdentifierForType[type] = identifier; break; } } } } else { (void)d->firstIdentifierForType.take(type); } } if (!factoryByIdentifier.count()) (void)d->backendsByType.take(type); // Notify the app that the available sensor list has changed. // This may cause recursive calls! d->emitSensorsChanged(); } /*! \internal */ void QSensorManager::registerStaticPlugin(CreatePluginFunc func) { QSensorManagerPrivate *d = sensorManagerPrivate(); d->staticRegistrations.append(func); } /*! Create a backend for \a sensor. Returns null if no suitable backend exists. */ QSensorBackend *QSensorManager::createBackend(QSensor *sensor) { Q_ASSERT(sensor); QSensorManagerPrivate *d = sensorManagerPrivate(); if (!d->pluginsLoaded) loadPlugins(); SENSORLOG() << "QSensorManager::createBackend" << "type" << sensor->type() << "identifier" << sensor->identifier(); if (!d->backendsByType.contains(sensor->type())) { SENSORLOG() << "no backends of type" << sensor->type() << "have been registered."; return 0; } const FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[sensor->type()]; QSensorBackendFactory *factory; QSensorBackend *backend; if (sensor->identifier().isEmpty()) { QByteArray defaultIdentifier = QSensor::defaultSensorForType(sensor->type()); SENSORLOG() << "Trying the default" << defaultIdentifier; // No identifier set, try the default factory = factoryByIdentifier[defaultIdentifier]; //SENSORLOG() << "factory" << QString().sprintf("0x%08x", (unsigned int)factory); sensor->setIdentifier(defaultIdentifier); // the factory requires this backend = factory->createBackend(sensor); if (backend) return backend; // Got it! // The default failed to instantiate so try any other registered sensors for this type Q_FOREACH (const QByteArray &identifier, factoryByIdentifier.keys()) { SENSORLOG() << "Trying" << identifier; if (identifier == defaultIdentifier) continue; // Don't do the default one again factory = factoryByIdentifier[identifier]; //SENSORLOG() << "factory" << QString().sprintf("0x%08x", (unsigned int)factory); sensor->setIdentifier(identifier); // the factory requires this backend = factory->createBackend(sensor); if (backend) return backend; // Got it! } SENSORLOG() << "FAILED"; sensor->setIdentifier(QByteArray()); // clear the identifier } else { if (!factoryByIdentifier.contains(sensor->identifier())) { SENSORLOG() << "no backend with identifier" << sensor->identifier() << "for type" << sensor->type(); return 0; } // We were given an explicit identifier so don't substitute other backends if it fails to instantiate factory = factoryByIdentifier[sensor->identifier()]; //SENSORLOG() << "factory" << QString().sprintf("0x%08x", (unsigned int)factory); backend = factory->createBackend(sensor); if (backend) return backend; // Got it! } SENSORLOG() << "no suitable backend found for requested identifier" << sensor->identifier() << "and type" << sensor->type(); return 0; } /*! Returns true if the backend identified by \a type and \a identifier is registered. This is a convenience method that helps out plugins doing dynamic registration. */ bool QSensorManager::isBackendRegistered(const QByteArray &type, const QByteArray &identifier) { QSensorManagerPrivate *d = sensorManagerPrivate(); if (!d->pluginsLoaded) loadPlugins(); if (!d->backendsByType.contains(type)) return false; const FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[type]; if (!factoryByIdentifier.contains(identifier)) return false; return true; } // ===================================================================== /*! Returns a list of all sensor types. */ QList<QByteArray> QSensor::sensorTypes() { QSensorManagerPrivate *d = sensorManagerPrivate(); if (!d->pluginsLoaded) loadPlugins(); return d->backendsByType.keys(); } /*! Returns a list of ids for each of the sensors for \a type. If there are no sensors of that type available the list will be empty. */ QList<QByteArray> QSensor::sensorsForType(const QByteArray &type) { QSensorManagerPrivate *d = sensorManagerPrivate(); if (!d->pluginsLoaded) loadPlugins(); // no sensors of that type exist if (!d->backendsByType.contains(type)) return QList<QByteArray>(); return d->backendsByType[type].keys(); } /*! Returns the default sensor identifier for \a type. This is set in a config file and can be overridden if required. If no default is available the system will return the first registered sensor for \a type. Note that there is special case logic to prevent the generic plugin's backends from becoming the default when another backend is registered for the same type. This logic means that a backend identifier starting with \c{generic.} will only be the default if no other backends have been registered for that type or if it is specified in \c{Sensors.conf}. \sa {Determining the default sensor for a type} */ QByteArray QSensor::defaultSensorForType(const QByteArray &type) { QSensorManagerPrivate *d = sensorManagerPrivate(); if (!d->pluginsLoaded) loadPlugins(); // no sensors of that type exist if (!d->backendsByType.contains(type)) return QByteArray(); // The unit test needs to modify Sensors.conf but it can't access the system directory QSettings::Scope scope = settings_use_user_scope ? QSettings::UserScope : QSettings::SystemScope; QSettings settings(scope, QLatin1String("Nokia"), QLatin1String("Sensors")); QVariant value = settings.value(QString(QLatin1String("Default/%1")).arg(QString::fromLatin1(type))); if (!value.isNull()) { QByteArray defaultIdentifier = value.toByteArray(); if (d->backendsByType[type].contains(defaultIdentifier)) // Don't return a value that we can't use! return defaultIdentifier; } // This is our fallback return d->firstIdentifierForType[type]; } void QSensor::registerInstance() { QSensorManagerPrivate *d = sensorManagerPrivate(); connect(d, SIGNAL(availableSensorsChanged()), this, SIGNAL(availableSensorsChanged())); } // ===================================================================== /*! \class QSensorBackendFactory \ingroup sensors_backend \inmodule QtSensors \brief The QSensorBackendFactory class instantiates instances of QSensorBackend. This interface must be implemented in order to register a sensor backend. \sa {Creating a sensor plugin} */ /*! \fn QSensorBackendFactory::~QSensorBackendFactory() \internal */ /*! \fn QSensorBackendFactory::createBackend(QSensor *sensor) Instantiate a backend. If the factory handles multiple identifiers it should check with the \a sensor to see which one is requested. If the factory cannot create a backend it should return 0. */ /*! \macro REGISTER_STATIC_PLUGIN(pluginname) \relates QSensorManager Registers a static plugin, \a pluginname. Note that this macro relies on static initialization so it may not be appropriate for use in a library and may not work on all platforms. \sa {Creating a sensor plugin} */ #include "qsensormanager.moc" QTM_END_NAMESPACE <commit_msg>Ensure that loadPlugins cannot be used incorrectly.<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsensormanager.h" #include <QDebug> #include "qsensorpluginloader_p.h" #include "qsensorplugin.h" #include <QSettings> #include "sensorlog_p.h" #include <QTimer> QTM_BEGIN_NAMESPACE Q_GLOBAL_STATIC(QSensorPluginLoader, pluginLoader) typedef QHash<QByteArray,QSensorBackendFactory*> FactoryForIdentifierMap; typedef QHash<QByteArray,FactoryForIdentifierMap> BackendIdentifiersForTypeMap; class QSensorManagerPrivate : public QObject { friend class QSensorManager; Q_OBJECT public: QSensorManagerPrivate() : pluginsLoaded(false) , sensorsChanged(false) { } bool pluginsLoaded; void loadPlugins(); QList<CreatePluginFunc> staticRegistrations; // Holds a mapping from type to available identifiers (and from there to the factory) BackendIdentifiersForTypeMap backendsByType; // Holds the first identifier for each type QHash<QByteArray, QByteArray> firstIdentifierForType; bool sensorsChanged; QList<QSensorChangesInterface*> changeListeners; Q_SIGNALS: void availableSensorsChanged(); public Q_SLOTS: void emitSensorsChanged() { static bool alreadyRunning = false; if (!pluginsLoaded || alreadyRunning) { // We're busy. // Just note that a registration changed and exit. // Someone up the call stack will deal with this. sensorsChanged = true; return; } // Set a flag so any recursive calls doesn't cause a loop. alreadyRunning = true; // Since one [un]registration may cause other [un]registrations and since // the order in which we do things matters we just do a cascading update // until things stop changing. do { sensorsChanged = false; Q_FOREACH (QSensorChangesInterface *changes, changeListeners) { changes->sensorsChanged(); } } while (sensorsChanged); // We're going away now so clear the flag alreadyRunning = false; // Notify the client of the changes Q_EMIT availableSensorsChanged(); } }; Q_GLOBAL_STATIC(QSensorManagerPrivate, sensorManagerPrivate) // The unit test needs to change the behaviour of the library. It does this // through an exported but undocumented function. static void initPlugin(QObject *plugin); static bool settings_use_user_scope = false; static bool load_external_plugins = true; Q_SENSORS_EXPORT void sensors_unit_test_hook(int index) { QSensorManagerPrivate *d = sensorManagerPrivate(); switch (index) { case 0: Q_ASSERT(d->pluginsLoaded == false); settings_use_user_scope = true; load_external_plugins = false; break; case 1: Q_ASSERT(load_external_plugins == false); Q_ASSERT(d->pluginsLoaded == true); SENSORLOG() << "initializing plugins"; Q_FOREACH (QObject *plugin, pluginLoader()->plugins()) { initPlugin(plugin); } break; default: break; } } static void initPlugin(QObject *o) { if (!o) return; QSensorManagerPrivate *d = sensorManagerPrivate(); QSensorPluginInterface *plugin = qobject_cast<QSensorPluginInterface*>(o); if (plugin) plugin->registerSensors(); QSensorChangesInterface *changes = qobject_cast<QSensorChangesInterface*>(o); if (changes) d->changeListeners << changes; } void QSensorManagerPrivate::loadPlugins() { QSensorManagerPrivate *d = this; if (d->pluginsLoaded) return; d->pluginsLoaded = true; SENSORLOG() << "initializing static plugins"; Q_FOREACH (CreatePluginFunc func, d->staticRegistrations) { QSensorPluginInterface *plugin = func(); plugin->registerSensors(); } if (load_external_plugins) { SENSORLOG() << "initializing plugins"; Q_FOREACH (QObject *plugin, pluginLoader()->plugins()) { initPlugin(plugin); } } if (d->sensorsChanged) { // Notify the app that the available sensor list has changed. // This may cause recursive calls! d->emitSensorsChanged(); } } // ===================================================================== /*! \class QSensorManager \ingroup sensors_backend \inmodule QtSensors \brief The QSensorManager class handles registration and creation of sensor backends. Sensor plugins register backends using the registerBackend() function. When QSensor::connectToBackend() is called, the createBackend() function will be called. */ /*! Register a sensor for \a type. The \a identifier must be unique. The \a factory will be asked to create instances of the backend. */ void QSensorManager::registerBackend(const QByteArray &type, const QByteArray &identifier, QSensorBackendFactory *factory) { QSensorManagerPrivate *d = sensorManagerPrivate(); if (!d->backendsByType.contains(type)) { (void)d->backendsByType[type]; d->firstIdentifierForType[type] = identifier; } else if (d->firstIdentifierForType[type].startsWith("generic.")) { // Don't let a generic backend be the default when some other backend exists! d->firstIdentifierForType[type] = identifier; } FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[type]; if (factoryByIdentifier.contains(identifier)) { qWarning() << "A backend with type" << type << "and identifier" << identifier << "has already been registered!"; return; } SENSORLOG() << "registering backend for type" << type << "identifier" << identifier;// << "factory" << QString().sprintf("0x%08x", (unsigned int)factory); factoryByIdentifier[identifier] = factory; // Notify the app that the available sensor list has changed. // This may cause recursive calls! d->emitSensorsChanged(); } /*! Unregister the backend for \a type with \a identifier. Note that this only prevents new instance of the backend from being created. It does not invalidate the existing instances of the backend. The backend code should handle the disappearance of the underlying hardware itself. */ void QSensorManager::unregisterBackend(const QByteArray &type, const QByteArray &identifier) { QSensorManagerPrivate *d = sensorManagerPrivate(); if (!d->backendsByType.contains(type)) { qWarning() << "No backends of type" << type << "are registered"; return; } FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[type]; if (!factoryByIdentifier.contains(identifier)) { qWarning() << "Identifier" << identifier << "is not registered"; return; } (void)factoryByIdentifier.take(identifier); // we don't own this pointer anyway if (d->firstIdentifierForType[type] == identifier) { if (factoryByIdentifier.count()) { d->firstIdentifierForType[type] = factoryByIdentifier.begin().key(); if (d->firstIdentifierForType[type].startsWith("generic.")) { // Don't let a generic backend be the default when some other backend exists! for (FactoryForIdentifierMap::const_iterator it = factoryByIdentifier.begin()++; it != factoryByIdentifier.end(); it++) { const QByteArray &identifier(it.key()); if (!identifier.startsWith("generic.")) { d->firstIdentifierForType[type] = identifier; break; } } } } else { (void)d->firstIdentifierForType.take(type); } } if (!factoryByIdentifier.count()) (void)d->backendsByType.take(type); // Notify the app that the available sensor list has changed. // This may cause recursive calls! d->emitSensorsChanged(); } /*! \internal */ void QSensorManager::registerStaticPlugin(CreatePluginFunc func) { QSensorManagerPrivate *d = sensorManagerPrivate(); d->staticRegistrations.append(func); } /*! Create a backend for \a sensor. Returns null if no suitable backend exists. */ QSensorBackend *QSensorManager::createBackend(QSensor *sensor) { Q_ASSERT(sensor); QSensorManagerPrivate *d = sensorManagerPrivate(); d->loadPlugins(); SENSORLOG() << "QSensorManager::createBackend" << "type" << sensor->type() << "identifier" << sensor->identifier(); if (!d->backendsByType.contains(sensor->type())) { SENSORLOG() << "no backends of type" << sensor->type() << "have been registered."; return 0; } const FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[sensor->type()]; QSensorBackendFactory *factory; QSensorBackend *backend; if (sensor->identifier().isEmpty()) { QByteArray defaultIdentifier = QSensor::defaultSensorForType(sensor->type()); SENSORLOG() << "Trying the default" << defaultIdentifier; // No identifier set, try the default factory = factoryByIdentifier[defaultIdentifier]; //SENSORLOG() << "factory" << QString().sprintf("0x%08x", (unsigned int)factory); sensor->setIdentifier(defaultIdentifier); // the factory requires this backend = factory->createBackend(sensor); if (backend) return backend; // Got it! // The default failed to instantiate so try any other registered sensors for this type Q_FOREACH (const QByteArray &identifier, factoryByIdentifier.keys()) { SENSORLOG() << "Trying" << identifier; if (identifier == defaultIdentifier) continue; // Don't do the default one again factory = factoryByIdentifier[identifier]; //SENSORLOG() << "factory" << QString().sprintf("0x%08x", (unsigned int)factory); sensor->setIdentifier(identifier); // the factory requires this backend = factory->createBackend(sensor); if (backend) return backend; // Got it! } SENSORLOG() << "FAILED"; sensor->setIdentifier(QByteArray()); // clear the identifier } else { if (!factoryByIdentifier.contains(sensor->identifier())) { SENSORLOG() << "no backend with identifier" << sensor->identifier() << "for type" << sensor->type(); return 0; } // We were given an explicit identifier so don't substitute other backends if it fails to instantiate factory = factoryByIdentifier[sensor->identifier()]; //SENSORLOG() << "factory" << QString().sprintf("0x%08x", (unsigned int)factory); backend = factory->createBackend(sensor); if (backend) return backend; // Got it! } SENSORLOG() << "no suitable backend found for requested identifier" << sensor->identifier() << "and type" << sensor->type(); return 0; } /*! Returns true if the backend identified by \a type and \a identifier is registered. This is a convenience method that helps out plugins doing dynamic registration. */ bool QSensorManager::isBackendRegistered(const QByteArray &type, const QByteArray &identifier) { QSensorManagerPrivate *d = sensorManagerPrivate(); d->loadPlugins(); if (!d->backendsByType.contains(type)) return false; const FactoryForIdentifierMap &factoryByIdentifier = d->backendsByType[type]; if (!factoryByIdentifier.contains(identifier)) return false; return true; } // ===================================================================== /*! Returns a list of all sensor types. */ QList<QByteArray> QSensor::sensorTypes() { QSensorManagerPrivate *d = sensorManagerPrivate(); d->loadPlugins(); return d->backendsByType.keys(); } /*! Returns a list of ids for each of the sensors for \a type. If there are no sensors of that type available the list will be empty. */ QList<QByteArray> QSensor::sensorsForType(const QByteArray &type) { QSensorManagerPrivate *d = sensorManagerPrivate(); d->loadPlugins(); // no sensors of that type exist if (!d->backendsByType.contains(type)) return QList<QByteArray>(); return d->backendsByType[type].keys(); } /*! Returns the default sensor identifier for \a type. This is set in a config file and can be overridden if required. If no default is available the system will return the first registered sensor for \a type. Note that there is special case logic to prevent the generic plugin's backends from becoming the default when another backend is registered for the same type. This logic means that a backend identifier starting with \c{generic.} will only be the default if no other backends have been registered for that type or if it is specified in \c{Sensors.conf}. \sa {Determining the default sensor for a type} */ QByteArray QSensor::defaultSensorForType(const QByteArray &type) { QSensorManagerPrivate *d = sensorManagerPrivate(); d->loadPlugins(); // no sensors of that type exist if (!d->backendsByType.contains(type)) return QByteArray(); // The unit test needs to modify Sensors.conf but it can't access the system directory QSettings::Scope scope = settings_use_user_scope ? QSettings::UserScope : QSettings::SystemScope; QSettings settings(scope, QLatin1String("Nokia"), QLatin1String("Sensors")); QVariant value = settings.value(QString(QLatin1String("Default/%1")).arg(QString::fromLatin1(type))); if (!value.isNull()) { QByteArray defaultIdentifier = value.toByteArray(); if (d->backendsByType[type].contains(defaultIdentifier)) // Don't return a value that we can't use! return defaultIdentifier; } // This is our fallback return d->firstIdentifierForType[type]; } void QSensor::registerInstance() { QSensorManagerPrivate *d = sensorManagerPrivate(); connect(d, SIGNAL(availableSensorsChanged()), this, SIGNAL(availableSensorsChanged())); } // ===================================================================== /*! \class QSensorBackendFactory \ingroup sensors_backend \inmodule QtSensors \brief The QSensorBackendFactory class instantiates instances of QSensorBackend. This interface must be implemented in order to register a sensor backend. \sa {Creating a sensor plugin} */ /*! \fn QSensorBackendFactory::~QSensorBackendFactory() \internal */ /*! \fn QSensorBackendFactory::createBackend(QSensor *sensor) Instantiate a backend. If the factory handles multiple identifiers it should check with the \a sensor to see which one is requested. If the factory cannot create a backend it should return 0. */ /*! \macro REGISTER_STATIC_PLUGIN(pluginname) \relates QSensorManager Registers a static plugin, \a pluginname. Note that this macro relies on static initialization so it may not be appropriate for use in a library and may not work on all platforms. \sa {Creating a sensor plugin} */ #include "qsensormanager.moc" QTM_END_NAMESPACE <|endoftext|>
<commit_before>/* * 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. * * Written (W) 2012 Sergey Lisitsyn * Copyright (C) 2012 Sergey Lisitsyn */ #include <shogun/ui/GUIConverter.h> #include <shogun/ui/SGInterface.h> #include <shogun/lib/config.h> #include <shogun/io/SGIO.h> #include <shogun/features/DenseFeatures.h> #include <shogun/kernel/GaussianKernel.h> #include <shogun/converter/LocallyLinearEmbedding.h> #include <shogun/converter/HessianLocallyLinearEmbedding.h> #include <shogun/converter/LocalTangentSpaceAlignment.h> #include <shogun/converter/NeighborhoodPreservingEmbedding.h> #include <shogun/converter/LaplacianEigenmaps.h> #include <shogun/converter/LocalityPreservingProjections.h> #include <shogun/converter/DiffusionMaps.h> #include <shogun/converter/LinearLocalTangentSpaceAlignment.h> #include <shogun/converter/MultidimensionalScaling.h> #include <shogun/converter/Isomap.h> #include <shogun/converter/EmbeddingConverter.h> using namespace shogun; CGUIConverter::CGUIConverter(CSGInterface* ui) : CSGObject(), m_ui(ui) { m_converter = NULL; } CGUIConverter::~CGUIConverter() { SG_UNREF(m_converter); } bool CGUIConverter::create_locallylinearembedding(int32_t k) { #ifdef HAVE_LAPACK m_converter = new CLocallyLinearEmbedding(); ((CLocallyLinearEmbedding*)m_converter)->set_k(k); #else SG_ERROR("Requires Lapack to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_neighborhoodpreservingembedding(int32_t k) { #ifdef HAVE_LAPACK m_converter = new CNeighborhoodPreservingEmbedding(); ((CNeighborhoodPreservingEmbedding*)m_converter)->set_k(k); #else SG_ERROR("Requires Lapack to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_localtangentspacealignment(int32_t k) { #ifdef HAVE_LAPACK m_converter = new CLocalTangentSpaceAlignment(); ((CLocalTangentSpaceAlignment*)m_converter)->set_k(k); #else SG_ERROR("Requires Lapack to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_linearlocaltangentspacealignment(int32_t k) { #ifdef HAVE_LAPACK m_converter = new CLinearLocalTangentSpaceAlignment(); ((CLinearLocalTangentSpaceAlignment*)m_converter)->set_k(k); #else SG_ERROR("Requires Lapack to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_hessianlocallylinearembedding(int32_t k) { #ifdef HAVE_LAPACK m_converter = new CLocallyLinearEmbedding(); ((CHessianLocallyLinearEmbedding*)m_converter)->set_k(k); #else SG_ERROR("Requires Lapack to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_laplacianeigenmaps(int32_t k, float64_t width) { #ifdef HAVE_LAPACK m_converter = new CLaplacianEigenmaps(); ((CLaplacianEigenmaps*)m_converter)->set_k(k); ((CLaplacianEigenmaps*)m_converter)->set_tau(width); #else SG_ERROR("Requires Lapack to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_localitypreservingprojections(int32_t k, float64_t width) { #ifdef HAVE_LAPACK m_converter = new CLocalityPreservingProjections(); ((CLocalityPreservingProjections*)m_converter)->set_k(k); ((CLocalityPreservingProjections*)m_converter)->set_tau(width); #else SG_ERROR("Requires Lapack to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_diffusionmaps(int32_t t, float64_t width) { #ifdef HAVE_LAPACK m_converter = new CDiffusionMaps(); ((CDiffusionMaps*)m_converter)->set_t(t); ((CDiffusionMaps*)m_converter)->set_kernel(new CGaussianKernel(100,width)); #else SG_ERROR("Requires Lapack to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_isomap(int32_t k) { #ifdef HAVE_LAPACK m_converter = new CIsomap(); ((CIsomap*)m_converter)->set_k(k); #else SG_ERROR("Requires Lapack to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_multidimensionalscaling() { #ifdef HAVE_LAPACK m_converter = new CMultidimensionalScaling(); #else SG_ERROR("Requires Lapack to be enabled at compile time\n"); #endif return true; } CDenseFeatures<float64_t>* CGUIConverter::embed(int32_t target_dim) { if (!m_converter) SG_ERROR("No converter created"); ((CEmbeddingConverter*)m_converter)->set_target_dim(target_dim); return ((CEmbeddingConverter*)m_converter)->embed(m_ui->ui_features->get_train_features()); } <commit_msg>Fixed requirement in static converter interface<commit_after>/* * 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. * * Written (W) 2012 Sergey Lisitsyn * Copyright (C) 2012 Sergey Lisitsyn */ #include <shogun/ui/GUIConverter.h> #include <shogun/ui/SGInterface.h> #include <shogun/lib/config.h> #include <shogun/io/SGIO.h> #include <shogun/features/DenseFeatures.h> #include <shogun/kernel/GaussianKernel.h> #include <shogun/converter/LocallyLinearEmbedding.h> #include <shogun/converter/HessianLocallyLinearEmbedding.h> #include <shogun/converter/LocalTangentSpaceAlignment.h> #include <shogun/converter/NeighborhoodPreservingEmbedding.h> #include <shogun/converter/LaplacianEigenmaps.h> #include <shogun/converter/LocalityPreservingProjections.h> #include <shogun/converter/DiffusionMaps.h> #include <shogun/converter/LinearLocalTangentSpaceAlignment.h> #include <shogun/converter/MultidimensionalScaling.h> #include <shogun/converter/Isomap.h> #include <shogun/converter/EmbeddingConverter.h> using namespace shogun; CGUIConverter::CGUIConverter(CSGInterface* ui) : CSGObject(), m_ui(ui) { m_converter = NULL; } CGUIConverter::~CGUIConverter() { SG_UNREF(m_converter); } bool CGUIConverter::create_locallylinearembedding(int32_t k) { #ifdef HAVE_EIGEN3 m_converter = new CLocallyLinearEmbedding(); ((CLocallyLinearEmbedding*)m_converter)->set_k(k); #else SG_ERROR("Requires EIGEN3 to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_neighborhoodpreservingembedding(int32_t k) { #ifdef HAVE_EIGEN3 m_converter = new CNeighborhoodPreservingEmbedding(); ((CNeighborhoodPreservingEmbedding*)m_converter)->set_k(k); #else SG_ERROR("Requires EIGEN3 to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_localtangentspacealignment(int32_t k) { #ifdef HAVE_EIGEN3 m_converter = new CLocalTangentSpaceAlignment(); ((CLocalTangentSpaceAlignment*)m_converter)->set_k(k); #else SG_ERROR("Requires EIGEN3 to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_linearlocaltangentspacealignment(int32_t k) { #ifdef HAVE_EIGEN3 m_converter = new CLinearLocalTangentSpaceAlignment(); ((CLinearLocalTangentSpaceAlignment*)m_converter)->set_k(k); #else SG_ERROR("Requires EIGEN3 to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_hessianlocallylinearembedding(int32_t k) { #ifdef HAVE_EIGEN3 m_converter = new CLocallyLinearEmbedding(); ((CHessianLocallyLinearEmbedding*)m_converter)->set_k(k); #else SG_ERROR("Requires EIGEN3 to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_laplacianeigenmaps(int32_t k, float64_t width) { #ifdef HAVE_EIGEN3 m_converter = new CLaplacianEigenmaps(); ((CLaplacianEigenmaps*)m_converter)->set_k(k); ((CLaplacianEigenmaps*)m_converter)->set_tau(width); #else SG_ERROR("Requires EIGEN3 to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_localitypreservingprojections(int32_t k, float64_t width) { #ifdef HAVE_EIGEN3 m_converter = new CLocalityPreservingProjections(); ((CLocalityPreservingProjections*)m_converter)->set_k(k); ((CLocalityPreservingProjections*)m_converter)->set_tau(width); #else SG_ERROR("Requires EIGEN3 to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_diffusionmaps(int32_t t, float64_t width) { #ifdef HAVE_EIGEN3 m_converter = new CDiffusionMaps(); ((CDiffusionMaps*)m_converter)->set_t(t); ((CDiffusionMaps*)m_converter)->set_kernel(new CGaussianKernel(100,width)); #else SG_ERROR("Requires EIGEN3 to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_isomap(int32_t k) { #ifdef HAVE_EIGEN3 m_converter = new CIsomap(); ((CIsomap*)m_converter)->set_k(k); #else SG_ERROR("Requires EIGEN3 to be enabled at compile time\n"); #endif return true; } bool CGUIConverter::create_multidimensionalscaling() { #ifdef HAVE_EIGEN3 m_converter = new CMultidimensionalScaling(); #else SG_ERROR("Requires EIGEN3 to be enabled at compile time\n"); #endif return true; } CDenseFeatures<float64_t>* CGUIConverter::embed(int32_t target_dim) { if (!m_converter) SG_ERROR("No converter created"); ((CEmbeddingConverter*)m_converter)->set_target_dim(target_dim); return ((CEmbeddingConverter*)m_converter)->embed(m_ui->ui_features->get_train_features()); } <|endoftext|>
<commit_before>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010 Belledonne Communications SARL. 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 "flexisip/sip-boolean-expressions.hh" #include "flexisip/expressionparser-impl.cc" #include "sofia-sip/sip.h" using namespace std; namespace flexisip{ shared_ptr<SipBooleanExpressionBuilder> SipBooleanExpressionBuilder::sInstance; static inline string stringFromC(const char *s){ return s ? string(s) : string(); } static ExpressionRules<sip_t> rules = { { {"direction", [](const sip_t &sip)->string {return sip.sip_request != nullptr ? "request" : "response";} }, {"request.method-name", [](const sip_t &sip)->string { return stringFromC((sip.sip_request && sip.sip_request->rq_method_name) ? sip.sip_request->rq_method_name : nullptr);} }, {"request.method", [](const sip_t &sip)->string { return stringFromC((sip.sip_request && sip.sip_request->rq_method_name) ? sip.sip_request->rq_method_name : nullptr);} }, {"request.uri.domain", [](const sip_t &sip)->string { return stringFromC(sip.sip_request ? sip.sip_request->rq_url->url_host : nullptr);} }, {"request.uri.user", [](const sip_t &sip)->string { return stringFromC(sip.sip_request ? sip.sip_request->rq_url->url_user : nullptr);} }, {"request.uri.params", [](const sip_t &sip)->string { return stringFromC(sip.sip_request ? sip.sip_request->rq_url->url_params : nullptr);} }, {"from.uri.domain", [](const sip_t &sip)->string {return stringFromC(sip.sip_from ? sip.sip_from->a_url->url_host : nullptr);} }, {"from.uri.user", [](const sip_t &sip)->string {return stringFromC(sip.sip_from ? sip.sip_from->a_url->url_user : nullptr);} }, {"from.uri.params", [](const sip_t &sip)->string {return stringFromC(sip.sip_from ? sip.sip_from->a_url->url_params : nullptr);} }, {"to.uri.domain", [](const sip_t &sip)->string {return stringFromC(sip.sip_to ? sip.sip_to->a_url->url_host : nullptr);} }, {"to.uri.user", [](const sip_t &sip)->string {return stringFromC(sip.sip_to ? sip.sip_to->a_url->url_user : nullptr);} }, {"to.uri.params", [](const sip_t &sip)->string {return stringFromC(sip.sip_to ? sip.sip_to->a_url->url_params : nullptr);} }, {"user-agent", [](const sip_t &sip)->string {return stringFromC(sip.sip_user_agent ? sip.sip_user_agent->g_string : nullptr);} }, {"call-id", [](const sip_t &sip)->string {return stringFromC(sip.sip_call_id ? sip.sip_call_id->i_id : nullptr);} }, {"call-id.hash", [](const sip_t &sip)->string { ostringstream ostr; if (sip.sip_call_id) ostr << sip.sip_call_id->i_hash; return ostr.str(); } }, {"status.phrase", [](const sip_t &sip)->string {return stringFromC(sip.sip_status ? sip.sip_status->st_phrase : nullptr);} }, {"status.code", [](const sip_t &sip)->string { ostringstream ostr; if (sip.sip_status) ostr << sip.sip_status->st_status; return ostr.str(); } } }, { {"is_request", [](const sip_t & sip)->bool {return sip.sip_request != nullptr;} }, {"is_response", [](const sip_t & sip)->bool {return sip.sip_request == nullptr;} } } }; SipBooleanExpressionBuilder::SipBooleanExpressionBuilder() : BooleanExpressionBuilder<sip_t>(rules){ } SipBooleanExpressionBuilder &SipBooleanExpressionBuilder::get(){ if (!sInstance) { sInstance = shared_ptr<SipBooleanExpressionBuilder>(new SipBooleanExpressionBuilder()); } return *sInstance; } shared_ptr<SipBooleanExpression> SipBooleanExpressionBuilder::parse(const string &expression){ return BooleanExpressionBuilder<sip_t>::parse(expression); } }//end of namespace <commit_msg>Add "contact" header to the list of headers that can be used in entry filters of modules. This may be useful to prevent NatHelper module to alterate contact header in some situations, until a better solution is found.<commit_after>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010 Belledonne Communications SARL. 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 "flexisip/sip-boolean-expressions.hh" #include "flexisip/expressionparser-impl.cc" #include "sofia-sip/sip.h" using namespace std; namespace flexisip{ shared_ptr<SipBooleanExpressionBuilder> SipBooleanExpressionBuilder::sInstance; static inline string stringFromC(const char *s){ return s ? string(s) : string(); } static ExpressionRules<sip_t> rules = { { {"direction", [](const sip_t &sip)->string {return sip.sip_request != nullptr ? "request" : "response";} }, {"request.method-name", [](const sip_t &sip)->string { return stringFromC((sip.sip_request && sip.sip_request->rq_method_name) ? sip.sip_request->rq_method_name : nullptr);} }, {"request.method", [](const sip_t &sip)->string { return stringFromC((sip.sip_request && sip.sip_request->rq_method_name) ? sip.sip_request->rq_method_name : nullptr);} }, {"request.uri.domain", [](const sip_t &sip)->string { return stringFromC(sip.sip_request ? sip.sip_request->rq_url->url_host : nullptr);} }, {"request.uri.user", [](const sip_t &sip)->string { return stringFromC(sip.sip_request ? sip.sip_request->rq_url->url_user : nullptr);} }, {"request.uri.params", [](const sip_t &sip)->string { return stringFromC(sip.sip_request ? sip.sip_request->rq_url->url_params : nullptr);} }, {"from.uri.domain", [](const sip_t &sip)->string {return stringFromC(sip.sip_from ? sip.sip_from->a_url->url_host : nullptr);} }, {"from.uri.user", [](const sip_t &sip)->string {return stringFromC(sip.sip_from ? sip.sip_from->a_url->url_user : nullptr);} }, {"from.uri.params", [](const sip_t &sip)->string {return stringFromC(sip.sip_from ? sip.sip_from->a_url->url_params : nullptr);} }, {"to.uri.domain", [](const sip_t &sip)->string {return stringFromC(sip.sip_to ? sip.sip_to->a_url->url_host : nullptr);} }, {"to.uri.user", [](const sip_t &sip)->string {return stringFromC(sip.sip_to ? sip.sip_to->a_url->url_user : nullptr);} }, {"to.uri.params", [](const sip_t &sip)->string {return stringFromC(sip.sip_to ? sip.sip_to->a_url->url_params : nullptr);} }, {"contact.uri.domain", [](const sip_t &sip)->string {return stringFromC(sip.sip_contact ? sip.sip_contact->m_url->url_host : nullptr);} }, {"contact.uri.user", [](const sip_t &sip)->string {return stringFromC(sip.sip_contact ? sip.sip_contact->m_url->url_user : nullptr);} }, {"contact.uri.params", [](const sip_t &sip)->string {return stringFromC(sip.sip_contact ? sip.sip_contact->m_url->url_params : nullptr);} }, {"user-agent", [](const sip_t &sip)->string {return stringFromC(sip.sip_user_agent ? sip.sip_user_agent->g_string : nullptr);} }, {"call-id", [](const sip_t &sip)->string {return stringFromC(sip.sip_call_id ? sip.sip_call_id->i_id : nullptr);} }, {"call-id.hash", [](const sip_t &sip)->string { ostringstream ostr; if (sip.sip_call_id) ostr << sip.sip_call_id->i_hash; return ostr.str(); } }, {"status.phrase", [](const sip_t &sip)->string {return stringFromC(sip.sip_status ? sip.sip_status->st_phrase : nullptr);} }, {"status.code", [](const sip_t &sip)->string { ostringstream ostr; if (sip.sip_status) ostr << sip.sip_status->st_status; return ostr.str(); } } }, { {"is_request", [](const sip_t & sip)->bool {return sip.sip_request != nullptr;} }, {"is_response", [](const sip_t & sip)->bool {return sip.sip_request == nullptr;} } } }; SipBooleanExpressionBuilder::SipBooleanExpressionBuilder() : BooleanExpressionBuilder<sip_t>(rules){ } SipBooleanExpressionBuilder &SipBooleanExpressionBuilder::get(){ if (!sInstance) { sInstance = shared_ptr<SipBooleanExpressionBuilder>(new SipBooleanExpressionBuilder()); } return *sInstance; } shared_ptr<SipBooleanExpression> SipBooleanExpressionBuilder::parse(const string &expression){ return BooleanExpressionBuilder<sip_t>::parse(expression); } }//end of namespace <|endoftext|>
<commit_before>#ifndef COMBINATIONS_HPP_ #define COMBINATIONS_HPP_ #include "iterbase.hpp" #include <vector> #include <type_traits> #include <iterator> #include <initializer_list> namespace iter { template <typename Container> class Combinator; template <typename Container> Combinator<Container> combinations(Container&&, std::size_t); template <typename T> Combinator<std::initializer_list<T>> combinations( std::initializer_list<T>, std::size_t); template <typename Container> class Combinator { private: Container container; std::size_t length; friend Combinator combinations<Container>(Container&&,std::size_t); template <typename T> friend Combinator<std::initializer_list<T>> combinations( std::initializer_list<T>, std::size_t); Combinator(Container in_container, std::size_t in_length) : container(std::forward<Container>(in_container)), length{in_length} { } public: class Iterator { private: Container& items; std::vector<iterator_type<Container>> indicies; bool not_done = true; public: Iterator(Container& i, std::size_t n) : items(i), indicies(n) { if (n == 0) { not_done = false; return; } size_t inc = 0; for (auto& iter : this->indicies) { auto it = std::begin(this->items); dumb_advance(it, std::end(this->items), inc); if (it != std::end(this->items)) { iter = it; ++inc; } else { not_done = false; break; } } } std::vector<collection_item_type<Container>> operator*() { std::vector<collection_item_type<Container>> values; for (auto i : indicies) { values.push_back(*i); } return values; } Iterator& operator++() { for (auto iter = indicies.rbegin(); iter != indicies.rend(); ++iter) { ++(*iter); //what we have to check here is if the distance between //the index and the end of indicies is >= the distance //between the item and end of item auto dist = std::distance( this->indicies.rbegin(),iter); if (!(dumb_next(*iter, dist) != std::end(this->items))) { if ( (iter + 1) != indicies.rend()) { size_t inc = 1; for (auto down = iter; down != indicies.rbegin()-1; --down) { (*down) = dumb_next(*(iter + 1), 1 + inc); ++inc; } } else { not_done = false; break; } } else { break; } //we break because none of the rest of the items need //to be incremented } return *this; } bool operator !=(const Iterator&) { //because of the way this is done you have to start from //the begining of the range and end at the end, you could //break in the middle of the loop though, it's not //different from the way that python's works return not_done; } }; Iterator begin() { return {this->container, this->length}; } Iterator end() { return {this->container, this->length}; } }; template <typename Container> Combinator<Container> combinations( Container&& container, std::size_t length) { return {std::forward<Container>(container), length}; } template <typename T> Combinator<std::initializer_list<T>> combinations( std::initializer_list<T> il, std::size_t length) { return {il, length}; } } #endif //#ifndef COMBINATIONS_HPP_ <commit_msg>combination iterator inherits from std::iterator<commit_after>#ifndef ITER_COMBINATIONS_HPP_ #define ITER_COMBINATIONS_HPP_ #include "iterbase.hpp" #include <vector> #include <type_traits> #include <iterator> #include <initializer_list> namespace iter { template <typename Container> class Combinator; template <typename Container> Combinator<Container> combinations(Container&&, std::size_t); template <typename T> Combinator<std::initializer_list<T>> combinations( std::initializer_list<T>, std::size_t); template <typename Container> class Combinator { private: Container container; std::size_t length; friend Combinator combinations<Container>(Container&&,std::size_t); template <typename T> friend Combinator<std::initializer_list<T>> combinations( std::initializer_list<T>, std::size_t); Combinator(Container in_container, std::size_t in_length) : container(std::forward<Container>(in_container)), length{in_length} { } using CombIteratorDeref = std::vector<collection_item_type<Container>>; public: class Iterator : public std::iterator<std::input_iterator_tag, CombIteratorDeref> { private: Container& items; std::vector<iterator_type<Container>> indicies; bool not_done = true; public: Iterator(Container& i, std::size_t n) : items(i), indicies(n) { if (n == 0) { not_done = false; return; } size_t inc = 0; for (auto& iter : this->indicies) { auto it = std::begin(this->items); dumb_advance(it, std::end(this->items), inc); if (it != std::end(this->items)) { iter = it; ++inc; } else { not_done = false; break; } } } CombIteratorDeref operator*() { CombIteratorDeref values; for (auto i : indicies) { values.push_back(*i); } return values; } Iterator& operator++() { for (auto iter = indicies.rbegin(); iter != indicies.rend(); ++iter) { ++(*iter); //what we have to check here is if the distance between //the index and the end of indicies is >= the distance //between the item and end of item auto dist = std::distance( this->indicies.rbegin(),iter); if (!(dumb_next(*iter, dist) != std::end(this->items))) { if ( (iter + 1) != indicies.rend()) { size_t inc = 1; for (auto down = iter; down != indicies.rbegin()-1; --down) { (*down) = dumb_next(*(iter + 1), 1 + inc); ++inc; } } else { not_done = false; break; } } else { break; } //we break because none of the rest of the items need //to be incremented } return *this; } bool operator !=(const Iterator&) { //because of the way this is done you have to start from //the begining of the range and end at the end, you could //break in the middle of the loop though, it's not //different from the way that python's works return not_done; } }; Iterator begin() { return {this->container, this->length}; } Iterator end() { return {this->container, this->length}; } }; template <typename Container> Combinator<Container> combinations( Container&& container, std::size_t length) { return {std::forward<Container>(container), length}; } template <typename T> Combinator<std::initializer_list<T>> combinations( std::initializer_list<T> il, std::size_t length) { return {il, length}; } } #endif <|endoftext|>
<commit_before>/* vim: tabstop=2 shiftwidth=2 expandtab textwidth=80 linebreak wrap * * Copyright 2012 Matthew McCormick * Copyright 2015 Pawel 'l0ner' Soltys * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <sstream> #include "memory.h" #include "luts.h" #include "conversions.h" #include "powerline.h" std::string mem_string( const MemoryStatus & mem_status, MEMORY_MODE mode, bool use_colors, bool use_powerline_left, bool use_powerline_right ) { std::ostringstream oss; // Change the percision for floats, for a pretty output oss.precision( 2 ); oss.setf( std::ios::fixed | std::ios::right ); unsigned int color = static_cast< unsigned int >((100 * mem_status.used_mem) / mem_status.total_mem); if( use_colors ) { if( use_powerline_right ) { oss << "#[bg=default]"; powerline( oss, mem_lut[color], POWERLINE_RIGHT ); oss << ' '; } else if( use_powerline_left ) { //powerline( oss, mem_lut[color], POWERLINE_LEFT ); // We do not know how to invert the default background color powerline( oss, mem_lut[color], NONE ); oss << ' '; } else { powerline( oss, mem_lut[color], NONE ); } } switch( mode ) { case MEMORY_MODE_FREE_MEMORY: // Show free memory in MB or GB { const float free_mem = mem_status.total_mem - mem_status.used_mem; const float free_mem_in_gigabytes = convert_unit( free_mem, GIGABYTES, MEGABYTES ); // if free memory is less than 1 GB, use MB instead if( free_mem_in_gigabytes < 1.0f ) { oss << free_mem << "MB"; } else { oss << free_mem_in_gigabytes << "GB"; } break; } case MEMORY_MODE_USAGE_PERCENTAGE: { // Calculate the percentage of used memory const float percentage_mem = mem_status.used_mem / static_cast<float>( mem_status.total_mem ) * 100.0; oss << percentage_mem << '%'; break; } default: // Default mode, just show the used/total memory in MB if(mem_status.used_mem>100000 && mem_status.total_mem>100000) oss<<static_cast<unsigned int>(mem_status.used_mem/1024)<<"/"<<static_cast<unsigned int>(mem_status.total_mem/1024)<<"GB"; else if(mem_status.used_mem<100000 && mem_status.total_mem>100000) oss<<static_cast<unsigned int>(mem_status.used_mem)<<"MB/"<<static_cast<unsigned int>(mem_status.total_mem/1024)<<"GB"; else oss<<static_cast<unsigned int>(mem_status.used_mem)<<"/"<<static_cast<unsigned int>(mem_status.total_mem)<<"MB"; } if( use_colors ) { if( use_powerline_left ) { powerline( oss, mem_lut[color], POWERLINE_LEFT, true ); } else if( !use_powerline_right ) { oss << "#[fg=default,bg=default]"; } } return oss.str(); } <commit_msg>Less sensitive memory default thresholds<commit_after>/* vim: tabstop=2 shiftwidth=2 expandtab textwidth=80 linebreak wrap * * Copyright 2012 Matthew McCormick * Copyright 2015 Pawel 'l0ner' Soltys * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <sstream> #include "memory.h" #include "luts.h" #include "conversions.h" #include "powerline.h" std::string mem_string( const MemoryStatus & mem_status, MEMORY_MODE mode, bool use_colors, bool use_powerline_left, bool use_powerline_right ) { std::ostringstream oss; // Change the percision for floats, for a pretty output oss.precision( 2 ); oss.setf( std::ios::fixed | std::ios::right ); unsigned int color = static_cast< unsigned int >((100 * mem_status.used_mem) / mem_status.total_mem); if( use_colors ) { if( use_powerline_right ) { oss << "#[bg=default]"; powerline( oss, mem_lut[color], POWERLINE_RIGHT ); oss << ' '; } else if( use_powerline_left ) { //powerline( oss, mem_lut[color], POWERLINE_LEFT ); // We do not know how to invert the default background color powerline( oss, mem_lut[color], NONE ); oss << ' '; } else { powerline( oss, mem_lut[color], NONE ); } } switch( mode ) { case MEMORY_MODE_FREE_MEMORY: // Show free memory in MB or GB { const float free_mem = mem_status.total_mem - mem_status.used_mem; const float free_mem_in_gigabytes = convert_unit( free_mem, GIGABYTES, MEGABYTES ); // if free memory is less than 1 GB, use MB instead if( free_mem_in_gigabytes < 1.0f ) { oss << free_mem << "MB"; } else { oss << free_mem_in_gigabytes << "GB"; } break; } case MEMORY_MODE_USAGE_PERCENTAGE: { // Calculate the percentage of used memory const float percentage_mem = mem_status.used_mem / static_cast<float>( mem_status.total_mem ) * 100.0; oss << percentage_mem << '%'; break; } default: // Default mode, just show the used/total memory in MB if(mem_status.used_mem>10000 && mem_status.total_mem>10000) oss<<static_cast<unsigned int>(mem_status.used_mem/1024)<<"/"<<static_cast<unsigned int>(mem_status.total_mem/1024)<<"GB"; else if(mem_status.used_mem<10000 && mem_status.total_mem>10000) oss<<static_cast<unsigned int>(mem_status.used_mem)<<"MB/"<<static_cast<unsigned int>(mem_status.total_mem/1024)<<"GB"; else oss<<static_cast<unsigned int>(mem_status.used_mem)<<"/"<<static_cast<unsigned int>(mem_status.total_mem)<<"MB"; } if( use_colors ) { if( use_powerline_left ) { powerline( oss, mem_lut[color], POWERLINE_LEFT, true ); } else if( !use_powerline_right ) { oss << "#[fg=default,bg=default]"; } } return oss.str(); } <|endoftext|>
<commit_before>#ifndef __MODEL_HPP_INCLUDED #define __MODEL_HPP_INCLUDED // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> #endif // Include GLFW #ifndef __GLFW3_H_INCLUDED #define __GLFW3_H_INCLUDED #include <glfw3.h> #endif // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> #endif #include <iostream> #include <queue> // std::queue #include <string.h> #include "globals.hpp" #include "shader.hpp" #include "heightmap_loader.hpp" #include "objloader.hpp" namespace model { class World { friend class Shader; friend class Species; public: // constructor. World(); // destructor. ~World(); // this method renders the entire world, one shader at a time. void render(); protected: // this method sets a shader pointer. void set_shader_pointer(GLuint shaderID, void* shader_pointer); // this method gets a shader pointer. void* get_shader_pointer(GLuint shaderID); // this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue. GLuint get_shaderID(); // this method sets a world species pointer. void set_world_species_pointer(void* world_species_pointer); private: void compute_matrices_from_inputs(); void* world_species_pointer; // pointer to world species (used in collision detection). std::vector<void*> shader_pointer_vector; std::queue<GLuint> free_shaderID_queue; }; class Shader { friend class World; friend class Texture; friend class Species; friend class Object; public: // constructor. Shader(ShaderStruct shader_struct); // destructor. ~Shader(); protected: // this method renders all textures using this shader. void render(); // this method sets a texture pointer. void set_texture_pointer(GLuint textureID, void* texture_pointer); // this method gets a texture pointer. void* get_texture_pointer(GLuint textureID); // this method gets a texture ID and removes it from the `free_textureID_queue` if it was popped from the queue. GLuint get_textureID(); // this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world. void switch_to_new_world(model::World *new_world_pointer); // this method sets a world species pointer. void set_world_species_pointer(void* world_species_pointer); model::World *world_pointer; // pointer to the world. GLuint programID; // shaders' programID, returned by `LoadShaders`. GLuint MatrixID; GLuint ViewMatrixID; GLuint ModelMatrixID; private: void bind_to_world(); void* world_species_pointer; // pointer to world species (used in collision detection). GLuint shaderID; // shader ID, returned by `model::World->get_shaderID()`. std::string vertex_shader; // filename of vertex shader. std::string fragment_shader; // filename of fragment shader. std::vector<void*> texture_pointer_vector; std::queue<GLuint> free_textureID_queue; const char *char_vertex_shader; const char *char_fragment_shader; }; class Texture { friend class Shader; friend class Species; friend class Object; public: // constructor. Texture(TextureStruct texture_struct); // destructor. ~Texture(); protected: // this method renders all species using this texture. void render(); // this method sets a species pointer. void set_species_pointer(GLuint speciesID, void* species_pointer); // this method gets a species pointer. void* get_species_pointer(GLuint speciesID); // this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue. GLuint get_speciesID(); // this method sets pointer to this shader to NULL, sets `shader_pointer` according to the input, and requests a new `textureID` from the new shader. void switch_to_new_shader(model::Shader *new_world_pointer); // this method sets a world species pointer. void set_world_species_pointer(void* world_species_pointer); model::Shader *shader_pointer; // pointer to the shader. private: void bind_to_shader(); void* world_species_pointer; // pointer to world species (used in collision detection). GLuint texture; // Texture, returned by `load_DDS_texture` or `load_BMP_texture`. GLuint openGL_textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`. std::vector<void*> species_pointer_vector; std::queue<GLuint> free_speciesID_queue; std::string texture_file_format; // type of the model file, eg. `"bmp"`. std::string texture_filename; // filename of the model file. GLuint textureID; // texture ID, returned by `Shader::get_textureID`. const char *char_texture_file_format; const char *char_texture_filename; }; class Graph { friend class Node; public: // constructor. Graph(); // destructor. ~Graph(); protected: // this method sets a node pointer. void set_node_pointer(GLuint nodeID, void* node_pointer); // this method gets a node pointer. void* get_node_pointer(GLuint nodeID); // this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue. GLuint get_nodeID(); private: std::vector<void*> node_pointer_vector; std::queue<GLuint> free_nodeID_queue; }; // `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph. // Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s. // The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`). class Node { public: // constructor. Node(NodeStruct node_struct); // destructor. ~Node(); // this method creates a bidirectional link. // creating of bidirectional links is not possible before all nodes are created. void create_bidirectional_link(GLuint nodeID); // this method deletes a bidirectional link. // deleting of links is not possible before all nodes are created. void delete_bidirectional_link(GLuint nodeID); // this method transfers this node to a new graph. // links will not be changed. // all nodes that are to be transferred must be transferred separately. // before transfering any node to a new graph, // all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls. void transfer_to_new_graph(model::Graph *new_graph_pointer); GLuint nodeID; model::Graph *graph_pointer; private: // nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created. std::vector<GLuint> neighbor_nodeIDs; // this method creates an unidirectional link. // in the constructor only unidirectional links can be created. void create_unidirectional_link(GLuint nodeID); // this method deletes an unidirectional link. void delete_unidirectional_link(GLuint nodeID); glm::vec3 coordinate_vector; }; class Species { public: // constructor. Species(SpeciesStruct species_struct); // destructor. ~Species(); // this method renders all objects of this species. void render(); // this method sets a object pointer. void set_object_pointer(GLuint objectID, void* object_pointer); // this method gets a object pointer. void* get_object_pointer(GLuint objectID); // this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue. GLuint get_objectID(); // this method sets pointer to this species to NULL, sets `texture_pointer` according to the input, and requests a new `speciesID` from the new texture. void switch_to_new_texture(model::Texture *new_texture_pointer); bool is_world; // worlds currently do not rotate nor translate. std::string color_channel; // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`. std::vector<ObjectStruct> object_vector; // vector of individual objects of this species. glm::vec3 lightPos; // light position. // The rest fields are created in the constructor. GLuint image_width; GLuint image_height; GLuint vertexPosition_modelspaceID; GLuint vertexUVID; GLuint vertexNormal_modelspaceID; std::vector<glm::vec3> vertices; // vertices of the object. std::vector<glm::vec2> UVs; // UVs of the object. std::vector<glm::vec3> normals; // normals of the object. std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory). std::vector<glm::vec3> indexed_vertices; std::vector<glm::vec2> indexed_UVs; std::vector<glm::vec3> indexed_normals; GLuint vertexbuffer; GLuint uvbuffer; GLuint normalbuffer; GLuint elementbuffer; model::Texture *texture_pointer; // pointer to the texture. private: void bind_to_texture(); std::string model_file_format; // type of the model file, eg. `"bmp"`. std::string model_filename; // filename of the model file. GLuint speciesID; // species ID, returned by `model::Texture->get_speciesID()`. GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`. const char *char_model_file_format; const char *char_model_filename; const char *char_color_channel; std::vector<void*> object_pointer_vector; std::queue<GLuint> free_objectID_queue; }; class Font { public: // constructor. Font(FontStruct font_struct); // destructor. ~Font(); // this method renders all objects of this species. void render(); // this method sets a glyph pointer. void set_glyph_pointer(GLuint objectID, void* object_pointer); // this method gets a glyph pointer. void* get_glyph_pointer(GLuint objectID); // this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue. GLuint get_glyphID(); // this method sets pointer to this species to NULL, sets `texture_pointer` according to the input, and requests a new `speciesID` from the new texture. void switch_to_new_texture(model::Texture *new_texture_pointer); std::vector<ObjectStruct> object_vector; // vector of individual objects of this species. glm::vec3 lightPos; // light position. // The rest fields are created in the constructor. GLuint image_width; GLuint image_height; model::Texture *texture_pointer; // pointer to the texture. private: void bind_to_texture(); std::string model_file_format; // type of the model file, eg. `"bmp"`. std::string model_filename; // filename of the model file. GLuint speciesID; // species ID, returned by `model::Texture->get_speciesID()`. GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`. const char *char_model_file_format; const char *char_model_filename; const char *char_color_channel; std::vector<void*> object_pointer_vector; std::queue<GLuint> free_objectID_queue; }; class Glyph { public: // constructor. Glyph(GlyphStruct glyph_struct); // destructor. ~Glyph(); // this method renders all objects of this species. void render(); // this method sets a object pointer. void set_object_pointer(GLuint objectID, void* object_pointer); // this method gets a object pointer. void* get_object_pointer(GLuint objectID); // this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue. GLuint get_objectID(); // The rest fields are created in the constructor. GLuint image_width; GLuint image_height; GLuint vertexPosition_modelspaceID; GLuint vertexUVID; GLuint vertexNormal_modelspaceID; std::vector<glm::vec3> vertices; // vertices of the object. std::vector<glm::vec2> UVs; // UVs of the object. std::vector<glm::vec3> normals; // normals of the object. std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory). std::vector<glm::vec3> indexed_vertices; std::vector<glm::vec2> indexed_UVs; std::vector<glm::vec3> indexed_normals; GLuint vertexbuffer; GLuint uvbuffer; GLuint normalbuffer; GLuint elementbuffer; model::Font *font_pointer; // pointer to the font. private: void bind_to_font(); GLuint glyphID; // glyph ID, returned by `model::Font->get_glyphID()`. GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`. std::vector<void*> object_pointer_vector; std::queue<GLuint> free_objectID_queue; }; class Object { public: // constructor. Object(ObjectStruct object_struct); // destructor. ~Object(); // this method renders this object. void render(); // this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species. void switch_to_new_species(model::Species *new_species_pointer); private: void bind_to_species(); model::Species *species_pointer; // pointer to the species. GLuint objectID; // object ID, returned by `model::Species->get_objectID()`. bool has_entered; glm::vec3 coordinate_vector; // coordinate vector. glm::vec3 original_scale_vector; // original scale vector. GLfloat rotate_angle; // rotate angle. glm::vec3 rotate_vector; // rotate vector. glm::vec3 translate_vector; // translate vector. // The rest fields are created in the constructor. glm::mat4 model_matrix; // model matrix. std::vector<glm::vec3> vertices; // vertices of the object. std::vector<glm::vec2> UVs; // UVs of the object. std::vector<glm::vec3> normals; // normals of the object. not used at the moment. glm::mat4 MVP_matrix; // model view projection matrix. }; } #endif <commit_msg>`namespace model`: `protected:` -> `private:`.<commit_after>#ifndef __MODEL_HPP_INCLUDED #define __MODEL_HPP_INCLUDED // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> #endif // Include GLFW #ifndef __GLFW3_H_INCLUDED #define __GLFW3_H_INCLUDED #include <glfw3.h> #endif // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> #endif #include <iostream> #include <queue> // std::queue #include <string.h> #include "globals.hpp" #include "shader.hpp" #include "heightmap_loader.hpp" #include "objloader.hpp" namespace model { class World { friend class Shader; friend class Species; public: // constructor. World(); // destructor. ~World(); // this method renders the entire world, one shader at a time. void render(); private: // this method sets a shader pointer. void set_shader_pointer(GLuint shaderID, void* shader_pointer); // this method gets a shader pointer. void* get_shader_pointer(GLuint shaderID); // this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue. GLuint get_shaderID(); // this method sets a world species pointer. void set_world_species_pointer(void* world_species_pointer); void compute_matrices_from_inputs(); void* world_species_pointer; // pointer to world species (used in collision detection). std::vector<void*> shader_pointer_vector; std::queue<GLuint> free_shaderID_queue; }; class Shader { friend class World; friend class Texture; friend class Species; friend class Object; public: // constructor. Shader(ShaderStruct shader_struct); // destructor. ~Shader(); private: // this method renders all textures using this shader. void render(); // this method sets a texture pointer. void set_texture_pointer(GLuint textureID, void* texture_pointer); // this method gets a texture pointer. void* get_texture_pointer(GLuint textureID); // this method gets a texture ID and removes it from the `free_textureID_queue` if it was popped from the queue. GLuint get_textureID(); // this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world. void switch_to_new_world(model::World *new_world_pointer); // this method sets a world species pointer. void set_world_species_pointer(void* world_species_pointer); model::World *world_pointer; // pointer to the world. GLuint programID; // shaders' programID, returned by `LoadShaders`. GLuint MatrixID; GLuint ViewMatrixID; GLuint ModelMatrixID; void bind_to_world(); void* world_species_pointer; // pointer to world species (used in collision detection). GLuint shaderID; // shader ID, returned by `model::World->get_shaderID()`. std::string vertex_shader; // filename of vertex shader. std::string fragment_shader; // filename of fragment shader. std::vector<void*> texture_pointer_vector; std::queue<GLuint> free_textureID_queue; const char *char_vertex_shader; const char *char_fragment_shader; }; class Texture { friend class Shader; friend class Species; friend class Object; public: // constructor. Texture(TextureStruct texture_struct); // destructor. ~Texture(); private: // this method renders all species using this texture. void render(); // this method sets a species pointer. void set_species_pointer(GLuint speciesID, void* species_pointer); // this method gets a species pointer. void* get_species_pointer(GLuint speciesID); // this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue. GLuint get_speciesID(); // this method sets pointer to this shader to NULL, sets `shader_pointer` according to the input, and requests a new `textureID` from the new shader. void switch_to_new_shader(model::Shader *new_world_pointer); // this method sets a world species pointer. void set_world_species_pointer(void* world_species_pointer); model::Shader *shader_pointer; // pointer to the shader. void bind_to_shader(); void* world_species_pointer; // pointer to world species (used in collision detection). GLuint texture; // Texture, returned by `load_DDS_texture` or `load_BMP_texture`. GLuint openGL_textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`. std::vector<void*> species_pointer_vector; std::queue<GLuint> free_speciesID_queue; std::string texture_file_format; // type of the model file, eg. `"bmp"`. std::string texture_filename; // filename of the model file. GLuint textureID; // texture ID, returned by `Shader::get_textureID`. const char *char_texture_file_format; const char *char_texture_filename; }; class Graph { friend class Node; public: // constructor. Graph(); // destructor. ~Graph(); private: // this method sets a node pointer. void set_node_pointer(GLuint nodeID, void* node_pointer); // this method gets a node pointer. void* get_node_pointer(GLuint nodeID); // this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue. GLuint get_nodeID(); std::vector<void*> node_pointer_vector; std::queue<GLuint> free_nodeID_queue; }; // `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph. // Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s. // The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`). class Node { public: // constructor. Node(NodeStruct node_struct); // destructor. ~Node(); // this method creates a bidirectional link. // creating of bidirectional links is not possible before all nodes are created. void create_bidirectional_link(GLuint nodeID); // this method deletes a bidirectional link. // deleting of links is not possible before all nodes are created. void delete_bidirectional_link(GLuint nodeID); // this method transfers this node to a new graph. // links will not be changed. // all nodes that are to be transferred must be transferred separately. // before transfering any node to a new graph, // all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls. void transfer_to_new_graph(model::Graph *new_graph_pointer); GLuint nodeID; model::Graph *graph_pointer; private: // nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created. std::vector<GLuint> neighbor_nodeIDs; // this method creates an unidirectional link. // in the constructor only unidirectional links can be created. void create_unidirectional_link(GLuint nodeID); // this method deletes an unidirectional link. void delete_unidirectional_link(GLuint nodeID); glm::vec3 coordinate_vector; }; class Species { public: // constructor. Species(SpeciesStruct species_struct); // destructor. ~Species(); // this method renders all objects of this species. void render(); // this method sets a object pointer. void set_object_pointer(GLuint objectID, void* object_pointer); // this method gets a object pointer. void* get_object_pointer(GLuint objectID); // this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue. GLuint get_objectID(); // this method sets pointer to this species to NULL, sets `texture_pointer` according to the input, and requests a new `speciesID` from the new texture. void switch_to_new_texture(model::Texture *new_texture_pointer); bool is_world; // worlds currently do not rotate nor translate. std::string color_channel; // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`. std::vector<ObjectStruct> object_vector; // vector of individual objects of this species. glm::vec3 lightPos; // light position. // The rest fields are created in the constructor. GLuint image_width; GLuint image_height; GLuint vertexPosition_modelspaceID; GLuint vertexUVID; GLuint vertexNormal_modelspaceID; std::vector<glm::vec3> vertices; // vertices of the object. std::vector<glm::vec2> UVs; // UVs of the object. std::vector<glm::vec3> normals; // normals of the object. std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory). std::vector<glm::vec3> indexed_vertices; std::vector<glm::vec2> indexed_UVs; std::vector<glm::vec3> indexed_normals; GLuint vertexbuffer; GLuint uvbuffer; GLuint normalbuffer; GLuint elementbuffer; model::Texture *texture_pointer; // pointer to the texture. private: void bind_to_texture(); std::string model_file_format; // type of the model file, eg. `"bmp"`. std::string model_filename; // filename of the model file. GLuint speciesID; // species ID, returned by `model::Texture->get_speciesID()`. GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`. const char *char_model_file_format; const char *char_model_filename; const char *char_color_channel; std::vector<void*> object_pointer_vector; std::queue<GLuint> free_objectID_queue; }; class Font { public: // constructor. Font(FontStruct font_struct); // destructor. ~Font(); // this method renders all objects of this species. void render(); // this method sets a glyph pointer. void set_glyph_pointer(GLuint objectID, void* object_pointer); // this method gets a glyph pointer. void* get_glyph_pointer(GLuint objectID); // this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue. GLuint get_glyphID(); // this method sets pointer to this species to NULL, sets `texture_pointer` according to the input, and requests a new `speciesID` from the new texture. void switch_to_new_texture(model::Texture *new_texture_pointer); std::vector<ObjectStruct> object_vector; // vector of individual objects of this species. glm::vec3 lightPos; // light position. // The rest fields are created in the constructor. GLuint image_width; GLuint image_height; model::Texture *texture_pointer; // pointer to the texture. private: void bind_to_texture(); std::string model_file_format; // type of the model file, eg. `"bmp"`. std::string model_filename; // filename of the model file. GLuint speciesID; // species ID, returned by `model::Texture->get_speciesID()`. GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`. const char *char_model_file_format; const char *char_model_filename; const char *char_color_channel; std::vector<void*> object_pointer_vector; std::queue<GLuint> free_objectID_queue; }; class Glyph { public: // constructor. Glyph(GlyphStruct glyph_struct); // destructor. ~Glyph(); // this method renders all objects of this species. void render(); // this method sets a object pointer. void set_object_pointer(GLuint objectID, void* object_pointer); // this method gets a object pointer. void* get_object_pointer(GLuint objectID); // this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue. GLuint get_objectID(); // The rest fields are created in the constructor. GLuint image_width; GLuint image_height; GLuint vertexPosition_modelspaceID; GLuint vertexUVID; GLuint vertexNormal_modelspaceID; std::vector<glm::vec3> vertices; // vertices of the object. std::vector<glm::vec2> UVs; // UVs of the object. std::vector<glm::vec3> normals; // normals of the object. std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory). std::vector<glm::vec3> indexed_vertices; std::vector<glm::vec2> indexed_UVs; std::vector<glm::vec3> indexed_normals; GLuint vertexbuffer; GLuint uvbuffer; GLuint normalbuffer; GLuint elementbuffer; model::Font *font_pointer; // pointer to the font. private: void bind_to_font(); GLuint glyphID; // glyph ID, returned by `model::Font->get_glyphID()`. GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`. std::vector<void*> object_pointer_vector; std::queue<GLuint> free_objectID_queue; }; class Object { public: // constructor. Object(ObjectStruct object_struct); // destructor. ~Object(); // this method renders this object. void render(); // this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species. void switch_to_new_species(model::Species *new_species_pointer); private: void bind_to_species(); model::Species *species_pointer; // pointer to the species. GLuint objectID; // object ID, returned by `model::Species->get_objectID()`. bool has_entered; glm::vec3 coordinate_vector; // coordinate vector. glm::vec3 original_scale_vector; // original scale vector. GLfloat rotate_angle; // rotate angle. glm::vec3 rotate_vector; // rotate vector. glm::vec3 translate_vector; // translate vector. // The rest fields are created in the constructor. glm::mat4 model_matrix; // model matrix. std::vector<glm::vec3> vertices; // vertices of the object. std::vector<glm::vec2> UVs; // UVs of the object. std::vector<glm::vec3> normals; // normals of the object. not used at the moment. glm::mat4 MVP_matrix; // model view projection matrix. }; } #endif <|endoftext|>
<commit_before>#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #include<queue> #include<iomanip> using namespace std; #define ll long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) #define Find(Arr,size,x) (lower_bound(&Arr[1],&Arr[size+1],x)-Arr) const int maxN=2010; const int maxNode=maxN*20; const int maxM=maxNode*4; const int inf=2147483647; class Point { public: int x,y,id; }; int n,Sx,Sy,Tx,Ty,S,T; int A[maxN],B[maxN],C[maxN],D[maxN]; int nx,Nx[maxNode],ny,Ny[maxNode]; int edgecnt=0,Head[maxNode],Next[maxM],V[maxM],W[maxM]; int stu[maxN][maxN],Id[maxN][maxN],pcnt; Point P[maxNode]; bool Exi[maxN],inq[maxNode]; int Dist[maxNode]; queue<int> Q; void Go(int x,int y,int dx,int dy); bool cmpx(Point P1,Point P2); bool cmpy(Point P1,Point P2); void Add_Edge(int u,int v,int w); void Spfa(); int main(){ int TTT;scanf("%d",&TTT); while (TTT--){ nx=ny=edgecnt=0;mem(Nx,0);mem(Ny,0);mem(stu,0);mem(Id,0);mem(Head,-1);mem(Exi,0); scanf("%d%d%d%d",&Sx,&Sy,&Tx,&Ty); Nx[++nx]=Sx;Nx[++nx]=Tx;Ny[++ny]=Sy,Ny[++ny]=Ty; scanf("%d",&n); bool flag=1; for (int i=1;i<=n;i++){ scanf("%d%d%d%d",&A[i],&B[i],&C[i],&D[i]);Exi[i]=1; if (A[i]>C[i]) swap(A[i],C[i]); if (B[i]>D[i]) swap(B[i],D[i]); if ((A[i]<Sx)&&(C[i]>Sx)&&(B[i]<Sy)&&(D[i]>Sy)) flag=0; if ((A[i]<Tx)&&(C[i]>Tx)&&(B[i]<Ty)&&(D[i]>Ty)) flag=0; Nx[++nx]=A[i];Nx[++nx]=C[i];Ny[++ny]=B[i];Ny[++ny]=D[i]; } if (flag==0){ printf("No Path\n");continue; } for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) if (i!=j) if ((A[j]<=A[i])&&(B[j]<=B[i])&&(C[j]>=C[i])&&(D[j]>=D[i])){ Exi[i]=0;break; } sort(&Nx[1],&Nx[nx+1]);nx=unique(&Nx[1],&Nx[nx+1])-Nx-1; sort(&Ny[1],&Ny[ny+1]);ny=unique(&Ny[1],&Ny[ny+1])-Ny-1; cout<<"Nx:";for (int i=1;i<=nx;i++) cout<<Nx[i]<<" ";cout<<endl; cout<<"Ny:";for (int i=1;i<=ny;i++) cout<<Ny[i]<<" ";cout<<endl; Sx=Find(Nx,nx,Sx);Sy=Find(Ny,ny,Sy);Tx=Find(Nx,nx,Tx);Ty=Find(Ny,ny,Ty); for (int i=1;i<=n;i++) A[i]=Find(Nx,nx,A[i]),B[i]=Find(Ny,ny,B[i]),C[i]=Find(Nx,nx,C[i]),D[i]=Find(Ny,ny,D[i]); cout<<Sx<<" "<<Sy<<" "<<Tx<<" "<<Ty<<endl; for (int i=1;i<=n;i++) cout<<"("<<A[i]<<","<<B[i]<<") ("<<C[i]<<","<<D[i]<<")"<<endl; for (int i=1;i<=n;i++){ if (Exi[i]==0) continue; for (int j=A[i];j<=C[i];j++) stu[j][B[i]]=1,stu[j][D[i]]=2; for (int j=B[i];j<=D[i];j++) stu[A[i]][j]=1,stu[C[i]][j]=2; stu[A[i]][B[i]]=stu[A[i]][D[i]]=stu[C[i]][B[i]]=stu[C[i]][D[i]]=-1; } stu[Sx][Sy]=stu[Tx][Ty]=-1; for (int i=1;i<=nx;i++){ for (int j=1;j<=ny;j++) cout<<setw(4)<<stu[i][j]; cout<<endl; } for (int i=1;i<=n;i++){ if (Exi[i]==0) continue; Go(A[i],B[i],-1,0);Go(A[i],B[i],0,-1);Go(A[i],D[i],-1,0);Go(A[i],D[i],0,1); Go(C[i],B[i],1,0);Go(C[i],B[i],0,-1);Go(C[i],D[i],1,0);Go(C[i],D[i],0,1); Id[A[i]][B[i]]=Id[A[i]][D[i]]=Id[C[i]][B[i]]=Id[C[i]][D[i]]=1; } Id[Sx][Sy]=Id[Tx][Ty]=1; cout<<endl; for (int i=1;i<=nx;i++){ for (int j=1;j<=ny;j++) cout<<setw(4)<<Id[i][j]; cout<<endl; } for (int i=1;i<=nx;i++) for (int j=1;j<=ny;j++){ if (Id[i][j]) P[++pcnt]=((Point){i,j,pcnt}); if ((i==Sx)&&(j==Sy)) S=pcnt; if ((i==Tx)&&(j==Ty)) T=pcnt; } sort(&P[1],&P[pcnt+1],cmpx); for (int i=1,j;i<=pcnt;i=j){ j=i+1; while (P[j].x==P[i].x){ if ((stu[P[j-1].x][P[j-1].y]==-1)||(stu[P[j].x][P[j].y]==-1)||((stu[P[j-1].x][P[j-1].y]==2)&&(stu[P[j].x][P[j].y]==1))) Add_Edge(P[j-1].id,P[j].id,abs(Ny[P[j].y]-Ny[P[j-1].y])); j++; } } sort(&P[1],&P[pcnt+1],cmpy); for (int i=1,j;i<=pcnt;i=j){ j=i+1; while (P[j].y==P[i].y){ if ((stu[P[j-1].x][P[j-1].y]==-1)||(stu[P[j].x][P[j].y]==-1)||((stu[P[j-1].x][P[j-1].y]==2)&&(stu[P[j].x][P[j].y]==1))) Add_Edge(P[j-1].id,P[j].id,abs(Nx[P[j].x]-Nx[P[j-1].x])); j++; } } Spfa(); if (Dist[T]==inf) printf("No Path\n"); else printf("%d\n",Dist[T]); } return 0; } void Add_Edge(int u,int v,int w){ Next[++edgecnt]=Head[u];Head[u]=edgecnt;V[edgecnt]=v;W[edgecnt]=w; Next[++edgecnt]=Head[v];Head[v]=edgecnt;V[edgecnt]=u;W[edgecnt]=w; return; } void Go(int x,int y,int dx,int dy){ x+=dx;y+=dy; while (stu[x][y]==0){ if ((x<1)||(y<1)||(x>nx)||(y>ny)) return; x+=dx;y+=dy; } Id[x][y]=1;return; } bool cmpx(Point P1,Point P2){ if (P1.x!=P2.x) return P1.x<P2.x; return P1.y<P2.y; } bool cmpy(Point P1,Point P2){ if (P1.y!=P2.y) return P1.y<P2.y; return P1.x<P2.x; } void Spfa(){ for (int i=1;i<=pcnt;i++) Dist[i]=inf; Dist[S]=0;inq[S]=1;Q.push(S); while (!Q.empty()){ int u=Q.front();Q.pop(); for (int i=Head[u];i!=-1;i=Next[i]) if (Dist[V[i]]>Dist[u]+W[i]){ Dist[V[i]]=Dist[u]+W[i]; if (inq[V[i]]==0){ Q.push(V[i]);inq[V[i]]=1; } } inq[u]=0; } return; } <commit_msg>2018.10.2 noon<commit_after>#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #include<queue> #include<iomanip> using namespace std; #define ll long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) #define Find(Arr,size,x) (lower_bound(&Arr[1],&Arr[size+1],x)-Arr) const int maxN=2010; const int maxNode=maxN*20; const int maxM=maxNode*4; const int inf=2147483647; class Point { public: int x,y,id; }; int n,Sx,Sy,Tx,Ty,S,T; int A[maxN],B[maxN],C[maxN],D[maxN]; int nx,Nx[maxNode],ny,Ny[maxNode]; int edgecnt=0,Head[maxNode],Next[maxM],V[maxM],W[maxM]; int stu[maxN][maxN],Id[maxN][maxN],pcnt; Point P[maxNode]; bool Exi[maxN],inq[maxNode]; int Dist[maxNode]; queue<int> Q; void Go(int x,int y,int dx,int dy); bool cmpx(Point P1,Point P2); bool cmpy(Point P1,Point P2); void Add_Edge(int u,int v,int w); void Spfa(); int main(){ int TTT;scanf("%d",&TTT); while (TTT--){ nx=ny=edgecnt=pcnt=0;mem(Nx,0);mem(Ny,0);mem(stu,0);mem(Id,0);mem(Head,-1);mem(Exi,0); scanf("%d%d%d%d",&Sx,&Sy,&Tx,&Ty); Nx[++nx]=Sx;Nx[++nx]=Tx;Ny[++ny]=Sy,Ny[++ny]=Ty; scanf("%d",&n); bool flag=1; for (int i=1;i<=n;i++){ scanf("%d%d%d%d",&A[i],&B[i],&C[i],&D[i]);Exi[i]=1; if (A[i]>C[i]) swap(A[i],C[i]); if (B[i]>D[i]) swap(B[i],D[i]); if ((A[i]<Sx)&&(C[i]>Sx)&&(B[i]<Sy)&&(D[i]>Sy)) flag=0; if ((A[i]<Tx)&&(C[i]>Tx)&&(B[i]<Ty)&&(D[i]>Ty)) flag=0; Nx[++nx]=A[i];Nx[++nx]=C[i];Ny[++ny]=B[i];Ny[++ny]=D[i]; } if (flag==0){ printf("No Path\n");continue; } for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) if (i!=j) if ((A[j]<=A[i])&&(B[j]<=B[i])&&(C[j]>=C[i])&&(D[j]>=D[i])){ Exi[i]=0;break; } sort(&Nx[1],&Nx[nx+1]);nx=unique(&Nx[1],&Nx[nx+1])-Nx-1; sort(&Ny[1],&Ny[ny+1]);ny=unique(&Ny[1],&Ny[ny+1])-Ny-1; //cout<<"Nx:";for (int i=1;i<=nx;i++) cout<<Nx[i]<<" ";cout<<endl; //cout<<"Ny:";for (int i=1;i<=ny;i++) cout<<Ny[i]<<" ";cout<<endl; Sx=Find(Nx,nx,Sx);Sy=Find(Ny,ny,Sy);Tx=Find(Nx,nx,Tx);Ty=Find(Ny,ny,Ty); for (int i=1;i<=n;i++) A[i]=Find(Nx,nx,A[i]),B[i]=Find(Ny,ny,B[i]),C[i]=Find(Nx,nx,C[i]),D[i]=Find(Ny,ny,D[i]); //cout<<Sx<<" "<<Sy<<" "<<Tx<<" "<<Ty<<endl; //for (int i=1;i<=n;i++) cout<<"("<<A[i]<<","<<B[i]<<") ("<<C[i]<<","<<D[i]<<")"<<endl; for (int i=1;i<=n;i++){ if (Exi[i]==0) continue; for (int j=A[i];j<=C[i];j++) stu[j][B[i]]=1,stu[j][D[i]]=2; for (int j=B[i];j<=D[i];j++) stu[A[i]][j]=1,stu[C[i]][j]=2; stu[A[i]][B[i]]=stu[A[i]][D[i]]=stu[C[i]][B[i]]=stu[C[i]][D[i]]=-1; } stu[Sx][Sy]=stu[Tx][Ty]=-1; /* for (int i=1;i<=nx;i++){ for (int j=1;j<=ny;j++) cout<<setw(4)<<stu[i][j]; cout<<endl; } //*/ for (int i=1;i<=n;i++){ if (Exi[i]==0) continue; Go(A[i],B[i],-1,0);Go(A[i],B[i],0,-1);Go(A[i],D[i],-1,0);Go(A[i],D[i],0,1); Go(C[i],B[i],1,0);Go(C[i],B[i],0,-1);Go(C[i],D[i],1,0);Go(C[i],D[i],0,1); Id[A[i]][B[i]]=Id[A[i]][D[i]]=Id[C[i]][B[i]]=Id[C[i]][D[i]]=1; } Id[Sx][Sy]=Id[Tx][Ty]=1; Go(Sx,Sy,0,1);Go(Sx,Sy,1,0);Go(Sx,Sy,0,-1);Go(Sx,Sy,-1,0); Go(Tx,Ty,0,1);Go(Tx,Ty,1,0);Go(Tx,Ty,0,-1);Go(Tx,Ty,-1,0); /* cout<<endl; for (int i=1;i<=nx;i++){ for (int j=1;j<=ny;j++) cout<<setw(4)<<Id[i][j]; cout<<endl; } //*/ for (int i=1;i<=nx;i++) for (int j=1;j<=ny;j++){ if (Id[i][j]) P[++pcnt]=((Point){i,j,pcnt}); if ((i==Sx)&&(j==Sy)) S=pcnt; if ((i==Tx)&&(j==Ty)) T=pcnt; //if (Id[i][j]) cout<<pcnt<<":"<<P[i].x<<" "<<P[i].y<<endl; } sort(&P[1],&P[pcnt+1],cmpx); //for (int i=1;i<=pcnt;i++) cout<<"("<<P[i].x<<" "<<P[i].y<<") ";cout<<endl; for (int i=1,j;i<=pcnt;i=j){ j=i+1; while (P[j].x==P[i].x){ if ((stu[P[j-1].x][P[j-1].y]==-1)||(stu[P[j].x][P[j].y]==-1)||((stu[P[j-1].x][P[j-1].y]==2)&&(stu[P[j].x][P[j].y]==1))) Add_Edge(P[j-1].id,P[j].id,Ny[P[j].y]-Ny[P[j-1].y]); j++; } } sort(&P[1],&P[pcnt+1],cmpy); for (int i=1,j;i<=pcnt;i=j){ j=i+1; while (P[j].y==P[i].y){ if ((stu[P[j-1].x][P[j-1].y]==-1)||(stu[P[j].x][P[j].y]==-1)||((stu[P[j-1].x][P[j-1].y]==2)&&(stu[P[j].x][P[j].y]==1))) Add_Edge(P[j-1].id,P[j].id,Nx[P[j].x]-Nx[P[j-1].x]); j++; } } Spfa(); if (Dist[T]==inf) printf("No Path\n"); else printf("%d\n",Dist[T]); } return 0; } void Add_Edge(int u,int v,int w){ //cout<<"Add:"<<u<<" "<<v<<" "<<w<<endl; Next[++edgecnt]=Head[u];Head[u]=edgecnt;V[edgecnt]=v;W[edgecnt]=w; Next[++edgecnt]=Head[v];Head[v]=edgecnt;V[edgecnt]=u;W[edgecnt]=w; return; } void Go(int x,int y,int dx,int dy){ x+=dx;y+=dy; while (stu[x][y]==0){ if ((x<1)||(y<1)||(x>nx)||(y>ny)) return; x+=dx;y+=dy; } Id[x][y]=1;return; } bool cmpx(Point P1,Point P2){ if (P1.x!=P2.x) return P1.x<P2.x; return P1.y<P2.y; } bool cmpy(Point P1,Point P2){ if (P1.y!=P2.y) return P1.y<P2.y; return P1.x<P2.x; } void Spfa(){ for (int i=1;i<=pcnt;i++) Dist[i]=inf; Dist[S]=0;inq[S]=1;Q.push(S); while (!Q.empty()){ int u=Q.front();Q.pop();//cout<<u<<endl; for (int i=Head[u];i!=-1;i=Next[i]) if (Dist[V[i]]>Dist[u]+W[i]){ Dist[V[i]]=Dist[u]+W[i]; if (inq[V[i]]==0){ Q.push(V[i]);inq[V[i]]=1; } } inq[u]=0; } return; } /* 2 1 7 7 8 2 2 5 3 8 4 10 6 7 2 1 5 4 1 3 1 4 3 1 1 7 7 8 2 2 5 3 8 4 10 6 7 //*/ <|endoftext|>
<commit_before>/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include <osvr/ClientKit/Context.h> #include <osvr/Common/ApplyPathNodeVisitor.h> #include <osvr/Common/ClientContext.h> #include <osvr/Common/PathElementTools.h> #include <osvr/Common/PathElementTypes.h> #include <osvr/Common/PathNode.h> #include <osvr/Common/PathTreeFull.h> #include <osvr/Common/ResolveFullTree.h> #include <osvr/Util/IndentingStream.h> #include <osvr/Util/ProgramOptionsToggleFlags.h> #include <osvr/Util/TreeTraversalVisitor.h> // Library/third-party includes #include <boost/noncopyable.hpp> #include <boost/program_options.hpp> #include <boost/variant.hpp> // Standard includes #include <chrono> #include <iomanip> #include <iostream> #include <string> #include <thread> #include <unordered_set> #include <vector> struct Options { bool showAliasSource; bool showAliasPriority; bool showDeviceDetails; bool showDeviceDescriptor; bool showSensors; bool showStringData; }; using osvr::common::PathNode; namespace elements = osvr::common::elements; /// This functor is applied at each node to get the (type-safe variant) value /// out of it (hence the numerous overloads of the function call operator - one /// for each node element type we want to treat differently.) /// /// As a "visitor", this visitor visits just a single node - it's used by a /// simple lambda to visit every node in the path tree. class TreeNodePrinter : public boost::static_visitor<>, boost::noncopyable { public: /// @brief Constructor TreeNodePrinter(Options opts, std::vector<std::string> const &badAliases) : boost::static_visitor<>(), m_opts(opts), m_maxTypeLen(elements::getMaxTypeNameLength()), m_os(std::cout), m_indentStream(m_maxTypeLen + 2 + 1 + 2, m_os), m_badAliases(begin(badAliases), end(badAliases)) { // Computation for initializing the indent stream above: // Indents type name size, +2 for the brackets, +1 for the space, and +2 // so it doesn't line up with the path. // Some initial space to set the output off. m_os << "\n\n"; } /// @brief print nothing for a null element. void operator()(PathNode const &, elements::NullElement const &) {} /// @brief We might print something for a sensor element. void operator()(PathNode const &node, elements::SensorElement const &elt) { if (m_opts.showSensors) { outputBasics(node, elt) << "\n"; } } /// @brief Print aliases void operator()(PathNode const &node, elements::AliasElement const &elt) { outputBasics(node, elt) << std::endl; /// Check to see if this alias fully resolved, and warn if it didn't. auto fullPath = osvr::common::getFullPath(node); if (m_badAliases.find(fullPath) != m_badAliases.end()) { m_indentStream << "WARNING: this alias does not fully resolve to a " "device/sensor!\n"; } if (m_opts.showAliasSource) { m_indentStream << "-> " << elt.getSource() << std::endl; } if (m_opts.showAliasPriority) { m_indentStream << "Priority: " << osvr::common::outputPriority(elt.priority()) << std::endl; } } /// @brief Print Devices void operator()(PathNode const &node, elements::DeviceElement const &elt) { outputBasics(node, elt) << std::endl; if (m_opts.showDeviceDetails) { m_indentStream << "- corresponds to " << elt.getFullDeviceName() << std::endl; } if (m_opts.showDeviceDescriptor) { m_indentStream << "- Descriptor: " << elt.getDescriptor().toStyledString() << std::endl; } } /// @brief We might print something for a sensor element. void operator()(PathNode const &node, elements::StringElement const &elt) { outputBasics(node, elt) << std::endl; if (m_opts.showStringData) { m_indentStream << "- Contained value: " << elt.getString() << std::endl; } } /// @brief Catch-all for other element types. template <typename T> void operator()(PathNode const &node, T const &elt) { outputBasics(node, elt) << "\n"; } private: /// @brief shared implementation: prints type name in brackets padded to /// fixed width, then the full path. template <typename T> std::ostream &outputBasics(PathNode const &node, T const &elt) { m_os << "[" << std::setw(m_maxTypeLen) << osvr::common::getTypeName(elt) << "] " << osvr::common::getFullPath(node); return m_os; } Options m_opts; size_t m_maxTypeLen; std::ostream &m_os; osvr::util::IndentingStream m_indentStream; /// The set of paths that are aliases that don't completely resolve. std::unordered_set<std::string> m_badAliases; }; int main(int argc, char *argv[]) { Options opts; namespace po = boost::program_options; // clang-format off po::options_description desc("Options"); desc.add_options() ("help,h", "produce help message") ("alias-source", po::value<bool>(&opts.showAliasSource)->default_value(true), "Whether or not to show the source associated with each alias") ("alias-priority", po::value<bool>(&opts.showAliasPriority)->default_value(false), "Whether or not to show the priority associated with each alias") ("device-details", po::value<bool>(&opts.showDeviceDetails)->default_value(true), "Whether or not to show the basic details associated with each device") ("device-descriptors", po::value<bool>(&opts.showDeviceDescriptor)->default_value(false), "Whether or not to show the JSON descriptors associated with each device") ("sensors", po::value<bool>(&opts.showSensors)->default_value(true), "Whether or not to show the 'sensor' nodes") ("string-data", po::value<bool>(&opts.showStringData)->default_value(true), "Whether or not to show the data in 'string' nodes") ; // clang-format on po::variables_map vm; bool usage = false; try { po::store(po::command_line_parser(argc, argv) .options(desc) .extra_parser( osvr::util::convertProgramOptionShowHideIntoTrueFalse) .run(), vm); po::notify(vm); } catch (std::exception &e) { std::cerr << "\nError parsing command line: " << e.what() << "\n\n"; usage = true; } if (usage || vm.count("help")) { std::cerr << "\nTraverses the path tree and outputs it as text for " "human consumption. See\nPathTreeExport for structured " "output for graphical display.\n"; std::cerr << "Usage: " << argv[0] << " [options]\n\n"; std::cerr << "All options are shown as being --option 1/0 (true/false) " "but may be expressed\nas --show-option or --hide-option " "instead (e.g. --show-alias-priority)\n\n"; std::cerr << desc << "\n"; return 1; } osvr::common::PathTree pathTree; std::vector<std::string> badAliases; { /// We only actually need the client open for long enough to get the /// path tree and clone it. osvr::clientkit::ClientContext context("org.osvr.tools.printtree"); if (!context.checkStatus()) { context.log(OSVR_LOGLEVEL_NOTICE, "Client context has not yet started up - waiting. " "Make sure the server is running."); do { std::this_thread::sleep_for(std::chrono::milliseconds(1)); context.update(); } while (!context.checkStatus()); context.log(OSVR_LOGLEVEL_NOTICE, "OK, client context ready. Proceeding."); } /// Get a non-const copy of the path tree. osvr::common::clonePathTree(context.get()->getPathTree(), pathTree); /// Resolve all aliases, keeping track of those that don't fully /// resolve. badAliases = osvr::common::resolveFullTree(pathTree); } /// Before we print anything, we should flush the logger so it doesn't /// intermix with our output. osvr::util::log::flush(); TreeNodePrinter printer{opts, badAliases}; /// Now traverse for output - traverse every node in the path tree and apply /// the node visitor to get the type-safe variant data out of the nodes. The /// lambda will be called (and thus the TreeNodePrinter applied) at every /// PathNode in the tree. osvr::util::traverseWith( pathTree.getRoot(), [&printer](PathNode const &node) { osvr::common::applyPathNodeVisitor(printer, node); }); return 0; } <commit_msg>add show articulation to print tree<commit_after>/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include <osvr/ClientKit/Context.h> #include <osvr/Common/ApplyPathNodeVisitor.h> #include <osvr/Common/ClientContext.h> #include <osvr/Common/PathElementTools.h> #include <osvr/Common/PathElementTypes.h> #include <osvr/Common/PathNode.h> #include <osvr/Common/PathTreeFull.h> #include <osvr/Common/ResolveFullTree.h> #include <osvr/Util/IndentingStream.h> #include <osvr/Util/ProgramOptionsToggleFlags.h> #include <osvr/Util/TreeTraversalVisitor.h> // Library/third-party includes #include <boost/noncopyable.hpp> #include <boost/program_options.hpp> #include <boost/variant.hpp> // Standard includes #include <chrono> #include <iomanip> #include <iostream> #include <string> #include <thread> #include <unordered_set> #include <vector> struct Options { bool showAliasSource; bool showAliasPriority; bool showDeviceDetails; bool showDeviceDescriptor; bool showSensors; bool showStringData; bool showArticulations; }; using osvr::common::PathNode; namespace elements = osvr::common::elements; /// This functor is applied at each node to get the (type-safe variant) value /// out of it (hence the numerous overloads of the function call operator - one /// for each node element type we want to treat differently.) /// /// As a "visitor", this visitor visits just a single node - it's used by a /// simple lambda to visit every node in the path tree. class TreeNodePrinter : public boost::static_visitor<>, boost::noncopyable { public: /// @brief Constructor TreeNodePrinter(Options opts, std::vector<std::string> const &badAliases) : boost::static_visitor<>(), m_opts(opts), m_maxTypeLen(elements::getMaxTypeNameLength()), m_os(std::cout), m_indentStream(m_maxTypeLen + 2 + 1 + 2, m_os), m_badAliases(begin(badAliases), end(badAliases)) { // Computation for initializing the indent stream above: // Indents type name size, +2 for the brackets, +1 for the space, and +2 // so it doesn't line up with the path. // Some initial space to set the output off. m_os << "\n\n"; } /// @brief print nothing for a null element. void operator()(PathNode const &, elements::NullElement const &) {} /// @brief We might print something for a sensor element. void operator()(PathNode const &node, elements::SensorElement const &elt) { if (m_opts.showSensors) { outputBasics(node, elt) << "\n"; } } /// @brief Print aliases void operator()(PathNode const &node, elements::AliasElement const &elt) { outputBasics(node, elt) << std::endl; /// Check to see if this alias fully resolved, and warn if it didn't. auto fullPath = osvr::common::getFullPath(node); if (m_badAliases.find(fullPath) != m_badAliases.end()) { m_indentStream << "WARNING: this alias does not fully resolve to a " "device/sensor!\n"; } if (m_opts.showAliasSource) { m_indentStream << "-> " << elt.getSource() << std::endl; } if (m_opts.showAliasPriority) { m_indentStream << "Priority: " << osvr::common::outputPriority(elt.priority()) << std::endl; } } /// @brief Print Devices void operator()(PathNode const &node, elements::DeviceElement const &elt) { outputBasics(node, elt) << std::endl; if (m_opts.showDeviceDetails) { m_indentStream << "- corresponds to " << elt.getFullDeviceName() << std::endl; } if (m_opts.showDeviceDescriptor) { m_indentStream << "- Descriptor: " << elt.getDescriptor().toStyledString() << std::endl; } } /// @brief We might print something for a sensor element. void operator()(PathNode const &node, elements::StringElement const &elt) { outputBasics(node, elt) << std::endl; if (m_opts.showStringData) { m_indentStream << "- Contained value: " << elt.getString() << std::endl; } } void operator()(osvr::common::PathNode const &node, osvr::common::elements::ArticulationElement const &elt) { m_outputBasics(node, elt) << std::endl; // if (m_opts.showStringData) { m_indentStream << "- Contained value: Articulation Type = " << elt.getArticulationType() << "; Tracker path = " << elt.getTrackerPath() << "; Bone Name = " << elt.getBoneName() << std::endl; //} } /// @brief Catch-all for other element types. template <typename T> void operator()(PathNode const &node, T const &elt) { outputBasics(node, elt) << "\n"; } private: /// @brief shared implementation: prints type name in brackets padded to /// fixed width, then the full path. template <typename T> std::ostream &outputBasics(PathNode const &node, T const &elt) { m_os << "[" << std::setw(m_maxTypeLen) << osvr::common::getTypeName(elt) << "] " << osvr::common::getFullPath(node); return m_os; } Options m_opts; size_t m_maxTypeLen; std::ostream &m_os; osvr::util::IndentingStream m_indentStream; /// The set of paths that are aliases that don't completely resolve. std::unordered_set<std::string> m_badAliases; }; int main(int argc, char *argv[]) { Options opts; namespace po = boost::program_options; // clang-format off po::options_description desc("Options"); desc.add_options() ("help,h", "produce help message") ("alias-source", po::value<bool>(&opts.showAliasSource)->default_value(true), "Whether or not to show the source associated with each alias") ("alias-priority", po::value<bool>(&opts.showAliasPriority)->default_value(false), "Whether or not to show the priority associated with each alias") ("device-details", po::value<bool>(&opts.showDeviceDetails)->default_value(true), "Whether or not to show the basic details associated with each device") ("device-descriptors", po::value<bool>(&opts.showDeviceDescriptor)->default_value(false), "Whether or not to show the JSON descriptors associated with each device") ("sensors", po::value<bool>(&opts.showSensors)->default_value(true), "Whether or not to show the 'sensor' nodes") ("string-data", po::value<bool>(&opts.showStringData)->default_value(true), "Whether or not to show the data in 'string' nodes") ("articulations", po::value<bool>(&opts.showArticulations)->default_value(true), "Whether or not to show the articulations") ; // clang-format on po::variables_map vm; bool usage = false; try { po::store(po::command_line_parser(argc, argv) .options(desc) .extra_parser( osvr::util::convertProgramOptionShowHideIntoTrueFalse) .run(), vm); po::notify(vm); } catch (std::exception &e) { std::cerr << "\nError parsing command line: " << e.what() << "\n\n"; usage = true; } if (usage || vm.count("help")) { std::cerr << "\nTraverses the path tree and outputs it as text for " "human consumption. See\nPathTreeExport for structured " "output for graphical display.\n"; std::cerr << "Usage: " << argv[0] << " [options]\n\n"; std::cerr << "All options are shown as being --option 1/0 (true/false) " "but may be expressed\nas --show-option or --hide-option " "instead (e.g. --show-alias-priority)\n\n"; std::cerr << desc << "\n"; return 1; } osvr::common::PathTree pathTree; std::vector<std::string> badAliases; { /// We only actually need the client open for long enough to get the /// path tree and clone it. osvr::clientkit::ClientContext context("org.osvr.tools.printtree"); if (!context.checkStatus()) { context.log(OSVR_LOGLEVEL_NOTICE, "Client context has not yet started up - waiting. " "Make sure the server is running."); do { std::this_thread::sleep_for(std::chrono::milliseconds(1)); context.update(); } while (!context.checkStatus()); context.log(OSVR_LOGLEVEL_NOTICE, "OK, client context ready. Proceeding."); } /// Get a non-const copy of the path tree. osvr::common::clonePathTree(context.get()->getPathTree(), pathTree); /// Resolve all aliases, keeping track of those that don't fully /// resolve. badAliases = osvr::common::resolveFullTree(pathTree); } /// Before we print anything, we should flush the logger so it doesn't /// intermix with our output. osvr::util::log::flush(); TreeNodePrinter printer{opts, badAliases}; /// Now traverse for output - traverse every node in the path tree and apply /// the node visitor to get the type-safe variant data out of the nodes. The /// lambda will be called (and thus the TreeNodePrinter applied) at every /// PathNode in the tree. osvr::util::traverseWith( pathTree.getRoot(), [&printer](PathNode const &node) { osvr::common::applyPathNodeVisitor(printer, node); }); return 0; } <|endoftext|>
<commit_before>#include "stdsneezy.h" #include "games.h" HiLoGame gHiLo; const float WIN_INIT=0.10; bool HiLoGame::enter(const TBeing *ch) { if(inuse){ ch->sendTo("This table is already in use.\n\r"); return false; } inuse = true; hilo_shuffle(ch); bet = 0; name=ch->name; return true; } void HiLoGame::hilo_shuffle(const TBeing *ch) { act("The dealer shuffles the deck.",FALSE, ch, 0, 0, TO_CHAR); act("The dealer shuffles the deck.",FALSE, ch, 0, 0, TO_ROOM); shuffle(); deck_inx = 0; } bool TBeing::checkHiLo(bool inGame = false) const { if (in_room == ROOM_HILO && (inGame || (gHiLo.index(this) > -1))) return true; else return false; } void HiLoGame::BetHi(TBeing *ch, int new_card) { sstring buf; if(CARD_NUM_ACEHI(new_card) > CARD_NUM_ACEHI(card)){ win_perc*=2; ch->sendTo("You win! Your winnings are now at %i talens.\n\r", (int)((float)bet * (1.0 + win_perc))); ssprintf(buf, "$n wins! $n's winnings are now at %i talens.", (int)((float)bet * (1.0 + win_perc))); act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM); observerReaction(ch, GAMBLER_HILO_BET); } else { ch->sendTo("You lose!\n\r"); act("$n loses!", TRUE, ch, 0, 0, TO_ROOM); observerReaction(ch, GAMBLER_LOST); bet = 0; card = 0; } } void HiLoGame::BetLo(TBeing *ch, int new_card) { sstring buf; if(CARD_NUM_ACEHI(new_card) < CARD_NUM_ACEHI(card)){ win_perc*=2; ch->sendTo("You win! Your winnings are now at %i talens.\n\r", (int)((float)bet * (1.0 + win_perc))); ssprintf(buf, "$n wins! $n's winnings are now at %i talens.", (int)((float)bet * (1.0 + win_perc))); act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM); observerReaction(ch, GAMBLER_HILO_BET); } else { ch->sendTo("You lose!\n\r"); act("$n loses!", TRUE, ch, 0, 0, TO_ROOM); observerReaction(ch, GAMBLER_LOST); bet = 0; card = 0; } } void HiLoGame::stay(TBeing *ch) { if(win_perc==WIN_INIT){ ch->sendTo("You just started, you can't quit now!\n\r"); return; } ch->sendTo("You give up and cash out your winnings.\n\r"); act("$n gives up and cashes out $s winnings.", TRUE, ch, 0, 0, TO_ROOM); payout(ch, (int)((double)bet * (1.0 + win_perc))); bet = 0; card = 0; observerReaction(ch, GAMBLER_WON); } void HiLoGame::Bet(TBeing *ch, const sstring &arg) { int inx, new_card; sstring coin_str; sstring log_msg; sstring buf; TObj *chip; if (ch->checkHiLo()) { inx = index(ch); if (inx < 0) { ch->sendTo("You are not sitting at the table yet.\n\r"); return; } if (bet > 0) { if(arg=="hi" || arg=="lo"){ if (deck_inx > 10) hilo_shuffle(ch); new_card=deck[deck_inx++]; ssprintf(buf, "$n bets %s.", arg.c_str()); act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM); ssprintf(log_msg, "You are dealt:\n\r%s\n\r", pretty_card_printout(ch, new_card).c_str()); ch->sendTo(COLOR_BASIC, log_msg.c_str()); ssprintf(log_msg, "$n is dealt:\n\r%s", pretty_card_printout(ch, new_card).c_str()); act(log_msg.c_str(), TRUE, ch, 0, 0, TO_ROOM); if(arg=="hi"){ BetHi(ch, new_card); } else if(arg=="lo"){ BetLo(ch, new_card); } card=new_card; return; } else { ch->sendTo("You can't change your bet now.\n\r"); ch->sendTo("You must either bet 'hi' or 'lo' for the next card.\n\r"); return; } } argument_parser(arg, coin_str); if (coin_str.empty()){ ch->sendTo("Bet which chip?\n\r"); return; } if(!(chip=find_chip(ch, coin_str))){ ch->sendTo("You don't have that chip!\n\r"); return; } bet = chip->obj_flags.cost; ch->doSave(SILENT_YES); sstring buf; ssprintf(buf, "$n bets %s.", chip->getName()); act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM); ssprintf(buf, "You bet %s.", chip->getName()); act(buf.c_str(), TRUE, ch, 0, 0, TO_CHAR); (*chip)--; delete chip; win_perc=WIN_INIT; card=0; if (deck_inx > 10) hilo_shuffle(ch); card = deck[deck_inx++]; ssprintf(log_msg, "You are dealt:\n\r%s\n\r", pretty_card_printout(ch, card).c_str()); ch->sendTo(COLOR_BASIC, log_msg.c_str()); ssprintf(log_msg, "$n is dealt:\n\r%s\n\r", pretty_card_printout(ch, card).c_str()); act(log_msg.c_str(), TRUE, ch, 0, 0, TO_ROOM); observerReaction(ch, GAMBLER_HILO_BET); } } void HiLoGame::peek(const TBeing *ch) const { sstring log_msg; if (index(ch) < 0) { ch->sendTo("You are not sitting at the table yet.\n\r"); return; } if (!bet) { ch->sendTo("You are not playing a game.\n\r"); return; } ssprintf(log_msg, "You peek at your hand:\n\r%s\n\r", pretty_card_printout(ch, card).c_str()); ch->sendTo(COLOR_BASIC, log_msg.c_str()); } int HiLoGame::exitGame(const TBeing *ch) { int inx; if ((inx = index(ch)) < 0) { forceCrash("%s left a table he was not at!", ch->name); return FALSE; } inuse = FALSE; name=""; deck_inx = 0; bet = 0; card = 0; win_perc=0; setup_deck(); ch->sendTo("You leave the hi-lo table.\n\r"); return TRUE; } int HiLoGame::index(const TBeing *ch) const { if(ch->name == name) return 0; return -1; } <commit_msg>put payout back down added display of next card when you stay<commit_after>#include "stdsneezy.h" #include "games.h" HiLoGame gHiLo; const float WIN_INIT=0.05; bool HiLoGame::enter(const TBeing *ch) { if(inuse){ ch->sendTo("This table is already in use.\n\r"); return false; } inuse = true; hilo_shuffle(ch); bet = 0; name=ch->name; return true; } void HiLoGame::hilo_shuffle(const TBeing *ch) { act("The dealer shuffles the deck.",FALSE, ch, 0, 0, TO_CHAR); act("The dealer shuffles the deck.",FALSE, ch, 0, 0, TO_ROOM); shuffle(); deck_inx = 0; } bool TBeing::checkHiLo(bool inGame = false) const { if (in_room == ROOM_HILO && (inGame || (gHiLo.index(this) > -1))) return true; else return false; } void HiLoGame::BetHi(TBeing *ch, int new_card) { sstring buf; if(CARD_NUM_ACEHI(new_card) > CARD_NUM_ACEHI(card)){ win_perc*=2; ch->sendTo("You win! Your winnings are now at %i talens.\n\r", (int)((float)bet * (1.0 + win_perc))); ssprintf(buf, "$n wins! $n's winnings are now at %i talens.", (int)((float)bet * (1.0 + win_perc))); act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM); observerReaction(ch, GAMBLER_HILO_BET); } else { ch->sendTo("You lose!\n\r"); act("$n loses!", TRUE, ch, 0, 0, TO_ROOM); observerReaction(ch, GAMBLER_LOST); bet = 0; card = 0; } } void HiLoGame::BetLo(TBeing *ch, int new_card) { sstring buf; if(CARD_NUM_ACEHI(new_card) < CARD_NUM_ACEHI(card)){ win_perc*=2; ch->sendTo("You win! Your winnings are now at %i talens.\n\r", (int)((float)bet * (1.0 + win_perc))); ssprintf(buf, "$n wins! $n's winnings are now at %i talens.", (int)((float)bet * (1.0 + win_perc))); act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM); observerReaction(ch, GAMBLER_HILO_BET); } else { ch->sendTo("You lose!\n\r"); act("$n loses!", TRUE, ch, 0, 0, TO_ROOM); observerReaction(ch, GAMBLER_LOST); bet = 0; card = 0; } } void HiLoGame::stay(TBeing *ch) { if(win_perc==WIN_INIT){ ch->sendTo("You just started, you can't quit now!\n\r"); return; } ch->sendTo("You give up and cash out your winnings.\n\r"); act("$n gives up and cashes out $s winnings.", TRUE, ch, 0, 0, TO_ROOM); int next_card=deck[deck_inx++]; sstring buf; ch->sendTo(COLOR_BASIC, "The next card was the %s.\n\r", pretty_card_printout(ch, next_card).c_str()); ssprintf(buf, "The next card was the %s.", pretty_card_printout(ch, next_card).c_str()); act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM); payout(ch, (int)((double)bet * (1.0 + win_perc))); bet = 0; card = 0; observerReaction(ch, GAMBLER_WON); } void HiLoGame::Bet(TBeing *ch, const sstring &arg) { int inx, new_card; sstring coin_str; sstring log_msg; sstring buf; TObj *chip; if (ch->checkHiLo()) { inx = index(ch); if (inx < 0) { ch->sendTo("You are not sitting at the table yet.\n\r"); return; } if (bet > 0) { if(arg=="hi" || arg=="lo"){ if (deck_inx > 10) hilo_shuffle(ch); new_card=deck[deck_inx++]; ssprintf(buf, "$n bets %s.", arg.c_str()); act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM); ssprintf(log_msg, "You are dealt:\n\r%s\n\r", pretty_card_printout(ch, new_card).c_str()); ch->sendTo(COLOR_BASIC, log_msg.c_str()); ssprintf(log_msg, "$n is dealt:\n\r%s", pretty_card_printout(ch, new_card).c_str()); act(log_msg.c_str(), TRUE, ch, 0, 0, TO_ROOM); if(arg=="hi"){ BetHi(ch, new_card); } else if(arg=="lo"){ BetLo(ch, new_card); } card=new_card; return; } else { ch->sendTo("You can't change your bet now.\n\r"); ch->sendTo("You must either bet 'hi' or 'lo' for the next card.\n\r"); return; } } argument_parser(arg, coin_str); if (coin_str.empty()){ ch->sendTo("Bet which chip?\n\r"); return; } if(!(chip=find_chip(ch, coin_str))){ ch->sendTo("You don't have that chip!\n\r"); return; } bet = chip->obj_flags.cost; ch->doSave(SILENT_YES); sstring buf; ssprintf(buf, "$n bets %s.", chip->getName()); act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM); ssprintf(buf, "You bet %s.", chip->getName()); act(buf.c_str(), TRUE, ch, 0, 0, TO_CHAR); (*chip)--; delete chip; win_perc=WIN_INIT; card=0; if (deck_inx > 10) hilo_shuffle(ch); card = deck[deck_inx++]; ssprintf(log_msg, "You are dealt:\n\r%s\n\r", pretty_card_printout(ch, card).c_str()); ch->sendTo(COLOR_BASIC, log_msg.c_str()); ssprintf(log_msg, "$n is dealt:\n\r%s\n\r", pretty_card_printout(ch, card).c_str()); act(log_msg.c_str(), TRUE, ch, 0, 0, TO_ROOM); observerReaction(ch, GAMBLER_HILO_BET); } } void HiLoGame::peek(const TBeing *ch) const { sstring log_msg; if (index(ch) < 0) { ch->sendTo("You are not sitting at the table yet.\n\r"); return; } if (!bet) { ch->sendTo("You are not playing a game.\n\r"); return; } ssprintf(log_msg, "You peek at your hand:\n\r%s\n\r", pretty_card_printout(ch, card).c_str()); ch->sendTo(COLOR_BASIC, log_msg.c_str()); } int HiLoGame::exitGame(const TBeing *ch) { int inx; if ((inx = index(ch)) < 0) { forceCrash("%s left a table he was not at!", ch->name); return FALSE; } inuse = FALSE; name=""; deck_inx = 0; bet = 0; card = 0; win_perc=0; setup_deck(); ch->sendTo("You leave the hi-lo table.\n\r"); return TRUE; } int HiLoGame::index(const TBeing *ch) const { if(ch->name == name) return 0; return -1; } <|endoftext|>
<commit_before>#include "prov_info.h" #include "../helper.h" using namespace crypt; NTSTATUS FreeKey(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE handle) { if (NCryptIsKeyHandle(handle)) { return NCryptFreeObject(handle); } else { if (!CryptReleaseContext(handle, 0)) { return GetLastError(); } } return ERROR_SUCCESS; } NTSTATUS OpenKey(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE* handle, PCRYPT_KEY_PROV_INFO provInfo, BOOL fSilent) { if (provInfo->dwProvType) { // CAPI if (!CryptAcquireContextW(handle, provInfo->pwszContainerName, provInfo->pwszProvName, provInfo->dwProvType, fSilent ? CRYPT_SILENT : 0)) { return GetLastError(); } } else { // CNG NTSTATUS status = ERROR_SUCCESS; NCRYPT_PROV_HANDLE hProv = 0; while (true) { status = NCryptOpenStorageProvider(&hProv, provInfo->pwszProvName, 0); if (status) { break; } status = NCryptOpenKey(hProv, handle, provInfo->pwszContainerName, provInfo->dwKeySpec, fSilent ? NCRYPT_SILENT_FLAG : 0); if (status) { break; } break; } if (hProv) { NCryptFreeObject(hProv); } return status; } return ERROR_SUCCESS; } ProviderInfo::ProviderInfo(Scoped<Buffer> info) : buffer(info), info((CRYPT_KEY_PROV_INFO*)info->data()) { } ProviderInfo::~ProviderInfo() { } bool crypt::ProviderInfo::IsAccassible() { HCRYPTPROV_OR_NCRYPT_KEY_HANDLE handle = 0; NTSTATUS status = ERROR_SUCCESS; status = OpenKey(&handle, info, true); if (status) { return false; } return true; } CRYPT_KEY_PROV_INFO * ProviderInfo::Get() { return info; } Scoped<Buffer> crypt::ProviderInfo::GetSmartCardGUID() { try { return GetBytes(PP_SMARTCARD_GUID); } CATCH_EXCEPTION } Scoped<std::string> crypt::ProviderInfo::GetSmartCardReader() { try { auto buf = GetBytes(PP_SMARTCARD_READER); return Scoped<std::string>(new std::string((PCHAR)buf->data())); } CATCH_EXCEPTION } Scoped<Buffer> crypt::ProviderInfo::GetBytes(DWORD dwParam) { try { HCRYPTPROV_OR_NCRYPT_KEY_HANDLE handle = 0; NTSTATUS status = 0; Scoped<Buffer> res(new Buffer(0)); status = OpenKey(&handle, info, true); if (status) { THROW_NT_EXCEPTION(status, "OpenKey"); } if (NCryptIsKeyHandle(handle)) { // CNG THROW_EXCEPTION("Not implemented"); } else { // CAPI DWORD dataLen = 0; if (!CryptGetProvParam(handle, dwParam, NULL, &dataLen, 0)) { status = GetLastError(); FreeKey(handle); THROW_MSCAPI_CODE_ERROR(MSCAPI_EXCEPTION_NAME, "CryptGetProvParam", status); } res->resize(dataLen); if (!CryptGetProvParam(handle, dwParam, res->data(), &dataLen, 0)) { status = GetLastError(); FreeKey(handle); THROW_MSCAPI_CODE_ERROR(MSCAPI_EXCEPTION_NAME, "CryptGetProvParam", status); } } FreeKey(handle); return res; } CATCH_EXCEPTION } <commit_msg>Ыгззщке ProviderInfo::GetBytes for CNG<commit_after>#include "prov_info.h" #include "../helper.h" using namespace crypt; NTSTATUS FreeKey(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE handle) { if (NCryptIsKeyHandle(handle)) { return NCryptFreeObject(handle); } else { if (!CryptReleaseContext(handle, 0)) { return GetLastError(); } } return ERROR_SUCCESS; } NTSTATUS OpenKey(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE* handle, PCRYPT_KEY_PROV_INFO provInfo, BOOL fSilent) { if (provInfo->dwProvType) { // CAPI if (!CryptAcquireContextW(handle, provInfo->pwszContainerName, provInfo->pwszProvName, provInfo->dwProvType, fSilent ? CRYPT_SILENT : 0)) { return GetLastError(); } } else { // CNG NTSTATUS status = ERROR_SUCCESS; NCRYPT_PROV_HANDLE hProv = 0; while (true) { status = NCryptOpenStorageProvider(&hProv, provInfo->pwszProvName, 0); if (status) { break; } status = NCryptOpenKey(hProv, handle, provInfo->pwszContainerName, provInfo->dwKeySpec, fSilent ? NCRYPT_SILENT_FLAG : 0); if (status) { break; } break; } if (hProv) { NCryptFreeObject(hProv); } return status; } return ERROR_SUCCESS; } ProviderInfo::ProviderInfo(Scoped<Buffer> info) : buffer(info), info((CRYPT_KEY_PROV_INFO*)info->data()) { } ProviderInfo::~ProviderInfo() { } bool crypt::ProviderInfo::IsAccassible() { HCRYPTPROV_OR_NCRYPT_KEY_HANDLE handle = 0; NTSTATUS status = ERROR_SUCCESS; status = OpenKey(&handle, info, true); if (status) { return false; } return true; } CRYPT_KEY_PROV_INFO * ProviderInfo::Get() { return info; } Scoped<Buffer> crypt::ProviderInfo::GetSmartCardGUID() { try { return GetBytes(PP_SMARTCARD_GUID); } CATCH_EXCEPTION } Scoped<std::string> crypt::ProviderInfo::GetSmartCardReader() { try { auto buf = GetBytes(PP_SMARTCARD_READER); return Scoped<std::string>(new std::string((PCHAR)buf->data())); } CATCH_EXCEPTION } Scoped<Buffer> crypt::ProviderInfo::GetBytes(DWORD dwParam) { try { HCRYPTPROV_OR_NCRYPT_KEY_HANDLE handle = 0; NTSTATUS status = 0; Scoped<Buffer> res(new Buffer(0)); status = OpenKey(&handle, info, true); if (status) { THROW_NT_EXCEPTION(status, "OpenKey"); } if (NCryptIsKeyHandle(handle)) { // CNG LPCWSTR propID; switch (dwParam) { case PP_SMARTCARD_GUID: propID = NCRYPT_SMARTCARD_GUID_PROPERTY; break; case PP_SMARTCARD_READER: propID = NCRYPT_READER_PROPERTY; break; default: FreeKey(handle); THROW_EXCEPTION("Unsupported property of Provider dwParam:%d", dwParam); } DWORD dataLen = 0; status = NCryptGetProperty(handle, propID, NULL, 0, &dataLen, 0); if (status) { FreeKey(handle); THROW_MSCAPI_CODE_ERROR(MSCAPI_EXCEPTION_NAME, "CryptGetProvParam", status); } res->resize(dataLen); status = NCryptGetProperty(handle, propID, res->data(), res->size(), &dataLen, 0); if (status) { FreeKey(handle); THROW_MSCAPI_CODE_ERROR(MSCAPI_EXCEPTION_NAME, "CryptGetProvParam", status); } } else { // CAPI DWORD dataLen = 0; if (!CryptGetProvParam(handle, dwParam, NULL, &dataLen, 0)) { status = GetLastError(); FreeKey(handle); THROW_MSCAPI_CODE_ERROR(MSCAPI_EXCEPTION_NAME, "CryptGetProvParam", status); } res->resize(dataLen); if (!CryptGetProvParam(handle, dwParam, res->data(), &dataLen, 0)) { status = GetLastError(); FreeKey(handle); THROW_MSCAPI_CODE_ERROR(MSCAPI_EXCEPTION_NAME, "CryptGetProvParam", status); } } return res; } CATCH_EXCEPTION } <|endoftext|>
<commit_before>/** * @file consensushash.cpp * * This file contains the function to generate consensus hashes. */ #include "omnicore/consensushash.h" #include "omnicore/dex.h" #include "omnicore/mdex.h" #include "omnicore/log.h" #include "omnicore/omnicore.h" #include "omnicore/sp.h" #include <stdint.h> #include <string> #include <openssl/sha.h> namespace mastercore { // Generates a consensus string for hashing based on a tally object std::string GenerateConsensusString(const CMPTally& tallyObj, const std::string& address, const uint32_t propertyId) { int64_t balance = tallyObj.getMoney(propertyId, BALANCE); int64_t sellOfferReserve = tallyObj.getMoney(propertyId, SELLOFFER_RESERVE); int64_t acceptReserve = tallyObj.getMoney(propertyId, ACCEPT_RESERVE); int64_t metaDExReserve = tallyObj.getMoney(propertyId, METADEX_RESERVE); // return a blank string if all balances are empty if (!balance && !sellOfferReserve && !acceptReserve && !metaDExReserve) return ""; return strprintf("%s|%d|%d|%d|%d|%d", address, propertyId, balance, sellOfferReserve, acceptReserve, metaDExReserve); } // Generates a consensus string for hashing based on a DEx sell offer object std::string GenerateConsensusString(const CMPOffer& offerObj, const std::string& address, const uint32_t propertyId) { return strprintf("%s|%s|%d|%d|%d|%d|%d", offerObj.getHash().GetHex(), address, propertyId, offerObj.getOfferAmountOriginal(), offerObj.getBTCDesiredOriginal(), offerObj.getMinFee(), offerObj.getBlockTimeLimit()); } // Generates a consensus string for hashing based on a DEx accept object std::string GenerateConsensusString(const CMPAccept& acceptObj, const std::string& address) { return strprintf("%s|%s|%d|%d|%d", acceptObj.getHash().GetHex(), address, acceptObj.getAcceptAmount(), acceptObj.getAcceptAmountRemaining(), acceptObj.getAcceptBlock()); } // Generates a consensus string for hashing based on a MetaDEx object std::string GenerateConsensusString(const CMPMetaDEx& tradeObj) { return strprintf("%s|%s|%d|%d|%d|%d|%d", tradeObj.getHash().GetHex(), tradeObj.getAddr(), tradeObj.getProperty(), tradeObj.getAmountForSale(), tradeObj.getDesProperty(), tradeObj.getAmountDesired(), tradeObj.getAmountRemaining()); } // Generates a consensus string for hashing based on a crowdsale object std::string GenerateConsensusString(const CMPCrowd& crowdObj) { return strprintf("%d|%d|%d|%d|%d", crowdObj.getPropertyId(), crowdObj.getCurrDes(), crowdObj.getDeadline(), crowdObj.getUserCreated(), crowdObj.getIssuerCreated()); } // Generates a consensus string for hashing based on a property issuer std::string GenerateConsensusString(const uint32_t propertyId, const std::string& address) { return strprintf("%d|%s", propertyId, address); } /** * Obtains a hash of the active state to use for consensus verification and checkpointing. * * For increased flexibility, so other implementations like OmniWallet and OmniChest can * also apply this methodology without necessarily using the same exact data types (which * would be needed to hash the data bytes directly), create a string in the following * format for each entry to use for hashing: * * ---STAGE 1 - BALANCES--- * Format specifiers & placeholders: * "%s|%d|%d|%d|%d|%d" - "address|propertyid|balance|selloffer_reserve|accept_reserve|metadex_reserve" * * Note: empty balance records and the pending tally are ignored. Addresses are sorted based * on lexicographical order, and balance records are sorted by the property identifiers. * * ---STAGE 2 - DEX SELL OFFERS--- * Format specifiers & placeholders: * "%s|%s|%d|%d|%d|%d|%d" - "txid|address|propertyid|offeramount|btcdesired|minfee|timelimit" * * Note: ordered ascending by txid. * * ---STAGE 3 - DEX ACCEPTS--- * Format specifiers & placeholders: * "%s|%s|%d|%d|%d" - "matchedselloffertxid|buyer|acceptamount|acceptamountremaining|acceptblock" * * Note: ordered ascending by matchedselloffertxid followed by buyer. * * ---STAGE 4 - METADEX TRADES--- * Format specifiers & placeholders: * "%s|%s|%d|%d|%d|%d|%d" - "txid|address|propertyidforsale|amountforsale|propertyiddesired|amountdesired|amountremaining" * * Note: ordered ascending by txid. * * ---STAGE 5 - CROWDSALES--- * Format specifiers & placeholders: * "%d|%d|%d|%d|%d" - "propertyid|propertyiddesired|deadline|usertokens|issuertokens" * * Note: ordered by property ID. * * ---STAGE 6 - PROPERTIES--- * Format specifiers & placeholders: * "%d|%s" - "propertyid|issueraddress" * * Note: ordered by property ID. * * The byte order is important, and we assume: * SHA256("abc") = "ad1500f261ff10b49c7a1796a36103b02322ae5dde404141eacf018fbf1678ba" * */ uint256 GetConsensusHash() { // allocate and init a SHA256_CTX SHA256_CTX shaCtx; SHA256_Init(&shaCtx); LOCK(cs_tally); if (msc_debug_consensus_hash) PrintToLog("Beginning generation of current consensus hash...\n"); // Balances - loop through the tally map, updating the sha context with the data from each balance and tally type // Placeholders: "address|propertyid|balance|selloffer_reserve|accept_reserve|metadex_reserve" for (std::map<string, CMPTally>::iterator my_it = mp_tally_map.begin(); my_it != mp_tally_map.end(); ++my_it) { const std::string& address = my_it->first; CMPTally& tally = my_it->second; tally.init(); uint32_t propertyId = 0; while (0 != (propertyId = (tally.next()))) { std::string dataStr = GenerateConsensusString(tally, address, propertyId); if (dataStr.empty()) continue; // skip empty balances if (msc_debug_consensus_hash) PrintToLog("Adding balance data to consensus hash: %s\n", dataStr); SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length()); } } // DEx sell offers - loop through the DEx and add each sell offer to the consensus hash (ordered by txid) // Placeholders: "txid|address|propertyid|offeramount|btcdesired|minfee|timelimit" std::vector<std::pair<uint256, std::string> > vecDExOffers; for (OfferMap::iterator it = my_offers.begin(); it != my_offers.end(); ++it) { const CMPOffer& selloffer = it->second; const std::string& sellCombo = it->first; uint32_t propertyId = selloffer.getProperty(); std::string seller = sellCombo.substr(0, sellCombo.size() - 2); std::string dataStr = GenerateConsensusString(selloffer, seller, propertyId); vecDExOffers.push_back(std::make_pair(selloffer.getHash(), dataStr)); } std::sort (vecDExOffers.begin(), vecDExOffers.end()); for (std::vector<std::pair<uint256, std::string> >::iterator it = vecDExOffers.begin(); it != vecDExOffers.end(); ++it) { std::string dataStr = (*it).second; if (msc_debug_consensus_hash) PrintToLog("Adding DEx offer data to consensus hash: %s\n", dataStr); SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length()); } // DEx accepts - loop through the accepts map and add each accept to the consensus hash (ordered by matchedtxid then buyer) // Placeholders: "matchedselloffertxid|buyer|acceptamount|acceptamountremaining|acceptblock" std::vector<std::pair<std::string, std::string> > vecAccepts; for (AcceptMap::const_iterator it = my_accepts.begin(); it != my_accepts.end(); ++it) { const CMPAccept& accept = it->second; const std::string& acceptCombo = it->first; std::string buyer = acceptCombo.substr((acceptCombo.find("+") + 1), (acceptCombo.size()-(acceptCombo.find("+") + 1))); std::string dataStr = GenerateConsensusString(accept, buyer); std::string sortKey = strprintf("%s-%s", accept.getHash().GetHex(), buyer); vecAccepts.push_back(std::make_pair(sortKey, dataStr)); } std::sort (vecAccepts.begin(), vecAccepts.end()); for (std::vector<std::pair<std::string, std::string> >::iterator it = vecAccepts.begin(); it != vecAccepts.end(); ++it) { std::string dataStr = (*it).second; if (msc_debug_consensus_hash) PrintToLog("Adding DEx accept to consensus hash: %s\n", dataStr); SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length()); } // MetaDEx trades - loop through the MetaDEx maps and add each open trade to the consensus hash (ordered by txid) // Placeholders: "txid|address|propertyidforsale|amountforsale|propertyiddesired|amountdesired|amountremaining" std::vector<std::pair<uint256, std::string> > vecMetaDExTrades; for (md_PropertiesMap::const_iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) { const md_PricesMap& prices = my_it->second; for (md_PricesMap::const_iterator it = prices.begin(); it != prices.end(); ++it) { const md_Set& indexes = it->second; for (md_Set::const_iterator it = indexes.begin(); it != indexes.end(); ++it) { const CMPMetaDEx& obj = *it; std::string dataStr = GenerateConsensusString(obj); vecMetaDExTrades.push_back(std::make_pair(obj.getHash(), dataStr)); } } } std::sort (vecMetaDExTrades.begin(), vecMetaDExTrades.end()); for (std::vector<std::pair<uint256, std::string> >::iterator it = vecMetaDExTrades.begin(); it != vecMetaDExTrades.end(); ++it) { std::string dataStr = (*it).second; if (msc_debug_consensus_hash) PrintToLog("Adding MetaDEx trade data to consensus hash: %s\n", dataStr); SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length()); } // Crowdsales - loop through open crowdsales and add to the consensus hash (ordered by property ID) // Note: the variables of the crowdsale (amount, bonus etc) are not part of the crowdsale map and not included here to // avoid additionalal loading of SP entries from the database // Placeholders: "propertyid|propertyiddesired|deadline|usertokens|issuertokens" std::vector<std::pair<uint32_t, std::string> > vecCrowds; for (CrowdMap::const_iterator it = my_crowds.begin(); it != my_crowds.end(); ++it) { const CMPCrowd& crowd = it->second; uint32_t propertyId = crowd.getPropertyId(); std::string dataStr = GenerateConsensusString(crowd); vecCrowds.push_back(std::make_pair(propertyId, dataStr)); } std::sort (vecCrowds.begin(), vecCrowds.end()); for (std::vector<std::pair<uint32_t, std::string> >::iterator it = vecCrowds.begin(); it != vecCrowds.end(); ++it) { std::string dataStr = (*it).second; if (msc_debug_consensus_hash) PrintToLog("Adding Crowdsale entry to consensus hash: %s\n", dataStr); SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length()); } // Properties - loop through each property and store the issuer (to capture state changes via change issuer transactions) // Note: we are loading every SP from the DB to check the issuer, if using consensus_hash_every_block debug option this // will slow things down dramatically. Not an issue to do it once every 10,000 blocks for checkpoint verification. // Placeholders: "propertyid|issueraddress" for (uint8_t ecosystem = 1; ecosystem <= 2; ecosystem++) { uint32_t startPropertyId = (ecosystem == 1) ? 1 : TEST_ECO_PROPERTY_1; for (uint32_t propertyId = startPropertyId; propertyId < _my_sps->peekNextSPID(ecosystem); propertyId++) { CMPSPInfo::Entry sp; { LOCK(cs_tally); if (!_my_sps->getSP(propertyId, sp)) { PrintToLog("Error loading property ID %d for consensus hashing, hash should not be trusted!\n"); continue; } } std::string dataStr = GenerateConsensusString(propertyId, sp.issuer); if (msc_debug_consensus_hash) PrintToLog("Adding property to consensus hash: %s\n", dataStr); SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length()); } } // extract the final result and return the hash uint256 consensusHash; SHA256_Final((unsigned char*)&consensusHash, &shaCtx); if (msc_debug_consensus_hash) PrintToLog("Finished generation of consensus hash. Result: %s\n", consensusHash.GetHex()); return consensusHash; } } // namespace mastercore <commit_msg>Remove second tally lock (thanks @dexX7)<commit_after>/** * @file consensushash.cpp * * This file contains the function to generate consensus hashes. */ #include "omnicore/consensushash.h" #include "omnicore/dex.h" #include "omnicore/mdex.h" #include "omnicore/log.h" #include "omnicore/omnicore.h" #include "omnicore/sp.h" #include <stdint.h> #include <string> #include <openssl/sha.h> namespace mastercore { // Generates a consensus string for hashing based on a tally object std::string GenerateConsensusString(const CMPTally& tallyObj, const std::string& address, const uint32_t propertyId) { int64_t balance = tallyObj.getMoney(propertyId, BALANCE); int64_t sellOfferReserve = tallyObj.getMoney(propertyId, SELLOFFER_RESERVE); int64_t acceptReserve = tallyObj.getMoney(propertyId, ACCEPT_RESERVE); int64_t metaDExReserve = tallyObj.getMoney(propertyId, METADEX_RESERVE); // return a blank string if all balances are empty if (!balance && !sellOfferReserve && !acceptReserve && !metaDExReserve) return ""; return strprintf("%s|%d|%d|%d|%d|%d", address, propertyId, balance, sellOfferReserve, acceptReserve, metaDExReserve); } // Generates a consensus string for hashing based on a DEx sell offer object std::string GenerateConsensusString(const CMPOffer& offerObj, const std::string& address, const uint32_t propertyId) { return strprintf("%s|%s|%d|%d|%d|%d|%d", offerObj.getHash().GetHex(), address, propertyId, offerObj.getOfferAmountOriginal(), offerObj.getBTCDesiredOriginal(), offerObj.getMinFee(), offerObj.getBlockTimeLimit()); } // Generates a consensus string for hashing based on a DEx accept object std::string GenerateConsensusString(const CMPAccept& acceptObj, const std::string& address) { return strprintf("%s|%s|%d|%d|%d", acceptObj.getHash().GetHex(), address, acceptObj.getAcceptAmount(), acceptObj.getAcceptAmountRemaining(), acceptObj.getAcceptBlock()); } // Generates a consensus string for hashing based on a MetaDEx object std::string GenerateConsensusString(const CMPMetaDEx& tradeObj) { return strprintf("%s|%s|%d|%d|%d|%d|%d", tradeObj.getHash().GetHex(), tradeObj.getAddr(), tradeObj.getProperty(), tradeObj.getAmountForSale(), tradeObj.getDesProperty(), tradeObj.getAmountDesired(), tradeObj.getAmountRemaining()); } // Generates a consensus string for hashing based on a crowdsale object std::string GenerateConsensusString(const CMPCrowd& crowdObj) { return strprintf("%d|%d|%d|%d|%d", crowdObj.getPropertyId(), crowdObj.getCurrDes(), crowdObj.getDeadline(), crowdObj.getUserCreated(), crowdObj.getIssuerCreated()); } // Generates a consensus string for hashing based on a property issuer std::string GenerateConsensusString(const uint32_t propertyId, const std::string& address) { return strprintf("%d|%s", propertyId, address); } /** * Obtains a hash of the active state to use for consensus verification and checkpointing. * * For increased flexibility, so other implementations like OmniWallet and OmniChest can * also apply this methodology without necessarily using the same exact data types (which * would be needed to hash the data bytes directly), create a string in the following * format for each entry to use for hashing: * * ---STAGE 1 - BALANCES--- * Format specifiers & placeholders: * "%s|%d|%d|%d|%d|%d" - "address|propertyid|balance|selloffer_reserve|accept_reserve|metadex_reserve" * * Note: empty balance records and the pending tally are ignored. Addresses are sorted based * on lexicographical order, and balance records are sorted by the property identifiers. * * ---STAGE 2 - DEX SELL OFFERS--- * Format specifiers & placeholders: * "%s|%s|%d|%d|%d|%d|%d" - "txid|address|propertyid|offeramount|btcdesired|minfee|timelimit" * * Note: ordered ascending by txid. * * ---STAGE 3 - DEX ACCEPTS--- * Format specifiers & placeholders: * "%s|%s|%d|%d|%d" - "matchedselloffertxid|buyer|acceptamount|acceptamountremaining|acceptblock" * * Note: ordered ascending by matchedselloffertxid followed by buyer. * * ---STAGE 4 - METADEX TRADES--- * Format specifiers & placeholders: * "%s|%s|%d|%d|%d|%d|%d" - "txid|address|propertyidforsale|amountforsale|propertyiddesired|amountdesired|amountremaining" * * Note: ordered ascending by txid. * * ---STAGE 5 - CROWDSALES--- * Format specifiers & placeholders: * "%d|%d|%d|%d|%d" - "propertyid|propertyiddesired|deadline|usertokens|issuertokens" * * Note: ordered by property ID. * * ---STAGE 6 - PROPERTIES--- * Format specifiers & placeholders: * "%d|%s" - "propertyid|issueraddress" * * Note: ordered by property ID. * * The byte order is important, and we assume: * SHA256("abc") = "ad1500f261ff10b49c7a1796a36103b02322ae5dde404141eacf018fbf1678ba" * */ uint256 GetConsensusHash() { // allocate and init a SHA256_CTX SHA256_CTX shaCtx; SHA256_Init(&shaCtx); LOCK(cs_tally); if (msc_debug_consensus_hash) PrintToLog("Beginning generation of current consensus hash...\n"); // Balances - loop through the tally map, updating the sha context with the data from each balance and tally type // Placeholders: "address|propertyid|balance|selloffer_reserve|accept_reserve|metadex_reserve" for (std::map<string, CMPTally>::iterator my_it = mp_tally_map.begin(); my_it != mp_tally_map.end(); ++my_it) { const std::string& address = my_it->first; CMPTally& tally = my_it->second; tally.init(); uint32_t propertyId = 0; while (0 != (propertyId = (tally.next()))) { std::string dataStr = GenerateConsensusString(tally, address, propertyId); if (dataStr.empty()) continue; // skip empty balances if (msc_debug_consensus_hash) PrintToLog("Adding balance data to consensus hash: %s\n", dataStr); SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length()); } } // DEx sell offers - loop through the DEx and add each sell offer to the consensus hash (ordered by txid) // Placeholders: "txid|address|propertyid|offeramount|btcdesired|minfee|timelimit" std::vector<std::pair<uint256, std::string> > vecDExOffers; for (OfferMap::iterator it = my_offers.begin(); it != my_offers.end(); ++it) { const CMPOffer& selloffer = it->second; const std::string& sellCombo = it->first; uint32_t propertyId = selloffer.getProperty(); std::string seller = sellCombo.substr(0, sellCombo.size() - 2); std::string dataStr = GenerateConsensusString(selloffer, seller, propertyId); vecDExOffers.push_back(std::make_pair(selloffer.getHash(), dataStr)); } std::sort (vecDExOffers.begin(), vecDExOffers.end()); for (std::vector<std::pair<uint256, std::string> >::iterator it = vecDExOffers.begin(); it != vecDExOffers.end(); ++it) { std::string dataStr = (*it).second; if (msc_debug_consensus_hash) PrintToLog("Adding DEx offer data to consensus hash: %s\n", dataStr); SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length()); } // DEx accepts - loop through the accepts map and add each accept to the consensus hash (ordered by matchedtxid then buyer) // Placeholders: "matchedselloffertxid|buyer|acceptamount|acceptamountremaining|acceptblock" std::vector<std::pair<std::string, std::string> > vecAccepts; for (AcceptMap::const_iterator it = my_accepts.begin(); it != my_accepts.end(); ++it) { const CMPAccept& accept = it->second; const std::string& acceptCombo = it->first; std::string buyer = acceptCombo.substr((acceptCombo.find("+") + 1), (acceptCombo.size()-(acceptCombo.find("+") + 1))); std::string dataStr = GenerateConsensusString(accept, buyer); std::string sortKey = strprintf("%s-%s", accept.getHash().GetHex(), buyer); vecAccepts.push_back(std::make_pair(sortKey, dataStr)); } std::sort (vecAccepts.begin(), vecAccepts.end()); for (std::vector<std::pair<std::string, std::string> >::iterator it = vecAccepts.begin(); it != vecAccepts.end(); ++it) { std::string dataStr = (*it).second; if (msc_debug_consensus_hash) PrintToLog("Adding DEx accept to consensus hash: %s\n", dataStr); SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length()); } // MetaDEx trades - loop through the MetaDEx maps and add each open trade to the consensus hash (ordered by txid) // Placeholders: "txid|address|propertyidforsale|amountforsale|propertyiddesired|amountdesired|amountremaining" std::vector<std::pair<uint256, std::string> > vecMetaDExTrades; for (md_PropertiesMap::const_iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) { const md_PricesMap& prices = my_it->second; for (md_PricesMap::const_iterator it = prices.begin(); it != prices.end(); ++it) { const md_Set& indexes = it->second; for (md_Set::const_iterator it = indexes.begin(); it != indexes.end(); ++it) { const CMPMetaDEx& obj = *it; std::string dataStr = GenerateConsensusString(obj); vecMetaDExTrades.push_back(std::make_pair(obj.getHash(), dataStr)); } } } std::sort (vecMetaDExTrades.begin(), vecMetaDExTrades.end()); for (std::vector<std::pair<uint256, std::string> >::iterator it = vecMetaDExTrades.begin(); it != vecMetaDExTrades.end(); ++it) { std::string dataStr = (*it).second; if (msc_debug_consensus_hash) PrintToLog("Adding MetaDEx trade data to consensus hash: %s\n", dataStr); SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length()); } // Crowdsales - loop through open crowdsales and add to the consensus hash (ordered by property ID) // Note: the variables of the crowdsale (amount, bonus etc) are not part of the crowdsale map and not included here to // avoid additionalal loading of SP entries from the database // Placeholders: "propertyid|propertyiddesired|deadline|usertokens|issuertokens" std::vector<std::pair<uint32_t, std::string> > vecCrowds; for (CrowdMap::const_iterator it = my_crowds.begin(); it != my_crowds.end(); ++it) { const CMPCrowd& crowd = it->second; uint32_t propertyId = crowd.getPropertyId(); std::string dataStr = GenerateConsensusString(crowd); vecCrowds.push_back(std::make_pair(propertyId, dataStr)); } std::sort (vecCrowds.begin(), vecCrowds.end()); for (std::vector<std::pair<uint32_t, std::string> >::iterator it = vecCrowds.begin(); it != vecCrowds.end(); ++it) { std::string dataStr = (*it).second; if (msc_debug_consensus_hash) PrintToLog("Adding Crowdsale entry to consensus hash: %s\n", dataStr); SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length()); } // Properties - loop through each property and store the issuer (to capture state changes via change issuer transactions) // Note: we are loading every SP from the DB to check the issuer, if using consensus_hash_every_block debug option this // will slow things down dramatically. Not an issue to do it once every 10,000 blocks for checkpoint verification. // Placeholders: "propertyid|issueraddress" for (uint8_t ecosystem = 1; ecosystem <= 2; ecosystem++) { uint32_t startPropertyId = (ecosystem == 1) ? 1 : TEST_ECO_PROPERTY_1; for (uint32_t propertyId = startPropertyId; propertyId < _my_sps->peekNextSPID(ecosystem); propertyId++) { CMPSPInfo::Entry sp; if (!_my_sps->getSP(propertyId, sp)) { PrintToLog("Error loading property ID %d for consensus hashing, hash should not be trusted!\n"); continue; } std::string dataStr = GenerateConsensusString(propertyId, sp.issuer); if (msc_debug_consensus_hash) PrintToLog("Adding property to consensus hash: %s\n", dataStr); SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length()); } } // extract the final result and return the hash uint256 consensusHash; SHA256_Final((unsigned char*)&consensusHash, &shaCtx); if (msc_debug_consensus_hash) PrintToLog("Finished generation of consensus hash. Result: %s\n", consensusHash.GetHex()); return consensusHash; } } // namespace mastercore <|endoftext|>
<commit_before>// Copyright (c) 2015 Pierre Moulon. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENMVG_SFM_REPORT_HPP #define OPENMVG_SFM_REPORT_HPP #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include "third_party/htmlDoc/htmlDoc.hpp" #include "third_party/histogram/histogram.hpp" #include "third_party/vectorGraphics/svgDrawer.hpp" namespace openMVG { namespace sfm { static bool Generate_SfM_Report ( const SfM_Data & sfm_data, const std::string & htmlFilename ) { // Compute mean,max,median residual values per View IndexT residualCount = 0; Hash_Map< IndexT, std::vector<double> > residuals_per_view; for (Landmarks::const_iterator iterTracks = sfm_data.GetLandmarks().begin(); iterTracks != sfm_data.GetLandmarks().end(); ++iterTracks ) { const Observations & obs = iterTracks->second.obs; for (Observations::const_iterator itObs = obs.begin(); itObs != obs.end(); ++itObs) { const View * view = sfm_data.GetViews().at(itObs->first).get(); const geometry::Pose3 pose = sfm_data.GetPoseOrDie(view); const cameras::IntrinsicBase * intrinsic = sfm_data.GetIntrinsics().at(view->id_intrinsic).get(); // Use absolute values const Vec2 residual = intrinsic->residual(pose, iterTracks->second.X, itObs->second.x).array().abs(); residuals_per_view[itObs->first].push_back(residual(0)); residuals_per_view[itObs->first].push_back(residual(1)); ++residualCount; } } using namespace htmlDocument; // extract directory from htmlFilename const std::string sTableBegin = "<table border=\"1\">", sTableEnd = "</table>", sRowBegin= "<tr>", sRowEnd = "</tr>", sColBegin = "<td>", sColEnd = "</td>", sNewLine = "<br>", sFullLine = "<hr>"; htmlDocument::htmlDocumentStream htmlDocStream("SFM report."); htmlDocStream.pushInfo( htmlDocument::htmlMarkup("h1", std::string("SFM report."))); htmlDocStream.pushInfo(sFullLine); htmlDocStream.pushInfo( "Dataset info:" + sNewLine ); std::ostringstream os; os << " #views: " << sfm_data.GetViews().size() << sNewLine << " #poses: " << sfm_data.GetPoses().size() << sNewLine << " #intrinsics: " << sfm_data.GetIntrinsics().size() << sNewLine << " #tracks: " << sfm_data.GetLandmarks().size() << sNewLine << " #residuals: " << residualCount << sNewLine; htmlDocStream.pushInfo( os.str() ); htmlDocStream.pushInfo( sFullLine ); htmlDocStream.pushInfo( sTableBegin); os.str(""); os << sRowBegin << sColBegin + "IdView" + sColEnd << sColBegin + "Basename" + sColEnd << sColBegin + "#Observations" + sColEnd << sColBegin + "Residuals min" + sColEnd << sColBegin + "Residuals median" + sColEnd << sColBegin + "Residuals mean" + sColEnd << sColBegin + "Residuals max" + sColEnd << sRowEnd; htmlDocStream.pushInfo( os.str() ); for (Views::const_iterator iterV = sfm_data.GetViews().begin(); iterV != sfm_data.GetViews().end(); ++iterV) { const View * v = iterV->second.get(); const IndexT id_view = v->id_view; os.str(""); os << sRowBegin << sColBegin << id_view << sColEnd << sColBegin + stlplus::basename_part(v->s_Img_path) + sColEnd; // IdView | basename | #Observations | residuals min | residual median | residual max if (sfm_data.IsPoseAndIntrinsicDefined(v)) { const std::vector<double> & residuals = residuals_per_view.at(id_view); if (!residuals.empty()) { double min, max, mean, median; minMaxMeanMedian(residuals.begin(), residuals.end(), min, max, mean, median); os << sColBegin << residuals.size()/2 << sColEnd // #observations << sColBegin << min << sColEnd << sColBegin << median << sColEnd << sColBegin << mean << sColEnd << sColBegin << max <<sColEnd; } } os << sRowEnd; htmlDocStream.pushInfo( os.str() ); } htmlDocStream.pushInfo( sTableEnd ); htmlDocStream.pushInfo( sFullLine ); // combine all residual values into one vector // export the SVG histogram { IndexT residualCount = 0; for (Hash_Map< IndexT, std::vector<double> >::const_iterator it = residuals_per_view.begin(); it != residuals_per_view.end(); ++it) { residualCount += it->second.size(); } // Concat per view residual values into one vector std::vector<double> residuals(residualCount); residualCount = 0; for (Hash_Map< IndexT, std::vector<double> >::const_iterator it = residuals_per_view.begin(); it != residuals_per_view.end(); ++it) { std::copy(it->second.begin(), it->second.begin()+it->second.size(), residuals.begin()+residualCount); residualCount += it->second.size(); } if (!residuals.empty()) { // RMSE computation const Eigen::Map<Eigen::RowVectorXd> residuals_mapping(&residuals[0], residuals.size()); const double RMSE = std::sqrt(residuals_mapping.squaredNorm() / (double)residuals.size()); os.str(""); os << sFullLine << "SfM Scene RMSE: " << RMSE << sFullLine; htmlDocStream.pushInfo(os.str()); const double maxRange = *max_element(residuals.begin(), residuals.end()); Histogram<double> histo(0.0, maxRange, 100); histo.Add(residuals.begin(), residuals.end()); svg::svgHisto svg_Histo; svg_Histo.draw(histo.GetHist(), std::pair<float,float>(0.f, maxRange), stlplus::create_filespec(stlplus::folder_part(htmlFilename), "residuals_histogram", "svg"), 600, 200); os.str(""); os << sNewLine<< "Residuals histogram" << sNewLine; os << "<img src=\"" << "residuals_histogram.svg" << "\" height=\"300\" width =\"800\">\n"; htmlDocStream.pushInfo(os.str()); } } std::ofstream htmlFileStream(htmlFilename.c_str()); htmlFileStream << htmlDocStream.getDoc(); const bool bOk = !htmlFileStream.bad(); return bOk; } } // namespace sfm } // namespace openMVG #endif // OPENMVG_SFM_REPORT_HPP <commit_msg>minor fix in html report file.<commit_after>// Copyright (c) 2015 Pierre Moulon. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENMVG_SFM_REPORT_HPP #define OPENMVG_SFM_REPORT_HPP #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include "third_party/htmlDoc/htmlDoc.hpp" #include "third_party/histogram/histogram.hpp" #include "third_party/vectorGraphics/svgDrawer.hpp" namespace openMVG { namespace sfm { static bool Generate_SfM_Report ( const SfM_Data & sfm_data, const std::string & htmlFilename ) { // Compute mean,max,median residual values per View IndexT residualCount = 0; Hash_Map< IndexT, std::vector<double> > residuals_per_view; for (Landmarks::const_iterator iterTracks = sfm_data.GetLandmarks().begin(); iterTracks != sfm_data.GetLandmarks().end(); ++iterTracks ) { const Observations & obs = iterTracks->second.obs; for (Observations::const_iterator itObs = obs.begin(); itObs != obs.end(); ++itObs) { const View * view = sfm_data.GetViews().at(itObs->first).get(); const geometry::Pose3 pose = sfm_data.GetPoseOrDie(view); const cameras::IntrinsicBase * intrinsic = sfm_data.GetIntrinsics().at(view->id_intrinsic).get(); // Use absolute values const Vec2 residual = intrinsic->residual(pose, iterTracks->second.X, itObs->second.x).array().abs(); residuals_per_view[itObs->first].push_back(residual(0)); residuals_per_view[itObs->first].push_back(residual(1)); ++residualCount; } } using namespace htmlDocument; // extract directory from htmlFilename const std::string sTableBegin = "<table border=\"1\">", sTableEnd = "</table>", sRowBegin= "<tr>", sRowEnd = "</tr>", sColBegin = "<td>", sColEnd = "</td>", sNewLine = "<br>", sFullLine = "<hr>"; htmlDocument::htmlDocumentStream htmlDocStream("SFM report."); htmlDocStream.pushInfo( htmlDocument::htmlMarkup("h1", std::string("SFM report."))); htmlDocStream.pushInfo(sFullLine); htmlDocStream.pushInfo( "Dataset info:" + sNewLine ); std::ostringstream os; os << " #views: " << sfm_data.GetViews().size() << sNewLine << " #poses: " << sfm_data.GetPoses().size() << sNewLine << " #intrinsics: " << sfm_data.GetIntrinsics().size() << sNewLine << " #tracks: " << sfm_data.GetLandmarks().size() << sNewLine << " #residuals: " << residualCount << sNewLine; htmlDocStream.pushInfo( os.str() ); htmlDocStream.pushInfo( sFullLine ); htmlDocStream.pushInfo( sTableBegin); os.str(""); os << sRowBegin << sColBegin + "IdView" + sColEnd << sColBegin + "Basename" + sColEnd << sColBegin + "#Observations" + sColEnd << sColBegin + "Residuals min" + sColEnd << sColBegin + "Residuals median" + sColEnd << sColBegin + "Residuals mean" + sColEnd << sColBegin + "Residuals max" + sColEnd << sRowEnd; htmlDocStream.pushInfo( os.str() ); for (Views::const_iterator iterV = sfm_data.GetViews().begin(); iterV != sfm_data.GetViews().end(); ++iterV) { const View * v = iterV->second.get(); const IndexT id_view = v->id_view; os.str(""); os << sRowBegin << sColBegin << id_view << sColEnd << sColBegin + stlplus::basename_part(v->s_Img_path) + sColEnd; // IdView | basename | #Observations | residuals min | residual median | residual max if (sfm_data.IsPoseAndIntrinsicDefined(v)) { if( residuals_per_view.find(id_view) != residuals_per_view.end() ) { const std::vector<double> & residuals = residuals_per_view.at(id_view); if (!residuals.empty()) { double min, max, mean, median; minMaxMeanMedian(residuals.begin(), residuals.end(), min, max, mean, median); os << sColBegin << residuals.size()/2 << sColEnd // #observations << sColBegin << min << sColEnd << sColBegin << median << sColEnd << sColBegin << mean << sColEnd << sColBegin << max <<sColEnd; } } } os << sRowEnd; htmlDocStream.pushInfo( os.str() ); } htmlDocStream.pushInfo( sTableEnd ); htmlDocStream.pushInfo( sFullLine ); // combine all residual values into one vector // export the SVG histogram { IndexT residualCount = 0; for (Hash_Map< IndexT, std::vector<double> >::const_iterator it = residuals_per_view.begin(); it != residuals_per_view.end(); ++it) { residualCount += it->second.size(); } // Concat per view residual values into one vector std::vector<double> residuals(residualCount); residualCount = 0; for (Hash_Map< IndexT, std::vector<double> >::const_iterator it = residuals_per_view.begin(); it != residuals_per_view.end(); ++it) { std::copy(it->second.begin(), it->second.begin()+it->second.size(), residuals.begin()+residualCount); residualCount += it->second.size(); } if (!residuals.empty()) { // RMSE computation const Eigen::Map<Eigen::RowVectorXd> residuals_mapping(&residuals[0], residuals.size()); const double RMSE = std::sqrt(residuals_mapping.squaredNorm() / (double)residuals.size()); os.str(""); os << sFullLine << "SfM Scene RMSE: " << RMSE << sFullLine; htmlDocStream.pushInfo(os.str()); const double maxRange = *max_element(residuals.begin(), residuals.end()); Histogram<double> histo(0.0, maxRange, 100); histo.Add(residuals.begin(), residuals.end()); svg::svgHisto svg_Histo; svg_Histo.draw(histo.GetHist(), std::pair<float,float>(0.f, maxRange), stlplus::create_filespec(stlplus::folder_part(htmlFilename), "residuals_histogram", "svg"), 600, 200); os.str(""); os << sNewLine<< "Residuals histogram" << sNewLine; os << "<img src=\"" << "residuals_histogram.svg" << "\" height=\"300\" width =\"800\">\n"; htmlDocStream.pushInfo(os.str()); } } std::ofstream htmlFileStream(htmlFilename.c_str()); htmlFileStream << htmlDocStream.getDoc(); const bool bOk = !htmlFileStream.bad(); return bOk; } } // namespace sfm } // namespace openMVG #endif // OPENMVG_SFM_REPORT_HPP <|endoftext|>
<commit_before>// *************************************************************************** // // Generated automatically by genwrapper. // Please DO NOT EDIT this file! // // *************************************************************************** #include <osgIntrospection/ReflectionMacros> #include <osgIntrospection/TypedMethodInfo> #include <osgIntrospection/Attributes> #include <osg/AlphaFunc> #include <osg/CopyOp> #include <osg/Shader> BEGIN_ENUM_REFLECTOR(osg::Shader::Type) EnumLabel(osg::Shader::VERTEX); EnumLabel(osg::Shader::FRAGMENT); EnumLabel(osg::Shader::UNDEFINED); END_REFLECTOR BEGIN_ABSTRACT_OBJECT_REFLECTOR(osg::Shader) BaseType(osg::Object); ConstructorWithDefaults1(IN, osg::Shader::Type, type, osg::Shader::UNDEFINED); Constructor2(IN, osg::Shader::Type, type, IN, const std::string &, source); ConstructorWithDefaults2(IN, const osg::Shader &, rhs, , IN, const osg::CopyOp &, copyop, osg::CopyOp::SHALLOW_COPY); Method2(, META_Object, IN, osg, x, IN, osg::Shader, x); Method1(int, compare, IN, const osg::Shader &, rhs); Method1(bool, setType, IN, osg::Shader::Type, t); Method1(void, setShaderSource, IN, const std::string &, sourceText); Method1(bool, loadShaderSourceFromFile, IN, const std::string &, fileName); Method0(const std::string &, getShaderSource); Method0(osg::Shader::Type, getType); Method0(const char *, getTypename); Method0(void, dirtyShader); Method1(void, compileShader, IN, unsigned int, contextID); Method2(void, attachShader, IN, unsigned int, contextID, IN, GLuint, program); Method2(bool, getGlShaderInfoLog, IN, unsigned int, contextID, IN, std::string &, log); Method1(void, setName, IN, const std::string &, name); Method1(void, setName, IN, const char *, name); Method0(const std::string &, getName); Property(const std::string &, Name); Property(const std::string &, ShaderSource); PropertyWithReturnType(osg::Shader::Type, Type, bool); ReadOnlyProperty(const char *, Typename); END_REFLECTOR <commit_msg>Updated wrappers.<commit_after>// *************************************************************************** // // Generated automatically by genwrapper. // Please DO NOT EDIT this file! // // *************************************************************************** #include <osgIntrospection/ReflectionMacros> #include <osgIntrospection/TypedMethodInfo> #include <osgIntrospection/Attributes> #include <osg/CopyOp> #include <osg/Object> #include <osg/Shader> BEGIN_ENUM_REFLECTOR(osg::Shader::Type) EnumLabel(osg::Shader::VERTEX); EnumLabel(osg::Shader::FRAGMENT); EnumLabel(osg::Shader::UNDEFINED); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osg::Shader) BaseType(osg::Object); ConstructorWithDefaults1(IN, osg::Shader::Type, type, osg::Shader::UNDEFINED); Constructor2(IN, osg::Shader::Type, type, IN, const std::string &, source); ConstructorWithDefaults2(IN, const osg::Shader &, rhs, , IN, const osg::CopyOp &, copyop, osg::CopyOp::SHALLOW_COPY); Method0(osg::Object *, cloneType); Method1(osg::Object *, clone, IN, const osg::CopyOp &, copyop); Method1(bool, isSameKindAs, IN, const osg::Object *, obj); Method0(const char *, libraryName); Method0(const char *, className); Method1(int, compare, IN, const osg::Shader &, rhs); Method1(bool, setType, IN, osg::Shader::Type, t); Method1(void, setShaderSource, IN, const std::string &, sourceText); Method1(bool, loadShaderSourceFromFile, IN, const std::string &, fileName); Method0(const std::string &, getShaderSource); Method0(osg::Shader::Type, getType); Method0(const char *, getTypename); Method0(void, dirtyShader); Method1(void, compileShader, IN, unsigned int, contextID); Method2(void, attachShader, IN, unsigned int, contextID, IN, GLuint, program); Method2(bool, getGlShaderInfoLog, IN, unsigned int, contextID, IN, std::string &, log); Method1(void, setName, IN, const std::string &, name); Method1(void, setName, IN, const char *, name); Method0(const std::string &, getName); Property(const std::string &, Name); Property(const std::string &, ShaderSource); PropertyWithReturnType(osg::Shader::Type, Type, bool); ReadOnlyProperty(const char *, Typename); END_REFLECTOR <|endoftext|>
<commit_before>#include <iostream> #include <stack> #include <queue> #include <cmath> using std::stack; using std::queue; #include "operatorregistry.h" #include "tokenizer.h" double toNumber(string numberString) { return std::stod(numberString); } double factorial(double n) { return (n <= 1) ? 1 : n * factorial(n - 1); } void registerOperatorsIn(OperatorRegistry& operatorsRegistry) { Operator plus("+", 2, 5, [](vector<double> args){return args[0] + args[1];}); operatorsRegistry.registerOperator(plus); Operator minus("-", 2, 5, [](vector<double> args){return args[0] - args[1];}); operatorsRegistry.registerOperator(minus); Operator mult("*", 2, 6, [](vector<double> args){return args[0] * args[1];}); operatorsRegistry.registerOperator(mult); Operator division("/", 2, 6, [](vector<double> args){return args[0] / args[1];}); operatorsRegistry.registerOperator(division); Operator fact("!", 1, 10, [](vector<double> args){return factorial(args[0]);}); operatorsRegistry.registerOperator(fact); Operator power("^", 2, 11, [](vector<double> args){return pow(args[0], args[1]);}); operatorsRegistry.registerOperator(power); } queue<Token> getReversedPolishNotationOf(string input, const OperatorRegistry& operatorsRegistry) { Tokenizer tokenizer(input); bool expectOperator = false; bool expectNegativeNumber = false; queue<Token> reversedPolishNotation; stack<Token> operators; Token token; while(tokenizer.present()) { token = tokenizer.get(); // std::cout << "|" << token.value << "|" << std::endl; if(token.isNumber) { if(expectNegativeNumber) { token.value.insert(0, "-"); reversedPolishNotation.push(token); expectNegativeNumber = false; } else { reversedPolishNotation.push(token); } expectOperator = true; } else { if(operatorsRegistry.hasOperatorFor(token.value)) { if(!expectOperator && token.value == "-") { expectNegativeNumber = true; continue; } Operator operatr = operatorsRegistry.getOperatorFor(token.value); double priority = operatr.getPriority(); while(!operators.empty() && operators.top().value != "(") { Operator topOperator = operatorsRegistry.getOperatorFor(operators.top().value); if(topOperator.getPriority() > priority) { reversedPolishNotation.push(operators.top()); operators.pop(); } else if(topOperator.getPriority() == priority && topOperator != operatr) { reversedPolishNotation.push(operators.top()); operators.pop(); } else { break; } } operators.push(token); expectOperator = false; } else // no operator { if(token.value == "(") { operators.push(token); } else if(token.value == ")") { while(!operators.empty() && operators.top().value != "(") { reversedPolishNotation.push(operators.top()); operators.pop(); } operators.pop(); //remove ( } else { throw logic_error("Unrecognized symbol"); } } } } while(!operators.empty()) { reversedPolishNotation.push(operators.top()); operators.pop(); } return reversedPolishNotation; } double evaluateReversedPolishNotation(queue<Token>& reversedPolishNotation, const OperatorRegistry& operatorsRegistry) { Token token; stack<double> numbers; while(!reversedPolishNotation.empty()) { token = reversedPolishNotation.front(); reversedPolishNotation.pop(); if(operatorsRegistry.hasOperatorFor(token.value)) { Operator operatr = operatorsRegistry.getOperatorFor(token.value); vector<double> operands; for (int i = 0; i < operatr.getArgumentsCount(); ++i) { if(numbers.empty()) { throw logic_error("Not enough operands"); } operands.insert(operands.begin(), numbers.top()); numbers.pop(); } numbers.push(operatr.evaluate(operands)); } else { numbers.push(toNumber(token.value)); } } if(numbers.size() != 1) { throw logic_error("Evaluaton error: More than one number in numbers stack at the end"); } return numbers.top(); } int main() { string input; std::getline(std::cin, input); OperatorRegistry operatorsRegistry; registerOperatorsIn(operatorsRegistry); queue<Token> reversedPolishNotation = getReversedPolishNotationOf(input, operatorsRegistry); double value = evaluateReversedPolishNotation(reversedPolishNotation, operatorsRegistry); std::cout << value << std::endl; return 0; } <commit_msg>RPN factorial priority fixed<commit_after>#include <iostream> #include <stack> #include <queue> #include <cmath> using std::stack; using std::queue; #include "operatorregistry.h" #include "tokenizer.h" double toNumber(string numberString) { return std::stod(numberString); } double factorial(double n) { return (n <= 1) ? 1 : n * factorial(n - 1); } void registerOperatorsIn(OperatorRegistry& operatorsRegistry) { Operator plus("+", 2, 5, [](vector<double> args){return args[0] + args[1];}); operatorsRegistry.registerOperator(plus); Operator minus("-", 2, 5, [](vector<double> args){return args[0] - args[1];}); operatorsRegistry.registerOperator(minus); Operator mult("*", 2, 6, [](vector<double> args){return args[0] * args[1];}); operatorsRegistry.registerOperator(mult); Operator division("/", 2, 6, [](vector<double> args){return args[0] / args[1];}); operatorsRegistry.registerOperator(division); Operator fact("!", 1, 11, [](vector<double> args){return factorial(args[0]);}); operatorsRegistry.registerOperator(fact); Operator power("^", 2, 10, [](vector<double> args){return pow(args[0], args[1]);}); operatorsRegistry.registerOperator(power); } queue<Token> getReversedPolishNotationOf(string input, const OperatorRegistry& operatorsRegistry) { Tokenizer tokenizer(input); bool expectOperator = false; bool expectNegativeNumber = false; queue<Token> reversedPolishNotation; stack<Token> operators; Token token; while(tokenizer.present()) { token = tokenizer.get(); // std::cout << "|" << token.value << "|" << std::endl; if(token.isNumber) { if(expectNegativeNumber) { token.value.insert(0, "-"); reversedPolishNotation.push(token); expectNegativeNumber = false; } else { reversedPolishNotation.push(token); } expectOperator = true; } else { if(operatorsRegistry.hasOperatorFor(token.value)) { if(!expectOperator && token.value == "-") { expectNegativeNumber = true; continue; } Operator operatr = operatorsRegistry.getOperatorFor(token.value); double priority = operatr.getPriority(); while(!operators.empty() && operators.top().value != "(") { Operator topOperator = operatorsRegistry.getOperatorFor(operators.top().value); if(topOperator.getPriority() > priority) { reversedPolishNotation.push(operators.top()); operators.pop(); } else if(topOperator.getPriority() == priority && topOperator != operatr) { reversedPolishNotation.push(operators.top()); operators.pop(); } else { break; } } operators.push(token); expectOperator = false; } else // no operator { if(token.value == "(") { operators.push(token); } else if(token.value == ")") { while(!operators.empty() && operators.top().value != "(") { reversedPolishNotation.push(operators.top()); operators.pop(); } operators.pop(); //remove ( } else { throw logic_error("Unrecognized symbol"); } } } } while(!operators.empty()) { reversedPolishNotation.push(operators.top()); operators.pop(); } return reversedPolishNotation; } double evaluateReversedPolishNotation(queue<Token>& reversedPolishNotation, const OperatorRegistry& operatorsRegistry) { Token token; stack<double> numbers; while(!reversedPolishNotation.empty()) { token = reversedPolishNotation.front(); reversedPolishNotation.pop(); if(operatorsRegistry.hasOperatorFor(token.value)) { Operator operatr = operatorsRegistry.getOperatorFor(token.value); vector<double> operands; for (int i = 0; i < operatr.getArgumentsCount(); ++i) { if(numbers.empty()) { throw logic_error("Not enough operands"); } operands.insert(operands.begin(), numbers.top()); numbers.pop(); } numbers.push(operatr.evaluate(operands)); } else { numbers.push(toNumber(token.value)); } } if(numbers.size() != 1) { throw logic_error("Evaluaton error: More than one number in numbers stack at the end"); } return numbers.top(); } int main() { string input; std::getline(std::cin, input); OperatorRegistry operatorsRegistry; registerOperatorsIn(operatorsRegistry); queue<Token> reversedPolishNotation = getReversedPolishNotationOf(input, operatorsRegistry); double value = evaluateReversedPolishNotation(reversedPolishNotation, operatorsRegistry); std::cout << value << std::endl; return 0; } <|endoftext|>
<commit_before>//===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Correlated Value Propagation pass. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "correlated-value-propagation" #include "llvm/Transforms/Scalar.h" #include "llvm/Function.h" #include "llvm/Instructions.h" #include "llvm/Pass.h" #include "llvm/Analysis/LazyValueInfo.h" #include "llvm/Support/CFG.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/ADT/Statistic.h" using namespace llvm; STATISTIC(NumPhis, "Number of phis propagated"); STATISTIC(NumSelects, "Number of selects propagated"); STATISTIC(NumMemAccess, "Number of memory access targets propagated"); STATISTIC(NumCmps, "Number of comparisons propagated"); namespace { class CorrelatedValuePropagation : public FunctionPass { LazyValueInfo *LVI; bool processSelect(SelectInst *SI); bool processPHI(PHINode *P); bool processMemAccess(Instruction *I); bool processCmp(CmpInst *C); public: static char ID; CorrelatedValuePropagation(): FunctionPass(ID) { } bool runOnFunction(Function &F); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<LazyValueInfo>(); } }; } char CorrelatedValuePropagation::ID = 0; INITIALIZE_PASS(CorrelatedValuePropagation, "correlated-propagation", "Value Propagation", false, false); // Public interface to the Value Propagation pass Pass *llvm::createCorrelatedValuePropagationPass() { return new CorrelatedValuePropagation(); } bool CorrelatedValuePropagation::processSelect(SelectInst *S) { if (S->getType()->isVectorTy()) return false; if (isa<Constant>(S->getOperand(0))) return false; Constant *C = LVI->getConstant(S->getOperand(0), S->getParent()); if (!C) return false; ConstantInt *CI = dyn_cast<ConstantInt>(C); if (!CI) return false; S->replaceAllUsesWith(S->getOperand(CI->isOne() ? 1 : 2)); S->eraseFromParent(); ++NumSelects; return true; } bool CorrelatedValuePropagation::processPHI(PHINode *P) { bool Changed = false; BasicBlock *BB = P->getParent(); for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) { Value *Incoming = P->getIncomingValue(i); if (isa<Constant>(Incoming)) continue; Constant *C = LVI->getConstantOnEdge(P->getIncomingValue(i), P->getIncomingBlock(i), BB); if (!C) continue; P->setIncomingValue(i, C); Changed = true; } if (Value *ConstVal = P->hasConstantValue()) { P->replaceAllUsesWith(ConstVal); P->eraseFromParent(); Changed = true; } ++NumPhis; return Changed; } bool CorrelatedValuePropagation::processMemAccess(Instruction *I) { Value *Pointer = 0; if (LoadInst *L = dyn_cast<LoadInst>(I)) Pointer = L->getPointerOperand(); else Pointer = cast<StoreInst>(I)->getPointerOperand(); if (isa<Constant>(Pointer)) return false; Constant *C = LVI->getConstant(Pointer, I->getParent()); if (!C) return false; ++NumMemAccess; I->replaceUsesOfWith(Pointer, C); return true; } /// processCmp - If the value of this comparison could be determined locally, /// constant propagation would already have figured it out. Instead, walk /// the predecessors and statically evaluate the comparison based on information /// available on that edge. If a given static evaluation is true on ALL /// incoming edges, then it's true universally and we can simplify the compare. bool CorrelatedValuePropagation::processCmp(CmpInst *C) { Value *Op0 = C->getOperand(0); if (isa<Instruction>(Op0) && cast<Instruction>(Op0)->getParent() == C->getParent()) return false; Constant *Op1 = dyn_cast<Constant>(C->getOperand(1)); if (!Op1) return false; pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent()); if (PI == PE) return false; LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(), C->getOperand(0), Op1, *PI, C->getParent()); if (Result == LazyValueInfo::Unknown) return false; ++PI; while (PI != PE) { LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(), C->getOperand(0), Op1, *PI, C->getParent()); if (Res != Result) return false; ++PI; } ++NumCmps; if (Result == LazyValueInfo::True) C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext())); else C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext())); C->eraseFromParent(); return true; } bool CorrelatedValuePropagation::runOnFunction(Function &F) { LVI = &getAnalysis<LazyValueInfo>(); bool FnChanged = false; for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) { bool BBChanged = false; for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) { Instruction *II = BI++; switch (II->getOpcode()) { case Instruction::Select: BBChanged |= processSelect(cast<SelectInst>(II)); break; case Instruction::PHI: BBChanged |= processPHI(cast<PHINode>(II)); break; case Instruction::ICmp: case Instruction::FCmp: BBChanged |= processCmp(cast<CmpInst>(II)); break; case Instruction::Load: case Instruction::Store: BBChanged |= processMemAccess(II); break; } } // Propagating correlated values might leave cruft around. // Try to clean it up before we continue. if (BBChanged) SimplifyInstructionsInBlock(FI); FnChanged |= BBChanged; } return FnChanged; } <commit_msg>Use a depth-first iteratation in CorrelatedValuePropagation to avoid wasting time trying to optimize unreachable blocks.<commit_after>//===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Correlated Value Propagation pass. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "correlated-value-propagation" #include "llvm/Transforms/Scalar.h" #include "llvm/Function.h" #include "llvm/Instructions.h" #include "llvm/Pass.h" #include "llvm/Analysis/LazyValueInfo.h" #include "llvm/Support/CFG.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/ADT/Statistic.h" using namespace llvm; STATISTIC(NumPhis, "Number of phis propagated"); STATISTIC(NumSelects, "Number of selects propagated"); STATISTIC(NumMemAccess, "Number of memory access targets propagated"); STATISTIC(NumCmps, "Number of comparisons propagated"); namespace { class CorrelatedValuePropagation : public FunctionPass { LazyValueInfo *LVI; bool processSelect(SelectInst *SI); bool processPHI(PHINode *P); bool processMemAccess(Instruction *I); bool processCmp(CmpInst *C); public: static char ID; CorrelatedValuePropagation(): FunctionPass(ID) { } bool runOnFunction(Function &F); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<LazyValueInfo>(); } }; } char CorrelatedValuePropagation::ID = 0; INITIALIZE_PASS(CorrelatedValuePropagation, "correlated-propagation", "Value Propagation", false, false); // Public interface to the Value Propagation pass Pass *llvm::createCorrelatedValuePropagationPass() { return new CorrelatedValuePropagation(); } bool CorrelatedValuePropagation::processSelect(SelectInst *S) { if (S->getType()->isVectorTy()) return false; if (isa<Constant>(S->getOperand(0))) return false; Constant *C = LVI->getConstant(S->getOperand(0), S->getParent()); if (!C) return false; ConstantInt *CI = dyn_cast<ConstantInt>(C); if (!CI) return false; S->replaceAllUsesWith(S->getOperand(CI->isOne() ? 1 : 2)); S->eraseFromParent(); ++NumSelects; return true; } bool CorrelatedValuePropagation::processPHI(PHINode *P) { bool Changed = false; BasicBlock *BB = P->getParent(); for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) { Value *Incoming = P->getIncomingValue(i); if (isa<Constant>(Incoming)) continue; Constant *C = LVI->getConstantOnEdge(P->getIncomingValue(i), P->getIncomingBlock(i), BB); if (!C) continue; P->setIncomingValue(i, C); Changed = true; } if (Value *ConstVal = P->hasConstantValue()) { P->replaceAllUsesWith(ConstVal); P->eraseFromParent(); Changed = true; } ++NumPhis; return Changed; } bool CorrelatedValuePropagation::processMemAccess(Instruction *I) { Value *Pointer = 0; if (LoadInst *L = dyn_cast<LoadInst>(I)) Pointer = L->getPointerOperand(); else Pointer = cast<StoreInst>(I)->getPointerOperand(); if (isa<Constant>(Pointer)) return false; Constant *C = LVI->getConstant(Pointer, I->getParent()); if (!C) return false; ++NumMemAccess; I->replaceUsesOfWith(Pointer, C); return true; } /// processCmp - If the value of this comparison could be determined locally, /// constant propagation would already have figured it out. Instead, walk /// the predecessors and statically evaluate the comparison based on information /// available on that edge. If a given static evaluation is true on ALL /// incoming edges, then it's true universally and we can simplify the compare. bool CorrelatedValuePropagation::processCmp(CmpInst *C) { Value *Op0 = C->getOperand(0); if (isa<Instruction>(Op0) && cast<Instruction>(Op0)->getParent() == C->getParent()) return false; Constant *Op1 = dyn_cast<Constant>(C->getOperand(1)); if (!Op1) return false; pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent()); if (PI == PE) return false; LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(), C->getOperand(0), Op1, *PI, C->getParent()); if (Result == LazyValueInfo::Unknown) return false; ++PI; while (PI != PE) { LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(), C->getOperand(0), Op1, *PI, C->getParent()); if (Res != Result) return false; ++PI; } ++NumCmps; if (Result == LazyValueInfo::True) C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext())); else C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext())); C->eraseFromParent(); return true; } bool CorrelatedValuePropagation::runOnFunction(Function &F) { LVI = &getAnalysis<LazyValueInfo>(); bool FnChanged = false; // Perform a depth-first walk of the CFG so that we don't waste time // optimizing unreachable blocks. for (df_iterator<BasicBlock*> FI = df_begin(&F.getEntryBlock()), FE = df_end(&F.getEntryBlock()); FI != FE; ++FI) { bool BBChanged = false; for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) { Instruction *II = BI++; switch (II->getOpcode()) { case Instruction::Select: BBChanged |= processSelect(cast<SelectInst>(II)); break; case Instruction::PHI: BBChanged |= processPHI(cast<PHINode>(II)); break; case Instruction::ICmp: case Instruction::FCmp: BBChanged |= processCmp(cast<CmpInst>(II)); break; case Instruction::Load: case Instruction::Store: BBChanged |= processMemAccess(II); break; } } // Propagating correlated values might leave cruft around. // Try to clean it up before we continue. if (BBChanged) SimplifyInstructionsInBlock(*FI); FnChanged |= BBChanged; } return FnChanged; } <|endoftext|>
<commit_before>#include "data_uri.h" #include <algorithm> #include <iostream> #include <string> #include "base64.h" using std::cout; using std::endl; using std::string; size_t DataURI::Leanify(size_t size_leanified /*= 0*/) { uint8_t *p_read = fp_, *p_write = fp_ - size_leanified; while (p_read < fp_ + size_) { const string magic = "data:image/"; uint8_t* data_magic = std::search(p_read, fp_ + size_, magic.begin(), magic.end()); if (data_magic >= fp_ + size_) { memmove(p_write, p_read, fp_ + size_ - p_read); p_write += fp_ + size_ - p_read; break; } const string base64_sign = ";base64,"; const size_t kMaxSearchGap = 64; uint8_t* search_end = data_magic + magic.size() + kMaxSearchGap + base64_sign.size(); search_end = std::min(search_end, fp_ + size_); uint8_t* start = std::search(data_magic + magic.size(), search_end, base64_sign.begin(), base64_sign.end()) + base64_sign.size(); memmove(p_write, p_read, start - p_read); p_write += start - p_read; p_read = start; if (p_read > search_end) continue; const string quote = "'\")"; uint8_t* end = fp_ + size_; if (!single_mode_) { end = std::find_first_of(p_read, fp_ + size_, quote.begin(), quote.end()); if (end >= fp_ + size_) { memmove(p_write, p_read, fp_ + size_ - p_read); p_write += fp_ + size_ - p_read; break; } } if (is_verbose) { cout << string(reinterpret_cast<char*>(data_magic), start + 8 - data_magic) << "... found at offset 0x" << std::hex << data_magic - fp_ << std::dec << endl; } size_t new_size = Base64(p_read, end - p_read).Leanify(p_read - p_write); p_write += new_size; p_read = end; } fp_ -= size_leanified; size_ = p_write - fp_; return size_; } <commit_msg>DataURI: don't print offset in single mode<commit_after>#include "data_uri.h" #include <algorithm> #include <iostream> #include <string> #include "base64.h" using std::cout; using std::endl; using std::string; size_t DataURI::Leanify(size_t size_leanified /*= 0*/) { uint8_t *p_read = fp_, *p_write = fp_ - size_leanified; while (p_read < fp_ + size_) { const string magic = "data:image/"; uint8_t* data_magic = std::search(p_read, fp_ + size_, magic.begin(), magic.end()); if (data_magic >= fp_ + size_) { memmove(p_write, p_read, fp_ + size_ - p_read); p_write += fp_ + size_ - p_read; break; } const string base64_sign = ";base64,"; const size_t kMaxSearchGap = 64; uint8_t* search_end = data_magic + magic.size() + kMaxSearchGap + base64_sign.size(); search_end = std::min(search_end, fp_ + size_); uint8_t* start = std::search(data_magic + magic.size(), search_end, base64_sign.begin(), base64_sign.end()) + base64_sign.size(); memmove(p_write, p_read, start - p_read); p_write += start - p_read; p_read = start; if (p_read > search_end) continue; const string quote = "'\")"; uint8_t* end = fp_ + size_; if (!single_mode_) { end = std::find_first_of(p_read, fp_ + size_, quote.begin(), quote.end()); if (end >= fp_ + size_) { memmove(p_write, p_read, fp_ + size_ - p_read); p_write += fp_ + size_ - p_read; break; } } if (is_verbose) { cout << string(reinterpret_cast<char*>(data_magic), start + 8 - data_magic) << "... found"; if (!single_mode_) { cout << " at offset 0x" << std::hex << data_magic - fp_ << std::dec; } cout << endl; } size_t new_size = Base64(p_read, end - p_read).Leanify(p_read - p_write); p_write += new_size; p_read = end; } fp_ -= size_leanified; size_ = p_write - fp_; return size_; } <|endoftext|>
<commit_before>#include "camera.hpp" //constructors Camera::Camera() : _position{0.0}, _direction{1.0,0.0,0.0}, _aperture{40.0} {} Camera::Camera(glm::vec3 const& direction, float aperture) : _direction{direction}, _aperture{aperture} {} Camera::Camera(std::string const& name, float aperture) : _name{name}, _aperture{aperture} {} //destructors Camera::~Camera() {} //get-methods std::string const& Camera::name() const { return _name; } glm::vec3 const& Camera::position() const { return _position; } glm::vec3 const& Camera::direction() const { return _direction; } //non-member functions Ray Camera::getEyeRay(int x, int y, float &distance) const { return Ray{glm::vec3{_position}, glm::vec3{x, y, distance}}; } float Camera::getDistance(int width) const { return (width/2)/tan(_aperture/2); } std::ostream& Camera::print(std::ostream& os) const { os << "[Camera] " << "position: " << glm::to_string(_position) << "\n" << "direction: " << glm::to_string(_direction) << "\n"; return os; } std::ostream& operator<<(std::ostream& os , Camera const& c) { return c.print(os); }<commit_msg>changed direction vector<commit_after>#include "camera.hpp" //constructors Camera::Camera() : _position{0.0}, _direction{0.0,0.0,-1.0}, _aperture{40.0} {} Camera::Camera(glm::vec3 const& direction, float aperture) : _direction{direction}, _aperture{aperture} {} Camera::Camera(std::string const& name, float aperture) : _name{name}, _direction{0.0,0.0,-1.0}, _aperture{aperture} {} //destructors Camera::~Camera() {} //get-methods std::string const& Camera::name() const { return _name; } glm::vec3 const& Camera::position() const { return _position; } glm::vec3 const& Camera::direction() const { return _direction; } //non-member functions Ray Camera::getEyeRay(int x, int y, float &distance) const { return Ray{glm::vec3{_position}, glm::vec3{x, y, distance}}; } float Camera::getDistance(int width) const { return (width/2)/tan(_aperture/2); } std::ostream& Camera::print(std::ostream& os) const { os << "[Camera] " << "position: " << glm::to_string(_position) << "\n" << "direction: " << glm::to_string(_direction) << "\n"; return os; } std::ostream& operator<<(std::ostream& os , Camera const& c) { return c.print(os); }<|endoftext|>
<commit_before>#include <curl/curl.h> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <iomanip> #include <iostream> #include "accumulator.h" #include "authenticate.h" #include "json/json.h" #include "logging/logging.h" #include "treehub_server.h" namespace po = boost::program_options; using std::string; // helper function to download data to a string static size_t writeString(void *contents, size_t size, size_t nmemb, void *userp) { assert(userp); // append the writeback data to the provided string (static_cast<std::string *>(userp))->append(static_cast<char *>(contents), size * nmemb); // return size of written data return size * nmemb; } class CurlEasyWrapper { public: CurlEasyWrapper() { handler = curl_easy_init(); } ~CurlEasyWrapper() { if (handler != nullptr) { curl_easy_cleanup(handler); } } CURL *get() { return handler; } private: CURL *handler; }; int main(int argc, char **argv) { logger_init(); string ref = "uninitialized"; boost::filesystem::path credentials_path; string home_path = string(getenv("HOME")); string cacerts; int verbosity; po::options_description desc("garage-check command line options"); // clang-format off desc.add_options() ("help", "print usage") ("verbose,v",accumulator<int>(&verbosity), "verbose logging (use twice for more information)") ("quiet,q", "quiet mode") ("ref,r", po::value<string>(&ref)->required(), "refhash to check") ("credentials,j", po::value<boost::filesystem::path>(&credentials_path)->required(), "credentials (json or zip containing json)") ("cacert", po::value<string>(&cacerts), "override path to CA root certificates, in the same format as curl --cacert"); // clang-format on po::variables_map vm; try { po::store(po::parse_command_line(argc, reinterpret_cast<const char *const *>(argv), desc), vm); if (vm.count("help") != 0u) { LOG_INFO << desc; return EXIT_SUCCESS; } po::notify(vm); } catch (const po::error &o) { LOG_INFO << o.what(); LOG_INFO << desc; return EXIT_FAILURE; } // Configure logging if (verbosity == 0) { // 'verbose' trumps 'quiet' if (static_cast<int>(vm.count("quiet")) != 0) { logger_set_threshold(boost::log::trivial::warning); } else { logger_set_threshold(boost::log::trivial::info); } } else if (verbosity == 1) { logger_set_threshold(boost::log::trivial::debug); LOG_DEBUG << "Debug level debugging enabled"; } else if (verbosity > 1) { logger_set_threshold(boost::log::trivial::trace); LOG_TRACE << "Trace level debugging enabled"; } else { assert(0); } TreehubServer treehub; if (cacerts != "") { if (boost::filesystem::exists(cacerts)) { treehub.ca_certs(cacerts); } else { LOG_FATAL << "--cacert path " << cacerts << " does not exist"; return EXIT_FAILURE; } } if (authenticate(cacerts, ServerCredentials(credentials_path), treehub) != EXIT_SUCCESS) { LOG_FATAL << "Authentication failed"; return EXIT_FAILURE; } // check if the ref is present on treehub CurlEasyWrapper curl; if (curl.get() == nullptr) { LOG_FATAL << "Error initializing curl"; return EXIT_FAILURE; } curl_easy_setopt(curl.get(), CURLOPT_VERBOSE, get_curlopt_verbose()); curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 1L); // HEAD treehub.InjectIntoCurl("objects/" + ref.substr(0, 2) + "/" + ref.substr(2) + ".commit", curl.get()); CURLcode result = curl_easy_perform(curl.get()); if (result != CURLE_OK) { LOG_FATAL << "Error connecting to treehub: " << result << ": " << curl_easy_strerror(result); return EXIT_FAILURE; } long http_code; // NOLINT curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code); if (http_code == 404) { LOG_FATAL << "OSTree commit " << ref << " is missing in treehub"; return EXIT_FAILURE; } if (http_code != 200) { LOG_FATAL << "Error " << http_code << " getting commit " << ref << " from treehub"; return EXIT_FAILURE; } LOG_INFO << "OSTree commit " << ref << " is found on treehub"; // check if the ref is present in targets.json curl_easy_setopt(curl.get(), CURLOPT_VERBOSE, get_curlopt_verbose()); curl_easy_setopt(curl.get(), CURLOPT_HTTPGET, 1L); curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 0L); treehub.InjectIntoCurl("/api/v1/user_repo/targets.json", curl.get(), true); std::string targets_str; curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, writeString); curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, (void *)&targets_str); result = curl_easy_perform(curl.get()); if (result != CURLE_OK) { LOG_FATAL << "Error connecting to TUF repo: " << result << ": " << curl_easy_strerror(result); return EXIT_FAILURE; } curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code); if (http_code != 200) { LOG_FATAL << "Error " << http_code << " getting targets.json from TUF repo: " << targets_str; return EXIT_FAILURE; } Json::Value targets_json = Utils::parseJSON(targets_str); Json::Value target_list = targets_json["signed"]["targets"]; for (Json::ValueIterator t_it = target_list.begin(); t_it != target_list.end(); t_it++) { if ((*t_it)["hashes"]["sha256"].asString() == ref) { LOG_INFO << "OSTree package " << ref << " is found in targets.json"; return EXIT_SUCCESS; } } LOG_INFO << "OSTree package " << ref << " was not found in targets.json"; return EXIT_FAILURE; } // vim: set tabstop=2 shiftwidth=2 expandtab: <commit_msg>Check targets expiry date in garage-check<commit_after>#include <curl/curl.h> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <ctime> #include <iomanip> #include <iostream> #include "accumulator.h" #include "authenticate.h" #include "json/json.h" #include "logging/logging.h" #include "treehub_server.h" #include "uptane/tuf.h" namespace po = boost::program_options; using std::string; // helper function to download data to a string static size_t writeString(void *contents, size_t size, size_t nmemb, void *userp) { assert(userp); // append the writeback data to the provided string (static_cast<std::string *>(userp))->append(static_cast<char *>(contents), size * nmemb); // return size of written data return size * nmemb; } class CurlEasyWrapper { public: CurlEasyWrapper() { handler = curl_easy_init(); } ~CurlEasyWrapper() { if (handler != nullptr) { curl_easy_cleanup(handler); } } CURL *get() { return handler; } private: CURL *handler; }; int main(int argc, char **argv) { logger_init(); string ref = "uninitialized"; boost::filesystem::path credentials_path; string home_path = string(getenv("HOME")); string cacerts; int verbosity; po::options_description desc("garage-check command line options"); // clang-format off desc.add_options() ("help", "print usage") ("verbose,v",accumulator<int>(&verbosity), "verbose logging (use twice for more information)") ("quiet,q", "quiet mode") ("ref,r", po::value<string>(&ref)->required(), "refhash to check") ("credentials,j", po::value<boost::filesystem::path>(&credentials_path)->required(), "credentials (json or zip containing json)") ("cacert", po::value<string>(&cacerts), "override path to CA root certificates, in the same format as curl --cacert"); // clang-format on po::variables_map vm; try { po::store(po::parse_command_line(argc, reinterpret_cast<const char *const *>(argv), desc), vm); if (vm.count("help") != 0u) { LOG_INFO << desc; return EXIT_SUCCESS; } po::notify(vm); } catch (const po::error &o) { LOG_INFO << o.what(); LOG_INFO << desc; return EXIT_FAILURE; } // Configure logging if (verbosity == 0) { // 'verbose' trumps 'quiet' if (static_cast<int>(vm.count("quiet")) != 0) { logger_set_threshold(boost::log::trivial::warning); } else { logger_set_threshold(boost::log::trivial::info); } } else if (verbosity == 1) { logger_set_threshold(boost::log::trivial::debug); LOG_DEBUG << "Debug level debugging enabled"; } else if (verbosity > 1) { logger_set_threshold(boost::log::trivial::trace); LOG_TRACE << "Trace level debugging enabled"; } else { assert(0); } TreehubServer treehub; if (cacerts != "") { if (boost::filesystem::exists(cacerts)) { treehub.ca_certs(cacerts); } else { LOG_FATAL << "--cacert path " << cacerts << " does not exist"; return EXIT_FAILURE; } } if (authenticate(cacerts, ServerCredentials(credentials_path), treehub) != EXIT_SUCCESS) { LOG_FATAL << "Authentication failed"; return EXIT_FAILURE; } // check if the ref is present on treehub CurlEasyWrapper curl; if (curl.get() == nullptr) { LOG_FATAL << "Error initializing curl"; return EXIT_FAILURE; } curl_easy_setopt(curl.get(), CURLOPT_VERBOSE, get_curlopt_verbose()); curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 1L); // HEAD treehub.InjectIntoCurl("objects/" + ref.substr(0, 2) + "/" + ref.substr(2) + ".commit", curl.get()); CURLcode result = curl_easy_perform(curl.get()); if (result != CURLE_OK) { LOG_FATAL << "Error connecting to treehub: " << result << ": " << curl_easy_strerror(result); return EXIT_FAILURE; } long http_code; // NOLINT curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code); if (http_code == 404) { LOG_FATAL << "OSTree commit " << ref << " is missing in treehub"; return EXIT_FAILURE; } if (http_code != 200) { LOG_FATAL << "Error " << http_code << " getting commit " << ref << " from treehub"; return EXIT_FAILURE; } LOG_INFO << "OSTree commit " << ref << " is found on treehub"; // check if the ref is present in targets.json curl_easy_setopt(curl.get(), CURLOPT_VERBOSE, get_curlopt_verbose()); curl_easy_setopt(curl.get(), CURLOPT_HTTPGET, 1L); curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 0L); treehub.InjectIntoCurl("/api/v1/user_repo/targets.json", curl.get(), true); std::string targets_str; curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, writeString); curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, (void *)&targets_str); result = curl_easy_perform(curl.get()); if (result != CURLE_OK) { LOG_FATAL << "Error connecting to TUF repo: " << result << ": " << curl_easy_strerror(result); return EXIT_FAILURE; } curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code); if (http_code != 200) { LOG_FATAL << "Error " << http_code << " getting targets.json from TUF repo: " << targets_str; return EXIT_FAILURE; } Json::Value targets_json = Utils::parseJSON(targets_str); std::string expiry_time_str = targets_json["signed"]["expires"].asString(); Uptane::TimeStamp timestamp(expiry_time_str); if (timestamp.IsExpiredAt(Uptane::TimeStamp::Now())) { LOG_FATAL << "targets.json has been expired."; return EXIT_FAILURE; } Json::Value target_list = targets_json["signed"]["targets"]; for (Json::ValueIterator t_it = target_list.begin(); t_it != target_list.end(); t_it++) { if ((*t_it)["hashes"]["sha256"].asString() == ref) { LOG_INFO << "OSTree package " << ref << " is found in targets.json"; return EXIT_SUCCESS; } } LOG_INFO << "OSTree package " << ref << " was not found in targets.json"; return EXIT_FAILURE; } // vim: set tabstop=2 shiftwidth=2 expandtab: <|endoftext|>
<commit_before>#ifndef scoped_H__ #define scoped_H__ namespace testbed { //////////////////////////////////////////////////////////////////////////////////////////////////// // scoped_ptr and scoped_linkage_ptr provide end-of-scope actions on arbitrary and external linkage // pointers, respectively. In addition, scoped_ptr is resettable, while scoped_linkage_ptr comes at // zero memory overhead. //////////////////////////////////////////////////////////////////////////////////////////////////// class non_copyable { non_copyable(const non_copyable&) {} non_copyable& operator =(const non_copyable&) { return *this; } public: non_copyable() {} }; template < typename T, template< typename F > class FTOR_T, T* PTR_T > class scoped_linkage_ptr : non_copyable, FTOR_T< T > { public: scoped_linkage_ptr() {} ~scoped_linkage_ptr() { FTOR_T< T >::operator()(PTR_T); } }; template < typename T, template< typename F > class FTOR_T > class scoped_ptr : non_copyable, FTOR_T< T > { T* m; public: scoped_ptr() : m(0) {} explicit scoped_ptr(T* arg) : m(arg) {} ~scoped_ptr() { if (0 != m) FTOR_T< T >::operator()(m); } void reset() { m = 0; } void swap(scoped_ptr& oth) { T* const t = m; m = oth.m; oth.m = t; } T* operator ()() const { return m; } }; template < typename T > class scoped_functor { public: void operator()(T*); }; typedef bool (deinit_resources_t)(); template <> class scoped_functor< deinit_resources_t > { public: void operator()(deinit_resources_t* arg) { arg(); } }; template < typename T > class generic_delete { public: void operator()(T* arg) { delete arg; } }; template < typename T > class generic_delete_arr { public: void operator()(T* arg) { delete [] arg; } }; } // namespace testbed #endif // scoped_H__ <commit_msg>update scoped in common to the latest version<commit_after>#ifndef scoped_H__ #define scoped_H__ namespace testbed { //////////////////////////////////////////////////////////////////////////////////////////////////// // scoped_ptr and scoped_linkage_ptr provide end-of-scope actions on arbitrary and external linkage // pointers, respectively. In addition, scoped_ptr is resettable, while scoped_linkage_ptr comes at // zero memory overhead. //////////////////////////////////////////////////////////////////////////////////////////////////// class non_copyable { non_copyable(const non_copyable&) {} non_copyable& operator =(const non_copyable&) { return *this; } public: non_copyable() {} }; template < typename T, template< typename F > class FTOR_T, T* PTR_T > class scoped_linkage_ptr : non_copyable, FTOR_T< T > { public: ~scoped_linkage_ptr() { FTOR_T< T >::operator()(PTR_T); } }; template < typename T, template< typename F > class FTOR_T > class scoped_ptr : non_copyable, FTOR_T< T > { T* m; public: scoped_ptr() : m(0) {} explicit scoped_ptr(T* arg) : m(arg) {} ~scoped_ptr() { if (0 != m) FTOR_T< T >::operator()(m); } void reset() { m = 0; } void swap(scoped_ptr& oth) { m = __atomic_exchange_n(&oth.m, m, __ATOMIC_RELAXED); } T* operator ()() const { return m; } }; template < typename T > class scoped_functor { public: void operator()(T*); }; typedef bool (deinit_resources_t)(); template <> class scoped_functor< deinit_resources_t > { public: void operator()(deinit_resources_t* arg) { arg(); } }; template < typename T > class generic_delete { public: void operator()(T* arg) { delete arg; } }; template < typename T > class generic_delete_arr { public: void operator()(T* arg) { delete [] arg; } }; } // namespace testbed #endif // scoped_H__ <|endoftext|>
<commit_before>/* This file is part of Strigi Desktop Search * * Copyright (C) 2007 Jos van den Oever <jos@vandenoever.info> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "variant.h" using namespace std; using namespace Strigi; class Strigi::VariantPrivate { public: int32_t i_value; uint32_t u_value; string s_value; vector<string> as_value; vector<vector<string> > aas_value; Variant::Type vartype; bool valid; VariantPrivate() :i_value(0), u_value(0), vartype(Variant::b_val), valid(false) {} VariantPrivate(const Variant& v) { *this = v; } void operator=(const VariantPrivate& v); bool b() const; int32_t i() const; uint32_t u() const; string s() const; vector<string> as() const; vector<vector<string> > aas() const; static string itos(int32_t i); }; Variant::Variant() :p(new VariantPrivate()) {} Variant::Variant(bool v) :p(new VariantPrivate()) { *this=v; } Variant::Variant(int32_t v) :p(new VariantPrivate()) { *this=v; } Variant::Variant(uint32_t v) :p(new VariantPrivate()) { *this=v; } Variant::Variant(const char* v) :p(new VariantPrivate()) { *this=v; } Variant::Variant(const string& v) :p(new VariantPrivate()) { *this=v; } Variant::Variant(const vector<string>& v) :p(new VariantPrivate()) { *this=v; } Variant::Variant(const vector<vector<string> >& v) :p(new VariantPrivate()) { *this=v; } Variant::Variant(const Variant& v) :p(new VariantPrivate(*v.p)) { } Variant::~Variant() { delete p; } Variant::Type Variant::type() const { return p->vartype; } const Variant& Variant::operator=(bool v) { p->valid = true; p->i_value = v; p->vartype = b_val; return *this; } const Variant& Variant::operator=(int32_t v) { p->valid=true; p->i_value = v; p->u_value = v; p->vartype = i_val; return *this; } const Variant& Variant::operator=(uint32_t v) { p->valid=true; p->i_value = v; p->u_value = v; p->vartype = u_val; return *this; } const Variant& Variant::operator=(const char* v) { p->valid=true; p->s_value.assign(v); p->vartype = s_val; return *this; } const Variant& Variant::operator=(const string& v) { p->valid=true; p->s_value.assign(v); p->vartype = s_val; return *this; } const Variant& Variant::operator=(const vector<string>& v) { p->valid=true; p->as_value = v; p->vartype = as_val; return *this; } const Variant& Variant::operator=(const vector<vector<string> >& v) { p->valid=true; p->aas_value = v; p->vartype = aas_val; return *this; } const Variant& Variant::operator=(const Variant& v) { *p = *v.p; return v; } void VariantPrivate::operator=(const VariantPrivate& v) { i_value = v.i_value; s_value = v.s_value; as_value = v.as_value; vartype = v.vartype; valid = v.valid; } bool Variant::b() const { return p->b(); } bool VariantPrivate::b() const { switch (vartype) { case Variant::b_val: case Variant::i_val: return i_value; case Variant::s_val: return s_value == "1" || s_value == "true" || s_value == "True" || s_value == "TRUE"; case Variant::as_val: return as_value.size(); default: return false; } } int32_t Variant::i() const { return p->i(); } int32_t VariantPrivate::i() const { switch (vartype) { case Variant::b_val: case Variant::i_val: return i_value; case Variant::s_val: return atoi(s_value.c_str()); case Variant::as_val: return as_value.size(); default: return -1; } } uint32_t Variant::u() const { return p->u(); } uint32_t VariantPrivate::u() const { switch (vartype) { case Variant::b_val: case Variant::i_val: case Variant::u_val: return u_value; case Variant::s_val: return atoi(s_value.c_str()); case Variant::as_val: return as_value.size(); default: return -1; } } string VariantPrivate::itos(int32_t i) { ostringstream o; o << i; return o.str(); } string Variant::s() const { return p->s(); } string VariantPrivate::s() const { switch (vartype) { case Variant::b_val: return i_value ?"true" :"false"; case Variant::i_val: return itos(i_value); case Variant::s_val: return s_value; case Variant::as_val: return as_value.size() ?as_value[0] :""; default: return ""; } } vector<string> Variant::as() const { return p->as(); } vector<string> VariantPrivate::as() const { if (vartype == Variant::as_val) { return as_value; } vector<string> v; if (b()) { v.push_back(s()); } return v; } vector<vector<string> > Variant::aas() const { return p->aas(); } vector<vector<string> > VariantPrivate::aas() const { if (vartype == Variant::aas_val) { return aas_value; } vector<vector<string> > v; if (b()) { v.push_back(as()); } return v; } bool Variant::isValid() const { return p->valid; } <commit_msg>warning--<commit_after>/* This file is part of Strigi Desktop Search * * Copyright (C) 2007 Jos van den Oever <jos@vandenoever.info> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "variant.h" using namespace std; using namespace Strigi; class Strigi::VariantPrivate { public: int32_t i_value; uint32_t u_value; string s_value; vector<string> as_value; vector<vector<string> > aas_value; Variant::Type vartype; bool valid; VariantPrivate() :i_value(0), u_value(0), vartype(Variant::b_val), valid(false) {} VariantPrivate(const Variant& v) { *this = v; } void operator=(const VariantPrivate& v); bool b() const; int32_t i() const; uint32_t u() const; string s() const; vector<string> as() const; vector<vector<string> > aas() const; static string itos(int32_t i); }; Variant::Variant() :p(new VariantPrivate()) {} Variant::Variant(bool v) :p(new VariantPrivate()) { *this=v; } Variant::Variant(int32_t v) :p(new VariantPrivate()) { *this=v; } Variant::Variant(uint32_t v) :p(new VariantPrivate()) { *this=v; } Variant::Variant(const char* v) :p(new VariantPrivate()) { *this=v; } Variant::Variant(const string& v) :p(new VariantPrivate()) { *this=v; } Variant::Variant(const vector<string>& v) :p(new VariantPrivate()) { *this=v; } Variant::Variant(const vector<vector<string> >& v) :p(new VariantPrivate()) { *this=v; } Variant::Variant(const Variant& v) :p(new VariantPrivate(*v.p)) { } Variant::~Variant() { delete p; } Variant::Type Variant::type() const { return p->vartype; } const Variant& Variant::operator=(bool v) { p->valid = true; p->i_value = v; p->vartype = b_val; return *this; } const Variant& Variant::operator=(int32_t v) { p->valid=true; p->i_value = v; p->u_value = v; p->vartype = i_val; return *this; } const Variant& Variant::operator=(uint32_t v) { p->valid=true; p->i_value = v; p->u_value = v; p->vartype = u_val; return *this; } const Variant& Variant::operator=(const char* v) { p->valid=true; p->s_value.assign(v); p->vartype = s_val; return *this; } const Variant& Variant::operator=(const string& v) { p->valid=true; p->s_value.assign(v); p->vartype = s_val; return *this; } const Variant& Variant::operator=(const vector<string>& v) { p->valid=true; p->as_value = v; p->vartype = as_val; return *this; } const Variant& Variant::operator=(const vector<vector<string> >& v) { p->valid=true; p->aas_value = v; p->vartype = aas_val; return *this; } const Variant& Variant::operator=(const Variant& v) { *p = *v.p; return v; } void VariantPrivate::operator=(const VariantPrivate& v) { i_value = v.i_value; s_value = v.s_value; as_value = v.as_value; vartype = v.vartype; valid = v.valid; } bool Variant::b() const { return p->b(); } bool VariantPrivate::b() const { switch (vartype) { case Variant::b_val: case Variant::i_val: return i_value; case Variant::s_val: return s_value == "1" || s_value == "true" || s_value == "True" || s_value == "TRUE"; case Variant::as_val: return as_value.size(); default: return false; } } int32_t Variant::i() const { return p->i(); } int32_t VariantPrivate::i() const { switch (vartype) { case Variant::b_val: case Variant::i_val: return i_value; case Variant::s_val: return atoi(s_value.c_str()); case Variant::as_val: return as_value.size(); default: return -1; } } uint32_t Variant::u() const { return p->u(); } uint32_t VariantPrivate::u() const { switch (vartype) { case Variant::b_val: case Variant::i_val: case Variant::u_val: return u_value; case Variant::s_val: return atoi(s_value.c_str()); case Variant::as_val: return as_value.size(); default: return ~0U; } } string VariantPrivate::itos(int32_t i) { ostringstream o; o << i; return o.str(); } string Variant::s() const { return p->s(); } string VariantPrivate::s() const { switch (vartype) { case Variant::b_val: return i_value ?"true" :"false"; case Variant::i_val: return itos(i_value); case Variant::s_val: return s_value; case Variant::as_val: return as_value.size() ?as_value[0] :""; default: return ""; } } vector<string> Variant::as() const { return p->as(); } vector<string> VariantPrivate::as() const { if (vartype == Variant::as_val) { return as_value; } vector<string> v; if (b()) { v.push_back(s()); } return v; } vector<vector<string> > Variant::aas() const { return p->aas(); } vector<vector<string> > VariantPrivate::aas() const { if (vartype == Variant::aas_val) { return aas_value; } vector<vector<string> > v; if (b()) { v.push_back(as()); } return v; } bool Variant::isValid() const { return p->valid; } <|endoftext|>
<commit_before>/* * Copyright (c) 1998-2004, Index Data. * See the file LICENSE for details. * * $Id: yaz-cql2rpn.cpp,v 1.11 2007-01-12 10:09:25 adam Exp $ */ #include <yaz/log.h> #include <yaz/pquery.h> #include <yazpp/cql2rpn.h> using namespace yazpp_1; Yaz_cql2rpn::Yaz_cql2rpn() { m_transform = 0; } Yaz_cql2rpn::~Yaz_cql2rpn() { if (m_transform) cql_transform_close(m_transform); } void Yaz_cql2rpn::set_pqf_file(const char *fname) { if (!m_transform) m_transform = cql_transform_open_fname(fname); } bool Yaz_cql2rpn::parse_spec_file(const char *fname, int *error) { *error = 0; cql_transform_close(m_transform); m_transform = cql_transform_open_fname(fname); return m_transform ? true : false; } int Yaz_cql2rpn::query_transform(const char *cql_query, Z_RPNQuery **rpnquery, ODR o, char **addinfop) { const char *addinfo = 0; if (!m_transform) return -3; CQL_parser cp = cql_parser_create(); int r = cql_parser_string(cp, cql_query); if (r) { yaz_log(YLOG_LOG, "CQL Parse Error"); r = 10; } else { char rpn_buf[10240]; r = cql_transform_buf(m_transform, cql_parser_result(cp), rpn_buf, sizeof(rpn_buf)-1); if (!r) { YAZ_PQF_Parser pp = yaz_pqf_create(); *rpnquery = yaz_pqf_parse(pp, o, rpn_buf); if (!*rpnquery) { size_t off; const char *pqf_msg; int code = yaz_pqf_error(pp, &pqf_msg, &off); yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)", pqf_msg, code); r = -1; } yaz_pqf_destroy(pp); } else { r = cql_transform_error(m_transform, &addinfo); yaz_log(YLOG_LOG, "CQL Transform Error %d %s", r, addinfo ? addinfo : ""); } } cql_parser_destroy(cp); if (addinfo) *addinfop = odr_strdup(o, addinfo); else *addinfop = 0; return r; } /* * Local variables: * c-basic-offset: 4 * indent-tabs-mode: nil * End: * vim: shiftwidth=4 tabstop=8 expandtab */ <commit_msg>Omit YLOG_LOG msg<commit_after>/* * Copyright (c) 1998-2004, Index Data. * See the file LICENSE for details. * * $Id: yaz-cql2rpn.cpp,v 1.12 2007-01-12 10:15:06 adam Exp $ */ #include <yaz/log.h> #include <yaz/pquery.h> #include <yazpp/cql2rpn.h> using namespace yazpp_1; Yaz_cql2rpn::Yaz_cql2rpn() { m_transform = 0; } Yaz_cql2rpn::~Yaz_cql2rpn() { if (m_transform) cql_transform_close(m_transform); } void Yaz_cql2rpn::set_pqf_file(const char *fname) { if (!m_transform) m_transform = cql_transform_open_fname(fname); } bool Yaz_cql2rpn::parse_spec_file(const char *fname, int *error) { *error = 0; cql_transform_close(m_transform); m_transform = cql_transform_open_fname(fname); return m_transform ? true : false; } int Yaz_cql2rpn::query_transform(const char *cql_query, Z_RPNQuery **rpnquery, ODR o, char **addinfop) { const char *addinfo = 0; if (!m_transform) return -3; CQL_parser cp = cql_parser_create(); int r = cql_parser_string(cp, cql_query); if (r) { r = 10; } else { char rpn_buf[10240]; r = cql_transform_buf(m_transform, cql_parser_result(cp), rpn_buf, sizeof(rpn_buf)-1); if (!r) { YAZ_PQF_Parser pp = yaz_pqf_create(); *rpnquery = yaz_pqf_parse(pp, o, rpn_buf); if (!*rpnquery) { size_t off; const char *pqf_msg; int code = yaz_pqf_error(pp, &pqf_msg, &off); yaz_log(YLOG_WARN, "PQF Parser Error %s (code %d)", pqf_msg, code); r = -1; } yaz_pqf_destroy(pp); } else { r = cql_transform_error(m_transform, &addinfo); yaz_log(YLOG_LOG, "CQL Transform Error %d %s", r, addinfo ? addinfo : ""); } } cql_parser_destroy(cp); if (addinfo) *addinfop = odr_strdup(o, addinfo); else *addinfop = 0; return r; } /* * Local variables: * c-basic-offset: 4 * indent-tabs-mode: nil * End: * vim: shiftwidth=4 tabstop=8 expandtab */ <|endoftext|>
<commit_before>/* * Copyright (C) 2008 Nokia Corporation. * * Contact: Marius Vollmer <marius.vollmer@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include "contexttyperegistryinfo.h" #include "logging.h" #include "loggingfeatures.h" #include <QMutex> #include <QMutexLocker> #include <QCoreApplication> #include "nanoxml.h" ContextTypeRegistryInfo* ContextTypeRegistryInfo::registryInstance = NULL; /* Public */ /// Returns the singleton instance of the ContextTypeRegistryInfo. The object /// is constructed automaticall on first access. ContextTypeRegistryInfo* ContextTypeRegistryInfo::instance() { static QMutex mutex; QMutexLocker locker(&mutex); if (! registryInstance) { contextDebug() << F_TYPES << "Creating ContextTypeRegistryInfo instance"; registryInstance = new ContextTypeRegistryInfo; // Move the backend to the main thread registryInstance->moveToThread(QCoreApplication::instance()->thread()); } return registryInstance; } /// Returns the full path to the registry directory. Takes the /// \c CONTEXT_TYPES env variable into account. QString ContextTypeRegistryInfo::registryPath() { const char *regpath = getenv("CONTEXT_TYPES"); if (! regpath) regpath = DEFAULT_CONTEXT_TYPES; return QString(regpath); } /// Returns the full path to the core property declaration file. Takes /// the \c CONTEXT_CORE_TYPES env variable into account. QString ContextTypeRegistryInfo::coreTypesPath() { const char *corepath = getenv("CONTEXT_CORE_TYPES"); if (! corepath) corepath = DEFAULT_CONTEXT_CORE_TYPES; return QString(corepath); } /// Returns a type definition for the type with the given name. The type /// is being fetched from the registry. NanoTree ContextTypeRegistryInfo::typeDefinitionForName(QString name) { // Support for the old types if (name == "TRUTH") return boolType(); else if (name == "STRING") return stringType(); else if (name == "INT") return int32Type(); else if (name == "INTEGER") return int32Type(); else if (name == "DOUBLE") return doubleType(); // Try using the cache first if (typeCache.contains(name)) return typeCache.value(name); // No type in cache? Find it in the nano tree and put in cache. foreach (NanoTree typeTree, coreTree.keyValues("type")) { if (typeTree.keyValue("name") == name) { typeCache.insert(name, typeTree); return typeTree; } } // Not found. Return blank null type. return NanoTree(); } /// Returns in instance of the int64 type definition. NanoTree ContextTypeRegistryInfo::int64Type() { return typeDefinitionForName("int64"); } /// Returns in instance of the string type definition. NanoTree ContextTypeRegistryInfo::stringType() { return typeDefinitionForName("string"); } /// Returns in instance of the double type definition. NanoTree ContextTypeRegistryInfo::doubleType() { return typeDefinitionForName("double"); } /// Returns in instance of the bool type definition. NanoTree ContextTypeRegistryInfo::boolType() { return typeDefinitionForName("bool"); } /// Returns in instance of the int32 type definition. NanoTree ContextTypeRegistryInfo::int32Type() { return typeDefinitionForName("int32"); } /* Private */ /// Private constructor. Do not use. ContextTypeRegistryInfo::ContextTypeRegistryInfo() { if (QFile(ContextTypeRegistryInfo::coreTypesPath()).exists()) { contextDebug() << F_TYPES << "Reading core types from:" << ContextTypeRegistryInfo::coreTypesPath(); NanoXml parser(ContextTypeRegistryInfo::coreTypesPath()); if (parser.didFail()) contextWarning() << F_TYPES << "Reading core types from" << ContextTypeRegistryInfo::coreTypesPath() << "failed, parsing error"; else coreTree = parser.result(); } else contextDebug() << F_TYPES << "Core types at" << ContextTypeRegistryInfo::coreTypesPath() << "missing."; } <commit_msg>Overview documentation for contexttyperegistryinfo.<commit_after>/* * Copyright (C) 2008 Nokia Corporation. * * Contact: Marius Vollmer <marius.vollmer@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include "contexttyperegistryinfo.h" #include "logging.h" #include "loggingfeatures.h" #include <QMutex> #include <QMutexLocker> #include <QCoreApplication> #include "nanoxml.h" /*! \class ContextTypeRegistryInfo \brief A class to access the type registry. This is a singelton class used to obtain information about the core types defined in the type registry. Information is provided as type definitions returned as NanoTree instances. Each type definition is a QVariant tree wrapped in NanoTree for easy helper key accessors. \section Usage To obtain a type definition for a given type: \code NanoTree typeDefinition = ContextTypeRegistryInfo::instance()->typeDefinitionForName("string-enum"); \endcode Unless you're building a dedicated type-introspection application, you don't want to deal with ContextTypeRegistryInfo directly. Instead, you can use the ContextTypeInfo class to fetch concrete types and use the easy accessors provided there. */ ContextTypeRegistryInfo* ContextTypeRegistryInfo::registryInstance = NULL; /* Public */ /// Returns the singleton instance of the ContextTypeRegistryInfo. The object /// is constructed automaticall on first access. ContextTypeRegistryInfo* ContextTypeRegistryInfo::instance() { static QMutex mutex; QMutexLocker locker(&mutex); if (! registryInstance) { contextDebug() << F_TYPES << "Creating ContextTypeRegistryInfo instance"; registryInstance = new ContextTypeRegistryInfo; // Move the backend to the main thread registryInstance->moveToThread(QCoreApplication::instance()->thread()); } return registryInstance; } /// Returns the full path to the registry directory. Takes the /// \c CONTEXT_TYPES env variable into account. QString ContextTypeRegistryInfo::registryPath() { const char *regpath = getenv("CONTEXT_TYPES"); if (! regpath) regpath = DEFAULT_CONTEXT_TYPES; return QString(regpath); } /// Returns the full path to the core property declaration file. Takes /// the \c CONTEXT_CORE_TYPES env variable into account. QString ContextTypeRegistryInfo::coreTypesPath() { const char *corepath = getenv("CONTEXT_CORE_TYPES"); if (! corepath) corepath = DEFAULT_CONTEXT_CORE_TYPES; return QString(corepath); } /// Returns a type definition for the type with the given name. The type /// is being fetched from the registry. NanoTree ContextTypeRegistryInfo::typeDefinitionForName(QString name) { // Support for the old types if (name == "TRUTH") return boolType(); else if (name == "STRING") return stringType(); else if (name == "INT") return int32Type(); else if (name == "INTEGER") return int32Type(); else if (name == "DOUBLE") return doubleType(); // Try using the cache first if (typeCache.contains(name)) return typeCache.value(name); // No type in cache? Find it in the nano tree and put in cache. foreach (NanoTree typeTree, coreTree.keyValues("type")) { if (typeTree.keyValue("name") == name) { typeCache.insert(name, typeTree); return typeTree; } } // Not found. Return blank null type. return NanoTree(); } /// Returns in instance of the int64 type definition. NanoTree ContextTypeRegistryInfo::int64Type() { return typeDefinitionForName("int64"); } /// Returns in instance of the string type definition. NanoTree ContextTypeRegistryInfo::stringType() { return typeDefinitionForName("string"); } /// Returns in instance of the double type definition. NanoTree ContextTypeRegistryInfo::doubleType() { return typeDefinitionForName("double"); } /// Returns in instance of the bool type definition. NanoTree ContextTypeRegistryInfo::boolType() { return typeDefinitionForName("bool"); } /// Returns in instance of the int32 type definition. NanoTree ContextTypeRegistryInfo::int32Type() { return typeDefinitionForName("int32"); } /* Private */ /// Private constructor. Do not use. ContextTypeRegistryInfo::ContextTypeRegistryInfo() { if (QFile(ContextTypeRegistryInfo::coreTypesPath()).exists()) { contextDebug() << F_TYPES << "Reading core types from:" << ContextTypeRegistryInfo::coreTypesPath(); NanoXml parser(ContextTypeRegistryInfo::coreTypesPath()); if (parser.didFail()) contextWarning() << F_TYPES << "Reading core types from" << ContextTypeRegistryInfo::coreTypesPath() << "failed, parsing error"; else coreTree = parser.result(); } else contextDebug() << F_TYPES << "Core types at" << ContextTypeRegistryInfo::coreTypesPath() << "missing."; } <|endoftext|>
<commit_before>// This file is part of SWGANH which is released under the MIT license. // See file LICENSE or go to http://swganh.com/LICENSE #include "event_dispatcher.h" #include <algorithm> #ifdef WIN32 #include <chrono> using namespace std::chrono; #else #include <boost/chrono.hpp> using namespace boost::chrono; #endif #include <boost/asio/io_service.hpp> using namespace swganh; using namespace std; namespace ba = boost::asio; BaseEvent::BaseEvent(EventType type) : type_(type) {} EventType BaseEvent::Type() const { return type_; } EventDispatcher::EventDispatcher(ba::io_service& io_service) : io_service_(io_service) {} EventDispatcher::~EventDispatcher() { Shutdown(); } CallbackId EventDispatcher::Subscribe(EventType type, EventHandlerCallback callback) { auto handler_id = GenerateCallbackId(); boost::upgrade_lock<boost::shared_mutex> lg(event_handlers_mutex_); auto find_iter = event_handlers_.find(type); if (find_iter == end(event_handlers_)) { find_iter = event_handlers_.insert(make_pair(type, EventHandlerList())).first; } find_iter->second.insert(std::make_pair(handler_id, move(callback))); return handler_id; } void EventDispatcher::Unsubscribe(EventType type, CallbackId identifier) { boost::upgrade_lock<boost::shared_mutex> lg(event_handlers_mutex_); auto event_type_iter = event_handlers_.find(type); if (event_type_iter != end(event_handlers_)) { auto type_handlers = event_type_iter->second; type_handlers.erase(identifier); type_handlers.clear(); } } boost::unique_future<shared_ptr<EventInterface>> EventDispatcher::Dispatch(const shared_ptr<EventInterface>& dispatch_event) { auto task = make_shared<boost::packaged_task<shared_ptr<EventInterface>>>( [this, dispatch_event] () -> shared_ptr<EventInterface> { InvokeCallbacks(dispatch_event); return dispatch_event; }); io_service_.post([task] () { (*task)(); }); return task->get_future(); } CallbackId EventDispatcher::GenerateCallbackId() { return CallbackId(steady_clock::now().time_since_epoch().count()); } void EventDispatcher::InvokeCallbacks(const shared_ptr<EventInterface>& dispatch_event) { boost::shared_lock<boost::shared_mutex> lg(event_handlers_mutex_); auto event_type_iter = event_handlers_.find(dispatch_event->Type()); if (event_type_iter != end(event_handlers_)) { for_each( begin(event_type_iter->second), end(event_type_iter->second), [&dispatch_event] (const EventHandlerList::value_type& handler) { handler.second(dispatch_event); }); } } void EventDispatcher::Shutdown() { boost::lock_guard<boost::shared_mutex> lg(event_handlers_mutex_); for (auto& item : event_handlers_) { item.second.clear(); } event_handlers_.clear(); }<commit_msg>Handlers are now wrapped in a try-catch<commit_after>// This file is part of SWGANH which is released under the MIT license. // See file LICENSE or go to http://swganh.com/LICENSE #include "event_dispatcher.h" #include "logger.h" #include <algorithm> #ifdef WIN32 #include <chrono> using namespace std::chrono; #else #include <boost/chrono.hpp> using namespace boost::chrono; #endif #include <boost/asio/io_service.hpp> using namespace swganh; using namespace std; namespace ba = boost::asio; BaseEvent::BaseEvent(EventType type) : type_(type) {} EventType BaseEvent::Type() const { return type_; } EventDispatcher::EventDispatcher(ba::io_service& io_service) : io_service_(io_service) {} EventDispatcher::~EventDispatcher() { Shutdown(); } CallbackId EventDispatcher::Subscribe(EventType type, EventHandlerCallback callback) { auto handler_id = GenerateCallbackId(); boost::upgrade_lock<boost::shared_mutex> lg(event_handlers_mutex_); auto find_iter = event_handlers_.find(type); if (find_iter == end(event_handlers_)) { find_iter = event_handlers_.insert(make_pair(type, EventHandlerList())).first; } find_iter->second.insert(std::make_pair(handler_id, move(callback))); return handler_id; } void EventDispatcher::Unsubscribe(EventType type, CallbackId identifier) { boost::upgrade_lock<boost::shared_mutex> lg(event_handlers_mutex_); auto event_type_iter = event_handlers_.find(type); if (event_type_iter != end(event_handlers_)) { auto type_handlers = event_type_iter->second; type_handlers.erase(identifier); type_handlers.clear(); } } boost::unique_future<shared_ptr<EventInterface>> EventDispatcher::Dispatch(const shared_ptr<EventInterface>& dispatch_event) { auto task = make_shared<boost::packaged_task<shared_ptr<EventInterface>>>( [this, dispatch_event] () -> shared_ptr<EventInterface> { InvokeCallbacks(dispatch_event); return dispatch_event; }); io_service_.post([task] () { (*task)(); }); return task->get_future(); } CallbackId EventDispatcher::GenerateCallbackId() { return CallbackId(steady_clock::now().time_since_epoch().count()); } void EventDispatcher::InvokeCallbacks(const shared_ptr<EventInterface>& dispatch_event) { boost::shared_lock<boost::shared_mutex> lg(event_handlers_mutex_); auto event_type_iter = event_handlers_.find(dispatch_event->Type()); if (event_type_iter != end(event_handlers_)) { for_each( begin(event_type_iter->second), end(event_type_iter->second), [&dispatch_event] (const EventHandlerList::value_type& handler) { try { handler.second(dispatch_event); } catch(...) { DLOG(warning) << "A handler callback caused an exception."; } }); } } void EventDispatcher::Shutdown() { boost::lock_guard<boost::shared_mutex> lg(event_handlers_mutex_); for (auto& item : event_handlers_) { item.second.clear(); } event_handlers_.clear(); } <|endoftext|>
<commit_before>/* * UIRenderSystem.cpp * * Created on: 14 Sep 2014 * Author: Ashley Davis (SgtCoDFish) */ #include <string> #include <algorithm> #include <bitset> #include "SDL2/SDL.h" #include "Ashley/AshleyCore.hpp" #include "StinkingRich.hpp" #include "StinkingRichConstants.hpp" #include "components/YesNoQuery.hpp" #include "components/MouseListener.hpp" #include "systems/UIRenderSystem.hpp" using namespace stinkingRich; stinkingRich::UIRenderSystem::UIRenderSystem(int priority) : UIRenderSystem(nullptr, priority) { } stinkingRich::UIRenderSystem::UIRenderSystem(SDL_Renderer *renderer, int priority) : ashley::IteratingSystem( ashley::Family::getFor( ashley::BitsType(ashley::ComponentType::getBitsFor<YesNoQuery>()), ashley::BitsType(), ashley::BitsType()), priority), renderer(renderer) { const int boxW = static_cast<int>(constants::boardWidth * 0.75); const int boxWDiff = (constants::boardWidth - boxW) / 2; const int boxH = static_cast<int>(constants::boardHeight * 0.75); const int boxHDiff = (constants::boardHeight - boxH) / 2; const SDL_Rect mainBox = { StinkingRich::leftGap + boxWDiff, StinkingRich::topGap + boxHDiff, boxW, boxH }; boxes.push_back(mainBox); constexpr int optionW = 100; const int optionY = static_cast<int>(mainBox.h * 0.75) + mainBox.y; const int gapW = (boxW - (2 * optionW)) / 3; const SDL_Rect yesBox = { mainBox.x + gapW, optionY, optionW, 50 }; const SDL_Rect noBox = { mainBox.x + gapW * 2 + optionW, optionY, optionW, 50 }; boxes.push_back(yesBox); boxes.push_back(noBox); const auto textRenderer = stinkingRich::StinkingRich::getTextRenderer(); textRenderer->setColor({0x00, 0x00, 0x00, 0xFF}); yesTexture = textRenderer->renderToTexture(renderer, 0, 0, yesBox.w, yesBox.h, "Yes", yesBox.w); noTexture = textRenderer->renderToTexture(renderer, 0, 0, noBox.w, noBox.h, "No", noBox.w); constexpr int queryOffsetX = 10; constexpr int queryOffsetY = 10; const int queryBoxW = mainBox.w - (2 * queryOffsetX); const int queryBoxH = static_cast<int>(mainBox.h * 0.25); const SDL_Rect queryBox = { mainBox.x + queryOffsetX, mainBox.y + queryOffsetY, queryBoxW, queryBoxH }; boxes.push_back(queryBox); } stinkingRich::UIRenderSystem::~UIRenderSystem() { if (addedUIEntities.size() > 0) { removeUIEntity(); } if (queryTexture != nullptr) { SDL_DestroyTexture(queryTexture); } if (yesTexture != nullptr) { SDL_DestroyTexture(yesTexture); } if (noTexture != nullptr) { SDL_DestroyTexture(noTexture); } } void stinkingRich::UIRenderSystem::processEntity(std::shared_ptr<ashley::Entity> &entity, float deltaTime) { auto &text = ashley::ComponentMapper<stinkingRich::YesNoQuery>::getMapper().get(entity)->question; SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderFillRects(renderer, boxes.data(), boxes.size()); SDL_RenderCopy(renderer, yesTexture, nullptr, &boxes[1]); SDL_RenderCopy(renderer, noTexture, nullptr, &boxes[2]); SDL_RenderCopy(renderer, queryTexture, nullptr, &boxes[3]); SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF); SDL_RenderDrawRects(renderer, boxes.data(), boxes.size()); } void stinkingRich::UIRenderSystem::addUIEntity(std::shared_ptr<ashley::Entity>& e) { if (engine == nullptr) { std::cerr << "Call to addQuery with invalid engine.\n"; return; } if (addedUIEntities.size() > 0) { std::cerr << "Trying to add new ui component when one already exists.\n"; return; } engine->addEntity(e); auto yes = std::make_shared<ashley::Entity>(); auto no = std::make_shared<ashley::Entity>(); yes->add<stinkingRich::MouseListener>(boxes[1], stinkingRich::MouseMessage::YES); no->add<stinkingRich::MouseListener>(boxes[2], stinkingRich::MouseMessage::NO); engine->addEntity(yes); engine->addEntity(no); addedUIEntities.emplace_back(std::shared_ptr<ashley::Entity>(e)); addedUIEntities.emplace_back(std::shared_ptr<ashley::Entity>(yes)); addedUIEntities.emplace_back(std::shared_ptr<ashley::Entity>(no)); auto queryText = std::string(ashley::ComponentMapper<YesNoQuery>::getMapper().get(e)->question); queryText.erase(std::remove(queryText.begin(), queryText.end(), '\n'), queryText.end()); const auto textRenderer = stinkingRich::StinkingRich::getTextRenderer(); textRenderer->setColor({0x00, 0x00, 0x00, 0xFF}); queryTexture = textRenderer->renderToTexture(renderer, 0, 0, boxes[3].w, boxes[3].h, queryText, boxes[3].w); } void stinkingRich::UIRenderSystem::removeUIEntity() { if (addedUIEntities.size() == 0) { std::cerr << "Trying to remove UI entity when none exists.\n"; return; } for (const auto &e : addedUIEntities) { engine->removeEntity(e); } addedUIEntities.clear(); if(queryTexture != nullptr) { SDL_DestroyTexture(queryTexture); } } void stinkingRich::UIRenderSystem::setRenderer(SDL_Renderer *renderer) { this->renderer = renderer; } void stinkingRich::UIRenderSystem::addedToEngine(ashley::Engine &engine) { ashley::IteratingSystem::addedToEngine(engine); this->engine = &engine; } void stinkingRich::UIRenderSystem::removedFromEngine(ashley::Engine &engine) { ashley::IteratingSystem::addedToEngine(engine); this->engine = nullptr; } <commit_msg>Update to new version of AshleyCPP<commit_after>/* * UIRenderSystem.cpp * * Created on: 14 Sep 2014 * Author: Ashley Davis (SgtCoDFish) */ #include <string> #include <algorithm> #include <bitset> #include "SDL2/SDL.h" #include "Ashley/AshleyCore.hpp" #include "StinkingRich.hpp" #include "StinkingRichConstants.hpp" #include "components/YesNoQuery.hpp" #include "components/MouseListener.hpp" #include "systems/UIRenderSystem.hpp" using namespace stinkingRich; stinkingRich::UIRenderSystem::UIRenderSystem(int priority) : UIRenderSystem(nullptr, priority) { } stinkingRich::UIRenderSystem::UIRenderSystem(SDL_Renderer *renderer, int priority) : ashley::IteratingSystem( ashley::Family::getFor( ashley::BitsType(ashley::ComponentType::getBitsFor<YesNoQuery>()), ashley::BitsType(), ashley::BitsType()), priority), renderer(renderer) { const int boxW = static_cast<int>(constants::boardWidth * 0.75); const int boxWDiff = (constants::boardWidth - boxW) / 2; const int boxH = static_cast<int>(constants::boardHeight * 0.75); const int boxHDiff = (constants::boardHeight - boxH) / 2; const SDL_Rect mainBox = { StinkingRich::leftGap + boxWDiff, StinkingRich::topGap + boxHDiff, boxW, boxH }; boxes.push_back(mainBox); constexpr int optionW = 100; const int optionY = static_cast<int>(mainBox.h * 0.75) + mainBox.y; const int gapW = (boxW - (2 * optionW)) / 3; const SDL_Rect yesBox = { mainBox.x + gapW, optionY, optionW, 50 }; const SDL_Rect noBox = { mainBox.x + gapW * 2 + optionW, optionY, optionW, 50 }; boxes.push_back(yesBox); boxes.push_back(noBox); const auto textRenderer = stinkingRich::StinkingRich::getTextRenderer(); textRenderer->setColor({0x00, 0x00, 0x00, 0xFF}); yesTexture = textRenderer->renderToTexture(renderer, 0, 0, yesBox.w, yesBox.h, "Yes", yesBox.w); noTexture = textRenderer->renderToTexture(renderer, 0, 0, noBox.w, noBox.h, "No", noBox.w); constexpr int queryOffsetX = 10; constexpr int queryOffsetY = 10; const int queryBoxW = mainBox.w - (2 * queryOffsetX); const int queryBoxH = static_cast<int>(mainBox.h * 0.25); const SDL_Rect queryBox = { mainBox.x + queryOffsetX, mainBox.y + queryOffsetY, queryBoxW, queryBoxH }; boxes.push_back(queryBox); } stinkingRich::UIRenderSystem::~UIRenderSystem() { if (addedUIEntities.size() > 0) { removeUIEntity(); } if (queryTexture != nullptr) { SDL_DestroyTexture(queryTexture); } if (yesTexture != nullptr) { SDL_DestroyTexture(yesTexture); } if (noTexture != nullptr) { SDL_DestroyTexture(noTexture); } } void stinkingRich::UIRenderSystem::processEntity(std::shared_ptr<ashley::Entity> &entity, float deltaTime) { auto &text = ashley::ComponentMapper<stinkingRich::YesNoQuery>::getMapper().get(entity)->question; SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderFillRects(renderer, boxes.data(), boxes.size()); SDL_RenderCopy(renderer, yesTexture, nullptr, &boxes[1]); SDL_RenderCopy(renderer, noTexture, nullptr, &boxes[2]); SDL_RenderCopy(renderer, queryTexture, nullptr, &boxes[3]); SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF); SDL_RenderDrawRects(renderer, boxes.data(), boxes.size()); } void stinkingRich::UIRenderSystem::addUIEntity(std::shared_ptr<ashley::Entity>& e) { if (engine == nullptr) { std::cerr << "Call to addQuery with invalid engine.\n"; return; } if (addedUIEntities.size() > 0) { std::cerr << "Trying to add new ui component when one already exists.\n"; return; } engine->addEntity(e); auto yes = std::make_shared<ashley::Entity>(); auto no = std::make_shared<ashley::Entity>(); yes->add<stinkingRich::MouseListener>(boxes[1], stinkingRich::MouseMessage::YES); no->add<stinkingRich::MouseListener>(boxes[2], stinkingRich::MouseMessage::NO); engine->addEntity(yes); engine->addEntity(no); addedUIEntities.emplace_back(std::shared_ptr<ashley::Entity>(e)); addedUIEntities.emplace_back(std::shared_ptr<ashley::Entity>(yes)); addedUIEntities.emplace_back(std::shared_ptr<ashley::Entity>(no)); auto queryText = std::string(ashley::ComponentMapper<YesNoQuery>::getMapper().get(e)->question); queryText.erase(std::remove(queryText.begin(), queryText.end(), '\n'), queryText.end()); const auto textRenderer = stinkingRich::StinkingRich::getTextRenderer(); textRenderer->setColor({0x00, 0x00, 0x00, 0xFF}); queryTexture = textRenderer->renderToTexture(renderer, 0, 0, boxes[3].w, boxes[3].h, queryText, boxes[3].w); } void stinkingRich::UIRenderSystem::removeUIEntity() { if (addedUIEntities.size() == 0) { std::cerr << "Trying to remove UI entity when none exists.\n"; return; } for (auto &e : addedUIEntities) { engine->removeEntity(e); } addedUIEntities.clear(); if(queryTexture != nullptr) { SDL_DestroyTexture(queryTexture); } } void stinkingRich::UIRenderSystem::setRenderer(SDL_Renderer *renderer) { this->renderer = renderer; } void stinkingRich::UIRenderSystem::addedToEngine(ashley::Engine &engine) { ashley::IteratingSystem::addedToEngine(engine); this->engine = &engine; } void stinkingRich::UIRenderSystem::removedFromEngine(ashley::Engine &engine) { ashley::IteratingSystem::addedToEngine(engine); this->engine = nullptr; } <|endoftext|>
<commit_before>#pragma once #include <eosio/chain/transaction_metadata.hpp> #include <eosio/chain/trace.hpp> #include <eosio/chain/block_state.hpp> #include <eosio/chain/exceptions.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/member.hpp> namespace fc { inline std::size_t hash_value( const fc::sha256& v ) { return v._hash[3]; } } namespace eosio { namespace chain { using namespace boost::multi_index; enum class trx_enum_type { unknown = 0, persisted = 1, forked = 2, aborted = 3, incoming_persisted = 4, incoming = 5 // incoming_end() needs to be updated if this changes }; using next_func_t = std::function<void(const fc::static_variant<fc::exception_ptr, transaction_trace_ptr>&)>; struct unapplied_transaction { const transaction_metadata_ptr trx_meta; const fc::time_point expiry; trx_enum_type trx_type = trx_enum_type::unknown; next_func_t next; const transaction_id_type& id()const { return trx_meta->id(); } unapplied_transaction(const unapplied_transaction&) = delete; unapplied_transaction() = delete; unapplied_transaction& operator=(const unapplied_transaction&) = delete; unapplied_transaction(unapplied_transaction&&) = default; }; /** * Track unapplied transactions for persisted, forked blocks, and aborted blocks. * Persisted are first so that they can be applied in each block until expired. */ class unapplied_transaction_queue { public: enum class process_mode { non_speculative, // HEAD, READ_ONLY, IRREVERSIBLE speculative_non_producer, // will never produce speculative_producer // can produce }; private: struct by_trx_id; struct by_type; struct by_expiry; typedef multi_index_container< unapplied_transaction, indexed_by< hashed_unique< tag<by_trx_id>, const_mem_fun<unapplied_transaction, const transaction_id_type&, &unapplied_transaction::id> >, ordered_non_unique< tag<by_type>, member<unapplied_transaction, trx_enum_type, &unapplied_transaction::trx_type> >, ordered_non_unique< tag<by_expiry>, member<unapplied_transaction, const fc::time_point, &unapplied_transaction::expiry> > > > unapplied_trx_queue_type; unapplied_trx_queue_type queue; process_mode mode = process_mode::speculative_producer; uint64_t max_transaction_queue_size = 1024*1024*1024; // enforced for incoming uint64_t size_in_bytes = 0; size_t incoming_count = 0; public: void set_max_transaction_queue_size( uint64_t v ) { max_transaction_queue_size = v; } void set_mode( process_mode new_mode ) { if( new_mode != mode ) { FC_ASSERT( empty(), "set_mode, queue required to be empty" ); } mode = new_mode; } bool empty() const { return queue.empty(); } size_t size() const { return queue.size(); } void clear() { queue.clear(); } size_t incoming_size()const { return incoming_count; } transaction_metadata_ptr get_trx( const transaction_id_type& id ) const { auto itr = queue.get<by_trx_id>().find( id ); if( itr == queue.get<by_trx_id>().end() ) return {}; return itr->trx_meta; } template <typename Func> bool clear_expired( const time_point& pending_block_time, const time_point& deadline, Func&& callback ) { auto& persisted_by_expiry = queue.get<by_expiry>(); while( !persisted_by_expiry.empty() ) { const auto& itr = persisted_by_expiry.begin(); if( itr->expiry > pending_block_time ) { break; } if( deadline <= fc::time_point::now() ) { return false; } callback( itr->id(), itr->trx_type ); if( itr->next ) { itr->next( std::static_pointer_cast<fc::exception>( std::make_shared<expired_tx_exception>( FC_LOG_MESSAGE( error, "expired transaction ${id}, expiration ${e}, block time ${bt}", ("id", itr->id())("e", itr->trx_meta->packed_trx()->expiration()) ("bt", pending_block_time) ) ) ) ); } removed( itr ); persisted_by_expiry.erase( itr ); } return true; } void clear_applied( const block_state_ptr& bs ) { if( empty() ) return; auto& idx = queue.get<by_trx_id>(); for( const auto& receipt : bs->block->transactions ) { if( receipt.trx.contains<packed_transaction>() ) { const auto& pt = receipt.trx.get<packed_transaction>(); auto itr = queue.get<by_trx_id>().find( pt.id() ); if( itr != queue.get<by_trx_id>().end() ) { if( itr->trx_type != trx_enum_type::persisted && itr->trx_type != trx_enum_type::incoming_persisted ) { removed( itr ); idx.erase( itr ); } } } } } void add_forked( const branch_type& forked_branch ) { if( mode == process_mode::non_speculative || mode == process_mode::speculative_non_producer ) return; // forked_branch is in reverse order for( auto ritr = forked_branch.rbegin(), rend = forked_branch.rend(); ritr != rend; ++ritr ) { const block_state_ptr& bsptr = *ritr; for( auto itr = bsptr->trxs_metas().begin(), end = bsptr->trxs_metas().end(); itr != end; ++itr ) { const auto& trx = *itr; fc::time_point expiry = trx->packed_trx()->expiration(); auto insert_itr = queue.insert( { trx, expiry, trx_enum_type::forked } ); if( insert_itr.second ) added( insert_itr.first ); } } } void add_aborted( std::vector<transaction_metadata_ptr> aborted_trxs ) { if( mode == process_mode::non_speculative || mode == process_mode::speculative_non_producer ) return; for( auto& trx : aborted_trxs ) { fc::time_point expiry = trx->packed_trx()->expiration(); auto insert_itr = queue.insert( { std::move( trx ), expiry, trx_enum_type::aborted } ); if( insert_itr.second ) added( insert_itr.first ); } } void add_persisted( const transaction_metadata_ptr& trx ) { if( mode == process_mode::non_speculative ) return; auto itr = queue.get<by_trx_id>().find( trx->id() ); if( itr == queue.get<by_trx_id>().end() ) { fc::time_point expiry = trx->packed_trx()->expiration(); auto insert_itr = queue.insert( { trx, expiry, trx_enum_type::persisted } ); if( insert_itr.second ) added( insert_itr.first ); } else if( itr->trx_type != trx_enum_type::persisted ) { queue.get<by_trx_id>().modify( itr, [](auto& un){ un.trx_type = trx_enum_type::persisted; } ); } } void add_incoming( const transaction_metadata_ptr& trx, bool persist_until_expired, next_func_t next ) { auto itr = queue.get<by_trx_id>().find( trx->id() ); if( itr == queue.get<by_trx_id>().end() ) { fc::time_point expiry = trx->packed_trx()->expiration(); auto insert_itr = queue.insert( { trx, expiry, persist_until_expired ? trx_enum_type::incoming_persisted : trx_enum_type::incoming, std::move( next ) } ); if( insert_itr.second ) added( insert_itr.first ); } else { queue.get<by_trx_id>().modify( itr, [persist_until_expired, next{std::move(next)}](auto& un) mutable { un.trx_type = persist_until_expired ? trx_enum_type::incoming_persisted : trx_enum_type::incoming; un.next = std::move( next ); } ); } } using iterator = unapplied_trx_queue_type::index<by_type>::type::iterator; iterator begin() { return queue.get<by_type>().begin(); } iterator end() { return queue.get<by_type>().end(); } // persisted, forked, aborted iterator unapplied_begin() { return queue.get<by_type>().begin(); } iterator unapplied_end() { return queue.get<by_type>().upper_bound( trx_enum_type::aborted ); } iterator persisted_begin() { return queue.get<by_type>().lower_bound( trx_enum_type::persisted ); } iterator persisted_end() { return queue.get<by_type>().upper_bound( trx_enum_type::persisted ); } iterator incoming_begin() { return queue.get<by_type>().lower_bound( trx_enum_type::incoming_persisted ); } iterator incoming_end() { return queue.get<by_type>().end(); } // if changed to upper_bound, verify usage performance iterator erase( iterator itr ) { removed( itr ); return queue.get<by_type>().erase( itr ); } private: template<typename Itr> void added( Itr itr ) { auto size = calc_size( itr->trx_meta ); if( itr->trx_type == trx_enum_type::incoming || itr->trx_type == trx_enum_type::incoming_persisted ) { ++incoming_count; EOS_ASSERT( size_in_bytes + size < max_transaction_queue_size, tx_resource_exhaustion, "Transaction ${id}, size ${s} bytes would exceed configured " "incoming-transaction-queue-size-mb ${qs}, current queue size ${cs} bytes", ("id", itr->trx_meta->id())("s", size)("qs", max_transaction_queue_size/(1024*1024)) ("cs", size_in_bytes) ); } size_in_bytes += size; } template<typename Itr> void removed( Itr itr ) { if( itr->trx_type == trx_enum_type::incoming || itr->trx_type == trx_enum_type::incoming_persisted ) { --incoming_count; } size_in_bytes -= calc_size( itr->trx_meta ); } static uint64_t calc_size( const transaction_metadata_ptr& trx ) { // packed_trx caches unpacked transaction so double return (trx->packed_trx()->get_unprunable_size() + trx->packed_trx()->get_prunable_size()) * 2 + sizeof( *trx ); } }; } } //eosio::chain <commit_msg>Always call next() since net_plugin needs callback for tracking transactions in progress<commit_after>#pragma once #include <eosio/chain/transaction_metadata.hpp> #include <eosio/chain/trace.hpp> #include <eosio/chain/block_state.hpp> #include <eosio/chain/exceptions.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/member.hpp> namespace fc { inline std::size_t hash_value( const fc::sha256& v ) { return v._hash[3]; } } namespace eosio { namespace chain { using namespace boost::multi_index; enum class trx_enum_type { unknown = 0, persisted = 1, forked = 2, aborted = 3, incoming_persisted = 4, incoming = 5 // incoming_end() needs to be updated if this changes }; using next_func_t = std::function<void(const fc::static_variant<fc::exception_ptr, transaction_trace_ptr>&)>; struct unapplied_transaction { const transaction_metadata_ptr trx_meta; const fc::time_point expiry; trx_enum_type trx_type = trx_enum_type::unknown; next_func_t next; const transaction_id_type& id()const { return trx_meta->id(); } unapplied_transaction(const unapplied_transaction&) = delete; unapplied_transaction() = delete; unapplied_transaction& operator=(const unapplied_transaction&) = delete; unapplied_transaction(unapplied_transaction&&) = default; }; /** * Track unapplied transactions for persisted, forked blocks, and aborted blocks. * Persisted are first so that they can be applied in each block until expired. */ class unapplied_transaction_queue { public: enum class process_mode { non_speculative, // HEAD, READ_ONLY, IRREVERSIBLE speculative_non_producer, // will never produce speculative_producer // can produce }; private: struct by_trx_id; struct by_type; struct by_expiry; typedef multi_index_container< unapplied_transaction, indexed_by< hashed_unique< tag<by_trx_id>, const_mem_fun<unapplied_transaction, const transaction_id_type&, &unapplied_transaction::id> >, ordered_non_unique< tag<by_type>, member<unapplied_transaction, trx_enum_type, &unapplied_transaction::trx_type> >, ordered_non_unique< tag<by_expiry>, member<unapplied_transaction, const fc::time_point, &unapplied_transaction::expiry> > > > unapplied_trx_queue_type; unapplied_trx_queue_type queue; process_mode mode = process_mode::speculative_producer; uint64_t max_transaction_queue_size = 1024*1024*1024; // enforced for incoming uint64_t size_in_bytes = 0; size_t incoming_count = 0; public: void set_max_transaction_queue_size( uint64_t v ) { max_transaction_queue_size = v; } void set_mode( process_mode new_mode ) { if( new_mode != mode ) { FC_ASSERT( empty(), "set_mode, queue required to be empty" ); } mode = new_mode; } bool empty() const { return queue.empty(); } size_t size() const { return queue.size(); } void clear() { queue.clear(); } size_t incoming_size()const { return incoming_count; } transaction_metadata_ptr get_trx( const transaction_id_type& id ) const { auto itr = queue.get<by_trx_id>().find( id ); if( itr == queue.get<by_trx_id>().end() ) return {}; return itr->trx_meta; } template <typename Func> bool clear_expired( const time_point& pending_block_time, const time_point& deadline, Func&& callback ) { auto& persisted_by_expiry = queue.get<by_expiry>(); while( !persisted_by_expiry.empty() ) { const auto& itr = persisted_by_expiry.begin(); if( itr->expiry > pending_block_time ) { break; } if( deadline <= fc::time_point::now() ) { return false; } callback( itr->id(), itr->trx_type ); if( itr->next ) { itr->next( std::static_pointer_cast<fc::exception>( std::make_shared<expired_tx_exception>( FC_LOG_MESSAGE( error, "expired transaction ${id}, expiration ${e}, block time ${bt}", ("id", itr->id())("e", itr->trx_meta->packed_trx()->expiration()) ("bt", pending_block_time) ) ) ) ); } removed( itr, false ); persisted_by_expiry.erase( itr ); } return true; } void clear_applied( const block_state_ptr& bs ) { if( empty() ) return; auto& idx = queue.get<by_trx_id>(); for( const auto& receipt : bs->block->transactions ) { if( receipt.trx.contains<packed_transaction>() ) { const auto& pt = receipt.trx.get<packed_transaction>(); auto itr = queue.get<by_trx_id>().find( pt.id() ); if( itr != queue.get<by_trx_id>().end() ) { if( itr->trx_type != trx_enum_type::persisted && itr->trx_type != trx_enum_type::incoming_persisted ) { removed( itr ); idx.erase( itr ); } } } } } void add_forked( const branch_type& forked_branch ) { if( mode == process_mode::non_speculative || mode == process_mode::speculative_non_producer ) return; // forked_branch is in reverse order for( auto ritr = forked_branch.rbegin(), rend = forked_branch.rend(); ritr != rend; ++ritr ) { const block_state_ptr& bsptr = *ritr; for( auto itr = bsptr->trxs_metas().begin(), end = bsptr->trxs_metas().end(); itr != end; ++itr ) { const auto& trx = *itr; fc::time_point expiry = trx->packed_trx()->expiration(); auto insert_itr = queue.insert( { trx, expiry, trx_enum_type::forked } ); if( insert_itr.second ) added( insert_itr.first ); } } } void add_aborted( std::vector<transaction_metadata_ptr> aborted_trxs ) { if( mode == process_mode::non_speculative || mode == process_mode::speculative_non_producer ) return; for( auto& trx : aborted_trxs ) { fc::time_point expiry = trx->packed_trx()->expiration(); auto insert_itr = queue.insert( { std::move( trx ), expiry, trx_enum_type::aborted } ); if( insert_itr.second ) added( insert_itr.first ); } } void add_persisted( const transaction_metadata_ptr& trx ) { if( mode == process_mode::non_speculative ) return; auto itr = queue.get<by_trx_id>().find( trx->id() ); if( itr == queue.get<by_trx_id>().end() ) { fc::time_point expiry = trx->packed_trx()->expiration(); auto insert_itr = queue.insert( { trx, expiry, trx_enum_type::persisted } ); if( insert_itr.second ) added( insert_itr.first ); } else if( itr->trx_type != trx_enum_type::persisted ) { queue.get<by_trx_id>().modify( itr, [](auto& un){ un.trx_type = trx_enum_type::persisted; } ); } } void add_incoming( const transaction_metadata_ptr& trx, bool persist_until_expired, next_func_t next ) { auto itr = queue.get<by_trx_id>().find( trx->id() ); if( itr == queue.get<by_trx_id>().end() ) { fc::time_point expiry = trx->packed_trx()->expiration(); auto insert_itr = queue.insert( { trx, expiry, persist_until_expired ? trx_enum_type::incoming_persisted : trx_enum_type::incoming, std::move( next ) } ); if( insert_itr.second ) added( insert_itr.first ); } else { queue.get<by_trx_id>().modify( itr, [persist_until_expired, next{std::move(next)}](auto& un) mutable { un.trx_type = persist_until_expired ? trx_enum_type::incoming_persisted : trx_enum_type::incoming; un.next = std::move( next ); } ); } } using iterator = unapplied_trx_queue_type::index<by_type>::type::iterator; iterator begin() { return queue.get<by_type>().begin(); } iterator end() { return queue.get<by_type>().end(); } // persisted, forked, aborted iterator unapplied_begin() { return queue.get<by_type>().begin(); } iterator unapplied_end() { return queue.get<by_type>().upper_bound( trx_enum_type::aborted ); } iterator persisted_begin() { return queue.get<by_type>().lower_bound( trx_enum_type::persisted ); } iterator persisted_end() { return queue.get<by_type>().upper_bound( trx_enum_type::persisted ); } iterator incoming_begin() { return queue.get<by_type>().lower_bound( trx_enum_type::incoming_persisted ); } iterator incoming_end() { return queue.get<by_type>().end(); } // if changed to upper_bound, verify usage performance /// callers responsibilty to call next() if applicable iterator erase( iterator itr ) { removed( itr, false ); return queue.get<by_type>().erase( itr ); } private: template<typename Itr> void added( Itr itr ) { auto size = calc_size( itr->trx_meta ); if( itr->trx_type == trx_enum_type::incoming || itr->trx_type == trx_enum_type::incoming_persisted ) { ++incoming_count; EOS_ASSERT( size_in_bytes + size < max_transaction_queue_size, tx_resource_exhaustion, "Transaction ${id}, size ${s} bytes would exceed configured " "incoming-transaction-queue-size-mb ${qs}, current queue size ${cs} bytes", ("id", itr->trx_meta->id())("s", size)("qs", max_transaction_queue_size/(1024*1024)) ("cs", size_in_bytes) ); } size_in_bytes += size; } template<typename Itr> void removed( Itr itr, bool call_next = true ) { if( itr->trx_type == trx_enum_type::incoming || itr->trx_type == trx_enum_type::incoming_persisted ) { --incoming_count; } if( call_next && itr->next ) { transaction_trace_ptr trace = std::make_shared<transaction_trace>(); trace->id = itr->trx_meta->id(); itr->next( trace ); } size_in_bytes -= calc_size( itr->trx_meta ); } static uint64_t calc_size( const transaction_metadata_ptr& trx ) { // packed_trx caches unpacked transaction so double return (trx->packed_trx()->get_unprunable_size() + trx->packed_trx()->get_prunable_size()) * 2 + sizeof( *trx ); } }; } } //eosio::chain <|endoftext|>
<commit_before>/* * Copyright 2016 The Imaging Source Europe GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "JedecFile.h" #include <algorithm> #include <string> using namespace MachXO2; namespace { enum class RowType { COMMENT, FUSE_CHECKSUM, FUSE_DATA, END_DATA, FUSE_LIST, SECURITY_FUSE, FUSE_DEFAULT, FUSE_SIZE, USER_CODE, FEATURE_ROW, FEATURE_BITS, DONE }; template<typename TCharIterator> std::string getline (TCharIterator& begin, TCharIterator end, std::string delim) { std::string line; for ( ; begin != end && !std::equal(delim.begin(), delim.end(), begin); ++begin) { line += *begin; } if (begin != end) { begin += delim.length(); } return line; } bool string_startswith (const std::string& s, const std::string& start) { return s.length() >= start.length() && s.substr(0, start.length()) == start; } bool string_contains (const std::string& str, const std::string& sub) { return str.find(sub) != std::string::npos; } void ParseFuseLine (const std::string& line, std::vector<uint8_t>& dest) { int n = 0; for (int i = 0; i < 16; i++) { uint8_t val = 0; for (int j = 0; j < 8; j++) { val = (uint8_t)((val << 1) | (line[n] - '0')); ++n; } dest.push_back(val); } } std::vector<uint8_t> ParseFeatureRow (const std::string& line, int len) { std::vector<uint8_t> result(len); int n = 8 * len - 1; for (int i = 0; i < len; i++) { uint8_t val = 0; for (int j = 0; j < 8; j++) { val = (uint8_t)((val << 1) | (line[n] - '0')); --n; } result[i] = val; } return result; } uint32_t ParseUserCode (const std::string& data) { if (data[0] == 'H') { uint32_t uc; sscanf( data.c_str(), "H%08X", &uc ); return uc; } else { uint32_t val = 0; for (size_t i = 0; i < 32 && i < data.length(); ++i) { val = (val << 1) | (uint32_t)(data[i] - '0'); } return val; } } std::string RemoveTrailingStar (const std::string& s) { if (s[s.length() - 1] == '*') return s.substr(0, s.length() - 1); else return s; } } /* namespace */ JedecFile JedecFile::Parse (const std::vector<uint8_t>& data) { RowType state = RowType::COMMENT; DeviceInfo devInfo; int pageCount = 0; int cfgPageCount = 0; int ufmPageCount = 0; std::vector<uint8_t> configurationData; std::vector<uint8_t> ufmData; std::vector<uint8_t> featureRow; std::vector<uint8_t> featureBits; uint32_t userCode = 0; auto pos = data.begin(); while (pos != data.end()) { auto line = getline(pos, data.end(), "\r\n"); if (state == RowType::FEATURE_ROW) state = RowType::FEATURE_BITS; else if (line[0] == '0' || line[0] == '1') state = RowType::FUSE_DATA; else if (string_startswith(line, "NOTE")) state = RowType::COMMENT; else if (string_startswith( line, "G")) state = RowType::SECURITY_FUSE; else if (string_startswith(line, "L")) state = RowType::FUSE_LIST; else if (string_startswith( line, "C")) state = RowType::FUSE_CHECKSUM; else if(string_startswith( line, "*")) state = RowType::END_DATA; else if(string_startswith( line, "D")) state = RowType::FUSE_DEFAULT; else if(string_startswith( line, "U")) state = RowType::USER_CODE; else if(string_startswith(line, "E")) state = RowType::FEATURE_ROW; else if(string_startswith( line, "QF")) state = RowType::FUSE_SIZE; else if(string_startswith(line, "\x03")) state = RowType::DONE; switch (state) { case RowType::FUSE_DATA: ++pageCount; if (pageCount <= devInfo.numCfgPages()) { ++cfgPageCount; ParseFuseLine(line, configurationData); } else { ++ufmPageCount; ParseFuseLine(line, ufmData); } break; case RowType::FEATURE_ROW: featureRow = ParseFeatureRow(line.substr(1), 8); break; case RowType::FEATURE_BITS: featureBits = ParseFeatureRow(line, 2); break; case RowType::USER_CODE: userCode = ParseUserCode(RemoveTrailingStar(line.substr(1))); break; } if (state == RowType::COMMENT && string_contains(line, "DEVICE NAME:")) { devInfo = DeviceInfo::Find(line); } if (state == RowType::DONE) { break; } } return { devInfo.type(), userCode, configurationData, featureRow, featureBits }; } <commit_msg>Add missing default case<commit_after>/* * Copyright 2016 The Imaging Source Europe GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "JedecFile.h" #include <algorithm> #include <string> using namespace MachXO2; namespace { enum class RowType { COMMENT, FUSE_CHECKSUM, FUSE_DATA, END_DATA, FUSE_LIST, SECURITY_FUSE, FUSE_DEFAULT, FUSE_SIZE, USER_CODE, FEATURE_ROW, FEATURE_BITS, DONE }; template<typename TCharIterator> std::string getline (TCharIterator& begin, TCharIterator end, std::string delim) { std::string line; for ( ; begin != end && !std::equal(delim.begin(), delim.end(), begin); ++begin) { line += *begin; } if (begin != end) { begin += delim.length(); } return line; } bool string_startswith (const std::string& s, const std::string& start) { return s.length() >= start.length() && s.substr(0, start.length()) == start; } bool string_contains (const std::string& str, const std::string& sub) { return str.find(sub) != std::string::npos; } void ParseFuseLine (const std::string& line, std::vector<uint8_t>& dest) { int n = 0; for (int i = 0; i < 16; i++) { uint8_t val = 0; for (int j = 0; j < 8; j++) { val = (uint8_t)((val << 1) | (line[n] - '0')); ++n; } dest.push_back(val); } } std::vector<uint8_t> ParseFeatureRow (const std::string& line, int len) { std::vector<uint8_t> result(len); int n = 8 * len - 1; for (int i = 0; i < len; i++) { uint8_t val = 0; for (int j = 0; j < 8; j++) { val = (uint8_t)((val << 1) | (line[n] - '0')); --n; } result[i] = val; } return result; } uint32_t ParseUserCode (const std::string& data) { if (data[0] == 'H') { uint32_t uc; sscanf( data.c_str(), "H%08X", &uc ); return uc; } else { uint32_t val = 0; for (size_t i = 0; i < 32 && i < data.length(); ++i) { val = (val << 1) | (uint32_t)(data[i] - '0'); } return val; } } std::string RemoveTrailingStar (const std::string& s) { if (s[s.length() - 1] == '*') return s.substr(0, s.length() - 1); else return s; } } /* namespace */ JedecFile JedecFile::Parse (const std::vector<uint8_t>& data) { RowType state = RowType::COMMENT; DeviceInfo devInfo; int pageCount = 0; int cfgPageCount = 0; int ufmPageCount = 0; std::vector<uint8_t> configurationData; std::vector<uint8_t> ufmData; std::vector<uint8_t> featureRow; std::vector<uint8_t> featureBits; uint32_t userCode = 0; auto pos = data.begin(); while (pos != data.end()) { auto line = getline(pos, data.end(), "\r\n"); if (state == RowType::FEATURE_ROW) state = RowType::FEATURE_BITS; else if (line[0] == '0' || line[0] == '1') state = RowType::FUSE_DATA; else if (string_startswith(line, "NOTE")) state = RowType::COMMENT; else if (string_startswith( line, "G")) state = RowType::SECURITY_FUSE; else if (string_startswith(line, "L")) state = RowType::FUSE_LIST; else if (string_startswith( line, "C")) state = RowType::FUSE_CHECKSUM; else if(string_startswith( line, "*")) state = RowType::END_DATA; else if(string_startswith( line, "D")) state = RowType::FUSE_DEFAULT; else if(string_startswith( line, "U")) state = RowType::USER_CODE; else if(string_startswith(line, "E")) state = RowType::FEATURE_ROW; else if(string_startswith( line, "QF")) state = RowType::FUSE_SIZE; else if(string_startswith(line, "\x03")) state = RowType::DONE; switch (state) { case RowType::FUSE_DATA: ++pageCount; if (pageCount <= devInfo.numCfgPages()) { ++cfgPageCount; ParseFuseLine(line, configurationData); } else { ++ufmPageCount; ParseFuseLine(line, ufmData); } break; case RowType::FEATURE_ROW: featureRow = ParseFeatureRow(line.substr(1), 8); break; case RowType::FEATURE_BITS: featureBits = ParseFeatureRow(line, 2); break; case RowType::USER_CODE: userCode = ParseUserCode(RemoveTrailingStar(line.substr(1))); break; default: break; } if (state == RowType::COMMENT && string_contains(line, "DEVICE NAME:")) { devInfo = DeviceInfo::Find(line); } if (state == RowType::DONE) { break; } } return { devInfo.type(), userCode, configurationData, featureRow, featureBits }; } <|endoftext|>
<commit_before>/* * Copyright (c) 2013-2015 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt) * * This file is part of vanillacoin. * * vanillacoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 <cassert> #include <coin/address_manager.hpp> #include <coin/configuration.hpp> #include <coin/globals.hpp> #include <coin/logger.hpp> #include <coin/message.hpp> #include <coin/network.hpp> #include <coin/stack_impl.hpp> #include <coin/status_manager.hpp> #include <coin/tcp_connection.hpp> #include <coin/tcp_connection_manager.hpp> #include <coin/tcp_transport.hpp> #include <coin/time.hpp> #include <coin/utility.hpp> using namespace coin; tcp_connection_manager::tcp_connection_manager( boost::asio::io_service & ios, stack_impl & owner ) : io_service_(ios) , resolver_(ios) , strand_(ios) , stack_impl_(owner) , timer_(ios) { // ... } void tcp_connection_manager::start() { std::vector<boost::asio::ip::tcp::resolver::query> queries; /** * Get the bootstrap nodes and ready them for DNS lookup. */ auto bootstrap_nodes = stack_impl_.get_configuration().bootstrap_nodes(); for (auto & i : bootstrap_nodes) { boost::asio::ip::tcp::resolver::query q( i.first, std::to_string(i.second) ); queries.push_back(q); } /** * Randomize the host names. */ std::random_shuffle(queries.begin(), queries.end()); /** * Start host name resolution. */ do_resolve(queries); /** * Start the timer. */ auto self(shared_from_this()); timer_.expires_from_now(std::chrono::seconds(1)); timer_.async_wait(globals::instance().strand().wrap( std::bind(&tcp_connection_manager::tick, self, std::placeholders::_1)) ); } void tcp_connection_manager::stop() { resolver_.cancel(); timer_.cancel(); std::lock_guard<std::recursive_mutex> l1(mutex_tcp_connections_); for (auto & i : m_tcp_connections) { if (auto connection = i.second.lock()) { connection->stop(); } } m_tcp_connections.clear(); } void tcp_connection_manager::handle_accept( std::shared_ptr<tcp_transport> transport ) { std::lock_guard<std::recursive_mutex> l1(mutex_tcp_connections_); /** * Only peers accept incoming connections. */ if (globals::instance().operation_mode() == protocol::operation_mode_peer) { /** * We allow this many incoming connections per same IP address. */ enum { maximum_per_same_ip = 8 }; auto connections = 0; for (auto & i : m_tcp_connections) { try { if (auto t = i.second.lock()) { if ( t->is_transport_valid() && i.first.address() == transport->socket().remote_endpoint().address() ) { if (++connections == maximum_per_same_ip) { break; } } } } catch (...) { // ... } } if (connections > maximum_per_same_ip) { log_error( "TCP connection manager is dropping duplicate IP connection " "from " << transport->socket().remote_endpoint() << "." ); /** * Stop the transport. */ transport->stop(); } else if ( network::instance().is_address_banned( transport->socket().remote_endpoint().address().to_string()) ) { log_info( "TCP connection manager is dropping banned connection from " << transport->socket().remote_endpoint() << ", limit reached." ); /** * Stop the transport. */ transport->stop(); } else if ( is_ip_banned( transport->socket().remote_endpoint().address().to_string()) ) { log_debug( "TCP connection manager is dropping bad connection from " << transport->socket().remote_endpoint() << ", limit reached." ); /** * Stop the transport. */ transport->stop(); } else if ( m_tcp_connections.size() >= stack_impl_.get_configuration().network_tcp_inbound_maximum() ) { log_error( "TCP connection manager is dropping connection from " << transport->socket().remote_endpoint() << ", limit reached." ); /** * Stop the transport. */ transport->stop(); } else { log_debug( "TCP connection manager accepted new tcp connection from " << transport->socket().remote_endpoint() << ", " << m_tcp_connections.size() << " connected peers." ); /** * Allocate the tcp_connection. */ auto connection = std::make_shared<tcp_connection> ( io_service_, stack_impl_, tcp_connection::direction_incoming, transport ); /** * Retain the connection. */ m_tcp_connections[transport->socket().remote_endpoint()] = connection ; /** * Start the tcp_connection. */ connection->start(); } } } void tcp_connection_manager::broadcast( const char * buf, const std::size_t & len ) { std::lock_guard<std::recursive_mutex> l1(mutex_tcp_connections_); for (auto & i : m_tcp_connections) { if (auto j = i.second.lock()) { j->send(buf, len); } } } std::map< boost::asio::ip::tcp::endpoint, std::weak_ptr<tcp_connection> > & tcp_connection_manager::tcp_connections() { std::lock_guard<std::recursive_mutex> l1(mutex_tcp_connections_); return m_tcp_connections; } bool tcp_connection_manager::is_connected() { std::lock_guard<std::recursive_mutex> l1(mutex_tcp_connections_); auto tcp_connections = 0; for (auto & i : m_tcp_connections) { if (auto connection = i.second.lock()) { if (auto t = connection->get_tcp_transport().lock()) { if (t->state() == tcp_transport::state_connected) { ++tcp_connections; } } } } return tcp_connections > 0; } bool tcp_connection_manager::connect(const boost::asio::ip::tcp::endpoint & ep) { std::lock_guard<std::recursive_mutex> l1(mutex_tcp_connections_); if (network::instance().is_address_banned(ep.address().to_string())) { log_info( "TCP connection manager tried to connect to a banned address " << ep << "." ); return false; } else if (is_ip_banned(ep.address().to_string())) { log_debug( "TCP connection manager tried to connect to a bad address " << ep << "." ); return false; } else if (m_tcp_connections.find(ep) == m_tcp_connections.end()) { log_none("TCP connection manager is connecting to " << ep << "."); /** * Inform the address_manager. */ stack_impl_.get_address_manager()->on_connection_attempt( protocol::network_address_t::from_endpoint(ep) ); /** * Allocate tcp_transport. */ auto transport = std::make_shared<tcp_transport>(io_service_, strand_); /** * Allocate the tcp_connection. */ auto connection = std::make_shared<tcp_connection> ( io_service_, stack_impl_, tcp_connection::direction_outgoing, transport ); /** * Retain the connection. */ m_tcp_connections[ep] = connection; /** * Start the tcp_connection. */ connection->start(ep); return true; } else { log_none( "TCP connection manager attempted connection to existing " "endpoint = " << ep << "." ); } return false; } void tcp_connection_manager::tick(const boost::system::error_code & ec) { if (ec) { // ... } else { std::lock_guard<std::recursive_mutex> l1(mutex_tcp_connections_); auto tcp_connections = 0; auto it = m_tcp_connections.begin(); while (it != m_tcp_connections.end()) { if (auto connection = it->second.lock()) { if (connection->is_transport_valid()) { if (auto t = connection->get_tcp_transport().lock()) { if (t->state() == tcp_transport::state_connected) { ++tcp_connections; } } ++it; } else { connection->stop(); it = m_tcp_connections.erase(it); } } else { it = m_tcp_connections.erase(it); } } /** * Maintain at least minimum_tcp_connections tcp connections. */ if (tcp_connections < minimum_tcp_connections) { for ( auto i = 0; i < minimum_tcp_connections - tcp_connections; i++ ) { /** * Get a network address from the address_manager. */ auto addr = stack_impl_.get_address_manager()->select( 10 + std::min(m_tcp_connections.size(), static_cast<std::size_t> (8)) * 10 ); /** * Only connect to one peer per group. */ bool is_in_same_group = false; for (auto & i : m_tcp_connections) { if (auto j = i.second.lock()) { if (auto k = j->get_tcp_transport().lock()) { try { auto addr_tmp = protocol::network_address_t::from_endpoint( k->socket().remote_endpoint() ); if (addr.group() == addr_tmp.group()) { is_in_same_group = true; } } catch (std::exception & e) { // ... } } } } if ( addr.is_valid() == false || addr.is_local() || is_in_same_group ) { // ... } else { /** * Do not retry connections to the same network address more * often than every 3.33 minutes. */ if (time::instance().get_adjusted() - addr.last_try < 200) { log_info( "TCP connection manager attempted to " "connect to " << addr.ipv4_mapped_address() << ":" << addr.port << " too soon, last try = " << (time::instance().get_adjusted() - addr.last_try) << " seconds." ); } else { /** * Connect to the endpoint. */ if (connect( boost::asio::ip::tcp::endpoint( addr.ipv4_mapped_address(), addr.port)) ) { log_info( "TCP connection manager is connecting to " << addr.ipv4_mapped_address() << ":" << addr.port << ", last seen = " << (time::instance().get_adjusted() - addr.timestamp) / 60 << " mins, " << tcp_connections << " connected peers." ); } } } } auto self(shared_from_this()); timer_.expires_from_now(std::chrono::seconds(2)); timer_.async_wait(globals::instance().strand().wrap( std::bind(&tcp_connection_manager::tick, self, std::placeholders::_1)) ); } else { auto self(shared_from_this()); timer_.expires_from_now(std::chrono::seconds(8)); timer_.async_wait(globals::instance().strand().wrap( std::bind(&tcp_connection_manager::tick, self, std::placeholders::_1)) ); } /** * Allocate the status. */ std::map<std::string, std::string> status; /** * Set the status message. */ status["type"] = "network"; /** * Set the value. */ status["value"] = tcp_connections > 0 ? "Connected" : "Connecting"; /** * Set the network.tcp.connections. */ status["network.tcp.connections"] = std::to_string( tcp_connections ); /** * Callback status. */ stack_impl_.get_status_manager()->insert(status); } } void tcp_connection_manager::do_resolve( const std::vector<boost::asio::ip::tcp::resolver::query> & queries ) { /** * Sanity check. */ assert(queries.size() <= 100); /** * Resolve the first entry. */ resolver_.async_resolve(queries.front(), strand_.wrap([this, queries]( const boost::system::error_code & ec, const boost::asio::ip::tcp::resolver::iterator & it ) { if (ec) { // ... } else { log_debug( "TCP connection manager resolved " << it->endpoint() << "." ); /** * Create the network address. */ protocol::network_address_t addr = protocol::network_address_t::from_endpoint( it->endpoint() ); /** * Add to the address manager. */ stack_impl_.get_address_manager()->add( addr, protocol::network_address_t::from_endpoint( boost::asio::ip::tcp::endpoint( boost::asio::ip::address::from_string("127.0.0.1"), 0)) ); } if (queries.size() > 0) { auto tmp = queries; /** * Remove the first entry. */ tmp.erase(tmp.begin()); if (tmp.size() > 0) { /** * Keep resolving as long as we have entries. */ do_resolve(tmp); } } } ) ); } bool tcp_connection_manager::is_ip_banned(const std::string & val) { if ( (val[0] == '5' && val[1] == '4') || (val[0] == '5' && val[1] == '0') || (val[0] == '2' && val[1] == '1' && val[2] == '1') || (val[0] == '2' && val[1] == '1' && val[2] == '9') || (val.find("222.190.") != std::string::npos) || (val.find("41.224.") != std::string::npos) || (val.find("5.246.") != std::string::npos) || (val.find("184.73.") != std::string::npos) || (val.find("186.73.252.") != std::string::npos) || (val.find("61.164.110.") != std::string::npos) ) { return true; } return false; } <commit_msg>allow re-connection attempts after 60 seconds<commit_after>/* * Copyright (c) 2013-2015 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt) * * This file is part of vanillacoin. * * vanillacoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 <cassert> #include <coin/address_manager.hpp> #include <coin/configuration.hpp> #include <coin/globals.hpp> #include <coin/logger.hpp> #include <coin/message.hpp> #include <coin/network.hpp> #include <coin/stack_impl.hpp> #include <coin/status_manager.hpp> #include <coin/tcp_connection.hpp> #include <coin/tcp_connection_manager.hpp> #include <coin/tcp_transport.hpp> #include <coin/time.hpp> #include <coin/utility.hpp> using namespace coin; tcp_connection_manager::tcp_connection_manager( boost::asio::io_service & ios, stack_impl & owner ) : io_service_(ios) , resolver_(ios) , strand_(ios) , stack_impl_(owner) , timer_(ios) { // ... } void tcp_connection_manager::start() { std::vector<boost::asio::ip::tcp::resolver::query> queries; /** * Get the bootstrap nodes and ready them for DNS lookup. */ auto bootstrap_nodes = stack_impl_.get_configuration().bootstrap_nodes(); for (auto & i : bootstrap_nodes) { boost::asio::ip::tcp::resolver::query q( i.first, std::to_string(i.second) ); queries.push_back(q); } /** * Randomize the host names. */ std::random_shuffle(queries.begin(), queries.end()); /** * Start host name resolution. */ do_resolve(queries); /** * Start the timer. */ auto self(shared_from_this()); timer_.expires_from_now(std::chrono::seconds(1)); timer_.async_wait(globals::instance().strand().wrap( std::bind(&tcp_connection_manager::tick, self, std::placeholders::_1)) ); } void tcp_connection_manager::stop() { resolver_.cancel(); timer_.cancel(); std::lock_guard<std::recursive_mutex> l1(mutex_tcp_connections_); for (auto & i : m_tcp_connections) { if (auto connection = i.second.lock()) { connection->stop(); } } m_tcp_connections.clear(); } void tcp_connection_manager::handle_accept( std::shared_ptr<tcp_transport> transport ) { std::lock_guard<std::recursive_mutex> l1(mutex_tcp_connections_); /** * Only peers accept incoming connections. */ if (globals::instance().operation_mode() == protocol::operation_mode_peer) { /** * We allow this many incoming connections per same IP address. */ enum { maximum_per_same_ip = 8 }; auto connections = 0; for (auto & i : m_tcp_connections) { try { if (auto t = i.second.lock()) { if ( t->is_transport_valid() && i.first.address() == transport->socket().remote_endpoint().address() ) { if (++connections == maximum_per_same_ip) { break; } } } } catch (...) { // ... } } if (connections > maximum_per_same_ip) { log_error( "TCP connection manager is dropping duplicate IP connection " "from " << transport->socket().remote_endpoint() << "." ); /** * Stop the transport. */ transport->stop(); } else if ( network::instance().is_address_banned( transport->socket().remote_endpoint().address().to_string()) ) { log_info( "TCP connection manager is dropping banned connection from " << transport->socket().remote_endpoint() << ", limit reached." ); /** * Stop the transport. */ transport->stop(); } else if ( is_ip_banned( transport->socket().remote_endpoint().address().to_string()) ) { log_debug( "TCP connection manager is dropping bad connection from " << transport->socket().remote_endpoint() << ", limit reached." ); /** * Stop the transport. */ transport->stop(); } else if ( m_tcp_connections.size() >= stack_impl_.get_configuration().network_tcp_inbound_maximum() ) { log_error( "TCP connection manager is dropping connection from " << transport->socket().remote_endpoint() << ", limit reached." ); /** * Stop the transport. */ transport->stop(); } else { log_debug( "TCP connection manager accepted new tcp connection from " << transport->socket().remote_endpoint() << ", " << m_tcp_connections.size() << " connected peers." ); /** * Allocate the tcp_connection. */ auto connection = std::make_shared<tcp_connection> ( io_service_, stack_impl_, tcp_connection::direction_incoming, transport ); /** * Retain the connection. */ m_tcp_connections[transport->socket().remote_endpoint()] = connection ; /** * Start the tcp_connection. */ connection->start(); } } } void tcp_connection_manager::broadcast( const char * buf, const std::size_t & len ) { std::lock_guard<std::recursive_mutex> l1(mutex_tcp_connections_); for (auto & i : m_tcp_connections) { if (auto j = i.second.lock()) { j->send(buf, len); } } } std::map< boost::asio::ip::tcp::endpoint, std::weak_ptr<tcp_connection> > & tcp_connection_manager::tcp_connections() { std::lock_guard<std::recursive_mutex> l1(mutex_tcp_connections_); return m_tcp_connections; } bool tcp_connection_manager::is_connected() { std::lock_guard<std::recursive_mutex> l1(mutex_tcp_connections_); auto tcp_connections = 0; for (auto & i : m_tcp_connections) { if (auto connection = i.second.lock()) { if (auto t = connection->get_tcp_transport().lock()) { if (t->state() == tcp_transport::state_connected) { ++tcp_connections; } } } } return tcp_connections > 0; } bool tcp_connection_manager::connect(const boost::asio::ip::tcp::endpoint & ep) { std::lock_guard<std::recursive_mutex> l1(mutex_tcp_connections_); if (network::instance().is_address_banned(ep.address().to_string())) { log_info( "TCP connection manager tried to connect to a banned address " << ep << "." ); return false; } else if (is_ip_banned(ep.address().to_string())) { log_debug( "TCP connection manager tried to connect to a bad address " << ep << "." ); return false; } else if (m_tcp_connections.find(ep) == m_tcp_connections.end()) { log_none("TCP connection manager is connecting to " << ep << "."); /** * Inform the address_manager. */ stack_impl_.get_address_manager()->on_connection_attempt( protocol::network_address_t::from_endpoint(ep) ); /** * Allocate tcp_transport. */ auto transport = std::make_shared<tcp_transport>(io_service_, strand_); /** * Allocate the tcp_connection. */ auto connection = std::make_shared<tcp_connection> ( io_service_, stack_impl_, tcp_connection::direction_outgoing, transport ); /** * Retain the connection. */ m_tcp_connections[ep] = connection; /** * Start the tcp_connection. */ connection->start(ep); return true; } else { log_none( "TCP connection manager attempted connection to existing " "endpoint = " << ep << "." ); } return false; } void tcp_connection_manager::tick(const boost::system::error_code & ec) { if (ec) { // ... } else { std::lock_guard<std::recursive_mutex> l1(mutex_tcp_connections_); auto tcp_connections = 0; auto it = m_tcp_connections.begin(); while (it != m_tcp_connections.end()) { if (auto connection = it->second.lock()) { if (connection->is_transport_valid()) { if (auto t = connection->get_tcp_transport().lock()) { if (t->state() == tcp_transport::state_connected) { ++tcp_connections; } } ++it; } else { connection->stop(); it = m_tcp_connections.erase(it); } } else { it = m_tcp_connections.erase(it); } } /** * Maintain at least minimum_tcp_connections tcp connections. */ if (tcp_connections < minimum_tcp_connections) { for ( auto i = 0; i < minimum_tcp_connections - tcp_connections; i++ ) { /** * Get a network address from the address_manager. */ auto addr = stack_impl_.get_address_manager()->select( 10 + std::min(m_tcp_connections.size(), static_cast<std::size_t> (8)) * 10 ); /** * Only connect to one peer per group. */ bool is_in_same_group = false; for (auto & i : m_tcp_connections) { if (auto j = i.second.lock()) { if (auto k = j->get_tcp_transport().lock()) { try { auto addr_tmp = protocol::network_address_t::from_endpoint( k->socket().remote_endpoint() ); if (addr.group() == addr_tmp.group()) { is_in_same_group = true; } } catch (std::exception & e) { // ... } } } } if ( addr.is_valid() == false || addr.is_local() || is_in_same_group ) { // ... } else { /** * Do not retry connections to the same network address more * often than every 60 seconds. */ if (time::instance().get_adjusted() - addr.last_try < 60) { log_info( "TCP connection manager attempted to " "connect to " << addr.ipv4_mapped_address() << ":" << addr.port << " too soon, last try = " << (time::instance().get_adjusted() - addr.last_try) << " seconds." ); } else { /** * Connect to the endpoint. */ if (connect( boost::asio::ip::tcp::endpoint( addr.ipv4_mapped_address(), addr.port)) ) { log_info( "TCP connection manager is connecting to " << addr.ipv4_mapped_address() << ":" << addr.port << ", last seen = " << (time::instance().get_adjusted() - addr.timestamp) / 60 << " mins, " << tcp_connections << " connected peers." ); } } } } auto self(shared_from_this()); timer_.expires_from_now(std::chrono::seconds(2)); timer_.async_wait(globals::instance().strand().wrap( std::bind(&tcp_connection_manager::tick, self, std::placeholders::_1)) ); } else { auto self(shared_from_this()); timer_.expires_from_now(std::chrono::seconds(8)); timer_.async_wait(globals::instance().strand().wrap( std::bind(&tcp_connection_manager::tick, self, std::placeholders::_1)) ); } /** * Allocate the status. */ std::map<std::string, std::string> status; /** * Set the status message. */ status["type"] = "network"; /** * Set the value. */ status["value"] = tcp_connections > 0 ? "Connected" : "Connecting"; /** * Set the network.tcp.connections. */ status["network.tcp.connections"] = std::to_string( tcp_connections ); /** * Callback status. */ stack_impl_.get_status_manager()->insert(status); } } void tcp_connection_manager::do_resolve( const std::vector<boost::asio::ip::tcp::resolver::query> & queries ) { /** * Sanity check. */ assert(queries.size() <= 100); /** * Resolve the first entry. */ resolver_.async_resolve(queries.front(), strand_.wrap([this, queries]( const boost::system::error_code & ec, const boost::asio::ip::tcp::resolver::iterator & it ) { if (ec) { // ... } else { log_debug( "TCP connection manager resolved " << it->endpoint() << "." ); /** * Create the network address. */ protocol::network_address_t addr = protocol::network_address_t::from_endpoint( it->endpoint() ); /** * Add to the address manager. */ stack_impl_.get_address_manager()->add( addr, protocol::network_address_t::from_endpoint( boost::asio::ip::tcp::endpoint( boost::asio::ip::address::from_string("127.0.0.1"), 0)) ); } if (queries.size() > 0) { auto tmp = queries; /** * Remove the first entry. */ tmp.erase(tmp.begin()); if (tmp.size() > 0) { /** * Keep resolving as long as we have entries. */ do_resolve(tmp); } } } ) ); } bool tcp_connection_manager::is_ip_banned(const std::string & val) { if ( (val[0] == '5' && val[1] == '4') || (val[0] == '5' && val[1] == '0') || (val[0] == '2' && val[1] == '1' && val[2] == '1') || (val[0] == '2' && val[1] == '1' && val[2] == '9') || (val.find("222.190.") != std::string::npos) || (val.find("41.224.") != std::string::npos) || (val.find("5.246.") != std::string::npos) || (val.find("184.73.") != std::string::npos) || (val.find("186.73.252.") != std::string::npos) || (val.find("61.164.110.") != std::string::npos) ) { return true; } return false; } <|endoftext|>
<commit_before>// Copyright (c) 2020 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #include "test.hpp" #include "verify_meta.hpp" namespace TAO_PEGTL_NAMESPACE { template< tracking_mode M > void unit_test() { memory_input< M > in( "foo\nbar bla blubb\nbaz", "test_source" ); try { parse< seq< identifier, eol, identifier, one< ' ' >, must< digit > > >( in ); } catch( const parse_error& e ) { TAO_PEGTL_TEST_ASSERT( e.what(), "parse error matching tao::pegtl::ascii::digit" ); TAO_PEGTL_TEST_ASSERT( e.positions.size() == 1 ); const auto& p = e.positions.front(); TAO_PEGTL_TEST_ASSERT( p.byte == 8 ); TAO_PEGTL_TEST_ASSERT( p.line == 2 ); TAO_PEGTL_TEST_ASSERT( p.byte_in_line == 5 ); TAO_PEGTL_TEST_ASSERT( p.source == "test_source" ); TAO_PEGTL_TEST_ASSERT( to_string( p ) == "test_source:2:5(8)" ); TAO_PEGTL_TEST_ASSERT( to_string( e ) == "test_source:2:5(8): parse error matching tao::pegtl::ascii::digit" ); TAO_PEGTL_TEST_ASSERT( in.line_at( p ) == "bar bla blubb" ); return; } TAO_PEGTL_TEST_UNREACHABLE; } void unit_test() { unit_test< tracking_mode::eager >(); unit_test< tracking_mode::lazy >(); } } // namespace TAO_PEGTL_NAMESPACE #include "main.hpp" <commit_msg>Fix test for MSVC<commit_after>// Copyright (c) 2020 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #include "test.hpp" #include "verify_meta.hpp" namespace TAO_PEGTL_NAMESPACE { template< tracking_mode M > void unit_test() { const std::string rulename{ demangle< digit >() }; memory_input< M > in( "foo\nbar bla blubb\nbaz", "test_source" ); try { parse< seq< identifier, eol, identifier, one< ' ' >, must< digit > > >( in ); } catch( const parse_error& e ) { TAO_PEGTL_TEST_ASSERT( e.what() == "parse error matching " + rulename ); TAO_PEGTL_TEST_ASSERT( e.positions.size() == 1 ); const auto& p = e.positions.front(); TAO_PEGTL_TEST_ASSERT( p.byte == 8 ); TAO_PEGTL_TEST_ASSERT( p.line == 2 ); TAO_PEGTL_TEST_ASSERT( p.byte_in_line == 5 ); TAO_PEGTL_TEST_ASSERT( p.source == "test_source" ); TAO_PEGTL_TEST_ASSERT( to_string( p ) == "test_source:2:5(8)" ); TAO_PEGTL_TEST_ASSERT( to_string( e ) == "test_source:2:5(8): parse error matching " + rulename ); TAO_PEGTL_TEST_ASSERT( in.line_at( p ) == "bar bla blubb" ); return; } TAO_PEGTL_TEST_UNREACHABLE; } void unit_test() { unit_test< tracking_mode::eager >(); unit_test< tracking_mode::lazy >(); } } // namespace TAO_PEGTL_NAMESPACE #include "main.hpp" <|endoftext|>
<commit_before>#include "StdAfx.h" #include "Tests.h" #include "stdlib.h" #define WIN32_LEAN_AND_MEAN #include <Windows.h> void TestAllocationMismatch_malloc_delete() { int* pint = (int*)malloc(56); // use the wrong function to deallocate delete pint; } void TestAllocationMismatch_malloc_deleteVec() { int* pint = (int*)malloc(56); // use the wrong function to deallocate delete [] pint; } void TestAllocationMismatch_new_free() { int* pint = new int(45); // scalar new // use the wrong function to deallocate free(pint); } void TestAllocationMismatch_newVec_free() { int* pint = new int[3]; // vector new // use the wrong function to deallocate free(pint); } void TestHeapMismatch() { HANDLE test_heap = HeapCreate(HEAP_GENERATE_EXCEPTIONS | HEAP_CREATE_ENABLE_EXECUTE, 0, // initialize reserved size; 0); // maximum size can grow HANDLE default_heap = GetProcessHeap(); // Have to initialize vld with something, so it doesn't dismiss // the default heap as having no memory allocs in it. void* aptr = HeapAlloc(default_heap, 0, 42); // Allocate it in the new heap void* vptr = HeapAlloc(test_heap, 0, 56); // Free this using the WRONG heap! HeapFree( default_heap, 0, vptr); HeapDestroy(test_heap); } <commit_msg>Set HeapEnableTerminationOnCorruption to ensure process termination on corruption test<commit_after>#include "StdAfx.h" #include "Tests.h" #include "stdlib.h" #define WIN32_LEAN_AND_MEAN #include <Windows.h> void TestAllocationMismatch_malloc_delete() { int* pint = (int*)malloc(56); // use the wrong function to deallocate delete pint; } void TestAllocationMismatch_malloc_deleteVec() { int* pint = (int*)malloc(56); // use the wrong function to deallocate delete [] pint; } void TestAllocationMismatch_new_free() { int* pint = new int(45); // scalar new // use the wrong function to deallocate free(pint); } void TestAllocationMismatch_newVec_free() { int* pint = new int[3]; // vector new // use the wrong function to deallocate free(pint); } void TestHeapMismatch() { HANDLE test_heap = HeapCreate(HEAP_GENERATE_EXCEPTIONS | HEAP_CREATE_ENABLE_EXECUTE, 0, // initialize reserved size; 0); // maximum size can grow HeapSetInformation(test_heap, HeapEnableTerminationOnCorruption, NULL, 0); HANDLE default_heap = GetProcessHeap(); HeapSetInformation(default_heap, HeapEnableTerminationOnCorruption, NULL, 0); // Have to initialize vld with something, so it doesn't dismiss // the default heap as having no memory allocs in it. void* aptr = HeapAlloc(default_heap, 0, 42); // Allocate it in the new heap void* vptr = HeapAlloc(test_heap, 0, 56); // Free this using the WRONG heap! HeapFree( default_heap, 0, vptr); HeapDestroy(test_heap); } <|endoftext|>
<commit_before>#include <iostream> // std::cout, std::cin, std::endl #include <queue> // std::queue, std::push, std::pop, std::front #include <tuple> #include "extra.hpp" // int_to_string #ifndef CUBE_H #define CUBE_H class Cube { /* Vamos a definir que un cubo tiene las siguientes caras, que comienzan de los colores: front = white back = yellow left = orange right = red top = blue down = green ____________ / / / /\ /___/___/___/ \ / / T / /\ /\ L/___/___/___/ \/ \B / / / /\ /\ /\ /___/___/___/ \/ \/ \ \ \ \ \ /\R /\ / \___\___\___\/ \/ \/ \ \ F \ \ /\ / \___\___\___\/ \/D \ \ \ \ / \___\___\___\/ LTF: LT = X FT = Y LF = Z T = XY = A L = YZ = B F = XZ = C //////////////////////////////////////// cubie X orientation |_|_|_| |_| |_|_|_|_| A B C 0 - 7 C -> goal orientation for all corners and eight edges */ public: // Constructor Cube(); ~Cube(); Cube* clone(); std::string to_string(); std::string corners_to_string(); std::string edges_to_string(); std::string printable(); bool equals(Cube* other); // operations on the cube void clock(char face); void counter(char face); void hundred(char face); std::queue<Cube*>* succ(); uint8_t* get_corners(); bool equals_corners(uint8_t *other); private: uint8_t *corners; uint8_t *edges; char last; int* switch_get(char chr); void switch_set(char chr, int* face); // getters and setters for the faces of the cube int* get_front(); void set_front(int* face); int* get_back(); void set_back(int* face); int* get_right(); void set_right(int* face); int* get_left(); void set_left(int* face); int* get_top(); void set_top(int* face); int* get_down(); void set_down(int* face); std::string color_face(int* face, char chr); }; #endif <commit_msg>comentario de goal para edges<commit_after>#include <iostream> // std::cout, std::cin, std::endl #include <queue> // std::queue, std::push, std::pop, std::front #include <tuple> #include "extra.hpp" // int_to_string #ifndef CUBE_H #define CUBE_H class Cube { /* Vamos a definir que un cubo tiene las siguientes caras, que comienzan de los colores: front = white back = yellow left = orange right = red top = blue down = green ____________ / / / /\ /___/___/___/ \ / / T / /\ /\ L/___/___/___/ \/ \B / / / /\ /\ /\ /___/___/___/ \/ \/ \ \ \ \ \ /\R /\ / \___\___\___\/ \/ \/ \ \ F \ \ /\ / \___\___\___\/ \/D \ \ \ \ / \___\___\___\/ LTF: LT = X FT = Y LF = Z T = XY = A L = YZ = B F = XZ = C //////////////////////////////////////// cubie X orientation |_|_|_| |_| |_|_|_|_| A B C 0 - 7 C -> goal orientation for all corners and eight edges B -> goal orientation for other 4 edges */ public: // Constructor Cube(); ~Cube(); Cube* clone(); std::string to_string(); std::string corners_to_string(); std::string edges_to_string(); std::string printable(); bool equals(Cube* other); // operations on the cube void clock(char face); void counter(char face); void hundred(char face); std::queue<Cube*>* succ(); uint8_t* get_corners(); bool equals_corners(uint8_t *other); private: uint8_t *corners; uint8_t *edges; char last; int* switch_get(char chr); void switch_set(char chr, int* face); // getters and setters for the faces of the cube int* get_front(); void set_front(int* face); int* get_back(); void set_back(int* face); int* get_right(); void set_right(int* face); int* get_left(); void set_left(int* face); int* get_top(); void set_top(int* face); int* get_down(); void set_down(int* face); std::string color_face(int* face, char chr); }; #endif <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/math/smoothing_spline/spline_2d_constraint.h" #include "glog/logging.h" #include "gtest/gtest.h" namespace apollo { namespace planning { using apollo::common::math::Vec2d; TEST(Spline2dConstraint, add_boundary_01) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 4; Spline2dConstraint constraint(x_knots, spline_order); std::vector<double> t_coord = {0.0}; std::vector<double> angle = {0.0}; std::vector<Vec2d> ref_point; ref_point.emplace_back(Vec2d(0.0, 0.0)); std::vector<double> longitidinal_bound = {1.0}; std::vector<double> lateral_bound = {2.0}; constraint.Add2dBoundary(t_coord, angle, ref_point, longitidinal_bound, lateral_bound); const auto mat = constraint.inequality_constraint().constraint_matrix(); const auto boundary = constraint.inequality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 8); ref_mat << -0, -0, -0, -0, 1, 0, 0, 0, 0, 0, 0, 0, -1, -0, -0, -0, 1, 0, 0, 0, 6.12323e-17, 0, 0, 0, -1, -0, -0, -0, -6.12323e-17, -0, -0, -0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-6); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(4, 1); ref_boundary << -1.0, -1.0, -2.0, -2.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-5); } } // test add boundary with non-zero angle TEST(Spline2dConstraint, add_boundary_02) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 4; Spline2dConstraint constraint(x_knots, spline_order); std::vector<double> t_coord = {0.0}; std::vector<double> angle = {0.2}; std::vector<Vec2d> ref_point; ref_point.emplace_back(Vec2d(0.0, 0.0)); std::vector<double> longitidinal_bound = {1.0}; std::vector<double> lateral_bound = {2.0}; constraint.Add2dBoundary(t_coord, angle, ref_point, longitidinal_bound, lateral_bound); const auto mat = constraint.inequality_constraint().constraint_matrix(); const auto boundary = constraint.inequality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 8); ref_mat << -0.198669, -0, -0, -0, 0.980067, 0, 0, 0, 0.198669, 0, 0, 0, -0.980067, -0, -0, -0, 0.980067, 0, 0, 0, 0.198669, 0, 0, 0, -0.980067, -0, -0, -0, -0.198669, -0, -0, -0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-6); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(4, 1); ref_boundary << -1.0, -1.0, -2.0, -2.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-5); } } } // namespace planning } // namespace apollo <commit_msg>Planning: Added add boundary with multiple splines test for 2d spline<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/math/smoothing_spline/spline_2d_constraint.h" #include "glog/logging.h" #include "gtest/gtest.h" namespace apollo { namespace planning { using apollo::common::math::Vec2d; TEST(Spline2dConstraint, add_boundary_01) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 4; Spline2dConstraint constraint(x_knots, spline_order); std::vector<double> t_coord = {0.0}; std::vector<double> angle = {0.0}; std::vector<Vec2d> ref_point; ref_point.emplace_back(Vec2d(0.0, 0.0)); std::vector<double> longitidinal_bound = {1.0}; std::vector<double> lateral_bound = {2.0}; constraint.Add2dBoundary(t_coord, angle, ref_point, longitidinal_bound, lateral_bound); const auto mat = constraint.inequality_constraint().constraint_matrix(); const auto boundary = constraint.inequality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 8); ref_mat << -0, -0, -0, -0, 1, 0, 0, 0, 0, 0, 0, 0, -1, -0, -0, -0, 1, 0, 0, 0, 6.12323e-17, 0, 0, 0, -1, -0, -0, -0, -6.12323e-17, -0, -0, -0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-6); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(4, 1); ref_boundary << -1.0, -1.0, -2.0, -2.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-5); } } // test add boundary with non-zero angle TEST(Spline2dConstraint, add_boundary_02) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 4; Spline2dConstraint constraint(x_knots, spline_order); std::vector<double> t_coord = {0.0}; std::vector<double> angle = {0.2}; std::vector<Vec2d> ref_point; ref_point.emplace_back(Vec2d(0.0, 0.0)); std::vector<double> longitidinal_bound = {1.0}; std::vector<double> lateral_bound = {2.0}; constraint.Add2dBoundary(t_coord, angle, ref_point, longitidinal_bound, lateral_bound); const auto mat = constraint.inequality_constraint().constraint_matrix(); const auto boundary = constraint.inequality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 8); ref_mat << -0.198669, -0, -0, -0, 0.980067, 0, 0, 0, 0.198669, 0, 0, 0, -0.980067, -0, -0, -0, 0.980067, 0, 0, 0, 0.198669, 0, 0, 0, -0.980067, -0, -0, -0, -0.198669, -0, -0, -0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-6); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(4, 1); ref_boundary << -1.0, -1.0, -2.0, -2.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-5); } } // test add boundary with multiple splines TEST(Spline2dConstraint, add_boundary_03) { std::vector<double> x_knots = {0.0, 1.0, 2.0}; int32_t spline_order = 4; Spline2dConstraint constraint(x_knots, spline_order); std::vector<double> t_coord = {1.0}; std::vector<double> angle = {0.2}; std::vector<Vec2d> ref_point; ref_point.emplace_back(Vec2d(0.0, 0.0)); std::vector<double> longitidinal_bound = {1.0}; std::vector<double> lateral_bound = {2.0}; constraint.Add2dBoundary(t_coord, angle, ref_point, longitidinal_bound, lateral_bound); const auto mat = constraint.inequality_constraint().constraint_matrix(); const auto boundary = constraint.inequality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 16); ref_mat << 0, 0, 0, 0, 0, 0, 0, 0, -0.198669, -0, -0, -0, 0.980067, 0, 0, 0, // NOLINT 0, 0, 0, 0, 0, 0, 0, 0, 0.198669, 0, 0, 0, -0.980067, -0, -0, -0, // NOLINT 0, 0, 0, 0, 0, 0, 0, 0, 0.980067, 0, 0, 0, 0.198669, 0, 0, 0, // NOLINT 0, 0, 0, 0, 0, 0, 0, 0, -0.980067, -0, -0, -0, -0.198669, -0, -0, -0; // NOLINT // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-6); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(4, 1); ref_boundary << -1.0, -1.0, -2.0, -2.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-5); } } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective icvers. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ #ifndef __OPENCV_FAST_NLMEANS_DENOISING_INVOKER_HPP__ #define __OPENCV_FAST_NLMEANS_DENOISING_INVOKER_HPP__ #include "precomp.hpp" #include <limits> #include "fast_nlmeans_denoising_invoker_commons.hpp" #include "arrays.hpp" using namespace cv; template <typename T, typename IT, typename UIT, typename D, typename WT> struct FastNlMeansDenoisingInvoker : public ParallelLoopBody { public: FastNlMeansDenoisingInvoker(const Mat& src, Mat& dst, int template_window_size, int search_window_size, const float *h); void operator() (const Range& range) const; private: void operator= (const FastNlMeansDenoisingInvoker&); const Mat& src_; Mat& dst_; Mat extended_src_; int border_size_; int template_window_size_; int search_window_size_; int template_window_half_size_; int search_window_half_size_; typename pixelInfo<WT>::sampleType fixed_point_mult_; int almost_template_window_size_sq_bin_shift_; std::vector<WT> almost_dist2weight_; void calcDistSumsForFirstElementInRow( int i, Array2d<int>& dist_sums, Array3d<int>& col_dist_sums, Array3d<int>& up_col_dist_sums) const; void calcDistSumsForElementInFirstRow( int i, int j, int first_col_num, Array2d<int>& dist_sums, Array3d<int>& col_dist_sums, Array3d<int>& up_col_dist_sums) const; }; inline int getNearestPowerOf2(int value) { int p = 0; while( 1 << p < value) ++p; return p; } template <typename T, typename IT, typename UIT, typename D, typename WT> FastNlMeansDenoisingInvoker<T, IT, UIT, D, WT>::FastNlMeansDenoisingInvoker( const Mat& src, Mat& dst, int template_window_size, int search_window_size, const float *h) : src_(src), dst_(dst) { CV_Assert(src.channels() == pixelInfo<T>::channels); template_window_half_size_ = template_window_size / 2; search_window_half_size_ = search_window_size / 2; template_window_size_ = template_window_half_size_ * 2 + 1; search_window_size_ = search_window_half_size_ * 2 + 1; border_size_ = search_window_half_size_ + template_window_half_size_; copyMakeBorder(src_, extended_src_, border_size_, border_size_, border_size_, border_size_, BORDER_DEFAULT); const IT max_estimate_sum_value = (IT)search_window_size_ * (IT)search_window_size_ * (IT)pixelInfo<T>::sampleMax(); fixed_point_mult_ = (int)std::min<IT>(std::numeric_limits<IT>::max() / max_estimate_sum_value, pixelInfo<WT>::sampleMax()); // precalc weight for every possible l2 dist between blocks // additional optimization of precalced weights to replace division(averaging) by binary shift CV_Assert(template_window_size_ <= 46340); // sqrt(INT_MAX) int template_window_size_sq = template_window_size_ * template_window_size_; almost_template_window_size_sq_bin_shift_ = getNearestPowerOf2(template_window_size_sq); double almost_dist2actual_dist_multiplier = ((double)(1 << almost_template_window_size_sq_bin_shift_)) / template_window_size_sq; int max_dist = D::template maxDist<T>(); int almost_max_dist = (int)(max_dist / almost_dist2actual_dist_multiplier + 1); almost_dist2weight_.resize(almost_max_dist); for (int almost_dist = 0; almost_dist < almost_max_dist; almost_dist++) { double dist = almost_dist * almost_dist2actual_dist_multiplier; almost_dist2weight_[almost_dist] = D::template calcWeight<T, WT>(dist, h, fixed_point_mult_); } // additional optimization init end if (dst_.empty()) dst_ = Mat::zeros(src_.size(), src_.type()); } template <typename T, typename IT, typename UIT, typename D, typename WT> void FastNlMeansDenoisingInvoker<T, IT, UIT, D, WT>::operator() (const Range& range) const { int row_from = range.start; int row_to = range.end - 1; // sums of cols anf rows for current pixel p Array2d<int> dist_sums(search_window_size_, search_window_size_); // for lazy calc optimization (sum of cols for current pixel) Array3d<int> col_dist_sums(template_window_size_, search_window_size_, search_window_size_); int first_col_num = -1; // last elements of column sum (for each element in row) Array3d<int> up_col_dist_sums(src_.cols, search_window_size_, search_window_size_); for (int i = row_from; i <= row_to; i++) { for (int j = 0; j < src_.cols; j++) { int search_window_y = i - search_window_half_size_; int search_window_x = j - search_window_half_size_; // calc dist_sums if (j == 0) { calcDistSumsForFirstElementInRow(i, dist_sums, col_dist_sums, up_col_dist_sums); first_col_num = 0; } else { // calc cur dist_sums using previous dist_sums if (i == row_from) { calcDistSumsForElementInFirstRow(i, j, first_col_num, dist_sums, col_dist_sums, up_col_dist_sums); } else { int ay = border_size_ + i; int ax = border_size_ + j + template_window_half_size_; int start_by = border_size_ + i - search_window_half_size_; int start_bx = border_size_ + j - search_window_half_size_ + template_window_half_size_; T a_up = extended_src_.at<T>(ay - template_window_half_size_ - 1, ax); T a_down = extended_src_.at<T>(ay + template_window_half_size_, ax); // copy class member to local variable for optimization int search_window_size = search_window_size_; for (int y = 0; y < search_window_size; y++) { int * dist_sums_row = dist_sums.row_ptr(y); int * col_dist_sums_row = col_dist_sums.row_ptr(first_col_num, y); int * up_col_dist_sums_row = up_col_dist_sums.row_ptr(j, y); const T * b_up_ptr = extended_src_.ptr<T>(start_by - template_window_half_size_ - 1 + y); const T * b_down_ptr = extended_src_.ptr<T>(start_by + template_window_half_size_ + y); for (int x = 0; x < search_window_size; x++) { // remove from current pixel sum column sum with index "first_col_num" dist_sums_row[x] -= col_dist_sums_row[x]; int bx = start_bx + x; col_dist_sums_row[x] = up_col_dist_sums_row[x] + D::template calcUpDownDist<T>(a_up, a_down, b_up_ptr[bx], b_down_ptr[bx]); dist_sums_row[x] += col_dist_sums_row[x]; up_col_dist_sums_row[x] = col_dist_sums_row[x]; } } } first_col_num = (first_col_num + 1) % template_window_size_; } // calc weights IT estimation[pixelInfo<T>::channels], weights_sum[pixelInfo<WT>::channels]; for (int channel_num = 0; channel_num < pixelInfo<T>::channels; channel_num++) estimation[channel_num] = 0; for (int channel_num = 0; channel_num < pixelInfo<WT>::channels; channel_num++) weights_sum[channel_num] = 0; for (int y = 0; y < search_window_size_; y++) { const T* cur_row_ptr = extended_src_.ptr<T>(border_size_ + search_window_y + y); int* dist_sums_row = dist_sums.row_ptr(y); for (int x = 0; x < search_window_size_; x++) { int almostAvgDist = dist_sums_row[x] >> almost_template_window_size_sq_bin_shift_; WT weight = almost_dist2weight_[almostAvgDist]; T p = cur_row_ptr[border_size_ + search_window_x + x]; incWithWeight<T, IT, WT>(estimation, weights_sum, weight, p); } } divByWeightsSum<IT, UIT, pixelInfo<T>::channels, pixelInfo<WT>::channels>(estimation, weights_sum); dst_.at<T>(i,j) = saturateCastFromArray<T, IT>(estimation); } } } template <typename T, typename IT, typename UIT, typename D, typename WT> inline void FastNlMeansDenoisingInvoker<T, IT, UIT, D, WT>::calcDistSumsForFirstElementInRow( int i, Array2d<int>& dist_sums, Array3d<int>& col_dist_sums, Array3d<int>& up_col_dist_sums) const { int j = 0; for (int y = 0; y < search_window_size_; y++) for (int x = 0; x < search_window_size_; x++) { dist_sums[y][x] = 0; for (int tx = 0; tx < template_window_size_; tx++) col_dist_sums[tx][y][x] = 0; int start_y = i + y - search_window_half_size_; int start_x = j + x - search_window_half_size_; for (int ty = -template_window_half_size_; ty <= template_window_half_size_; ty++) for (int tx = -template_window_half_size_; tx <= template_window_half_size_; tx++) { int dist = D::template calcDist<T>(extended_src_, border_size_ + i + ty, border_size_ + j + tx, border_size_ + start_y + ty, border_size_ + start_x + tx); dist_sums[y][x] += dist; col_dist_sums[tx + template_window_half_size_][y][x] += dist; } up_col_dist_sums[j][y][x] = col_dist_sums[template_window_size_ - 1][y][x]; } } template <typename T, typename IT, typename UIT, typename D, typename WT> inline void FastNlMeansDenoisingInvoker<T, IT, UIT, D, WT>::calcDistSumsForElementInFirstRow( int i, int j, int first_col_num, Array2d<int>& dist_sums, Array3d<int>& col_dist_sums, Array3d<int>& up_col_dist_sums) const { int ay = border_size_ + i; int ax = border_size_ + j + template_window_half_size_; int start_by = border_size_ + i - search_window_half_size_; int start_bx = border_size_ + j - search_window_half_size_ + template_window_half_size_; int new_last_col_num = first_col_num; for (int y = 0; y < search_window_size_; y++) for (int x = 0; x < search_window_size_; x++) { dist_sums[y][x] -= col_dist_sums[first_col_num][y][x]; col_dist_sums[new_last_col_num][y][x] = 0; int by = start_by + y; int bx = start_bx + x; for (int ty = -template_window_half_size_; ty <= template_window_half_size_; ty++) col_dist_sums[new_last_col_num][y][x] += D::template calcDist<T>(extended_src_, ay + ty, ax, by + ty, bx); dist_sums[y][x] += col_dist_sums[new_last_col_num][y][x]; up_col_dist_sums[j][y][x] = col_dist_sums[new_last_col_num][y][x]; } } #endif <commit_msg>photo: crash workaround for MSVC 2015 32-bit<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective icvers. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ #ifndef __OPENCV_FAST_NLMEANS_DENOISING_INVOKER_HPP__ #define __OPENCV_FAST_NLMEANS_DENOISING_INVOKER_HPP__ #include "precomp.hpp" #include <limits> #include "fast_nlmeans_denoising_invoker_commons.hpp" #include "arrays.hpp" using namespace cv; template <typename T, typename IT, typename UIT, typename D, typename WT> struct FastNlMeansDenoisingInvoker : public ParallelLoopBody { public: FastNlMeansDenoisingInvoker(const Mat& src, Mat& dst, int template_window_size, int search_window_size, const float *h); void operator() (const Range& range) const; private: void operator= (const FastNlMeansDenoisingInvoker&); const Mat& src_; Mat& dst_; Mat extended_src_; int border_size_; int template_window_size_; int search_window_size_; int template_window_half_size_; int search_window_half_size_; typename pixelInfo<WT>::sampleType fixed_point_mult_; int almost_template_window_size_sq_bin_shift_; std::vector<WT> almost_dist2weight_; void calcDistSumsForFirstElementInRow( int i, Array2d<int>& dist_sums, Array3d<int>& col_dist_sums, Array3d<int>& up_col_dist_sums) const; void calcDistSumsForElementInFirstRow( int i, int j, int first_col_num, Array2d<int>& dist_sums, Array3d<int>& col_dist_sums, Array3d<int>& up_col_dist_sums) const; }; inline int getNearestPowerOf2(int value) { int p = 0; while( 1 << p < value) ++p; return p; } template <typename T, typename IT, typename UIT, typename D, typename WT> FastNlMeansDenoisingInvoker<T, IT, UIT, D, WT>::FastNlMeansDenoisingInvoker( const Mat& src, Mat& dst, int template_window_size, int search_window_size, const float *h) : src_(src), dst_(dst) { CV_Assert(src.channels() == pixelInfo<T>::channels); template_window_half_size_ = template_window_size / 2; search_window_half_size_ = search_window_size / 2; template_window_size_ = template_window_half_size_ * 2 + 1; search_window_size_ = search_window_half_size_ * 2 + 1; border_size_ = search_window_half_size_ + template_window_half_size_; copyMakeBorder(src_, extended_src_, border_size_, border_size_, border_size_, border_size_, BORDER_DEFAULT); const IT max_estimate_sum_value = (IT)search_window_size_ * (IT)search_window_size_ * (IT)pixelInfo<T>::sampleMax(); fixed_point_mult_ = (int)std::min<IT>(std::numeric_limits<IT>::max() / max_estimate_sum_value, pixelInfo<WT>::sampleMax()); // precalc weight for every possible l2 dist between blocks // additional optimization of precalced weights to replace division(averaging) by binary shift CV_Assert(template_window_size_ <= 46340); // sqrt(INT_MAX) int template_window_size_sq = template_window_size_ * template_window_size_; almost_template_window_size_sq_bin_shift_ = getNearestPowerOf2(template_window_size_sq); double almost_dist2actual_dist_multiplier = ((double)(1 << almost_template_window_size_sq_bin_shift_)) / template_window_size_sq; int max_dist = D::template maxDist<T>(); int almost_max_dist = (int)(max_dist / almost_dist2actual_dist_multiplier + 1); almost_dist2weight_.resize(almost_max_dist); for (int almost_dist = 0; almost_dist < almost_max_dist; almost_dist++) { double dist = almost_dist * almost_dist2actual_dist_multiplier; almost_dist2weight_[almost_dist] = D::template calcWeight<T, WT>(dist, h, fixed_point_mult_); } // additional optimization init end if (dst_.empty()) dst_ = Mat::zeros(src_.size(), src_.type()); } template <typename T, typename IT, typename UIT, typename D, typename WT> void FastNlMeansDenoisingInvoker<T, IT, UIT, D, WT>::operator() (const Range& range) const { int row_from = range.start; int row_to = range.end - 1; // sums of cols anf rows for current pixel p Array2d<int> dist_sums(search_window_size_, search_window_size_); // for lazy calc optimization (sum of cols for current pixel) Array3d<int> col_dist_sums(template_window_size_, search_window_size_, search_window_size_); int first_col_num = -1; // last elements of column sum (for each element in row) Array3d<int> up_col_dist_sums(src_.cols, search_window_size_, search_window_size_); for (int i = row_from; i <= row_to; i++) { for (int j = 0; j < src_.cols; j++) { int search_window_y = i - search_window_half_size_; int search_window_x = j - search_window_half_size_; // calc dist_sums if (j == 0) { calcDistSumsForFirstElementInRow(i, dist_sums, col_dist_sums, up_col_dist_sums); first_col_num = 0; } else { // calc cur dist_sums using previous dist_sums if (i == row_from) { calcDistSumsForElementInFirstRow(i, j, first_col_num, dist_sums, col_dist_sums, up_col_dist_sums); } else { int ay = border_size_ + i; int ax = border_size_ + j + template_window_half_size_; int start_by = border_size_ + i - search_window_half_size_; int start_bx = border_size_ + j - search_window_half_size_ + template_window_half_size_; T a_up = extended_src_.at<T>(ay - template_window_half_size_ - 1, ax); T a_down = extended_src_.at<T>(ay + template_window_half_size_, ax); // copy class member to local variable for optimization int search_window_size = search_window_size_; for (int y = 0; y < search_window_size; y++) { int * dist_sums_row = dist_sums.row_ptr(y); int * col_dist_sums_row = col_dist_sums.row_ptr(first_col_num, y); int * up_col_dist_sums_row = up_col_dist_sums.row_ptr(j, y); const T * b_up_ptr = extended_src_.ptr<T>(start_by - template_window_half_size_ - 1 + y); const T * b_down_ptr = extended_src_.ptr<T>(start_by + template_window_half_size_ + y); // MSVC 2015 generates unaligned destination for "movaps" instruction for 32-bit builds #if defined _MSC_VER && _MSC_VER == 1900 && !defined _WIN64 #pragma loop(no_vector) #endif for (int x = 0; x < search_window_size; x++) { // remove from current pixel sum column sum with index "first_col_num" dist_sums_row[x] -= col_dist_sums_row[x]; int bx = start_bx + x; col_dist_sums_row[x] = up_col_dist_sums_row[x] + D::template calcUpDownDist<T>(a_up, a_down, b_up_ptr[bx], b_down_ptr[bx]); dist_sums_row[x] += col_dist_sums_row[x]; up_col_dist_sums_row[x] = col_dist_sums_row[x]; } } } first_col_num = (first_col_num + 1) % template_window_size_; } // calc weights IT estimation[pixelInfo<T>::channels], weights_sum[pixelInfo<WT>::channels]; for (int channel_num = 0; channel_num < pixelInfo<T>::channels; channel_num++) estimation[channel_num] = 0; for (int channel_num = 0; channel_num < pixelInfo<WT>::channels; channel_num++) weights_sum[channel_num] = 0; for (int y = 0; y < search_window_size_; y++) { const T* cur_row_ptr = extended_src_.ptr<T>(border_size_ + search_window_y + y); int* dist_sums_row = dist_sums.row_ptr(y); for (int x = 0; x < search_window_size_; x++) { int almostAvgDist = dist_sums_row[x] >> almost_template_window_size_sq_bin_shift_; WT weight = almost_dist2weight_[almostAvgDist]; T p = cur_row_ptr[border_size_ + search_window_x + x]; incWithWeight<T, IT, WT>(estimation, weights_sum, weight, p); } } divByWeightsSum<IT, UIT, pixelInfo<T>::channels, pixelInfo<WT>::channels>(estimation, weights_sum); dst_.at<T>(i,j) = saturateCastFromArray<T, IT>(estimation); } } } template <typename T, typename IT, typename UIT, typename D, typename WT> inline void FastNlMeansDenoisingInvoker<T, IT, UIT, D, WT>::calcDistSumsForFirstElementInRow( int i, Array2d<int>& dist_sums, Array3d<int>& col_dist_sums, Array3d<int>& up_col_dist_sums) const { int j = 0; for (int y = 0; y < search_window_size_; y++) for (int x = 0; x < search_window_size_; x++) { dist_sums[y][x] = 0; for (int tx = 0; tx < template_window_size_; tx++) col_dist_sums[tx][y][x] = 0; int start_y = i + y - search_window_half_size_; int start_x = j + x - search_window_half_size_; for (int ty = -template_window_half_size_; ty <= template_window_half_size_; ty++) for (int tx = -template_window_half_size_; tx <= template_window_half_size_; tx++) { int dist = D::template calcDist<T>(extended_src_, border_size_ + i + ty, border_size_ + j + tx, border_size_ + start_y + ty, border_size_ + start_x + tx); dist_sums[y][x] += dist; col_dist_sums[tx + template_window_half_size_][y][x] += dist; } up_col_dist_sums[j][y][x] = col_dist_sums[template_window_size_ - 1][y][x]; } } template <typename T, typename IT, typename UIT, typename D, typename WT> inline void FastNlMeansDenoisingInvoker<T, IT, UIT, D, WT>::calcDistSumsForElementInFirstRow( int i, int j, int first_col_num, Array2d<int>& dist_sums, Array3d<int>& col_dist_sums, Array3d<int>& up_col_dist_sums) const { int ay = border_size_ + i; int ax = border_size_ + j + template_window_half_size_; int start_by = border_size_ + i - search_window_half_size_; int start_bx = border_size_ + j - search_window_half_size_ + template_window_half_size_; int new_last_col_num = first_col_num; for (int y = 0; y < search_window_size_; y++) for (int x = 0; x < search_window_size_; x++) { dist_sums[y][x] -= col_dist_sums[first_col_num][y][x]; col_dist_sums[new_last_col_num][y][x] = 0; int by = start_by + y; int bx = start_bx + x; for (int ty = -template_window_half_size_; ty <= template_window_half_size_; ty++) col_dist_sums[new_last_col_num][y][x] += D::template calcDist<T>(extended_src_, ay + ty, ax, by + ty, bx); dist_sums[y][x] += col_dist_sums[new_last_col_num][y][x]; up_col_dist_sums[j][y][x] = col_dist_sums[new_last_col_num][y][x]; } } #endif <|endoftext|>
<commit_before>#include "Processor.h" #include "Config.h" #include "Controller.h" #include "SpeedyController.h" #include "Memory.h" #include "DRAM.h" #include "Statistics.h" #include <cstdio> #include <cstdlib> #include <cstring> #include <stdlib.h> #include <functional> #include <map> /* Standards */ #include "Gem5Wrapper.h" #include "DDR3.h" #include "DDR4.h" #include "DSARP.h" #include "GDDR5.h" #include "LPDDR3.h" #include "LPDDR4.h" #include "WideIO.h" #include "WideIO2.h" #include "HBM.h" #include "SALP.h" #include "ALDRAM.h" #include "TLDRAM.h" using namespace std; using namespace ramulator; template<typename T> void run_dramtrace(const Config& configs, Memory<T, Controller>& memory, const char* tracename) { /* initialize DRAM trace */ Trace trace(tracename); /* run simulation */ bool stall = false, end = false; int reads = 0, writes = 0, clks = 0; long addr = 0; Request::Type type = Request::Type::READ; map<int, int> latencies; auto read_complete = [&latencies](Request& r){latencies[r.depart - r.arrive]++;}; Request req(addr, type, read_complete); while (!end || memory.pending_requests()){ if (!end && !stall){ end = !trace.get_request(addr, type); } if (!end){ req.addr = addr; req.type = type; stall = !memory.send(req); if (!stall){ if (type == Request::Type::READ) reads++; else if (type == Request::Type::WRITE) writes++; } } memory.tick(); clks ++; Stats::curTick++; // memory clock, global, for Statistics } // This a workaround for statistics set only initially lost in the end memory.finish(); Stats::statlist.printall(); } template <typename T> void run_cputrace(const Config& configs, Memory<T, Controller>& memory, const char * file) { int cpu_tick = configs.get_cpu_tick(); int mem_tick = configs.get_mem_tick(); auto send = bind(&Memory<T, Controller>::send, &memory, placeholders::_1); Processor proc(configs, file, send); for (long i = 0; ; i++) { proc.tick(); Stats::curTick++; // processor clock, global, for Statistics if (i % cpu_tick == (cpu_tick - 1)) for (int j = 0; j < mem_tick; j++) memory.tick(); if (configs.is_early_exit()) { if (proc.finished()) break; } else { if (proc.finished() && (memory.pending_requests() == 0)) break; } } // This a workaround for statistics set only initially lost in the end memory.finish(); Stats::statlist.printall(); } template<typename T> void start_run(const Config& configs, T* spec, const char* file) { // initiate controller and memory int C = configs.get_channels(), R = configs.get_ranks(); // Check and Set channel, rank number spec->set_channel_number(C); spec->set_rank_number(R); std::vector<Controller<T>*> ctrls; for (int c = 0 ; c < C ; c++) { DRAM<T>* channel = new DRAM<T>(spec, T::Level::Channel); channel->id = c; channel->regStats(""); Controller<T>* ctrl = new Controller<T>(configs, channel); ctrls.push_back(ctrl); } Memory<T, Controller> memory(configs, ctrls); if (configs["trace_type"] == "CPU") { run_cputrace(configs, memory, file); } else if (configs["trace_type"] == "DRAM") { run_dramtrace(configs, memory, file); } } int main(int argc, const char *argv[]) { if (argc < 2) { printf("Usage: %s <configs-file> --mode=cpu,dram [--stats <filename>] <trace-filename>\n" "Example: %s ramulator-configs.cfg cpu.trace\n", argv[0], argv[0]); return 0; } Config configs(argv[1]); const std::string& standard = configs["standard"]; assert(standard != "" || "DRAM standard should be specified."); char *trace_type = strstr(argv[2], "="); trace_type++; if (strcmp(trace_type, "cpu") == 0) { configs.add("trace_type", "CPU"); } else if (strcmp(trace_type, "mem") == 0) { configs.add("trace_type", "DRAM"); } else { printf("invalid trace type: %s\n", trace_type); assert(false); } int trace_start = 3; string stats_out; if (strcmp(argv[3], "--stats") == 0) { Stats::statlist.output(argv[4]); stats_out = argv[4]; trace_start = 5; } else { Stats::statlist.output(standard+".stats"); stats_out = standard + string(".stats"); } const char* file = argv[trace_start]; if (standard == "DDR3") { DDR3* ddr3 = new DDR3(configs["org"], configs["speed"]); start_run(configs, ddr3, file); } else if (standard == "DDR4") { DDR4* ddr4 = new DDR4(configs["org"], configs["speed"]); start_run(configs, ddr4, file); } else if (standard == "SALP-MASA") { SALP* salp8 = new SALP(configs["org"], configs["speed"], "SALP-MASA", configs.get_subarrays()); start_run(configs, salp8, file); } else if (standard == "LPDDR3") { LPDDR3* lpddr3 = new LPDDR3(configs["org"], configs["speed"]); start_run(configs, lpddr3, file); } else if (standard == "LPDDR4") { // total cap: 2GB, 1/2 of others LPDDR4* lpddr4 = new LPDDR4(configs["org"], configs["speed"]); start_run(configs, lpddr4, file); } else if (standard == "GDDR5") { GDDR5* gddr5 = new GDDR5(configs["org"], configs["speed"]); start_run(configs, gddr5, file); } else if (standard == "HBM") { HBM* hbm = new HBM(configs["org"], configs["speed"]); start_run(configs, hbm, file); } else if (standard == "WideIO") { // total cap: 1GB, 1/4 of others WideIO* wio = new WideIO(configs["org"], configs["speed"]); start_run(configs, wio, file); } else if (standard == "WideIO2") { // total cap: 2GB, 1/2 of others WideIO2* wio2 = new WideIO2(configs["org"], configs["speed"], configs.get_channels()); wio2->channel_width *= 2; start_run(configs, wio2, file); } // Various refresh mechanisms else if (standard == "DSARP") { DSARP* dsddr3_dsarp = new DSARP(configs["org"], configs["speed"], DSARP::Type::DSARP, configs.get_subarrays()); start_run(configs, dsddr3_dsarp, file); } else if (standard == "ALDRAM") { ALDRAM* aldram = new ALDRAM(configs["org"], configs["speed"]); start_run(configs, aldram, file); } else if (standard == "TLDRAM") { TLDRAM* tldram = new TLDRAM(configs["org"], configs["speed"], configs.get_subarrays()); start_run(configs, tldram, file); } printf("Simulation done. Statistics written to %s\n", stats_out.c_str()); return 0; } <commit_msg>Fix compile error when assign const char* to char*<commit_after>#include "Processor.h" #include "Config.h" #include "Controller.h" #include "SpeedyController.h" #include "Memory.h" #include "DRAM.h" #include "Statistics.h" #include <cstdio> #include <cstdlib> #include <cstring> #include <stdlib.h> #include <functional> #include <map> /* Standards */ #include "Gem5Wrapper.h" #include "DDR3.h" #include "DDR4.h" #include "DSARP.h" #include "GDDR5.h" #include "LPDDR3.h" #include "LPDDR4.h" #include "WideIO.h" #include "WideIO2.h" #include "HBM.h" #include "SALP.h" #include "ALDRAM.h" #include "TLDRAM.h" using namespace std; using namespace ramulator; template<typename T> void run_dramtrace(const Config& configs, Memory<T, Controller>& memory, const char* tracename) { /* initialize DRAM trace */ Trace trace(tracename); /* run simulation */ bool stall = false, end = false; int reads = 0, writes = 0, clks = 0; long addr = 0; Request::Type type = Request::Type::READ; map<int, int> latencies; auto read_complete = [&latencies](Request& r){latencies[r.depart - r.arrive]++;}; Request req(addr, type, read_complete); while (!end || memory.pending_requests()){ if (!end && !stall){ end = !trace.get_request(addr, type); } if (!end){ req.addr = addr; req.type = type; stall = !memory.send(req); if (!stall){ if (type == Request::Type::READ) reads++; else if (type == Request::Type::WRITE) writes++; } } memory.tick(); clks ++; Stats::curTick++; // memory clock, global, for Statistics } // This a workaround for statistics set only initially lost in the end memory.finish(); Stats::statlist.printall(); } template <typename T> void run_cputrace(const Config& configs, Memory<T, Controller>& memory, const char * file) { int cpu_tick = configs.get_cpu_tick(); int mem_tick = configs.get_mem_tick(); auto send = bind(&Memory<T, Controller>::send, &memory, placeholders::_1); Processor proc(configs, file, send); for (long i = 0; ; i++) { proc.tick(); Stats::curTick++; // processor clock, global, for Statistics if (i % cpu_tick == (cpu_tick - 1)) for (int j = 0; j < mem_tick; j++) memory.tick(); if (configs.is_early_exit()) { if (proc.finished()) break; } else { if (proc.finished() && (memory.pending_requests() == 0)) break; } } // This a workaround for statistics set only initially lost in the end memory.finish(); Stats::statlist.printall(); } template<typename T> void start_run(const Config& configs, T* spec, const char* file) { // initiate controller and memory int C = configs.get_channels(), R = configs.get_ranks(); // Check and Set channel, rank number spec->set_channel_number(C); spec->set_rank_number(R); std::vector<Controller<T>*> ctrls; for (int c = 0 ; c < C ; c++) { DRAM<T>* channel = new DRAM<T>(spec, T::Level::Channel); channel->id = c; channel->regStats(""); Controller<T>* ctrl = new Controller<T>(configs, channel); ctrls.push_back(ctrl); } Memory<T, Controller> memory(configs, ctrls); if (configs["trace_type"] == "CPU") { run_cputrace(configs, memory, file); } else if (configs["trace_type"] == "DRAM") { run_dramtrace(configs, memory, file); } } int main(int argc, const char *argv[]) { if (argc < 2) { printf("Usage: %s <configs-file> --mode=cpu,dram [--stats <filename>] <trace-filename>\n" "Example: %s ramulator-configs.cfg cpu.trace\n", argv[0], argv[0]); return 0; } Config configs(argv[1]); const std::string& standard = configs["standard"]; assert(standard != "" || "DRAM standard should be specified."); const char *trace_type = strstr(argv[2], "="); trace_type++; if (strcmp(trace_type, "cpu") == 0) { configs.add("trace_type", "CPU"); } else if (strcmp(trace_type, "mem") == 0) { configs.add("trace_type", "DRAM"); } else { printf("invalid trace type: %s\n", trace_type); assert(false); } int trace_start = 3; string stats_out; if (strcmp(argv[3], "--stats") == 0) { Stats::statlist.output(argv[4]); stats_out = argv[4]; trace_start = 5; } else { Stats::statlist.output(standard+".stats"); stats_out = standard + string(".stats"); } const char* file = argv[trace_start]; if (standard == "DDR3") { DDR3* ddr3 = new DDR3(configs["org"], configs["speed"]); start_run(configs, ddr3, file); } else if (standard == "DDR4") { DDR4* ddr4 = new DDR4(configs["org"], configs["speed"]); start_run(configs, ddr4, file); } else if (standard == "SALP-MASA") { SALP* salp8 = new SALP(configs["org"], configs["speed"], "SALP-MASA", configs.get_subarrays()); start_run(configs, salp8, file); } else if (standard == "LPDDR3") { LPDDR3* lpddr3 = new LPDDR3(configs["org"], configs["speed"]); start_run(configs, lpddr3, file); } else if (standard == "LPDDR4") { // total cap: 2GB, 1/2 of others LPDDR4* lpddr4 = new LPDDR4(configs["org"], configs["speed"]); start_run(configs, lpddr4, file); } else if (standard == "GDDR5") { GDDR5* gddr5 = new GDDR5(configs["org"], configs["speed"]); start_run(configs, gddr5, file); } else if (standard == "HBM") { HBM* hbm = new HBM(configs["org"], configs["speed"]); start_run(configs, hbm, file); } else if (standard == "WideIO") { // total cap: 1GB, 1/4 of others WideIO* wio = new WideIO(configs["org"], configs["speed"]); start_run(configs, wio, file); } else if (standard == "WideIO2") { // total cap: 2GB, 1/2 of others WideIO2* wio2 = new WideIO2(configs["org"], configs["speed"], configs.get_channels()); wio2->channel_width *= 2; start_run(configs, wio2, file); } // Various refresh mechanisms else if (standard == "DSARP") { DSARP* dsddr3_dsarp = new DSARP(configs["org"], configs["speed"], DSARP::Type::DSARP, configs.get_subarrays()); start_run(configs, dsddr3_dsarp, file); } else if (standard == "ALDRAM") { ALDRAM* aldram = new ALDRAM(configs["org"], configs["speed"]); start_run(configs, aldram, file); } else if (standard == "TLDRAM") { TLDRAM* tldram = new TLDRAM(configs["org"], configs["speed"], configs.get_subarrays()); start_run(configs, tldram, file); } printf("Simulation done. Statistics written to %s\n", stats_out.c_str()); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <opencv2/opencv.hpp> #include "DB.hpp" #include "Image.hpp" #include "Mosaic.hpp" int main() { // Setup directory and folder paths, no recursive solution yet string image_name = "zlatan_blue_background_1920x1080.jpg"; // ----> Directory for: KRISTOFER <----- //string mainDirectory = "C:/Users/StoffesBok/Bilddatabaser_TNM025/dataset/"; //cv::Mat image_temp = imread("C:/Users/StoffesBok/Bilddatabaser_TNM025/dataset/zlatan/zlatan_blue_background_1920x1080.jpg", 1); // ----> Directory for: GABRIEL <----- //string mainDirectory = "C:/Users/Gabriel/Desktop/Bildatabaser/Bilddatabaser_TNM025/dataset/"; //cv::Mat image_temp = imread("C:/Users/Gabriel/Desktop/Bildatabaser/Bilddatabaser_TNM025/dataset/zlatan/" + image_name, 1); if (!image_temp.data){ cout << "Zlatan is too big!" << endl; return -1; } vector<string> inputFolders = { "animal2", "beach2", "cat2", "colorful2", "doll2", "elegant2", "flower2", "food2", "formal2", "garden2" }; vector<string> animalFolder = { "animal2" }; // Initilize the database DB database = DB(); database.loadImages(mainDirectory, inputFolders); DB zlatan_DB = DB(image_temp, 32); zlatan_DB.reconstructImageFromDB(zlatan_DB, image_name); // A test for color histogram /*Mat src = imread("test.png", 1) cout << "Total: " << src.total() << endl; int r_bins = 2; int g_bins = 2; int b_bins = 2; const int hist_size[] = { r_bins, g_bins, b_bins }; float r_range[] = { 0, 255 }; float g_range[] = { 0, 255 }; float b_range[] = { 0, 255 }; const float *hist_range[] = { r_range, g_range, b_range }; cv::Mat histos; bool uniform = true; bool accumulate = false; int channels[] = { 0, 1, 2 }; // Check if channels and dims is correct calcHist(&src, 1, channels, Mat(), histos, 3, hist_size, hist_range, uniform, accumulate); //cout << "size" << histos.size[0] << endl; //cout << " x " << histos.size[1] << endl; //cout << " x " << histos.size[2] << endl; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { cout << "B: " << i << endl; cout << "G: " << j << endl; cout << "R: " << k << endl; cout << histos.at<Vec3b>(i, j, k) << " " << endl; } } } */ system("pause"); return 0; }<commit_msg>Testing different histogram format<commit_after>#include <iostream> #include <opencv2/opencv.hpp> #include "DB.hpp" #include "Image.hpp" #include "Mosaic.hpp" int main() { // Setup directory and folder paths, no recursive solution yet string image_name = "zlatan_blue_background_1920x1080.jpg"; // ----> Directory for: KRISTOFER <----- //string mainDirectory = "C:/Users/StoffesBok/Bilddatabaser_TNM025/dataset/"; //cv::Mat image_temp = imread("C:/Users/StoffesBok/Bilddatabaser_TNM025/dataset/zlatan/zlatan_blue_background_1920x1080.jpg", 1); // ----> Directory for: GABRIEL <----- string mainDirectory = "C:/Users/Gabriel/Desktop/Bildatabaser/Bilddatabaser_TNM025/dataset/"; cv::Mat image_temp = imread("C:/Users/Gabriel/Desktop/Bildatabaser/Bilddatabaser_TNM025/dataset/zlatan/" + image_name, 1); if (!image_temp.data){ cout << "Zlatan is too big!" << endl; return -1; } //vector<string> inputFolders = { "animal2", "beach2", "cat2", "colorful2", // "doll2", "elegant2", "flower2", "food2", "formal2", "garden2" }; //vector<string> animalFolder = { "animal2" }; // Initilize the database //DB database = DB(); //database.loadImages(mainDirectory, inputFolders); // //DB zlatan_DB = DB(image_temp, 32); //zlatan_DB.reconstructImageFromDB(zlatan_DB, image_name); // A test for color histogram Mat src = imread("test.png", 1); int r_bins = 4; int g_bins = 4; int b_bins = 4; const int hist_size[] = { r_bins, g_bins, b_bins }; float r_range[] = { 0, 255 }; float g_range[] = { 0, 255 }; float b_range[] = { 0, 255 }; const float *hist_range[] = { r_range, g_range, b_range }; cv::Mat histos; histos.create(3, hist_size, CV_32F); bool uniform = true; bool accumulate = false; int channels[] = { 0, 1, 2 }; // Check if channels and dims is correct calcHist(&src, 1, channels, Mat(), histos, 3, hist_size, hist_range, uniform, accumulate); //cout << "size" << histos.size[0] << endl; //cout << " x " << histos.size[1] << endl; //cout << " x " << histos.size[2] << endl; vector<Mat> histoVec; split(histos, histoVec); cout << histoVec[0].size(); for (int i = 0; i < r_bins; i++) { for (int j = 0; j < g_bins; j++) { cout << histoVec[0].data[histoVec[0].channels()*histoVec[0].cols*i + j] << " "; } } //for (int i = 0; i < r_bins; i++) //{ // for (int j = 0; j < g_bins; j++) // { // for (int k = 0; k < b_bins; k++) // { // cout << histoVec[0].at<float>(i, j, k) << " "; // } // } //} system("pause"); return 0; }<|endoftext|>
<commit_before>#include "Note.h" #include <math.h> namespace rparser { const char *kNoteTypesStr[] = { "NONE", "NOTE", "TOUCH", "KNOB", "BGM", "BGA", "TEMPO", "SPECIAL", }; const char *kNoteSubTypesStr[] = { "NORMAL", "INVISIBLE", "LONGNOTE", "CHARGE", "HCHARGE", "MINE", "AUTO", "FAKE", "COMBO", "DRAG", "CHAIN", "REPEAT", }; const char *kNoteTempoTypesStr[] = { "BPM", "STOP", "WARP", "SCROLL", "MEASURE", "TICK", "BMSBPM", "BMSSTOP", }; const char *kNoteBgaTypesStr[] = { "MAINBGA", "MISSBGA", "LAYER1", "LAYER2", "LAYER3", "LAYER4", "LAYER5", "LAYER6", "LAYER7", "LAYER8", "LAYER9", "LAYER10", }; const char *kNoteSpecialTypesStr[] = { "REST", "BMSKEYBIND", "BMSEXTCHR", "BMSTEXT", "BMSOPTION", "BMSARGBBASE", "BMSARGBMISS", "BGAARGBLAYER1", "BGAARGBLAYER2", }; const char **pNoteSubtypeStr[] = { kNoteSubTypesStr, kNoteTempoTypesStr, kNoteBgaTypesStr, kNoteSpecialTypesStr, }; NotePos::NotePos() : type(NotePosTypes::NullPos), time_msec(0), beat(0), measure(0), denominator(8) {} void NotePos::SetRowPos(uint32_t measure, RowPos deno, RowPos num) { if (deno == 0) SetRowPos(measure); else SetRowPos(measure + (double)num / deno); } void NotePos::SetRowPos(double barpos) { type = NotePosTypes::Bar; this->measure = barpos; } void NotePos::SetBeatPos(double beat) { type = NotePosTypes::Beat; this->beat = beat; } void NotePos::SetTimePos(double time_msec) { type = NotePosTypes::Time; this->time_msec = time_msec; } void NotePos::SetDenominator(uint32_t denominator) { this->denominator = denominator; } std::string NotePos::toString() const { std::stringstream ss; int32_t num = 0; switch (type) { case NotePosTypes::NullPos: ss << "(No note pos set)" << std::endl; break; case NotePosTypes::Beat: ss << "Beat: " << beat << "(Deno " << denominator << ")" << std::endl; break; case NotePosTypes::Time: ss << "Time: " << time_msec << "(Deno " << denominator << ")" << std::endl; break; case NotePosTypes::Bar: // recalculate numerator of Row num = static_cast<int32_t>(lround(measure * denominator) % denominator); ss << "Row: " << (static_cast<int32_t>(measure) % 1) << " " << num << "/" << denominator << std::endl; break; } return ss.str(); } std::string Note::toString() const { std::stringstream ss; std::string sType, sSubtype; sType = kNoteTypesStr[type_]; sSubtype = pNoteSubtypeStr[type_][subtype_]; ss << "[Object Note]\n"; ss << "type/subtype: " << sType << "," << sSubtype << std::endl; ss << NotePos::toString(); ss << getValueAsString(); return ss.str(); } NotePos& NotePos::pos() { return *this; } const NotePos& NotePos::pos() const { return const_cast<NotePos*>(this)->pos(); } NotePosTypes NotePos::postype() const { return type; } double NotePos::GetBeatPos() const { return beat; } double NotePos::GetTimePos() const { return time_msec; } bool NotePos::operator<(const NotePos &other) const noexcept { return beat < other.beat; } bool NotePos::operator==(const NotePos &other) const noexcept { return beat == other.beat; } #if 0 bool NotePos::operator==(const NotePos &other) const noexcept { if (type != other.type) return false; switch (type) { case NotePosTypes::Beat: return beat == other.beat; case NotePosTypes::Time: return time_msec == other.time_msec; default: ASSERT(0); return false; } } #endif Note::Note() : NotePos(), type_(0), subtype_(0), is_conditional_object_(0) { } NoteType Note::type() const { return type_; } NoteType Note::subtype() const { return subtype_; } void Note::set_type(NoteType t) { type_ = t; } void Note::set_subtype(NoteType t) { subtype_ = t; } bool Note::operator==(const Note &other) const noexcept { return NotePos::operator==(other) && type() == other.type() && subtype() == other.subtype(); } SoundNote::SoundNote() : value(0), channel_type(0), effect{ 0, 0, 1.0f, false } { SetAsBGM(0); } void SoundNote::SetAsBGM(uint8_t col) { set_type(NoteTypes::kBGM); track.lane.note.player = 0; track.lane.note.lane = col; } void SoundNote::SetAsTouchNote() { set_type(NoteTypes::kTouch); } void SoundNote::SetAsTapNote(uint8_t player, uint8_t lane) { set_type(NoteTypes::kTap); set_subtype(NoteSubTypes::kNormalNote); track.lane.note.player = player; track.lane.note.lane = lane; } void SoundNote::SetAsChainNote() { set_subtype(NoteSubTypes::kLongNote); } void SoundNote::SetMidiNote(float duration_ms, int32_t key, float volume) { effect.duration_ms = duration_ms; effect.key = key; effect.volume = volume; channel_type = 1; // mark source as MIDI } void SoundNote::SetLongnoteLength(double delta_value) { ASSERT(type() == NoteTypes::kTap || type() == NoteTypes::kTouch); if (!IsLongnote()) chains.emplace_back(NoteChain{ track, *this, 0 }); switch (postype()) { case NotePosTypes::Beat: chains.back().pos.SetBeatPos(pos().beat + delta_value); break; case NotePosTypes::Bar: chains.back().pos.SetRowPos(pos().measure + delta_value); break; case NotePosTypes::Time: chains.back().pos.SetTimePos(pos().time_msec + delta_value); break; } } void SoundNote::SetLongnoteEndPos(const NotePos& row_pos) { ASSERT(type() == NoteTypes::kTap || type() == NoteTypes::kTouch); if (!IsLongnote()) chains.emplace_back(NoteChain{ track, *this, 0 }); chains.back().pos = row_pos; } void SoundNote::SetLongnoteEndValue(Channel v) { ASSERT(type() == NoteTypes::kTap || type() == NoteTypes::kTouch); if (!IsLongnote()) chains.emplace_back(NoteChain{ track, *this, 0 }); chains.back().value = v; } void SoundNote::AddChain(const NotePos& pos, uint8_t col) { ASSERT(type() == NoteTypes::kTap || type() == NoteTypes::kTouch); NoteTrack track; track.lane.note.player = 0; track.lane.note.lane = col; chains.emplace_back(NoteChain{ track, pos, 0 }); } void SoundNote::AddTouch(const NotePos& pos, uint8_t x, uint8_t y) { ASSERT(type() == NoteTypes::kTouch); NoteTrack track; track.lane.touch.x = x; track.lane.touch.y = y; chains.emplace_back(NoteChain{ track, pos, 0 }); } void SoundNote::ClearChain() { chains.clear(); } bool SoundNote::IsLongnote() const { return chains.size() > 0; } bool SoundNote::IsScoreable() const { return type() == NoteTypes::kTap || type() == NoteTypes::kTouch; } uint8_t SoundNote::GetPlayer() const { return track.lane.note.player; } uint8_t SoundNote::GetLane() const { return track.lane.note.lane; } uint8_t SoundNote::GetBGMCol() const { return track.lane.note.lane; } uint8_t SoundNote::GetX() const { return track.lane.touch.x; } uint8_t SoundNote::GetY() const { return track.lane.touch.y; } NotePos& SoundNote::endpos() { if (!IsLongnote()) return pos(); else return chains.back().pos; } const NotePos& SoundNote::endpos() const { return const_cast<SoundNote*>(this)->endpos(); } std::string SoundNote::getValueAsString() const { std::stringstream ss; ss << "Track (note - player, lane): " << track.lane.note.player << "," << track.lane.note.lane << std::endl; ss << "Track (touch - x, y): " << track.lane.touch.x << "," << track.lane.touch.y << std::endl; ss << "Volume: " << effect.volume << std::endl; ss << "Key (Pitch): " << effect.key << std::endl; ss << "Restart (sound) ?: " << effect.restart << std::endl; return ss.str(); } bool SoundNote::operator==(const SoundNote &other) const noexcept { return Note::operator==(other) && value == other.value; } std::string EventNote::getValueAsString() const { std::stringstream ss; ss << "Command: " << command_; if (arg1_) ss << ", arg1: " << arg1_; if (arg2_) ss << ", arg2: " << arg2_; ss << std::endl; return ss.str(); } EventNote::EventNote() : command_(0), arg1_(0), arg2_(0) { set_type(NoteTypes::kEvent); } void EventNote::SetBga(BgaTypes bgatype, Channel channel, uint8_t column) { set_subtype(NoteEventTypes::kBGA); command_ = bgatype; arg1_ = static_cast<decltype(arg1_)>(channel); arg2_ = column; } void EventNote::SetMidiCommand(uint8_t command, uint8_t arg1, uint8_t arg2) { set_subtype(NoteEventTypes::kMIDI); command_ = command; arg1_ = arg1; arg2_ = arg2; } void EventNote::SetBmsARGBCommand(BgaTypes bgatype, Channel channel) { set_subtype(NoteEventTypes::kBmsARGBLAYER); command_ = bgatype; arg1_ = static_cast<decltype(arg1_)>(channel); arg2_ = 0; } void EventNote::GetMidiCommand(uint8_t &command, uint8_t &arg1, uint8_t &arg2) const { ASSERT(type() == NoteEventTypes::kMIDI); command = (uint8_t)command_; arg1 = (uint8_t)arg1_; arg2 = (uint8_t)arg2_; } bool EventNote::operator==(const EventNote &other) const noexcept { return Note::operator==(other) && command_ == other.command_ && arg1_ == other.arg1_ && arg2_ == other.arg2_; } TempoNote::TempoNote() { set_type(NoteTypes::kTempo); } void TempoNote::SetBpm(float bpm) { set_subtype(NoteTempoTypes::kBpm); value.f = bpm; } void TempoNote::SetBmsBpm(Channel bms_channel) { set_subtype(NoteTempoTypes::kBmsBpm); value.i = bms_channel; } void TempoNote::SetStop(float stop) { set_subtype(NoteTempoTypes::kStop); value.f = stop; } void TempoNote::SetBmsStop(Channel bms_channel) { set_subtype(NoteTempoTypes::kBmsStop); value.i = bms_channel; } void TempoNote::SetMeasure(float measure_length) { set_subtype(NoteTempoTypes::kMeasure); value.f = measure_length; } void TempoNote::SetScroll(float scrollspeed) { set_subtype(NoteTempoTypes::kScroll); value.f = scrollspeed; } void TempoNote::SetTick(int32_t tick) { set_subtype(NoteTempoTypes::kTick); value.i = tick; } void TempoNote::SetWarp(float warp_to) { set_subtype(NoteTempoTypes::kWarp); value.f = warp_to; } float TempoNote::GetFloatValue() const { return value.f; } int32_t TempoNote::GetIntValue() const { return value.i; } std::string TempoNote::getValueAsString() const { std::stringstream ss; ss << "Value (float): " << value.f << std::endl; ss << "Value (int): " << value.i << std::endl; return ss.str(); } bool TempoNote::operator==(const TempoNote &other) const noexcept { return Note::operator==(other) && value.i == other.value.i && value.f == other.value.f; } } <commit_msg>Bugfix: GetMidiCommand() sigsegv when fetching midi object<commit_after>#include "Note.h" #include <math.h> namespace rparser { const char *kNoteTypesStr[] = { "NONE", "NOTE", "TOUCH", "KNOB", "BGM", "BGA", "TEMPO", "SPECIAL", }; const char *kNoteSubTypesStr[] = { "NORMAL", "INVISIBLE", "LONGNOTE", "CHARGE", "HCHARGE", "MINE", "AUTO", "FAKE", "COMBO", "DRAG", "CHAIN", "REPEAT", }; const char *kNoteTempoTypesStr[] = { "BPM", "STOP", "WARP", "SCROLL", "MEASURE", "TICK", "BMSBPM", "BMSSTOP", }; const char *kNoteBgaTypesStr[] = { "MAINBGA", "MISSBGA", "LAYER1", "LAYER2", "LAYER3", "LAYER4", "LAYER5", "LAYER6", "LAYER7", "LAYER8", "LAYER9", "LAYER10", }; const char *kNoteSpecialTypesStr[] = { "REST", "BMSKEYBIND", "BMSEXTCHR", "BMSTEXT", "BMSOPTION", "BMSARGBBASE", "BMSARGBMISS", "BGAARGBLAYER1", "BGAARGBLAYER2", }; const char **pNoteSubtypeStr[] = { kNoteSubTypesStr, kNoteTempoTypesStr, kNoteBgaTypesStr, kNoteSpecialTypesStr, }; NotePos::NotePos() : type(NotePosTypes::NullPos), time_msec(0), beat(0), measure(0), denominator(8) {} void NotePos::SetRowPos(uint32_t measure, RowPos deno, RowPos num) { if (deno == 0) SetRowPos(measure); else SetRowPos(measure + (double)num / deno); } void NotePos::SetRowPos(double barpos) { type = NotePosTypes::Bar; this->measure = barpos; } void NotePos::SetBeatPos(double beat) { type = NotePosTypes::Beat; this->beat = beat; } void NotePos::SetTimePos(double time_msec) { type = NotePosTypes::Time; this->time_msec = time_msec; } void NotePos::SetDenominator(uint32_t denominator) { this->denominator = denominator; } std::string NotePos::toString() const { std::stringstream ss; int32_t num = 0; switch (type) { case NotePosTypes::NullPos: ss << "(No note pos set)" << std::endl; break; case NotePosTypes::Beat: ss << "Beat: " << beat << "(Deno " << denominator << ")" << std::endl; break; case NotePosTypes::Time: ss << "Time: " << time_msec << "(Deno " << denominator << ")" << std::endl; break; case NotePosTypes::Bar: // recalculate numerator of Row num = static_cast<int32_t>(lround(measure * denominator) % denominator); ss << "Row: " << (static_cast<int32_t>(measure) % 1) << " " << num << "/" << denominator << std::endl; break; } return ss.str(); } std::string Note::toString() const { std::stringstream ss; std::string sType, sSubtype; sType = kNoteTypesStr[type_]; sSubtype = pNoteSubtypeStr[type_][subtype_]; ss << "[Object Note]\n"; ss << "type/subtype: " << sType << "," << sSubtype << std::endl; ss << NotePos::toString(); ss << getValueAsString(); return ss.str(); } NotePos& NotePos::pos() { return *this; } const NotePos& NotePos::pos() const { return const_cast<NotePos*>(this)->pos(); } NotePosTypes NotePos::postype() const { return type; } double NotePos::GetBeatPos() const { return beat; } double NotePos::GetTimePos() const { return time_msec; } bool NotePos::operator<(const NotePos &other) const noexcept { return beat < other.beat; } bool NotePos::operator==(const NotePos &other) const noexcept { return beat == other.beat; } #if 0 bool NotePos::operator==(const NotePos &other) const noexcept { if (type != other.type) return false; switch (type) { case NotePosTypes::Beat: return beat == other.beat; case NotePosTypes::Time: return time_msec == other.time_msec; default: ASSERT(0); return false; } } #endif Note::Note() : NotePos(), type_(0), subtype_(0), is_conditional_object_(0) { } NoteType Note::type() const { return type_; } NoteType Note::subtype() const { return subtype_; } void Note::set_type(NoteType t) { type_ = t; } void Note::set_subtype(NoteType t) { subtype_ = t; } bool Note::operator==(const Note &other) const noexcept { return NotePos::operator==(other) && type() == other.type() && subtype() == other.subtype(); } SoundNote::SoundNote() : value(0), channel_type(0), effect{ 0, 0, 1.0f, false } { SetAsBGM(0); } void SoundNote::SetAsBGM(uint8_t col) { set_type(NoteTypes::kBGM); track.lane.note.player = 0; track.lane.note.lane = col; } void SoundNote::SetAsTouchNote() { set_type(NoteTypes::kTouch); } void SoundNote::SetAsTapNote(uint8_t player, uint8_t lane) { set_type(NoteTypes::kTap); set_subtype(NoteSubTypes::kNormalNote); track.lane.note.player = player; track.lane.note.lane = lane; } void SoundNote::SetAsChainNote() { set_subtype(NoteSubTypes::kLongNote); } void SoundNote::SetMidiNote(float duration_ms, int32_t key, float volume) { effect.duration_ms = duration_ms; effect.key = key; effect.volume = volume; channel_type = 1; // mark source as MIDI } void SoundNote::SetLongnoteLength(double delta_value) { ASSERT(type() == NoteTypes::kTap || type() == NoteTypes::kTouch); if (!IsLongnote()) chains.emplace_back(NoteChain{ track, *this, 0 }); switch (postype()) { case NotePosTypes::Beat: chains.back().pos.SetBeatPos(pos().beat + delta_value); break; case NotePosTypes::Bar: chains.back().pos.SetRowPos(pos().measure + delta_value); break; case NotePosTypes::Time: chains.back().pos.SetTimePos(pos().time_msec + delta_value); break; } } void SoundNote::SetLongnoteEndPos(const NotePos& row_pos) { ASSERT(type() == NoteTypes::kTap || type() == NoteTypes::kTouch); if (!IsLongnote()) chains.emplace_back(NoteChain{ track, *this, 0 }); chains.back().pos = row_pos; } void SoundNote::SetLongnoteEndValue(Channel v) { ASSERT(type() == NoteTypes::kTap || type() == NoteTypes::kTouch); if (!IsLongnote()) chains.emplace_back(NoteChain{ track, *this, 0 }); chains.back().value = v; } void SoundNote::AddChain(const NotePos& pos, uint8_t col) { ASSERT(type() == NoteTypes::kTap || type() == NoteTypes::kTouch); NoteTrack track; track.lane.note.player = 0; track.lane.note.lane = col; chains.emplace_back(NoteChain{ track, pos, 0 }); } void SoundNote::AddTouch(const NotePos& pos, uint8_t x, uint8_t y) { ASSERT(type() == NoteTypes::kTouch); NoteTrack track; track.lane.touch.x = x; track.lane.touch.y = y; chains.emplace_back(NoteChain{ track, pos, 0 }); } void SoundNote::ClearChain() { chains.clear(); } bool SoundNote::IsLongnote() const { return chains.size() > 0; } bool SoundNote::IsScoreable() const { return type() == NoteTypes::kTap || type() == NoteTypes::kTouch; } uint8_t SoundNote::GetPlayer() const { return track.lane.note.player; } uint8_t SoundNote::GetLane() const { return track.lane.note.lane; } uint8_t SoundNote::GetBGMCol() const { return track.lane.note.lane; } uint8_t SoundNote::GetX() const { return track.lane.touch.x; } uint8_t SoundNote::GetY() const { return track.lane.touch.y; } NotePos& SoundNote::endpos() { if (!IsLongnote()) return pos(); else return chains.back().pos; } const NotePos& SoundNote::endpos() const { return const_cast<SoundNote*>(this)->endpos(); } std::string SoundNote::getValueAsString() const { std::stringstream ss; ss << "Track (note - player, lane): " << track.lane.note.player << "," << track.lane.note.lane << std::endl; ss << "Track (touch - x, y): " << track.lane.touch.x << "," << track.lane.touch.y << std::endl; ss << "Volume: " << effect.volume << std::endl; ss << "Key (Pitch): " << effect.key << std::endl; ss << "Restart (sound) ?: " << effect.restart << std::endl; return ss.str(); } bool SoundNote::operator==(const SoundNote &other) const noexcept { return Note::operator==(other) && value == other.value; } std::string EventNote::getValueAsString() const { std::stringstream ss; ss << "Command: " << command_; if (arg1_) ss << ", arg1: " << arg1_; if (arg2_) ss << ", arg2: " << arg2_; ss << std::endl; return ss.str(); } EventNote::EventNote() : command_(0), arg1_(0), arg2_(0) { set_type(NoteTypes::kEvent); } void EventNote::SetBga(BgaTypes bgatype, Channel channel, uint8_t column) { set_subtype(NoteEventTypes::kBGA); command_ = bgatype; arg1_ = static_cast<decltype(arg1_)>(channel); arg2_ = column; } void EventNote::SetMidiCommand(uint8_t command, uint8_t arg1, uint8_t arg2) { set_subtype(NoteEventTypes::kMIDI); command_ = command; arg1_ = arg1; arg2_ = arg2; } void EventNote::SetBmsARGBCommand(BgaTypes bgatype, Channel channel) { set_subtype(NoteEventTypes::kBmsARGBLAYER); command_ = bgatype; arg1_ = static_cast<decltype(arg1_)>(channel); arg2_ = 0; } void EventNote::GetMidiCommand(uint8_t &command, uint8_t &arg1, uint8_t &arg2) const { ASSERT(subtype() == NoteEventTypes::kMIDI); command = (uint8_t)command_; arg1 = (uint8_t)arg1_; arg2 = (uint8_t)arg2_; } bool EventNote::operator==(const EventNote &other) const noexcept { return Note::operator==(other) && command_ == other.command_ && arg1_ == other.arg1_ && arg2_ == other.arg2_; } TempoNote::TempoNote() { set_type(NoteTypes::kTempo); } void TempoNote::SetBpm(float bpm) { set_subtype(NoteTempoTypes::kBpm); value.f = bpm; } void TempoNote::SetBmsBpm(Channel bms_channel) { set_subtype(NoteTempoTypes::kBmsBpm); value.i = bms_channel; } void TempoNote::SetStop(float stop) { set_subtype(NoteTempoTypes::kStop); value.f = stop; } void TempoNote::SetBmsStop(Channel bms_channel) { set_subtype(NoteTempoTypes::kBmsStop); value.i = bms_channel; } void TempoNote::SetMeasure(float measure_length) { set_subtype(NoteTempoTypes::kMeasure); value.f = measure_length; } void TempoNote::SetScroll(float scrollspeed) { set_subtype(NoteTempoTypes::kScroll); value.f = scrollspeed; } void TempoNote::SetTick(int32_t tick) { set_subtype(NoteTempoTypes::kTick); value.i = tick; } void TempoNote::SetWarp(float warp_to) { set_subtype(NoteTempoTypes::kWarp); value.f = warp_to; } float TempoNote::GetFloatValue() const { return value.f; } int32_t TempoNote::GetIntValue() const { return value.i; } std::string TempoNote::getValueAsString() const { std::stringstream ss; ss << "Value (float): " << value.f << std::endl; ss << "Value (int): " << value.i << std::endl; return ss.str(); } bool TempoNote::operator==(const TempoNote &other) const noexcept { return Note::operator==(other) && value.i == other.value.i && value.f == other.value.f; } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: Pixel.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "Pixel.hh" #include "Quad.hh" #include "Polygon.hh" #include "Plane.hh" #include "vlMath.hh" #include "CellArr.hh" #include "Line.hh" static vlMath math; static vlPlane plane; static vlPolygon poly; // Description: // Deep copy of cell. vlPixel::vlPixel(const vlPixel& p) { this->Points = p.Points; this->PointIds = p.PointIds; } int vlPixel::EvaluatePosition(float x[3], float closestPoint[3], int& subId, float pcoords[3], float& dist2, float weights[MAX_CELL_SIZE]) { float *pt1, *pt2, *pt3; int i; float p[3], p21[3], p31[3]; float l21, l31, n[3]; subId = 0; pcoords[0] = pcoords[1] = pcoords[2] = 0.0; // // Get normal for pixel // pt1 = this->Points.GetPoint(0); pt2 = this->Points.GetPoint(1); pt3 = this->Points.GetPoint(2); poly.ComputeNormal (pt1, pt2, pt3, n); // // Project point to plane // plane.ProjectPoint(x,pt1,n,closestPoint); for (i=0; i<3; i++) { p21[i] = pt2[i] - pt1[i]; p31[i] = pt3[i] - pt1[i]; p[i] = x[i] - pt1[i]; } if ( (l21=math.Norm(p21)) == 0.0 ) l21 = 1.0; if ( (l31=math.Norm(p31)) == 0.0 ) l31 = 1.0; pcoords[0] = math.Dot(p21,p) / (l21*l21); pcoords[1] = math.Dot(p31,p) / (l31*l31); if ( pcoords[0] >= 0.0 && pcoords[1] <= 1.0 && pcoords[1] >= 0.0 && pcoords[1] <= 1.0 ) { dist2 = math.Distance2BetweenPoints(closestPoint,x); //projection distance this->InterpolationFunctions(pcoords, weights); return 1; } else { for (i=0; i<2; i++) { if (pcoords[i] < 0.0) pcoords[i] = 0.0; if (pcoords[i] > 1.0) pcoords[i] = 1.0; } this->EvaluateLocation(subId, pcoords, closestPoint, weights); dist2 = math.Distance2BetweenPoints(closestPoint,x); return 0; } } void vlPixel::EvaluateLocation(int& subId, float pcoords[3], float x[3], float weights[MAX_CELL_SIZE]) { float *pt1, *pt2, *pt3; int i; pt1 = this->Points.GetPoint(0); pt2 = this->Points.GetPoint(1); pt3 = this->Points.GetPoint(2); for (i=0; i<3; i++) { x[i] = pt1[i] + pcoords[0]*(pt2[i] - pt1[i]) + pcoords[1]*(pt3[i] - pt1[i]); } this->InterpolationFunctions(pcoords, weights); } int vlPixel::CellBoundary(int subId, float pcoords[3], vlIdList& pts) { float t1=pcoords[0]-pcoords[1]; float t2=1.0-pcoords[0]-pcoords[1]; pts.Reset(); // compare against two lines in parametric space that divide element // into four pieces. if ( t1 >= 0.0 && t2 >= 0.0 ) { pts.SetId(0,this->PointIds.GetId(0)); pts.SetId(1,this->PointIds.GetId(1)); } else if ( t1 >= 0.0 && t2 < 0.0 ) { pts.SetId(0,this->PointIds.GetId(1)); pts.SetId(1,this->PointIds.GetId(3)); } else if ( t1 < 0.0 && t2 < 0.0 ) { pts.SetId(0,this->PointIds.GetId(3)); pts.SetId(1,this->PointIds.GetId(2)); } else //( t1 < 0.0 && t2 >= 0.0 ) { pts.SetId(0,this->PointIds.GetId(2)); pts.SetId(1,this->PointIds.GetId(0)); } if ( pcoords[0] < 0.0 || pcoords[0] > 1.0 || pcoords[1] < 0.0 || pcoords[1] > 1.0 ) return 0; else return 1; } // // Marching squares // static int edges[4][2] = { {0,1}, {1,3}, {3,2}, {2,0} }; typedef int EDGE_LIST; typedef struct { EDGE_LIST edges[5]; } LINE_CASES; static LINE_CASES lineCases[] = { {-1, -1, -1, -1, -1}, {0, 3, -1, -1, -1}, {1, 0, -1, -1, -1}, {1, 3, -1, -1, -1}, {2, 1, -1, -1, -1}, {0, 3, 2, 1, -1}, {2, 0, -1, -1, -1}, {2, 3, -1, -1, -1}, {3, 2, -1, -1, -1}, {0, 2, -1, -1, -1}, {1, 0, 3, 2, -1}, {1, 2, -1, -1, -1}, {3, 1, -1, -1, -1}, {0, 1, -1, -1, -1}, {3, 0, -1, -1, -1}, {-1, -1, -1, -1, -1} }; void vlPixel::Contour(float value, vlFloatScalars *cellScalars, vlFloatPoints *points, vlCellArray *verts, vlCellArray *lines, vlCellArray *polys, vlFloatScalars *scalars) { static int CASE_MASK[4] = {1,2,4,8}; LINE_CASES *lineCase; EDGE_LIST *edge; int i, j, index, *vert; int pts[2]; float t, *x1, *x2, x[3]; // Build the case table for ( i=0, index = 0; i < 4; i++) if (cellScalars->GetScalar(i) >= value) index |= CASE_MASK[i]; lineCase = lineCases + index; edge = lineCase->edges; for ( ; edge[0] > -1; edge += 2 ) { for (i=0; i<2; i++) // insert line { vert = edges[edge[i]]; t = (value - cellScalars->GetScalar(vert[0])) / (cellScalars->GetScalar(vert[1]) - cellScalars->GetScalar(vert[0])); x1 = this->Points.GetPoint(vert[0]); x2 = this->Points.GetPoint(vert[1]); for (j=0; j<3; j++) x[j] = x1[j] + t * (x2[j] - x1[j]); pts[i] = points->InsertNextPoint(x); scalars->InsertNextScalar(value); } lines->InsertNextCell(2,pts); } } vlCell *vlPixel::GetEdge(int edgeId) { static vlLine line; int *verts; verts = edges[edgeId]; // load point id's line.PointIds.SetId(0,this->PointIds.GetId(verts[0])); line.PointIds.SetId(1,this->PointIds.GetId(verts[1])); // load coordinates line.Points.SetPoint(0,this->Points.GetPoint(verts[0])); line.Points.SetPoint(1,this->Points.GetPoint(verts[1])); return &line; } // // Compute interpolation functions (similar but different than Quad interpolation functions) // void vlPixel::InterpolationFunctions(float pcoords[3], float sf[4]) { float rm, sm; rm = 1. - pcoords[0]; sm = 1. - pcoords[1]; sf[0] = rm * sm; sf[1] = pcoords[0] * sm; sf[2] = rm * pcoords[1]; sf[3] = pcoords[0] * pcoords[1]; } // // Intersect plane; see whether point is inside. // int vlPixel::IntersectWithLine(float p1[3], float p2[3], float tol, float& t, float x[3], float pcoords[3], int& subId) { float *pt1, *pt2, *pt3, *pt4, n[3]; float tol2 = tol*tol; float closestPoint[3]; float dist2, weights[MAX_CELL_SIZE]; int i; subId = 0; pcoords[0] = pcoords[1] = pcoords[2] = 0.0; // // Get normal for triangle // pt1 = this->Points.GetPoint(0); pt2 = this->Points.GetPoint(1); pt3 = this->Points.GetPoint(2); pt4 = this->Points.GetPoint(3); n[0] = n[1] = n[2] = 0.0; for (i=0; i<3; i++) { if ( (pt4[i] - pt1[i]) <= 0.0 ) { n[i] = 1.0; break; } } // // Intersect plane of pixel with line // if ( ! plane.IntersectWithLine(p1,p2,n,pt1,t,x) ) return 0; // // Use evaluate position // if ( this->EvaluatePosition(x, closestPoint, subId, pcoords, dist2, weights) ) if ( dist2 <= tol2 ) return 1; return 0; } <commit_msg>*** empty log message ***<commit_after>/*========================================================================= Program: Visualization Library Module: Pixel.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "Pixel.hh" #include "Quad.hh" #include "Polygon.hh" #include "Plane.hh" #include "vlMath.hh" #include "CellArr.hh" #include "Line.hh" static vlMath math; static vlPlane plane; static vlPolygon poly; // Description: // Deep copy of cell. vlPixel::vlPixel(const vlPixel& p) { this->Points = p.Points; this->PointIds = p.PointIds; } int vlPixel::EvaluatePosition(float x[3], float closestPoint[3], int& subId, float pcoords[3], float& dist2, float weights[MAX_CELL_SIZE]) { float *pt1, *pt2, *pt3; int i; float p[3], p21[3], p31[3]; float l21, l31, n[3]; subId = 0; pcoords[0] = pcoords[1] = pcoords[2] = 0.0; // // Get normal for pixel // pt1 = this->Points.GetPoint(0); pt2 = this->Points.GetPoint(1); pt3 = this->Points.GetPoint(2); poly.ComputeNormal (pt1, pt2, pt3, n); // // Project point to plane // plane.ProjectPoint(x,pt1,n,closestPoint); for (i=0; i<3; i++) { p21[i] = pt2[i] - pt1[i]; p31[i] = pt3[i] - pt1[i]; p[i] = x[i] - pt1[i]; } if ( (l21=math.Norm(p21)) == 0.0 ) l21 = 1.0; if ( (l31=math.Norm(p31)) == 0.0 ) l31 = 1.0; pcoords[0] = math.Dot(p21,p) / (l21*l21); pcoords[1] = math.Dot(p31,p) / (l31*l31); if ( pcoords[0] >= 0.0 && pcoords[1] <= 1.0 && pcoords[1] >= 0.0 && pcoords[1] <= 1.0 ) { dist2 = math.Distance2BetweenPoints(closestPoint,x); //projection distance this->InterpolationFunctions(pcoords, weights); return 1; } else { for (i=0; i<2; i++) { if (pcoords[i] < 0.0) pcoords[i] = 0.0; if (pcoords[i] > 1.0) pcoords[i] = 1.0; } this->EvaluateLocation(subId, pcoords, closestPoint, weights); dist2 = math.Distance2BetweenPoints(closestPoint,x); return 0; } } void vlPixel::EvaluateLocation(int& subId, float pcoords[3], float x[3], float weights[MAX_CELL_SIZE]) { float *pt1, *pt2, *pt3; int i; pt1 = this->Points.GetPoint(0); pt2 = this->Points.GetPoint(1); pt3 = this->Points.GetPoint(2); for (i=0; i<3; i++) { x[i] = pt1[i] + pcoords[0]*(pt2[i] - pt1[i]) + pcoords[1]*(pt3[i] - pt1[i]); } this->InterpolationFunctions(pcoords, weights); } int vlPixel::CellBoundary(int subId, float pcoords[3], vlIdList& pts) { float t1=pcoords[0]-pcoords[1]; float t2=1.0-pcoords[0]-pcoords[1]; pts.Reset(); // compare against two lines in parametric space that divide element // into four pieces. if ( t1 >= 0.0 && t2 >= 0.0 ) { pts.SetId(0,this->PointIds.GetId(0)); pts.SetId(1,this->PointIds.GetId(1)); } else if ( t1 >= 0.0 && t2 < 0.0 ) { pts.SetId(0,this->PointIds.GetId(1)); pts.SetId(1,this->PointIds.GetId(3)); } else if ( t1 < 0.0 && t2 < 0.0 ) { pts.SetId(0,this->PointIds.GetId(3)); pts.SetId(1,this->PointIds.GetId(2)); } else //( t1 < 0.0 && t2 >= 0.0 ) { pts.SetId(0,this->PointIds.GetId(2)); pts.SetId(1,this->PointIds.GetId(0)); } if ( pcoords[0] < 0.0 || pcoords[0] > 1.0 || pcoords[1] < 0.0 || pcoords[1] > 1.0 ) return 0; else return 1; } // // Marching squares // static int edges[4][2] = { {0,1}, {1,3}, {3,2}, {2,0} }; typedef int EDGE_LIST; typedef struct { EDGE_LIST edges[5]; } LINE_CASES; static LINE_CASES lineCases[] = { {-1, -1, -1, -1, -1}, {0, 3, -1, -1, -1}, {1, 0, -1, -1, -1}, {1, 3, -1, -1, -1}, {2, 1, -1, -1, -1}, {0, 3, 2, 1, -1}, {2, 0, -1, -1, -1}, {2, 3, -1, -1, -1}, {3, 2, -1, -1, -1}, {0, 2, -1, -1, -1}, {1, 0, 3, 2, -1}, {1, 2, -1, -1, -1}, {3, 1, -1, -1, -1}, {0, 1, -1, -1, -1}, {3, 0, -1, -1, -1}, {-1, -1, -1, -1, -1} }; void vlPixel::Contour(float value, vlFloatScalars *cellScalars, vlFloatPoints *points, vlCellArray *verts, vlCellArray *lines, vlCellArray *polys, vlFloatScalars *scalars) { static int CASE_MASK[4] = {1,2,8,4}; //note difference! LINE_CASES *lineCase; EDGE_LIST *edge; int i, j, index, *vert; int pts[2]; float t, *x1, *x2, x[3]; // Build the case table for ( i=0, index = 0; i < 4; i++) if (cellScalars->GetScalar(i) >= value) index |= CASE_MASK[i]; lineCase = lineCases + index; edge = lineCase->edges; for ( ; edge[0] > -1; edge += 2 ) { for (i=0; i<2; i++) // insert line { vert = edges[edge[i]]; t = (value - cellScalars->GetScalar(vert[0])) / (cellScalars->GetScalar(vert[1]) - cellScalars->GetScalar(vert[0])); x1 = this->Points.GetPoint(vert[0]); x2 = this->Points.GetPoint(vert[1]); for (j=0; j<3; j++) x[j] = x1[j] + t * (x2[j] - x1[j]); pts[i] = points->InsertNextPoint(x); scalars->InsertNextScalar(value); } lines->InsertNextCell(2,pts); } } vlCell *vlPixel::GetEdge(int edgeId) { static vlLine line; int *verts; verts = edges[edgeId]; // load point id's line.PointIds.SetId(0,this->PointIds.GetId(verts[0])); line.PointIds.SetId(1,this->PointIds.GetId(verts[1])); // load coordinates line.Points.SetPoint(0,this->Points.GetPoint(verts[0])); line.Points.SetPoint(1,this->Points.GetPoint(verts[1])); return &line; } // // Compute interpolation functions (similar but different than Quad interpolation functions) // void vlPixel::InterpolationFunctions(float pcoords[3], float sf[4]) { float rm, sm; rm = 1. - pcoords[0]; sm = 1. - pcoords[1]; sf[0] = rm * sm; sf[1] = pcoords[0] * sm; sf[2] = rm * pcoords[1]; sf[3] = pcoords[0] * pcoords[1]; } // // Intersect plane; see whether point is inside. // int vlPixel::IntersectWithLine(float p1[3], float p2[3], float tol, float& t, float x[3], float pcoords[3], int& subId) { float *pt1, *pt2, *pt3, *pt4, n[3]; float tol2 = tol*tol; float closestPoint[3]; float dist2, weights[MAX_CELL_SIZE]; int i; subId = 0; pcoords[0] = pcoords[1] = pcoords[2] = 0.0; // // Get normal for triangle // pt1 = this->Points.GetPoint(0); pt2 = this->Points.GetPoint(1); pt3 = this->Points.GetPoint(2); pt4 = this->Points.GetPoint(3); n[0] = n[1] = n[2] = 0.0; for (i=0; i<3; i++) { if ( (pt4[i] - pt1[i]) <= 0.0 ) { n[i] = 1.0; break; } } // // Intersect plane of pixel with line // if ( ! plane.IntersectWithLine(p1,p2,n,pt1,t,x) ) return 0; // // Use evaluate position // if ( this->EvaluatePosition(x, closestPoint, subId, pcoords, dist2, weights) ) if ( dist2 <= tol2 ) return 1; return 0; } <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include <boost/algorithm/string.hpp> #ifndef unix #include <float.h> #else #include "CoreTypes.h" #endif #include "RexNetworkUtils.h" #include "QuatUtils.h" #include <QStringList> namespace RexTypes { bool ParseBool(const std::string &value) { std::string testedvalue = value; boost::algorithm::to_lower(testedvalue); return (boost::algorithm::starts_with(testedvalue,"true") || boost::algorithm::starts_with(testedvalue,"1")); } Quaternion GetProcessedQuaternion(const uint8_t* bytes) { uint16_t *rot = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]); Quaternion rotation = UnpackQuaternionFromU16_4(rot); rotation.normalize(); return rotation; } Vector3df GetProcessedScaledVectorFromUint16(const uint8_t* bytes, float scale) { uint16_t *vec = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]); Vector3df resultvector; resultvector.x = scale * ((vec[0] / 32768.0f) - 1.0f); resultvector.y = scale * ((vec[1] / 32768.0f) - 1.0f); resultvector.z = scale * ((vec[2] / 32768.0f) - 1.0f); return resultvector; } Vector3df GetProcessedVectorFromUint16(const uint8_t* bytes) { uint16_t *vec = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]); return Vector3df(vec[0],vec[1],vec[2]); } Vector3df GetProcessedVector(const uint8_t* bytes) { Vector3df resultvector = *reinterpret_cast<Vector3df*>((Vector3df*)&bytes[0]); return resultvector; } bool IsValidPositionVector(const Vector3df &pos) { // This is a heuristic check to guard against the OpenSim server sending us stupid positions. if (fabs(pos.x) > 1e6f || fabs(pos.y) > 1e6f || fabs(pos.z) > 1e6f) return false; if (_isnan(pos.x) || _isnan(pos.y) || _isnan(pos.z)) return false; if (!_finite(pos.x) || !_finite(pos.y) || !_finite(pos.z)) return false; return true; } bool IsValidVelocityVector(const Vector3df &pos) { // This is a heuristic check to guard against the OpenSim server sending us stupid velocity vectors. if (fabs(pos.x) > 1e3f || fabs(pos.y) > 1e3f || fabs(pos.z) > 1e3f) return false; if (_isnan(pos.x) || _isnan(pos.y) || _isnan(pos.z)) return false; if (!_finite(pos.x) || !_finite(pos.y) || !_finite(pos.z)) return false; return true; } bool ReadBoolFromBytes(const uint8_t* bytes, int& idx) { bool result = *(bool*)(&bytes[idx]); idx += sizeof(bool); return result; } uint8_t ReadUInt8FromBytes(const uint8_t* bytes, int& idx) { uint8_t result = bytes[idx]; idx++; return result; } uint16_t ReadUInt16FromBytes(const uint8_t* bytes, int& idx) { uint16_t result = *(uint16_t*)(&bytes[idx]); idx += sizeof(uint16_t); return result; } uint32_t ReadUInt32FromBytes(const uint8_t* bytes, int& idx) { uint32_t result = *(uint32_t*)(&bytes[idx]); idx += sizeof(uint32_t); return result; } int16_t ReadSInt16FromBytes(const uint8_t* bytes, int& idx) { int16_t result = *(int16_t*)(&bytes[idx]); idx += sizeof(int16_t); return result; } int32_t ReadSInt32FromBytes(const uint8_t* bytes, int& idx) { int32_t result = *(int32_t*)(&bytes[idx]); idx += sizeof(int32_t); return result; } float ReadFloatFromBytes(const uint8_t* bytes, int& idx) { float result = *(float*)(&bytes[idx]); idx += sizeof(float); return result; } RexUUID ReadUUIDFromBytes(const uint8_t* bytes, int& idx) { RexUUID result = *(RexUUID*)(&bytes[idx]); idx += sizeof(RexUUID); return result; } Color ReadColorFromBytes(const uint8_t* bytes, int& idx) { uint8_t r = bytes[idx++]; uint8_t g = bytes[idx++]; uint8_t b = bytes[idx++]; uint8_t a = bytes[idx++]; return Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f); } Color ReadColorFromBytesInverted(const uint8_t* bytes, int& idx) { uint8_t r = 255 - bytes[idx++]; uint8_t g = 255 - bytes[idx++]; uint8_t b = 255 - bytes[idx++]; uint8_t a = 255 - bytes[idx++]; return Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f); } std::string ReadNullTerminatedStringFromBytes(const uint8_t* bytes, int& idx) { std::string result = ""; uint8_t readbyte = bytes[idx]; idx++; while(readbyte != 0) { result.push_back((char)readbyte); readbyte = bytes[idx]; idx++; } return result; } void WriteBoolToBytes(bool value, uint8_t* bytes, int& idx) { bytes[idx] = (uint8_t)value; idx++; } void WriteUInt8ToBytes(uint8_t value, uint8_t* bytes, int& idx) { bytes[idx] = value; idx++; } void WriteUInt16ToBytes(uint16_t value, uint8_t* bytes, int& idx) { *(uint16_t*)(&bytes[idx]) = value; idx += sizeof(uint16_t); } void WriteUInt32ToBytes(uint32_t value, uint8_t* bytes, int& idx) { *(uint32_t*)(&bytes[idx]) = value; idx += sizeof(uint32_t); } void WriteFloatToBytes(float value, uint8_t* bytes, int& idx) { *(float*)(&bytes[idx]) = value; idx += sizeof(float); } void WriteUUIDToBytes(const RexUUID &value, uint8_t* bytes, int& idx) { *(RexUUID*)(&bytes[idx]) = value; idx += sizeof(RexUUID); } void WriteNullTerminatedStringToBytes(const std::string& value, uint8_t* bytes, int& idx) { const char* c_str = value.c_str(); memcpy(&bytes[idx], c_str, value.length() + 1); idx += value.length() + 1; } NameValueMap ParseNameValueMap(const std::string& namevalue) { // NameValue contains: "FirstName STRING RW SV <firstName>\nLastName STRING RW SV <lastName>" // When using rex auth <firstName> contains both first and last name and <lastName> contains the auth server address // Split into lines NameValueMap map; StringVector lines = SplitString(namevalue, '\n'); for (unsigned i = 0; i < lines.size(); ++i) { StringVector line = SplitString(lines[i], ' '); if (line.size() > 4) { // First element is the name const std::string& name = line[0]; std::string value; // Skip over the STRING RW SV etc. (3 values) // Concatenate the rest of the values for (unsigned j = 4; j < line.size(); ++j) { value += line[j]; if (j != line.size()-1) value += " "; } map[name] = value; } } // Parse auth server address out from the NameValue if it exists QString fullname = QString(map["FirstName"].c_str()) + " " + QString(map["LastName"].c_str()); // Rex auth has: <First Last> <rex auth url> if (fullname.count('@') == 1) { QStringList names; if (fullname.contains('@')) { names = fullname.split(" "); foreach(QString name, names) { if (name.contains('@')) { map["RexAuth"] = name.toStdString(); names.removeOne(name); } } } assert(names[0].size() >= 2); if (names.length() >= 1) map["FirstName"] = names[0].toStdString(); if (names.length() >= 2) map["LastName"] = names[1].toStdString(); } // Web auth has: <url> <url> else if (fullname.count('@') == 2) { QStringList names = fullname.split(" "); map["FirstName"] = names[0].toStdString(); map["LastName"] = ""; } return map; } bool ReadTextureEntryBits(uint32_t& bits, int& num_bits, const uint8_t* bytes, int& idx) { bits = 0; num_bits = 0; uint8_t byte; do { byte = bytes[idx++]; bits <<= 7; bits |= byte & 0x7f; num_bits += 7; } while (byte & 0x80); return bits != 0; } } <commit_msg>Don't crash on 1 char first names, or malformed web auth lines<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include <boost/algorithm/string.hpp> #ifndef unix #include <float.h> #else #include "CoreTypes.h" #endif #include "RexNetworkUtils.h" #include "QuatUtils.h" #include <QStringList> namespace RexTypes { bool ParseBool(const std::string &value) { std::string testedvalue = value; boost::algorithm::to_lower(testedvalue); return (boost::algorithm::starts_with(testedvalue,"true") || boost::algorithm::starts_with(testedvalue,"1")); } Quaternion GetProcessedQuaternion(const uint8_t* bytes) { uint16_t *rot = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]); Quaternion rotation = UnpackQuaternionFromU16_4(rot); rotation.normalize(); return rotation; } Vector3df GetProcessedScaledVectorFromUint16(const uint8_t* bytes, float scale) { uint16_t *vec = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]); Vector3df resultvector; resultvector.x = scale * ((vec[0] / 32768.0f) - 1.0f); resultvector.y = scale * ((vec[1] / 32768.0f) - 1.0f); resultvector.z = scale * ((vec[2] / 32768.0f) - 1.0f); return resultvector; } Vector3df GetProcessedVectorFromUint16(const uint8_t* bytes) { uint16_t *vec = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]); return Vector3df(vec[0],vec[1],vec[2]); } Vector3df GetProcessedVector(const uint8_t* bytes) { Vector3df resultvector = *reinterpret_cast<Vector3df*>((Vector3df*)&bytes[0]); return resultvector; } bool IsValidPositionVector(const Vector3df &pos) { // This is a heuristic check to guard against the OpenSim server sending us stupid positions. if (fabs(pos.x) > 1e6f || fabs(pos.y) > 1e6f || fabs(pos.z) > 1e6f) return false; if (_isnan(pos.x) || _isnan(pos.y) || _isnan(pos.z)) return false; if (!_finite(pos.x) || !_finite(pos.y) || !_finite(pos.z)) return false; return true; } bool IsValidVelocityVector(const Vector3df &pos) { // This is a heuristic check to guard against the OpenSim server sending us stupid velocity vectors. if (fabs(pos.x) > 1e3f || fabs(pos.y) > 1e3f || fabs(pos.z) > 1e3f) return false; if (_isnan(pos.x) || _isnan(pos.y) || _isnan(pos.z)) return false; if (!_finite(pos.x) || !_finite(pos.y) || !_finite(pos.z)) return false; return true; } bool ReadBoolFromBytes(const uint8_t* bytes, int& idx) { bool result = *(bool*)(&bytes[idx]); idx += sizeof(bool); return result; } uint8_t ReadUInt8FromBytes(const uint8_t* bytes, int& idx) { uint8_t result = bytes[idx]; idx++; return result; } uint16_t ReadUInt16FromBytes(const uint8_t* bytes, int& idx) { uint16_t result = *(uint16_t*)(&bytes[idx]); idx += sizeof(uint16_t); return result; } uint32_t ReadUInt32FromBytes(const uint8_t* bytes, int& idx) { uint32_t result = *(uint32_t*)(&bytes[idx]); idx += sizeof(uint32_t); return result; } int16_t ReadSInt16FromBytes(const uint8_t* bytes, int& idx) { int16_t result = *(int16_t*)(&bytes[idx]); idx += sizeof(int16_t); return result; } int32_t ReadSInt32FromBytes(const uint8_t* bytes, int& idx) { int32_t result = *(int32_t*)(&bytes[idx]); idx += sizeof(int32_t); return result; } float ReadFloatFromBytes(const uint8_t* bytes, int& idx) { float result = *(float*)(&bytes[idx]); idx += sizeof(float); return result; } RexUUID ReadUUIDFromBytes(const uint8_t* bytes, int& idx) { RexUUID result = *(RexUUID*)(&bytes[idx]); idx += sizeof(RexUUID); return result; } Color ReadColorFromBytes(const uint8_t* bytes, int& idx) { uint8_t r = bytes[idx++]; uint8_t g = bytes[idx++]; uint8_t b = bytes[idx++]; uint8_t a = bytes[idx++]; return Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f); } Color ReadColorFromBytesInverted(const uint8_t* bytes, int& idx) { uint8_t r = 255 - bytes[idx++]; uint8_t g = 255 - bytes[idx++]; uint8_t b = 255 - bytes[idx++]; uint8_t a = 255 - bytes[idx++]; return Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f); } std::string ReadNullTerminatedStringFromBytes(const uint8_t* bytes, int& idx) { std::string result = ""; uint8_t readbyte = bytes[idx]; idx++; while(readbyte != 0) { result.push_back((char)readbyte); readbyte = bytes[idx]; idx++; } return result; } void WriteBoolToBytes(bool value, uint8_t* bytes, int& idx) { bytes[idx] = (uint8_t)value; idx++; } void WriteUInt8ToBytes(uint8_t value, uint8_t* bytes, int& idx) { bytes[idx] = value; idx++; } void WriteUInt16ToBytes(uint16_t value, uint8_t* bytes, int& idx) { *(uint16_t*)(&bytes[idx]) = value; idx += sizeof(uint16_t); } void WriteUInt32ToBytes(uint32_t value, uint8_t* bytes, int& idx) { *(uint32_t*)(&bytes[idx]) = value; idx += sizeof(uint32_t); } void WriteFloatToBytes(float value, uint8_t* bytes, int& idx) { *(float*)(&bytes[idx]) = value; idx += sizeof(float); } void WriteUUIDToBytes(const RexUUID &value, uint8_t* bytes, int& idx) { *(RexUUID*)(&bytes[idx]) = value; idx += sizeof(RexUUID); } void WriteNullTerminatedStringToBytes(const std::string& value, uint8_t* bytes, int& idx) { const char* c_str = value.c_str(); memcpy(&bytes[idx], c_str, value.length() + 1); idx += value.length() + 1; } NameValueMap ParseNameValueMap(const std::string& namevalue) { // NameValue starts with: "FirstName STRING RW SV <firstName>\nLastName STRING RW SV <lastName>" // When using rex auth <firstName> contains both first and last name and <lastName> contains the auth server address // Split into lines NameValueMap map; StringVector lines = SplitString(namevalue, '\n'); for (unsigned i = 0; i < lines.size(); ++i) { StringVector line = SplitString(lines[i], ' '); if (line.size() > 4) { // First element is the name const std::string& name = line[0]; std::string value; // Skip over the STRING RW SV etc. (3 values) // Concatenate the rest of the values for (unsigned j = 4; j < line.size(); ++j) { value += line[j]; if (j != line.size()-1) value += " "; } map[name] = value; } } // Parse auth server address out from the NameValue if it exists QString fullname = QString(map["FirstName"].c_str()) + " " + QString(map["LastName"].c_str()); // Rex auth has: <First Last> <rex auth url> if (fullname.count('@') == 1) { QStringList names; if (fullname.contains('@')) { names = fullname.split(" "); foreach(QString name, names) { if (name.contains('@')) { map["RexAuth"] = name.toStdString(); names.removeOne(name); } } } if (names.length() >= 1) map["FirstName"] = names[0].toStdString(); if (names.length() >= 2) map["LastName"] = names[1].toStdString(); } // Web auth has: <url> <url> else if (fullname.count('@') == 2) { QStringList names = fullname.split(" "); if (names.length() >= 1) { map["FirstName"] = names[0].toStdString(); map["LastName"] = ""; } } return map; } bool ReadTextureEntryBits(uint32_t& bits, int& num_bits, const uint8_t* bytes, int& idx) { bits = 0; num_bits = 0; uint8_t byte; do { byte = bytes[idx++]; bits <<= 7; bits |= byte & 0x7f; num_bits += 7; } while (byte & 0x80); return bits != 0; } } <|endoftext|>
<commit_before>#include "PRINTOBJ.H" #include "DRAW.H" #include "SPECIFIC.H" #include "MATHS.H" #include "3D_GEN.H" #include "CONTROL.H" #include "SETUP.H" #include "ITEMS.H" #include "EFFECTS.H" #include "LOAD_LEV.H" #include "DELTAPAK.H" #include "DRAWOBJ.H" void CalcAllAnimatingItems_ASM() { UNIMPLEMENTED(); } void DrawEffect(short item_num) { struct FX_INFO* fx = &effects[item_num]; struct object_info* obj = &objects[fx->object_number]; if (obj->draw_routine != NULL && obj->loaded) { mPushMatrix(); mTranslateAbsXYZ(fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos); if (Matrix->tz < 20480) { mRotYXZ(fx->pos.y_rot, fx->pos.x_rot, fx->pos.z_rot); S_CalculateLight(fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos, fx->room_number, &duff_item.il); duff_item.il.Light[3].pad = 0; phd_PutPolygons(meshes[obj->nmeshes != 0 ? obj->mesh_index : fx->frame_number], -1); } mPopMatrix(); } } void PrintAllOtherObjects_ASM(short room_num /*s3*/)//(F) { struct room_info* r = &room[room_num]; struct ITEM_INFO* item = NULL; struct object_info* object; short item_num; struct FX_INFO* effect; int mesh_num; short* mesh; int effect_num; r->bound_active = 0; mPushMatrix(); mTranslateAbsXYZ(r->x, r->y, r->z); phd_right = 512; phd_bottom = 240; phd_left = 0; phd_top = 0; item_num = r->item_number; if (item_num != -1) { do { item = &items[item_num]; object = &objects[item->object_number]; if (item->status != 6) { if (!object->using_drawanimating_item && object->draw_routine != NULL) { object->draw_routine(item); } } //loc_8F5AC if (object->draw_routine_extra != NULL) { object->draw_routine_extra(item); } //loc_8F5C4 if (item->after_death - 1 < 127) { item->after_death++; if (item->after_death == 128) { KillItem(r->item_number); } }//loc_8F5EC item_num = item->next_item; } while (item_num != -1); }//loc_8F5FC effect_num = r->fx_number; if (effect_num != -1) { //loc_8F608 do { effect = &effect[effect_num]; object = &objects[effect->object_number]; if (object->draw_routine != NULL && object->loaded) { mPushMatrix(); mTranslateAbsXYZ(effect->pos.x_pos, effect->pos.y_pos, effect->pos.z_pos); if (((int*)MatrixStack)[2] - 21 < 20459) { mRotYXZ(effect->pos.y_rot, effect->pos.x_rot, effect->pos.z_rot); duff_item.il.Light[3].pad = 0; S_CalculateLight(effect->pos.x_pos, effect->pos.y_pos, effect->pos.z_pos, effect->room_number, &duff_item.il); mesh_num = effect->frame_number; if (object->nmeshes != 0) { mesh_num = object->mesh_index; }//loc_8F6C0 phd_PutPolygons(meshes[mesh_num], -1); }//loc_8F6D8 mPopMatrix(); //loc_8F6E0 effect_num = effect->next_fx; } } while (effect_num != -1);//loc_8F6E0 }//loc_8F6EC mPopMatrix(); ((int*)&r->left)[0] = 511; ((int*)&r->top)[0] = 239; } void print_all_object_NOW()//8F474(<), 914B8(<) (F) { CalcAllAnimatingItems_ASM(); for (int i = 0; i < number_draw_rooms; i++) { PrintAllOtherObjects_ASM(draw_rooms[i]); } }<commit_msg>[Specific-PSXPC_N] Implement init_scratchpad<commit_after>#include "PRINTOBJ.H" #include "CAMERA.H" #include "DRAW.H" #include "SPECIFIC.H" #include "MATHS.H" #include "3D_GEN.H" #include "CONTROL.H" #include "SETUP.H" #include "ITEMS.H" #include "EFFECTS.H" #include "LOAD_LEV.H" #include "DELTAPAK.H" #include "DRAWOBJ.H" #include <GTEREG.H> void init_scratchpad(int* fp)//8281C(<) (F) { int t0; int t1; int t2; int t3; int t4; int t5; int t6; int t7; int* at = &fp[47]; fp[20] = (int)at; t0 = R11 | (R12 << 16); t1 = R13 | (R21 << 16); t2 = R22 | (R23 << 16); t3 = R31 | (R32 << 16); t4 = R33; t5 = TRX; t6 = TRY; t7 = TRZ; at[0] = t0; at[1] = t1; at[2] = t2; at[3] = t3; at[4] = t4; at[5] = t5; at[6] = t6; at[7] = t7; //v0 = (int)&stashed_objects_list[0] //v1 = (int)&stashed_matrix_list[0] //a0 = (int)&items[0] //a1 = (int)&room[0] fp[16] = (int)stashed_objects_list; fp[17] = (int)stashed_matrix_list; fp[18] = 0; fp[24] = (int)items; fp[38] = (int)room; //v0 = camera.pos.room_number //v1 = anims //a0 = meshes //a1 = bones ((short*)fp)[53] = camera.pos.room_number; fp[39] = (int)anims; fp[40] = (int)meshes; fp[41] = (int)bones; t0 = ((int*)MatrixStack)[5]; t1 = ((int*)MatrixStack)[6]; t2 = ((int*)MatrixStack)[7]; fp[46] = BinocularRange; fp[27] = t0; fp[28] = t1; fp[29] = t2; /* Must be set in outer function */ //s1 = number_draw_rooms //s0 = &draw_rooms[0]; } void CalcAllAnimatingItems_ASM() { int scratchPad[256]; int* fp; fp = &scratchPad[0]; init_scratchpad(fp); #if 0 blez $s1, loc_827DC loc_82658 : lh $a0, 0($s0) lw $v1, 0x80 + arg_18($fp) sll $v0, $a0, 2 addu $v0, $a0 sll $v0, 4 addu $s2, $v1, $v0 sh $a0, 0x80 + var_18($fp) jal sub_81BBC sw $s2, 0x80 + var_1C($fp) lh $s3, 0x32($s2) lw $s4, 0x10($s2) blez $s3, loc_8275C lw $v0, 0x38($s2) lw $v1, 0x3C($s2) sw $v0, 0x80 + arg_10($fp) sw $v1, 0x80 + arg_14($fp) loc_82698: lh $v0, 0x12($s4) lh $v1, 0x10($s4) li $s5, 0x1F9780//static objects? sll $at, $v0, 3 subu $at, $v0 sll $at, 2 andi $v0, $v1, 1 beqz $v0, loc_82750 addu $s5, $at jal sub_81BBC lw $a1, 4($s4) lw $a0, 0($s4) jal sub_81A8C lw $a2, 8($s4) lh $a0, 0xC($s4) jal sub_81858 nop lhu $v1, 2($s5) cfc2 $at, $7 srl $v1, 2 sll $v1, 10 beqz $v1, loc_82704 slt $at, $v1, $at beqz $at, loc_82704 nop addiu $s5, 0x1C loc_82704: jal sub_811FC addiu $a0, $s5, 4 beqz $v0, loc_8274C lw $a3, 0x80 + var_38($fp) lw $a2, 0x80 + var_40($fp) addiu $a3, 1 sw $a3, 0x80 + var_38($fp) sh $v0, 0($a2) sw $s4, 4($a2) sh $zero, 2($a2) addiu $a2, 0xC sw $a2, 0x80 + var_40($fp) lh $v1, 0($s5) lw $v0, 0x80 + arg_20($fp) sll $v1, 2 addu $v0, $v1 jal sub_81750 lw $a0, 0($v0) loc_8274C: jal sub_81C0C loc_82750 : addiu $s3, -1 bgtz $s3, loc_82698 addiu $s4, 0x14 loc_8275C : lh $s2, 0x48($s2) li $v1, 0xFFFFFFFF beq $s2, $v1, loc_827CC sll $v0, $s2, 7 loc_8276C : sll $v1, $s2, 4 lw $s3, 0x80 + var_20($fp) addu $v0, $v1 addu $s3, $v0 lh $v1, 0xC($s3) li $s6, 0x1F2480//objects? sll $v1, 6 addu $s6, $v1 lhu $v0, 0x32($s6) lw $a1, 0x84($s3) andi $v0, 0x200 beqz $v0, loc_827BC li $v1, 6 andi $a1, 6 beq $a1, $v1, loc_827BC nop jal sub_81504 move $s2, $s3 move $s3, $s2 loc_827BC : lh $s2, 0x1A($s3) li $v0, 0xFFFFFFFF bne $s2, $v0, loc_8276C sll $v0, $s2, 7 loc_827CC : jal sub_81C0C addiu $s1, -1 bnez $s1, loc_82658 addiu $s0, 2 loc_827DC : lw $s4, 0x80 + var_38($fp) lui $gp, 0xA jal sub_82900 la $gp, aTwat # "TWAT" lw $ra, 0x80 + var_44($sp) lw $fp, 0x80 + var_48($sp) lw $s7, 0x80 + var_4C($sp) lw $s6, 0x80 + var_50($sp) lw $s5, 0x80 + var_54($sp) lw $s4, 0x80 + var_58($sp) lw $s3, 0x80 + var_5C($sp) lw $s2, 0x80 + var_60($sp) lw $s1, 0x80 + var_64($sp) lw $s0, 0x80 + var_68($sp) jr $ra addiu $sp, 0x80 #endif } void DrawEffect(short item_num) { struct FX_INFO* fx = &effects[item_num]; struct object_info* obj = &objects[fx->object_number]; if (obj->draw_routine != NULL && obj->loaded) { mPushMatrix(); mTranslateAbsXYZ(fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos); if (Matrix->tz < 20480) { mRotYXZ(fx->pos.y_rot, fx->pos.x_rot, fx->pos.z_rot); S_CalculateLight(fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos, fx->room_number, &duff_item.il); duff_item.il.Light[3].pad = 0; phd_PutPolygons(meshes[obj->nmeshes != 0 ? obj->mesh_index : fx->frame_number], -1); } mPopMatrix(); } } void PrintAllOtherObjects_ASM(short room_num /*s3*/)//(F) { struct room_info* r = &room[room_num]; struct ITEM_INFO* item = NULL; struct object_info* object; short item_num; struct FX_INFO* effect; int mesh_num; short* mesh; int effect_num; r->bound_active = 0; mPushMatrix(); mTranslateAbsXYZ(r->x, r->y, r->z); phd_right = 512; phd_bottom = 240; phd_left = 0; phd_top = 0; item_num = r->item_number; if (item_num != -1) { do { item = &items[item_num]; object = &objects[item->object_number]; if (item->status != 6) { if (!object->using_drawanimating_item && object->draw_routine != NULL) { object->draw_routine(item); } } //loc_8F5AC if (object->draw_routine_extra != NULL) { object->draw_routine_extra(item); } //loc_8F5C4 if (item->after_death - 1 < 127) { item->after_death++; if (item->after_death == 128) { KillItem(r->item_number); } }//loc_8F5EC item_num = item->next_item; } while (item_num != -1); }//loc_8F5FC effect_num = r->fx_number; if (effect_num != -1) { //loc_8F608 do { effect = &effect[effect_num]; object = &objects[effect->object_number]; if (object->draw_routine != NULL && object->loaded) { mPushMatrix(); mTranslateAbsXYZ(effect->pos.x_pos, effect->pos.y_pos, effect->pos.z_pos); if (((int*)MatrixStack)[2] - 21 < 20459) { mRotYXZ(effect->pos.y_rot, effect->pos.x_rot, effect->pos.z_rot); duff_item.il.Light[3].pad = 0; S_CalculateLight(effect->pos.x_pos, effect->pos.y_pos, effect->pos.z_pos, effect->room_number, &duff_item.il); mesh_num = effect->frame_number; if (object->nmeshes != 0) { mesh_num = object->mesh_index; }//loc_8F6C0 phd_PutPolygons(meshes[mesh_num], -1); }//loc_8F6D8 mPopMatrix(); //loc_8F6E0 effect_num = effect->next_fx; } } while (effect_num != -1);//loc_8F6E0 }//loc_8F6EC mPopMatrix(); ((int*)&r->left)[0] = 511; ((int*)&r->top)[0] = 239; } void print_all_object_NOW()//8F474(<), 914B8(<) (F) { CalcAllAnimatingItems_ASM(); for (int i = 0; i < number_draw_rooms; i++) { PrintAllOtherObjects_ASM(draw_rooms[i]); } }<|endoftext|>
<commit_before>#include "xUnitAssert.h" namespace { std::string AssembleWhat(const std::string &call, const std::vector<std::string> &userMsg, const std::string &customMsg, const std::string &expected, const std::string &actual) { std::string msg = call + "() failure"; if (!userMsg.empty()) { msg += ": "; for (const auto &s : userMsg) { msg += s; } if (!customMsg.empty()) { msg += "\n " + customMsg; } } else { if (!customMsg.empty()) { msg += ": " + customMsg; } } if (!expected.empty()) { msg += "\n Expected: " + expected; msg += "\n Actual: " + actual; } return msg; } } namespace xUnitpp { const xUnitAssert &xUnitAssert::None() { static xUnitAssert none("", xUnitpp::LineInfo()); return none; } xUnitAssert::xUnitAssert(std::string &&call, xUnitpp::LineInfo &&lineInfo) : lineInfo(std::move(lineInfo)) , call(std::move(call)) { } xUnitAssert &xUnitAssert::CustomMessage(std::string &&message) { customMessage = std::move(message); return *this; } xUnitAssert &xUnitAssert::Expected(std::string &&str) { expected = std::move(str); return *this; } xUnitAssert &xUnitAssert::Actual(std::string &&str) { actual = std::move(str); return *this; } const LineInfo &xUnitAssert::LineInfo() const { return lineInfo; } const char *xUnitAssert::what() const noexcept(true) { if (whatMessage.empty()) { whatMessage = AssembleWhat(call, userMessage, customMessage, expected, actual); } return whatMessage.c_str(); } xUnitFailure::xUnitFailure() : OnFailureComplete([](const xUnitAssert &){}) , assert(xUnitAssert::None()) , refCount(*(new int(0))) { } xUnitFailure::xUnitFailure(xUnitAssert &&assert, std::function<void(const xUnitAssert &)> onFailureComplete) : OnFailureComplete(onFailureComplete) , assert(std::move(assert)) , refCount(*(new int(1))) { } xUnitFailure::xUnitFailure(const xUnitFailure &other) : OnFailureComplete(other.OnFailureComplete) , assert(other.assert) , refCount(other.refCount) { refCount++; } xUnitFailure::~xUnitFailure() noexcept(false) { if (!--refCount) { delete &refCount; // http://cpp-next.com/archive/2012/08/evil-or-just-misunderstood/ // http://akrzemi1.wordpress.com/2011/09/21/destructors-that-throw/ // throwing destructors aren't Evil, just misunderstood OnFailureComplete(assert); } } xUnitFailure xUnitFailure::None() { return xUnitFailure(); } xUnitFailure Assert::OnFailure(xUnitAssert &&assert) const { return xUnitFailure(std::move(assert), handleFailure); } xUnitFailure Assert::OnSuccess() const { return xUnitFailure::None(); } double Assert::round(double value, size_t precision) { if (value < 0) { return std::ceil((value - 0.5) * std::pow(10, precision)) / std::pow(10, precision); } else { return std::floor((value + 0.5) * std::pow(10, precision)) / std::pow(10, precision); } } xUnitFailure Assert::Equal(const std::string &expected, const std::string &actual, LineInfo &&lineInfo) const { if (expected != actual) { return OnFailure(std::move(xUnitAssert(callPrefix + "Equal", std::move(lineInfo)) .Expected(std::string(expected)) // can't assume expected or actual are allowed to be moved .Actual(std::string(actual)))); } return OnSuccess(); } xUnitFailure Assert::Equal(const char *expected, const char *actual, LineInfo &&lineInfo) const { return Equal(std::string(expected), std::string(actual), std::move(lineInfo)); } xUnitFailure Assert::Equal(const char *expected, const std::string &actual, LineInfo &&lineInfo) const { return Equal(std::string(expected), actual, std::move(lineInfo)); } xUnitFailure Assert::Equal(const std::string &expected, const char *actual, LineInfo &&lineInfo) const { return Equal(expected, std::string(actual), std::move(lineInfo)); } xUnitFailure Assert::Equal(float expected, float actual, int precision, LineInfo &&lineInfo) const { return Equal((double)expected, (double)actual, precision, std::move(lineInfo)); } xUnitFailure Assert::Equal(double expected, double actual, int precision, LineInfo &&lineInfo) const { auto er = round(expected, precision); auto ar = round(actual, precision); return Equal(er, ar, [](double er, double ar) { return er == ar; }, std::move(lineInfo)); } xUnitFailure Assert::NotEqual(const std::string &expected, const std::string &actual, LineInfo &&lineInfo) const { if (expected == actual) { return OnFailure(std::move(xUnitAssert(callPrefix + "NotEqual", std::move(lineInfo)) .Expected(std::string(expected)) // can't assume expected or actual are allowed to be moved .Actual(std::string(actual)))); } return OnSuccess(); } xUnitFailure Assert::NotEqual(const char *expected, const char *actual, LineInfo &&lineInfo) const { return NotEqual(std::string(expected), std::string(actual), std::move(lineInfo)); } xUnitFailure Assert::NotEqual(const char *expected, const std::string &actual, LineInfo &&lineInfo) const { return NotEqual(std::string(expected), actual, std::move(lineInfo)); } xUnitFailure Assert::NotEqual(const std::string &expected, const char *actual, LineInfo &&lineInfo) const { return NotEqual(expected, std::string(actual), std::move(lineInfo)); } xUnitFailure Assert::Fail(LineInfo &&lineInfo) const { return OnFailure(std::move(xUnitAssert(callPrefix + "Fail", std::move(lineInfo)))); } xUnitFailure Assert::False(bool b, LineInfo &&lineInfo) const { if (b) { return OnFailure(std::move(xUnitAssert(callPrefix + "False", std::move(lineInfo)).Expected("false").Actual("true"))); } return OnSuccess(); } xUnitFailure Assert::True(bool b, LineInfo &&lineInfo) const { if (!b) { return OnFailure(std::move(xUnitAssert(callPrefix + "True", std::move(lineInfo)).Expected("true").Actual("false"))); } return OnSuccess(); } xUnitFailure Assert::DoesNotContain(const char *actualString, const char *value, LineInfo &&lineInfo) const { const auto a = std::string(actualString); const auto v = std::string(value); return DoesNotContain(a, v, std::move(lineInfo)); } xUnitFailure Assert::DoesNotContain(const char *actualString, const std::string &value, LineInfo &&lineInfo) const { const auto a = std::string(actualString); return DoesNotContain(a, value, std::move(lineInfo)); } xUnitFailure Assert::DoesNotContain(const std::string &actualString, const char *value, LineInfo &&lineInfo) const { const auto v = std::string(value); return DoesNotContain(actualString, v, std::move(lineInfo)); } xUnitFailure Assert::DoesNotContain(const std::string &actualString, const std::string &value, LineInfo &&lineInfo) const { auto found = actualString.find(value); if (found != std::string::npos) { return OnFailure(std::move(xUnitAssert(callPrefix + "DoesNotContain", std::move(lineInfo)) .CustomMessage("Found: \"" + value + "\" at position " + ToString(found) + "."))); } return OnSuccess(); } xUnitFailure Assert::Contains(const char *actualString, const char *value, LineInfo &&lineInfo) const { const auto a = std::string(actualString); const auto v = std::string(value); return Contains(a, v, std::move(lineInfo)); } xUnitFailure Assert::Contains(const char *actualString, const std::string &value, LineInfo &&lineInfo) const { const auto a = std::string(actualString); return Contains(a, value, std::move(lineInfo)); } xUnitFailure Assert::Contains(const std::string &actualString, const char *value, LineInfo &&lineInfo) const { const auto v = std::string(value); return Contains(actualString, v, std::move(lineInfo)); } xUnitFailure Assert::Contains(const std::string &actualString, const std::string &value, LineInfo &&lineInfo) const { if (actualString.find(value) == std::string::npos) { return OnFailure(std::move(xUnitAssert(callPrefix + "Contains", std::move(lineInfo)) .Expected(std::string(actualString)) // can't assume actualString or value can be moved .Actual(std::string(value)))); } return OnSuccess(); } Assert::Assert(std::string &&callPrefix, std::function<void (const xUnitAssert &)> &&onFailure) : callPrefix(std::move(callPrefix)) , handleFailure(std::move(onFailure)) { } } <commit_msg>xUnitAssert.cpp needs <cmath> to compile properly with OS X clang++<commit_after>#include "xUnitAssert.h" #include <cmath> namespace { std::string AssembleWhat(const std::string &call, const std::vector<std::string> &userMsg, const std::string &customMsg, const std::string &expected, const std::string &actual) { std::string msg = call + "() failure"; if (!userMsg.empty()) { msg += ": "; for (const auto &s : userMsg) { msg += s; } if (!customMsg.empty()) { msg += "\n " + customMsg; } } else { if (!customMsg.empty()) { msg += ": " + customMsg; } } if (!expected.empty()) { msg += "\n Expected: " + expected; msg += "\n Actual: " + actual; } return msg; } } namespace xUnitpp { const xUnitAssert &xUnitAssert::None() { static xUnitAssert none("", xUnitpp::LineInfo()); return none; } xUnitAssert::xUnitAssert(std::string &&call, xUnitpp::LineInfo &&lineInfo) : lineInfo(std::move(lineInfo)) , call(std::move(call)) { } xUnitAssert &xUnitAssert::CustomMessage(std::string &&message) { customMessage = std::move(message); return *this; } xUnitAssert &xUnitAssert::Expected(std::string &&str) { expected = std::move(str); return *this; } xUnitAssert &xUnitAssert::Actual(std::string &&str) { actual = std::move(str); return *this; } const LineInfo &xUnitAssert::LineInfo() const { return lineInfo; } const char *xUnitAssert::what() const noexcept(true) { if (whatMessage.empty()) { whatMessage = AssembleWhat(call, userMessage, customMessage, expected, actual); } return whatMessage.c_str(); } xUnitFailure::xUnitFailure() : OnFailureComplete([](const xUnitAssert &){}) , assert(xUnitAssert::None()) , refCount(*(new int(0))) { } xUnitFailure::xUnitFailure(xUnitAssert &&assert, std::function<void(const xUnitAssert &)> onFailureComplete) : OnFailureComplete(onFailureComplete) , assert(std::move(assert)) , refCount(*(new int(1))) { } xUnitFailure::xUnitFailure(const xUnitFailure &other) : OnFailureComplete(other.OnFailureComplete) , assert(other.assert) , refCount(other.refCount) { refCount++; } xUnitFailure::~xUnitFailure() noexcept(false) { if (!--refCount) { delete &refCount; // http://cpp-next.com/archive/2012/08/evil-or-just-misunderstood/ // http://akrzemi1.wordpress.com/2011/09/21/destructors-that-throw/ // throwing destructors aren't Evil, just misunderstood OnFailureComplete(assert); } } xUnitFailure xUnitFailure::None() { return xUnitFailure(); } xUnitFailure Assert::OnFailure(xUnitAssert &&assert) const { return xUnitFailure(std::move(assert), handleFailure); } xUnitFailure Assert::OnSuccess() const { return xUnitFailure::None(); } double Assert::round(double value, size_t precision) { if (value < 0) { return std::ceil((value - 0.5) * std::pow(10, precision)) / std::pow(10, precision); } else { return std::floor((value + 0.5) * std::pow(10, precision)) / std::pow(10, precision); } } xUnitFailure Assert::Equal(const std::string &expected, const std::string &actual, LineInfo &&lineInfo) const { if (expected != actual) { return OnFailure(std::move(xUnitAssert(callPrefix + "Equal", std::move(lineInfo)) .Expected(std::string(expected)) // can't assume expected or actual are allowed to be moved .Actual(std::string(actual)))); } return OnSuccess(); } xUnitFailure Assert::Equal(const char *expected, const char *actual, LineInfo &&lineInfo) const { return Equal(std::string(expected), std::string(actual), std::move(lineInfo)); } xUnitFailure Assert::Equal(const char *expected, const std::string &actual, LineInfo &&lineInfo) const { return Equal(std::string(expected), actual, std::move(lineInfo)); } xUnitFailure Assert::Equal(const std::string &expected, const char *actual, LineInfo &&lineInfo) const { return Equal(expected, std::string(actual), std::move(lineInfo)); } xUnitFailure Assert::Equal(float expected, float actual, int precision, LineInfo &&lineInfo) const { return Equal((double)expected, (double)actual, precision, std::move(lineInfo)); } xUnitFailure Assert::Equal(double expected, double actual, int precision, LineInfo &&lineInfo) const { auto er = round(expected, precision); auto ar = round(actual, precision); return Equal(er, ar, [](double er, double ar) { return er == ar; }, std::move(lineInfo)); } xUnitFailure Assert::NotEqual(const std::string &expected, const std::string &actual, LineInfo &&lineInfo) const { if (expected == actual) { return OnFailure(std::move(xUnitAssert(callPrefix + "NotEqual", std::move(lineInfo)) .Expected(std::string(expected)) // can't assume expected or actual are allowed to be moved .Actual(std::string(actual)))); } return OnSuccess(); } xUnitFailure Assert::NotEqual(const char *expected, const char *actual, LineInfo &&lineInfo) const { return NotEqual(std::string(expected), std::string(actual), std::move(lineInfo)); } xUnitFailure Assert::NotEqual(const char *expected, const std::string &actual, LineInfo &&lineInfo) const { return NotEqual(std::string(expected), actual, std::move(lineInfo)); } xUnitFailure Assert::NotEqual(const std::string &expected, const char *actual, LineInfo &&lineInfo) const { return NotEqual(expected, std::string(actual), std::move(lineInfo)); } xUnitFailure Assert::Fail(LineInfo &&lineInfo) const { return OnFailure(std::move(xUnitAssert(callPrefix + "Fail", std::move(lineInfo)))); } xUnitFailure Assert::False(bool b, LineInfo &&lineInfo) const { if (b) { return OnFailure(std::move(xUnitAssert(callPrefix + "False", std::move(lineInfo)).Expected("false").Actual("true"))); } return OnSuccess(); } xUnitFailure Assert::True(bool b, LineInfo &&lineInfo) const { if (!b) { return OnFailure(std::move(xUnitAssert(callPrefix + "True", std::move(lineInfo)).Expected("true").Actual("false"))); } return OnSuccess(); } xUnitFailure Assert::DoesNotContain(const char *actualString, const char *value, LineInfo &&lineInfo) const { const auto a = std::string(actualString); const auto v = std::string(value); return DoesNotContain(a, v, std::move(lineInfo)); } xUnitFailure Assert::DoesNotContain(const char *actualString, const std::string &value, LineInfo &&lineInfo) const { const auto a = std::string(actualString); return DoesNotContain(a, value, std::move(lineInfo)); } xUnitFailure Assert::DoesNotContain(const std::string &actualString, const char *value, LineInfo &&lineInfo) const { const auto v = std::string(value); return DoesNotContain(actualString, v, std::move(lineInfo)); } xUnitFailure Assert::DoesNotContain(const std::string &actualString, const std::string &value, LineInfo &&lineInfo) const { auto found = actualString.find(value); if (found != std::string::npos) { return OnFailure(std::move(xUnitAssert(callPrefix + "DoesNotContain", std::move(lineInfo)) .CustomMessage("Found: \"" + value + "\" at position " + ToString(found) + "."))); } return OnSuccess(); } xUnitFailure Assert::Contains(const char *actualString, const char *value, LineInfo &&lineInfo) const { const auto a = std::string(actualString); const auto v = std::string(value); return Contains(a, v, std::move(lineInfo)); } xUnitFailure Assert::Contains(const char *actualString, const std::string &value, LineInfo &&lineInfo) const { const auto a = std::string(actualString); return Contains(a, value, std::move(lineInfo)); } xUnitFailure Assert::Contains(const std::string &actualString, const char *value, LineInfo &&lineInfo) const { const auto v = std::string(value); return Contains(actualString, v, std::move(lineInfo)); } xUnitFailure Assert::Contains(const std::string &actualString, const std::string &value, LineInfo &&lineInfo) const { if (actualString.find(value) == std::string::npos) { return OnFailure(std::move(xUnitAssert(callPrefix + "Contains", std::move(lineInfo)) .Expected(std::string(actualString)) // can't assume actualString or value can be moved .Actual(std::string(value)))); } return OnSuccess(); } Assert::Assert(std::string &&callPrefix, std::function<void (const xUnitAssert &)> &&onFailure) : callPrefix(std::move(callPrefix)) , handleFailure(std::move(onFailure)) { } } <|endoftext|>
<commit_before>/** * Exercise 5 : Read in a gph-file, computes the longest (with respect to the edge weights) shortest path from any vertex to the vertex with index 1. * * @author FirstSanny */ #include <iostream> #include <fstream> #include <utility> #include <vector> #include <climits> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/dijkstra_shortest_paths.hpp> #include <boost/graph/named_function_params.hpp> #include <boost/program_options.hpp> #include <boost/timer/timer.hpp> #include "Dijkstra.h" // Constants namespace { const char* FILEEND = ".gph"; } // declaring print using std::cout; using std::endl; using std::cerr; using std::string; // declaring types namespace po = boost::program_options; using Graph = boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, int>> ; using VertexDescriptor = boost::graph_traits < Graph >::vertex_descriptor; using Directions = std::vector<VertexDescriptor >; using Edge = std::pair<int, int>; using Edges = std::vector<Edge >; using Weights = std::vector<int >; po::variables_map parseCommandLine(po::options_description desc, int argn, char* argv[]) { desc.add_options()("help", "produce help message")("algo,m", po::value<int>(), "algorithm to solve shortest Path. \n 1 - libary (boost)\n 2 - own Algo")( "input-file", po::value<string>(), "input file"); po::positional_options_description p; p.add("input-file", -1); po::variables_map vm; po::store( po::command_line_parser(argn, argv).options(desc).positional(p).run(), vm); po::notify(vm); return vm; } char parseAlgoOption(const po::variables_map& vm, char useOwnAlgo) { if (vm.count("algo")) { useOwnAlgo = vm["algo"].as<int>(); if (useOwnAlgo == 2) { useOwnAlgo = 0; } if (useOwnAlgo != 1 && useOwnAlgo != 0) { cout << "No valid Option was given for Algorithm! Fallback: algo from libary" << endl; } } if (useOwnAlgo) { cout << "Using own algorithm..." << endl; } else { cout << "Using algorithm from boost-libary..." << endl; } return useOwnAlgo; } /** Reading in a Graphfile, computes the longest shortest path */ int main(int argn, char *argv[]) { boost::timer::auto_cpu_timer t; if (argn <= 1) { cerr << "ERROR : There was no filename" << endl; return 1; } po::options_description desc("Allowed options"); po::variables_map vm = parseCommandLine(desc, argn, argv); if (vm.count("help")) { cout << desc << "\n"; return 1; } char useOwnAlgo = 0; useOwnAlgo = parseAlgoOption(vm, useOwnAlgo); std::ifstream fileStream; if(vm.count("input-file") == 0){ cerr << "No input-file was given!" << endl; return 1; } string filename = vm["input-file"].as<string >(); filename += FILEEND; cout << "Going to parse the file " << filename << endl; fileStream.open(filename.c_str(), std::ios::in); if ( (fileStream.rdstate()) != 0 ){ std::perror("ERROR : Encoutered Problem opening file"); return 1; } string line; unsigned int edgeCount; unsigned int vertexCount; if(std::getline(fileStream, line)){ sscanf(line.c_str(), "%d %d", &vertexCount, &edgeCount); cout << "Vertexcount: " << vertexCount << endl; cout << "Edgecount: " << edgeCount << endl; line.clear(); vertexCount++; } else { cerr << "ERROR : File was empty" << endl; return 1; } Edges* edges = new Edges(edgeCount); Weights* weights = new Weights(edgeCount); cout << "Reading edges..." << endl; while (getline(fileStream, line)) { int start; int end; int weight; int count = sscanf(line.c_str(), "%d %d %d", &start, &end, &weight); if (count != 3) { line.clear(); continue; } edges->push_back(std::make_pair(start, end)); weights->push_back(weight); line.clear(); } Weights weightsForShortestpath; if(useOwnAlgo){ cout << "Compute shortest paths via Dijkstra(own)..." << endl; Dijkstra* d = new Dijkstra(); weightsForShortestpath = d->dijkstra(vertexCount, *edges, *weights, 1); } else { cout << "Creating graph..." << endl; Graph g{edges->begin(), edges->end(), weights->begin(), vertexCount}; Directions* directions = new std::vector<VertexDescriptor>(vertexCount); cout << "Compute shortest paths via Dijkstra(boost)..." << endl; std::vector<int>* weightMapPointer = new std::vector<int>(vertexCount); boost::dijkstra_shortest_paths(g, 1, boost::predecessor_map(// boost::make_iterator_property_map(directions->begin(), boost::get(boost::vertex_index, g))) // .distance_map(// boost::make_iterator_property_map(weightMapPointer->begin(), boost::get(boost::vertex_index, g)))); weightsForShortestpath = *weightMapPointer; delete weightMapPointer; delete directions; } cout << "Search longest shortest path..." << endl; int vertex = 1; int distance = 0; for(unsigned int i=2; i<vertexCount; i++){ if(weightsForShortestpath[i]>distance){ distance = weightsForShortestpath[i]; vertex = i; } } cout << "RESULT VERTEX " << vertex << endl; cout << "RESULT DIST " << distance << endl; delete edges; delete weights; return 0; } <commit_msg>getting m1 and m2 right<commit_after>/** * Exercise 5 : Read in a gph-file, computes the longest (with respect to the edge weights) shortest path from any vertex to the vertex with index 1. * * @author FirstSanny */ #include <iostream> #include <fstream> #include <utility> #include <vector> #include <climits> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/dijkstra_shortest_paths.hpp> #include <boost/graph/named_function_params.hpp> #include <boost/program_options.hpp> #include <boost/timer/timer.hpp> #include "Dijkstra.h" // Constants namespace { const char* FILEEND = ".gph"; } // declaring print using std::cout; using std::endl; using std::cerr; using std::string; // declaring types namespace po = boost::program_options; using Graph = boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, int>> ; using VertexDescriptor = boost::graph_traits < Graph >::vertex_descriptor; using Directions = std::vector<VertexDescriptor >; using Edge = std::pair<int, int>; using Edges = std::vector<Edge >; using Weights = std::vector<int >; po::variables_map parseCommandLine(po::options_description desc, int argn, char* argv[]) { desc.add_options()("help", "produce help message")("algo,m", po::value<int>(), "algorithm to solve shortest Path. \n 1 - libary (boost)\n 2 - own Algo")( "input-file", po::value<string>(), "input file"); po::positional_options_description p; p.add("input-file", -1); po::variables_map vm; po::store( po::command_line_parser(argn, argv).options(desc).positional(p).run(), vm); po::notify(vm); return vm; } char parseAlgoOption(const po::variables_map& vm, char useOwnAlgo) { if (vm.count("algo")) { useOwnAlgo = vm["algo"].as<int>(); useOwnAlgo--; if (useOwnAlgo != 1 && useOwnAlgo != 0) { cout << "No valid Option was given for Algorithm! Fallback: algo from libary" << endl; useOwnAlgo = 0; } } if (useOwnAlgo) { cout << "Using own algorithm..." << endl; } else { cout << "Using algorithm from boost-libary..." << endl; } return useOwnAlgo; } /** Reading in a Graphfile, computes the longest shortest path */ int main(int argn, char *argv[]) { boost::timer::auto_cpu_timer t; if (argn <= 1) { cerr << "ERROR : There was no filename" << endl; return 1; } po::options_description desc("Allowed options"); po::variables_map vm = parseCommandLine(desc, argn, argv); if (vm.count("help")) { cout << desc << "\n"; return 1; } char useOwnAlgo = 0; useOwnAlgo = parseAlgoOption(vm, useOwnAlgo); std::ifstream fileStream; if(vm.count("input-file") == 0){ cerr << "No input-file was given!" << endl; return 1; } string filename = vm["input-file"].as<string >(); filename += FILEEND; cout << "Going to parse the file " << filename << endl; fileStream.open(filename.c_str(), std::ios::in); if ( (fileStream.rdstate()) != 0 ){ std::perror("ERROR : Encoutered Problem opening file"); return 1; } string line; unsigned int edgeCount; unsigned int vertexCount; if(std::getline(fileStream, line)){ sscanf(line.c_str(), "%d %d", &vertexCount, &edgeCount); cout << "Vertexcount: " << vertexCount << endl; cout << "Edgecount: " << edgeCount << endl; line.clear(); vertexCount++; } else { cerr << "ERROR : File was empty" << endl; return 1; } Edges* edges = new Edges(edgeCount); Weights* weights = new Weights(edgeCount); cout << "Reading edges..." << endl; while (getline(fileStream, line)) { int start; int end; int weight; int count = sscanf(line.c_str(), "%d %d %d", &start, &end, &weight); if (count != 3) { line.clear(); continue; } edges->push_back(std::make_pair(start, end)); weights->push_back(weight); line.clear(); } Weights weightsForShortestpath; if(useOwnAlgo){ cout << "Compute shortest paths via Dijkstra(own)..." << endl; Dijkstra* d = new Dijkstra(); weightsForShortestpath = d->dijkstra(vertexCount, *edges, *weights, 1); } else { cout << "Creating graph..." << endl; Graph g{edges->begin(), edges->end(), weights->begin(), vertexCount}; Directions* directions = new std::vector<VertexDescriptor>(vertexCount); cout << "Compute shortest paths via Dijkstra(boost)..." << endl; std::vector<int>* weightMapPointer = new std::vector<int>(vertexCount); boost::dijkstra_shortest_paths(g, 1, boost::predecessor_map(// boost::make_iterator_property_map(directions->begin(), boost::get(boost::vertex_index, g))) // .distance_map(// boost::make_iterator_property_map(weightMapPointer->begin(), boost::get(boost::vertex_index, g)))); weightsForShortestpath = *weightMapPointer; delete weightMapPointer; delete directions; } cout << "Search longest shortest path..." << endl; int vertex = 1; int distance = 0; for(unsigned int i=2; i<vertexCount; i++){ if(weightsForShortestpath[i]>distance){ distance = weightsForShortestpath[i]; vertex = i; } } cout << "RESULT VERTEX " << vertex << endl; cout << "RESULT DIST " << distance << endl; delete edges; delete weights; return 0; } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2008 Scientific Computing and Imaging Institute, University of Utah. 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. */ //! File : Scripting.cpp //! Author : Jens Krueger //! SCI Institute //! University of Utah //! Date : January 2009 // //! Copyright (C) 2008 SCI Institute #include "Scripting.h" #include <Controller/MasterController.h> #include <Basics/SysTools.h> #include <sstream> using namespace std; ScriptableListElement::ScriptableListElement(Scriptable* source, const std::string& strCommand, const std::string& strParameters, const std::string& strDescription) : m_source(source), m_strCommand(strCommand), m_strDescription(strDescription) { m_vParameters = SysTools::Tokenize(strParameters, false); m_iMaxParam = UINT32(m_vParameters.size()); m_iMinParam = 0; bool bFoundOptional = false; for (UINT32 i = 0;i<m_iMaxParam;i++) { if (m_vParameters[i][0] == '[' && m_vParameters[i][m_vParameters[i].size()-1] == ']') { bFoundOptional = true; m_vParameters[i] = string(m_vParameters[i].begin()+1, m_vParameters[i].end()-1); } else { if (!bFoundOptional) m_iMinParam++; // else // this else would be an syntax error case but lets just assume all parameters after the first optional parameter are also optional } } } Scripting::Scripting(MasterController* pMasterController) : m_pMasterController(pMasterController), m_bEcho(false) { RegisterCalls(this); } Scripting::~Scripting() { for (size_t i = 0;i<m_ScriptableList.size();i++) delete m_ScriptableList[i]; } bool Scripting::RegisterCommand(Scriptable* source, const std::string& strCommand, const std::string& strParameters, const std::string& strDescription) { // commands may not contain whitespaces vector<string> strTest = SysTools::Tokenize(strCommand, false); if (strTest.size() != 1) return false; // commands must be unique for (size_t i = 0;i<m_ScriptableList.size();i++) { if (m_ScriptableList[i]->m_strCommand == strCommand) return false; } // ok, all seems fine: add the command to the list ScriptableListElement* elem = new ScriptableListElement(source, strCommand, strParameters, strDescription); m_ScriptableList.push_back(elem); return true; } bool Scripting::ParseLine(const string& strLine) { // tokenize string vector<string> vParameters = SysTools::Tokenize(strLine); string strMessage = ""; bool bResult = ParseCommand(vParameters, strMessage); if (!bResult) { if (strMessage == "") m_pMasterController->DebugOut()->printf("Input \"%s\" not understood, try \"help\"!", strLine.c_str()); else m_pMasterController->DebugOut()->printf(strMessage.c_str()); } else if (m_bEcho) m_pMasterController->DebugOut()->printf("OK (%s)", strLine.c_str()); return bResult; } bool Scripting::ParseCommand(const vector<string>& strTokenized, string& strMessage) { if (strTokenized.size() == 0) return false; string strCommand = strTokenized[0]; vector<string> strParams(strTokenized.begin()+1, strTokenized.end()); strMessage = ""; for (size_t i = 0;i<m_ScriptableList.size();i++) { if (m_ScriptableList[i]->m_strCommand == strCommand) { if (strParams.size() >= m_ScriptableList[i]->m_iMinParam && strParams.size() <= m_ScriptableList[i]->m_iMaxParam) { return m_ScriptableList[i]->m_source->Execute(strCommand, strParams, strMessage); } else { strMessage = "Parameter mismatch for command \""+strCommand+"\""; return false; } } } return false; } bool Scripting::ParseFile(const std::string& strFilename) { string line; ifstream fileData(strFilename.c_str()); UINT32 iLine=0; if (fileData.is_open()) { while (! fileData.eof() ) { getline (fileData,line); iLine++; SysTools::RemoveLeadingWhitespace(line); if (line.size() == 0) continue; // skip empty lines if (line[0] == '#') continue; // skip comments if (!ParseLine(line)) { m_pMasterController->DebugOut()->Error("Scripting::ParseFile:","Error reading line %i in file %s (%s)", iLine, strFilename.c_str(), line.c_str()); fileData.close(); return false; } } } else { m_pMasterController->DebugOut()->Error("Scripting::ParseFile:","Error opening script file %s", strFilename.c_str()); return false; } fileData.close(); return true; } void Scripting::RegisterCalls(Scripting* pScriptEngine) { pScriptEngine->RegisterCommand(this, "help", "", "show all commands"); pScriptEngine->RegisterCommand(this, "echo", "on/off", "turn feedback on succesfull command execution on or off"); } bool Scripting::Execute(const std::string& strCommand, const std::vector< std::string >& strParams, std::string& strMessage) { strMessage = ""; if (strCommand == "echo") { m_bEcho = SysTools::ToLowerCase(strParams[0]) == "on"; return true; } else if (strCommand == "help") { m_pMasterController->DebugOut()->printf("Command Listing:"); m_pMasterController->DebugOut()->printf("\"help\" : this help screen"); for (size_t i = 0;i<m_ScriptableList.size();i++) { string strParams = ""; for (size_t j = 0;j<m_ScriptableList[i]->m_iMinParam;j++) { strParams = strParams + m_ScriptableList[i]->m_vParameters[j]; if (j != m_ScriptableList[i]->m_vParameters.size()-1) strParams = strParams + " "; } for (size_t j = m_ScriptableList[i]->m_iMinParam;j<m_ScriptableList[i]->m_iMaxParam;j++) { strParams = strParams + "["+m_ScriptableList[i]->m_vParameters[j]+"]"; if (j != m_ScriptableList[i]->m_vParameters.size()-1) strParams = strParams + " "; } m_pMasterController->DebugOut()->printf("\"%s\" %s: %s", m_ScriptableList[i]->m_strCommand.c_str(), strParams.c_str(), m_ScriptableList[i]->m_strDescription.c_str()); } return true; } return false; }<commit_msg>Handle blank lines correctly.<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2008 Scientific Computing and Imaging Institute, University of Utah. 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. */ //! File : Scripting.cpp //! Author : Jens Krueger //! SCI Institute //! University of Utah //! Date : January 2009 // //! Copyright (C) 2008 SCI Institute #include "Scripting.h" #include <Controller/MasterController.h> #include <Basics/SysTools.h> #include <sstream> using namespace std; ScriptableListElement::ScriptableListElement(Scriptable* source, const std::string& strCommand, const std::string& strParameters, const std::string& strDescription) : m_source(source), m_strCommand(strCommand), m_strDescription(strDescription) { m_vParameters = SysTools::Tokenize(strParameters, false); m_iMaxParam = UINT32(m_vParameters.size()); m_iMinParam = 0; bool bFoundOptional = false; for (UINT32 i = 0;i<m_iMaxParam;i++) { if (m_vParameters[i][0] == '[' && m_vParameters[i][m_vParameters[i].size()-1] == ']') { bFoundOptional = true; m_vParameters[i] = string(m_vParameters[i].begin()+1, m_vParameters[i].end()-1); } else { if (!bFoundOptional) m_iMinParam++; // else // this else would be an syntax error case but lets just assume all parameters after the first optional parameter are also optional } } } Scripting::Scripting(MasterController* pMasterController) : m_pMasterController(pMasterController), m_bEcho(false) { RegisterCalls(this); } Scripting::~Scripting() { for (size_t i = 0;i<m_ScriptableList.size();i++) delete m_ScriptableList[i]; } bool Scripting::RegisterCommand(Scriptable* source, const std::string& strCommand, const std::string& strParameters, const std::string& strDescription) { // commands may not contain whitespaces vector<string> strTest = SysTools::Tokenize(strCommand, false); if (strTest.size() != 1) return false; // commands must be unique for (size_t i = 0;i<m_ScriptableList.size();i++) { if (m_ScriptableList[i]->m_strCommand == strCommand) return false; } // ok, all seems fine: add the command to the list ScriptableListElement* elem = new ScriptableListElement(source, strCommand, strParameters, strDescription); m_ScriptableList.push_back(elem); return true; } bool Scripting::ParseLine(const string& strLine) { // tokenize string vector<string> vParameters = SysTools::Tokenize(strLine); if(vParameters.empty()) { return true; } string strMessage = ""; bool bResult = ParseCommand(vParameters, strMessage); if (!bResult) { if (strMessage == "") m_pMasterController->DebugOut()->printf("Input \"%s\" not understood, try \"help\"!", strLine.c_str()); else m_pMasterController->DebugOut()->printf(strMessage.c_str()); } else if (m_bEcho) m_pMasterController->DebugOut()->printf("OK (%s)", strLine.c_str()); return bResult; } bool Scripting::ParseCommand(const vector<string>& strTokenized, string& strMessage) { if (strTokenized.empty()) return false; string strCommand = strTokenized[0]; vector<string> strParams(strTokenized.begin()+1, strTokenized.end()); strMessage = ""; for (size_t i = 0;i<m_ScriptableList.size();i++) { if (m_ScriptableList[i]->m_strCommand == strCommand) { if (strParams.size() >= m_ScriptableList[i]->m_iMinParam && strParams.size() <= m_ScriptableList[i]->m_iMaxParam) { return m_ScriptableList[i]->m_source->Execute(strCommand, strParams, strMessage); } else { strMessage = "Parameter mismatch for command \""+strCommand+"\""; return false; } } } return false; } bool Scripting::ParseFile(const std::string& strFilename) { string line; ifstream fileData(strFilename.c_str()); UINT32 iLine=0; if (fileData.is_open()) { while (! fileData.eof() ) { getline (fileData,line); iLine++; SysTools::RemoveLeadingWhitespace(line); if (line.size() == 0) continue; // skip empty lines if (line[0] == '#') continue; // skip comments if (!ParseLine(line)) { m_pMasterController->DebugOut()->Error("Scripting::ParseFile:","Error reading line %i in file %s (%s)", iLine, strFilename.c_str(), line.c_str()); fileData.close(); return false; } } } else { m_pMasterController->DebugOut()->Error("Scripting::ParseFile:","Error opening script file %s", strFilename.c_str()); return false; } fileData.close(); return true; } void Scripting::RegisterCalls(Scripting* pScriptEngine) { pScriptEngine->RegisterCommand(this, "help", "", "show all commands"); pScriptEngine->RegisterCommand(this, "echo", "on/off", "turn feedback on succesfull command execution on or off"); } bool Scripting::Execute(const std::string& strCommand, const std::vector< std::string >& strParams, std::string& strMessage) { strMessage = ""; if (strCommand == "echo") { m_bEcho = SysTools::ToLowerCase(strParams[0]) == "on"; return true; } else if (strCommand == "help") { m_pMasterController->DebugOut()->printf("Command Listing:"); m_pMasterController->DebugOut()->printf("\"help\" : this help screen"); for (size_t i = 0;i<m_ScriptableList.size();i++) { string strParams = ""; for (size_t j = 0;j<m_ScriptableList[i]->m_iMinParam;j++) { strParams = strParams + m_ScriptableList[i]->m_vParameters[j]; if (j != m_ScriptableList[i]->m_vParameters.size()-1) strParams = strParams + " "; } for (size_t j = m_ScriptableList[i]->m_iMinParam;j<m_ScriptableList[i]->m_iMaxParam;j++) { strParams = strParams + "["+m_ScriptableList[i]->m_vParameters[j]+"]"; if (j != m_ScriptableList[i]->m_vParameters.size()-1) strParams = strParams + " "; } m_pMasterController->DebugOut()->printf("\"%s\" %s: %s", m_ScriptableList[i]->m_strCommand.c_str(), strParams.c_str(), m_ScriptableList[i]->m_strDescription.c_str()); } return true; } return false; } <|endoftext|>
<commit_before>#include "TexManagementGL.h" std::string TexManagementGL::fetchTexPath(TextureId texId) { std::string pathComplete = texPath; switch(texId) { case TEXTURE_PACMAN: pathComplete += texPacman; break; case TEXTURE_WALL: pathComplete += texWall; break; case TEXTURE_PILL: pathComplete += texPill; break; case TEXTURE_PILL_BLOODY: pathComplete += texPillBloody; break; case TEXTURE_PILL_CONSUME: pathComplete += texConsume; break; default: pathComplete += texPlaceHolder; break; } return pathComplete; } void TexManagementGL::init() { std::vector<TextureId>* loadTex = new std::vector<TextureId>(); loadTex->push_back(TEXTURE_PACMAN); loadTex->push_back(TEXTURE_PILL); loadTex->push_back(TEXTURE_PILL_BLOODY); loadTex->push_back(TEXTURE_GHOST); loadTex->push_back(TEXTURE_WALL); loadTex->push_back(TEXTURE_PLACEHOLDER); loadTex->push_back(TEXTURE_CONSUME); std::string completePath; for(unsigned int i = 0; i < loadTex->size(); i++) { completePath = fetchTexPath(loadTex->at(i)); Texture* tex = loadTexture(loadTex->at(i), completePath); textures->push_back(tex); } delete loadTex; } Texture* TexManagementGL::loadTexture(TextureId id, std::string completePath) { Texture* texture = new Texture(); texture->textureId = id; bool textureLoaded = LoadTGA(texture, completePath.c_str()); if(textureLoaded) { //Creates a texture and put it's ID in the given integer variable glGenTextures(1, &(texture->texID)); //Setting as active texture glBindTexture(GL_TEXTURE_2D, texture->texID); //Load texture into memory glTexImage2D( GL_TEXTURE_2D, 0, texture->bpp / 8, texture->width, texture->height, 0, texture->type, GL_UNSIGNED_BYTE, texture->imageData); } else { throw 0; } return texture; } Texture* TexManagementGL::getTexture(TextureId textureId) { Texture* texture = NULL; bool textureFound = false; for(unsigned int i = 0; i < textures->size() && !textureFound; i++) { if(textures->at(i)->textureId == textureId) { texture = textures->at(i); textureFound = true; } } return texture; } TexManagementGL::TexManagementGL() { textures = new std::vector<Texture*>(); } TexManagementGL::~TexManagementGL() { if(textures) { for(unsigned int i = 0; i < textures->size(); i++) { if(textures->at(i)) { free(textures->at(i)->imageData); //Free raw image data if(textures->at(i)) { delete textures->at(i); textures->at(i) = NULL; } } } delete textures; } }<commit_msg>redundant<commit_after>#include "TexManagementGL.h" std::string TexManagementGL::fetchTexPath(TextureId texId) { std::string pathComplete = texPath; switch(texId) { case TEXTURE_PACMAN: pathComplete += texPacman; break; case TEXTURE_WALL: pathComplete += texWall; break; case TEXTURE_PILL: pathComplete += texPill; break; case TEXTURE_PILL_BLOODY: pathComplete += texPillBloody; break; case TEXTURE_CONSUME: pathComplete += texConsume; break; default: pathComplete += texPlaceHolder; break; } return pathComplete; } void TexManagementGL::init() { std::vector<TextureId>* loadTex = new std::vector<TextureId>(); loadTex->push_back(TEXTURE_PACMAN); loadTex->push_back(TEXTURE_PILL); loadTex->push_back(TEXTURE_PILL_BLOODY); loadTex->push_back(TEXTURE_GHOST); loadTex->push_back(TEXTURE_WALL); loadTex->push_back(TEXTURE_PLACEHOLDER); loadTex->push_back(TEXTURE_CONSUME); std::string completePath; for(unsigned int i = 0; i < loadTex->size(); i++) { completePath = fetchTexPath(loadTex->at(i)); Texture* tex = loadTexture(loadTex->at(i), completePath); textures->push_back(tex); } delete loadTex; } Texture* TexManagementGL::loadTexture(TextureId id, std::string completePath) { Texture* texture = new Texture(); texture->textureId = id; bool textureLoaded = LoadTGA(texture, completePath.c_str()); if(textureLoaded) { //Creates a texture and put it's ID in the given integer variable glGenTextures(1, &(texture->texID)); //Setting as active texture glBindTexture(GL_TEXTURE_2D, texture->texID); //Load texture into memory glTexImage2D( GL_TEXTURE_2D, 0, texture->bpp / 8, texture->width, texture->height, 0, texture->type, GL_UNSIGNED_BYTE, texture->imageData); } else { throw 0; } return texture; } Texture* TexManagementGL::getTexture(TextureId textureId) { Texture* texture = NULL; bool textureFound = false; for(unsigned int i = 0; i < textures->size() && !textureFound; i++) { if(textures->at(i)->textureId == textureId) { texture = textures->at(i); textureFound = true; } } return texture; } TexManagementGL::TexManagementGL() { textures = new std::vector<Texture*>(); } TexManagementGL::~TexManagementGL() { if(textures) { for(unsigned int i = 0; i < textures->size(); i++) { if(textures->at(i)) { free(textures->at(i)->imageData); //Free raw image data if(textures->at(i)) { delete textures->at(i); textures->at(i) = NULL; } } } delete textures; } }<|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/math/math_function.h" #include "paddle/fluid/operators/math/softmax.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; using LoDTensor = framework::LoDTensor; template <typename T> class SequenceSoftmaxCUDNNKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* x = ctx.Input<LoDTensor>("X"); auto* out = ctx.Output<LoDTensor>("Out"); auto& lod = x->lod(); auto& dims = x->dims(); const size_t level = lod.size() - 1; PADDLE_ENFORCE_EQ(dims[0], static_cast<int64_t>(lod[level].back()), "The first dimension of Input(X) should be equal to the " "sum of all sequences' lengths."); PADDLE_ENFORCE_EQ(dims[0], x->numel(), "The width of each timestep in Input(X) of " "SequenceSoftmaxOp should be 1."); out->mutable_data<T>(ctx.GetPlace()); for (int i = 0; i < static_cast<int>(lod[level].size()) - 1; ++i) { int start_pos = static_cast<int>(lod[level][i]); int end_pos = static_cast<int>(lod[level][i + 1]); Tensor x_i = x->Slice(start_pos, end_pos); Tensor out_i = out->Slice(start_pos, end_pos); // Reshape from (end_pos - start_pos) x 1UL to 1UL x (end_pos - start_pos) framework::DDim dims_i = // framework::make_ddim({1UL, end_pos - start_pos, 1UL, 1UL}); framework::make_ddim({1UL, end_pos - start_pos}); x_i.Resize(dims_i); out_i.Resize(dims_i); math::SoftmaxCUDNNFunctor<T>()( ctx.template device_context<platform::CUDADeviceContext>(), &x_i, &out_i); } } }; template <typename T> class SequenceSoftmaxGradCUDNNKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* out = ctx.Input<LoDTensor>("Out"); auto* out_grad = ctx.Input<LoDTensor>(framework::GradVarName("Out")); auto* x = ctx.Input<LoDTensor>("X"); auto* x_grad = ctx.Output<LoDTensor>(framework::GradVarName("X")); if (x_grad) { x_grad->set_lod(x->lod()); } auto& lod = x->lod(); const size_t level = lod.size() - 1; x_grad->mutable_data<T>(ctx.GetPlace()); for (int i = 0; i < static_cast<int>(lod[level].size()) - 1; ++i) { int start_pos = static_cast<int>(lod[level][i]); int end_pos = static_cast<int>(lod[level][i + 1]); Tensor out_i = out->Slice(start_pos, end_pos); Tensor out_grad_i = out_grad->Slice(start_pos, end_pos); Tensor x_grad_i = x_grad->Slice(start_pos, end_pos); // Reshape from (end_pos - start_pos) x 1UL to 1UL x (end_pos - start_pos) framework::DDim dims_i = framework::make_ddim({1UL, end_pos - start_pos}); out_i.Resize(dims_i); out_grad_i.Resize(dims_i); x_grad_i.Resize(dims_i); math::SoftmaxGradCUDNNFunctor<T>()( ctx.template device_context<platform::CUDADeviceContext>(), &out_i, &out_grad_i, &x_grad_i); } } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_KERNEL(sequence_softmax, CUDNN, ::paddle::platform::CUDAPlace, ops::SequenceSoftmaxCUDNNKernel<float>, ops::SequenceSoftmaxCUDNNKernel<double>); REGISTER_OP_KERNEL(sequence_softmax_grad, CUDNN, ::paddle::platform::CUDAPlace, ops::SequenceSoftmaxGradCUDNNKernel<float>, ops::SequenceSoftmaxGradCUDNNKernel<double>); <commit_msg>polish two error message, test=develop (#24778)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/math/math_function.h" #include "paddle/fluid/operators/math/softmax.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; using LoDTensor = framework::LoDTensor; template <typename T> class SequenceSoftmaxCUDNNKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* x = ctx.Input<LoDTensor>("X"); auto* out = ctx.Output<LoDTensor>("Out"); auto& lod = x->lod(); auto& dims = x->dims(); const size_t level = lod.size() - 1; PADDLE_ENFORCE_EQ( dims[0], static_cast<int64_t>(lod[level].back()), platform::errors::InvalidArgument( "The first dimension of Input(X) should be equal to the sum of all " "sequences' lengths. But received first dimension of Input(X) is " "%d, the sum of all sequences' lengths is %d.", dims[0], static_cast<int64_t>(lod[level].back()))); PADDLE_ENFORCE_EQ(dims[0], x->numel(), platform::errors::InvalidArgument( "The width of each timestep in Input(X) of " "SequenceSoftmaxOp should be 1.")); out->mutable_data<T>(ctx.GetPlace()); for (int i = 0; i < static_cast<int>(lod[level].size()) - 1; ++i) { int start_pos = static_cast<int>(lod[level][i]); int end_pos = static_cast<int>(lod[level][i + 1]); Tensor x_i = x->Slice(start_pos, end_pos); Tensor out_i = out->Slice(start_pos, end_pos); // Reshape from (end_pos - start_pos) x 1UL to 1UL x (end_pos - start_pos) framework::DDim dims_i = // framework::make_ddim({1UL, end_pos - start_pos, 1UL, 1UL}); framework::make_ddim({1UL, end_pos - start_pos}); x_i.Resize(dims_i); out_i.Resize(dims_i); math::SoftmaxCUDNNFunctor<T>()( ctx.template device_context<platform::CUDADeviceContext>(), &x_i, &out_i); } } }; template <typename T> class SequenceSoftmaxGradCUDNNKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* out = ctx.Input<LoDTensor>("Out"); auto* out_grad = ctx.Input<LoDTensor>(framework::GradVarName("Out")); auto* x = ctx.Input<LoDTensor>("X"); auto* x_grad = ctx.Output<LoDTensor>(framework::GradVarName("X")); if (x_grad) { x_grad->set_lod(x->lod()); } auto& lod = x->lod(); const size_t level = lod.size() - 1; x_grad->mutable_data<T>(ctx.GetPlace()); for (int i = 0; i < static_cast<int>(lod[level].size()) - 1; ++i) { int start_pos = static_cast<int>(lod[level][i]); int end_pos = static_cast<int>(lod[level][i + 1]); Tensor out_i = out->Slice(start_pos, end_pos); Tensor out_grad_i = out_grad->Slice(start_pos, end_pos); Tensor x_grad_i = x_grad->Slice(start_pos, end_pos); // Reshape from (end_pos - start_pos) x 1UL to 1UL x (end_pos - start_pos) framework::DDim dims_i = framework::make_ddim({1UL, end_pos - start_pos}); out_i.Resize(dims_i); out_grad_i.Resize(dims_i); x_grad_i.Resize(dims_i); math::SoftmaxGradCUDNNFunctor<T>()( ctx.template device_context<platform::CUDADeviceContext>(), &out_i, &out_grad_i, &x_grad_i); } } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_KERNEL(sequence_softmax, CUDNN, ::paddle::platform::CUDAPlace, ops::SequenceSoftmaxCUDNNKernel<float>, ops::SequenceSoftmaxCUDNNKernel<double>); REGISTER_OP_KERNEL(sequence_softmax_grad, CUDNN, ::paddle::platform::CUDAPlace, ops::SequenceSoftmaxGradCUDNNKernel<float>, ops::SequenceSoftmaxGradCUDNNKernel<double>); <|endoftext|>
<commit_before>// This file is part of the KDE libraries // Copyright (C) 2008 Paul Giannaros <paul@giannaros.org> // Copyright (C) 2009 Dominik Haumann <dhaumann kde org> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) version 3. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public License // along with this library; see the file COPYING.LIB. If not, write to // the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301, USA. #include "katescript.h" #include "katescriptdocument.h" #include "katescriptview.h" #include "kateview.h" #include "katedocument.h" #include <iostream> #include <QFile> #include <QScriptEngine> #include <QScriptValue> #include <QScriptContext> #include <QFileInfo> #include <kdebug.h> #include <klocale.h> #include <kstandarddirs.h> //BEGIN conversion functions for Cursors and Ranges /** Converstion function from KTextEditor::Cursor to QtScript cursor */ static QScriptValue cursorToScriptValue(QScriptEngine *engine, const KTextEditor::Cursor &cursor) { QString code = QString("new Cursor(%1, %2);").arg(cursor.line()) .arg(cursor.column()); return engine->evaluate(code); } /** Converstion function from QtScript cursor to KTextEditor::Cursor */ static void cursorFromScriptValue(const QScriptValue &obj, KTextEditor::Cursor &cursor) { cursor.setPosition(obj.property("line").toInt32(), obj.property("column").toInt32()); } /** Converstion function from QtScript range to KTextEditor::Range */ static QScriptValue rangeToScriptValue(QScriptEngine *engine, const KTextEditor::Range &range) { QString code = QString("new Range(%1, %2, %3, %4);").arg(range.start().line()) .arg(range.start().column()) .arg(range.end().line()) .arg(range.end().column()); return engine->evaluate(code); } /** Converstion function from QtScript range to KTextEditor::Range */ static void rangeFromScriptValue(const QScriptValue &obj, KTextEditor::Range &range) { range.start().setPosition(obj.property("start").property("line").toInt32(), obj.property("start").property("column").toInt32()); range.end().setPosition(obj.property("end").property("line").toInt32(), obj.property("end").property("column").toInt32()); } //END namespace Kate { namespace Script { QScriptValue debug(QScriptContext *context, QScriptEngine *engine) { QStringList message; for(int i = 0; i < context->argumentCount(); ++i) { message << context->argument(i).toString(); } // debug in blue to distance from other debug output if necessary std::cerr << "\033[34m" << qPrintable(message.join(" ")) << "\033[0m\n"; return engine->nullValue(); } } } bool KateScript::s_scriptingApiLoaded = false; void KateScript::reloadScriptingApi() { s_scriptingApiLoaded = false; } bool KateScript::readFile(const QString& sourceUrl, QString& sourceCode) { sourceCode = QString(); QFile file(sourceUrl); if (!file.open(QIODevice::ReadOnly)) { kDebug(13050) << i18n("Unable to find '%1'", sourceUrl); return false; } else { QTextStream stream(&file); stream.setCodec("UTF-8"); sourceCode = stream.readAll(); file.close(); } return true; } KateScript::KateScript(const QString &url) : m_loaded(false) , m_loadSuccessful(false) , m_url(url) , m_engine(0) , m_document(0) , m_view(0) { } KateScript::~KateScript() { if(m_loadSuccessful) { // remove data... delete m_engine; delete m_document; delete m_view; } } void KateScript::displayBacktrace(const QScriptValue &error, const QString &header) { if(!m_engine) { std::cerr << "KateScript::displayBacktrace: no engine, cannot display error\n"; return; } std::cerr << "\033[31m"; if(!header.isNull()) std::cerr << qPrintable(header) << ":\n"; if(error.isError()) std::cerr << qPrintable(error.toString()) << '\n'; std::cerr << qPrintable(m_engine->uncaughtExceptionBacktrace().join("\n")); std::cerr << "\033[0m" << '\n'; } void KateScript::clearExceptions() { m_engine->clearExceptions(); } QScriptValue KateScript::global(const QString &name) { // load the script if necessary if(!load()) return QScriptValue(); return m_engine->globalObject().property(name); } QScriptValue KateScript::function(const QString &name) { QScriptValue value = global(name); if(!value.isFunction()) return QScriptValue(); return value; } bool KateScript::initApi () { // cache file names static QStringList apiFileBaseNames; static QHash<QString, QString> apiBaseName2FileName; static QHash<QString, QString> apiBaseName2Content; // read katepart javascript api if (!s_scriptingApiLoaded) { s_scriptingApiLoaded = true; apiFileBaseNames.clear (); apiBaseName2FileName.clear (); apiBaseName2Content.clear (); // get all api files const QStringList list = KGlobal::dirs()->findAllResources("data","katepart/api/*.js", KStandardDirs::NoDuplicates); for ( QStringList::ConstIterator it = list.begin(); it != list.end(); ++it ) { // get abs filename.... QFileInfo fi(*it); const QString absPath = fi.absoluteFilePath(); const QString baseName = fi.baseName (); // remember filenames apiFileBaseNames.append (baseName); apiBaseName2FileName[baseName] = absPath; // read the file QString content; readFile(absPath, content); apiBaseName2Content[baseName] = content; } // sort... apiFileBaseNames.sort (); } // register all script apis found for ( QStringList::ConstIterator it = apiFileBaseNames.begin(); it != apiFileBaseNames.end(); ++it ) { // try to load into engine, bail out one error, use fullpath for error messages QScriptValue apiObject = m_engine->evaluate(apiBaseName2Content[*it], apiBaseName2FileName[*it]); if (hasException(apiObject, apiBaseName2FileName[*it])) { return false; } } // success ;) return true; } bool KateScript::load() { if(m_loaded) return m_loadSuccessful; m_loaded = true; m_loadSuccessful = false; // here set to false, and at end of function to true // read the script file into memory QString source; if (!readFile(m_url, source)) { return false; } // create script engine, register meta types m_engine = new QScriptEngine(); qScriptRegisterMetaType (m_engine, cursorToScriptValue, cursorFromScriptValue); qScriptRegisterMetaType (m_engine, rangeToScriptValue, rangeFromScriptValue); // init API if (!initApi ()) return false; // register scripts itself QScriptValue result = m_engine->evaluate(source, m_url); if (hasException(result, m_url)) { return false; } // yip yip! initEngine(); m_loadSuccessful = true; return true; } bool KateScript::hasException(const QScriptValue& object, const QString& file) { if(m_engine->hasUncaughtException()) { displayBacktrace(object, i18n("Error loading script %1\n", file)); m_errorMessage = i18n("Error loading script %1", file); delete m_engine; m_engine = 0; m_loadSuccessful = false; return true; } return false; } void KateScript::initEngine() { // set the view/document objects as necessary m_engine->globalObject().setProperty("document", m_engine->newQObject(m_document = new KateScriptDocument())); m_engine->globalObject().setProperty("view", m_engine->newQObject(m_view = new KateScriptView())); m_engine->globalObject().setProperty("debug", m_engine->newFunction(Kate::Script::debug)); } bool KateScript::setView(KateView *view) { if (!load()) return false; // setup the stuff m_document->setDocument (view->doc()); m_view->setView (view); return true; } // kate: space-indent on; indent-width 2; replace-tabs on; <commit_msg>Fix iterator<commit_after>// This file is part of the KDE libraries // Copyright (C) 2008 Paul Giannaros <paul@giannaros.org> // Copyright (C) 2009 Dominik Haumann <dhaumann kde org> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) version 3. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public License // along with this library; see the file COPYING.LIB. If not, write to // the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301, USA. #include "katescript.h" #include "katescriptdocument.h" #include "katescriptview.h" #include "kateview.h" #include "katedocument.h" #include <iostream> #include <QFile> #include <QScriptEngine> #include <QScriptValue> #include <QScriptContext> #include <QFileInfo> #include <kdebug.h> #include <klocale.h> #include <kstandarddirs.h> //BEGIN conversion functions for Cursors and Ranges /** Converstion function from KTextEditor::Cursor to QtScript cursor */ static QScriptValue cursorToScriptValue(QScriptEngine *engine, const KTextEditor::Cursor &cursor) { QString code = QString("new Cursor(%1, %2);").arg(cursor.line()) .arg(cursor.column()); return engine->evaluate(code); } /** Converstion function from QtScript cursor to KTextEditor::Cursor */ static void cursorFromScriptValue(const QScriptValue &obj, KTextEditor::Cursor &cursor) { cursor.setPosition(obj.property("line").toInt32(), obj.property("column").toInt32()); } /** Converstion function from QtScript range to KTextEditor::Range */ static QScriptValue rangeToScriptValue(QScriptEngine *engine, const KTextEditor::Range &range) { QString code = QString("new Range(%1, %2, %3, %4);").arg(range.start().line()) .arg(range.start().column()) .arg(range.end().line()) .arg(range.end().column()); return engine->evaluate(code); } /** Converstion function from QtScript range to KTextEditor::Range */ static void rangeFromScriptValue(const QScriptValue &obj, KTextEditor::Range &range) { range.start().setPosition(obj.property("start").property("line").toInt32(), obj.property("start").property("column").toInt32()); range.end().setPosition(obj.property("end").property("line").toInt32(), obj.property("end").property("column").toInt32()); } //END namespace Kate { namespace Script { QScriptValue debug(QScriptContext *context, QScriptEngine *engine) { QStringList message; for(int i = 0; i < context->argumentCount(); ++i) { message << context->argument(i).toString(); } // debug in blue to distance from other debug output if necessary std::cerr << "\033[34m" << qPrintable(message.join(" ")) << "\033[0m\n"; return engine->nullValue(); } } } bool KateScript::s_scriptingApiLoaded = false; void KateScript::reloadScriptingApi() { s_scriptingApiLoaded = false; } bool KateScript::readFile(const QString& sourceUrl, QString& sourceCode) { sourceCode = QString(); QFile file(sourceUrl); if (!file.open(QIODevice::ReadOnly)) { kDebug(13050) << i18n("Unable to find '%1'", sourceUrl); return false; } else { QTextStream stream(&file); stream.setCodec("UTF-8"); sourceCode = stream.readAll(); file.close(); } return true; } KateScript::KateScript(const QString &url) : m_loaded(false) , m_loadSuccessful(false) , m_url(url) , m_engine(0) , m_document(0) , m_view(0) { } KateScript::~KateScript() { if(m_loadSuccessful) { // remove data... delete m_engine; delete m_document; delete m_view; } } void KateScript::displayBacktrace(const QScriptValue &error, const QString &header) { if(!m_engine) { std::cerr << "KateScript::displayBacktrace: no engine, cannot display error\n"; return; } std::cerr << "\033[31m"; if(!header.isNull()) std::cerr << qPrintable(header) << ":\n"; if(error.isError()) std::cerr << qPrintable(error.toString()) << '\n'; std::cerr << qPrintable(m_engine->uncaughtExceptionBacktrace().join("\n")); std::cerr << "\033[0m" << '\n'; } void KateScript::clearExceptions() { m_engine->clearExceptions(); } QScriptValue KateScript::global(const QString &name) { // load the script if necessary if(!load()) return QScriptValue(); return m_engine->globalObject().property(name); } QScriptValue KateScript::function(const QString &name) { QScriptValue value = global(name); if(!value.isFunction()) return QScriptValue(); return value; } bool KateScript::initApi () { // cache file names static QStringList apiFileBaseNames; static QHash<QString, QString> apiBaseName2FileName; static QHash<QString, QString> apiBaseName2Content; // read katepart javascript api if (!s_scriptingApiLoaded) { s_scriptingApiLoaded = true; apiFileBaseNames.clear (); apiBaseName2FileName.clear (); apiBaseName2Content.clear (); // get all api files const QStringList list = KGlobal::dirs()->findAllResources("data","katepart/api/*.js", KStandardDirs::NoDuplicates); for ( QStringList::ConstIterator it = list.begin(); it != list.end(); ++it ) { // get abs filename.... QFileInfo fi(*it); const QString absPath = fi.absoluteFilePath(); const QString baseName = fi.baseName (); // remember filenames apiFileBaseNames.append (baseName); apiBaseName2FileName[baseName] = absPath; // read the file QString content; readFile(absPath, content); apiBaseName2Content[baseName] = content; } // sort... apiFileBaseNames.sort (); } // register all script apis found for ( QStringList::ConstIterator it = apiFileBaseNames.constBegin(); it != apiFileBaseNames.constEnd(); ++it ) { // try to load into engine, bail out one error, use fullpath for error messages QScriptValue apiObject = m_engine->evaluate(apiBaseName2Content[*it], apiBaseName2FileName[*it]); if (hasException(apiObject, apiBaseName2FileName[*it])) { return false; } } // success ;) return true; } bool KateScript::load() { if(m_loaded) return m_loadSuccessful; m_loaded = true; m_loadSuccessful = false; // here set to false, and at end of function to true // read the script file into memory QString source; if (!readFile(m_url, source)) { return false; } // create script engine, register meta types m_engine = new QScriptEngine(); qScriptRegisterMetaType (m_engine, cursorToScriptValue, cursorFromScriptValue); qScriptRegisterMetaType (m_engine, rangeToScriptValue, rangeFromScriptValue); // init API if (!initApi ()) return false; // register scripts itself QScriptValue result = m_engine->evaluate(source, m_url); if (hasException(result, m_url)) { return false; } // yip yip! initEngine(); m_loadSuccessful = true; return true; } bool KateScript::hasException(const QScriptValue& object, const QString& file) { if(m_engine->hasUncaughtException()) { displayBacktrace(object, i18n("Error loading script %1\n", file)); m_errorMessage = i18n("Error loading script %1", file); delete m_engine; m_engine = 0; m_loadSuccessful = false; return true; } return false; } void KateScript::initEngine() { // set the view/document objects as necessary m_engine->globalObject().setProperty("document", m_engine->newQObject(m_document = new KateScriptDocument())); m_engine->globalObject().setProperty("view", m_engine->newQObject(m_view = new KateScriptView())); m_engine->globalObject().setProperty("debug", m_engine->newFunction(Kate::Script::debug)); } bool KateScript::setView(KateView *view) { if (!load()) return false; // setup the stuff m_document->setDocument (view->doc()); m_view->setView (view); return true; } // kate: space-indent on; indent-width 2; replace-tabs on; <|endoftext|>
<commit_before>/* Copyright (c) 2009 Yahoo! Inc. All rights reserved. The copyrights embodied in the content of this file are licensed under the BSD (revised) open source license */ #include <math.h> #include <ctype.h> #include "parse_example.h" #include "hash.h" #include "cache.h" #include "unique_sort.h" using namespace std; size_t hashstring (substring s, unsigned long h) { size_t ret = 0; //trim leading whitespace for(; *(s.start) <= 0x20 && s.start < s.end; s.start++); //trim trailing white space for(; *(s.end-1) <= 0x20 && s.end > s.start; s.end--); char *p = s.start; while (p != s.end) if (isdigit(*p)) ret = 10*ret + *(p++) - '0'; else return uniform_hash((unsigned char *)s.start, s.end - s.start, h); return ret + h; } size_t hashall (substring s, unsigned long h) { return uniform_hash((unsigned char *)s.start, s.end - s.start, h); } hash_func_t getHasher(const string& s){ if (s=="strings") return hashstring; else if(s=="all") return hashall; else{ cerr << "Unknown hash function: " << s << ". Exiting " << endl; exit(1); } } void feature_value(substring &s, v_array<substring>& name, float &v) { tokenize(':', s, name); switch (name.index()) { case 0: case 1: v = 1.; break; case 2: v = float_of_substring(name[1]); if ( isnan(v)) { cerr << "error NaN value for feature: "; cerr.write(name[0].start, name[0].end - name[0].start); cerr << " terminating." << endl; exit(1); } break; default: cerr << "example with a wierd name. What is "; cerr.write(s.start, s.end - s.start); cerr << "\n"; } } // new should be empty. --Alex template<class T> void copy_v_array(v_array<T>& old, v_array<T>& new_va) { // allocate new memory for new. new_va.begin = (T *) malloc(sizeof(T)*old.index()); // copy the old to the new. memcpy(new_va.begin,old.begin,sizeof(T)*old.index()); // update pointers new_va.end = new_va.begin + old.index(); new_va.end_array = new_va.end; } char* c_string_of_substring(substring s) { size_t len = s.end - s.start+1; char* ret = (char *)calloc(len,sizeof(char)); memcpy(ret,s.start,len-1); return ret; } char* copy(char* base) { size_t len = 0; while (base[len++] != '\0'); char* ret = (char *)calloc(len,sizeof(char)); memcpy(ret,base,len); return ret; } int read_features(parser* p, void* ex) { example* ae = (example*)ex; char *line=NULL; int num_chars = readto(*(p->input), line, '\n'); if (num_chars == 0) return num_chars; substring example = {line, line + num_chars}; tokenize('|', example, p->channels); p->lp->default_label(ae->ld); substring* feature_start = &(p->channels[1]); if (*line == '|') feature_start = &(p->channels[0]); else { substring label_space = p->channels[0]; char* tab_location = safe_index(label_space.start, '\t', label_space.end); if (tab_location != label_space.end) label_space.start = tab_location+1; tokenize(' ',label_space,p->words); if (p->words.index() > 0 && p->words.last().end == label_space.end) //The last field is a tag, so record and strip it off { substring tag = p->words.pop(); push_many(ae->tag, tag.start, tag.end - tag.start); } p->lp->parse_label(ae->ld, p->words); } size_t mask = global.parse_mask; bool audit = global.audit; for (substring* i = feature_start; i != p->channels.end; i++) { substring channel = *i; tokenize(' ',channel, p->words); if (p->words.begin == p->words.end) continue; float channel_v = 1.; size_t channel_hash; char* base=NULL; size_t index = 0; bool new_index = false; size_t feature_offset = 0; if (channel.start[0] != ' ')//we have a nonanonymous namespace { feature_offset++; feature_value(p->words[0], p->name, channel_v); if (p->name.index() > 0) { index = (unsigned char)(*p->name[0].start); if (ae->atomics[index].begin == ae->atomics[index].end) new_index = true; } if (audit) base = c_string_of_substring(p->name[0]); channel_hash = p->hasher(p->name[0], hash_base); } else { index = (unsigned char)' '; if (ae->atomics[index].begin == ae->atomics[index].end) new_index = true; if (audit) { base = (char *)calloc(2,sizeof(char)); base[0]=' '; base[1]='\0'; } channel_hash = 0; } for (substring* i = p->words.begin+feature_offset; i != p->words.end; i++) { float v = 0.; feature_value(*i, p->name, v); v *= channel_v; size_t word_hash = (p->hasher(p->name[0], channel_hash)) & mask; feature f = {v,(uint32_t)word_hash}; ae->sum_feat_sq[index] += v*v; push(ae->atomics[index], f); } if (new_index && ae->atomics[index].begin != ae->atomics[index].end) push(ae->indices, index); if (audit) { for (substring* i = p->words.begin+feature_offset; i != p->words.end; i++) { float v = 0.; feature_value(*i, p->name, v); v *= channel_v; size_t word_hash = (p->hasher(p->name[0], channel_hash)) & mask; char* feature = c_string_of_substring(p->name[0]); audit_data ad = {copy(base), feature, word_hash, v, true}; push(ae->audit_features[index], ad); } free(base); } } return num_chars; } <commit_msg>tweaked tag format to allow whitespace<commit_after>/* Copyright (c) 2009 Yahoo! Inc. All rights reserved. The copyrights embodied in the content of this file are licensed under the BSD (revised) open source license */ #include <math.h> #include <ctype.h> #include "parse_example.h" #include "hash.h" #include "cache.h" #include "unique_sort.h" using namespace std; size_t hashstring (substring s, unsigned long h) { size_t ret = 0; //trim leading whitespace for(; *(s.start) <= 0x20 && s.start < s.end; s.start++); //trim trailing white space for(; *(s.end-1) <= 0x20 && s.end > s.start; s.end--); char *p = s.start; while (p != s.end) if (isdigit(*p)) ret = 10*ret + *(p++) - '0'; else return uniform_hash((unsigned char *)s.start, s.end - s.start, h); return ret + h; } size_t hashall (substring s, unsigned long h) { return uniform_hash((unsigned char *)s.start, s.end - s.start, h); } hash_func_t getHasher(const string& s){ if (s=="strings") return hashstring; else if(s=="all") return hashall; else{ cerr << "Unknown hash function: " << s << ". Exiting " << endl; exit(1); } } void feature_value(substring &s, v_array<substring>& name, float &v) { tokenize(':', s, name); switch (name.index()) { case 0: case 1: v = 1.; break; case 2: v = float_of_substring(name[1]); if ( isnan(v)) { cerr << "error NaN value for feature: "; cerr.write(name[0].start, name[0].end - name[0].start); cerr << " terminating." << endl; exit(1); } break; default: cerr << "example with a wierd name. What is "; cerr.write(s.start, s.end - s.start); cerr << "\n"; } } // new should be empty. --Alex template<class T> void copy_v_array(v_array<T>& old, v_array<T>& new_va) { // allocate new memory for new. new_va.begin = (T *) malloc(sizeof(T)*old.index()); // copy the old to the new. memcpy(new_va.begin,old.begin,sizeof(T)*old.index()); // update pointers new_va.end = new_va.begin + old.index(); new_va.end_array = new_va.end; } char* c_string_of_substring(substring s) { size_t len = s.end - s.start+1; char* ret = (char *)calloc(len,sizeof(char)); memcpy(ret,s.start,len-1); return ret; } char* copy(char* base) { size_t len = 0; while (base[len++] != '\0'); char* ret = (char *)calloc(len,sizeof(char)); memcpy(ret,base,len); return ret; } int read_features(parser* p, void* ex) { example* ae = (example*)ex; char *line=NULL; int num_chars = readto(*(p->input), line, '\n'); if (num_chars == 0) return num_chars; substring example = {line, line + num_chars}; tokenize('|', example, p->channels); p->lp->default_label(ae->ld); substring* feature_start = &(p->channels[1]); if (*line == '|') feature_start = &(p->channels[0]); else { substring label_space = p->channels[0]; char* tab_location = safe_index(label_space.start, '\t', label_space.end); if (tab_location != label_space.end) label_space.start = tab_location+1; tokenize(' ',label_space,p->words); if (p->words.index() > 0 && (p->words.last().end == label_space.end || *(p->words.last().start)=='\'') ) //The last field is a tag, so record and strip it off { substring tag = p->words.pop(); if (*tag.start == '\'') tag.start++; push_many(ae->tag, tag.start, tag.end - tag.start); } p->lp->parse_label(ae->ld, p->words); } size_t mask = global.parse_mask; bool audit = global.audit; for (substring* i = feature_start; i != p->channels.end; i++) { substring channel = *i; tokenize(' ',channel, p->words); if (p->words.begin == p->words.end) continue; float channel_v = 1.; size_t channel_hash; char* base=NULL; size_t index = 0; bool new_index = false; size_t feature_offset = 0; if (channel.start[0] != ' ')//we have a nonanonymous namespace { feature_offset++; feature_value(p->words[0], p->name, channel_v); if (p->name.index() > 0) { index = (unsigned char)(*p->name[0].start); if (ae->atomics[index].begin == ae->atomics[index].end) new_index = true; } if (audit) base = c_string_of_substring(p->name[0]); channel_hash = p->hasher(p->name[0], hash_base); } else { index = (unsigned char)' '; if (ae->atomics[index].begin == ae->atomics[index].end) new_index = true; if (audit) { base = (char *)calloc(2,sizeof(char)); base[0]=' '; base[1]='\0'; } channel_hash = 0; } for (substring* i = p->words.begin+feature_offset; i != p->words.end; i++) { float v = 0.; feature_value(*i, p->name, v); v *= channel_v; size_t word_hash = (p->hasher(p->name[0], channel_hash)) & mask; feature f = {v,(uint32_t)word_hash}; ae->sum_feat_sq[index] += v*v; push(ae->atomics[index], f); } if (new_index && ae->atomics[index].begin != ae->atomics[index].end) push(ae->indices, index); if (audit) { for (substring* i = p->words.begin+feature_offset; i != p->words.end; i++) { float v = 0.; feature_value(*i, p->name, v); v *= channel_v; size_t word_hash = (p->hasher(p->name[0], channel_hash)) & mask; char* feature = c_string_of_substring(p->name[0]); audit_data ad = {copy(base), feature, word_hash, v, true}; push(ae->audit_features[index], ad); } free(base); } } return num_chars; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: PyVTKSpecialObject.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*----------------------------------------------------------------------- The PyVTKSpecialObject was created in Feb 2001 by David Gobbi. It was substantially updated in April 2010 by David Gobbi. A PyVTKSpecialObject is a python object that represents an object that belongs to one of the special classes in VTK, that is, classes that are not derived from vtkObjectBase. Unlike vtkObjects, these special objects are not reference counted: a PyVTKSpecialObject always contains its own copy of the C++ object. A PyVTKSpecialType is a simple structure that contains information about the C++ class, including the class name and methods. Each PyVTKSpecialObject contains a pointer to its PyVTKSpecialType. The use of PyVTKSpecialType is a bit of a cop-out. Ideally, each special type should have its own PyTypeObject struct that defines it as a distinct sub-type of PyVTKSpecialObjectType. This would allow different special types to support different protocols and behaviours, instead of just supporting different methods. -----------------------------------------------------------------------*/ #include "PyVTKSpecialObject.h" #include "vtkPythonUtil.h" #include <vtksys/ios/sstream> //-------------------------------------------------------------------- PyVTKSpecialType::PyVTKSpecialType( char *cname, char *cdocs[], PyMethodDef *cmethods, PyMethodDef *ccons, PyVTKSpecialMethods *smethods) { this->classname = PyString_FromString(cname); this->docstring = vtkPythonUtil::BuildDocString(cdocs); this->methods = cmethods; this->constructors = ccons; this->copy_func = smethods->copy_func; this->delete_func = smethods->delete_func; this->print_func = smethods->print_func; this->compare_func = smethods->compare_func; this->hash_func = smethods->hash_func; } //-------------------------------------------------------------------- static PyObject *PyVTKSpecialObject_PyString(PyVTKSpecialObject *self) { vtksys_ios::ostringstream os; self->vtk_info->print_func(os, self->vtk_ptr); const vtksys_stl::string &s = os.str(); return PyString_FromStringAndSize(s.data(), s.size()); } //-------------------------------------------------------------------- static PyObject *PyVTKSpecialObject_PyRepr(PyVTKSpecialObject *self) { vtksys_ios::ostringstream os; os << "(" << PyString_AS_STRING(self->vtk_info->classname) << ")"; self->vtk_info->print_func(os, self->vtk_ptr); const vtksys_stl::string &s = os.str(); return PyString_FromStringAndSize(s.data(), s.size()); } //-------------------------------------------------------------------- static PyObject *PyVTKSpecialObject_PyGetAttr(PyVTKSpecialObject *self, PyObject *attr) { char *name = PyString_AsString(attr); PyMethodDef *meth; if (name[0] == '_') { if (strcmp(name,"__name__") == 0) { Py_INCREF(self->vtk_info->classname); return self->vtk_info->classname; } if (strcmp(name,"__doc__") == 0) { Py_INCREF(self->vtk_info->docstring); return self->vtk_info->docstring; } if (strcmp(name,"__methods__") == 0) { meth = self->vtk_info->methods; PyObject *lst; int i, n; for (n = 0; meth && meth[n].ml_name; n++) { ; } if ((lst = PyList_New(n)) != NULL) { meth = self->vtk_info->methods; for (i = 0; i < n; i++) { PyList_SetItem(lst, i, PyString_FromString(meth[i].ml_name)); } PyList_Sort(lst); } return lst; } if (strcmp(name,"__members__") == 0) { PyObject *lst; if ((lst = PyList_New(4)) != NULL) { PyList_SetItem(lst,0,PyString_FromString("__doc__")); PyList_SetItem(lst,1,PyString_FromString("__members__")); PyList_SetItem(lst,2,PyString_FromString("__methods__")); PyList_SetItem(lst,3,PyString_FromString("__name__")); } return lst; } } for (meth = self->vtk_info->methods; meth && meth->ml_name; meth++) { if (name[0] == meth->ml_name[0] && strcmp(name+1, meth->ml_name+1) == 0) { return PyCFunction_New(meth, (PyObject *)self); } } PyErr_SetString(PyExc_AttributeError, name); return NULL; } //-------------------------------------------------------------------- static void PyVTKSpecialObject_PyDelete(PyVTKSpecialObject *self) { if (self->vtk_ptr) { self->vtk_info->delete_func(self->vtk_ptr); } self->vtk_ptr = NULL; #if (PY_MAJOR_VERSION >= 2) PyObject_Del(self); #else PyMem_DEL(self); #endif } //-------------------------------------------------------------------- static long PyVTKSpecialObject_PyHash(PyVTKSpecialObject *self) { // self->vtk_hash must never be set to anything but -1 for mutable objects if (self->vtk_hash != -1) { return self->vtk_hash; } if (self->vtk_ptr && self->vtk_info->hash_func) { int imm = 0; long val = self->vtk_info->hash_func(self->vtk_ptr, &imm); if (val != -1) { if (imm) { // cache the hash for immutable objects self->vtk_hash = val; } return val; } } // python 2.6 #if PY_VERSION_HEX >= 0x02060000 return PyObject_HashNotImplemented((PyObject *)self); #else PyErr_SetString(PyExc_TypeError, (char *)"object is not hashable"); return -1; #endif } //-------------------------------------------------------------------- static PyObject *PyVTKSpecialObject_PyRichCompare( PyVTKSpecialObject *self, PyVTKSpecialObject *o, int opid) { if (self->vtk_ptr && self->vtk_info->compare_func) { int val = self->vtk_info->compare_func(self->vtk_ptr, o->vtk_ptr, opid); if (val == 0) { Py_INCREF(Py_False); return Py_False; } else if (val != -1) { Py_INCREF(Py_True); return Py_True; } } PyErr_SetString(PyExc_TypeError, (char *)"operation not available"); return NULL; // Returning "None" is also valid, but not as informative #if PY_VERSION_HEX >= 0x02010000 // Py_INCREF(Py_NotImplemented); // return Py_NotImplemented; #else // Py_INCREF(Py_None); // return Py_None; #endif } //-------------------------------------------------------------------- static PyTypeObject PyVTKSpecialObjectType = { PyObject_HEAD_INIT(&PyType_Type) 0, (char*)"vtkspecialobject", // tp_name sizeof(PyVTKSpecialObject), // tp_basicsize 0, // tp_itemsize (destructor)PyVTKSpecialObject_PyDelete, // tp_dealloc (printfunc)0, // tp_print (getattrfunc)0, // tp_getattr (setattrfunc)0, // tp_setattr (cmpfunc)0, // tp_compare (reprfunc)PyVTKSpecialObject_PyRepr, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping (hashfunc)PyVTKSpecialObject_PyHash, // tp_hash (ternaryfunc)0, // tp_call (reprfunc)PyVTKSpecialObject_PyString, // tp_string (getattrofunc)PyVTKSpecialObject_PyGetAttr, // tp_getattro (setattrofunc)0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_HAVE_RICHCOMPARE, // tp_flags (char*)"vtkspecialobject - a vtk object not derived from vtkObjectBase.", // tp_doc 0, // tp_traverse 0, // tp_clear (richcmpfunc)PyVTKSpecialObject_PyRichCompare, // tp_richcompare 0, // tp_weaklistoffset VTK_PYTHON_UTIL_SUPRESS_UNINITIALIZED }; //-------------------------------------------------------------------- int PyVTKSpecialObject_Check(PyObject *obj) { return (obj->ob_type == &PyVTKSpecialObjectType); } //-------------------------------------------------------------------- PyObject *PyVTKSpecialObject_New(const char *classname, void *ptr) { // would be nice if "info" could be passed instead if "classname" PyVTKSpecialType *info = vtkPythonUtil::FindSpecialType(classname); #if (PY_MAJOR_VERSION >= 2) PyVTKSpecialObject *self = PyObject_New(PyVTKSpecialObject, &PyVTKSpecialObjectType); #else PyVTKSpecialObject *self = PyObject_NEW(PyVTKSpecialObject, &PyVTKSpecialObjectType); #endif self->vtk_ptr = ptr; self->vtk_hash = -1; self->vtk_info = info; return (PyObject *)self; } //-------------------------------------------------------------------- PyObject *PyVTKSpecialObject_CopyNew(const char *classname, const void *ptr) { PyVTKSpecialType *info = vtkPythonUtil::FindSpecialType(classname); if (info == 0) { char buf[256]; sprintf(buf,"cannot create object of unknown type \"%s\"",classname); PyErr_SetString(PyExc_ValueError,buf); return NULL; } #if (PY_MAJOR_VERSION >= 2) PyVTKSpecialObject *self = PyObject_New(PyVTKSpecialObject, &PyVTKSpecialObjectType); #else PyVTKSpecialObject *self = PyObject_NEW(PyVTKSpecialObject, &PyVTKSpecialObjectType); #endif self->vtk_ptr = info->copy_func(ptr); self->vtk_hash = -1; self->vtk_info = info; return (PyObject *)self; } //-------------------------------------------------------------------- PyObject *PyVTKSpecialType_New( PyMethodDef *newmethod, PyMethodDef *methods, PyMethodDef *constructors, char *classname, char *docstring[], PyVTKSpecialMethods *smethods) { // Add this type to the special type map PyVTKSpecialType *info = vtkPythonUtil::AddSpecialTypeToMap( classname, docstring, methods, constructors, smethods); // Add the built docstring to the method newmethod->ml_doc = PyString_AsString(info->docstring); // Returns a function. Returning a type object would be nicer. return PyCFunction_New(newmethod, Py_None); } <commit_msg>BUG: PyVTKSpecialObject RichCompare needs to check arg types<commit_after>/*========================================================================= Program: Visualization Toolkit Module: PyVTKSpecialObject.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*----------------------------------------------------------------------- The PyVTKSpecialObject was created in Feb 2001 by David Gobbi. It was substantially updated in April 2010 by David Gobbi. A PyVTKSpecialObject is a python object that represents an object that belongs to one of the special classes in VTK, that is, classes that are not derived from vtkObjectBase. Unlike vtkObjects, these special objects are not reference counted: a PyVTKSpecialObject always contains its own copy of the C++ object. A PyVTKSpecialType is a simple structure that contains information about the C++ class, including the class name and methods. Each PyVTKSpecialObject contains a pointer to its PyVTKSpecialType. The use of PyVTKSpecialType is a bit of a cop-out. Ideally, each special type should have its own PyTypeObject struct that defines it as a distinct sub-type of PyVTKSpecialObjectType. This would allow different special types to support different protocols and behaviours, instead of just supporting different methods. -----------------------------------------------------------------------*/ #include "PyVTKSpecialObject.h" #include "vtkPythonUtil.h" #include <vtksys/ios/sstream> //-------------------------------------------------------------------- PyVTKSpecialType::PyVTKSpecialType( char *cname, char *cdocs[], PyMethodDef *cmethods, PyMethodDef *ccons, PyVTKSpecialMethods *smethods) { this->classname = PyString_FromString(cname); this->docstring = vtkPythonUtil::BuildDocString(cdocs); this->methods = cmethods; this->constructors = ccons; this->copy_func = smethods->copy_func; this->delete_func = smethods->delete_func; this->print_func = smethods->print_func; this->compare_func = smethods->compare_func; this->hash_func = smethods->hash_func; } //-------------------------------------------------------------------- static PyObject *PyVTKSpecialObject_PyString(PyVTKSpecialObject *self) { vtksys_ios::ostringstream os; self->vtk_info->print_func(os, self->vtk_ptr); const vtksys_stl::string &s = os.str(); return PyString_FromStringAndSize(s.data(), s.size()); } //-------------------------------------------------------------------- static PyObject *PyVTKSpecialObject_PyRepr(PyVTKSpecialObject *self) { vtksys_ios::ostringstream os; os << "(" << PyString_AS_STRING(self->vtk_info->classname) << ")"; self->vtk_info->print_func(os, self->vtk_ptr); const vtksys_stl::string &s = os.str(); return PyString_FromStringAndSize(s.data(), s.size()); } //-------------------------------------------------------------------- static PyObject *PyVTKSpecialObject_PyGetAttr(PyVTKSpecialObject *self, PyObject *attr) { char *name = PyString_AsString(attr); PyMethodDef *meth; if (name[0] == '_') { if (strcmp(name,"__name__") == 0) { Py_INCREF(self->vtk_info->classname); return self->vtk_info->classname; } if (strcmp(name,"__doc__") == 0) { Py_INCREF(self->vtk_info->docstring); return self->vtk_info->docstring; } if (strcmp(name,"__methods__") == 0) { meth = self->vtk_info->methods; PyObject *lst; int i, n; for (n = 0; meth && meth[n].ml_name; n++) { ; } if ((lst = PyList_New(n)) != NULL) { meth = self->vtk_info->methods; for (i = 0; i < n; i++) { PyList_SetItem(lst, i, PyString_FromString(meth[i].ml_name)); } PyList_Sort(lst); } return lst; } if (strcmp(name,"__members__") == 0) { PyObject *lst; if ((lst = PyList_New(4)) != NULL) { PyList_SetItem(lst,0,PyString_FromString("__doc__")); PyList_SetItem(lst,1,PyString_FromString("__members__")); PyList_SetItem(lst,2,PyString_FromString("__methods__")); PyList_SetItem(lst,3,PyString_FromString("__name__")); } return lst; } } for (meth = self->vtk_info->methods; meth && meth->ml_name; meth++) { if (name[0] == meth->ml_name[0] && strcmp(name+1, meth->ml_name+1) == 0) { return PyCFunction_New(meth, (PyObject *)self); } } PyErr_SetString(PyExc_AttributeError, name); return NULL; } //-------------------------------------------------------------------- static void PyVTKSpecialObject_PyDelete(PyVTKSpecialObject *self) { if (self->vtk_ptr) { self->vtk_info->delete_func(self->vtk_ptr); } self->vtk_ptr = NULL; #if (PY_MAJOR_VERSION >= 2) PyObject_Del(self); #else PyMem_DEL(self); #endif } //-------------------------------------------------------------------- static long PyVTKSpecialObject_PyHash(PyVTKSpecialObject *self) { // self->vtk_hash must never be set to anything but -1 for mutable objects if (self->vtk_hash != -1) { return self->vtk_hash; } if (self->vtk_ptr && self->vtk_info->hash_func) { int imm = 0; long val = self->vtk_info->hash_func(self->vtk_ptr, &imm); if (val != -1) { if (imm) { // cache the hash for immutable objects self->vtk_hash = val; } return val; } } // python 2.6 #if PY_VERSION_HEX >= 0x02060000 return PyObject_HashNotImplemented((PyObject *)self); #else PyErr_SetString(PyExc_TypeError, (char *)"object is not hashable"); return -1; #endif } //-------------------------------------------------------------------- static PyObject *PyVTKSpecialObject_PyRichCompare( PyObject *o1, PyObject *o2, int opid) { // Heterogenous comparisons are not implemented if (!PyVTKSpecialObject_Check(o1) || !PyVTKSpecialObject_Check(o2) || (((PyVTKSpecialObject *)o1)->vtk_info != ((PyVTKSpecialObject *)o2)->vtk_info)) { #if PY_VERSION_HEX >= 0x02010000 Py_INCREF(Py_NotImplemented); return Py_NotImplemented; #else Py_INCREF(Py_None); return Py_None; #endif } // Types are matched, try to do the comparison PyVTKSpecialCompareFunc cmpfunc = ((PyVTKSpecialObject *)o1)->vtk_info->compare_func; if (cmpfunc) { int val = cmpfunc(((PyVTKSpecialObject *)o1)->vtk_ptr, ((PyVTKSpecialObject *)o2)->vtk_ptr, opid); if (val == 0) { Py_INCREF(Py_False); return Py_False; } else if (val != -1) { Py_INCREF(Py_True); return Py_True; } } PyErr_SetString(PyExc_TypeError, (char *)"operation not available"); return NULL; } //-------------------------------------------------------------------- static PyTypeObject PyVTKSpecialObjectType = { PyObject_HEAD_INIT(&PyType_Type) 0, (char*)"vtkspecialobject", // tp_name sizeof(PyVTKSpecialObject), // tp_basicsize 0, // tp_itemsize (destructor)PyVTKSpecialObject_PyDelete, // tp_dealloc (printfunc)0, // tp_print (getattrfunc)0, // tp_getattr (setattrfunc)0, // tp_setattr (cmpfunc)0, // tp_compare (reprfunc)PyVTKSpecialObject_PyRepr, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping (hashfunc)PyVTKSpecialObject_PyHash, // tp_hash (ternaryfunc)0, // tp_call (reprfunc)PyVTKSpecialObject_PyString, // tp_string (getattrofunc)PyVTKSpecialObject_PyGetAttr, // tp_getattro (setattrofunc)0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_HAVE_RICHCOMPARE, // tp_flags (char*)"vtkspecialobject - a vtk object not derived from vtkObjectBase.", // tp_doc 0, // tp_traverse 0, // tp_clear (richcmpfunc)PyVTKSpecialObject_PyRichCompare, // tp_richcompare 0, // tp_weaklistoffset VTK_PYTHON_UTIL_SUPRESS_UNINITIALIZED }; //-------------------------------------------------------------------- int PyVTKSpecialObject_Check(PyObject *obj) { return (obj->ob_type == &PyVTKSpecialObjectType); } //-------------------------------------------------------------------- PyObject *PyVTKSpecialObject_New(const char *classname, void *ptr) { // would be nice if "info" could be passed instead if "classname" PyVTKSpecialType *info = vtkPythonUtil::FindSpecialType(classname); #if (PY_MAJOR_VERSION >= 2) PyVTKSpecialObject *self = PyObject_New(PyVTKSpecialObject, &PyVTKSpecialObjectType); #else PyVTKSpecialObject *self = PyObject_NEW(PyVTKSpecialObject, &PyVTKSpecialObjectType); #endif self->vtk_ptr = ptr; self->vtk_hash = -1; self->vtk_info = info; return (PyObject *)self; } //-------------------------------------------------------------------- PyObject *PyVTKSpecialObject_CopyNew(const char *classname, const void *ptr) { PyVTKSpecialType *info = vtkPythonUtil::FindSpecialType(classname); if (info == 0) { char buf[256]; sprintf(buf,"cannot create object of unknown type \"%s\"",classname); PyErr_SetString(PyExc_ValueError,buf); return NULL; } #if (PY_MAJOR_VERSION >= 2) PyVTKSpecialObject *self = PyObject_New(PyVTKSpecialObject, &PyVTKSpecialObjectType); #else PyVTKSpecialObject *self = PyObject_NEW(PyVTKSpecialObject, &PyVTKSpecialObjectType); #endif self->vtk_ptr = info->copy_func(ptr); self->vtk_hash = -1; self->vtk_info = info; return (PyObject *)self; } //-------------------------------------------------------------------- PyObject *PyVTKSpecialType_New( PyMethodDef *newmethod, PyMethodDef *methods, PyMethodDef *constructors, char *classname, char *docstring[], PyVTKSpecialMethods *smethods) { // Add this type to the special type map PyVTKSpecialType *info = vtkPythonUtil::AddSpecialTypeToMap( classname, docstring, methods, constructors, smethods); // Add the built docstring to the method newmethod->ml_doc = PyString_AsString(info->docstring); // Returns a function. Returning a type object would be nicer. return PyCFunction_New(newmethod, Py_None); } <|endoftext|>
<commit_before>/*========================================================================= Library : Image Registration Toolkit (IRTK) Module : $Id$ Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2008 onwards Date : $Date$ Version : $Revision$ Changes : $Author$ =========================================================================*/ #include <irtkImage.h> #include <irtkHistogram.h> #include <irtkTransformation.h> // Default filenames char *output_name = NULL, *prefix_name = NULL, *suffix_name = NULL, *textfile = NULL; #define MAX_IMAGES 10000 #define EPSILON 0.001 void usage() { cerr << "Usage: atlas [output] <input1..inputN> <options>\n" << endl; cerr << "where <options> is one or more of the following:\n"; cerr << "<-imagenames file> Name of file containing image names for <input1..inputN>\n"; cerr << "<-prefix directory> Directory in which to find the images\n"; cerr << "<-gaussian mean sigma> Use Gaussian with mean and sigma for kernel-based smoothing\n"; cerr << "<-epsilon value> Epsilon value for ignoring image in kernel-based smoothing (default = " << EPSILON << ")\n"; cerr << "<-scaling value> Scaling value for final atlas (default = 1)\n"; cerr << "<-norm> Normalise intensities before atlas construction (default = off)\n"; exit(1); } void normalise(irtkGreyImage &input, irtkRealImage &output) { int j; double mean, std; irtkGreyPixel *ptr1; irtkRealPixel *ptr2; // Set up input histogram cerr << "Setting up input histogram..."; cout.flush(); irtkGreyPixel min, max; input.GetMinMax(&min, &max); irtkHistogram histogram(max-min+1); histogram.PutMin(min-0.5); histogram.PutMax(max+0.5); ptr1 = input.GetPointerToVoxels(); for (j = 0; j < input.GetNumberOfVoxels(); j++) { histogram.AddSample(*ptr1); ptr1++; } mean = histogram.Mean(); std = histogram.StandardDeviation(); cout << "done" << endl; cerr << "Stats: Mean = " << mean << " SD = " << std << endl; ptr1 = input.GetPointerToVoxels(); ptr2 = output.GetPointerToVoxels(); for (j = 0; j < input.GetNumberOfVoxels(); j++) { *ptr2 = (*ptr1 - mean) / std; ptr1++; ptr2++; } } int main(int argc, char **argv) { double scale, mean, sigma, epsilon; int i, j, n, padding, norm, no, ok; irtkGreyPixel *ptr1; irtkGreyImage input; irtkRealPixel *ptr2; irtkRealImage tmp, output; // Check command line if (argc < 5) { usage(); } // Parse parameters output_name = argv[1]; argc--; argv++; // Default: scaling factor scale = 1; // Default: No kernel smoothing mean = 0; sigma = 1; // Default: No intensity normalisation norm = False; // Default: Epsilon epsilon = EPSILON; // Default padding padding = MIN_GREY; // Parse input file names and values char **input_name = new char *[MAX_IMAGES]; double *input_value = new double[MAX_IMAGES]; double *input_weight = new double[MAX_IMAGES]; double total_weight = 0; // Parse any remaining paramters no = 0; while ((argc > 1) && (argv[1][0] != '-' )) { input_name[no] = argv[1]; input_weight[no] = 1; total_weight += 1; no++; argc--; argv++; } while (argc > 1) { ok = False; if ((ok == False) && (strcmp(argv[1], "-scaling") == 0)) { argc--; argv++; scale = atof(argv[1]); argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-gaussian") == 0)) { argc--; argv++; mean = atof(argv[1]); argc--; argv++; sigma = atof(argv[1]); argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-norm") == 0)) { argc--; argv++; norm = True; ok = True; } if ((ok == False) && (strcmp(argv[1], "-imagenames") == 0)) { argc--; argv++; textfile = argv[1]; argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-padding") == 0)) { argc--; argv++; padding = atoi(argv[1]); argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-prefix") == 0)) { argc--; argv++; prefix_name = argv[1]; argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-suffix") == 0)) { argc--; argv++; suffix_name = argv[1]; argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-epsilon") == 0)) { argc--; argv++; epsilon = atof(argv[1]); argc--; argv++; ok = True; } if (ok == False) { cerr << "Unknown argument: " << argv[1] << endl << endl; usage(); } } if (textfile != NULL) { ifstream in(textfile); if (in.is_open()) { while (!in.eof()) { input_name[no] = new char[256]; in >> input_name[no] >> input_value[no]; if (strlen(input_name[no]) > 0) { input_weight[no] = 1.0 / sqrt(2.0) / sigma * exp(-pow((mean - input_value[no])/sigma, 2.0)/2); if (input_weight[no] > epsilon) { total_weight += input_weight[no]; cout << input_value[no] << " " << input_weight[no] << " " << total_weight << endl; no++; } } } in.close(); } else { cout << "atlas: Unable to open file " << textfile << endl; exit(1); } } // Read and add one input image after the other n = 0; for (i = 0; i < no; i++) { char buffer[255]; // Read input if (prefix_name != NULL) { sprintf(buffer, "%s%s", prefix_name, input_name[i]); } else { sprintf(buffer, "%s", input_name[i]); } input_name[i] = strdup(buffer); if (suffix_name != NULL) { sprintf(buffer, "%s%s", input_name[i], suffix_name); } else { sprintf(buffer, "%s", input_name[i]); } input_name[i] = strdup(buffer); cout << "Reading input image " << input_name[i] << "... "; cout.flush(); input.Read(input_name[i]); cout << "done" << endl; if (i == 0) { n = input.GetX()*input.GetY()*input.GetZ(); output = input; ptr2 = output.GetPointerToVoxels(); for (j = 0; j < n; j++) { *ptr2 = 0; ptr2++; } } tmp = input; if (norm == True) normalise(input, tmp); cerr << "Adding input to atlas..."; cout.flush(); tmp *= input_weight[i]; output += tmp; cerr << "done\n"; } ptr1 = input.GetPointerToVoxels(); ptr2 = output.GetPointerToVoxels(); for (j = 0; j < n; j++) { *ptr1 = round(scale * *ptr2 / total_weight); ptr1++; ptr2++; } cerr << " done\n"; // Write atlas cerr << "Writing atlas to " << output_name << " ... "; cout.flush(); input.Write(output_name); cerr << "done\n"; } <commit_msg>Allow user to calculate their own weights (i.e. can override default use of Gaussian function).<commit_after>/*========================================================================= Library : Image Registration Toolkit (IRTK) Module : $Id$ Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2008 onwards Date : $Date$ Version : $Revision$ Changes : $Author$ =========================================================================*/ #include <irtkImage.h> #include <irtkHistogram.h> #include <irtkTransformation.h> // Default filenames char *output_name = NULL, *prefix_name = NULL, *suffix_name = NULL, *textfile = NULL; #define MAX_IMAGES 10000 #define EPSILON 0.001 void usage() { cerr << "Usage: atlas [output] <input1..inputN> <options>" << endl; cerr << "" << endl; cerr << "Make an atlas from a given set of input images. All input images must have the" << endl; cerr << "same voxel lattice. Names of input images can be given on the command line or" << endl; cerr << "in a file (see below)." << endl; cerr << "" << endl; cerr << "If they are named on the command line, images are given equal weighting." << endl; cerr << "Different weights can be given if a file with names is provided." << endl; cerr << "" << endl; cerr << "where <options> is one or more of the following:" << endl; cerr << "<-imagenames file> File containing image names and values to use for weighting." << endl; cerr << " The format should be one line for each image with" << endl; cerr << " \"image_name value\"" << endl; cerr << " on each line. If a mean and sigma value are specified" << endl; cerr << " with the \'-gaussian\' flag (see below), then the values" << endl; cerr << " are converted to weights using the corresponding Gaussian" << endl; cerr << " function. Otherwise, the values in the file are used" << endl; cerr << " directly as weights." << endl; cerr << "<-prefix directory> Directory in which to find the images." << endl; cerr << "<-gaussian mean sigma> Use Gaussian with mean and sigma for kernel-based smoothing\n"; cerr << "<-epsilon value> Epsilon value for ignoring image in kernel-based smoothing " << endl; cerr << " (default = " << EPSILON << ")" << endl; cerr << "<-scaling value> Scaling value for final atlas (default = 1)\n"; cerr << "<-norm> Normalise intensities before atlas construction " << endl; cerr << " (default = off)\n"; exit(1); } void normalise(irtkGreyImage &input, irtkRealImage &output) { int j; double mean, std; irtkGreyPixel *ptr1; irtkRealPixel *ptr2; // Set up input histogram cerr << "Setting up input histogram..."; cout.flush(); irtkGreyPixel min, max; input.GetMinMax(&min, &max); irtkHistogram histogram(max-min+1); histogram.PutMin(min-0.5); histogram.PutMax(max+0.5); ptr1 = input.GetPointerToVoxels(); for (j = 0; j < input.GetNumberOfVoxels(); j++) { histogram.AddSample(*ptr1); ptr1++; } mean = histogram.Mean(); std = histogram.StandardDeviation(); cout << "done" << endl; cerr << "Stats: Mean = " << mean << " SD = " << std << endl; ptr1 = input.GetPointerToVoxels(); ptr2 = output.GetPointerToVoxels(); for (j = 0; j < input.GetNumberOfVoxels(); j++) { *ptr2 = (*ptr1 - mean) / std; ptr1++; ptr2++; } } int main(int argc, char **argv) { double scale, mean, sigma, epsilon; int i, j, n, padding, norm, no, ok; int useGaussianWeights; irtkGreyPixel *ptr1; irtkGreyImage input; irtkRealPixel *ptr2; irtkRealImage tmp, output; // Check command line if (argc < 5) { usage(); } // Parse parameters output_name = argv[1]; argc--; argv++; // Default: scaling factor scale = 1; // Default: Use weights directly. Alternatively, convert using Gaussian formula. useGaussianWeights = False; // Default values for kernel smoothing mean = 0; sigma = 1; // Default: No intensity normalisation norm = False; // Default: Epsilon epsilon = EPSILON; // Default padding padding = MIN_GREY; // Parse input file names and values char **input_name = new char *[MAX_IMAGES]; double *input_value = new double[MAX_IMAGES]; double *input_weight = new double[MAX_IMAGES]; double total_weight = 0; // Parse any remaining paramters no = 0; while ((argc > 1) && (argv[1][0] != '-' )) { input_name[no] = argv[1]; input_weight[no] = 1; total_weight += 1; no++; argc--; argv++; } while (argc > 1) { ok = False; if ((ok == False) && (strcmp(argv[1], "-scaling") == 0)) { argc--; argv++; scale = atof(argv[1]); argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-gaussian") == 0)) { argc--; argv++; useGaussianWeights = True; mean = atof(argv[1]); argc--; argv++; sigma = atof(argv[1]); argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-norm") == 0)) { argc--; argv++; norm = True; ok = True; } if ((ok == False) && (strcmp(argv[1], "-imagenames") == 0)) { argc--; argv++; textfile = argv[1]; argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-padding") == 0)) { argc--; argv++; padding = atoi(argv[1]); argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-prefix") == 0)) { argc--; argv++; prefix_name = argv[1]; argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-suffix") == 0)) { argc--; argv++; suffix_name = argv[1]; argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-epsilon") == 0)) { argc--; argv++; epsilon = atof(argv[1]); argc--; argv++; ok = True; } if (ok == False) { cerr << "Unknown argument: " << argv[1] << endl << endl; usage(); } } if (textfile != NULL) { ifstream in(textfile); if (in.is_open()) { while (!in.eof()) { input_name[no] = new char[256]; in >> input_name[no] >> input_value[no]; if (strlen(input_name[no]) > 0) { if (useGaussianWeights == True){ // Convert input value to weight based on Gaussian centred at above specified mean. input_weight[no] = 1.0 / sqrt(2.0) / sigma * exp(-pow((mean - input_value[no])/sigma, 2.0)/2); } else { // Use input value directly as a weight. input_weight[no] = input_value[no]; } if (input_weight[no] > epsilon) { total_weight += input_weight[no]; cout << input_value[no] << " " << input_weight[no] << " " << total_weight << endl; no++; } } } in.close(); } else { cout << "atlas: Unable to open file " << textfile << endl; exit(1); } } // Read and add one input image after the other n = 0; for (i = 0; i < no; i++) { char buffer[255]; // Read input if (prefix_name != NULL) { sprintf(buffer, "%s%s", prefix_name, input_name[i]); } else { sprintf(buffer, "%s", input_name[i]); } input_name[i] = strdup(buffer); if (suffix_name != NULL) { sprintf(buffer, "%s%s", input_name[i], suffix_name); } else { sprintf(buffer, "%s", input_name[i]); } input_name[i] = strdup(buffer); cout << "Reading input image " << input_name[i] << "... "; cout.flush(); input.Read(input_name[i]); cout << "done" << endl; if (i == 0) { n = input.GetX()*input.GetY()*input.GetZ(); output = input; ptr2 = output.GetPointerToVoxels(); for (j = 0; j < n; j++) { *ptr2 = 0; ptr2++; } } tmp = input; if (norm == True) normalise(input, tmp); cerr << "Adding input to atlas..."; cout.flush(); tmp *= input_weight[i]; output += tmp; cerr << "done\n"; } ptr1 = input.GetPointerToVoxels(); ptr2 = output.GetPointerToVoxels(); for (j = 0; j < n; j++) { *ptr1 = round(scale * *ptr2 / total_weight); ptr1++; ptr2++; } cerr << " done\n"; // Write atlas cerr << "Writing atlas to " << output_name << " ... "; cout.flush(); input.Write(output_name); cerr << "done\n"; } <|endoftext|>
<commit_before>/* Copyright (c) 2013, Project OSRM, Dennis Luxen, others 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 <osrm/RouteParameters.h> #include <boost/fusion/container/vector.hpp> #include <boost/fusion/sequence/intrinsic.hpp> #include <boost/fusion/include/at_c.hpp> RouteParameters::RouteParameters() : zoom_level(18), print_instructions(false), alternate_route(true), geometry(true), compression(true), deprecatedAPI(false), check_sum(-1) { } void RouteParameters::setZoomLevel(const short level) { if (18 >= level && 0 <= level) { zoom_level = level; } } void RouteParameters::setAlternateRouteFlag(const bool flag) { alternate_route = flag; } void RouteParameters::setDeprecatedAPIFlag(const std::string &) { deprecatedAPI = true; } void RouteParameters::setChecksum(const unsigned sum) { check_sum = sum; } void RouteParameters::setInstructionFlag(const bool flag) { print_instructions = flag; } void RouteParameters::setService(const std::string &service_string) { service = service_string; } void RouteParameters::setOutputFormat(const std::string &format) { output_format = format; } void RouteParameters::setJSONpParameter(const std::string &parameter) { jsonp_parameter = parameter; } void RouteParameters::addHint(const std::string &hint) { hints.resize(coordinates.size()); if (!hints.empty()) { hints.back() = hint; } } void RouteParameters::setLanguage(const std::string &language_string) { language = language_string; } void RouteParameters::setGeometryFlag(const bool flag) { geometry = flag; } void RouteParameters::setCompressionFlag(const bool flag) { compression = flag; } void RouteParameters::addCoordinate(const boost::fusion::vector<double, double> &transmitted_coordinates) { coordinates.emplace_back( static_cast<int>(COORDINATE_PRECISION * boost::fusion::at_c<0>(transmitted_coordinates)), static_cast<int>(COORDINATE_PRECISION * boost::fusion::at_c<1>(transmitted_coordinates))); } <commit_msg>reformat to cut long line<commit_after>/* Copyright (c) 2013, Project OSRM, Dennis Luxen, others 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 <osrm/RouteParameters.h> #include <boost/fusion/container/vector.hpp> #include <boost/fusion/sequence/intrinsic.hpp> #include <boost/fusion/include/at_c.hpp> RouteParameters::RouteParameters() : zoom_level(18), print_instructions(false), alternate_route(true), geometry(true), compression(true), deprecatedAPI(false), check_sum(-1) { } void RouteParameters::setZoomLevel(const short level) { if (18 >= level && 0 <= level) { zoom_level = level; } } void RouteParameters::setAlternateRouteFlag(const bool flag) { alternate_route = flag; } void RouteParameters::setDeprecatedAPIFlag(const std::string &) { deprecatedAPI = true; } void RouteParameters::setChecksum(const unsigned sum) { check_sum = sum; } void RouteParameters::setInstructionFlag(const bool flag) { print_instructions = flag; } void RouteParameters::setService(const std::string &service_string) { service = service_string; } void RouteParameters::setOutputFormat(const std::string &format) { output_format = format; } void RouteParameters::setJSONpParameter(const std::string &parameter) { jsonp_parameter = parameter; } void RouteParameters::addHint(const std::string &hint) { hints.resize(coordinates.size()); if (!hints.empty()) { hints.back() = hint; } } void RouteParameters::setLanguage(const std::string &language_string) { language = language_string; } void RouteParameters::setGeometryFlag(const bool flag) { geometry = flag; } void RouteParameters::setCompressionFlag(const bool flag) { compression = flag; } void RouteParameters::addCoordinate(const boost::fusion::vector<double, double> &transmitted_coordinates) { coordinates.emplace_back( static_cast<int>(COORDINATE_PRECISION * boost::fusion::at_c<0>(transmitted_coordinates)), static_cast<int>(COORDINATE_PRECISION * boost::fusion::at_c<1>(transmitted_coordinates))); } <|endoftext|>
<commit_before>// // Copyright (c) 2008-2013 the Urho3D project. // // 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 "Precompiled.h" #include "Geometry.h" #include "Graphics.h" #include "IndexBuffer.h" #include "Log.h" #include "Ray.h" #include "VertexBuffer.h" #include "DebugNew.h" namespace Urho3D { Geometry::Geometry(Context* context) : Object(context), primitiveType_(TRIANGLE_LIST), indexStart_(0), indexCount_(0), vertexStart_(0), vertexCount_(0), positionBufferIndex_(M_MAX_UNSIGNED), rawVertexSize_(0), rawElementMask_(0), rawIndexSize_(0), lodDistance_(0.0f) { SetNumVertexBuffers(1); } Geometry::~Geometry() { } bool Geometry::SetNumVertexBuffers(unsigned num) { if (num >= MAX_VERTEX_STREAMS) { LOGERROR("Too many vertex streams"); return false; } unsigned oldSize = vertexBuffers_.Size(); vertexBuffers_.Resize(num); elementMasks_.Resize(num); for (unsigned i = oldSize; i < num; ++i) elementMasks_[i] = MASK_NONE; GetPositionBufferIndex(); return true; } bool Geometry::SetVertexBuffer(unsigned index, VertexBuffer* buffer, unsigned elementMask) { if (index >= vertexBuffers_.Size()) { LOGERROR("Stream index out of bounds"); return false; } vertexBuffers_[index] = buffer; if (buffer) { if (elementMask == MASK_DEFAULT) elementMasks_[index] = buffer->GetElementMask(); else elementMasks_[index] = elementMask; } GetPositionBufferIndex(); return true; } void Geometry::SetIndexBuffer(IndexBuffer* buffer) { indexBuffer_ = buffer; } bool Geometry::SetDrawRange(PrimitiveType type, unsigned indexStart, unsigned indexCount, bool getUsedVertexRange) { if (!indexBuffer_ && !rawIndexData_) { LOGERROR("Null index buffer and no raw index data, can not define indexed draw range"); return false; } if (indexBuffer_ && indexStart + indexCount > indexBuffer_->GetIndexCount()) { LOGERROR("Illegal draw range " + String(indexStart) + " to " + String(indexStart + indexCount - 1) + ", index buffer has " + String(indexBuffer_->GetIndexCount()) + " indices"); return false; } primitiveType_ = type; indexStart_ = indexStart; indexCount_ = indexCount; // Get min.vertex index and num of vertices from index buffer. If it fails, use full range as fallback if (indexCount) { vertexStart_ = 0; vertexCount_ = vertexBuffers_[0] ? vertexBuffers_[0]->GetVertexCount() : 0; if (getUsedVertexRange && indexBuffer_) indexBuffer_->GetUsedVertexRange(indexStart_, indexCount_, vertexStart_, vertexCount_); } else { vertexStart_ = 0; vertexCount_ = 0; } return true; } bool Geometry::SetDrawRange(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount) { if (indexBuffer_) { if (indexStart + indexCount > indexBuffer_->GetIndexCount()) { LOGERROR("Illegal draw range " + String(indexStart) + " to " + String(indexStart + indexCount - 1) + ", index buffer has " + String(indexBuffer_->GetIndexCount()) + " indices"); return false; } } else if (!rawIndexData_) { indexStart = 0; indexCount = 0; } primitiveType_ = type; indexStart_ = indexStart; indexCount_ = indexCount; vertexStart_ = minVertex; vertexCount_ = vertexCount; return true; } void Geometry::SetLodDistance(float distance) { if (distance < 0.0f) distance = 0.0f; lodDistance_ = distance; } void Geometry::SetRawVertexData(SharedArrayPtr<unsigned char> data, unsigned vertexSize, unsigned elementMask) { rawVertexData_ = data; rawVertexSize_ = vertexSize; rawElementMask_ = elementMask; } void Geometry::SetRawIndexData(SharedArrayPtr<unsigned char> data, unsigned indexSize) { rawIndexData_ = data; rawIndexSize_ = indexSize; } void Geometry::Draw(Graphics* graphics) { if (indexBuffer_ && indexCount_ > 0) { graphics->SetIndexBuffer(indexBuffer_); graphics->SetVertexBuffers(vertexBuffers_, elementMasks_); graphics->Draw(primitiveType_, indexStart_, indexCount_, vertexStart_, vertexCount_); } else if (vertexCount_ > 0) { graphics->SetVertexBuffers(vertexBuffers_, elementMasks_); graphics->Draw(primitiveType_, vertexStart_, vertexCount_); } } VertexBuffer* Geometry::GetVertexBuffer(unsigned index) const { return index < vertexBuffers_.Size() ? vertexBuffers_[index] : (VertexBuffer*)0; } unsigned Geometry::GetVertexElementMask(unsigned index) const { return index < elementMasks_.Size() ? elementMasks_[index] : 0; } unsigned short Geometry::GetBufferHash() const { unsigned short hash = 0; for (unsigned i = 0; i < vertexBuffers_.Size(); ++i) { VertexBuffer* vBuf = vertexBuffers_[i]; hash += *((unsigned short*)&vBuf); } IndexBuffer* iBuf = indexBuffer_; hash += *((unsigned short*)&iBuf); return hash; } void Geometry::GetRawData(const unsigned char*& vertexData, unsigned& vertexSize, const unsigned char*& indexData, unsigned& indexSize, unsigned& elementMask) const { // These shared arrays are held in the vertex/index buffers so it's safe to construct temporary shared pointers SharedArrayPtr<unsigned char> vertexDataShared; SharedArrayPtr<unsigned char> indexDataShared; GetRawDataShared(vertexDataShared, vertexSize, indexDataShared, indexSize, elementMask); vertexData = vertexDataShared.Get(); indexData = indexDataShared.Get(); } void Geometry::GetRawDataShared(SharedArrayPtr<unsigned char>& vertexData, unsigned& vertexSize, SharedArrayPtr<unsigned char>& indexData, unsigned& indexSize, unsigned& elementMask) const { if (rawVertexData_) { vertexData = rawVertexData_; vertexSize = rawVertexSize_; elementMask = rawElementMask_; } else { if (positionBufferIndex_ < vertexBuffers_.Size() && vertexBuffers_[positionBufferIndex_]) { vertexData = vertexBuffers_[positionBufferIndex_]->GetShadowDataShared(); if (vertexData) { vertexSize = vertexBuffers_[positionBufferIndex_]->GetVertexSize(); elementMask = vertexBuffers_[positionBufferIndex_]->GetElementMask(); } else { vertexSize = 0; elementMask = 0; } } else { vertexData = 0; vertexSize = 0; elementMask = 0; } } if (rawIndexData_) { indexData = rawIndexData_; indexSize = rawIndexSize_; } else { if (indexBuffer_) { indexData = indexBuffer_->GetShadowDataShared(); if (indexData) indexSize = indexBuffer_->GetIndexSize(); else indexSize = 0; } else { indexData = 0; indexSize = 0; } } } float Geometry::GetHitDistance(const Ray& ray, Vector3* outNormal) const { const unsigned char* vertexData; const unsigned char* indexData; unsigned vertexSize; unsigned indexSize; unsigned elementMask; GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask); if (vertexData && indexData) return ray.HitDistance(vertexData, vertexSize, indexData, indexSize, indexStart_, indexCount_, outNormal); else if (vertexData) return ray.HitDistance(vertexData, vertexSize, vertexStart_, vertexCount_, outNormal); else return M_INFINITY; } bool Geometry::IsInside(const Ray& ray) const { const unsigned char* vertexData; const unsigned char* indexData; unsigned vertexSize; unsigned indexSize; unsigned elementMask; GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask); if (vertexData && indexData) return ray.InsideGeometry(vertexData, vertexSize, indexData, indexSize, indexStart_, indexCount_); else if (vertexData) return ray.InsideGeometry(vertexData, vertexSize, vertexStart_, vertexCount_); else return false; } void Geometry::GetPositionBufferIndex() { for (unsigned i = 0; i < vertexBuffers_.Size(); ++i) { if (vertexBuffers_[i] && vertexBuffers_[i]->GetElementMask() & MASK_POSITION) { positionBufferIndex_ = i; return; } } // No vertex buffer with positions positionBufferIndex_ = M_MAX_UNSIGNED; } } <commit_msg>Restored previous Geometry::GetRawData() function (though it leads to duplicated code) to prevent unnecessary copying of shared array pointers.<commit_after>// // Copyright (c) 2008-2013 the Urho3D project. // // 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 "Precompiled.h" #include "Geometry.h" #include "Graphics.h" #include "IndexBuffer.h" #include "Log.h" #include "Ray.h" #include "VertexBuffer.h" #include "DebugNew.h" namespace Urho3D { Geometry::Geometry(Context* context) : Object(context), primitiveType_(TRIANGLE_LIST), indexStart_(0), indexCount_(0), vertexStart_(0), vertexCount_(0), positionBufferIndex_(M_MAX_UNSIGNED), rawVertexSize_(0), rawElementMask_(0), rawIndexSize_(0), lodDistance_(0.0f) { SetNumVertexBuffers(1); } Geometry::~Geometry() { } bool Geometry::SetNumVertexBuffers(unsigned num) { if (num >= MAX_VERTEX_STREAMS) { LOGERROR("Too many vertex streams"); return false; } unsigned oldSize = vertexBuffers_.Size(); vertexBuffers_.Resize(num); elementMasks_.Resize(num); for (unsigned i = oldSize; i < num; ++i) elementMasks_[i] = MASK_NONE; GetPositionBufferIndex(); return true; } bool Geometry::SetVertexBuffer(unsigned index, VertexBuffer* buffer, unsigned elementMask) { if (index >= vertexBuffers_.Size()) { LOGERROR("Stream index out of bounds"); return false; } vertexBuffers_[index] = buffer; if (buffer) { if (elementMask == MASK_DEFAULT) elementMasks_[index] = buffer->GetElementMask(); else elementMasks_[index] = elementMask; } GetPositionBufferIndex(); return true; } void Geometry::SetIndexBuffer(IndexBuffer* buffer) { indexBuffer_ = buffer; } bool Geometry::SetDrawRange(PrimitiveType type, unsigned indexStart, unsigned indexCount, bool getUsedVertexRange) { if (!indexBuffer_ && !rawIndexData_) { LOGERROR("Null index buffer and no raw index data, can not define indexed draw range"); return false; } if (indexBuffer_ && indexStart + indexCount > indexBuffer_->GetIndexCount()) { LOGERROR("Illegal draw range " + String(indexStart) + " to " + String(indexStart + indexCount - 1) + ", index buffer has " + String(indexBuffer_->GetIndexCount()) + " indices"); return false; } primitiveType_ = type; indexStart_ = indexStart; indexCount_ = indexCount; // Get min.vertex index and num of vertices from index buffer. If it fails, use full range as fallback if (indexCount) { vertexStart_ = 0; vertexCount_ = vertexBuffers_[0] ? vertexBuffers_[0]->GetVertexCount() : 0; if (getUsedVertexRange && indexBuffer_) indexBuffer_->GetUsedVertexRange(indexStart_, indexCount_, vertexStart_, vertexCount_); } else { vertexStart_ = 0; vertexCount_ = 0; } return true; } bool Geometry::SetDrawRange(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount) { if (indexBuffer_) { if (indexStart + indexCount > indexBuffer_->GetIndexCount()) { LOGERROR("Illegal draw range " + String(indexStart) + " to " + String(indexStart + indexCount - 1) + ", index buffer has " + String(indexBuffer_->GetIndexCount()) + " indices"); return false; } } else if (!rawIndexData_) { indexStart = 0; indexCount = 0; } primitiveType_ = type; indexStart_ = indexStart; indexCount_ = indexCount; vertexStart_ = minVertex; vertexCount_ = vertexCount; return true; } void Geometry::SetLodDistance(float distance) { if (distance < 0.0f) distance = 0.0f; lodDistance_ = distance; } void Geometry::SetRawVertexData(SharedArrayPtr<unsigned char> data, unsigned vertexSize, unsigned elementMask) { rawVertexData_ = data; rawVertexSize_ = vertexSize; rawElementMask_ = elementMask; } void Geometry::SetRawIndexData(SharedArrayPtr<unsigned char> data, unsigned indexSize) { rawIndexData_ = data; rawIndexSize_ = indexSize; } void Geometry::Draw(Graphics* graphics) { if (indexBuffer_ && indexCount_ > 0) { graphics->SetIndexBuffer(indexBuffer_); graphics->SetVertexBuffers(vertexBuffers_, elementMasks_); graphics->Draw(primitiveType_, indexStart_, indexCount_, vertexStart_, vertexCount_); } else if (vertexCount_ > 0) { graphics->SetVertexBuffers(vertexBuffers_, elementMasks_); graphics->Draw(primitiveType_, vertexStart_, vertexCount_); } } VertexBuffer* Geometry::GetVertexBuffer(unsigned index) const { return index < vertexBuffers_.Size() ? vertexBuffers_[index] : (VertexBuffer*)0; } unsigned Geometry::GetVertexElementMask(unsigned index) const { return index < elementMasks_.Size() ? elementMasks_[index] : 0; } unsigned short Geometry::GetBufferHash() const { unsigned short hash = 0; for (unsigned i = 0; i < vertexBuffers_.Size(); ++i) { VertexBuffer* vBuf = vertexBuffers_[i]; hash += *((unsigned short*)&vBuf); } IndexBuffer* iBuf = indexBuffer_; hash += *((unsigned short*)&iBuf); return hash; } void Geometry::GetRawData(const unsigned char*& vertexData, unsigned& vertexSize, const unsigned char*& indexData, unsigned& indexSize, unsigned& elementMask) const { if (rawVertexData_) { vertexData = rawVertexData_; vertexSize = rawVertexSize_; elementMask = rawElementMask_; } else { if (positionBufferIndex_ < vertexBuffers_.Size() && vertexBuffers_[positionBufferIndex_]) { vertexData = vertexBuffers_[positionBufferIndex_]->GetShadowData(); if (vertexData) { vertexSize = vertexBuffers_[positionBufferIndex_]->GetVertexSize(); elementMask = vertexBuffers_[positionBufferIndex_]->GetElementMask(); } else { vertexSize = 0; elementMask = 0; } } else { vertexData = 0; vertexSize = 0; elementMask = 0; } } if (rawIndexData_) { indexData = rawIndexData_; indexSize = rawIndexSize_; } else { if (indexBuffer_) { indexData = indexBuffer_->GetShadowData(); if (indexData) indexSize = indexBuffer_->GetIndexSize(); else indexSize = 0; } else { indexData = 0; indexSize = 0; } } } void Geometry::GetRawDataShared(SharedArrayPtr<unsigned char>& vertexData, unsigned& vertexSize, SharedArrayPtr<unsigned char>& indexData, unsigned& indexSize, unsigned& elementMask) const { if (rawVertexData_) { vertexData = rawVertexData_; vertexSize = rawVertexSize_; elementMask = rawElementMask_; } else { if (positionBufferIndex_ < vertexBuffers_.Size() && vertexBuffers_[positionBufferIndex_]) { vertexData = vertexBuffers_[positionBufferIndex_]->GetShadowDataShared(); if (vertexData) { vertexSize = vertexBuffers_[positionBufferIndex_]->GetVertexSize(); elementMask = vertexBuffers_[positionBufferIndex_]->GetElementMask(); } else { vertexSize = 0; elementMask = 0; } } else { vertexData = 0; vertexSize = 0; elementMask = 0; } } if (rawIndexData_) { indexData = rawIndexData_; indexSize = rawIndexSize_; } else { if (indexBuffer_) { indexData = indexBuffer_->GetShadowDataShared(); if (indexData) indexSize = indexBuffer_->GetIndexSize(); else indexSize = 0; } else { indexData = 0; indexSize = 0; } } } float Geometry::GetHitDistance(const Ray& ray, Vector3* outNormal) const { const unsigned char* vertexData; const unsigned char* indexData; unsigned vertexSize; unsigned indexSize; unsigned elementMask; GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask); if (vertexData && indexData) return ray.HitDistance(vertexData, vertexSize, indexData, indexSize, indexStart_, indexCount_, outNormal); else if (vertexData) return ray.HitDistance(vertexData, vertexSize, vertexStart_, vertexCount_, outNormal); else return M_INFINITY; } bool Geometry::IsInside(const Ray& ray) const { const unsigned char* vertexData; const unsigned char* indexData; unsigned vertexSize; unsigned indexSize; unsigned elementMask; GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask); if (vertexData && indexData) return ray.InsideGeometry(vertexData, vertexSize, indexData, indexSize, indexStart_, indexCount_); else if (vertexData) return ray.InsideGeometry(vertexData, vertexSize, vertexStart_, vertexCount_); else return false; } void Geometry::GetPositionBufferIndex() { for (unsigned i = 0; i < vertexBuffers_.Size(); ++i) { if (vertexBuffers_[i] && vertexBuffers_[i]->GetElementMask() & MASK_POSITION) { positionBufferIndex_ = i; return; } } // No vertex buffer with positions positionBufferIndex_ = M_MAX_UNSIGNED; } } <|endoftext|>
<commit_before>#include "openmc/bank.h" #include "openmc/capi.h" #include "openmc/error.h" #include <cstdint> // Explicit template instantiation definition template class std::vector<openmc::Particle::Bank>; namespace openmc { //============================================================================== // Global variables //============================================================================== namespace simulation { std::vector<Particle::Bank> source_bank; std::vector<Particle::Bank> fission_bank; Particle::Bank* shared_fission_bank; int shared_fission_bank_length {0}; int shared_fission_bank_max; } // namespace simulation //============================================================================== // Non-member functions //============================================================================== void free_memory_bank() { simulation::source_bank.clear(); simulation::fission_bank.clear(); delete[] simulation::shared_fission_bank; simulation::shared_fission_bank_length = 0; } void init_shared_fission_bank(int max) { simulation::shared_fission_bank_max = max; simulation::shared_fission_bank = new Particle::Bank[max]; simulation::shared_fission_bank_length = 0; } //============================================================================== // C API //============================================================================== extern "C" int openmc_source_bank(void** ptr, int64_t* n) { if (simulation::source_bank.size() == 0) { set_errmsg("Source bank has not been allocated."); return OPENMC_E_ALLOCATE; } else { *ptr = simulation::source_bank.data(); *n = simulation::source_bank.size(); return 0; } } extern "C" int openmc_fission_bank(void** ptr, int64_t* n) { if (simulation::fission_bank.size() == 0) { set_errmsg("Fission bank has not been allocated."); return OPENMC_E_ALLOCATE; } else { *ptr = simulation::fission_bank.data(); *n = simulation::fission_bank.size(); return 0; } } } // namespace openmc <commit_msg>In some unit tests, OpenMC finalize is called twice in a row without re-initializing the whole simulation. This caused the shared fission bank to be freed twice. Fixed now to check if it is a null pointer, and only free if null. Also initializes this value to null and sets it to null after freeing.<commit_after>#include "openmc/bank.h" #include "openmc/capi.h" #include "openmc/error.h" #include <cstdint> // Explicit template instantiation definition template class std::vector<openmc::Particle::Bank>; namespace openmc { //============================================================================== // Global variables //============================================================================== namespace simulation { std::vector<Particle::Bank> source_bank; std::vector<Particle::Bank> fission_bank; Particle::Bank* shared_fission_bank {nullptr}; int shared_fission_bank_length {0}; int shared_fission_bank_max; } // namespace simulation //============================================================================== // Non-member functions //============================================================================== void free_memory_bank() { simulation::source_bank.clear(); simulation::fission_bank.clear(); if( simulation::shared_fission_bank != nullptr ) delete[] simulation::shared_fission_bank; simulation::shared_fission_bank = nullptr; simulation::shared_fission_bank_length = 0; } void init_shared_fission_bank(int max) { simulation::shared_fission_bank_max = max; simulation::shared_fission_bank = new Particle::Bank[max]; simulation::shared_fission_bank_length = 0; } //============================================================================== // C API //============================================================================== extern "C" int openmc_source_bank(void** ptr, int64_t* n) { if (simulation::source_bank.size() == 0) { set_errmsg("Source bank has not been allocated."); return OPENMC_E_ALLOCATE; } else { *ptr = simulation::source_bank.data(); *n = simulation::source_bank.size(); return 0; } } extern "C" int openmc_fission_bank(void** ptr, int64_t* n) { if (simulation::fission_bank.size() == 0) { set_errmsg("Fission bank has not been allocated."); return OPENMC_E_ALLOCATE; } else { *ptr = simulation::fission_bank.data(); *n = simulation::fission_bank.size(); return 0; } } } // namespace openmc <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This is really Posix minus Mac. Mac code is in base_paths_mac.mm. #include "base/base_paths.h" #include <unistd.h> #include "base/env_var.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/scoped_ptr.h" #include "base/sys_string_conversions.h" #include "base/xdg_util.h" namespace base { #if defined(OS_LINUX) const char kSelfExe[] = "/proc/self/exe"; #elif defined(OS_SOLARIS) const char kSelfExe[] = getexecname(); #elif defined(OS_FREEBSD) const char kSelfExe[] = "/proc/curproc/file"; #endif bool PathProviderPosix(int key, FilePath* result) { FilePath path; switch (key) { case base::FILE_EXE: case base::FILE_MODULE: { // TODO(evanm): is this correct? char bin_dir[PATH_MAX + 1]; int bin_dir_size = readlink(kSelfExe, bin_dir, PATH_MAX); if (bin_dir_size < 0 || bin_dir_size > PATH_MAX) { NOTREACHED() << "Unable to resolve " << kSelfExe << "."; return false; } bin_dir[bin_dir_size] = 0; *result = FilePath(bin_dir); return true; } case base::DIR_SOURCE_ROOT: { // Allow passing this in the environment, for more flexibility in build // tree configurations (sub-project builds, gyp --output_dir, etc.) scoped_ptr<base::EnvVarGetter> env(base::EnvVarGetter::Create()); std::string cr_source_root; if (env->GetEnv("CR_SOURCE_ROOT", &cr_source_root)) { path = FilePath(cr_source_root); if (file_util::PathExists(path.Append("base/base_paths_posix.cc"))) { *result = path; return true; } else { LOG(WARNING) << "CR_SOURCE_ROOT is set, but it appears to not " << "point to the correct source root directory."; } } // On POSIX, unit tests execute two levels deep from the source root. // For example: sconsbuild/{Debug|Release}/net_unittest if (PathService::Get(base::DIR_EXE, &path)) { path = path.DirName().DirName(); if (file_util::PathExists(path.Append("base/base_paths_posix.cc"))) { *result = path; return true; } } // If that failed (maybe the build output is symlinked to a different // drive) try assuming the current directory is the source root. if (file_util::GetCurrentDirectory(&path) && file_util::PathExists(path.Append("base/base_paths_posix.cc"))) { *result = path; return true; } LOG(ERROR) << "Couldn't find your source root. " << "Try running from your chromium/src directory."; return false; } case base::DIR_USER_CACHE: scoped_ptr<base::EnvVarGetter> env(base::EnvVarGetter::Create()); FilePath cache_dir(base::GetXDGDirectory(env.get(), "XDG_CACHE_HOME", ".cache")); *result = cache_dir; return true; } return false; } } // namespace base <commit_msg>use sysctl instead of /proc on FreeBSD (unfortunately this approach is not available on OpenBSD though) patch from sprewell Review URL: http://codereview.chromium.org/1979006<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This is really Posix minus Mac. Mac code is in base_paths_mac.mm. #include "base/base_paths.h" #include <unistd.h> #if defined(OS_FREEBSD) #include <sys/param.h> #include <sys/sysctl.h> #endif #include "base/env_var.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/scoped_ptr.h" #include "base/sys_string_conversions.h" #include "base/xdg_util.h" namespace base { #if defined(OS_LINUX) const char kSelfExe[] = "/proc/self/exe"; #elif defined(OS_SOLARIS) const char kSelfExe[] = getexecname(); #endif bool PathProviderPosix(int key, FilePath* result) { FilePath path; switch (key) { case base::FILE_EXE: case base::FILE_MODULE: { // TODO(evanm): is this correct? #if defined(OS_LINUX) char bin_dir[PATH_MAX + 1]; int bin_dir_size = readlink(kSelfExe, bin_dir, PATH_MAX); if (bin_dir_size < 0 || bin_dir_size > PATH_MAX) { NOTREACHED() << "Unable to resolve " << kSelfExe << "."; return false; } bin_dir[bin_dir_size] = 0; *result = FilePath(bin_dir); return true; #elif defined(OS_FREEBSD) int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 }; char bin_dir[PATH_MAX + 1]; size_t length = sizeof(bin_dir); int error = sysctl(name, 4, bin_dir, &length, NULL, 0); if (error < 0 || length == 0 || strlen(bin_dir) == 0) { NOTREACHED() << "Unable to resolve path."; return false; } bin_dir[strlen(bin_dir)] = 0; *result = FilePath(bin_dir); return true; #endif } case base::DIR_SOURCE_ROOT: { // Allow passing this in the environment, for more flexibility in build // tree configurations (sub-project builds, gyp --output_dir, etc.) scoped_ptr<base::EnvVarGetter> env(base::EnvVarGetter::Create()); std::string cr_source_root; if (env->GetEnv("CR_SOURCE_ROOT", &cr_source_root)) { path = FilePath(cr_source_root); if (file_util::PathExists(path.Append("base/base_paths_posix.cc"))) { *result = path; return true; } else { LOG(WARNING) << "CR_SOURCE_ROOT is set, but it appears to not " << "point to the correct source root directory."; } } // On POSIX, unit tests execute two levels deep from the source root. // For example: sconsbuild/{Debug|Release}/net_unittest if (PathService::Get(base::DIR_EXE, &path)) { path = path.DirName().DirName(); if (file_util::PathExists(path.Append("base/base_paths_posix.cc"))) { *result = path; return true; } } // If that failed (maybe the build output is symlinked to a different // drive) try assuming the current directory is the source root. if (file_util::GetCurrentDirectory(&path) && file_util::PathExists(path.Append("base/base_paths_posix.cc"))) { *result = path; return true; } LOG(ERROR) << "Couldn't find your source root. " << "Try running from your chromium/src directory."; return false; } case base::DIR_USER_CACHE: scoped_ptr<base::EnvVarGetter> env(base::EnvVarGetter::Create()); FilePath cache_dir(base::GetXDGDirectory(env.get(), "XDG_CACHE_HOME", ".cache")); *result = cache_dir; return true; } return false; } } // namespace base <|endoftext|>
<commit_before>#include "robot_interface/arm_perception_ctrl.h" #include <tf/transform_datatypes.h> using namespace std; using namespace human_robot_collaboration_msgs; ArmPerceptionCtrl::ArmPerceptionCtrl(std::string _name, std::string _limb, bool _use_robot) : ArmCtrl(_name,_limb, _use_robot), PerceptionClientImpl(_name, _limb) { setHomeConfiguration(); setState(START); insertAction(ACTION_GET, static_cast<f_action>(&ArmPerceptionCtrl::getObject)); insertAction(ACTION_PASS, static_cast<f_action>(&ArmPerceptionCtrl::passObject)); insertAction(ACTION_GET_PASS, static_cast<f_action>(&ArmPerceptionCtrl::getPassObject)); if (not _use_robot) return; // moveArm("up",0.2,"strict"); // moveArm("down",0.2,"strict"); // moveArm("right",0.2,"strict"); // moveArm("left",0.2,"strict"); // moveArm("forward",0.1,"strict"); // moveArm("backward",0.2,"strict"); // moveArm("forward",0.1,"strict"); } bool ArmPerceptionCtrl::selectObject4PickUp() { if (getObjectIDs().size() > 1) { setSubState(CHECK_OBJ_IDS); int id = chooseObjectID(getObjectIDs()); if (id == -1) { return false; }; setObjectID(id); ROS_INFO_COND(print_level>=1, "[%s] Chosen object with name %s", getLimb().c_str(), getObjectNameFromDB(ClientTemplate<int>::getObjectID()).c_str()); } return true; } bool ArmPerceptionCtrl::recoverRelease() { if (getPrevAction() != ACTION_RELEASE) return false; if(!homePoseStrict()) return false; ros::Duration(0.05).sleep(); if (!pickUpObject()) return false; if (!close()) return false; if (!moveArm("up", 0.2)) return false; if (!homePoseStrict()) return false; return true; } bool ArmPerceptionCtrl::recoverGet() { if (!hoverAbovePool()) return false; if (!open()) return false; if (!homePoseStrict()) return false; return true; } bool ArmPerceptionCtrl::pickUpObject() { ROS_INFO_COND(print_level>=0, "[%s] Start Picking up object %s..", getLimb().c_str(), getObjectNameFromDB(ClientTemplate<int>::getObjectID()).c_str()); if (!isIRok()) { ROS_ERROR("No callback from the IR sensor! Stopping."); setSubState(NO_IR_SENSOR); return false; } if (!waitForData()) { setSubState(NO_OBJ); return false; } double offs_x = 0.0; double offs_y = 0.0; if (not computeOffsets(offs_x, offs_y)) { return false; } // Let's compute a first estimation of the joint position // (we reduce the z by 15 cm to start picking up from a // closer position) double x = getObjectPos().x + offs_x; double y = getObjectPos().y + offs_y; double z = getPos().z - 0.15; geometry_msgs::Quaternion q; if (not computeOrientation(q)) { return false; } ROS_INFO_COND(print_level>=1, "Going to: %g %g %g", x, y, z); if (not goToPose(x, y, z, q.x, q.y, q.z, q.w, "loose")) { return false; } if (!waitForData()) { setSubState(NO_OBJ); return false; } ros::Time start_time = ros::Time::now(); double z_start = getPos().z; int cnt_ik_fail = 0; ros::Rate r(THREAD_FREQ); while(RobotInterface::ok()) { double elap_time = (ros::Time::now() - start_time).toSec(); double x = getObjectPos().x + offs_x; double y = getObjectPos().y + offs_y; double z = z_start - getArmSpeed() * elap_time; ROS_INFO_COND(print_level>=3, "Time %g Going to: %g %g %g Position: %g %g %g", elap_time, x, y, z, getPos().x, getPos().y, getPos().z); if (goToPoseNoCheck(x, y, z, q.x, q.y, q.z, q.w)) { cnt_ik_fail = 0; // if (elap_time - old_elap_time > 0.02) // { // ROS_WARN("\t\t\t\t\tTime elapsed: %g", elap_time - old_elap_time); // } // old_elap_time = elap_time; if (determineContactCondition()) { return true; } r.sleep(); } else { ++cnt_ik_fail; } if (cnt_ik_fail == 10) { return false; } } return false; } bool ArmPerceptionCtrl::determineContactCondition() { if (hasCollidedIR("strict") || hasCollidedCD()) { if (hasCollidedCD()) { moveArm("up", 0.002); } ROS_INFO("Collision!"); return true; } else { if (getAction() == ACTION_GET || getAction() == ACTION_GET_PASS) { if (getPos().z < -0.28) { ROS_INFO("Object reached!"); return true; } } } return false; } bool ArmPerceptionCtrl::computeOffsets(double &_x_offs, double &_y_offs) { return true; } int ArmPerceptionCtrl::chooseObjectID(vector<int> _objs) { if (getSubState() != CHECK_OBJ_IDS) { return ArmCtrl::chooseObjectID(_objs); } ROS_INFO_COND(print_level>=3, "[%s] Choosing object IDs", getLimb().c_str()); if (!waitForOK()) { setSubState(NO_OBJ); return -1; } if (!waitForObjsFound()) { setSubState(NO_OBJ); return -1; } std::vector<int> av_objects = ClientTemplate<int>::getAvailableObjects(_objs); if (av_objects.size() == 0) { setSubState(NO_OBJ); return -1; } srand(time(0)); //use current time as seed return av_objects[rand() % av_objects.size()]; } bool ArmPerceptionCtrl::computeOrientation(geometry_msgs::Quaternion &_ori) { if (getLimb() == "left") { if (getAction() == ACTION_GET || getAction() == ACTION_GET_PASS) { if (ClientTemplate<int>::getObjectID() == 24) { // Get the rotation matrix for the object, as retrieved from tf::Quaternion mrk_q; tf::quaternionMsgToTF(getObjectOri(), mrk_q); tf::Matrix3x3 mrk_rot(mrk_q); // printf("Object Orientation\n"); // for (int j = 0; j < 3; ++j) // { // printf("%g\t%g\t%g\n", mrk_rot[j][0], mrk_rot[j][1], mrk_rot[j][2]); // } // Compute the transform matrix between the object's orientation // and the end-effector's orientation tf::Matrix3x3 mrk2ee; mrk2ee[0][0] = 1; mrk2ee[0][1] = 0; mrk2ee[0][2] = 0; mrk2ee[1][0] = 0; mrk2ee[1][1] = 0; mrk2ee[1][2] = -1; mrk2ee[2][0] = 0; mrk2ee[2][1] = 1; mrk2ee[2][2] = 0; // printf("Rotation\n"); // for (int j = 0; j < 3; ++j) // { // printf("%g\t%g\t%g\n", mrk2ee[j][0], mrk2ee[j][1], mrk2ee[j][2]); // } // Compute the final end-effector orientation, and convert it to a msg mrk2ee = mrk_rot * mrk2ee; tf::Quaternion ee_q; mrk2ee.getRotation(ee_q); geometry_msgs::Quaternion ee_q_msg; tf::quaternionTFToMsg(ee_q,ee_q_msg); // printf("Desired Orientation\n"); // for (int j = 0; j < 3; ++j) // { // printf("%g\t%g\t%g\n", mrk2ee[j][0], mrk2ee[j][1], mrk2ee[j][2]); // } _ori = ee_q_msg; } else { quaternionFromDoubles(_ori, POOL_ORI_L); } } else if (getAction() == ACTION_CLEANUP) { quaternionFromDoubles(_ori, VERTICAL_ORI_L); } else { ROS_ERROR("State is neither ACTION_GET, ACTION_GET_PASS or ACTION_CLEANUP!"); return false; } } else if (getLimb() == "right") { if (getAction() == ACTION_GET || getAction() == ACTION_GET_PASS) { quaternionFromDoubles(_ori, POOL_ORI_L); } else if (getAction() == ACTION_CLEANUP) { quaternionFromDoubles(_ori, VERTICAL_ORI_R); } else { ROS_ERROR("State is neither ACTION_GET, ACTION_GET_PASS or ACTION_CLEANUP!"); return false; } } return true; } void ArmPerceptionCtrl::setHomeConfiguration() { ArmCtrl::setHomeConfiguration("pool"); } void ArmPerceptionCtrl::setObjectID(int _obj) { ArmCtrl::setObjectID(_obj); PerceptionClientImpl::setObjectID(_obj); } ArmPerceptionCtrl::~ArmPerceptionCtrl() { } <commit_msg>[arm_perception_ctrl] Fixed bug in pickup of objects.<commit_after>#include "robot_interface/arm_perception_ctrl.h" #include <tf/transform_datatypes.h> using namespace std; using namespace human_robot_collaboration_msgs; ArmPerceptionCtrl::ArmPerceptionCtrl(std::string _name, std::string _limb, bool _use_robot) : ArmCtrl(_name,_limb, _use_robot), PerceptionClientImpl(_name, _limb) { setHomeConfiguration(); setState(START); insertAction(ACTION_GET, static_cast<f_action>(&ArmPerceptionCtrl::getObject)); insertAction(ACTION_PASS, static_cast<f_action>(&ArmPerceptionCtrl::passObject)); insertAction(ACTION_GET_PASS, static_cast<f_action>(&ArmPerceptionCtrl::getPassObject)); if (not _use_robot) return; // moveArm("up",0.2,"strict"); // moveArm("down",0.2,"strict"); // moveArm("right",0.2,"strict"); // moveArm("left",0.2,"strict"); // moveArm("forward",0.1,"strict"); // moveArm("backward",0.2,"strict"); // moveArm("forward",0.1,"strict"); } bool ArmPerceptionCtrl::selectObject4PickUp() { if (getObjectIDs().size() > 1) { setSubState(CHECK_OBJ_IDS); int id = chooseObjectID(getObjectIDs()); if (id == -1) { return false; }; setObjectID(id); ROS_INFO_COND(print_level>=1, "[%s] Chosen object with name %s", getLimb().c_str(), getObjectNameFromDB(ClientTemplate<int>::getObjectID()).c_str()); } return true; } bool ArmPerceptionCtrl::recoverRelease() { if (getPrevAction() != ACTION_RELEASE) return false; if(!homePoseStrict()) return false; ros::Duration(0.05).sleep(); if (!pickUpObject()) return false; if (!close()) return false; if (!moveArm("up", 0.2)) return false; if (!homePoseStrict()) return false; return true; } bool ArmPerceptionCtrl::recoverGet() { if (!hoverAbovePool()) return false; if (!open()) return false; if (!homePoseStrict()) return false; return true; } bool ArmPerceptionCtrl::pickUpObject() { ROS_INFO_COND(print_level>=0, "[%s] Start Picking up object %s..", getLimb().c_str(), getObjectNameFromDB(ClientTemplate<int>::getObjectID()).c_str()); if (!isIRok()) { ROS_ERROR("No callback from the IR sensor! Stopping."); setSubState(NO_IR_SENSOR); return false; } if (!waitForData()) { setSubState(NO_OBJ); return false; } double offs_x = 0.0; double offs_y = 0.0; if (not computeOffsets(offs_x, offs_y)) { return false; } // Let's compute a first estimation of the joint position // (we reduce the z by 15 cm to start picking up from a // closer position) double x = getObjectPos().x + offs_x; double y = getObjectPos().y + offs_y; double z = getPos().z - 0.15; geometry_msgs::Quaternion q; if (not computeOrientation(q)) { return false; } ROS_INFO_COND(print_level>=1, "Going to: %g %g %g", x, y, z); if (not goToPose(x, y, z, q.x, q.y, q.z, q.w, "loose")) { return false; } if (!waitForData()) { setSubState(NO_OBJ); return false; } ros::Time start_time = ros::Time::now(); double z_start = getPos().z; int cnt_ik_fail = 0; ros::Rate r(THREAD_FREQ); while(RobotInterface::ok()) { double elap_time = (ros::Time::now() - start_time).toSec(); double x = getObjectPos().x + offs_x; double y = getObjectPos().y + offs_y; double z = z_start - getArmSpeed() * elap_time; ROS_INFO_COND(print_level>=3, "Time %g Going to: %g %g %g Position: %g %g %g", elap_time, x, y, z, getPos().x, getPos().y, getPos().z); if (goToPoseNoCheck(x, y, z, q.x, q.y, q.z, q.w)) { cnt_ik_fail = 0; // if (elap_time - old_elap_time > 0.02) // { // ROS_WARN("\t\t\t\t\tTime elapsed: %g", elap_time - old_elap_time); // } // old_elap_time = elap_time; if (determineContactCondition()) { return true; } r.sleep(); } else { ++cnt_ik_fail; } if (cnt_ik_fail == 10) { return false; } } return false; } bool ArmPerceptionCtrl::determineContactCondition() { if (hasCollidedIR("strict") || hasCollidedCD()) { if (hasCollidedCD()) { moveArm("up", 0.002); } ROS_INFO("Collision!"); return true; } else { if (getAction() == ACTION_GET || getAction() == ACTION_GET_PASS) { if (getPos().z < -0.28) { ROS_INFO("Object reached!"); return true; } } } return false; } bool ArmPerceptionCtrl::computeOffsets(double &_x_offs, double &_y_offs) { return true; } int ArmPerceptionCtrl::chooseObjectID(vector<int> _objs) { if (getSubState() != CHECK_OBJ_IDS) { return ArmCtrl::chooseObjectID(_objs); } ROS_INFO_COND(print_level>=3, "[%s] Choosing object IDs", getLimb().c_str()); if (!waitForOK()) { setSubState(NO_OBJ); return -1; } if (!waitForObjsFound()) { setSubState(NO_OBJ); return -1; } std::vector<int> av_objects = ClientTemplate<int>::getAvailableObjects(_objs); if (av_objects.size() == 0) { setSubState(NO_OBJ); return -1; } srand(time(0)); //use current time as seed return av_objects[rand() % av_objects.size()]; } bool ArmPerceptionCtrl::computeOrientation(geometry_msgs::Quaternion &_ori) { if (getLimb() == "left") { if (getAction() == ACTION_GET || getAction() == ACTION_GET_PASS) { if (ClientTemplate<int>::getObjectID() == 24) { // Get the rotation matrix for the object, as retrieved from tf::Quaternion mrk_q; tf::quaternionMsgToTF(getObjectOri(), mrk_q); tf::Matrix3x3 mrk_rot(mrk_q); // printf("Object Orientation\n"); // for (int j = 0; j < 3; ++j) // { // printf("%g\t%g\t%g\n", mrk_rot[j][0], mrk_rot[j][1], mrk_rot[j][2]); // } // Compute the transform matrix between the object's orientation // and the end-effector's orientation tf::Matrix3x3 mrk2ee; mrk2ee[0][0] = 1; mrk2ee[0][1] = 0; mrk2ee[0][2] = 0; mrk2ee[1][0] = 0; mrk2ee[1][1] = 0; mrk2ee[1][2] = -1; mrk2ee[2][0] = 0; mrk2ee[2][1] = 1; mrk2ee[2][2] = 0; // printf("Rotation\n"); // for (int j = 0; j < 3; ++j) // { // printf("%g\t%g\t%g\n", mrk2ee[j][0], mrk2ee[j][1], mrk2ee[j][2]); // } // Compute the final end-effector orientation, and convert it to a msg mrk2ee = mrk_rot * mrk2ee; tf::Quaternion ee_q; mrk2ee.getRotation(ee_q); geometry_msgs::Quaternion ee_q_msg; tf::quaternionTFToMsg(ee_q,ee_q_msg); // printf("Desired Orientation\n"); // for (int j = 0; j < 3; ++j) // { // printf("%g\t%g\t%g\n", mrk2ee[j][0], mrk2ee[j][1], mrk2ee[j][2]); // } _ori = ee_q_msg; } else { quaternionFromDoubles(_ori, POOL_ORI_L); } } else if (getAction() == ACTION_CLEANUP) { quaternionFromDoubles(_ori, VERTICAL_ORI_L); } else { ROS_ERROR("State is neither ACTION_GET, ACTION_GET_PASS or ACTION_CLEANUP!"); return false; } } else if (getLimb() == "right") { if (getAction() == ACTION_GET || getAction() == ACTION_GET_PASS) { quaternionFromDoubles(_ori, POOL_ORI_R); } else if (getAction() == ACTION_CLEANUP) { quaternionFromDoubles(_ori, VERTICAL_ORI_R); } else { ROS_ERROR("State is neither ACTION_GET, ACTION_GET_PASS or ACTION_CLEANUP!"); return false; } } return true; } void ArmPerceptionCtrl::setHomeConfiguration() { ArmCtrl::setHomeConfiguration("pool"); } void ArmPerceptionCtrl::setObjectID(int _obj) { ArmCtrl::setObjectID(_obj); PerceptionClientImpl::setObjectID(_obj); } ArmPerceptionCtrl::~ArmPerceptionCtrl() { } <|endoftext|>
<commit_before> #pragma once // This code comes from: // https://code.google.com/p/or-tools/source/browse/trunk/src/base/fingerprint2011.h // and was adapted to Visual Studio 2013 and to the needs of this project. // Copyright 2010-2014 Google // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cstdint> namespace principia { namespace base { inline std::uint64_t FingerprintCat2011(std::uint64_t fp1, std::uint64_t fp2) { // Two big prime numbers. const std::uint64_t kMul1 = 0xc6a4a7935bd1e995ULL; const std::uint64_t kMul2 = 0x228876a7198b743ULL; std::uint64_t a = fp1 * kMul1 + fp2 * kMul2; // Note: The following line also makes sure we never return 0 or 1, because we // will only add something to 'a' if there are any MSBs (the remaining bits // after the shift) being 0, in which case wrapping around would not happen. return a + (~a >> 47); } // This should be better (collision-wise) than the default hash<std::string>, // without being much slower. It never returns 0 or 1. inline std::uint64_t Fingerprint2011(const char* bytes, size_t len) { // Some big prime numer. std::uint64_t fp = 0xa5b85c5e198ed849ULL; const char* end = bytes + len; while (bytes + 8 <= end) { fp = FingerprintCat2011( fp, *(reinterpret_cast<const std::uint64_t*>(bytes))); bytes += 8; } // Note: we don't care about "consistency" (little or big endian) between // the bulk and the suffix of the message. std::uint64_t last_bytes = 0; while (bytes < end) { last_bytes += *bytes; last_bytes <<= 8; bytes++; } return FingerprintCat2011(fp, last_bytes); } } // namespace base } // namespace principia <commit_msg>Hex digits.<commit_after> #pragma once // This code comes from: // https://code.google.com/p/or-tools/source/browse/trunk/src/base/fingerprint2011.h // and was adapted to Visual Studio 2013 and to the needs of this project. // Copyright 2010-2014 Google // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cstdint> namespace principia { namespace base { inline std::uint64_t FingerprintCat2011(std::uint64_t fp1, std::uint64_t fp2) { // Two big prime numbers. const std::uint64_t kMul1 = 0xC6A4A7935BD1E995u; const std::uint64_t kMul2 = 0x228876A7198B743u; std::uint64_t a = fp1 * kMul1 + fp2 * kMul2; // Note: The following line also makes sure we never return 0 or 1, because we // will only add something to 'a' if there are any MSBs (the remaining bits // after the shift) being 0, in which case wrapping around would not happen. return a + (~a >> 47); } // This should be better (collision-wise) than the default hash<std::string>, // without being much slower. It never returns 0 or 1. inline std::uint64_t Fingerprint2011(const char* bytes, size_t len) { // Some big prime numer. std::uint64_t fp = 0xA5B85C5E198ED849u; const char* end = bytes + len; while (bytes + 8 <= end) { fp = FingerprintCat2011( fp, *(reinterpret_cast<const std::uint64_t*>(bytes))); bytes += 8; } // Note: we don't care about "consistency" (little or big endian) between // the bulk and the suffix of the message. std::uint64_t last_bytes = 0; while (bytes < end) { last_bytes += *bytes; last_bytes <<= 8; bytes++; } return FingerprintCat2011(fp, last_bytes); } } // namespace base } // namespace principia <|endoftext|>
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <hspp/Cards/Entity.h> namespace Hearthstonepp { Entity::Entity(Card& _card) : card(new Card(_card)) { for (auto& mechanic : card->mechanics) { gameTags.insert(std::make_pair(mechanic, 1)); } } Entity::Entity(const Entity& ent) { FreeMemory(); card = ent.card; gameTags = ent.gameTags; } Entity::~Entity() { FreeMemory(); } Entity& Entity::operator=(const Entity& ent) { if (this == &ent) { return *this; } FreeMemory(); card = ent.card; gameTags = ent.gameTags; return *this; } Entity* Entity::Clone() const { return new Entity(*this); } void Entity::SetAbility(GameTag tag, bool flag) { gameTags.insert_or_assign(tag, flag); } void Entity::FreeMemory() { gameTags.clear(); delete card; } } // namespace Hearthstonepp<commit_msg>[ci skip] feat(improve-tool): Change SetAbility() method logic<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <hspp/Cards/Entity.h> namespace Hearthstonepp { Entity::Entity(Card& _card) : card(new Card(_card)) { for (auto& mechanic : card->mechanics) { gameTags.insert(std::make_pair(mechanic, 1)); } } Entity::Entity(const Entity& ent) { FreeMemory(); card = ent.card; gameTags = ent.gameTags; } Entity::~Entity() { FreeMemory(); } Entity& Entity::operator=(const Entity& ent) { if (this == &ent) { return *this; } FreeMemory(); card = ent.card; gameTags = ent.gameTags; return *this; } Entity* Entity::Clone() const { return new Entity(*this); } void Entity::SetAbility(GameTag tag, bool flag) { const bool isExistAbility = (gameTags.find(tag) != gameTags.end()) && (static_cast<bool>(gameTags[tag])); if (isExistAbility ^ flag) { gameTags.insert_or_assign(tag, flag); } } void Entity::FreeMemory() { gameTags.clear(); delete card; } } // namespace Hearthstonepp<|endoftext|>
<commit_before>// Copyright 2012-2019 Richard Copley // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "mswin.h" #include "bump.h" #include <limits> void step_t::initialize (float t0, float t1) { // Precompute the coefficents c of the cubic polynomial f // such that f(t0)=0, f(t1)=1, f'(t0)=0 and f'(t0)=1. float d = t1 - t0; float a = t1 + t0; c [0] = t0 * t0 * (a + d + d); c [1] = -6 * t0 * t1; c [2] = 3 * a; c [3] = -2; // Divide c [] by d^3. v4f dt = _mm_set1_ps (d); store4f (c, load4f (c) / (dt * dt * dt)); T [0] = t0; T [1] = t1; T [2] = t1; T [3] = std::numeric_limits <float>::infinity (); } v4f step_t::operator () (float t) const { // Evaluate the polynomial f by Estrin's method. Return // (0 0 0 0) if t < t0, // (f f f f) if t0 <= t < t1, // (1 1 1 1) if t > t1. v4f c4 = load4f (c); v4f one = { 1.0f, 1.0f, 1.0f, 1.0f, }; v4f tttt = _mm_set1_ps (t); // t t t t v4f tt = _mm_unpacklo_ps (one, tttt); // 1 t 1 t v4f f0 = c4 * tt; // c0 c1*t c2 c3*t v4f ha = _mm_hadd_ps (f0, f0) * tt * tt; v4f f = _mm_hadd_ps (ha, ha); // f f f f v4f f1 = _mm_unpacklo_ps (f, one); // f 1 f 1 v4f tx = load4f (T); // t0 t1 t1 inf v4f lo = _mm_movelh_ps (tx, tx); // t0 t1 t0 t1 v4f hi = _mm_movehl_ps (tx, tx); // t1 inf t1 inf v4f sel = _mm_and_ps (_mm_cmpge_ps (tttt, lo), _mm_cmplt_ps (tttt, hi)); v4f val = _mm_and_ps (sel, f1); // f? 1? f? 1? return _mm_hadd_ps (val, val); } void bumps_t::initialize (const bump_specifier_t & b0, const bump_specifier_t & b1) { // Precompute the coefficients of four cubic polynomials in t, giving // the two smoothstep regions of the each of the two bump functions. v4f b0t = _mm_load_ps (& b0.t0); // b0.t0 b0.t1 b0.t2 b0.t2 v4f b1t = _mm_load_ps (& b1.t0); // b1.t0 b1.t1 b1.t2 b1.t2 v4f b0v = _mm_movelh_ps (_mm_load_ps (& b0.v0), _mm_setzero_ps ()); // b0.v0 b0.v1 0 0 v4f b1v = _mm_movelh_ps (_mm_load_ps (& b1.v0), _mm_setzero_ps ()); // b1.v0 b1.v1 0 0 v4f S = _mm_shuffle_ps (b0t, b1t, SHUFFLE (0, 2, 0, 2)); // b0.t0 b0.t2 b1.t0 b1.t2 v4f T = _mm_shuffle_ps (b0t, b1t, SHUFFLE (1, 3, 1, 3)); // b0.t1 b0.t3 b1.t1 b1.t3 v4f U = _mm_shuffle_ps (b0v, b1v, SHUFFLE (0, 2, 0, 2)); // b0.v0 0 b1.v0 0 v4f V1 = _mm_shuffle_ps (b0v, b1v, SHUFFLE (1, 0, 1, 0)); // b0.v1 b0.v0 b1.v1 b1.v0 v4f V2 = _mm_shuffle_ps (b0v, b1v, SHUFFLE (2, 1, 2, 1)); // 0 b0.v1 0 b1.v1 v4f V = V1 - V2; v4f d = T - S; v4f a = T + S; v4f m = (V - U) / (d * d * d); store4f (c [0], U + m * S * S * (a + d + d)); store4f (c [1], _mm_set1_ps (-6.0f) * m * S * T); store4f (c [2], _mm_set1_ps (+3.0f) * m * a); store4f (c [3], _mm_set1_ps (-2.0f) * m); store4f (S0, S); store4f (T0, T); store4f (U0, U); store4f (V0, V); } // Returns {f,g,f,g}, where f = bump0 (t), g = bump1 (t). v4f bumps_t::operator () (float t) const { // Compute all four polynomials by Estrin's method, and mask // and combine the values according to the region of the graph // to which t belongs. v4f s = _mm_set1_ps (t); v4f S = load4f (S0); v4f T = load4f (T0); v4f U = load4f (U0); v4f V = load4f (V0); v4f f01 = load4f (c [0]) + load4f (c [1]) * s; v4f f12 = load4f (c [2]) + load4f (c [3]) * s; v4f f = f01 + f12 * s * s; v4f ltS = _mm_cmplt_ps (s, S); v4f geT = _mm_cmpge_ps (s, T); v4f x1 = _mm_andnot_ps (_mm_or_ps (ltS, geT), f); v4f x2 = _mm_and_ps (ltS, U); v4f x3 = _mm_and_ps (geT, V); v4f val = _mm_or_ps (_mm_or_ps (x1, x2), x3); return _mm_hadd_ps (val, val); } <commit_msg>bump.cpp: Refill to 80 columns.<commit_after>// Copyright 2012-2019 Richard Copley // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "mswin.h" #include "bump.h" #include <limits> void step_t::initialize (float t0, float t1) { // Precompute the coefficents c of the cubic polynomial f // such that f(t0)=0, f(t1)=1, f'(t0)=0 and f'(t0)=1. float d = t1 - t0; float a = t1 + t0; c [0] = t0 * t0 * (a + d + d); c [1] = -6 * t0 * t1; c [2] = 3 * a; c [3] = -2; // Divide c [] by d^3. v4f dt = _mm_set1_ps (d); store4f (c, load4f (c) / (dt * dt * dt)); T [0] = t0; T [1] = t1; T [2] = t1; T [3] = std::numeric_limits <float>::infinity (); } v4f step_t::operator () (float t) const { // Evaluate the polynomial f by Estrin's method. Return // (0 0 0 0) if t < t0, // (f f f f) if t0 <= t < t1, // (1 1 1 1) if t > t1. v4f c4 = load4f (c); v4f one = { 1.0f, 1.0f, 1.0f, 1.0f, }; v4f tttt = _mm_set1_ps (t); // t t t t v4f tt = _mm_unpacklo_ps (one, tttt); // 1 t 1 t v4f f0 = c4 * tt; // c0 c1*t c2 c3*t v4f ha = _mm_hadd_ps (f0, f0) * tt * tt; v4f f = _mm_hadd_ps (ha, ha); // f f f f v4f f1 = _mm_unpacklo_ps (f, one); // f 1 f 1 v4f tx = load4f (T); // t0 t1 t1 inf v4f lo = _mm_movelh_ps (tx, tx); // t0 t1 t0 t1 v4f hi = _mm_movehl_ps (tx, tx); // t1 inf t1 inf v4f sel = _mm_and_ps (_mm_cmpge_ps (tttt, lo), _mm_cmplt_ps (tttt, hi)); v4f val = _mm_and_ps (sel, f1); // f? 1? f? 1? return _mm_hadd_ps (val, val); } #define SHUFPS(u, v, shuffle) _mm_shuffle_ps (u, v, SHUFFLE shuffle) void bumps_t::initialize ( const bump_specifier_t & b0, const bump_specifier_t & b1) { // Precompute the coefficients of four cubic polynomials in t, giving // the two smoothstep regions of the each of the two bump functions. v4f b0t = load4f (& b0.t0); // b0.t0 b0.t1 b0.t2 b0.t2 v4f b1t = load4f (& b1.t0); // b1.t0 b1.t1 b1.t2 b1.t2 v4f b0v = _mm_movelh_ps (load4f (& b0.v0), _mm_setzero_ps ()); // b0.v0 b0.v1 v4f b1v = _mm_movelh_ps (load4f (& b1.v0), _mm_setzero_ps ()); // b1.v0 b1.v1 v4f S = SHUFPS (b0t, b1t, (0, 2, 0, 2)); // b0.t0 b0.t2 b1.t0 b1.t2 v4f T = SHUFPS (b0t, b1t, (1, 3, 1, 3)); // b0.t1 b0.t3 b1.t1 b1.t3 v4f U = SHUFPS (b0v, b1v, (0, 2, 0, 2)); // b0.v0 0 b1.v0 0 v4f V1 = SHUFPS (b0v, b1v, (1, 0, 1, 0)); // b0.v1 b0.v0 b1.v1 b1.v0 v4f V2 = SHUFPS (b0v, b1v, (2, 1, 2, 1)); // 0 b0.v1 0 b1.v1 v4f V = V1 - V2; v4f d = T - S; v4f a = T + S; v4f m = (V - U) / (d * d * d); store4f (c [0], U + m * S * S * (a + d + d)); store4f (c [1], _mm_set1_ps (-6.0f) * m * S * T); store4f (c [2], _mm_set1_ps (+3.0f) * m * a); store4f (c [3], _mm_set1_ps (-2.0f) * m); store4f (S0, S); store4f (T0, T); store4f (U0, U); store4f (V0, V); } // Returns {f,g,f,g}, where f = bump0 (t), g = bump1 (t). v4f bumps_t::operator () (float t) const { // Compute all four polynomials by Estrin's method, and mask and combine the // values according to the region of the graph to which t belongs. v4f s = _mm_set1_ps (t); v4f S = load4f (S0); v4f T = load4f (T0); v4f U = load4f (U0); v4f V = load4f (V0); v4f f01 = load4f (c [0]) + load4f (c [1]) * s; v4f f12 = load4f (c [2]) + load4f (c [3]) * s; v4f f = f01 + f12 * s * s; v4f ltS = _mm_cmplt_ps (s, S); v4f geT = _mm_cmpge_ps (s, T); v4f x1 = _mm_andnot_ps (_mm_or_ps (ltS, geT), f); v4f x2 = _mm_and_ps (ltS, U); v4f x3 = _mm_and_ps (geT, V); v4f val = _mm_or_ps (_mm_or_ps (x1, x2), x3); return _mm_hadd_ps (val, val); } <|endoftext|>
<commit_before>#include <ph.h> #include <chef.h> #include <phstream.h> #include <phAttrib.h> #include <phInput.h> #include <phBC.h> #include <phRestart.h> #include <phAdapt.h> #include <phOutput.h> #include <phPartition.h> #include <phFilterMatching.h> #include <apfMDS.h> #include <apfMesh2.h> #include <apfPartition.h> #include <apf.h> #include <gmi_mesh.h> #include <PCU.h> #include <pcu_io.h> #include <string> #include <stdlib.h> #include <assert.h> #include <iostream> #define SIZET(a) static_cast<size_t>(a) namespace { void balanceAndReorder(apf::Mesh2* m, ph::Input& in, int numMasters) { /* check if the mesh changed at all */ if ((PCU_Comm_Peers()!=numMasters) || in.adaptFlag || in.tetrahedronize) { if (in.parmaPtn && PCU_Comm_Peers() > 1) ph::balance(in,m); apf::reorderMdsMesh(m); } } void switchToMasters(int splitFactor) { int self = PCU_Comm_Self(); int groupRank = self / splitFactor; int group = self % splitFactor; MPI_Comm groupComm; MPI_Comm_split(MPI_COMM_WORLD, group, groupRank, &groupComm); PCU_Switch_Comm(groupComm); } void switchToAll() { MPI_Comm prevComm = PCU_Get_Comm(); PCU_Switch_Comm(MPI_COMM_WORLD); MPI_Comm_free(&prevComm); PCU_Barrier(); } void loadCommon(ph::Input& in, ph::BCs& bcs, gmi_model*& g) { ph::loadModelAndBCs(in, g, bcs); } void originalMain(apf::Mesh2*& m, ph::Input& in, gmi_model* g, apf::Migration*& plan) { if(!m) m = apf::loadMdsMesh(g, in.meshFileName.c_str()); else apf::printStats(m); m->verify(); if (in.solutionMigration) ph::readAndAttachFields(in, m); else ph::attachZeroSolution(in, m); if (in.buildMapping) ph::buildMapping(m); apf::setMigrationLimit(SIZET(in.elementsPerMigration)); if (in.adaptFlag) ph::adapt(in, m); if (in.tetrahedronize) ph::tetrahedronize(in, m); plan = ph::split(in, m); } }//end namespace namespace ph { void preprocess(apf::Mesh2* m, Input& in, Output& out, BCs& bcs) { // if (in.adaptFlag) // ph::goToStepDir(in.timeStepNumber); std::string path = ph::setupOutputDir(); ph::setupOutputSubdir(path); ph::enterFilteredMatching(m, in, bcs); ph::generateOutput(in, bcs, m, out); ph::exitFilteredMatching(m); // a path is not needed for inmem ph::detachAndWriteSolution(in,out,m,path); //write restart if (in.adaptFlag && (in.timeStepNumber % in.writeVizFiles == 0) ) { // store the value of the function pointer FILE (*fn)(out, path) = out.openfile_write; // set function pointer for file writing out.openfile_write = openfile_write; // as defined in phCook.cc writeGeomBC(out, path, in.timeStepNumber); //write geombc for viz only // reset the function pointer to the original value out.openfile_write = fn; } ph::writeGeomBC(out, path); //write geombc ph::writeAuxiliaryFiles(path, in.timeStepNumber); // if ( ! in.outMeshFileName.empty() ) // m->writeNative(in.outMeshFileName.c_str()); m->verify(); gmi_model* g = m->getModel(); ph::clearAttAssociation(g,in); if (in.adaptFlag) ph::goToParentDir(); } void preprocess(apf::Mesh2* m, Input& in, Output& out) { gmi_model* g = m->getModel(); assert(g); BCs bcs; ph::readBCs(g, in.attributeFileName.c_str(), in.axisymmetry, bcs); preprocess(m,in,out,bcs); } } namespace chef { static FILE* openfile_read(ph::Input&, const char* path) { return pcu_group_open(path, false); } static FILE* openfile_write(ph::Output&, const char* path) { return pcu_group_open(path, true); } static FILE* openstream_write(ph::Output& out, const char* path) { return openGRStreamWrite(out.grs, path); } static FILE* openstream_read(ph::Input& in, const char* path) { std::string fname(path); std::string restartStr("restart"); FILE* f = NULL; if( fname.find(restartStr) != std::string::npos ) f = openRStreamRead(in.rs); else { fprintf(stderr, "ERROR %s type of stream %s is unknown... exiting\n", __func__, fname.c_str()); exit(1); } return f; } void bake(gmi_model*& g, apf::Mesh2*& m, ph::Input& in, ph::Output& out) { apf::Migration* plan = 0; ph::BCs bcs; loadCommon(in, bcs, g); const int worldRank = PCU_Comm_Self(); switchToMasters(in.splitFactor); const int numMasters = PCU_Comm_Peers(); if ((worldRank % in.splitFactor) == 0) originalMain(m, in, g, plan); switchToAll(); m = repeatMdsMesh(m, g, plan, in.splitFactor); balanceAndReorder(m,in,numMasters); ph::preprocess(m,in,out,bcs); } void cook(gmi_model*& g, apf::Mesh2*& m) { ph::Input in; in.load("adapt.inp"); in.openfile_read = openfile_read; ph::Output out; out.openfile_write = openfile_write; bake(g,m,in,out); } void cook(gmi_model*& g, apf::Mesh2*& m, ph::Input& ctrl) { ctrl.openfile_read = openfile_read; ph::Output out; out.openfile_write = openfile_write; bake(g,m,ctrl,out); } void cook(gmi_model*& g, apf::Mesh2*& m, ph::Input& ctrl, GRStream* grs) { ctrl.openfile_read = openfile_read; ph::Output out; out.openfile_write = openstream_write; out.grs = grs; bake(g,m,ctrl,out); } void cook(gmi_model*& g, apf::Mesh2*& m, ph::Input& ctrl, RStream* rs) { ctrl.openfile_read = openstream_read; ctrl.rs = rs; ph::Output out; out.openfile_write = openfile_write; bake(g,m,ctrl,out); return; } void cook(gmi_model*& g, apf::Mesh2*& m, ph::Input& ctrl, RStream* rs, GRStream* grs) { ctrl.openfile_read = openstream_read; ctrl.rs = rs; ph::Output out; out.openfile_write = openstream_write; out.grs = grs; bake(g,m,ctrl,out); return; } void readAndAttachFields(ph::Input& ctrl, apf::Mesh2*& m) { ph::readAndAttachFields(ctrl, m); } void preprocess(apf::Mesh2*& m, ph::Input& in) { ph::Output out; out.openfile_write = chef::openfile_write; ph::preprocess(m,in,out); } void preprocess(apf::Mesh2*& m, ph::Input& in, GRStream* grs) { ph::Output out; out.openfile_write = chef::openstream_write; out.grs = grs; ph::preprocess(m,in,out); } } <commit_msg>write geombc for viz onluy<commit_after>#include <ph.h> #include <chef.h> #include <phstream.h> #include <phAttrib.h> #include <phInput.h> #include <phBC.h> #include <phRestart.h> #include <phAdapt.h> #include <phOutput.h> #include <phPartition.h> #include <phFilterMatching.h> #include <apfMDS.h> #include <apfMesh2.h> #include <apfPartition.h> #include <apf.h> #include <gmi_mesh.h> #include <PCU.h> #include <pcu_io.h> #include <string> #include <stdlib.h> #include <assert.h> #include <iostream> #define SIZET(a) static_cast<size_t>(a) namespace { void balanceAndReorder(apf::Mesh2* m, ph::Input& in, int numMasters) { /* check if the mesh changed at all */ if ((PCU_Comm_Peers()!=numMasters) || in.adaptFlag || in.tetrahedronize) { if (in.parmaPtn && PCU_Comm_Peers() > 1) ph::balance(in,m); apf::reorderMdsMesh(m); } } void switchToMasters(int splitFactor) { int self = PCU_Comm_Self(); int groupRank = self / splitFactor; int group = self % splitFactor; MPI_Comm groupComm; MPI_Comm_split(MPI_COMM_WORLD, group, groupRank, &groupComm); PCU_Switch_Comm(groupComm); } void switchToAll() { MPI_Comm prevComm = PCU_Get_Comm(); PCU_Switch_Comm(MPI_COMM_WORLD); MPI_Comm_free(&prevComm); PCU_Barrier(); } void loadCommon(ph::Input& in, ph::BCs& bcs, gmi_model*& g) { ph::loadModelAndBCs(in, g, bcs); } void originalMain(apf::Mesh2*& m, ph::Input& in, gmi_model* g, apf::Migration*& plan) { if(!m) m = apf::loadMdsMesh(g, in.meshFileName.c_str()); else apf::printStats(m); m->verify(); if (in.solutionMigration) ph::readAndAttachFields(in, m); else ph::attachZeroSolution(in, m); if (in.buildMapping) ph::buildMapping(m); apf::setMigrationLimit(SIZET(in.elementsPerMigration)); if (in.adaptFlag) ph::adapt(in, m); if (in.tetrahedronize) ph::tetrahedronize(in, m); plan = ph::split(in, m); } }//end namespace namespace ph { void preprocess(apf::Mesh2* m, Input& in, Output& out, BCs& bcs) { // if (in.adaptFlag) // ph::goToStepDir(in.timeStepNumber); std::string path = ph::setupOutputDir(); ph::setupOutputSubdir(path); ph::enterFilteredMatching(m, in, bcs); ph::generateOutput(in, bcs, m, out); ph::exitFilteredMatching(m); // a path is not needed for inmem ph::detachAndWriteSolution(in,out,m,path); //write restart if (in.adaptFlag && (in.timeStepNumber % in.writeVizFiles == 0) ) { // store the value of the function pointer FILE* (*fn)(Output& out, const char* path) = out.openfile_write; // set function pointer for file writing out.openfile_write = openfile_write; writeGeomBC(out, path, in.timeStepNumber); //write geombc for viz only // reset the function pointer to the original value out.openfile_write = fn; } ph::writeGeomBC(out, path); //write geombc ph::writeAuxiliaryFiles(path, in.timeStepNumber); // if ( ! in.outMeshFileName.empty() ) // m->writeNative(in.outMeshFileName.c_str()); m->verify(); gmi_model* g = m->getModel(); ph::clearAttAssociation(g,in); if (in.adaptFlag) ph::goToParentDir(); } void preprocess(apf::Mesh2* m, Input& in, Output& out) { gmi_model* g = m->getModel(); assert(g); BCs bcs; ph::readBCs(g, in.attributeFileName.c_str(), in.axisymmetry, bcs); preprocess(m,in,out,bcs); } } namespace chef { static FILE* openfile_read(ph::Input&, const char* path) { return pcu_group_open(path, false); } static FILE* openfile_write(ph::Output&, const char* path) { return pcu_group_open(path, true); } static FILE* openstream_write(ph::Output& out, const char* path) { return openGRStreamWrite(out.grs, path); } static FILE* openstream_read(ph::Input& in, const char* path) { std::string fname(path); std::string restartStr("restart"); FILE* f = NULL; if( fname.find(restartStr) != std::string::npos ) f = openRStreamRead(in.rs); else { fprintf(stderr, "ERROR %s type of stream %s is unknown... exiting\n", __func__, fname.c_str()); exit(1); } return f; } void bake(gmi_model*& g, apf::Mesh2*& m, ph::Input& in, ph::Output& out) { apf::Migration* plan = 0; ph::BCs bcs; loadCommon(in, bcs, g); const int worldRank = PCU_Comm_Self(); switchToMasters(in.splitFactor); const int numMasters = PCU_Comm_Peers(); if ((worldRank % in.splitFactor) == 0) originalMain(m, in, g, plan); switchToAll(); m = repeatMdsMesh(m, g, plan, in.splitFactor); balanceAndReorder(m,in,numMasters); ph::preprocess(m,in,out,bcs); } void cook(gmi_model*& g, apf::Mesh2*& m) { ph::Input in; in.load("adapt.inp"); in.openfile_read = openfile_read; ph::Output out; out.openfile_write = openfile_write; bake(g,m,in,out); } void cook(gmi_model*& g, apf::Mesh2*& m, ph::Input& ctrl) { ctrl.openfile_read = openfile_read; ph::Output out; out.openfile_write = openfile_write; bake(g,m,ctrl,out); } void cook(gmi_model*& g, apf::Mesh2*& m, ph::Input& ctrl, GRStream* grs) { ctrl.openfile_read = openfile_read; ph::Output out; out.openfile_write = openstream_write; out.grs = grs; bake(g,m,ctrl,out); } void cook(gmi_model*& g, apf::Mesh2*& m, ph::Input& ctrl, RStream* rs) { ctrl.openfile_read = openstream_read; ctrl.rs = rs; ph::Output out; out.openfile_write = openfile_write; bake(g,m,ctrl,out); return; } void cook(gmi_model*& g, apf::Mesh2*& m, ph::Input& ctrl, RStream* rs, GRStream* grs) { ctrl.openfile_read = openstream_read; ctrl.rs = rs; ph::Output out; out.openfile_write = openstream_write; out.grs = grs; bake(g,m,ctrl,out); return; } void readAndAttachFields(ph::Input& ctrl, apf::Mesh2*& m) { ph::readAndAttachFields(ctrl, m); } void preprocess(apf::Mesh2*& m, ph::Input& in) { ph::Output out; out.openfile_write = chef::openfile_write; ph::preprocess(m,in,out); } void preprocess(apf::Mesh2*& m, ph::Input& in, GRStream* grs) { ph::Output out; out.openfile_write = chef::openstream_write; out.grs = grs; ph::preprocess(m,in,out); } } <|endoftext|>
<commit_before><commit_msg>PLANNING TEST: unit test timeout so add todo to fix<commit_after><|endoftext|>
<commit_before>/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ClassAssemblingUtils.h" #include <boost/algorithm/string.hpp> #include "Creators.h" #include "DexStoreUtil.h" #include "DexUtil.h" #include "Model.h" namespace { void patch_iget_for_int_like_types(DexMethod* meth, IRList::iterator it, IRInstruction* convert) { auto insn = it->insn; auto move_result_it = std::next(it); auto src_dest = move_result_it->insn->dest(); convert->set_src(0, src_dest)->set_dest(src_dest); meth->get_code()->insert_after(move_result_it, convert); insn->set_opcode(OPCODE_IGET); } /** * Change the super class of a given class. The assumption is the new super * class has only one ctor and it shares the same signature with the old super * ctor. */ void change_super_class(DexClass* cls, DexType* super_type) { always_assert(cls); DexClass* super_cls = type_class(super_type); DexClass* old_super_cls = type_class(cls->get_super_class()); always_assert(super_cls); always_assert(old_super_cls); auto super_ctors = super_cls->get_ctors(); auto old_super_ctors = old_super_cls->get_ctors(); // Assume that both the old and the new super only have one ctor always_assert(super_ctors.size() == 1); always_assert(old_super_ctors.size() == 1); // Fix calls to super_ctor in its ctors. // NOTE: we are not parallelizing this since the ctor is very short. size_t num_insn_fixed = 0; for (auto ctor : cls->get_ctors()) { TRACE(TERA, 5, "Fixing ctor: %s\n", SHOW(ctor)); auto code = ctor->get_code(); for (auto& mie : InstructionIterable(code)) { auto insn = mie.insn; if (!is_invoke_direct(insn->opcode()) || !insn->has_method()) { continue; } // Replace "invoke_direct v0, old_super_type;.<init>:()V" with // "invoke_direct v0, super_type;.<init>:()V" if (insn->get_method() == old_super_ctors[0]) { TRACE(TERA, 9, " - Replacing call: %s with", SHOW(insn)); insn->set_method(super_ctors[0]); TRACE(TERA, 9, " %s\n", SHOW(insn)); num_insn_fixed++; } } } TRACE(TERA, 5, "Fixed %ld instructions\n", num_insn_fixed); cls->set_super_class(super_type); TRACE(TERA, 5, "Added super class %s to %s\n", SHOW(super_type), SHOW(cls)); } } // namespace DexClass* create_class(const DexType* type, const DexType* super_type, const std::string& pkg_name, std::vector<DexField*> fields, const TypeSet& interfaces, bool with_default_ctor, DexAccessFlags access) { DexType* t = const_cast<DexType*>(type); always_assert(!pkg_name.empty()); auto name = std::string(type->get_name()->c_str()); name = pkg_name + "/" + name.substr(1); t->assign_name_alias(DexString::make_string(name)); // Create class. ClassCreator creator(t); creator.set_access(access); always_assert(super_type != nullptr); creator.set_super(const_cast<DexType*>(super_type)); for (const auto& itf : interfaces) { creator.add_interface(const_cast<DexType*>(itf)); } for (const auto& field : fields) { creator.add_field(field); } auto cls = creator.create(); // Keeping type-erasure generated classes from being renamed. cls->rstate.set_keep_name(); if (!with_default_ctor) { return cls; } // Create ctor. auto super_ctors = type_class(super_type)->get_ctors(); for (auto super_ctor : super_ctors) { auto mc = new MethodCreator(t, DexString::make_string("<init>"), super_ctor->get_proto(), ACC_PUBLIC | ACC_CONSTRUCTOR); // Call to super.<init> std::vector<Location> args; size_t args_size = super_ctor->get_proto()->get_args()->size(); for (size_t arg_loc = 0; arg_loc < args_size + 1; ++arg_loc) { args.push_back(mc->get_local(arg_loc)); } auto mb = mc->get_main_block(); mb->invoke(OPCODE_INVOKE_DIRECT, super_ctor, args); mb->ret_void(); auto ctor = mc->create(); TRACE(TERA, 4, " default ctor created %s\n", SHOW(ctor)); cls->add_method(ctor); } return cls; } std::vector<DexField*> create_merger_fields( const DexType* owner, const std::vector<DexField*>& mergeable_fields) { std::vector<DexField*> res; size_t cnt = 0; for (const auto f : mergeable_fields) { auto type = f->get_type(); std::string name; if (type == get_byte_type() || type == get_char_type() || type == get_short_type() || type == get_int_type()) { type = get_int_type(); name = "i"; } else if (type == get_boolean_type()) { type = get_boolean_type(); name = "z"; } else if (type == get_long_type()) { type = get_long_type(); name = "j"; } else if (type == get_float_type()) { type = get_float_type(); name = "f"; } else if (type == get_double_type()) { type = get_double_type(); name = "d"; } else { static DexType* string_type = DexType::make_type("Ljava/lang/String;"); if (type == string_type) { type = string_type; name = "s"; } else { char t = type_shorty(type); always_assert(t == 'L' || t == '['); type = get_object_type(); name = "l"; } } name = name + std::to_string(cnt); auto field = static_cast<DexField*>( DexField::make_field(owner, DexString::make_string(name), type)); field->make_concrete(ACC_PUBLIC); res.push_back(field); cnt++; } TRACE(TERA, 8, " created merger fields %d \n", res.size()); return res; } void cook_merger_fields_lookup( const std::vector<DexField*>& new_fields, const FieldsMap& fields_map, std::unordered_map<DexField*, DexField*>& merger_fields_lookup) { for (const auto& fmap : fields_map) { const auto& old_fields = fmap.second; always_assert(new_fields.size() == old_fields.size()); for (size_t i = 0; i < new_fields.size(); i++) { if (old_fields.at(i) != nullptr) { merger_fields_lookup[old_fields.at(i)] = new_fields.at(i); } } } } std::string get_merger_package_name(const DexType* type) { auto pkg_name = get_package_name(type); // Avoid an Android OS like package name, which might confuse the custom class // loader. if (boost::starts_with(pkg_name, "Landroid") || boost::starts_with(pkg_name, "Ldalvik")) { return "Lcom/facebook"; } return pkg_name; } DexClass* create_merger_class(const DexType* type, const DexType* super_type, const std::vector<DexField*>& merger_fields, const TypeSet& interfaces, bool add_type_tag_field, bool with_default_ctor /* false */) { always_assert(type && super_type); std::vector<DexField*> fields; if (add_type_tag_field) { auto type_tag_field = static_cast<DexField*>(DexField::make_field( type, DexString::make_string(INTERNAL_TYPE_TAG_FIELD_NAME), get_int_type())); type_tag_field->make_concrete(ACC_PUBLIC | ACC_FINAL); fields.push_back(type_tag_field); } for (auto f : merger_fields) { fields.push_back(f); } // Put merger class in the same package as super_type. auto pkg_name = get_merger_package_name(super_type); auto cls = create_class(type, super_type, pkg_name, fields, interfaces, with_default_ctor); TRACE(TERA, 3, " created merger class w/ fields %s \n", SHOW(cls)); return cls; } void patch_iput(IRList::iterator it) { auto insn = it->insn; const auto op = insn->opcode(); always_assert(is_iput(op)); switch (op) { case OPCODE_IPUT_BYTE: case OPCODE_IPUT_CHAR: case OPCODE_IPUT_SHORT: insn->set_opcode(OPCODE_IPUT); break; default: break; } }; void patch_iget(DexMethod* meth, IRList::iterator it, DexType* original_field_type) { auto insn = it->insn; const auto op = insn->opcode(); always_assert(is_iget(op)); switch (op) { case OPCODE_IGET_OBJECT: { auto dest = std::next(it)->insn->dest(); auto cast = MethodMerger::make_check_cast(original_field_type, dest); meth->get_code()->insert_after(insn, cast); break; } case OPCODE_IGET_BYTE: { always_assert(original_field_type == get_byte_type()); auto int_to_byte = new IRInstruction(OPCODE_INT_TO_BYTE); patch_iget_for_int_like_types(meth, it, int_to_byte); break; } case OPCODE_IGET_CHAR: { always_assert(original_field_type == get_char_type()); auto int_to_char = new IRInstruction(OPCODE_INT_TO_CHAR); patch_iget_for_int_like_types(meth, it, int_to_char); break; } case OPCODE_IGET_SHORT: { always_assert(original_field_type == get_short_type()); auto int_to_short = new IRInstruction(OPCODE_INT_TO_SHORT); patch_iget_for_int_like_types(meth, it, int_to_short); break; } default: break; } }; void add_class(DexClass* new_cls, Scope& scope, DexStoresVector& stores) { always_assert(new_cls != nullptr); scope.push_back(new_cls); TRACE(TERA, 4, " TERA Adding class %s to scope %d \n", SHOW(new_cls), scope.size()); // TODO(emmasevastian): Handle this case in a better way. if (!stores.empty()) { DexClassesVector& root_store = stores.front().get_dexen(); DexClasses dc = {new_cls}; root_store.emplace_back(std::move(dc)); } } /** * In some limited cases we can do type erasure on an interface when * implementors of the interface only implement that interface and have no * parent class other than java.lang.Object. We create a base class for those * implementors and use the new base class as root, and proceed with type * erasure as usual. */ void handle_interface_as_root(ModelSpec& spec, Scope& scope, DexStoresVector& stores) { auto cls = type_class(spec.root); if (cls == nullptr) { return; } if (!is_interface(cls)) { TRACE(TERA, 1, "root %s is not an interface!\n", SHOW(spec.root)); return; } // Build a temporary type system. TypeSystem type_system(scope); // Create an empty base and add to the scope. Put the base class in the same // package as the root interface. auto base_type = DexType::make_type( DexString::make_string("L" + spec.class_name_prefix + "EmptyBase;")); auto base_class = create_class(base_type, get_object_type(), get_merger_package_name(spec.root), std::vector<DexField*>(), TypeSet(), true); TRACE(TERA, 1, "Created an empty base class %s for interface %s.\n", SHOW(cls), SHOW(spec.root)); // Set it as the super class of implementors. size_t num = 0; XStoreRefs xstores(stores); for (auto impl_type : type_system.get_implementors(spec.root)) { auto& ifcs = type_system.get_implemented_interfaces(impl_type); // Add an empty base class to qualified implementors auto impl_cls = type_class(impl_type); if (ifcs.size() == 1 && impl_cls && impl_cls->get_super_class() == get_object_type() && !is_in_non_root_store(impl_type, stores, xstores, spec.include_primary_dex)) { change_super_class(impl_cls, base_type); num++; } } // Change the root from the interface to the added base class. if (num > 0) { TRACE(TERA, 3, "Changing the root from %s to %s.\n", SHOW(spec.root), SHOW(base_type)); spec.root = base_type; add_class(base_class, scope, stores); } } <commit_msg>Add one more directory level in default merger type package name<commit_after>/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ClassAssemblingUtils.h" #include <boost/algorithm/string.hpp> #include "Creators.h" #include "DexStoreUtil.h" #include "DexUtil.h" #include "Model.h" namespace { void patch_iget_for_int_like_types(DexMethod* meth, IRList::iterator it, IRInstruction* convert) { auto insn = it->insn; auto move_result_it = std::next(it); auto src_dest = move_result_it->insn->dest(); convert->set_src(0, src_dest)->set_dest(src_dest); meth->get_code()->insert_after(move_result_it, convert); insn->set_opcode(OPCODE_IGET); } /** * Change the super class of a given class. The assumption is the new super * class has only one ctor and it shares the same signature with the old super * ctor. */ void change_super_class(DexClass* cls, DexType* super_type) { always_assert(cls); DexClass* super_cls = type_class(super_type); DexClass* old_super_cls = type_class(cls->get_super_class()); always_assert(super_cls); always_assert(old_super_cls); auto super_ctors = super_cls->get_ctors(); auto old_super_ctors = old_super_cls->get_ctors(); // Assume that both the old and the new super only have one ctor always_assert(super_ctors.size() == 1); always_assert(old_super_ctors.size() == 1); // Fix calls to super_ctor in its ctors. // NOTE: we are not parallelizing this since the ctor is very short. size_t num_insn_fixed = 0; for (auto ctor : cls->get_ctors()) { TRACE(TERA, 5, "Fixing ctor: %s\n", SHOW(ctor)); auto code = ctor->get_code(); for (auto& mie : InstructionIterable(code)) { auto insn = mie.insn; if (!is_invoke_direct(insn->opcode()) || !insn->has_method()) { continue; } // Replace "invoke_direct v0, old_super_type;.<init>:()V" with // "invoke_direct v0, super_type;.<init>:()V" if (insn->get_method() == old_super_ctors[0]) { TRACE(TERA, 9, " - Replacing call: %s with", SHOW(insn)); insn->set_method(super_ctors[0]); TRACE(TERA, 9, " %s\n", SHOW(insn)); num_insn_fixed++; } } } TRACE(TERA, 5, "Fixed %ld instructions\n", num_insn_fixed); cls->set_super_class(super_type); TRACE(TERA, 5, "Added super class %s to %s\n", SHOW(super_type), SHOW(cls)); } } // namespace DexClass* create_class(const DexType* type, const DexType* super_type, const std::string& pkg_name, std::vector<DexField*> fields, const TypeSet& interfaces, bool with_default_ctor, DexAccessFlags access) { DexType* t = const_cast<DexType*>(type); always_assert(!pkg_name.empty()); auto name = std::string(type->get_name()->c_str()); name = pkg_name + "/" + name.substr(1); t->assign_name_alias(DexString::make_string(name)); // Create class. ClassCreator creator(t); creator.set_access(access); always_assert(super_type != nullptr); creator.set_super(const_cast<DexType*>(super_type)); for (const auto& itf : interfaces) { creator.add_interface(const_cast<DexType*>(itf)); } for (const auto& field : fields) { creator.add_field(field); } auto cls = creator.create(); // Keeping type-erasure generated classes from being renamed. cls->rstate.set_keep_name(); if (!with_default_ctor) { return cls; } // Create ctor. auto super_ctors = type_class(super_type)->get_ctors(); for (auto super_ctor : super_ctors) { auto mc = new MethodCreator(t, DexString::make_string("<init>"), super_ctor->get_proto(), ACC_PUBLIC | ACC_CONSTRUCTOR); // Call to super.<init> std::vector<Location> args; size_t args_size = super_ctor->get_proto()->get_args()->size(); for (size_t arg_loc = 0; arg_loc < args_size + 1; ++arg_loc) { args.push_back(mc->get_local(arg_loc)); } auto mb = mc->get_main_block(); mb->invoke(OPCODE_INVOKE_DIRECT, super_ctor, args); mb->ret_void(); auto ctor = mc->create(); TRACE(TERA, 4, " default ctor created %s\n", SHOW(ctor)); cls->add_method(ctor); } return cls; } std::vector<DexField*> create_merger_fields( const DexType* owner, const std::vector<DexField*>& mergeable_fields) { std::vector<DexField*> res; size_t cnt = 0; for (const auto f : mergeable_fields) { auto type = f->get_type(); std::string name; if (type == get_byte_type() || type == get_char_type() || type == get_short_type() || type == get_int_type()) { type = get_int_type(); name = "i"; } else if (type == get_boolean_type()) { type = get_boolean_type(); name = "z"; } else if (type == get_long_type()) { type = get_long_type(); name = "j"; } else if (type == get_float_type()) { type = get_float_type(); name = "f"; } else if (type == get_double_type()) { type = get_double_type(); name = "d"; } else { static DexType* string_type = DexType::make_type("Ljava/lang/String;"); if (type == string_type) { type = string_type; name = "s"; } else { char t = type_shorty(type); always_assert(t == 'L' || t == '['); type = get_object_type(); name = "l"; } } name = name + std::to_string(cnt); auto field = static_cast<DexField*>( DexField::make_field(owner, DexString::make_string(name), type)); field->make_concrete(ACC_PUBLIC); res.push_back(field); cnt++; } TRACE(TERA, 8, " created merger fields %d \n", res.size()); return res; } void cook_merger_fields_lookup( const std::vector<DexField*>& new_fields, const FieldsMap& fields_map, std::unordered_map<DexField*, DexField*>& merger_fields_lookup) { for (const auto& fmap : fields_map) { const auto& old_fields = fmap.second; always_assert(new_fields.size() == old_fields.size()); for (size_t i = 0; i < new_fields.size(); i++) { if (old_fields.at(i) != nullptr) { merger_fields_lookup[old_fields.at(i)] = new_fields.at(i); } } } } std::string get_merger_package_name(const DexType* type) { auto pkg_name = get_package_name(type); // Avoid an Android OS like package name, which might confuse the custom class // loader. if (boost::starts_with(pkg_name, "Landroid") || boost::starts_with(pkg_name, "Ldalvik")) { return "Lcom/facebook/redex"; } return pkg_name; } DexClass* create_merger_class(const DexType* type, const DexType* super_type, const std::vector<DexField*>& merger_fields, const TypeSet& interfaces, bool add_type_tag_field, bool with_default_ctor /* false */) { always_assert(type && super_type); std::vector<DexField*> fields; if (add_type_tag_field) { auto type_tag_field = static_cast<DexField*>(DexField::make_field( type, DexString::make_string(INTERNAL_TYPE_TAG_FIELD_NAME), get_int_type())); type_tag_field->make_concrete(ACC_PUBLIC | ACC_FINAL); fields.push_back(type_tag_field); } for (auto f : merger_fields) { fields.push_back(f); } // Put merger class in the same package as super_type. auto pkg_name = get_merger_package_name(super_type); auto cls = create_class(type, super_type, pkg_name, fields, interfaces, with_default_ctor); TRACE(TERA, 3, " created merger class w/ fields %s \n", SHOW(cls)); return cls; } void patch_iput(IRList::iterator it) { auto insn = it->insn; const auto op = insn->opcode(); always_assert(is_iput(op)); switch (op) { case OPCODE_IPUT_BYTE: case OPCODE_IPUT_CHAR: case OPCODE_IPUT_SHORT: insn->set_opcode(OPCODE_IPUT); break; default: break; } }; void patch_iget(DexMethod* meth, IRList::iterator it, DexType* original_field_type) { auto insn = it->insn; const auto op = insn->opcode(); always_assert(is_iget(op)); switch (op) { case OPCODE_IGET_OBJECT: { auto dest = std::next(it)->insn->dest(); auto cast = MethodMerger::make_check_cast(original_field_type, dest); meth->get_code()->insert_after(insn, cast); break; } case OPCODE_IGET_BYTE: { always_assert(original_field_type == get_byte_type()); auto int_to_byte = new IRInstruction(OPCODE_INT_TO_BYTE); patch_iget_for_int_like_types(meth, it, int_to_byte); break; } case OPCODE_IGET_CHAR: { always_assert(original_field_type == get_char_type()); auto int_to_char = new IRInstruction(OPCODE_INT_TO_CHAR); patch_iget_for_int_like_types(meth, it, int_to_char); break; } case OPCODE_IGET_SHORT: { always_assert(original_field_type == get_short_type()); auto int_to_short = new IRInstruction(OPCODE_INT_TO_SHORT); patch_iget_for_int_like_types(meth, it, int_to_short); break; } default: break; } }; void add_class(DexClass* new_cls, Scope& scope, DexStoresVector& stores) { always_assert(new_cls != nullptr); scope.push_back(new_cls); TRACE(TERA, 4, " TERA Adding class %s to scope %d \n", SHOW(new_cls), scope.size()); // TODO(emmasevastian): Handle this case in a better way. if (!stores.empty()) { DexClassesVector& root_store = stores.front().get_dexen(); DexClasses dc = {new_cls}; root_store.emplace_back(std::move(dc)); } } /** * In some limited cases we can do type erasure on an interface when * implementors of the interface only implement that interface and have no * parent class other than java.lang.Object. We create a base class for those * implementors and use the new base class as root, and proceed with type * erasure as usual. */ void handle_interface_as_root(ModelSpec& spec, Scope& scope, DexStoresVector& stores) { auto cls = type_class(spec.root); if (cls == nullptr) { return; } if (!is_interface(cls)) { TRACE(TERA, 1, "root %s is not an interface!\n", SHOW(spec.root)); return; } // Build a temporary type system. TypeSystem type_system(scope); // Create an empty base and add to the scope. Put the base class in the same // package as the root interface. auto base_type = DexType::make_type( DexString::make_string("L" + spec.class_name_prefix + "EmptyBase;")); auto base_class = create_class(base_type, get_object_type(), get_merger_package_name(spec.root), std::vector<DexField*>(), TypeSet(), true); TRACE(TERA, 1, "Created an empty base class %s for interface %s.\n", SHOW(cls), SHOW(spec.root)); // Set it as the super class of implementors. size_t num = 0; XStoreRefs xstores(stores); for (auto impl_type : type_system.get_implementors(spec.root)) { auto& ifcs = type_system.get_implemented_interfaces(impl_type); // Add an empty base class to qualified implementors auto impl_cls = type_class(impl_type); if (ifcs.size() == 1 && impl_cls && impl_cls->get_super_class() == get_object_type() && !is_in_non_root_store(impl_type, stores, xstores, spec.include_primary_dex)) { change_super_class(impl_cls, base_type); num++; } } // Change the root from the interface to the added base class. if (num > 0) { TRACE(TERA, 3, "Changing the root from %s to %s.\n", SHOW(spec.root), SHOW(base_type)); spec.root = base_type; add_class(base_class, scope, stores); } } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Pavel N. Vyssotski * @version $Revision: 1.10 $ */ // AgentEventRequest.cpp #include "AgentEventRequest.h" #include "RequestManager.h" #include "Log.h" using namespace jdwp; AgentEventRequest::AgentEventRequest(jdwpEventKind kind, jdwpSuspendPolicy suspend, jint modCount) throw(AgentException) { m_requestId = 0; m_eventKind = kind; m_suspendPolicy = suspend; m_modifierCount = modCount; m_modifiers = 0; m_isExpired = false; if (modCount != 0) { m_modifiers = reinterpret_cast<RequestModifier**> (GetMemoryManager().Allocate(sizeof(RequestModifier*)*modCount JDWP_FILE_LINE)); memset(m_modifiers, 0, sizeof(RequestModifier*)*modCount); } } AgentEventRequest::~AgentEventRequest() throw() { for (jint i = 0; i < m_modifierCount; i++) { delete m_modifiers[i]; } if (m_modifiers != 0) { GetMemoryManager().Free(m_modifiers JDWP_FILE_LINE); } } bool AgentEventRequest::ApplyModifiers(JNIEnv *jni, EventInfo &eInfo) throw(AgentException) { for (jint i = 0; i < m_modifierCount; i++) { if (!m_modifiers[i]->Apply(jni, eInfo)) { return false; } if ((m_modifiers[i])->GetKind() == JDWP_MODIFIER_COUNT) { // once the count reaches 0, the event becomes expired m_isExpired = true; } } return true; } jthread AgentEventRequest::GetThread() const throw() { for (jint i = 0; i < m_modifierCount; i++) { if ((m_modifiers[i])->GetKind() == JDWP_MODIFIER_THREAD_ONLY) { return (reinterpret_cast<ThreadOnlyModifier*> (m_modifiers[i]))->GetThread(); } } return 0; } FieldOnlyModifier* AgentEventRequest::GetField() const throw() { for (jint i = 0; i < m_modifierCount; i++) { if ((m_modifiers[i])->GetKind() == JDWP_MODIFIER_FIELD_ONLY) { return reinterpret_cast<FieldOnlyModifier*>(m_modifiers[i]); } } return 0; } LocationOnlyModifier* AgentEventRequest::GetLocation() const throw() { for (jint i = 0; i < m_modifierCount; i++) { if ((m_modifiers[i])->GetKind() == JDWP_MODIFIER_LOCATION_ONLY) { return reinterpret_cast<LocationOnlyModifier*>(m_modifiers[i]); } } return 0; } //----------------------------------------------------------------------------- // StepRequest //----------------------------------------------------------------------------- StepRequest::~StepRequest() throw() { ControlSingleStep(false); JNIEnv *jni = GetJniEnv(); if (m_framePopRequest != 0) { GetRequestManager().DeleteRequest(jni, m_framePopRequest); } if (m_methodEntryRequest != 0) { GetRequestManager().DeleteRequest(jni, m_methodEntryRequest); } jni->DeleteGlobalRef(m_thread); } jint StepRequest::GetCurrentLine() throw() { jint lineNumber = -1; if (m_size == JDWP_STEP_LINE) { jmethodID method; jlocation location; jvmtiError err; JVMTI_TRACE(err, GetJvmtiEnv()->GetFrameLocation(m_thread, 0, &method, &location)); if (err == JVMTI_ERROR_NONE && location != -1) { jint cnt; jvmtiLineNumberEntry* table = 0; JVMTI_TRACE(err, GetJvmtiEnv()->GetLineNumberTable(method, &cnt, &table)); JvmtiAutoFree jafTable(table); if (err == JVMTI_ERROR_NONE && cnt > 0) { jint i = 1; while (i < cnt && location >= table[i].start_location) { i++; } lineNumber = table[i-1].line_number; } } } return lineNumber; } void StepRequest::ControlSingleStep(bool enable) throw() { JDWP_TRACE_EVENT("control Step: "<< (enable ? "on" : "off") << ", thread=" << m_thread); jvmtiError err; JVMTI_TRACE(err, GetJvmtiEnv()->SetEventNotificationMode( (enable) ? JVMTI_ENABLE : JVMTI_DISABLE, JVMTI_EVENT_SINGLE_STEP, m_thread)); m_isActive = enable; } void StepRequest::Restore() throw(AgentException) { JDWP_TRACE_EVENT("Restore stepRequest: " << (m_isActive ? "on" : "off")); jvmtiError err; JVMTI_TRACE(err, GetJvmtiEnv()->SetEventNotificationMode( (m_isActive) ? JVMTI_ENABLE : JVMTI_DISABLE, JVMTI_EVENT_SINGLE_STEP, m_thread)); if (err != JVMTI_ERROR_NONE) { throw AgentException(err); } } bool StepRequest::IsClassApplicable(JNIEnv* jni, EventInfo &eInfo) throw() { for (jint i = 0; i < m_modifierCount; i++) { switch ((m_modifiers[i])->GetKind()) { case JDWP_MODIFIER_CLASS_ONLY: case JDWP_MODIFIER_CLASS_MATCH: case JDWP_MODIFIER_CLASS_EXCLUDE: if (!m_modifiers[i]->Apply(jni, eInfo)) { return false; } break; case JDWP_MODIFIER_COUNT: return true; default: break; } } return true; } void StepRequest::OnFramePop(JNIEnv *jni) throw(AgentException) { JDWP_ASSERT(m_framePopRequest != 0); jint currentCount; jvmtiError err; JVMTI_TRACE(err, GetJvmtiEnv()->GetFrameCount(m_thread, &currentCount)); if (err != JVMTI_ERROR_NONE) { currentCount = -1; } if (m_depth == JDWP_STEP_OVER || (m_depth == JDWP_STEP_OUT && currentCount <= m_frameCount) || (m_methodEntryRequest != 0 && currentCount-1 <= m_frameCount)) { ControlSingleStep(true); if (m_methodEntryRequest != 0) { GetRequestManager().DeleteRequest(jni, m_methodEntryRequest); m_methodEntryRequest = 0; } } } void StepRequest::OnMethodEntry(JNIEnv *jni, EventInfo &eInfo) throw(AgentException) { JDWP_ASSERT(m_methodEntryRequest != 0); JDWP_ASSERT(m_depth == JDWP_STEP_INTO); if ((m_size == JDWP_STEP_MIN || GetCurrentLine() != -1) && IsClassApplicable(jni, eInfo)) { ControlSingleStep(true); m_methodEntryRequest->SetExpired(true); m_methodEntryRequest = 0; } } void StepRequest::Init(JNIEnv *jni, jthread thread, jint size, jint depth) throw(AgentException) { m_thread = jni->NewGlobalRef(thread); if (m_thread == 0) { throw OutOfMemoryException(); } m_size = size; m_depth = depth; if (m_depth != JDWP_STEP_INTO || m_size != JDWP_STEP_MIN) { jvmtiError err; JVMTI_TRACE(err, GetJvmtiEnv()->GetFrameCount(m_thread, &m_frameCount)); if (err != JVMTI_ERROR_NONE) { m_frameCount = -1; } if (m_size == JDWP_STEP_LINE) { m_lineNumber = GetCurrentLine(); } } if (m_depth == JDWP_STEP_INTO || m_frameCount > 0) { // add internal FramePop event request for the thread m_framePopRequest = new AgentEventRequest(JDWP_EVENT_FRAME_POP, JDWP_SUSPEND_NONE, 1); m_framePopRequest->AddModifier(new ThreadOnlyModifier(jni, thread), 0); GetRequestManager().AddInternalRequest(jni, m_framePopRequest); jvmtiError err; JVMTI_TRACE(err, GetJvmtiEnv()->NotifyFramePop(m_thread, 0)); if (err == JVMTI_ERROR_OPAQUE_FRAME) { m_isNative = true; } } if (m_depth == JDWP_STEP_INTO || (m_depth == JDWP_STEP_OUT && m_frameCount > 0 && m_isNative) || (m_depth == JDWP_STEP_OVER && m_frameCount > 0 && (m_size == JDWP_STEP_MIN || m_isNative || m_lineNumber != -1))) { ControlSingleStep(true); } JDWP_TRACE_EVENT("step start: size=" << m_size << ", depth=" << m_depth << ", frame=" << m_frameCount << ", line=" << m_lineNumber); } bool StepRequest::ApplyModifiers(JNIEnv *jni, EventInfo &eInfo) throw(AgentException) { JDWP_ASSERT(eInfo.thread != 0); if (JNI_FALSE == jni->IsSameObject(eInfo.thread, m_thread)) { return false; } jint currentCount = 0; jvmtiError err; JVMTI_TRACE(err, GetJvmtiEnv()->GetFrameCount(m_thread, &currentCount)); if (err != JVMTI_ERROR_NONE) { return false; } jint currentLine = 0; if (m_size == JDWP_STEP_LINE) { currentLine = GetCurrentLine(); } if (currentCount < m_frameCount) { // method exit } else if (currentCount > m_frameCount) { // method entry if (m_depth != JDWP_STEP_INTO || !IsClassApplicable(jni, eInfo)) { ControlSingleStep(false); if (m_depth == JDWP_STEP_INTO) { // add internal MethodEntry event request for the thread m_methodEntryRequest = new AgentEventRequest( JDWP_EVENT_METHOD_ENTRY, JDWP_SUSPEND_NONE, 1); m_methodEntryRequest->AddModifier( new ThreadOnlyModifier(jni, m_thread), 0); GetRequestManager().AddInternalRequest( jni, m_methodEntryRequest); } JVMTI_TRACE(err, GetJvmtiEnv()->NotifyFramePop(m_thread, 0)); if (err == JVMTI_ERROR_OPAQUE_FRAME) { m_isNative = true; } return false; } } else { // currentCount == m_frameCount // check against line if (m_size == JDWP_STEP_LINE && currentLine == m_lineNumber) { return false; } } if (m_size == JDWP_STEP_LINE && currentLine == -1) { return false; } m_frameCount = currentCount; m_lineNumber = currentLine; JDWP_TRACE_EVENT("step: frame=" << m_frameCount << ", line=" << m_lineNumber); return AgentEventRequest::ApplyModifiers(jni, eInfo); } <commit_msg>Applied fix for HARMONY-4823 [jdktools][jdwp] 2 jdtdebug tests fail with similar messages in EUT 3.2<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Pavel N. Vyssotski * @version $Revision: 1.10 $ */ // AgentEventRequest.cpp #include "AgentEventRequest.h" #include "RequestManager.h" #include "Log.h" using namespace jdwp; AgentEventRequest::AgentEventRequest(jdwpEventKind kind, jdwpSuspendPolicy suspend, jint modCount) throw(AgentException) { m_requestId = 0; m_eventKind = kind; m_suspendPolicy = suspend; m_modifierCount = modCount; m_modifiers = 0; m_isExpired = false; if (modCount != 0) { m_modifiers = reinterpret_cast<RequestModifier**> (GetMemoryManager().Allocate(sizeof(RequestModifier*)*modCount JDWP_FILE_LINE)); memset(m_modifiers, 0, sizeof(RequestModifier*)*modCount); } } AgentEventRequest::~AgentEventRequest() throw() { for (jint i = 0; i < m_modifierCount; i++) { delete m_modifiers[i]; } if (m_modifiers != 0) { GetMemoryManager().Free(m_modifiers JDWP_FILE_LINE); } } bool AgentEventRequest::ApplyModifiers(JNIEnv *jni, EventInfo &eInfo) throw(AgentException) { for (jint i = 0; i < m_modifierCount; i++) { if (!m_modifiers[i]->Apply(jni, eInfo)) { return false; } if ((m_modifiers[i])->GetKind() == JDWP_MODIFIER_COUNT) { // once the count reaches 0, the event becomes expired m_isExpired = true; } } return true; } jthread AgentEventRequest::GetThread() const throw() { for (jint i = 0; i < m_modifierCount; i++) { if ((m_modifiers[i])->GetKind() == JDWP_MODIFIER_THREAD_ONLY) { return (reinterpret_cast<ThreadOnlyModifier*> (m_modifiers[i]))->GetThread(); } } return 0; } FieldOnlyModifier* AgentEventRequest::GetField() const throw() { for (jint i = 0; i < m_modifierCount; i++) { if ((m_modifiers[i])->GetKind() == JDWP_MODIFIER_FIELD_ONLY) { return reinterpret_cast<FieldOnlyModifier*>(m_modifiers[i]); } } return 0; } LocationOnlyModifier* AgentEventRequest::GetLocation() const throw() { for (jint i = 0; i < m_modifierCount; i++) { if ((m_modifiers[i])->GetKind() == JDWP_MODIFIER_LOCATION_ONLY) { return reinterpret_cast<LocationOnlyModifier*>(m_modifiers[i]); } } return 0; } //----------------------------------------------------------------------------- // StepRequest //----------------------------------------------------------------------------- StepRequest::~StepRequest() throw() { ControlSingleStep(false); JNIEnv *jni = GetJniEnv(); if (m_framePopRequest != 0) { GetRequestManager().DeleteRequest(jni, m_framePopRequest); } if (m_methodEntryRequest != 0) { GetRequestManager().DeleteRequest(jni, m_methodEntryRequest); } jni->DeleteGlobalRef(m_thread); } jint StepRequest::GetCurrentLine() throw() { jint lineNumber = -1; if (m_size == JDWP_STEP_LINE) { jmethodID method; jlocation location; jvmtiError err; JVMTI_TRACE(err, GetJvmtiEnv()->GetFrameLocation(m_thread, 0, &method, &location)); if (err == JVMTI_ERROR_NONE && location != -1) { jint cnt; jvmtiLineNumberEntry* table = 0; JVMTI_TRACE(err, GetJvmtiEnv()->GetLineNumberTable(method, &cnt, &table)); JvmtiAutoFree jafTable(table); if (err == JVMTI_ERROR_NONE && cnt > 0) { jint i = 1; while (i < cnt && location >= table[i].start_location) { i++; } lineNumber = table[i-1].line_number; } } } return lineNumber; } void StepRequest::ControlSingleStep(bool enable) throw() { JDWP_TRACE_EVENT("control Step: "<< (enable ? "on" : "off") << ", thread=" << m_thread); jvmtiError err; JVMTI_TRACE(err, GetJvmtiEnv()->SetEventNotificationMode( (enable) ? JVMTI_ENABLE : JVMTI_DISABLE, JVMTI_EVENT_SINGLE_STEP, m_thread)); m_isActive = enable; } void StepRequest::Restore() throw(AgentException) { JDWP_TRACE_EVENT("Restore stepRequest: " << (m_isActive ? "on" : "off")); jvmtiError err; JVMTI_TRACE(err, GetJvmtiEnv()->SetEventNotificationMode( (m_isActive) ? JVMTI_ENABLE : JVMTI_DISABLE, JVMTI_EVENT_SINGLE_STEP, m_thread)); if (err != JVMTI_ERROR_NONE) { throw AgentException(err); } } bool StepRequest::IsClassApplicable(JNIEnv* jni, EventInfo &eInfo) throw() { for (jint i = 0; i < m_modifierCount; i++) { switch ((m_modifiers[i])->GetKind()) { case JDWP_MODIFIER_CLASS_ONLY: case JDWP_MODIFIER_CLASS_MATCH: case JDWP_MODIFIER_CLASS_EXCLUDE: if (!m_modifiers[i]->Apply(jni, eInfo)) { return false; } break; case JDWP_MODIFIER_COUNT: return true; default: break; } } return true; } void StepRequest::OnFramePop(JNIEnv *jni) throw(AgentException) { JDWP_ASSERT(m_framePopRequest != 0); jint currentCount; jvmtiError err; JVMTI_TRACE(err, GetJvmtiEnv()->GetFrameCount(m_thread, &currentCount)); if (err != JVMTI_ERROR_NONE) { currentCount = -1; } if (m_depth == JDWP_STEP_OVER || (m_depth == JDWP_STEP_OUT && currentCount <= m_frameCount) || (m_methodEntryRequest != 0 && currentCount-1 <= m_frameCount)) { ControlSingleStep(true); if (m_methodEntryRequest != 0) { GetRequestManager().DeleteRequest(jni, m_methodEntryRequest); m_methodEntryRequest = 0; } } } void StepRequest::OnMethodEntry(JNIEnv *jni, EventInfo &eInfo) throw(AgentException) { JDWP_ASSERT(m_methodEntryRequest != 0); JDWP_ASSERT(m_depth == JDWP_STEP_INTO); if ((m_size == JDWP_STEP_MIN || GetCurrentLine() != -1) && IsClassApplicable(jni, eInfo)) { ControlSingleStep(true); m_methodEntryRequest->SetExpired(true); m_methodEntryRequest = 0; } } void StepRequest::Init(JNIEnv *jni, jthread thread, jint size, jint depth) throw(AgentException) { m_thread = jni->NewGlobalRef(thread); if (m_thread == 0) { throw OutOfMemoryException(); } m_size = size; m_depth = depth; if (m_depth != JDWP_STEP_INTO || m_size != JDWP_STEP_MIN) { jvmtiError err; JVMTI_TRACE(err, GetJvmtiEnv()->GetFrameCount(m_thread, &m_frameCount)); if (err != JVMTI_ERROR_NONE) { m_frameCount = -1; } if (m_size == JDWP_STEP_LINE) { m_lineNumber = GetCurrentLine(); } } if (m_depth == JDWP_STEP_INTO || m_frameCount > 0) { // add internal FramePop event request for the thread m_framePopRequest = new AgentEventRequest(JDWP_EVENT_FRAME_POP, JDWP_SUSPEND_NONE, 1); m_framePopRequest->AddModifier(new ThreadOnlyModifier(jni, thread), 0); GetRequestManager().AddInternalRequest(jni, m_framePopRequest); jvmtiError err; JVMTI_TRACE(err, GetJvmtiEnv()->NotifyFramePop(m_thread, 0)); if (err == JVMTI_ERROR_OPAQUE_FRAME) { m_isNative = true; } } if (m_depth == JDWP_STEP_INTO || (m_depth == JDWP_STEP_OUT && m_frameCount > 0 && m_isNative) || (m_depth == JDWP_STEP_OVER && m_frameCount > 0 && (m_size == JDWP_STEP_MIN || m_isNative || m_lineNumber != -1))) { ControlSingleStep(true); } JDWP_TRACE_EVENT("step start: size=" << m_size << ", depth=" << m_depth << ", frame=" << m_frameCount << ", line=" << m_lineNumber); } bool StepRequest::ApplyModifiers(JNIEnv *jni, EventInfo &eInfo) throw(AgentException) { JDWP_ASSERT(eInfo.thread != 0); if (JNI_FALSE == jni->IsSameObject(eInfo.thread, m_thread)) { return false; } jint currentCount = 0; jvmtiError err; JVMTI_TRACE(err, GetJvmtiEnv()->GetFrameCount(m_thread, &currentCount)); if (err != JVMTI_ERROR_NONE) { return false; } jint currentLine = 0; if (m_size == JDWP_STEP_LINE) { currentLine = GetCurrentLine(); } if (currentCount < m_frameCount) { // method exit } else if (currentCount > m_frameCount) { // method entry if (m_depth != JDWP_STEP_INTO || !IsClassApplicable(jni, eInfo)) { ControlSingleStep(false); if (m_depth == JDWP_STEP_INTO) { // add internal MethodEntry event request for the thread m_methodEntryRequest = new AgentEventRequest( JDWP_EVENT_METHOD_ENTRY, JDWP_SUSPEND_NONE, 1); m_methodEntryRequest->AddModifier( new ThreadOnlyModifier(jni, m_thread), 0); GetRequestManager().AddInternalRequest( jni, m_methodEntryRequest); } JVMTI_TRACE(err, GetJvmtiEnv()->NotifyFramePop(m_thread, 0)); if (err == JVMTI_ERROR_OPAQUE_FRAME) { m_isNative = true; } return false; } } else { // currentCount == m_frameCount // check against line if (m_size == JDWP_STEP_LINE && currentLine == m_lineNumber && currentLine != -1) { return false; } } m_frameCount = currentCount; m_lineNumber = currentLine; JDWP_TRACE_EVENT("step: frame=" << m_frameCount << ", line=" << m_lineNumber); return AgentEventRequest::ApplyModifiers(jni, eInfo); } <|endoftext|>
<commit_before><commit_msg>planning: fix a bug in Standby stage<commit_after><|endoftext|>
<commit_before>#include "OS.hpp" #include <port/port.hpp> PriorityQueue_t<TaskStruct_t, MAX_TASKS> TaskQueue; TaskStruct_t ActrualRunningTaskStruct; void sys::boot() { InitSysTick(); ActrualRunningTaskStruct = TaskQueue.front(); TaskQueue.pop(); ContextSet(&ActrualRunningTaskStruct.lowLevel); // Now we will execute this task (jump to first task) ExecutePendingTask(); // This will also enable interrupts // This will never execute, aber zicher ist zicher! while (1) {} } void sys::taskCreate(TaskHandler_t taskHandler, uint8_t priority, uint16_t StackSize) { TaskStruct_t task; task.priority = priority; task.lowLevel = TaskAllocate(taskHandler, StackSize); TaskQueue.push(task); } void sys::ProcSysTick() { ContextGet(&ActrualRunningTaskStruct.lowLevel); TaskQueue.push(ActrualRunningTaskStruct); ActrualRunningTaskStruct = TaskQueue.front(); TaskQueue.pop(); ContextSet(&ActrualRunningTaskStruct.lowLevel); } <commit_msg>uninitialized variable!<commit_after>#include "OS.hpp" #include <port/port.hpp> PriorityQueue_t<TaskStruct_t, MAX_TASKS> TaskQueue; TaskStruct_t ActrualRunningTaskStruct; void sys::boot() { InitSysTick(); ActrualRunningTaskStruct = TaskQueue.front(); TaskQueue.pop(); ContextSet(&ActrualRunningTaskStruct.lowLevel); // Now we will execute this task (jump to first task) ExecutePendingTask(); // This will also enable interrupts // This will never execute, aber zicher ist zicher! while (1) {} } void sys::taskCreate(TaskHandler_t taskHandler, uint8_t priority, uint16_t StackSize) { TaskStruct_t task; task.priority = priority; task.blockingMutexNr = 0; task.lowLevel = TaskAllocate(taskHandler, StackSize); TaskQueue.push(task); } void sys::ProcSysTick() { ContextGet(&ActrualRunningTaskStruct.lowLevel); TaskQueue.push(ActrualRunningTaskStruct); ActrualRunningTaskStruct = TaskQueue.front(); TaskQueue.pop(); ContextSet(&ActrualRunningTaskStruct.lowLevel); } <|endoftext|>
<commit_before>//===--------------------------------------------------------------------------------*- C++ -*-===// // _ _ // | | | | // __ _| |_ ___| | __ _ _ __ __ _ // / _` | __/ __| |/ _` | '_ \ / _` | // | (_| | || (__| | (_| | | | | (_| | // \__, |\__\___|_|\__,_|_| |_|\__, | - GridTools Clang DSL // __/ | __/ | // |___/ |___/ // // // This file is distributed under the MIT License (MIT). // See LICENSE.txt for details. // //===------------------------------------------------------------------------------------------===// #ifndef GRIDTOOLS_CLANG_VERIFY_HPP #define GRIDTOOLS_CLANG_VERIFY_HPP #include "gridtools/clang_dsl.hpp" #include <array> #include <cmath> #include <cstdlib> #include <iostream> namespace gridtools { namespace clang { class verifier { public: verifier(const domain& dom, double precision = std::is_same<gridtools::float_type, double>::value ? 1e-12 : 1e-6) : m_domain(dom), m_precision(precision) {} template <class FunctorType, class... StorageTypes> void for_each(FunctorType&& functor, StorageTypes&... storages) const { for_each_impl(std::forward<FunctorType>(functor), storages...); } template <class FunctorType, class... StorageTypes> void for_each_boundary(FunctorType&& functor, StorageTypes&... storages) const { for_each_boundary_impl(std::forward<FunctorType>(functor), storages...); } template <class ValueType, class... StorageTypes> void fill(ValueType value, StorageTypes&... storages) const { fill_impl(value, storages...); } template <class... StorageTypes> void fillMath(double a, double b, double c, double d, double e, double f, StorageTypes&... storages) const { const gridtools::float_type pi = std::atan(1.) * 4.; for_each( [&](std::array<unsigned int, 3> dims, int i, int j, int k) { // 8,2,1.5,1.5,2,4 double x = i / (gridtools::float_type)dims[0]; double y = j / (gridtools::float_type)dims[1]; return k + (gridtools::float_type)a * ((gridtools::float_type)b + cos(pi * (x + (gridtools::float_type)c * y)) + sin((gridtools::float_type)d * pi * (x + (gridtools::float_type)e * y))) / (gridtools::float_type)f; }, storages...); } template <class... StorageTypes> void fill_random(StorageTypes&... storages) const { for_each([&](int, int, int) { return static_cast<double>(std::rand()) / RAND_MAX; }, storages...); } template <class ValueType, class... StorageTypes> void fill_boundaries(ValueType value, StorageTypes&... storages) const { boundary_fill_impl(value, storages...); } template <class StorageType1, class StorageType2> bool verify(StorageType1& storage1, StorageType2& storage2, int max_erros = 10) const { using namespace gridtools; storage1.sync(); storage2.sync(); auto meta_data_1 = *storage1.get_storage_info_ptr(); auto meta_data_2 = *storage2.get_storage_info_ptr(); const uint_t idim1 = meta_data_1.template unaligned_dim<0>(); const uint_t jdim1 = meta_data_1.template unaligned_dim<1>(); const uint_t kdim1 = meta_data_1.template unaligned_dim<2>(); const uint_t idim2 = meta_data_2.template unaligned_dim<0>(); const uint_t jdim2 = meta_data_2.template unaligned_dim<1>(); const uint_t kdim2 = meta_data_2.template unaligned_dim<2>(); auto storage1_v = make_host_view(storage1); auto storage2_v = make_host_view(storage2); // Check dimensions auto check_dim = [&](uint_t dim1, uint_t dim2, uint_t size, const char* dimstr) { if(dim1 != dim2 || dim1 != size) { std::cerr << "dimension \"" << dimstr << "\" missmatch in storage pair \"" << storage1.name() << "\" : \"" << storage2.name() << "\"\n"; std::cerr << " " << dimstr << "-dim storage1: " << dim1 << "\n"; std::cerr << " " << dimstr << "-dim storage2: " << dim2 << "\n"; std::cerr << " " << dimstr << "-size domain: " << size << "\n"; return false; } return true; }; check_dim(idim1, idim2, m_domain.isize(), "i"); check_dim(jdim1, jdim2, m_domain.jsize(), "j"); check_dim(kdim1, kdim2, m_domain.ksize(), "k"); bool verified = true; for(int i = m_domain.iminus(); i < (m_domain.isize() - m_domain.iplus()); ++i) for(int j = m_domain.jminus(); j < (m_domain.jsize() - m_domain.jplus()); ++j) for(int k = m_domain.kminus(); k < (m_domain.ksize() - m_domain.kplus()); ++k) { typename StorageType1::data_t value1 = storage1_v(i, j, k); typename StorageType2::data_t value2 = storage2_v(i, j, k); if(!compare_below_threashold(value1, value2, m_precision)) { if(--max_erros >= 0) { std::cerr << "( " << i << ", " << j << ", " << k << " ) : " << " " << storage1.name() << " = " << value1 << " ; " << " " << storage2.name() << " = " << value2 << " error: " << std::fabs((value2 - value1) / (value2)) << std::endl; } verified = false; } } return verified; } private: template <typename value_type> bool compare_below_threashold(value_type expected, value_type actual, value_type precision) const { if(std::fabs(expected) < 1e-3 && std::fabs(actual) < 1e-3) { if(std::fabs(expected - actual) < precision) return true; } else { if(std::fabs((expected - actual) / (precision * expected)) < 1.0) return true; } return false; } template <class StorageType, class FunctorType> void for_each_do_it(FunctorType&& functor, StorageType& storage) const { using namespace gridtools; auto sinfo = *(storage.get_storage_info_ptr()); auto storage_v = make_host_view(storage); const uint_t d1 = sinfo.template unaligned_dim<0>(); const uint_t d2 = sinfo.template unaligned_dim<1>(); const uint_t d3 = sinfo.template unaligned_dim<2>(); for(uint_t i = 0; i < d1; ++i) { for(uint_t j = 0; j < d2; ++j) { for(uint_t k = 0; k < d3; ++k) { storage_v(i, j, k) = functor(std::array<uint_t, 3>{d1, d2, d3}, i, j, k); } } } } template <class FunctorType, class StorageType> void for_each_impl(FunctorType&& functor, StorageType& storage) const { for_each_do_it(std::forward<FunctorType>(functor), storage); } template <class FunctorType, class StorageType, class... StorageTypes> void for_each_impl(FunctorType&& functor, StorageType& storage, StorageTypes&... storages) const { using namespace gridtools; for_each_do_it(std::forward<FunctorType>(functor), storage); for_each_impl(std::forward<FunctorType>(functor), storages...); } template <class StorageType> void fill_impl(typename StorageType::data_t value, StorageType& storage) const { using namespace gridtools; for_each([&](std::array<uint_t, 3> dims, uint_t i, uint_t j, uint_t k) { return value; }, storage); } template <class StorageType, class... StorageTypes> void fill_impl(typename StorageType::data_t value, StorageType& storage, StorageTypes&... storages) const { using namespace gridtools; for_each([&](std::array<uint_t, 3> dims, uint_t i, uint_t j, uint_t k) { return value; }, storage); fill_impl(value, storages...); } template <class StorageType, class FunctorType> void for_each_boundary_do_it(FunctorType&& functor, StorageType& storage) const { using namespace gridtools; auto sinfo = *(storage.get_storage_info_ptr()); auto storage_v = make_host_view(storage); const uint_t start_d1 = sinfo.template total_begin<0>(); const uint_t halo_d1 = decltype(sinfo)::halo_t::template at<0>(); const uint_t end_d1 = sinfo.template total_end<0>(); const uint_t start_d2 = sinfo.template total_begin<1>(); const uint_t halo_d2 = decltype(sinfo)::halo_t::template at<1>(); const uint_t end_d2 = sinfo.template total_end<1>(); const uint_t d3 = sinfo.template unaligned_dim<2>(); for(uint_t k = 0; k < d3; ++k) { for(uint_t i = start_d1; i < halo_d1; ++i) { for(uint_t j = start_d2; j < end_d2; ++j) { storage_v(i, j, k) = functor(std::array<uint_t, 3>{end_d1, end_d2, d3}, i, j, k); } } for(uint_t i = halo_d1; i < end_d1 - halo_d1; ++i) { for(uint_t j = start_d2; j < halo_d2; ++j) { storage_v(i, j, k) = functor(std::array<uint_t, 3>{end_d1, end_d2, d3}, i, j, k); } for(uint_t j = end_d2 - halo_d2; j < end_d2; ++j) { storage_v(i, j, k) = functor(std::array<uint_t, 3>{end_d1, end_d2, d3}, i, j, k); } } for(uint_t i = end_d1 - halo_d1; i < end_d1; ++i) { for(uint_t j = start_d2; j < end_d2; ++j) { storage_v(i, j, k) = functor(std::array<uint_t, 3>{end_d1, end_d2, d3}, i, j, k); } } } } template <class FunctorType, class StorageType> void for_each_boundary_impl(FunctorType&& functor, StorageType& storage) const { for_each_boundary_do_it(std::forward<FunctorType>(functor), storage); } template <class FunctorType, class StorageType, class... StorageTypes> void for_each_boundary_impl(FunctorType&& functor, StorageType& storage, StorageTypes&... storages) const { using namespace gridtools; for_each_boundary_do_it(std::forward<FunctorType>(functor), storage); for_each_boundary_impl(std::forward<FunctorType>(functor), storages...); } template <class StorageType> void boundary_fill_impl(typename StorageType::data_t value, StorageType& storage) const { using namespace gridtools; for_each_boundary( [&](std::array<uint_t, 3> dims, uint_t i, uint_t j, uint_t k) { return value; }, storage); } template <class StorageType, class... StorageTypes> void boundary_fill_impl(typename StorageType::data_t value, StorageType& storage, StorageTypes&... storages) const { using namespace gridtools; for_each_boundary( [&](std::array<uint_t, 3> dims, uint_t i, uint_t j, uint_t k) { return value; }, storage); boundary_fill_impl(value, storages...); } private: domain m_domain; double m_precision; }; } } #endif <commit_msg>fix checks on domain sizes (#53)<commit_after>//===--------------------------------------------------------------------------------*- C++ -*-===// // _ _ // | | | | // __ _| |_ ___| | __ _ _ __ __ _ // / _` | __/ __| |/ _` | '_ \ / _` | // | (_| | || (__| | (_| | | | | (_| | // \__, |\__\___|_|\__,_|_| |_|\__, | - GridTools Clang DSL // __/ | __/ | // |___/ |___/ // // // This file is distributed under the MIT License (MIT). // See LICENSE.txt for details. // //===------------------------------------------------------------------------------------------===// #ifndef GRIDTOOLS_CLANG_VERIFY_HPP #define GRIDTOOLS_CLANG_VERIFY_HPP #include "gridtools/clang_dsl.hpp" #include <array> #include <cmath> #include <cstdlib> #include <iostream> namespace gridtools { namespace clang { class verifier { public: verifier(const domain& dom, double precision = std::is_same<gridtools::float_type, double>::value ? 1e-12 : 1e-6) : m_domain(dom), m_precision(precision) {} template <class FunctorType, class... StorageTypes> void for_each(FunctorType&& functor, StorageTypes&... storages) const { for_each_impl(std::forward<FunctorType>(functor), storages...); } template <class FunctorType, class... StorageTypes> void for_each_boundary(FunctorType&& functor, StorageTypes&... storages) const { for_each_boundary_impl(std::forward<FunctorType>(functor), storages...); } template <class ValueType, class... StorageTypes> void fill(ValueType value, StorageTypes&... storages) const { fill_impl(value, storages...); } template <class... StorageTypes> void fillMath(double a, double b, double c, double d, double e, double f, StorageTypes&... storages) const { const gridtools::float_type pi = std::atan(1.) * 4.; for_each( [&](std::array<unsigned int, 3> dims, int i, int j, int k) { // 8,2,1.5,1.5,2,4 double x = i / (gridtools::float_type)dims[0]; double y = j / (gridtools::float_type)dims[1]; return k + (gridtools::float_type)a * ((gridtools::float_type)b + cos(pi * (x + (gridtools::float_type)c * y)) + sin((gridtools::float_type)d * pi * (x + (gridtools::float_type)e * y))) / (gridtools::float_type)f; }, storages...); } template <class... StorageTypes> void fill_random(StorageTypes&... storages) const { for_each([&](int, int, int) { return static_cast<double>(std::rand()) / RAND_MAX; }, storages...); } template <class ValueType, class... StorageTypes> void fill_boundaries(ValueType value, StorageTypes&... storages) const { boundary_fill_impl(value, storages...); } template <class StorageType1, class StorageType2> bool verify(StorageType1& storage1, StorageType2& storage2, int max_erros = 10) const { using namespace gridtools; storage1.sync(); storage2.sync(); auto meta_data_1 = *storage1.get_storage_info_ptr(); auto meta_data_2 = *storage2.get_storage_info_ptr(); const uint_t idim1 = meta_data_1.template unaligned_dim<0>(); const uint_t jdim1 = meta_data_1.template unaligned_dim<1>(); const uint_t kdim1 = meta_data_1.template unaligned_dim<2>(); const uint_t idim2 = meta_data_2.template unaligned_dim<0>(); const uint_t jdim2 = meta_data_2.template unaligned_dim<1>(); const uint_t kdim2 = meta_data_2.template unaligned_dim<2>(); auto storage1_v = make_host_view(storage1); auto storage2_v = make_host_view(storage2); // Check dimensions auto check_dim = [&](uint_t dim1, uint_t dim2, uint_t size, const char* dimstr) { if(dim1 != dim2 || dim1 < size) { std::cerr << "dimension \"" << dimstr << "\" missmatch in storage pair \"" << storage1.name() << "\" : \"" << storage2.name() << "\"\n"; std::cerr << " " << dimstr << "-dim storage1: " << dim1 << "\n"; std::cerr << " " << dimstr << "-dim storage2: " << dim2 << "\n"; std::cerr << " " << dimstr << "-size domain: " << size << "\n"; return false; } return true; }; check_dim(idim1, idim2, m_domain.isize(), "i"); check_dim(jdim1, jdim2, m_domain.jsize(), "j"); check_dim(kdim1, kdim2, m_domain.ksize(), "k"); bool verified = true; for(int i = m_domain.iminus(); i < (m_domain.isize() - m_domain.iplus()); ++i) for(int j = m_domain.jminus(); j < (m_domain.jsize() - m_domain.jplus()); ++j) for(int k = m_domain.kminus(); k < (m_domain.ksize() - m_domain.kplus()); ++k) { typename StorageType1::data_t value1 = storage1_v(i, j, k); typename StorageType2::data_t value2 = storage2_v(i, j, k); if(!compare_below_threashold(value1, value2, m_precision)) { if(--max_erros >= 0) { std::cerr << "( " << i << ", " << j << ", " << k << " ) : " << " " << storage1.name() << " = " << value1 << " ; " << " " << storage2.name() << " = " << value2 << " error: " << std::fabs((value2 - value1) / (value2)) << std::endl; } verified = false; } } return verified; } private: template <typename value_type> bool compare_below_threashold(value_type expected, value_type actual, value_type precision) const { if(std::fabs(expected) < 1e-3 && std::fabs(actual) < 1e-3) { if(std::fabs(expected - actual) < precision) return true; } else { if(std::fabs((expected - actual) / (precision * expected)) < 1.0) return true; } return false; } template <class StorageType, class FunctorType> void for_each_do_it(FunctorType&& functor, StorageType& storage) const { using namespace gridtools; auto sinfo = *(storage.get_storage_info_ptr()); auto storage_v = make_host_view(storage); const uint_t d1 = sinfo.template unaligned_dim<0>(); const uint_t d2 = sinfo.template unaligned_dim<1>(); const uint_t d3 = sinfo.template unaligned_dim<2>(); for(uint_t i = 0; i < d1; ++i) { for(uint_t j = 0; j < d2; ++j) { for(uint_t k = 0; k < d3; ++k) { storage_v(i, j, k) = functor(std::array<uint_t, 3>{d1, d2, d3}, i, j, k); } } } } template <class FunctorType, class StorageType> void for_each_impl(FunctorType&& functor, StorageType& storage) const { for_each_do_it(std::forward<FunctorType>(functor), storage); } template <class FunctorType, class StorageType, class... StorageTypes> void for_each_impl(FunctorType&& functor, StorageType& storage, StorageTypes&... storages) const { using namespace gridtools; for_each_do_it(std::forward<FunctorType>(functor), storage); for_each_impl(std::forward<FunctorType>(functor), storages...); } template <class StorageType> void fill_impl(typename StorageType::data_t value, StorageType& storage) const { using namespace gridtools; for_each([&](std::array<uint_t, 3> dims, uint_t i, uint_t j, uint_t k) { return value; }, storage); } template <class StorageType, class... StorageTypes> void fill_impl(typename StorageType::data_t value, StorageType& storage, StorageTypes&... storages) const { using namespace gridtools; for_each([&](std::array<uint_t, 3> dims, uint_t i, uint_t j, uint_t k) { return value; }, storage); fill_impl(value, storages...); } template <class StorageType, class FunctorType> void for_each_boundary_do_it(FunctorType&& functor, StorageType& storage) const { using namespace gridtools; auto sinfo = *(storage.get_storage_info_ptr()); auto storage_v = make_host_view(storage); const uint_t start_d1 = sinfo.template total_begin<0>(); const uint_t halo_d1 = decltype(sinfo)::halo_t::template at<0>(); const uint_t end_d1 = sinfo.template total_end<0>(); const uint_t start_d2 = sinfo.template total_begin<1>(); const uint_t halo_d2 = decltype(sinfo)::halo_t::template at<1>(); const uint_t end_d2 = sinfo.template total_end<1>(); const uint_t d3 = sinfo.template unaligned_dim<2>(); for(uint_t k = 0; k < d3; ++k) { for(uint_t i = start_d1; i < halo_d1; ++i) { for(uint_t j = start_d2; j < end_d2; ++j) { storage_v(i, j, k) = functor(std::array<uint_t, 3>{end_d1, end_d2, d3}, i, j, k); } } for(uint_t i = halo_d1; i < end_d1 - halo_d1; ++i) { for(uint_t j = start_d2; j < halo_d2; ++j) { storage_v(i, j, k) = functor(std::array<uint_t, 3>{end_d1, end_d2, d3}, i, j, k); } for(uint_t j = end_d2 - halo_d2; j < end_d2; ++j) { storage_v(i, j, k) = functor(std::array<uint_t, 3>{end_d1, end_d2, d3}, i, j, k); } } for(uint_t i = end_d1 - halo_d1; i < end_d1; ++i) { for(uint_t j = start_d2; j < end_d2; ++j) { storage_v(i, j, k) = functor(std::array<uint_t, 3>{end_d1, end_d2, d3}, i, j, k); } } } } template <class FunctorType, class StorageType> void for_each_boundary_impl(FunctorType&& functor, StorageType& storage) const { for_each_boundary_do_it(std::forward<FunctorType>(functor), storage); } template <class FunctorType, class StorageType, class... StorageTypes> void for_each_boundary_impl(FunctorType&& functor, StorageType& storage, StorageTypes&... storages) const { using namespace gridtools; for_each_boundary_do_it(std::forward<FunctorType>(functor), storage); for_each_boundary_impl(std::forward<FunctorType>(functor), storages...); } template <class StorageType> void boundary_fill_impl(typename StorageType::data_t value, StorageType& storage) const { using namespace gridtools; for_each_boundary( [&](std::array<uint_t, 3> dims, uint_t i, uint_t j, uint_t k) { return value; }, storage); } template <class StorageType, class... StorageTypes> void boundary_fill_impl(typename StorageType::data_t value, StorageType& storage, StorageTypes&... storages) const { using namespace gridtools; for_each_boundary( [&](std::array<uint_t, 3> dims, uint_t i, uint_t j, uint_t k) { return value; }, storage); boundary_fill_impl(value, storages...); } private: domain m_domain; double m_precision; }; } } #endif <|endoftext|>
<commit_before>/* Copyright 2016 Jonathan Bayle, Thomas Medioni Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "cyclist.hpp" #include <sstream> /** * * CYCLIST * */ Cyclist::Cyclist() : speed_(1.), sprinting_(false), sprinting_ratio_(1.) { sprite_ = std::unique_ptr<ALLEGRO_BITMAP, al_bitmap_deleter>(al_create_bitmap(32, 68)); al_set_target_bitmap(sprite_.get()); al_clear_to_color(al_map_rgb(255, 0, 255)); al_set_target_bitmap(al_get_backbuffer(al_get_current_display())); } Cyclist::~Cyclist() { } void Cyclist::update(double delta_t) { //update cyclist movement update_sprinting_ratio(delta_t); pos_.y += speed_ * 50. * sprinting_ratio_ * delta_t; } void Cyclist::draw() { al_draw_bitmap(sprite_.get(), 380 + pos_.x, 280 - pos_.y, 0); } void Cyclist::handle(const ALLEGRO_EVENT& event) { (void) event; //Handle events : void for bots } void Cyclist::update_sprinting_ratio(double delta_t) { if (sprinting_) sprinting_ratio_ = glm::clamp(sprinting_ratio_ + (1 * delta_t), 1., 2.); else sprinting_ratio_ = glm::clamp(sprinting_ratio_ - (1* delta_t), 1., 2.); } /** * * PLAYER CYCLIST * */ PlayerCyclist::PlayerCyclist() : Cyclist(), power_(1000) { add_draw_back( [&]() { al_draw_rectangle(772, 150, 790, 500, al_map_rgb(0, 255, 0), 1.); const int size = glm::clamp(power_, 0, maxpower) * 350 / maxpower; al_draw_filled_rectangle(772, 500 - size, 790, 500, al_map_rgb(0, 240, 0)); std::ostringstream oss; oss << power_ << " kcal"; al_draw_text(debug_font(), al_map_rgb(0, 255, 0), 790, 130, ALLEGRO_ALIGN_RIGHT, oss.str().c_str()); }); #ifndef NDEBUG #define POS #define SPT_RATIO #ifdef POS add_draw_back( [&]() { std::ostringstream oss; oss.precision(5); oss << "x: " << pos_.x << " y: " << pos_.y; al_draw_text(debug_font(), al_map_rgb(255, 255, 255), 10, 10, ALLEGRO_ALIGN_LEFT, oss.str().c_str()); }); #endif #ifdef SPT_RATIO add_draw_back( [&]() { std::ostringstream oss; oss.precision(3); oss << "SPT ratio: " << sprinting_ratio_; al_draw_text(debug_font(), al_map_rgb(255, 255, 255), 10, 20, ALLEGRO_ALIGN_LEFT, oss.str().c_str()); }); #endif #endif } PlayerCyclist::~PlayerCyclist() { } void PlayerCyclist::update(double delta_t) { Cyclist::update(delta_t); power_ -= speed_ * 50. * delta_t; if (power_ < 0) //LOST { power_ = 0; } } void PlayerCyclist::draw() { Cyclist::draw(); Object_split_aggregator::draw(); } void PlayerCyclist::handle(const ALLEGRO_EVENT& event) { Object_split_aggregator::handle(event); switch(event.type) { case ALLEGRO_EVENT_KEY_DOWN: switch(event.keyboard.keycode) { case ALLEGRO_KEY_LCTRL: sprinting_ = true; break; } break; case ALLEGRO_EVENT_KEY_UP: switch(event.keyboard.keycode) { case ALLEGRO_KEY_LCTRL: sprinting_ = false; break; } break; } } bool PlayerCyclist::alive() { return power_ > 0; } <commit_msg>little fix, update power wrt sprinting ratio<commit_after>/* Copyright 2016 Jonathan Bayle, Thomas Medioni Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "cyclist.hpp" #include <sstream> /** * * CYCLIST * */ Cyclist::Cyclist() : speed_(1.), sprinting_(false), sprinting_ratio_(1.) { sprite_ = std::unique_ptr<ALLEGRO_BITMAP, al_bitmap_deleter>(al_create_bitmap(32, 68)); al_set_target_bitmap(sprite_.get()); al_clear_to_color(al_map_rgb(255, 0, 255)); al_set_target_bitmap(al_get_backbuffer(al_get_current_display())); } Cyclist::~Cyclist() { } void Cyclist::update(double delta_t) { //update cyclist movement update_sprinting_ratio(delta_t); pos_.y += speed_ * 50. * sprinting_ratio_ * delta_t; } void Cyclist::draw() { al_draw_bitmap(sprite_.get(), 380 + pos_.x, 280 - pos_.y, 0); } void Cyclist::handle(const ALLEGRO_EVENT& event) { (void) event; //Handle events : void for bots } void Cyclist::update_sprinting_ratio(double delta_t) { if (sprinting_) sprinting_ratio_ = glm::clamp(sprinting_ratio_ + (1 * delta_t), 1., 2.); else sprinting_ratio_ = glm::clamp(sprinting_ratio_ - (1 * delta_t), 1., 2.); } /** * * PLAYER CYCLIST * */ PlayerCyclist::PlayerCyclist() : Cyclist(), power_(1000) { add_draw_back( [&]() { al_draw_rectangle(772, 150, 790, 500, al_map_rgb(0, 255, 0), 1.); const int size = glm::clamp(power_, 0, maxpower) * 350 / maxpower; al_draw_filled_rectangle(772, 500 - size, 790, 500, al_map_rgb(0, 240, 0)); std::ostringstream oss; oss << power_ << " kcal"; al_draw_text(debug_font(), al_map_rgb(0, 255, 0), 790, 130, ALLEGRO_ALIGN_RIGHT, oss.str().c_str()); }); #ifndef NDEBUG #define POS #define SPT_RATIO #ifdef POS add_draw_back( [&]() { std::ostringstream oss; oss.precision(5); oss << "x: " << pos_.x << " y: " << pos_.y; al_draw_text(debug_font(), al_map_rgb(255, 255, 255), 10, 10, ALLEGRO_ALIGN_LEFT, oss.str().c_str()); }); #endif #ifdef SPT_RATIO add_draw_back( [&]() { std::ostringstream oss; oss.precision(3); oss << "SPT ratio: " << sprinting_ratio_; al_draw_text(debug_font(), al_map_rgb(255, 255, 255), 10, 20, ALLEGRO_ALIGN_LEFT, oss.str().c_str()); }); #endif #endif } PlayerCyclist::~PlayerCyclist() { } void PlayerCyclist::update(double delta_t) { Cyclist::update(delta_t); power_ -= speed_ * 50. * sprinting_ratio_ * delta_t; if (power_ < 0) //LOST { power_ = 0; } } void PlayerCyclist::draw() { Cyclist::draw(); Object_split_aggregator::draw(); } void PlayerCyclist::handle(const ALLEGRO_EVENT& event) { Object_split_aggregator::handle(event); switch(event.type) { case ALLEGRO_EVENT_KEY_DOWN: switch(event.keyboard.keycode) { case ALLEGRO_KEY_LCTRL: sprinting_ = true; break; } break; case ALLEGRO_EVENT_KEY_UP: switch(event.keyboard.keycode) { case ALLEGRO_KEY_LCTRL: sprinting_ = false; break; } break; } } bool PlayerCyclist::alive() { return power_ > 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "jni_internal.h" #include "class_linker.h" #include "object.h" #include "object_utils.h" #include "reflection.h" #include "JniConstants.h" // Last to avoid problems with LOG redefinition. namespace art { static bool GetFieldValue(Object* o, Field* f, JValue& value, bool allow_references) { ScopedThreadStateChange tsc(Thread::Current(), kRunnable); if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(f->GetDeclaringClass(), true, true)) { return false; } switch (FieldHelper(f).GetTypeAsPrimitiveType()) { case Primitive::kPrimBoolean: value.z = f->GetBoolean(o); return true; case Primitive::kPrimByte: value.b = f->GetByte(o); return true; case Primitive::kPrimChar: value.c = f->GetChar(o); return true; case Primitive::kPrimDouble: value.d = f->GetDouble(o); return true; case Primitive::kPrimFloat: value.f = f->GetFloat(o); return true; case Primitive::kPrimInt: value.i = f->GetInt(o); return true; case Primitive::kPrimLong: value.j = f->GetLong(o); return true; case Primitive::kPrimShort: value.s = f->GetShort(o); return true; case Primitive::kPrimNot: if (allow_references) { value.l = f->GetObject(o); return true; } // Else break to report an error. break; case Primitive::kPrimVoid: // Never okay. break; } Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "Not a primitive field: %s", PrettyField(f).c_str()); return false; } static bool CheckReceiver(JNIEnv* env, jobject javaObj, Field* f, Object*& o) { if (f->IsStatic()) { o = NULL; return true; } o = Decode<Object*>(env, javaObj); Class* declaringClass = f->GetDeclaringClass(); if (!VerifyObjectInClass(env, o, declaringClass)) { return false; } return true; } static jobject Field_get(JNIEnv* env, jobject javaField, jobject javaObj) { Field* f = DecodeField(env->FromReflectedField(javaField)); Object* o = NULL; if (!CheckReceiver(env, javaObj, f, o)) { return NULL; } // Get the field's value, boxing if necessary. JValue value = { 0 }; if (!GetFieldValue(o, f, value, true)) { return NULL; } BoxPrimitive(FieldHelper(f).GetTypeAsPrimitiveType(), value); return AddLocalReference<jobject>(env, value.l); } static JValue GetPrimitiveField(JNIEnv* env, jobject javaField, jobject javaObj, char dst_descriptor) { Field* f = DecodeField(env->FromReflectedField(javaField)); Object* o = NULL; if (!CheckReceiver(env, javaObj, f, o)) { return JValue(); } // Read the value. JValue field_value = { 0 }; if (!GetFieldValue(o, f, field_value, false)) { return JValue(); } // Widen it if necessary (and possible). JValue wide_value; Class* dst_type = Runtime::Current()->GetClassLinker()->FindPrimitiveClass(dst_descriptor); if (!ConvertPrimitiveValue(FieldHelper(f).GetTypeAsPrimitiveType(), dst_type->GetPrimitiveType(), field_value, wide_value)) { return JValue(); } return wide_value; } static jboolean Field_getBoolean(JNIEnv* env, jobject javaField, jobject javaObj) { return GetPrimitiveField(env, javaField, javaObj, 'Z').z; } static jbyte Field_getByte(JNIEnv* env, jobject javaField, jobject javaObj) { return GetPrimitiveField(env, javaField, javaObj, 'B').b; } static jchar Field_getChar(JNIEnv* env, jobject javaField, jobject javaObj) { return GetPrimitiveField(env, javaField, javaObj, 'C').c; } static jdouble Field_getDouble(JNIEnv* env, jobject javaField, jobject javaObj) { return GetPrimitiveField(env, javaField, javaObj, 'D').d; } static jfloat Field_getFloat(JNIEnv* env, jobject javaField, jobject javaObj) { return GetPrimitiveField(env, javaField, javaObj, 'F').f; } static jint Field_getInt(JNIEnv* env, jobject javaField, jobject javaObj) { return GetPrimitiveField(env, javaField, javaObj, 'I').i; } static jlong Field_getLong(JNIEnv* env, jobject javaField, jobject javaObj) { return GetPrimitiveField(env, javaField, javaObj, 'J').j; } static jshort Field_getShort(JNIEnv* env, jobject javaField, jobject javaObj) { return GetPrimitiveField(env, javaField, javaObj, 'S').s; } static void SetFieldValue(Object* o, Field* f, const JValue& new_value, bool allow_references) { if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(f->GetDeclaringClass(), true, true)) { return; } switch (FieldHelper(f).GetTypeAsPrimitiveType()) { case Primitive::kPrimBoolean: f->SetBoolean(o, new_value.z); break; case Primitive::kPrimByte: f->SetByte(o, new_value.b); break; case Primitive::kPrimChar: f->SetChar(o, new_value.c); break; case Primitive::kPrimDouble: f->SetDouble(o, new_value.d); break; case Primitive::kPrimFloat: f->SetFloat(o, new_value.f); break; case Primitive::kPrimInt: f->SetInt(o, new_value.i); break; case Primitive::kPrimLong: f->SetLong(o, new_value.j); break; case Primitive::kPrimShort: f->SetShort(o, new_value.s); break; case Primitive::kPrimNot: if (allow_references) { f->SetObject(o, new_value.l); break; } // Else fall through to report an error. case Primitive::kPrimVoid: // Never okay. Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "Not a primitive field: %s", PrettyField(f).c_str()); return; } // Special handling for final fields on SMP systems. // We need a store/store barrier here (JMM requirement). if (f->IsFinal()) { ANDROID_MEMBAR_STORE(); } } static void Field_set(JNIEnv* env, jobject javaField, jobject javaObj, jobject javaValue) { ScopedThreadStateChange tsc(Thread::Current(), kRunnable); Field* f = DecodeField(env->FromReflectedField(javaField)); // Unbox the value, if necessary. Object* boxed_value = Decode<Object*>(env, javaValue); JValue unboxed_value; if (!UnboxPrimitive(boxed_value, FieldHelper(f).GetType(), unboxed_value, "field")) { return; } // Check that the receiver is non-null and an instance of the field's declaring class. Object* o = NULL; if (!CheckReceiver(env, javaObj, f, o)) { return; } SetFieldValue(o, f, unboxed_value, true); } static void SetPrimitiveField(JNIEnv* env, jobject javaField, jobject javaObj, char src_descriptor, const JValue& new_value) { ScopedThreadStateChange tsc(Thread::Current(), kRunnable); Field* f = DecodeField(env->FromReflectedField(javaField)); Object* o = NULL; if (!CheckReceiver(env, javaObj, f, o)) { return; } FieldHelper fh(f); if (!fh.IsPrimitiveType()) { Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "Not a primitive field: %s", PrettyField(f).c_str()); return; } // Widen the value if necessary (and possible). JValue wide_value; Class* src_type = Runtime::Current()->GetClassLinker()->FindPrimitiveClass(src_descriptor); if (!ConvertPrimitiveValue(src_type->GetPrimitiveType(), fh.GetTypeAsPrimitiveType(), new_value, wide_value)) { return; } // Write the value. SetFieldValue(o, f, wide_value, false); } static void Field_setBoolean(JNIEnv* env, jobject javaField, jobject javaObj, jboolean value) { JValue v = { 0 }; v.z = value; SetPrimitiveField(env, javaField, javaObj, 'Z', v); } static void Field_setByte(JNIEnv* env, jobject javaField, jobject javaObj, jbyte value) { JValue v = { 0 }; v.b = value; SetPrimitiveField(env, javaField, javaObj, 'B', v); } static void Field_setChar(JNIEnv* env, jobject javaField, jobject javaObj, jchar value) { JValue v = { 0 }; v.c = value; SetPrimitiveField(env, javaField, javaObj, 'C', v); } static void Field_setDouble(JNIEnv* env, jobject javaField, jobject javaObj, jdouble value) { JValue v = { 0 }; v.d = value; SetPrimitiveField(env, javaField, javaObj, 'D', v); } static void Field_setFloat(JNIEnv* env, jobject javaField, jobject javaObj, jfloat value) { JValue v = { 0 }; v.f = value; SetPrimitiveField(env, javaField, javaObj, 'F', v); } static void Field_setInt(JNIEnv* env, jobject javaField, jobject javaObj, jint value) { JValue v = { 0 }; v.i = value; SetPrimitiveField(env, javaField, javaObj, 'I', v); } static void Field_setLong(JNIEnv* env, jobject javaField, jobject javaObj, jlong value) { JValue v = { 0 }; v.j = value; SetPrimitiveField(env, javaField, javaObj, 'J', v); } static void Field_setShort(JNIEnv* env, jobject javaField, jobject javaObj, jshort value) { JValue v = { 0 }; v.s = value; SetPrimitiveField(env, javaField, javaObj, 'S', v); } static JNINativeMethod gMethods[] = { NATIVE_METHOD(Field, get, "(Ljava/lang/Object;)Ljava/lang/Object;"), NATIVE_METHOD(Field, getBoolean, "(Ljava/lang/Object;)Z"), NATIVE_METHOD(Field, getByte, "(Ljava/lang/Object;)B"), NATIVE_METHOD(Field, getChar, "(Ljava/lang/Object;)C"), NATIVE_METHOD(Field, getDouble, "(Ljava/lang/Object;)D"), NATIVE_METHOD(Field, getFloat, "(Ljava/lang/Object;)F"), NATIVE_METHOD(Field, getInt, "(Ljava/lang/Object;)I"), NATIVE_METHOD(Field, getLong, "(Ljava/lang/Object;)J"), NATIVE_METHOD(Field, getShort, "(Ljava/lang/Object;)S"), NATIVE_METHOD(Field, set, "(Ljava/lang/Object;Ljava/lang/Object;)V"), NATIVE_METHOD(Field, setBoolean, "(Ljava/lang/Object;Z)V"), NATIVE_METHOD(Field, setByte, "(Ljava/lang/Object;B)V"), NATIVE_METHOD(Field, setChar, "(Ljava/lang/Object;C)V"), NATIVE_METHOD(Field, setDouble, "(Ljava/lang/Object;D)V"), NATIVE_METHOD(Field, setFloat, "(Ljava/lang/Object;F)V"), NATIVE_METHOD(Field, setInt, "(Ljava/lang/Object;I)V"), NATIVE_METHOD(Field, setLong, "(Ljava/lang/Object;J)V"), NATIVE_METHOD(Field, setShort, "(Ljava/lang/Object;S)V"), }; void register_java_lang_reflect_Field(JNIEnv* env) { jniRegisterNativeMethods(env, "java/lang/reflect/Field", gMethods, NELEM(gMethods)); } } // namespace art <commit_msg>am 4b952e74: Merge "Ensure byte and short values are sign extended before boxing." into ics-mr1-plus-art<commit_after>/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "jni_internal.h" #include "class_linker.h" #include "object.h" #include "object_utils.h" #include "reflection.h" #include "JniConstants.h" // Last to avoid problems with LOG redefinition. namespace art { static bool GetFieldValue(Object* o, Field* f, JValue& value, bool allow_references) { DCHECK_EQ(value.j, 0LL); ScopedThreadStateChange tsc(Thread::Current(), kRunnable); if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(f->GetDeclaringClass(), true, true)) { return false; } switch (FieldHelper(f).GetTypeAsPrimitiveType()) { case Primitive::kPrimBoolean: value.z = f->GetBoolean(o); return true; case Primitive::kPrimByte: // Read byte and ensure it is fully sign-extended to an int. value.i = ((int32_t)f->GetByte(o) << 24) >> 24; return true; case Primitive::kPrimChar: value.c = f->GetChar(o); return true; case Primitive::kPrimDouble: value.d = f->GetDouble(o); return true; case Primitive::kPrimFloat: value.f = f->GetFloat(o); return true; case Primitive::kPrimInt: value.i = f->GetInt(o); return true; case Primitive::kPrimLong: value.j = f->GetLong(o); return true; case Primitive::kPrimShort: // Read short and ensure it is fully sign-extended to an int. value.i = ((int32_t)f->GetShort(o) << 16) >> 16; return true; case Primitive::kPrimNot: if (allow_references) { value.l = f->GetObject(o); return true; } // Else break to report an error. break; case Primitive::kPrimVoid: // Never okay. break; } Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "Not a primitive field: %s", PrettyField(f).c_str()); return false; } static bool CheckReceiver(JNIEnv* env, jobject javaObj, Field* f, Object*& o) { if (f->IsStatic()) { o = NULL; return true; } o = Decode<Object*>(env, javaObj); Class* declaringClass = f->GetDeclaringClass(); if (!VerifyObjectInClass(env, o, declaringClass)) { return false; } return true; } static jobject Field_get(JNIEnv* env, jobject javaField, jobject javaObj) { Field* f = DecodeField(env->FromReflectedField(javaField)); Object* o = NULL; if (!CheckReceiver(env, javaObj, f, o)) { return NULL; } // Get the field's value, boxing if necessary. JValue value = { 0 }; if (!GetFieldValue(o, f, value, true)) { return NULL; } BoxPrimitive(FieldHelper(f).GetTypeAsPrimitiveType(), value); return AddLocalReference<jobject>(env, value.l); } static JValue GetPrimitiveField(JNIEnv* env, jobject javaField, jobject javaObj, char dst_descriptor) { Field* f = DecodeField(env->FromReflectedField(javaField)); Object* o = NULL; if (!CheckReceiver(env, javaObj, f, o)) { return JValue(); } // Read the value. JValue field_value = { 0 }; if (!GetFieldValue(o, f, field_value, false)) { return JValue(); } // Widen it if necessary (and possible). JValue wide_value; Class* dst_type = Runtime::Current()->GetClassLinker()->FindPrimitiveClass(dst_descriptor); if (!ConvertPrimitiveValue(FieldHelper(f).GetTypeAsPrimitiveType(), dst_type->GetPrimitiveType(), field_value, wide_value)) { return JValue(); } return wide_value; } static jboolean Field_getBoolean(JNIEnv* env, jobject javaField, jobject javaObj) { return GetPrimitiveField(env, javaField, javaObj, 'Z').z; } static jbyte Field_getByte(JNIEnv* env, jobject javaField, jobject javaObj) { return GetPrimitiveField(env, javaField, javaObj, 'B').b; } static jchar Field_getChar(JNIEnv* env, jobject javaField, jobject javaObj) { return GetPrimitiveField(env, javaField, javaObj, 'C').c; } static jdouble Field_getDouble(JNIEnv* env, jobject javaField, jobject javaObj) { return GetPrimitiveField(env, javaField, javaObj, 'D').d; } static jfloat Field_getFloat(JNIEnv* env, jobject javaField, jobject javaObj) { return GetPrimitiveField(env, javaField, javaObj, 'F').f; } static jint Field_getInt(JNIEnv* env, jobject javaField, jobject javaObj) { return GetPrimitiveField(env, javaField, javaObj, 'I').i; } static jlong Field_getLong(JNIEnv* env, jobject javaField, jobject javaObj) { return GetPrimitiveField(env, javaField, javaObj, 'J').j; } static jshort Field_getShort(JNIEnv* env, jobject javaField, jobject javaObj) { return GetPrimitiveField(env, javaField, javaObj, 'S').s; } static void SetFieldValue(Object* o, Field* f, const JValue& new_value, bool allow_references) { if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(f->GetDeclaringClass(), true, true)) { return; } switch (FieldHelper(f).GetTypeAsPrimitiveType()) { case Primitive::kPrimBoolean: f->SetBoolean(o, new_value.z); break; case Primitive::kPrimByte: f->SetByte(o, new_value.b); break; case Primitive::kPrimChar: f->SetChar(o, new_value.c); break; case Primitive::kPrimDouble: f->SetDouble(o, new_value.d); break; case Primitive::kPrimFloat: f->SetFloat(o, new_value.f); break; case Primitive::kPrimInt: f->SetInt(o, new_value.i); break; case Primitive::kPrimLong: f->SetLong(o, new_value.j); break; case Primitive::kPrimShort: f->SetShort(o, new_value.s); break; case Primitive::kPrimNot: if (allow_references) { f->SetObject(o, new_value.l); break; } // Else fall through to report an error. case Primitive::kPrimVoid: // Never okay. Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "Not a primitive field: %s", PrettyField(f).c_str()); return; } // Special handling for final fields on SMP systems. // We need a store/store barrier here (JMM requirement). if (f->IsFinal()) { ANDROID_MEMBAR_STORE(); } } static void Field_set(JNIEnv* env, jobject javaField, jobject javaObj, jobject javaValue) { ScopedThreadStateChange tsc(Thread::Current(), kRunnable); Field* f = DecodeField(env->FromReflectedField(javaField)); // Unbox the value, if necessary. Object* boxed_value = Decode<Object*>(env, javaValue); JValue unboxed_value; if (!UnboxPrimitive(boxed_value, FieldHelper(f).GetType(), unboxed_value, "field")) { return; } // Check that the receiver is non-null and an instance of the field's declaring class. Object* o = NULL; if (!CheckReceiver(env, javaObj, f, o)) { return; } SetFieldValue(o, f, unboxed_value, true); } static void SetPrimitiveField(JNIEnv* env, jobject javaField, jobject javaObj, char src_descriptor, const JValue& new_value) { ScopedThreadStateChange tsc(Thread::Current(), kRunnable); Field* f = DecodeField(env->FromReflectedField(javaField)); Object* o = NULL; if (!CheckReceiver(env, javaObj, f, o)) { return; } FieldHelper fh(f); if (!fh.IsPrimitiveType()) { Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;", "Not a primitive field: %s", PrettyField(f).c_str()); return; } // Widen the value if necessary (and possible). JValue wide_value; Class* src_type = Runtime::Current()->GetClassLinker()->FindPrimitiveClass(src_descriptor); if (!ConvertPrimitiveValue(src_type->GetPrimitiveType(), fh.GetTypeAsPrimitiveType(), new_value, wide_value)) { return; } // Write the value. SetFieldValue(o, f, wide_value, false); } static void Field_setBoolean(JNIEnv* env, jobject javaField, jobject javaObj, jboolean value) { JValue v = { 0 }; v.z = value; SetPrimitiveField(env, javaField, javaObj, 'Z', v); } static void Field_setByte(JNIEnv* env, jobject javaField, jobject javaObj, jbyte value) { JValue v = { 0 }; v.b = value; SetPrimitiveField(env, javaField, javaObj, 'B', v); } static void Field_setChar(JNIEnv* env, jobject javaField, jobject javaObj, jchar value) { JValue v = { 0 }; v.c = value; SetPrimitiveField(env, javaField, javaObj, 'C', v); } static void Field_setDouble(JNIEnv* env, jobject javaField, jobject javaObj, jdouble value) { JValue v = { 0 }; v.d = value; SetPrimitiveField(env, javaField, javaObj, 'D', v); } static void Field_setFloat(JNIEnv* env, jobject javaField, jobject javaObj, jfloat value) { JValue v = { 0 }; v.f = value; SetPrimitiveField(env, javaField, javaObj, 'F', v); } static void Field_setInt(JNIEnv* env, jobject javaField, jobject javaObj, jint value) { JValue v = { 0 }; v.i = value; SetPrimitiveField(env, javaField, javaObj, 'I', v); } static void Field_setLong(JNIEnv* env, jobject javaField, jobject javaObj, jlong value) { JValue v = { 0 }; v.j = value; SetPrimitiveField(env, javaField, javaObj, 'J', v); } static void Field_setShort(JNIEnv* env, jobject javaField, jobject javaObj, jshort value) { JValue v = { 0 }; v.s = value; SetPrimitiveField(env, javaField, javaObj, 'S', v); } static JNINativeMethod gMethods[] = { NATIVE_METHOD(Field, get, "(Ljava/lang/Object;)Ljava/lang/Object;"), NATIVE_METHOD(Field, getBoolean, "(Ljava/lang/Object;)Z"), NATIVE_METHOD(Field, getByte, "(Ljava/lang/Object;)B"), NATIVE_METHOD(Field, getChar, "(Ljava/lang/Object;)C"), NATIVE_METHOD(Field, getDouble, "(Ljava/lang/Object;)D"), NATIVE_METHOD(Field, getFloat, "(Ljava/lang/Object;)F"), NATIVE_METHOD(Field, getInt, "(Ljava/lang/Object;)I"), NATIVE_METHOD(Field, getLong, "(Ljava/lang/Object;)J"), NATIVE_METHOD(Field, getShort, "(Ljava/lang/Object;)S"), NATIVE_METHOD(Field, set, "(Ljava/lang/Object;Ljava/lang/Object;)V"), NATIVE_METHOD(Field, setBoolean, "(Ljava/lang/Object;Z)V"), NATIVE_METHOD(Field, setByte, "(Ljava/lang/Object;B)V"), NATIVE_METHOD(Field, setChar, "(Ljava/lang/Object;C)V"), NATIVE_METHOD(Field, setDouble, "(Ljava/lang/Object;D)V"), NATIVE_METHOD(Field, setFloat, "(Ljava/lang/Object;F)V"), NATIVE_METHOD(Field, setInt, "(Ljava/lang/Object;I)V"), NATIVE_METHOD(Field, setLong, "(Ljava/lang/Object;J)V"), NATIVE_METHOD(Field, setShort, "(Ljava/lang/Object;S)V"), }; void register_java_lang_reflect_Field(JNIEnv* env) { jniRegisterNativeMethods(env, "java/lang/reflect/Field", gMethods, NELEM(gMethods)); } } // namespace art <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "TextAndDescription.h" namespace Interaction { DEFINE_ITEM_COMMON(TextAndDescription, "item") using namespace Visualization; TextAndDescription::TextAndDescription(Item* parent, const StyleType* style) : Super{parent, style}, textVis_{}, descriptionVis_{} { } TextAndDescription::TextAndDescription(const QString& text, const QString& description, const StyleType* style) : TextAndDescription{nullptr, style} { setContents(text, description); } TextAndDescription::~TextAndDescription() { // These will automatically be deleted by layout's destructor textVis_ = nullptr; descriptionVis_ = nullptr; } bool TextAndDescription::sizeDependsOnParent() const { return true; } void TextAndDescription::setContents(const QString& text, const QString& description) { text_ = text; description_ = description; } void TextAndDescription::determineChildren() { layout()->synchronizeFirst(textVis_, !text_.isEmpty(), &style()->text()); layout()->synchronizeLast(descriptionVis_, !description_.isEmpty(), &style()->description()); layout()->setStyle( &style()->layout() ); if (textVis_) { textVis_->setStyle( &style()->text() ); textVis_->setText(text_); } if (descriptionVis_) { descriptionVis_->setStyle( &style()->description() ); descriptionVis_->setText(description_); } } } <commit_msg>Use RichText as text format for descriptionVis_<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "TextAndDescription.h" namespace Interaction { DEFINE_ITEM_COMMON(TextAndDescription, "item") using namespace Visualization; TextAndDescription::TextAndDescription(Item* parent, const StyleType* style) : Super{parent, style}, textVis_{}, descriptionVis_{} { } TextAndDescription::TextAndDescription(const QString& text, const QString& description, const StyleType* style) : TextAndDescription{nullptr, style} { setContents(text, description); } TextAndDescription::~TextAndDescription() { // These will automatically be deleted by layout's destructor textVis_ = nullptr; descriptionVis_ = nullptr; } bool TextAndDescription::sizeDependsOnParent() const { return true; } void TextAndDescription::setContents(const QString& text, const QString& description) { text_ = text; description_ = description; } void TextAndDescription::determineChildren() { layout()->synchronizeFirst(textVis_, !text_.isEmpty(), &style()->text()); layout()->synchronizeLast(descriptionVis_, !description_.isEmpty(), &style()->description()); layout()->setStyle( &style()->layout() ); if (textVis_) { textVis_->setStyle( &style()->text() ); textVis_->setText(text_); } if (descriptionVis_) { descriptionVis_->setStyle( &style()->description() ); descriptionVis_->setText(description_); descriptionVis_->setTextFormat(Qt::RichText); } } } <|endoftext|>
<commit_before>/* Copyright (c) 2014, Project OSRM, Dennis Luxen, others 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. */ #ifndef DISTANCE_TABLE_PLUGIN_H #define DISTANCE_TABLE_PLUGIN_H #include "plugin_base.hpp" #include "../algorithms/object_encoder.hpp" #include "../data_structures/json_container.hpp" #include "../data_structures/query_edge.hpp" #include "../data_structures/search_engine.hpp" #include "../descriptors/descriptor_base.hpp" #include "../Util/json_renderer.hpp" #include "../Util/make_unique.hpp" #include "../Util/StringUtil.h" #include "../Util/timing_util.hpp" #include <cstdlib> #include <algorithm> #include <memory> #include <unordered_map> #include <string> #include <vector> template <class DataFacadeT> class DistanceTablePlugin final : public BasePlugin { private: std::unique_ptr<SearchEngine<DataFacadeT>> search_engine_ptr; public: explicit DistanceTablePlugin(DataFacadeT *facade) : descriptor_string("table"), facade(facade) { search_engine_ptr = osrm::make_unique<SearchEngine<DataFacadeT>>(facade); } virtual ~DistanceTablePlugin() {} const std::string GetDescriptor() const final { return descriptor_string; } void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) final { if (!check_all_coordinates(route_parameters.coordinates)) { reply = http::Reply::StockReply(http::Reply::badRequest); return; } const bool checksum_OK = (route_parameters.check_sum == facade->GetCheckSum()); unsigned max_locations = std::min(100u, static_cast<unsigned>(route_parameters.coordinates.size())); PhantomNodeArray phantom_node_vector(max_locations); for (const auto i : osrm::irange(1u, max_locations)) { if (checksum_OK && i < route_parameters.hints.size() && !route_parameters.hints[i].empty()) { PhantomNode current_phantom_node; ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], current_phantom_node); if (current_phantom_node.is_valid(facade->GetNumberOfNodes())) { phantom_node_vector[i].emplace_back(std::move(current_phantom_node)); continue; } } facade->IncrementalFindPhantomNodeForCoordinate(route_parameters.coordinates[i], phantom_node_vector[i], 1); BOOST_ASSERT(phantom_node_vector[i].front().is_valid(facade->GetNumberOfNodes())); } // TIMER_START(distance_table); std::shared_ptr<std::vector<EdgeWeight>> result_table = search_engine_ptr->distance_table(phantom_node_vector); // TIMER_STOP(distance_table); if (!result_table) { reply = http::Reply::StockReply(http::Reply::badRequest); return; } JSON::Object json_object; JSON::Array json_array; const unsigned number_of_locations = static_cast<unsigned>(phantom_node_vector.size()); for (unsigned row = 0; row < number_of_locations; ++row) { JSON::Array json_row; auto row_begin_iterator = result_table->begin() + (row * number_of_locations); auto row_end_iterator = result_table->begin() + ((row + 1) * number_of_locations); json_row.values.insert(json_row.values.end(), row_begin_iterator, row_end_iterator); json_array.values.push_back(json_row); } json_object.values["distance_table"] = json_array; JSON::render(reply.content, json_object); } private: std::string descriptor_string; DataFacadeT *facade; }; #endif // DISTANCE_TABLE_PLUGIN_H <commit_msg>Fix off-by-one in distance table plugin.<commit_after>/* Copyright (c) 2014, Project OSRM, Dennis Luxen, others 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. */ #ifndef DISTANCE_TABLE_PLUGIN_H #define DISTANCE_TABLE_PLUGIN_H #include "plugin_base.hpp" #include "../algorithms/object_encoder.hpp" #include "../data_structures/json_container.hpp" #include "../data_structures/query_edge.hpp" #include "../data_structures/search_engine.hpp" #include "../descriptors/descriptor_base.hpp" #include "../Util/json_renderer.hpp" #include "../Util/make_unique.hpp" #include "../Util/StringUtil.h" #include "../Util/timing_util.hpp" #include <cstdlib> #include <algorithm> #include <memory> #include <unordered_map> #include <string> #include <vector> template <class DataFacadeT> class DistanceTablePlugin final : public BasePlugin { private: std::unique_ptr<SearchEngine<DataFacadeT>> search_engine_ptr; public: explicit DistanceTablePlugin(DataFacadeT *facade) : descriptor_string("table"), facade(facade) { search_engine_ptr = osrm::make_unique<SearchEngine<DataFacadeT>>(facade); } virtual ~DistanceTablePlugin() {} const std::string GetDescriptor() const final { return descriptor_string; } void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) final { if (!check_all_coordinates(route_parameters.coordinates)) { reply = http::Reply::StockReply(http::Reply::badRequest); return; } const bool checksum_OK = (route_parameters.check_sum == facade->GetCheckSum()); unsigned max_locations = std::min(100u, static_cast<unsigned>(route_parameters.coordinates.size())); PhantomNodeArray phantom_node_vector(max_locations); for (const auto i : osrm::irange(0u, max_locations)) { if (checksum_OK && i < route_parameters.hints.size() && !route_parameters.hints[i].empty()) { PhantomNode current_phantom_node; ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], current_phantom_node); if (current_phantom_node.is_valid(facade->GetNumberOfNodes())) { phantom_node_vector[i].emplace_back(std::move(current_phantom_node)); continue; } } facade->IncrementalFindPhantomNodeForCoordinate(route_parameters.coordinates[i], phantom_node_vector[i], 1); BOOST_ASSERT(phantom_node_vector[i].front().is_valid(facade->GetNumberOfNodes())); } // TIMER_START(distance_table); std::shared_ptr<std::vector<EdgeWeight>> result_table = search_engine_ptr->distance_table(phantom_node_vector); // TIMER_STOP(distance_table); if (!result_table) { reply = http::Reply::StockReply(http::Reply::badRequest); return; } JSON::Object json_object; JSON::Array json_array; const unsigned number_of_locations = static_cast<unsigned>(phantom_node_vector.size()); for (unsigned row = 0; row < number_of_locations; ++row) { JSON::Array json_row; auto row_begin_iterator = result_table->begin() + (row * number_of_locations); auto row_end_iterator = result_table->begin() + ((row + 1) * number_of_locations); json_row.values.insert(json_row.values.end(), row_begin_iterator, row_end_iterator); json_array.values.push_back(json_row); } json_object.values["distance_table"] = json_array; JSON::render(reply.content, json_object); } private: std::string descriptor_string; DataFacadeT *facade; }; #endif // DISTANCE_TABLE_PLUGIN_H <|endoftext|>
<commit_before>/** * projectM -- Milkdrop-esque visualisation SDK * Copyright (C)2003-2004 projectM Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * See 'LICENSE.txt' included within this release * */ #include <stdio.h> #include "Common.hpp" #include "fatal.h" #include "KeyHandler.hpp" #include "event.h" #include "BeatDetect.hpp" #include "PresetChooser.hpp" #include "Renderer.hpp" #include "projectM.hpp" #include <iostream> #include "TimeKeeper.hpp" class Preset; interface_t current_interface = DEFAULT_INTERFACE; void selectRandom(const bool hardCut); void selectNext(const bool hardCut); void selectPrevious(const bool hardCut); std::string round_float(float number) { std::string num_text = std::to_string(number); std::string rounded = num_text.substr(0, num_text.find(".")+3); return rounded; } void refreshConsole() { switch (current_interface) { case MENU_INTERFACE: // unimplemented break; case SHELL_INTERFACE: // unimplemented break; case EDITOR_INTERFACE: // unimplemented break; case DEFAULT_INTERFACE: break; case BROWSER_INTERFACE: // unimplemented break; default: break; } } void projectM::key_handler( projectMEvent event, projectMKeycode keycode, projectMModifier modifier ) { switch( event ) { case PROJECTM_KEYDOWN: //default_key_handler(); switch (current_interface) { case MENU_INTERFACE: // menu_key_handler(this, event, keycode); break; case SHELL_INTERFACE: //shell_key_handler(); break; case EDITOR_INTERFACE: // editor_key_handler(event,keycode); break; case BROWSER_INTERFACE: // browser_key_handler(event,keycode,modifier); break; case DEFAULT_INTERFACE: default_key_handler(event,keycode); break; default: default_key_handler(event,keycode); break; } break; default: break; } } void projectM::default_key_handler( projectMEvent event, projectMKeycode keycode) { switch( event ) { case PROJECTM_KEYDOWN: switch (keycode) { case PROJECTM_K_HOME: if (renderer->showmenu) { // pageup only does something when the preset menu is active. selectPreset(0); // jump to top of presets. } break; case PROJECTM_K_END: if (renderer->showmenu) { // pageup only does something when the preset menu is active. selectPreset(m_presetLoader->size() - 1); // jump to bottom of presets. } break; case PROJECTM_K_PAGEUP: if (renderer->showmenu) { // pageup only does something when the preset menu is active. int upPreset = m_presetPos->lastIndex() - (renderer->textMenuPageSize / 2.0f); // jump up by page size / 2 if (upPreset < 0) // handle lower boundary upPreset = m_presetLoader->size() - 1; selectPreset(upPreset); // jump up menu half a page. } break; case PROJECTM_K_PAGEDOWN: if (renderer->showmenu) { // pagedown only does something when the preset menu is active. int downPreset = m_presetPos->lastIndex() + (renderer->textMenuPageSize / 2.0f); // jump down by page size / 2 if (downPreset >= (m_presetLoader->size() - 1)) // handle upper boundary downPreset = 0; selectPreset(downPreset); // jump down menu half a page. } break; case PROJECTM_K_UP: if (renderer->showmenu) { selectPrevious(true); } else { beatDetect->beatSensitivity += 0.25; if (beatDetect->beatSensitivity > 5.0) beatDetect->beatSensitivity = 5.0; renderer->setToastMessage("Beat Sensitivity: " + round_float(beatDetect->beatSensitivity)); } break; case PROJECTM_K_DOWN: if (renderer->showmenu) { selectNext(true); } else { beatDetect->beatSensitivity -= 0.25; if (beatDetect->beatSensitivity < 0) beatDetect->beatSensitivity = 0; renderer->setToastMessage("Beat Sensitivity: " + round_float(beatDetect->beatSensitivity)); } break; case PROJECTM_K_h: renderer->showhelp = !renderer->showhelp; renderer->showstats = false; renderer->showmenu = false; case PROJECTM_K_F1: renderer->showhelp = !renderer->showhelp; renderer->showstats = false; renderer->showmenu = false; break; case PROJECTM_K_y: this->setShuffleEnabled(!this->isShuffleEnabled()); if (this->isShuffleEnabled()) { renderer->setToastMessage("Shuffle Enabled"); } else { renderer->setToastMessage("Shuffle Disabled"); } break; case PROJECTM_K_F5: renderer->showfps = !renderer->showfps; // Initialize counters and reset frame count. renderer->lastTimeFPS = duration_cast<milliseconds>(system_clock::now().time_since_epoch()); renderer->currentTimeFPS = duration_cast<milliseconds>(system_clock::now().time_since_epoch()); renderer->totalframes = 0; // Hide preset name from screen and replace it with FPS counter. if (renderer->showfps) { renderer->showpreset = false; } break; case PROJECTM_K_F4: renderer->showstats = !renderer->showstats; if (renderer->showstats) { renderer->showhelp = false; renderer->showmenu = false; } break; case PROJECTM_K_F3: { renderer->showpreset = !renderer->showpreset; // Hide FPS from screen and replace it with preset name. if (renderer->showpreset) { renderer->showfps = false; } break; } case PROJECTM_K_F2: renderer->showtitle = !renderer->showtitle; break; #ifndef MACOS case PROJECTM_K_F9: #else case PROJECTM_K_F8: #endif renderer->studio = !renderer->studio; break; case PROJECTM_K_ESCAPE: { // exit( 1 ); break; } case PROJECTM_K_f: break; case PROJECTM_K_a: renderer->correction = !renderer->correction; break; case PROJECTM_K_b: break; case PROJECTM_K_H: case PROJECTM_K_m: renderer->showmenu = !renderer->showmenu; if (renderer->showmenu) { renderer->showhelp = false; renderer->showstats = false; populatePresetMenu(); } break; case PROJECTM_K_M: renderer->showmenu = !renderer->showmenu; if (renderer->showmenu) { renderer->showhelp=false; renderer->showstats=false; populatePresetMenu(); } break; case PROJECTM_K_n: selectNext(true); break; case PROJECTM_K_N: selectNext(false); break; case PROJECTM_K_r: selectRandom(true); break; case PROJECTM_K_R: selectRandom(false); break; case PROJECTM_K_p: selectPrevious(true); break; case PROJECTM_K_P: case PROJECTM_K_BACKSPACE: selectPrevious(false); break; case PROJECTM_K_l: setPresetLock(!isPresetLocked()); break; case PROJECTM_K_s: renderer->studio = !renderer->studio; case PROJECTM_K_i: break; case PROJECTM_K_z: break; case PROJECTM_K_0: // nWaveMode=0; break; case PROJECTM_K_6: // nWaveMode=6; break; case PROJECTM_K_7: // nWaveMode=7; break; case PROJECTM_K_t: break; case PROJECTM_K_EQUALS: case PROJECTM_K_PLUS: unsigned int index; if (selectedPresetIndex(index)) { const int oldRating = getPresetRating(index, HARD_CUT_RATING_TYPE); if (oldRating >= 6) break; const int rating = oldRating + 1; changePresetRating(index, rating, HARD_CUT_RATING_TYPE); } break; case PROJECTM_K_MINUS: if (selectedPresetIndex(index)) { const int oldRating = getPresetRating(index, HARD_CUT_RATING_TYPE); if (oldRating <= 1) break; const int rating = oldRating - 1; changePresetRating(index, rating, HARD_CUT_RATING_TYPE); } break; default: break; } default: break; } } <commit_msg>tweak beat sensitivity to be more sensitive / granular<commit_after>/** * projectM -- Milkdrop-esque visualisation SDK * Copyright (C)2003-2004 projectM Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * See 'LICENSE.txt' included within this release * */ #include <stdio.h> #include "Common.hpp" #include "fatal.h" #include "KeyHandler.hpp" #include "event.h" #include "BeatDetect.hpp" #include "PresetChooser.hpp" #include "Renderer.hpp" #include "projectM.hpp" #include <iostream> #include "TimeKeeper.hpp" class Preset; interface_t current_interface = DEFAULT_INTERFACE; void selectRandom(const bool hardCut); void selectNext(const bool hardCut); void selectPrevious(const bool hardCut); std::string round_float(float number) { std::string num_text = std::to_string(number); std::string rounded = num_text.substr(0, num_text.find(".")+3); return rounded; } void refreshConsole() { switch (current_interface) { case MENU_INTERFACE: // unimplemented break; case SHELL_INTERFACE: // unimplemented break; case EDITOR_INTERFACE: // unimplemented break; case DEFAULT_INTERFACE: break; case BROWSER_INTERFACE: // unimplemented break; default: break; } } void projectM::key_handler( projectMEvent event, projectMKeycode keycode, projectMModifier modifier ) { switch( event ) { case PROJECTM_KEYDOWN: //default_key_handler(); switch (current_interface) { case MENU_INTERFACE: // menu_key_handler(this, event, keycode); break; case SHELL_INTERFACE: //shell_key_handler(); break; case EDITOR_INTERFACE: // editor_key_handler(event,keycode); break; case BROWSER_INTERFACE: // browser_key_handler(event,keycode,modifier); break; case DEFAULT_INTERFACE: default_key_handler(event,keycode); break; default: default_key_handler(event,keycode); break; } break; default: break; } } void projectM::default_key_handler( projectMEvent event, projectMKeycode keycode) { switch( event ) { case PROJECTM_KEYDOWN: switch (keycode) { case PROJECTM_K_HOME: if (renderer->showmenu) { // pageup only does something when the preset menu is active. selectPreset(0); // jump to top of presets. } break; case PROJECTM_K_END: if (renderer->showmenu) { // pageup only does something when the preset menu is active. selectPreset(m_presetLoader->size() - 1); // jump to bottom of presets. } break; case PROJECTM_K_PAGEUP: if (renderer->showmenu) { // pageup only does something when the preset menu is active. int upPreset = m_presetPos->lastIndex() - (renderer->textMenuPageSize / 2.0f); // jump up by page size / 2 if (upPreset < 0) // handle lower boundary upPreset = m_presetLoader->size() - 1; selectPreset(upPreset); // jump up menu half a page. } break; case PROJECTM_K_PAGEDOWN: if (renderer->showmenu) { // pagedown only does something when the preset menu is active. int downPreset = m_presetPos->lastIndex() + (renderer->textMenuPageSize / 2.0f); // jump down by page size / 2 if (downPreset >= (m_presetLoader->size() - 1)) // handle upper boundary downPreset = 0; selectPreset(downPreset); // jump down menu half a page. } break; case PROJECTM_K_UP: if (renderer->showmenu) { selectPrevious(true); } else { beatDetect->beatSensitivity += 0.01; if (beatDetect->beatSensitivity > 5.0) beatDetect->beatSensitivity = 5.0; renderer->setToastMessage("Beat Sensitivity: " + round_float(beatDetect->beatSensitivity)); } break; case PROJECTM_K_DOWN: if (renderer->showmenu) { selectNext(true); } else { beatDetect->beatSensitivity -= 0.01; if (beatDetect->beatSensitivity < 0) beatDetect->beatSensitivity = 0; renderer->setToastMessage("Beat Sensitivity: " + round_float(beatDetect->beatSensitivity)); } break; case PROJECTM_K_h: renderer->showhelp = !renderer->showhelp; renderer->showstats = false; renderer->showmenu = false; case PROJECTM_K_F1: renderer->showhelp = !renderer->showhelp; renderer->showstats = false; renderer->showmenu = false; break; case PROJECTM_K_y: this->setShuffleEnabled(!this->isShuffleEnabled()); if (this->isShuffleEnabled()) { renderer->setToastMessage("Shuffle Enabled"); } else { renderer->setToastMessage("Shuffle Disabled"); } break; case PROJECTM_K_F5: renderer->showfps = !renderer->showfps; // Initialize counters and reset frame count. renderer->lastTimeFPS = duration_cast<milliseconds>(system_clock::now().time_since_epoch()); renderer->currentTimeFPS = duration_cast<milliseconds>(system_clock::now().time_since_epoch()); renderer->totalframes = 0; // Hide preset name from screen and replace it with FPS counter. if (renderer->showfps) { renderer->showpreset = false; } break; case PROJECTM_K_F4: renderer->showstats = !renderer->showstats; if (renderer->showstats) { renderer->showhelp = false; renderer->showmenu = false; } break; case PROJECTM_K_F3: { renderer->showpreset = !renderer->showpreset; // Hide FPS from screen and replace it with preset name. if (renderer->showpreset) { renderer->showfps = false; } break; } case PROJECTM_K_F2: renderer->showtitle = !renderer->showtitle; break; #ifndef MACOS case PROJECTM_K_F9: #else case PROJECTM_K_F8: #endif renderer->studio = !renderer->studio; break; case PROJECTM_K_ESCAPE: { // exit( 1 ); break; } case PROJECTM_K_f: break; case PROJECTM_K_a: renderer->correction = !renderer->correction; break; case PROJECTM_K_b: break; case PROJECTM_K_H: case PROJECTM_K_m: renderer->showmenu = !renderer->showmenu; if (renderer->showmenu) { renderer->showhelp = false; renderer->showstats = false; populatePresetMenu(); } break; case PROJECTM_K_M: renderer->showmenu = !renderer->showmenu; if (renderer->showmenu) { renderer->showhelp=false; renderer->showstats=false; populatePresetMenu(); } break; case PROJECTM_K_n: selectNext(true); break; case PROJECTM_K_N: selectNext(false); break; case PROJECTM_K_r: selectRandom(true); break; case PROJECTM_K_R: selectRandom(false); break; case PROJECTM_K_p: selectPrevious(true); break; case PROJECTM_K_P: case PROJECTM_K_BACKSPACE: selectPrevious(false); break; case PROJECTM_K_l: setPresetLock(!isPresetLocked()); break; case PROJECTM_K_s: renderer->studio = !renderer->studio; case PROJECTM_K_i: break; case PROJECTM_K_z: break; case PROJECTM_K_0: // nWaveMode=0; break; case PROJECTM_K_6: // nWaveMode=6; break; case PROJECTM_K_7: // nWaveMode=7; break; case PROJECTM_K_t: break; case PROJECTM_K_EQUALS: case PROJECTM_K_PLUS: unsigned int index; if (selectedPresetIndex(index)) { const int oldRating = getPresetRating(index, HARD_CUT_RATING_TYPE); if (oldRating >= 6) break; const int rating = oldRating + 1; changePresetRating(index, rating, HARD_CUT_RATING_TYPE); } break; case PROJECTM_K_MINUS: if (selectedPresetIndex(index)) { const int oldRating = getPresetRating(index, HARD_CUT_RATING_TYPE); if (oldRating <= 1) break; const int rating = oldRating - 1; changePresetRating(index, rating, HARD_CUT_RATING_TYPE); } break; default: break; } default: break; } } <|endoftext|>
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/tensor_function.h> #include <vespa/eval/eval/test/eval_fixture.h> #include <vespa/eval/eval/test/gen_spec.h> #include <vespa/eval/instruction/join_with_number_function.h> #include <vespa/vespalib/util/stringfmt.h> using namespace vespalib; using namespace vespalib::eval; using namespace vespalib::eval::test; using namespace vespalib::eval::tensor_function; using vespalib::make_string_short::fmt; using Primary = JoinWithNumberFunction::Primary; namespace vespalib::eval { std::ostream &operator<<(std::ostream &os, Primary primary) { switch(primary) { case Primary::LHS: return os << "LHS"; case Primary::RHS: return os << "RHS"; } abort(); } } struct FunInfo { using LookFor = JoinWithNumberFunction; Primary primary; bool inplace; void verify(const EvalFixture &fixture, const LookFor &fun) const { EXPECT_TRUE(fun.result_is_mutable()); EXPECT_EQUAL(fun.primary(), primary); EXPECT_EQUAL(fun.inplace(), inplace); if (inplace) { size_t idx = (fun.primary() == Primary::LHS) ? 0 : 1; EXPECT_EQUAL(fixture.result_value().cells().data, fixture.param_value(idx).cells().data); } } }; void verify_optimized(const vespalib::string &expr, Primary primary, bool inplace) { // fprintf(stderr, "%s\n", expr.c_str()); const auto stable_types = CellTypeSpace({CellType::FLOAT, CellType::DOUBLE}, 2); FunInfo stable_details{primary, inplace}; TEST_DO(EvalFixture::verify<FunInfo>(expr, {stable_details}, stable_types)); } void verify_not_optimized(const vespalib::string &expr) { // fprintf(stderr, "%s\n", expr.c_str()); CellTypeSpace all_types(CellTypeUtils::list_types(), 2); TEST_DO(EvalFixture::verify<FunInfo>(expr, {}, all_types)); } TEST("require that dense number join can be optimized") { TEST_DO(verify_optimized("x3y5+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3y5", Primary::RHS, false)); TEST_DO(verify_optimized("x3y5*reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)*x3y5", Primary::RHS, false)); } TEST("require that dense number join can be inplace") { TEST_DO(verify_optimized("@x3y5*reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)*@x3y5", Primary::RHS, true)); TEST_DO(verify_optimized("@x3y5+reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)+@x3y5", Primary::RHS, true)); } TEST("require that asymmetric operations work") { TEST_DO(verify_optimized("x3y5/reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)/x3y5", Primary::RHS, false)); TEST_DO(verify_optimized("x3y5-reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)-x3y5", Primary::RHS, false)); } TEST("require that sparse number join can be optimized") { TEST_DO(verify_optimized("x3_1z2_1+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3_1z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1z2_1<reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)<x3_1z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1z2_1+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3_1z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1z2_1<reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)<x3_1z2_1", Primary::RHS, false)); } TEST("require that sparse number join can be inplace") { TEST_DO(verify_optimized("@x3_1z2_1+reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)+@x3_1z2_1", Primary::RHS, true)); TEST_DO(verify_optimized("@x3_1z2_1<reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)<@x3_1z2_1", Primary::RHS, true)); } TEST("require that mixed number join can be optimized") { TEST_DO(verify_optimized("x3_1y5z2_1+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3_1y5z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1y5z2_1<reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)<x3_1y5z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1y5z2_1+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3_1y5z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1y5z2_1<reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)<x3_1y5z2_1", Primary::RHS, false)); } TEST("require that mixed number join can be inplace") { TEST_DO(verify_optimized("@x3_1y5z2_1+reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)+@x3_1y5z2_1", Primary::RHS, true)); TEST_DO(verify_optimized("@x3_1y5z2_1<reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)<@x3_1y5z2_1", Primary::RHS, true)); } TEST("require that inappropriate cases are not optimized") { for (vespalib::string lhs: {"y5", "x3_1z2_1", "x3_1y5z2_1"}) { for (vespalib::string rhs: {"y5", "x3_1z2_1", "x3_1y5z2_1"}) { auto expr = fmt("%s$1*%s$2", lhs.c_str(), rhs.c_str()); verify_not_optimized(expr); } verify_optimized(fmt("reduce(v3,sum)*%s", lhs.c_str()), Primary::RHS, false); verify_optimized(fmt("%s*reduce(v3,sum)", lhs.c_str()), Primary::LHS, false); } // two scalars -> not optimized verify_not_optimized("reduce(v3,sum)*reduce(k4,sum)"); } TEST_MAIN() { TEST_RUN_ALL(); } <commit_msg>test unstable cell types for JoinWithNumberFunction<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/tensor_function.h> #include <vespa/eval/eval/test/eval_fixture.h> #include <vespa/eval/eval/test/gen_spec.h> #include <vespa/eval/instruction/join_with_number_function.h> #include <vespa/vespalib/util/stringfmt.h> using namespace vespalib; using namespace vespalib::eval; using namespace vespalib::eval::test; using namespace vespalib::eval::tensor_function; using vespalib::make_string_short::fmt; using Primary = JoinWithNumberFunction::Primary; namespace vespalib::eval { std::ostream &operator<<(std::ostream &os, Primary primary) { switch(primary) { case Primary::LHS: return os << "LHS"; case Primary::RHS: return os << "RHS"; } abort(); } } struct FunInfo { using LookFor = JoinWithNumberFunction; Primary primary; bool inplace; void verify(const EvalFixture &fixture, const LookFor &fun) const { EXPECT_TRUE(fun.result_is_mutable()); EXPECT_EQUAL(fun.primary(), primary); EXPECT_EQUAL(fun.inplace(), inplace); if (inplace) { size_t idx = (fun.primary() == Primary::LHS) ? 0 : 1; EXPECT_EQUAL(fixture.result_value().cells().data, fixture.param_value(idx).cells().data); } } }; void verify_optimized(const vespalib::string &expr, Primary primary, bool inplace) { // fprintf(stderr, "%s\n", expr.c_str()); const auto stable_types = CellTypeSpace({CellType::FLOAT, CellType::DOUBLE}, 2); FunInfo stable_details{primary, inplace}; TEST_DO(EvalFixture::verify<FunInfo>(expr, {stable_details}, stable_types)); const auto unstable_types = CellTypeSpace({CellType::BFLOAT16, CellType::INT8}, 2); TEST_DO(EvalFixture::verify<FunInfo>(expr, {}, unstable_types)); } void verify_not_optimized(const vespalib::string &expr) { // fprintf(stderr, "%s\n", expr.c_str()); CellTypeSpace all_types(CellTypeUtils::list_types(), 2); TEST_DO(EvalFixture::verify<FunInfo>(expr, {}, all_types)); } TEST("require that dense number join can be optimized") { TEST_DO(verify_optimized("x3y5+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3y5", Primary::RHS, false)); TEST_DO(verify_optimized("x3y5*reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)*x3y5", Primary::RHS, false)); } TEST("require that dense number join can be inplace") { TEST_DO(verify_optimized("@x3y5*reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)*@x3y5", Primary::RHS, true)); TEST_DO(verify_optimized("@x3y5+reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)+@x3y5", Primary::RHS, true)); } TEST("require that asymmetric operations work") { TEST_DO(verify_optimized("x3y5/reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)/x3y5", Primary::RHS, false)); TEST_DO(verify_optimized("x3y5-reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)-x3y5", Primary::RHS, false)); } TEST("require that sparse number join can be optimized") { TEST_DO(verify_optimized("x3_1z2_1+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3_1z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1z2_1<reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)<x3_1z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1z2_1+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3_1z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1z2_1<reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)<x3_1z2_1", Primary::RHS, false)); } TEST("require that sparse number join can be inplace") { TEST_DO(verify_optimized("@x3_1z2_1+reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)+@x3_1z2_1", Primary::RHS, true)); TEST_DO(verify_optimized("@x3_1z2_1<reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)<@x3_1z2_1", Primary::RHS, true)); } TEST("require that mixed number join can be optimized") { TEST_DO(verify_optimized("x3_1y5z2_1+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3_1y5z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1y5z2_1<reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)<x3_1y5z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1y5z2_1+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3_1y5z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1y5z2_1<reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)<x3_1y5z2_1", Primary::RHS, false)); } TEST("require that mixed number join can be inplace") { TEST_DO(verify_optimized("@x3_1y5z2_1+reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)+@x3_1y5z2_1", Primary::RHS, true)); TEST_DO(verify_optimized("@x3_1y5z2_1<reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)<@x3_1y5z2_1", Primary::RHS, true)); } TEST("require that inappropriate cases are not optimized") { for (vespalib::string lhs: {"y5", "x3_1z2_1", "x3_1y5z2_1"}) { for (vespalib::string rhs: {"y5", "x3_1z2_1", "x3_1y5z2_1"}) { auto expr = fmt("%s$1*%s$2", lhs.c_str(), rhs.c_str()); verify_not_optimized(expr); } verify_optimized(fmt("reduce(v3,sum)*%s", lhs.c_str()), Primary::RHS, false); verify_optimized(fmt("%s*reduce(v3,sum)", lhs.c_str()), Primary::LHS, false); } // two scalars -> not optimized verify_not_optimized("reduce(v3,sum)*reduce(k4,sum)"); } TEST_MAIN() { TEST_RUN_ALL(); } <|endoftext|>
<commit_before>/******************************************************************** * livegrep -- chunk.cc * Copyright (c) 2011-2013 Nelson Elhage * * This program is free software. You may use, redistribute, and/or * modify it under the terms listed in the COPYING file. ********************************************************************/ #include "chunk.h" #include "radix_sort.h" #include "radix_sorter.h" #include <re2/re2.h> #include <gflags/gflags.h> #include <limits> using re2::StringPiece; DECLARE_bool(index); void chunk::add_chunk_file(indexed_file *sf, const StringPiece& line) { int l = (unsigned char*)line.data() - data; int r = l + line.size(); chunk_file *f = NULL; int min_dist = numeric_limits<int>::max(), dist; for (vector<chunk_file>::iterator it = cur_file.begin(); it != cur_file.end(); it ++) { if (l <= it->left) dist = max(0, it->left - r); else if (r >= it->right) dist = max(0, l - it->right); else dist = 0; assert(dist == 0 || r < it->left || l > it->right); if (dist < min_dist) { min_dist = dist; f = &(*it); } } if (f && min_dist < kMaxGap) { f->expand(l, r); return; } chunk_files++; cur_file.push_back(chunk_file()); chunk_file& cf = cur_file.back(); cf.files.push_front(sf); cf.left = l; cf.right = r; } void chunk::finish_file() { int right = -1; sort(cur_file.begin(), cur_file.end()); for (vector<chunk_file>::iterator it = cur_file.begin(); it != cur_file.end(); it ++) { assert(right < it->left); right = max(right, it->right); } files.insert(files.end(), cur_file.begin(), cur_file.end()); cur_file.clear(); } int chunk::chunk_files = 0; void radix_sorter::sort(uint32_t *l, uint32_t *r) { cmp_suffix cmp(*this); indexer idx(*this); msd_radix_sort(l, r, 0, idx, cmp); assert(is_sorted(l, r, cmp)); } void chunk::finalize() { if (FLAGS_index) { for (int i = 0; i < size; i++) suffixes[i] = i; radix_sorter sorter(data, size); sorter.sort(suffixes, suffixes + size); } } void chunk::finalize_files() { sort(files.begin(), files.end()); vector<chunk_file>::iterator out, in; out = in = files.begin(); while (in != files.end()) { *out = *in; ++in; while (in != files.end() && out->left == in->left && out->right == in->right) { out->files.push_back(in->files.front()); ++in; } ++out; } files.resize(out - files.begin()); build_tree(); } void chunk::build_tree() { assert(is_sorted(files.begin(), files.end())); cf_root = build_tree(0, files.size()); } chunk_file_node *chunk::build_tree(int left, int right) { if (right == left) return 0; int mid = (left + right) / 2; chunk_file_node *node = new chunk_file_node; node->chunk = &files[mid]; node->left = build_tree(left, mid); node->right = build_tree(mid + 1, right); node->right_limit = node->chunk->right; if (node->left && node->left->right_limit > node->right_limit) node->right_limit = node->left->right_limit; if (node->right && node->right->right_limit > node->right_limit) node->right_limit = node->right->right_limit; assert(!node->left || *(node->left->chunk) < *(node->chunk)); assert(!node->right || *(node->chunk) < *(node->right->chunk)); return node; } <commit_msg>Put an expensive assertion behind an ifdef<commit_after>/******************************************************************** * livegrep -- chunk.cc * Copyright (c) 2011-2013 Nelson Elhage * * This program is free software. You may use, redistribute, and/or * modify it under the terms listed in the COPYING file. ********************************************************************/ #include "chunk.h" #include "radix_sort.h" #include "radix_sorter.h" #include <re2/re2.h> #include <gflags/gflags.h> #include <limits> using re2::StringPiece; DECLARE_bool(index); void chunk::add_chunk_file(indexed_file *sf, const StringPiece& line) { int l = (unsigned char*)line.data() - data; int r = l + line.size(); chunk_file *f = NULL; int min_dist = numeric_limits<int>::max(), dist; for (vector<chunk_file>::iterator it = cur_file.begin(); it != cur_file.end(); it ++) { if (l <= it->left) dist = max(0, it->left - r); else if (r >= it->right) dist = max(0, l - it->right); else dist = 0; assert(dist == 0 || r < it->left || l > it->right); if (dist < min_dist) { min_dist = dist; f = &(*it); } } if (f && min_dist < kMaxGap) { f->expand(l, r); return; } chunk_files++; cur_file.push_back(chunk_file()); chunk_file& cf = cur_file.back(); cf.files.push_front(sf); cf.left = l; cf.right = r; } void chunk::finish_file() { int right = -1; sort(cur_file.begin(), cur_file.end()); for (vector<chunk_file>::iterator it = cur_file.begin(); it != cur_file.end(); it ++) { assert(right < it->left); right = max(right, it->right); } files.insert(files.end(), cur_file.begin(), cur_file.end()); cur_file.clear(); } int chunk::chunk_files = 0; void radix_sorter::sort(uint32_t *l, uint32_t *r) { cmp_suffix cmp(*this); indexer idx(*this); msd_radix_sort(l, r, 0, idx, cmp); #ifdef DEBUG_RADIX_SORT assert(is_sorted(l, r, cmp)); #endif } void chunk::finalize() { if (FLAGS_index) { for (int i = 0; i < size; i++) suffixes[i] = i; radix_sorter sorter(data, size); sorter.sort(suffixes, suffixes + size); } } void chunk::finalize_files() { sort(files.begin(), files.end()); vector<chunk_file>::iterator out, in; out = in = files.begin(); while (in != files.end()) { *out = *in; ++in; while (in != files.end() && out->left == in->left && out->right == in->right) { out->files.push_back(in->files.front()); ++in; } ++out; } files.resize(out - files.begin()); build_tree(); } void chunk::build_tree() { assert(is_sorted(files.begin(), files.end())); cf_root = build_tree(0, files.size()); } chunk_file_node *chunk::build_tree(int left, int right) { if (right == left) return 0; int mid = (left + right) / 2; chunk_file_node *node = new chunk_file_node; node->chunk = &files[mid]; node->left = build_tree(left, mid); node->right = build_tree(mid + 1, right); node->right_limit = node->chunk->right; if (node->left && node->left->right_limit > node->right_limit) node->right_limit = node->left->right_limit; if (node->right && node->right->right_limit > node->right_limit) node->right_limit = node->right->right_limit; assert(!node->left || *(node->left->chunk) < *(node->chunk)); assert(!node->right || *(node->chunk) < *(node->right->chunk)); return node; } <|endoftext|>
<commit_before>/******************************************************************************* * ALMA - Atacama Large Millimeter Array * Copyright (c) ESO - European Southern Observatory, 2011 * (in the framework of the ALMA collaboration). * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *******************************************************************************/ #include "Timestamp.h" #include <sys/time.h> #include <sstream> #include <iostream> #include <stdio.h> using std::stringstream; using std::string; using acsalarm::Timestamp; /** * Default no-args constructor, creates an instance with the time at instantiation. */ Timestamp::Timestamp() { // TODO later: portability issues with gettimeofday? // i.e. will this work on non-unix platforms? do we care? timeval tim; gettimeofday(&tim, NULL); setSeconds(tim.tv_sec); setMicroSeconds(tim.tv_usec); } /** * Constructor to instantiate and configure a Timestamp with a time. */ Timestamp::Timestamp(long secs, long microSecs) { setSeconds(secs); setMicroSeconds(microSecs); } /* * Copy constructor */ Timestamp::Timestamp(const Timestamp & ts) { seconds = ts.seconds; microSeconds = ts.microSeconds; } /** * Destructor. */ Timestamp::~Timestamp() { } /* * Assignment operator. */ Timestamp & Timestamp::operator=(const Timestamp & rhs) { setSeconds(rhs.seconds); setMicroSeconds(rhs.microSeconds); return *this; } /* * Equality operator. */ int Timestamp::operator==(const Timestamp &rhs) const { int retVal = 1; if(rhs.seconds != seconds || rhs.microSeconds != microSeconds) { retVal = 0; } return retVal; } std::string Timestamp::toISOFormat() const { struct timeval tval; tval.tv_sec=getSeconds(); tval.tv_usec=getMicroSeconds(); struct tm* temptm = gmtime(&tval.tv_sec); char tmbuf[64], buf[64]; strftime(tmbuf, sizeof tmbuf, "%FT%H:%M:%S", temptm); snprintf(buf, sizeof buf, "%s.%03ld", tmbuf, tval.tv_usec/1000); std::string ret=buf; return ret; } <commit_msg>ICT-4351: Changed method gmtime to its thread-safe version gmtime_r<commit_after>/******************************************************************************* * ALMA - Atacama Large Millimeter Array * Copyright (c) ESO - European Southern Observatory, 2011 * (in the framework of the ALMA collaboration). * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *******************************************************************************/ #include "Timestamp.h" #include <sys/time.h> #include <sstream> #include <iostream> #include <stdio.h> using std::stringstream; using std::string; using acsalarm::Timestamp; /** * Default no-args constructor, creates an instance with the time at instantiation. */ Timestamp::Timestamp() { // TODO later: portability issues with gettimeofday? // i.e. will this work on non-unix platforms? do we care? timeval tim; gettimeofday(&tim, NULL); setSeconds(tim.tv_sec); setMicroSeconds(tim.tv_usec); } /** * Constructor to instantiate and configure a Timestamp with a time. */ Timestamp::Timestamp(long secs, long microSecs) { setSeconds(secs); setMicroSeconds(microSecs); } /* * Copy constructor */ Timestamp::Timestamp(const Timestamp & ts) { seconds = ts.seconds; microSeconds = ts.microSeconds; } /** * Destructor. */ Timestamp::~Timestamp() { } /* * Assignment operator. */ Timestamp & Timestamp::operator=(const Timestamp & rhs) { setSeconds(rhs.seconds); setMicroSeconds(rhs.microSeconds); return *this; } /* * Equality operator. */ int Timestamp::operator==(const Timestamp &rhs) const { int retVal = 1; if(rhs.seconds != seconds || rhs.microSeconds != microSeconds) { retVal = 0; } return retVal; } std::string Timestamp::toISOFormat() const { struct timeval tval; tval.tv_sec=getSeconds(); tval.tv_usec=getMicroSeconds(); struct tm temptm = {0}; gmtime_r(&tval.tv_sec,&temptm); char tmbuf[64], buf[64]; strftime(tmbuf, sizeof tmbuf, "%FT%H:%M:%S", &temptm); snprintf(buf, sizeof buf, "%s.%03ld", tmbuf, tval.tv_usec/1000); std::string ret=buf; return ret; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Linguist of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "translator.h" #include "profileevaluator.h" #ifndef QT_BOOTSTRAPPED #include <QtCore/QCoreApplication> #include <QtCore/QTranslator> #endif #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QFileInfo> #include <QtCore/QRegExp> #include <QtCore/QString> #include <QtCore/QStringList> #include <QtCore/QTextStream> #include <iostream> QT_USE_NAMESPACE #ifdef QT_BOOTSTRAPPED static void initBinaryDir( #ifndef Q_OS_WIN const char *argv0 #endif ); struct LR { static inline QString tr(const char *sourceText, const char *comment = 0) { return QCoreApplication::translate("LRelease", sourceText, comment); } }; #else class LR { Q_DECLARE_TR_FUNCTIONS(LRelease) }; #endif static void printOut(const QString & out) { QTextStream stream(stdout); stream << out; } static void printUsage() { printOut(LR::tr( "Usage:\n" " lrelease [options] project-file\n" " lrelease [options] ts-files [-qm qm-file]\n\n" "lrelease is part of Qt's Linguist tool chain. It can be used as a\n" "stand-alone tool to convert XML-based translations files in the TS\n" "format into the 'compiled' QM format used by QTranslator objects.\n\n" "Options:\n" " -help Display this information and exit\n" " -idbased\n" " Use IDs instead of source strings for message keying\n" " -compress\n" " Compress the QM files\n" " -nounfinished\n" " Do not include unfinished translations\n" " -removeidentical\n" " If the translated text is the same as\n" " the source text, do not include the message\n" " -markuntranslated <prefix>\n" " If a message has no real translation, use the source text\n" " prefixed with the given string instead\n" " -silent\n" " Do not explain what is being done\n" " -version\n" " Display the version of lrelease and exit\n" )); } static bool loadTsFile(Translator &tor, const QString &tsFileName, bool /* verbose */) { ConversionData cd; bool ok = tor.load(tsFileName, cd, QLatin1String("auto")); if (!ok) { std::cerr << qPrintable(LR::tr("lrelease error: %1").arg(cd.error())); } else { if (!cd.errors().isEmpty()) printOut(cd.error()); } cd.clearErrors(); return ok; } static bool releaseTranslator(Translator &tor, const QString &qmFileName, ConversionData &cd, bool removeIdentical) { tor.reportDuplicates(tor.resolveDuplicates(), qmFileName, cd.isVerbose()); if (cd.isVerbose()) printOut(LR::tr("Updating '%1'...\n").arg(qmFileName)); if (removeIdentical) { if (cd.isVerbose()) printOut(LR::tr("Removing translations equal to source text in '%1'...\n").arg(qmFileName)); tor.stripIdenticalSourceTranslations(); } QFile file(qmFileName); if (!file.open(QIODevice::WriteOnly)) { std::cerr << qPrintable(LR::tr("lrelease error: cannot create '%1': %2\n") .arg(qmFileName, file.errorString())); return false; } tor.normalizeTranslations(cd); bool ok = tor.release(&file, cd); file.close(); if (!ok) { std::cerr << qPrintable(LR::tr("lrelease error: cannot save '%1': %2") .arg(qmFileName, cd.error())); } else if (!cd.errors().isEmpty()) { printOut(cd.error()); } cd.clearErrors(); return ok; } static bool releaseTsFile(const QString& tsFileName, ConversionData &cd, bool removeIdentical) { Translator tor; if (!loadTsFile(tor, tsFileName, cd.isVerbose())) return false; QString qmFileName = tsFileName; foreach (const Translator::FileFormat &fmt, Translator::registeredFileFormats()) { if (qmFileName.endsWith(QLatin1Char('.') + fmt.extension)) { qmFileName.chop(fmt.extension.length() + 1); break; } } qmFileName += QLatin1String(".qm"); return releaseTranslator(tor, qmFileName, cd, removeIdentical); } int main(int argc, char **argv) { #ifdef QT_BOOTSTRAPPED initBinaryDir( #ifndef Q_OS_WIN argv[0] #endif ); #else QCoreApplication app(argc, argv); #ifndef Q_OS_WIN32 QTranslator translator; QTranslator qtTranslator; QString sysLocale = QLocale::system().name(); QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath); if (translator.load(QLatin1String("linguist_") + sysLocale, resourceDir) && qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir)) { app.installTranslator(&translator); app.installTranslator(&qtTranslator); } #endif // Q_OS_WIN32 #endif // QT_BOOTSTRAPPED ConversionData cd; cd.m_verbose = true; // the default is true starting with Qt 4.2 bool removeIdentical = false; Translator tor; QStringList inputFiles; QString outputFile; for (int i = 1; i < argc; ++i) { if (!strcmp(argv[i], "-compress")) { cd.m_saveMode = SaveStripped; continue; } else if (!strcmp(argv[i], "-idbased")) { cd.m_idBased = true; continue; } else if (!strcmp(argv[i], "-nocompress")) { cd.m_saveMode = SaveEverything; continue; } else if (!strcmp(argv[i], "-removeidentical")) { removeIdentical = true; continue; } else if (!strcmp(argv[i], "-nounfinished")) { cd.m_ignoreUnfinished = true; continue; } else if (!strcmp(argv[i], "-markuntranslated")) { if (i == argc - 1) { printUsage(); return 1; } cd.m_unTrPrefix = QString::fromLocal8Bit(argv[++i]); } else if (!strcmp(argv[i], "-silent")) { cd.m_verbose = false; continue; } else if (!strcmp(argv[i], "-verbose")) { cd.m_verbose = true; continue; } else if (!strcmp(argv[i], "-version")) { printOut(LR::tr("lrelease version %1\n").arg(QLatin1String(QT_VERSION_STR))); return 0; } else if (!strcmp(argv[i], "-qm")) { if (i == argc - 1) { printUsage(); return 1; } outputFile = QString::fromLocal8Bit(argv[++i]); } else if (!strcmp(argv[i], "-help")) { printUsage(); return 0; } else if (argv[i][0] == '-') { printUsage(); return 1; } else { inputFiles << QString::fromLocal8Bit(argv[i]); } } if (inputFiles.isEmpty()) { printUsage(); return 1; } foreach (const QString &inputFile, inputFiles) { if (inputFile.endsWith(QLatin1String(".pro"), Qt::CaseInsensitive) || inputFile.endsWith(QLatin1String(".pri"), Qt::CaseInsensitive)) { QFileInfo fi(inputFile); ProFile pro(fi.absoluteFilePath()); ProFileEvaluator visitor; visitor.setVerbose(cd.isVerbose()); if (!visitor.queryProFile(&pro)) { std::cerr << qPrintable(LR::tr( "lrelease error: cannot read project file '%1'.\n") .arg(inputFile)); continue; } if (!visitor.accept(&pro)) { std::cerr << qPrintable(LR::tr( "lrelease error: cannot process project file '%1'.\n") .arg(inputFile)); continue; } QStringList translations = visitor.values(QLatin1String("TRANSLATIONS")); if (translations.isEmpty()) { std::cerr << qPrintable(LR::tr( "lrelease warning: Met no 'TRANSLATIONS' entry in project file '%1'\n") .arg(inputFile)); } else { QDir proDir(fi.absolutePath()); foreach (const QString &trans, translations) if (!releaseTsFile(QFileInfo(proDir, trans).filePath(), cd, removeIdentical)) return 1; } } else { if (outputFile.isEmpty()) { if (!releaseTsFile(inputFile, cd, removeIdentical)) return 1; } else { if (!loadTsFile(tor, inputFile, cd.isVerbose())) return 1; } } } if (!outputFile.isEmpty()) return releaseTranslator(tor, outputFile, cd, removeIdentical) ? 0 : 1; return 0; } #ifdef QT_BOOTSTRAPPED #ifdef Q_OS_WIN # include <windows.h> #endif static QString binDir; static void initBinaryDir( #ifndef Q_OS_WIN const char *_argv0 #endif ) { #ifdef Q_OS_WIN wchar_t module_name[MAX_PATH]; GetModuleFileName(0, module_name, MAX_PATH); QFileInfo filePath = QString::fromWCharArray(module_name); binDir = filePath.filePath(); #else QString argv0 = QFile::decodeName(QByteArray(_argv0)); QString absPath; if (!argv0.isEmpty() && argv0.at(0) == QLatin1Char('/')) { /* If argv0 starts with a slash, it is already an absolute file path. */ absPath = argv0; } else if (argv0.contains(QLatin1Char('/'))) { /* If argv0 contains one or more slashes, it is a file path relative to the current directory. */ absPath = QDir::current().absoluteFilePath(argv0); } else { /* Otherwise, the file path has to be determined using the PATH environment variable. */ QByteArray pEnv = qgetenv("PATH"); QDir currentDir = QDir::current(); QStringList paths = QString::fromLocal8Bit(pEnv.constData()).split(QLatin1String(":")); for (QStringList::const_iterator p = paths.constBegin(); p != paths.constEnd(); ++p) { if ((*p).isEmpty()) continue; QString candidate = currentDir.absoluteFilePath(*p + QLatin1Char('/') + argv0); QFileInfo candidate_fi(candidate); if (candidate_fi.exists() && !candidate_fi.isDir()) { binDir = candidate_fi.canonicalPath(); return; } } return; } QFileInfo fi(absPath); if (fi.exists()) binDir = fi.canonicalPath(); #endif } QT_BEGIN_NAMESPACE // The name is hard-coded in QLibraryInfo QString qmake_libraryInfoFile() { if (binDir.isEmpty()) return QString(); return QDir(binDir).filePath(QString::fromLatin1("qt.conf")); } QT_END_NAMESPACE #endif // QT_BOOTSTRAPPED <commit_msg>Added missing header to lrelease.<commit_after>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Linguist of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "translator.h" #include "profileevaluator.h" #ifndef QT_BOOTSTRAPPED #include <QtCore/QCoreApplication> #include <QtCore/QTranslator> #endif #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QFileInfo> #include <QtCore/QRegExp> #include <QtCore/QString> #include <QtCore/QStringList> #include <QtCore/QTextStream> #include <QtCore/QLibraryInfo> #include <iostream> QT_USE_NAMESPACE #ifdef QT_BOOTSTRAPPED static void initBinaryDir( #ifndef Q_OS_WIN const char *argv0 #endif ); struct LR { static inline QString tr(const char *sourceText, const char *comment = 0) { return QCoreApplication::translate("LRelease", sourceText, comment); } }; #else class LR { Q_DECLARE_TR_FUNCTIONS(LRelease) }; #endif static void printOut(const QString & out) { QTextStream stream(stdout); stream << out; } static void printUsage() { printOut(LR::tr( "Usage:\n" " lrelease [options] project-file\n" " lrelease [options] ts-files [-qm qm-file]\n\n" "lrelease is part of Qt's Linguist tool chain. It can be used as a\n" "stand-alone tool to convert XML-based translations files in the TS\n" "format into the 'compiled' QM format used by QTranslator objects.\n\n" "Options:\n" " -help Display this information and exit\n" " -idbased\n" " Use IDs instead of source strings for message keying\n" " -compress\n" " Compress the QM files\n" " -nounfinished\n" " Do not include unfinished translations\n" " -removeidentical\n" " If the translated text is the same as\n" " the source text, do not include the message\n" " -markuntranslated <prefix>\n" " If a message has no real translation, use the source text\n" " prefixed with the given string instead\n" " -silent\n" " Do not explain what is being done\n" " -version\n" " Display the version of lrelease and exit\n" )); } static bool loadTsFile(Translator &tor, const QString &tsFileName, bool /* verbose */) { ConversionData cd; bool ok = tor.load(tsFileName, cd, QLatin1String("auto")); if (!ok) { std::cerr << qPrintable(LR::tr("lrelease error: %1").arg(cd.error())); } else { if (!cd.errors().isEmpty()) printOut(cd.error()); } cd.clearErrors(); return ok; } static bool releaseTranslator(Translator &tor, const QString &qmFileName, ConversionData &cd, bool removeIdentical) { tor.reportDuplicates(tor.resolveDuplicates(), qmFileName, cd.isVerbose()); if (cd.isVerbose()) printOut(LR::tr("Updating '%1'...\n").arg(qmFileName)); if (removeIdentical) { if (cd.isVerbose()) printOut(LR::tr("Removing translations equal to source text in '%1'...\n").arg(qmFileName)); tor.stripIdenticalSourceTranslations(); } QFile file(qmFileName); if (!file.open(QIODevice::WriteOnly)) { std::cerr << qPrintable(LR::tr("lrelease error: cannot create '%1': %2\n") .arg(qmFileName, file.errorString())); return false; } tor.normalizeTranslations(cd); bool ok = tor.release(&file, cd); file.close(); if (!ok) { std::cerr << qPrintable(LR::tr("lrelease error: cannot save '%1': %2") .arg(qmFileName, cd.error())); } else if (!cd.errors().isEmpty()) { printOut(cd.error()); } cd.clearErrors(); return ok; } static bool releaseTsFile(const QString& tsFileName, ConversionData &cd, bool removeIdentical) { Translator tor; if (!loadTsFile(tor, tsFileName, cd.isVerbose())) return false; QString qmFileName = tsFileName; foreach (const Translator::FileFormat &fmt, Translator::registeredFileFormats()) { if (qmFileName.endsWith(QLatin1Char('.') + fmt.extension)) { qmFileName.chop(fmt.extension.length() + 1); break; } } qmFileName += QLatin1String(".qm"); return releaseTranslator(tor, qmFileName, cd, removeIdentical); } int main(int argc, char **argv) { #ifdef QT_BOOTSTRAPPED initBinaryDir( #ifndef Q_OS_WIN argv[0] #endif ); #else QCoreApplication app(argc, argv); #ifndef Q_OS_WIN32 QTranslator translator; QTranslator qtTranslator; QString sysLocale = QLocale::system().name(); QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath); if (translator.load(QLatin1String("linguist_") + sysLocale, resourceDir) && qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir)) { app.installTranslator(&translator); app.installTranslator(&qtTranslator); } #endif // Q_OS_WIN32 #endif // QT_BOOTSTRAPPED ConversionData cd; cd.m_verbose = true; // the default is true starting with Qt 4.2 bool removeIdentical = false; Translator tor; QStringList inputFiles; QString outputFile; for (int i = 1; i < argc; ++i) { if (!strcmp(argv[i], "-compress")) { cd.m_saveMode = SaveStripped; continue; } else if (!strcmp(argv[i], "-idbased")) { cd.m_idBased = true; continue; } else if (!strcmp(argv[i], "-nocompress")) { cd.m_saveMode = SaveEverything; continue; } else if (!strcmp(argv[i], "-removeidentical")) { removeIdentical = true; continue; } else if (!strcmp(argv[i], "-nounfinished")) { cd.m_ignoreUnfinished = true; continue; } else if (!strcmp(argv[i], "-markuntranslated")) { if (i == argc - 1) { printUsage(); return 1; } cd.m_unTrPrefix = QString::fromLocal8Bit(argv[++i]); } else if (!strcmp(argv[i], "-silent")) { cd.m_verbose = false; continue; } else if (!strcmp(argv[i], "-verbose")) { cd.m_verbose = true; continue; } else if (!strcmp(argv[i], "-version")) { printOut(LR::tr("lrelease version %1\n").arg(QLatin1String(QT_VERSION_STR))); return 0; } else if (!strcmp(argv[i], "-qm")) { if (i == argc - 1) { printUsage(); return 1; } outputFile = QString::fromLocal8Bit(argv[++i]); } else if (!strcmp(argv[i], "-help")) { printUsage(); return 0; } else if (argv[i][0] == '-') { printUsage(); return 1; } else { inputFiles << QString::fromLocal8Bit(argv[i]); } } if (inputFiles.isEmpty()) { printUsage(); return 1; } foreach (const QString &inputFile, inputFiles) { if (inputFile.endsWith(QLatin1String(".pro"), Qt::CaseInsensitive) || inputFile.endsWith(QLatin1String(".pri"), Qt::CaseInsensitive)) { QFileInfo fi(inputFile); ProFile pro(fi.absoluteFilePath()); ProFileEvaluator visitor; visitor.setVerbose(cd.isVerbose()); if (!visitor.queryProFile(&pro)) { std::cerr << qPrintable(LR::tr( "lrelease error: cannot read project file '%1'.\n") .arg(inputFile)); continue; } if (!visitor.accept(&pro)) { std::cerr << qPrintable(LR::tr( "lrelease error: cannot process project file '%1'.\n") .arg(inputFile)); continue; } QStringList translations = visitor.values(QLatin1String("TRANSLATIONS")); if (translations.isEmpty()) { std::cerr << qPrintable(LR::tr( "lrelease warning: Met no 'TRANSLATIONS' entry in project file '%1'\n") .arg(inputFile)); } else { QDir proDir(fi.absolutePath()); foreach (const QString &trans, translations) if (!releaseTsFile(QFileInfo(proDir, trans).filePath(), cd, removeIdentical)) return 1; } } else { if (outputFile.isEmpty()) { if (!releaseTsFile(inputFile, cd, removeIdentical)) return 1; } else { if (!loadTsFile(tor, inputFile, cd.isVerbose())) return 1; } } } if (!outputFile.isEmpty()) return releaseTranslator(tor, outputFile, cd, removeIdentical) ? 0 : 1; return 0; } #ifdef QT_BOOTSTRAPPED #ifdef Q_OS_WIN # include <windows.h> #endif static QString binDir; static void initBinaryDir( #ifndef Q_OS_WIN const char *_argv0 #endif ) { #ifdef Q_OS_WIN wchar_t module_name[MAX_PATH]; GetModuleFileName(0, module_name, MAX_PATH); QFileInfo filePath = QString::fromWCharArray(module_name); binDir = filePath.filePath(); #else QString argv0 = QFile::decodeName(QByteArray(_argv0)); QString absPath; if (!argv0.isEmpty() && argv0.at(0) == QLatin1Char('/')) { /* If argv0 starts with a slash, it is already an absolute file path. */ absPath = argv0; } else if (argv0.contains(QLatin1Char('/'))) { /* If argv0 contains one or more slashes, it is a file path relative to the current directory. */ absPath = QDir::current().absoluteFilePath(argv0); } else { /* Otherwise, the file path has to be determined using the PATH environment variable. */ QByteArray pEnv = qgetenv("PATH"); QDir currentDir = QDir::current(); QStringList paths = QString::fromLocal8Bit(pEnv.constData()).split(QLatin1String(":")); for (QStringList::const_iterator p = paths.constBegin(); p != paths.constEnd(); ++p) { if ((*p).isEmpty()) continue; QString candidate = currentDir.absoluteFilePath(*p + QLatin1Char('/') + argv0); QFileInfo candidate_fi(candidate); if (candidate_fi.exists() && !candidate_fi.isDir()) { binDir = candidate_fi.canonicalPath(); return; } } return; } QFileInfo fi(absPath); if (fi.exists()) binDir = fi.canonicalPath(); #endif } QT_BEGIN_NAMESPACE // The name is hard-coded in QLibraryInfo QString qmake_libraryInfoFile() { if (binDir.isEmpty()) return QString(); return QDir(binDir).filePath(QString::fromLatin1("qt.conf")); } QT_END_NAMESPACE #endif // QT_BOOTSTRAPPED <|endoftext|>
<commit_before><commit_msg>WaE: type name first seen using 'class' now seen using 'struct'<commit_after><|endoftext|>
<commit_before>#include "scimed/wx.h" // todo: // add loading, zooming and panning in image // add loading/saving and specifying areas // add preview pane class MyFrame: public wxFrame { public: MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size) : wxFrame(NULL, wxID_ANY, title, pos, size) { SetMenuBar(CreateMenuBar()); CreateStatusBar(); SetStatusText("Welcome to wxWidgets!"); Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnExit, this, wxID_EXIT); Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnAbout, this, wxID_ABOUT); Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnSave, this, wxID_SAVE); Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnSaveAs, this, wxID_SAVEAS); Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnOpen, this, wxID_OPEN); } private: wxMenu* CreateFileMenu() { wxMenu *menuFile = new wxMenu; menuFile->Append(wxID_OPEN); menuFile->Append(wxID_SAVE); menuFile->Append(wxID_SAVEAS); menuFile->AppendSeparator(); menuFile->Append(wxID_EXIT); return menuFile; } wxMenu* CreateHelpMenu() { wxMenu *menuHelp = new wxMenu; menuHelp->Append(wxID_ABOUT); return menuHelp; } wxMenuBar* CreateMenuBar() { wxMenuBar *menuBar = new wxMenuBar; menuBar->Append(CreateFileMenu(), "&File"); menuBar->Append(CreateHelpMenu(), "&Help"); return menuBar; } void OnSave(wxCommandEvent& event){ } void OnSaveAs(wxCommandEvent& event){ } void OnOpen(wxCommandEvent& event){ } void OnExit(wxCommandEvent& event){ Close(true); } void OnAbout(wxCommandEvent& event){ wxMessageBox("Scimed - the Scalable Image Editor", "About Scimed", wxOK | wxICON_INFORMATION); } }; //////////////////////////////////////////////////////////////////////////////// class MyApp: public wxApp { public: virtual bool OnInit() { MyFrame *frame = new MyFrame( "Scimed", wxPoint(50, 50), wxSize(450, 340) ); frame->Show( true ); return true; } }; wxIMPLEMENT_APP(MyApp);<commit_msg>load and display png<commit_after>#include "scimed/wx.h" #include <wx/sizer.h> // todo: // add loading, zooming and panning in image // add loading/saving and specifying areas // add preview pane class wxImagePanel : public wxPanel { wxImage image; wxBitmap resized; int w, h; bool displayImage_; public: explicit wxImagePanel(wxFrame* parent) : wxPanel(parent), displayImage_(false) { Bind(wxEVT_SIZE, &wxImagePanel::OnSize, this); Bind(wxEVT_PAINT, &wxImagePanel::OnPaint, this); } bool LoadImage(wxString file, wxBitmapType format) { displayImage_ = image.LoadFile(file, format); w = -1; h = -1; // displayImage_ = true; if( displayImage_ ) { Refresh(); } return displayImage_; } void OnPaint(wxPaintEvent & evt) { if(displayImage_ == false) { return; } wxPaintDC dc(this); int neww, newh; dc.GetSize( &neww, &newh ); if( neww != w || newh != h ) { resized = wxBitmap( image.Scale( neww, newh /*, wxIMAGE_QUALITY_HIGH*/ ) ); w = neww; h = newh; dc.DrawBitmap( resized, 0, 0, false ); } else { dc.DrawBitmap( resized, 0, 0, false ); } } void OnSize(wxSizeEvent& event){ Refresh(); //skip the event. event.Skip(); } // some useful events /* void mouseMoved(wxMouseEvent& event); void mouseDown(wxMouseEvent& event); void mouseWheelMoved(wxMouseEvent& event); void mouseReleased(wxMouseEvent& event); void rightClick(wxMouseEvent& event); void mouseLeftWindow(wxMouseEvent& event); void keyPressed(wxKeyEvent& event); void keyReleased(wxKeyEvent& event); */ }; // some useful events /* void wxImagePanel::mouseMoved(wxMouseEvent& event) {} void wxImagePanel::mouseDown(wxMouseEvent& event) {} void wxImagePanel::mouseWheelMoved(wxMouseEvent& event) {} void wxImagePanel::mouseReleased(wxMouseEvent& event) {} void wxImagePanel::rightClick(wxMouseEvent& event) {} void wxImagePanel::mouseLeftWindow(wxMouseEvent& event) {} void wxImagePanel::keyPressed(wxKeyEvent& event) {} void wxImagePanel::keyReleased(wxKeyEvent& event) {} */ class MyFrame: public wxFrame { public: MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size) : wxFrame(NULL, wxID_ANY, title, pos, size), title_(title) { SetMenuBar(CreateMenuBar()); CreateStatusBar(); SetStatusText(""); wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL); drawPane = new wxImagePanel(this); sizer->Add(drawPane, 1, wxEXPAND); SetSizer(sizer); Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnExit, this, wxID_EXIT); Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnAbout, this, wxID_ABOUT); Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnSave, this, wxID_SAVE); Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnSaveAs, this, wxID_SAVEAS); Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnOpen, this, wxID_OPEN); } private: wxImagePanel * drawPane; wxString title_; wxString filename_; void UpdateTitle() { if( filename_.IsEmpty() ) { SetTitle( title_ ); } else { SetTitle( title_ + " - " + filename_ ); } } wxMenu* CreateFileMenu() { wxMenu *menuFile = new wxMenu; menuFile->Append(wxID_OPEN); menuFile->Append(wxID_SAVE); menuFile->Append(wxID_SAVEAS); menuFile->AppendSeparator(); menuFile->Append(wxID_EXIT); return menuFile; } wxMenu* CreateHelpMenu() { wxMenu *menuHelp = new wxMenu; menuHelp->Append(wxID_ABOUT); return menuHelp; } wxMenuBar* CreateMenuBar() { wxMenuBar *menuBar = new wxMenuBar; menuBar->Append(CreateFileMenu(), "&File"); menuBar->Append(CreateHelpMenu(), "&Help"); return menuBar; } void OnSave(wxCommandEvent& event){ if( filename_.IsEmpty() ) { OnSaveAs(event); return; } // do saving... } void OnSaveAs(wxCommandEvent& event) { wxFileDialog saveFileDialog(this, _("Save scim file"), "", "", "SCIM files (*.png)|*.png", wxFD_SAVE|wxFD_OVERWRITE_PROMPT); if (saveFileDialog.ShowModal() == wxID_CANCEL) { return; } filename_ = saveFileDialog.GetPath(); UpdateTitle(); OnSave(event); } void OnOpen(wxCommandEvent& event) { wxFileDialog openFileDialog(this, _("Open scim file"), "", "", "SCIM files (*.png)|*.png", wxFD_OPEN|wxFD_FILE_MUST_EXIST); if (openFileDialog.ShowModal() == wxID_CANCEL) { return; } if( drawPane->LoadImage(openFileDialog.GetPath(), wxBITMAP_TYPE_PNG) ) { filename_ = openFileDialog.GetPath(); } else { filename_ = ""; } UpdateTitle(); } void OnExit(wxCommandEvent& event){ Close(true); } void OnAbout(wxCommandEvent& event){ wxMessageBox("Scimed - the Scalable Image Editor", "About Scimed", wxOK | wxICON_INFORMATION); } }; //////////////////////////////////////////////////////////////////////////////// class MyApp: public wxApp { public: virtual bool OnInit() { wxInitAllImageHandlers(); MyFrame *frame = new MyFrame( "Scimed", wxPoint(50, 50), wxSize(450, 340) ); frame->Show( true ); return true; } }; wxIMPLEMENT_APP(MyApp); <|endoftext|>
<commit_before>// Copyright (C) 2011 Oliver Schulz <oliver.schulz@tu-dortmund.de> // This is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This software is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include <string> #include <iostream> #include <cstdlib> #include <cstring> #include <unistd.h> #include <TROOT.h> #include <TSystem.h> #include <TApplication.h> #include <THttpServer.h> #include "logging.h" #include "Props.h" #include "ApplicationBric.h" using namespace std; using namespace dbrx; PropVal g_config = Props(); Name g_logLevelOverride; unique_ptr<TApplication> g_rootApplication; void configureLogging() { // g_logLevel overrides logging config in g_config if (! g_logLevelOverride.empty()) { g_config["logLevel"] = g_logLevelOverride; } if (g_config.contains("logLevel")) { auto level = LoggingFacility::levelOf(g_config.at("logLevel").asString()); if (level != log_level()) { dbrx_log_debug("Changing logging level to %s", LoggingFacility::nameOf(level)); log_level(level); } } } void configureLogging(const std::string &levelName) { if (!levelName.empty()) { Name normalizedLevelName = LoggingFacility::nameOf(LoggingFacility::levelOf(levelName)); g_logLevelOverride = normalizedLevelName; configureLogging(); } } void addConfigFrom(PropVal &config, const std::string &from) { dbrx_log_debug("Reading \"%s\"", from); PropVal p = PropVal::fromFile(from); dbrx_log_debug("Done reading"); if (!p.isProps()) throw invalid_argument("Invalid config in \"%s\", but contain an object, not a value or an array"_format(from)); config.asProps() += p.asProps(); } void addGlobalConfigFrom(const std::string &from) { dbrx_log_debug("Adding \"%s\" to config", from); addConfigFrom(g_config, from); } void printConfig(std::ostream &out, const PropVal &config, const std::string &format) { if (format == "json") { config.toJSON(out); out << endl; } else throw invalid_argument("Unknown configuration output format"); } void task_config_printUsage(const char* progName) { cerr << "Syntax: " << progName << " [OPTIONS] CONFIG.." << endl; cerr << "" << endl; cerr << "Options:" << endl; cerr << "-? Show help" << endl; cerr << "-f FORMAT Set output format (formats: [json], ...)" << endl; cerr << "-l LEVEL Set logging level" << endl; cerr << "" << endl; cerr << "Combine and output given configurations in specified format (JSON by default)." << endl; cerr << "Supported output formats: \"json\" (more formats to come in future versions)." << endl; } int task_config(int argc, char *argv[], char *envp[]) { string outputFormat("json"); int opt = 0; while ((opt = getopt(argc, argv, "?c:l:f:j")) != -1) { switch (opt) { case '?': { task_config_printUsage(argv[0]); return 0; } case 'l': { configureLogging(optarg); break; } case 'f': { dbrx_log_debug("Setting output format to %s", optarg); outputFormat = string(optarg); break; } default: throw invalid_argument("Unkown command line option"); } } PropVal config = Props(); while (optind < argc) { std::string from = argv[optind++]; dbrx_log_debug("Reading config from \"%s\"", from); addConfigFrom(config, from); } printConfig(cout, config, outputFormat); } void task_run_printUsage(const char* progName) { cerr << "Syntax: " << progName << " [OPTIONS] CONFIG.." << endl; cerr << "" << endl; cerr << "Options:" << endl; cerr << "-? Show help" << endl; cerr << "-c SETTINGS Load configuration/settings" << endl; cerr << "-l LEVEL Set logging level (default: \"info\")" << endl; cerr << "-w Enable HTTP server" << endl; cerr << "-p PORT HTTP server port (default: 8080)" << endl; cerr << "-k Don't exit after processing (e.g. to keep HTTP server running)" << endl; cerr << "" << endl; cerr << "Run the given bric configuration. If multiple configuration are given, they" << endl; cerr << "are merged together (from left to right)." << endl; } int task_run(int argc, char *argv[], char *envp[]) { bool enableHTTP = false; uint16_t httpPort = 8080; bool keepRunning = false; int opt = 0; while ((opt = getopt(argc, argv, "?c:l:wp:k")) != -1) { switch (opt) { case '?': { task_run_printUsage(argv[0]); return 0; } case 'l': { configureLogging(optarg); break; } case 'w': { enableHTTP = true; break; } case 'p': { httpPort = atoi(optarg); break; } case 'k': { keepRunning = true; break; } default: throw invalid_argument("Unkown command line option"); } } if (! (optind < argc)) { task_run_printUsage(argv[0]); return 1; } while (optind < argc) { std::string from = argv[optind++]; dbrx_log_debug("Reading config from \"%s\"", from); addGlobalConfigFrom(from); } configureLogging(); unique_ptr<THttpServer> httpServer; if (enableHTTP) { dbrx_log_info("Starting HTTP server on port %s", httpPort); httpServer = unique_ptr<THttpServer>( new THttpServer("civetweb:%s"_format(httpPort).c_str())); } ApplicationBric app("dbrx"); app.applyConfig(g_config); app.run(); if (keepRunning) { dbrx_log_info("Keeping program running"); if (httpServer) dbrx_log_info("HTTP server active on port %s", httpPort); g_rootApplication->Run(true); } return 0; } void main_printUsage(const char* progName) { cerr << "Syntax: " << progName << " COMMAND ..." << endl << endl; cerr << "Commands: " << endl; cerr << " config" << endl; cerr << " run" << endl; cerr << "" << endl; cerr << "Use" << endl; cerr << "" << endl; cerr << " " << progName << " COMMAND -?" << endl; cerr << "" << endl; cerr << "to get help for the individual commands." << endl; } int main(int argc, char *argv[], char *envp[]) { try { // Have to create an application to activate ROOT's on-demand class loader // (still true for ROOT-6?): g_rootApplication = unique_ptr<TApplication>(new TApplication("dbrx", 0, 0)); // Set ROOT program name (necessary / useful ?): gSystem->SetProgname("dbrx"); // Have to tell ROOT to load vector dlls, otherwise ROOT will produce // "is not of a class known to ROOT" errors on creation of STL vector // branches (still true for ROOT-6?): gROOT->ProcessLineSync("#include <vector>"); // Make sure Cling has all databricxx headers loaded. This currently // seems to be the only way, gSystem->Load("libdatabricxx.so") is not // sufficient for some reason: gROOT->ProcessLineSync("dbrx::PropVal();"); string progName(argv[0]); if (argc < 2) { main_printUsage(argv[0]); return 1; } string cmd(argv[1]); int cmd_argc = argc - 1; char **cmd_argv = argv + 1; if (cmd == "-?") { main_printUsage(argv[0]); return 0; } if (cmd == "config") return task_config(cmd_argc, cmd_argv, envp); else if (cmd == "run") return task_run(cmd_argc, cmd_argv, envp); else throw invalid_argument("Command \"%s\" not supported."_format(cmd)); } catch(std::exception &e) { dbrx_log_error("%s (%s)",e.what(), typeid(e).name()); return 1; } dbrx_log_info("Done."); } <commit_msg>Renamed dbrx command "config" to "get-config"<commit_after>// Copyright (C) 2011 Oliver Schulz <oliver.schulz@tu-dortmund.de> // This is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This software is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include <string> #include <iostream> #include <cstdlib> #include <cstring> #include <unistd.h> #include <TROOT.h> #include <TSystem.h> #include <TApplication.h> #include <THttpServer.h> #include "logging.h" #include "Props.h" #include "ApplicationBric.h" using namespace std; using namespace dbrx; PropVal g_config = Props(); Name g_logLevelOverride; unique_ptr<TApplication> g_rootApplication; void configureLogging() { // g_logLevel overrides logging config in g_config if (! g_logLevelOverride.empty()) { g_config["logLevel"] = g_logLevelOverride; } if (g_config.contains("logLevel")) { auto level = LoggingFacility::levelOf(g_config.at("logLevel").asString()); if (level != log_level()) { dbrx_log_debug("Changing logging level to %s", LoggingFacility::nameOf(level)); log_level(level); } } } void configureLogging(const std::string &levelName) { if (!levelName.empty()) { Name normalizedLevelName = LoggingFacility::nameOf(LoggingFacility::levelOf(levelName)); g_logLevelOverride = normalizedLevelName; configureLogging(); } } void addConfigFrom(PropVal &config, const std::string &from) { dbrx_log_debug("Reading \"%s\"", from); PropVal p = PropVal::fromFile(from); dbrx_log_debug("Done reading"); if (!p.isProps()) throw invalid_argument("Invalid config in \"%s\", but contain an object, not a value or an array"_format(from)); config.asProps() += p.asProps(); } void addGlobalConfigFrom(const std::string &from) { dbrx_log_debug("Adding \"%s\" to config", from); addConfigFrom(g_config, from); } void printConfig(std::ostream &out, const PropVal &config, const std::string &format) { if (format == "json") { config.toJSON(out); out << endl; } else throw invalid_argument("Unknown configuration output format"); } void task_get_config_printUsage(const char* progName) { cerr << "Syntax: " << progName << " [OPTIONS] CONFIG.." << endl; cerr << "" << endl; cerr << "Options:" << endl; cerr << "-? Show help" << endl; cerr << "-f FORMAT Set output format (formats: [json], ...)" << endl; cerr << "-l LEVEL Set logging level" << endl; cerr << "" << endl; cerr << "Combine and output given configurations in specified format (JSON by default)." << endl; cerr << "Supported output formats: \"json\" (more formats to come in future versions)." << endl; } int task_get_config(int argc, char *argv[], char *envp[]) { string outputFormat("json"); int opt = 0; while ((opt = getopt(argc, argv, "?c:l:f:j")) != -1) { switch (opt) { case '?': { task_get_config_printUsage(argv[0]); return 0; } case 'l': { configureLogging(optarg); break; } case 'f': { dbrx_log_debug("Setting output format to %s", optarg); outputFormat = string(optarg); break; } default: throw invalid_argument("Unkown command line option"); } } PropVal config = Props(); while (optind < argc) { std::string from = argv[optind++]; dbrx_log_debug("Reading config from \"%s\"", from); addConfigFrom(config, from); } printConfig(cout, config, outputFormat); } void task_run_printUsage(const char* progName) { cerr << "Syntax: " << progName << " [OPTIONS] CONFIG.." << endl; cerr << "" << endl; cerr << "Options:" << endl; cerr << "-? Show help" << endl; cerr << "-c SETTINGS Load configuration/settings" << endl; cerr << "-l LEVEL Set logging level (default: \"info\")" << endl; cerr << "-w Enable HTTP server" << endl; cerr << "-p PORT HTTP server port (default: 8080)" << endl; cerr << "-k Don't exit after processing (e.g. to keep HTTP server running)" << endl; cerr << "" << endl; cerr << "Run the given bric configuration. If multiple configuration are given, they" << endl; cerr << "are merged together (from left to right)." << endl; } int task_run(int argc, char *argv[], char *envp[]) { bool enableHTTP = false; uint16_t httpPort = 8080; bool keepRunning = false; int opt = 0; while ((opt = getopt(argc, argv, "?c:l:wp:k")) != -1) { switch (opt) { case '?': { task_run_printUsage(argv[0]); return 0; } case 'l': { configureLogging(optarg); break; } case 'w': { enableHTTP = true; break; } case 'p': { httpPort = atoi(optarg); break; } case 'k': { keepRunning = true; break; } default: throw invalid_argument("Unkown command line option"); } } if (! (optind < argc)) { task_run_printUsage(argv[0]); return 1; } while (optind < argc) { std::string from = argv[optind++]; dbrx_log_debug("Reading config from \"%s\"", from); addGlobalConfigFrom(from); } configureLogging(); unique_ptr<THttpServer> httpServer; if (enableHTTP) { dbrx_log_info("Starting HTTP server on port %s", httpPort); httpServer = unique_ptr<THttpServer>( new THttpServer("civetweb:%s"_format(httpPort).c_str())); } ApplicationBric app("dbrx"); app.applyConfig(g_config); app.run(); if (keepRunning) { dbrx_log_info("Keeping program running"); if (httpServer) dbrx_log_info("HTTP server active on port %s", httpPort); g_rootApplication->Run(true); } return 0; } void main_printUsage(const char* progName) { cerr << "Syntax: " << progName << " COMMAND ..." << endl << endl; cerr << "Commands: " << endl; cerr << " get-config" << endl; cerr << " run" << endl; cerr << "" << endl; cerr << "Use" << endl; cerr << "" << endl; cerr << " " << progName << " COMMAND -?" << endl; cerr << "" << endl; cerr << "to get help for the individual commands." << endl; } int main(int argc, char *argv[], char *envp[]) { try { // Have to create an application to activate ROOT's on-demand class loader // (still true for ROOT-6?): g_rootApplication = unique_ptr<TApplication>(new TApplication("dbrx", 0, 0)); // Set ROOT program name (necessary / useful ?): gSystem->SetProgname("dbrx"); // Have to tell ROOT to load vector dlls, otherwise ROOT will produce // "is not of a class known to ROOT" errors on creation of STL vector // branches (still true for ROOT-6?): gROOT->ProcessLineSync("#include <vector>"); // Make sure Cling has all databricxx headers loaded. This currently // seems to be the only way, gSystem->Load("libdatabricxx.so") is not // sufficient for some reason: gROOT->ProcessLineSync("dbrx::PropVal();"); string progName(argv[0]); if (argc < 2) { main_printUsage(argv[0]); return 1; } string cmd(argv[1]); int cmd_argc = argc - 1; char **cmd_argv = argv + 1; if (cmd == "-?") { main_printUsage(argv[0]); return 0; } if (cmd == "get-config") return task_get_config(cmd_argc, cmd_argv, envp); else if (cmd == "run") return task_run(cmd_argc, cmd_argv, envp); else throw invalid_argument("Command \"%s\" not supported."_format(cmd)); } catch(std::exception &e) { dbrx_log_error("%s (%s)",e.what(), typeid(e).name()); return 1; } dbrx_log_info("Done."); } <|endoftext|>