<commit_before>/* Copyright (C) 2012-2013 Justin Berger
   The full license is available in the LICENSE file at the root of this project and is also available at http://opensource.org/licenses/MIT. */

#include <mxcomp/log.h>
#include <fstream>
#include <iostream>
#include <mxcomp/future_contwith.h>

// http://connect.microsoft.com/VisualStudio/feedback/details/809540/c-warnings-in-stl-thread
#pragma warning(disable: 4265)
#include <mutex>
#pragma warning(default: 4265)

#ifdef _MSC_VER
#include <mxcomp/vsostream.h>
static std::ostream* defaultStream = &mxcomp::vsdb;
#else
static std::ostream* defaultStream = &std::cerr;
#endif

namespace mxcomp {
  namespace log {

    static std::map<std::string, std::ostream*> logStreams;
	std::mutex logMutex;

    std::map<std::string, int>& logLevels(){
      static std::map<std::string, int>* logLevels = 0;
	  if (logLevels == 0) { // Makes logLevels look up cheap when there is an object (no mutex lock)
		  std::lock_guard<std::mutex> lock(logMutex);
		  if (logLevels == 0) { // If we blocked for another thread, make sure we dont create two logLevels.
			  logLevels = new std::map<std::string, int>();
		  }
	  }
      return *logLevels;
    }
    void SetLogStream(std::ostream* stream) {
         defaultStream = stream;
    }
    void SetLogStream(std::ostream& stream) {
         defaultStream = &stream;
    }

    void SetLogStream(const std::string& category, std::ostream& stream){
      logStreams[category] = &stream;
    }

    std::ostream& LogStream(const std::string& category){
      auto it = logStreams.find(category);
      return it == logStreams.end() ? *defaultStream : *(it->second);
    }

    void SetLogLevel(const std::string& category, int level){
      logLevels()[category] = level;
    }
    static int getLevel(const std::string& level){
      if(level == "Verbose") {
	return Verbose;
      } else if (level == "Info") {
	return Info;
      } else if (level == "Debug") {
	return Debug;
      } else if (level == "Error") {
	return Error;
      }
      return INVALID;
    }

    void SetLogLevel(const std::string& category, const std::string& level){
      int _level = getLevel(level);
      SetLogLevel(category, _level);
      LOG(Logging, Verbose) << "Setting '" << category << "' to '" << level << "'(" << _level << ")" << std::endl;
      if(_level == INVALID)
	LOG(Logging, Error) << "Invalid logging level('" << level << "') set for category '" << category << "'. Level set to highest verbosity." << std::endl;
    }
  }
}

// We _must_ define this block in this file; as its the only way to insure that it fires off before any of the functions for logging
#ifdef RT_USE_CONFIGURATION
#include <rikitiki/configuration/configuration>
using namespace rikitiki;
using namespace rikitiki::log;
using namespace libconfig;

static bool LoadFromConfig(Configuration& config) {
  try {
    const Setting& logsettings = config.getRoot()["log"]["levels"];
    std::string name, value;
    for(int i = 0;i < logsettings.getLength();i++){
      const Setting& entry = logsettings[i];
      bool cFind = entry.lookupValue("category", name);
      bool vFind = entry.lookupValue("level", value);
      if(cFind && vFind)
	SetLogLevel(name, value);
    }
    return true;
  } catch(const SettingNotFoundException& nfex){
    return false;
  }
}

static bool config_loaded = LoadFromConfig(Configuration::Global());
#endif

<commit_msg>fixed non chunking<commit_after>/* Copyright (C) 2012-2013 Justin Berger
   The full license is available in the LICENSE file at the root of this project and is also available at http://opensource.org/licenses/MIT. */

#include <mxcomp/log.h>
#include <fstream>
#include <iostream>
//#include <mxcomp/future_contwith.h>

// http://connect.microsoft.com/VisualStudio/feedback/details/809540/c-warnings-in-stl-thread
#pragma warning(disable: 4265)
#include <mutex>
#pragma warning(default: 4265)

#ifdef _MSC_VER
#include <mxcomp/vsostream.h>
static std::ostream* defaultStream = &mxcomp::vsdb;
#else
static std::ostream* defaultStream = &std::cerr;
#endif

namespace mxcomp {
  namespace log {

    static std::map<std::string, std::ostream*> logStreams;
	std::mutex logMutex;

    std::map<std::string, int>& logLevels(){
      static std::map<std::string, int>* logLevels = 0;
	  if (logLevels == 0) { // Makes logLevels look up cheap when there is an object (no mutex lock)
		  std::lock_guard<std::mutex> lock(logMutex);
		  if (logLevels == 0) { // If we blocked for another thread, make sure we dont create two logLevels.
			  logLevels = new std::map<std::string, int>();
		  }
	  }
      return *logLevels;
    }
    void SetLogStream(std::ostream* stream) {
         defaultStream = stream;
    }
    void SetLogStream(std::ostream& stream) {
         defaultStream = &stream;
    }

    void SetLogStream(const std::string& category, std::ostream& stream){
      logStreams[category] = &stream;
    }

    std::ostream& LogStream(const std::string& category){
      auto it = logStreams.find(category);
      return it == logStreams.end() ? *defaultStream : *(it->second);
    }

    void SetLogLevel(const std::string& category, int level){
      logLevels()[category] = level;
    }
    static int getLevel(const std::string& level){
      if(level == "Verbose") {
	return Verbose;
      } else if (level == "Info") {
	return Info;
      } else if (level == "Debug") {
	return Debug;
      } else if (level == "Error") {
	return Error;
      }
      return INVALID;
    }

    void SetLogLevel(const std::string& category, const std::string& level){
      int _level = getLevel(level);
      SetLogLevel(category, _level);
      LOG(Logging, Verbose) << "Setting '" << category << "' to '" << level << "'(" << _level << ")" << std::endl;
      if(_level == INVALID)
	LOG(Logging, Error) << "Invalid logging level('" << level << "') set for category '" << category << "'. Level set to highest verbosity." << std::endl;
    }
  }
}

// We _must_ define this block in this file; as its the only way to insure that it fires off before any of the functions for logging
#ifdef RT_USE_CONFIGURATION
#include <rikitiki/configuration/configuration>
using namespace rikitiki;
using namespace rikitiki::log;
using namespace libconfig;

static bool LoadFromConfig(Configuration& config) {
  try {
    const Setting& logsettings = config.getRoot()["log"]["levels"];
    std::string name, value;
    for(int i = 0;i < logsettings.getLength();i++){
      const Setting& entry = logsettings[i];
      bool cFind = entry.lookupValue("category", name);
      bool vFind = entry.lookupValue("level", value);
      if(cFind && vFind)
	SetLogLevel(name, value);
    }
    return true;
  } catch(const SettingNotFoundException& nfex){
    return false;
  }
}

static bool config_loaded = LoadFromConfig(Configuration::Global());
#endif

<|endoftext|>


<commit_before>#include <chrono>
#include <iostream>

#include "image.h"
using namespace AhoViewer::Booru;

#include "browser.h"

Image::Image(const std::string &path, const std::string &url,
             const std::string &thumbPath, const std::string &thumbUrl,
             const std::string &postUrl,
             std::set<std::string> tags, const Page &page)
  : AhoViewer::Image(path),
    m_Url(url),
    m_ThumbnailUrl(thumbUrl),
    m_PostUrl(postUrl),
    m_Tags(tags),
    m_Page(page),
    m_Curler(m_Url),
    m_ThumbnailCurler(m_ThumbnailUrl),
    m_PixbufError(false)
{
    m_ThumbnailPath = thumbPath;

    if (!m_isWebM)
        m_Curler.signal_write().connect(sigc::mem_fun(*this, &Image::on_write));

    if (m_isWebM && !Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))
        m_Loading = true;

    m_Curler.set_referer(page.get_site()->get_url());
    m_Curler.signal_progress().connect(sigc::mem_fun(*this, &Image::on_progress));
    m_Curler.signal_finished().connect(sigc::mem_fun(*this, &Image::on_finished));
}

Image::~Image()
{
    cancel_download();

    if (m_Curler.is_active())
        m_Page.get_image_fetcher().remove_handle(&m_Curler);
}

std::string Image::get_filename() const
{
    return Glib::build_filename(m_Page.get_site()->get_name(), Glib::path_get_basename(m_Path));
}

const Glib::RefPtr<Gdk::Pixbuf>& Image::get_thumbnail()
{
    if (!m_ThumbnailPixbuf)
    {
        m_ThumbnailLock.writer_lock();
        if (m_ThumbnailCurler.perform())
        {
            m_ThumbnailCurler.save_file(m_ThumbnailPath);

            try
            {
                m_ThumbnailPixbuf = create_pixbuf_at_size(m_ThumbnailPath, 128, 128);
            }
            catch (const Gdk::PixbufError &ex)
            {
                std::cerr << ex.what() << std::endl;
                m_ThumbnailPixbuf = get_missing_pixbuf();
            }
        }
        else
        {
            std::cerr << "Error while downloading thumbnail " << m_ThumbnailUrl
                      << " " << std::endl << "  " << m_ThumbnailCurler.get_error() << std::endl;
            m_ThumbnailPixbuf = get_missing_pixbuf();
        }
        m_ThumbnailLock.writer_unlock();
    }

    return m_ThumbnailPixbuf;
}

void Image::load_pixbuf()
{
    if (!m_Pixbuf && !m_PixbufError)
    {
        if (Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))
        {
            AhoViewer::Image::load_pixbuf();
        }
        else if (!start_download() && !m_isWebM && m_Loader->get_animation())
        {
            m_Pixbuf = m_Loader->get_animation();
        }
    }
}

void Image::reset_pixbuf()
{
    if (m_Loading)
        cancel_download();

    AhoViewer::Image::reset_pixbuf();
}

void Image::save(const std::string &path)
{
    if (!Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))
    {
        start_download();

        Glib::Threads::Mutex::Lock lock(m_DownloadMutex);
        while (!m_Curler.is_cancelled() && !Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))
            m_DownloadCond.wait(m_DownloadMutex);
    }

    if (m_Curler.is_cancelled())
        return;

    Glib::RefPtr<Gio::File> src = Gio::File::create_for_path(m_Path),
                            dst = Gio::File::create_for_path(path);
    src->copy(dst, Gio::FILE_COPY_OVERWRITE);
}

void Image::cancel_download()
{
    Glib::Threads::Mutex::Lock lock(m_DownloadMutex);
    m_Curler.cancel();
    m_Curler.clear();

    if (m_Loader)
    {
        try { m_Loader->close(); }
        catch (...) { }
        m_Loader.reset();
    }

    m_DownloadCond.signal();
}

/**
 * Returns true if the download was started
 **/
bool Image::start_download()
{
    if (!m_Curler.is_active())
    {
        m_Page.get_image_fetcher().add_handle(&m_Curler);
        m_Loading = true;

        if (!m_isWebM)
        {
            m_Loader = Gdk::PixbufLoader::create();
            m_Loader->signal_area_prepared().connect(sigc::mem_fun(*this, &Image::on_area_prepared));
            m_Loader->signal_area_updated().connect(sigc::mem_fun(*this, &Image::on_area_updated));
        }

        return true;
    }

    return false;
}

void Image::on_write(const unsigned char *d, size_t l)
{
    try
    {
        Glib::Threads::Mutex::Lock lock(m_DownloadMutex);
        m_Loader->write(d, l);
    }
    catch (const Gdk::PixbufError &ex)
    {
        std::cerr << ex.what() << std::endl;
        cancel_download();
        m_PixbufError = true;
    }
}

void Image::on_progress()
{
    double c, t;
    m_Curler.get_progress(c, t);
    m_SignalProgress(c, t);
}

void Image::on_finished()
{
    Glib::Threads::Mutex::Lock lock(m_DownloadMutex);

    m_Curler.save_file(m_Path);
    m_Curler.clear();

    if (m_Loader)
    {
        m_Loader->close();
        m_Loader.reset();
    }

    m_Loading = false;

    m_SignalPixbufChanged();
    m_DownloadCond.signal();
}

void Image::on_area_prepared()
{
    m_ThumbnailLock.reader_lock();
    if (m_ThumbnailPixbuf && m_ThumbnailPixbuf != get_missing_pixbuf())
    {
        Glib::RefPtr<Gdk::Pixbuf> pixbuf = m_Loader->get_pixbuf();
        m_ThumbnailPixbuf->composite(pixbuf, 0, 0, pixbuf->get_width(), pixbuf->get_height(), 0, 0,
                                     static_cast<double>(pixbuf->get_width()) / m_ThumbnailPixbuf->get_width(),
                                     static_cast<double>(pixbuf->get_height()) / m_ThumbnailPixbuf->get_height(),
                                     Gdk::INTERP_BILINEAR, 255);
    }
    m_ThumbnailLock.reader_unlock();

    m_Pixbuf = m_Loader->get_animation();

    if (!m_Curler.is_cancelled())
        m_SignalPixbufChanged();
}

void Image::on_area_updated(int, int, int, int)
{
    using namespace std::chrono;
    if (!m_Curler.is_cancelled() && steady_clock::now() >= m_LastDraw + milliseconds(100))
    {
        m_SignalPixbufChanged();
        m_LastDraw = steady_clock::now();
    }
}
<commit_msg>booru/image: Remove curler from the imagefetcher in cancel_download<commit_after>#include <chrono>
#include <iostream>

#include "image.h"
using namespace AhoViewer::Booru;

#include "browser.h"

Image::Image(const std::string &path, const std::string &url,
             const std::string &thumbPath, const std::string &thumbUrl,
             const std::string &postUrl,
             std::set<std::string> tags, const Page &page)
  : AhoViewer::Image(path),
    m_Url(url),
    m_ThumbnailUrl(thumbUrl),
    m_PostUrl(postUrl),
    m_Tags(tags),
    m_Page(page),
    m_Curler(m_Url),
    m_ThumbnailCurler(m_ThumbnailUrl),
    m_PixbufError(false)
{
    m_ThumbnailPath = thumbPath;

    if (!m_isWebM)
        m_Curler.signal_write().connect(sigc::mem_fun(*this, &Image::on_write));

    if (m_isWebM && !Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))
        m_Loading = true;

    m_Curler.set_referer(page.get_site()->get_url());
    m_Curler.signal_progress().connect(sigc::mem_fun(*this, &Image::on_progress));
    m_Curler.signal_finished().connect(sigc::mem_fun(*this, &Image::on_finished));
}

Image::~Image()
{
    cancel_download();
}

std::string Image::get_filename() const
{
    return Glib::build_filename(m_Page.get_site()->get_name(), Glib::path_get_basename(m_Path));
}

const Glib::RefPtr<Gdk::Pixbuf>& Image::get_thumbnail()
{
    if (!m_ThumbnailPixbuf)
    {
        m_ThumbnailLock.writer_lock();
        if (m_ThumbnailCurler.perform())
        {
            m_ThumbnailCurler.save_file(m_ThumbnailPath);

            try
            {
                m_ThumbnailPixbuf = create_pixbuf_at_size(m_ThumbnailPath, 128, 128);
            }
            catch (const Gdk::PixbufError &ex)
            {
                std::cerr << ex.what() << std::endl;
                m_ThumbnailPixbuf = get_missing_pixbuf();
            }
        }
        else
        {
            std::cerr << "Error while downloading thumbnail " << m_ThumbnailUrl
                      << " " << std::endl << "  " << m_ThumbnailCurler.get_error() << std::endl;
            m_ThumbnailPixbuf = get_missing_pixbuf();
        }
        m_ThumbnailLock.writer_unlock();
    }

    return m_ThumbnailPixbuf;
}

void Image::load_pixbuf()
{
    if (!m_Pixbuf && !m_PixbufError)
    {
        if (Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))
        {
            AhoViewer::Image::load_pixbuf();
        }
        else if (!start_download() && !m_isWebM && m_Loader->get_animation())
        {
            m_Pixbuf = m_Loader->get_animation();
        }
    }
}

void Image::reset_pixbuf()
{
    if (m_Loading)
        cancel_download();

    AhoViewer::Image::reset_pixbuf();
}

void Image::save(const std::string &path)
{
    if (!Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))
    {
        start_download();

        Glib::Threads::Mutex::Lock lock(m_DownloadMutex);
        while (!m_Curler.is_cancelled() && !Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS))
            m_DownloadCond.wait(m_DownloadMutex);
    }

    if (m_Curler.is_cancelled())
        return;

    Glib::RefPtr<Gio::File> src = Gio::File::create_for_path(m_Path),
                            dst = Gio::File::create_for_path(path);
    src->copy(dst, Gio::FILE_COPY_OVERWRITE);
}

void Image::cancel_download()
{
    Glib::Threads::Mutex::Lock lock(m_DownloadMutex);
    m_Curler.cancel();
    m_Curler.clear();

    if (m_Loader)
    {
        try { m_Loader->close(); }
        catch (...) { }
        m_Loader.reset();
    }

    m_DownloadCond.signal();

    if (m_Curler.is_active())
        m_Page.get_image_fetcher().remove_handle(&m_Curler);
}

/**
 * Returns true if the download was started
 **/
bool Image::start_download()
{
    if (!m_Curler.is_active())
    {
        m_Page.get_image_fetcher().add_handle(&m_Curler);
        m_Loading = true;

        if (!m_isWebM)
        {
            m_Loader = Gdk::PixbufLoader::create();
            m_Loader->signal_area_prepared().connect(sigc::mem_fun(*this, &Image::on_area_prepared));
            m_Loader->signal_area_updated().connect(sigc::mem_fun(*this, &Image::on_area_updated));
        }

        return true;
    }

    return false;
}

void Image::on_write(const unsigned char *d, size_t l)
{
    try
    {
        Glib::Threads::Mutex::Lock lock(m_DownloadMutex);
        m_Loader->write(d, l);
    }
    catch (const Gdk::PixbufError &ex)
    {
        std::cerr << ex.what() << std::endl;
        cancel_download();
        m_PixbufError = true;
    }
}

void Image::on_progress()
{
    double c, t;
    m_Curler.get_progress(c, t);
    m_SignalProgress(c, t);
}

void Image::on_finished()
{
    Glib::Threads::Mutex::Lock lock(m_DownloadMutex);

    m_Curler.save_file(m_Path);
    m_Curler.clear();

    if (m_Loader)
    {
        m_Loader->close();
        m_Loader.reset();
    }

    m_Loading = false;

    m_SignalPixbufChanged();
    m_DownloadCond.signal();
}

void Image::on_area_prepared()
{
    m_ThumbnailLock.reader_lock();
    if (m_ThumbnailPixbuf && m_ThumbnailPixbuf != get_missing_pixbuf())
    {
        Glib::RefPtr<Gdk::Pixbuf> pixbuf = m_Loader->get_pixbuf();
        m_ThumbnailPixbuf->composite(pixbuf, 0, 0, pixbuf->get_width(), pixbuf->get_height(), 0, 0,
                                     static_cast<double>(pixbuf->get_width()) / m_ThumbnailPixbuf->get_width(),
                                     static_cast<double>(pixbuf->get_height()) / m_ThumbnailPixbuf->get_height(),
                                     Gdk::INTERP_BILINEAR, 255);
    }
    m_ThumbnailLock.reader_unlock();

    m_Pixbuf = m_Loader->get_animation();

    if (!m_Curler.is_cancelled())
        m_SignalPixbufChanged();
}

void Image::on_area_updated(int, int, int, int)
{
    using namespace std::chrono;
    if (!m_Curler.is_cancelled() && steady_clock::now() >= m_LastDraw + milliseconds(100))
    {
        m_SignalPixbufChanged();
        m_LastDraw = steady_clock::now();
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;

bool isDirectory(char* directoryName) {

	struct directoryInCurrent;
	int errorCheck;
	if (-1 == (errorCheck = stat(directoryName, directoryInCurrent))) {

		perror("stat failed");
		exit(0);
	}
}

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

	if (argc == 1) {

		char const *dirName = ".";
		DIR *dirp;
		if (!(dirp = opendir(dirName))) {
		cerr << "Error(" << errno << ") opening " << dirName << endl;
			return errno;
		}

		dirent *direntp;
		while ((direntp = readdir(dirp))) {
			if (direntp->d_name[0] != '.') {

				//cout << direntp->d_name << endl; // use stat here to find attributes of a file
				printf(direntp->d_name, 8);
				cout << " ";
			}
		}
		cout << endl;
		closedir(dirp);
	}

	else {

		vector<string> directories;
		vector<string> flags;
		for (unsigned i = 1; i < argc; ++i) {

			if (argv[i][0] == '-') {
				flags.push_back(argv[i]);
			}
			else {

			}
		}
	}

}

<commit_msg>made functions to call ls<commit_after>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;

bool isDirectory(char* directoryName) {

	struct directoryInCurrent;
	int errorCheck;
	if (-1 == (errorCheck = stat(directoryName, directoryInCurrent))) {

		perror("stat failed");
		return false;
	}

	if (directoryInCurrent.st_mode & S_IFDIR) {
		return true;
	}
	else {
		return false;
	}
}

bool ls(char* directoryName) {

		char const *dirName = ".";
		DIR *dirp;
		if (!(dirp = opendir(dirName))) {
		cerr << "Error(" << errno << ") opening " << dirName << endl;
			return errno;
		}

		dirent *direntp;
		while ((direntp = readdir(dirp))) {
			if (direntp->d_name[0] != '.') {

				//cout << direntp->d_name << endl; // use stat here to find attributes of a file
				printf(direntp->d_name, 8);
				cout << " ";
			}
		}
		cout << endl;
		closedir(dirp);
}
bool lsWithFlags(char* directoryName, vector<string> flags) {

	bool isA = false;
	bool isL = false;
	bool isR = false;
	for (unsigned i = 0; i < flags.size(); ++i) {

		if (flags.at(i) == "a")
			isA = true;
		else if (flags.at(i) == "l")
			isL = true;
		else if (flags.at(i) == "R")
			isR = true;

	}
	char const *dirName = directoryName;
	DIR *dirp;
	if (!(dirp = opendir(dirName))) {
		cerr << "Error(" << errno << ") opening " << dirName << endl;
		return errno;
	}

	dirent *direntp;
	while ((direntp = readdir(dirp))) {
		if (direntp->d_name[0] != '.') {

			//cout << direntp->d_name << endl; // use stat here to find attributes of a file
			printf(direntp->d_name, 8);
			cout << " ";
		}
	}
	cout << endl;
	closedir(dirp);
}

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

	if (argc == 1) {

		if (!ls(".")) {
			exit(1);
		}
	}

	else {

		vector<string> directories;
		vector<string> flags;
		for (unsigned i = 1; i < argc; ++i) {

			if (argv[i][0] == '-') {
				flags.push_back(argv[i]);
			}
			else {
				if (isDirectory(
			}
		}
	}

}

<|endoftext|>


<commit_before>#ifndef __INCLUDED_BITFIELD_BITFIELD_HPP__
#define __INCLUDED_BITFIELD_BITFIELD_HPP__

#include <bitfield/bit_type.hpp>
#include <bitfield/container/array.hpp>
#include <cstdint>

namespace bitfield {
    template<uint32_t Size, uint32_t Offset = 0>
    class field {
    public:
        static constexpr uint32_t SIZE = Size;
        static constexpr uint32_t OFFSET = Offset;
        static constexpr uint32_t NEXT_OFFSET = SIZE + OFFSET;

        static constexpr uint32_t BYTE = bit_type(SIZE).ceil().byte();
        static constexpr uint32_t PADDING = bit_type(NEXT_OFFSET).ceil().diff(NEXT_OFFSET).bit();
        static constexpr uint32_t MASK = bit_type(SIZE).max_value() << PADDING;

        template<uint32_t NextSize>
        using next_field = field<NextSize, NEXT_OFFSET>;
        using container_type = container::array<bit_type(NEXT_OFFSET).ceil().byte()>;

        field() = default;
        field(const field & v) { this->set(v.get()); }
        field(uint32_t v) { this->set(v); }

        field & operator =(const field & rop) {
            this->set(rop.get());
            return *this;
        }

        field & operator =(uint32_t rop) {
            this->set(rop);
            return *this;
        }

        operator uint32_t() const {
            return this->get();
        }

        // for Little-Endian
        uint32_t get() const {
            uint32_t value = 0x00;
            uint8_t * addr = bit_type(OFFSET).addr(this);
            uint8_t * value_addr = (uint8_t *)&value;

            for (uint32_t i=0; i < BYTE; ++i) {
                value_addr[BYTE-i-1] = addr[i];
            }

            value &= MASK;
            value >>= PADDING;
            return value;
        }

        // for Little-Endian
        void set(uint32_t value) {
            static constexpr uint32_t clear_mask = ~MASK;

            value <<= PADDING;
            value &= MASK;

            uint8_t * addr = bit_type(OFFSET).addr(this);
            uint8_t * value_addr = (uint8_t *)&value;
            uint8_t * clear_mask_addr = (uint8_t *)&clear_mask;

            for (uint32_t i=0; i < BYTE; ++i) {
                uint32_t j = BYTE-i-1;
                addr[i] &= clear_mask_addr[j];
                addr[i] |= value_addr[j];
            }
        }
   };
}

#endif // __INCLUDED_BITFIELD_BITFIELD_HPP__
<commit_msg>Deleted a copy constructor and copy assignment operator from the field.<commit_after>#ifndef __INCLUDED_BITFIELD_BITFIELD_HPP__
#define __INCLUDED_BITFIELD_BITFIELD_HPP__

#include <bitfield/bit_type.hpp>
#include <bitfield/container/array.hpp>
#include <cstdint>

namespace bitfield {
    template<uint32_t Size, uint32_t Offset = 0>
    class field {
    public:
        static constexpr uint32_t SIZE = Size;
        static constexpr uint32_t OFFSET = Offset;
        static constexpr uint32_t NEXT_OFFSET = SIZE + OFFSET;

        static constexpr uint32_t BYTE = bit_type(SIZE).ceil().byte();
        static constexpr uint32_t PADDING = bit_type(NEXT_OFFSET).ceil().diff(NEXT_OFFSET).bit();
        static constexpr uint32_t MASK = bit_type(SIZE).max_value() << PADDING;

        template<uint32_t NextSize>
        using next_field = field<NextSize, NEXT_OFFSET>;
        using container_type = container::array<bit_type(NEXT_OFFSET).ceil().byte()>;

        field() = default;
        field(const field &) = delete;
        field & operator =(const field &) = delete;

        field(uint32_t v) { this->set(v); }

        field & operator =(uint32_t rop) {
            this->set(rop);
            return *this;
        }

        operator uint32_t() const {
            return this->get();
        }

        // for Little-Endian
        uint32_t get() const {
            uint32_t value = 0x00;
            uint8_t * addr = bit_type(OFFSET).addr(this);
            uint8_t * value_addr = (uint8_t *)&value;

            for (uint32_t i=0; i < BYTE; ++i) {
                value_addr[BYTE-i-1] = addr[i];
            }

            value &= MASK;
            value >>= PADDING;
            return value;
        }

        // for Little-Endian
        void set(uint32_t value) {
            static constexpr uint32_t clear_mask = ~MASK;

            value <<= PADDING;
            value &= MASK;

            uint8_t * addr = bit_type(OFFSET).addr(this);
            uint8_t * value_addr = (uint8_t *)&value;
            uint8_t * clear_mask_addr = (uint8_t *)&clear_mask;

            for (uint32_t i=0; i < BYTE; ++i) {
                uint32_t j = BYTE-i-1;
                addr[i] &= clear_mask_addr[j];
                addr[i] |= value_addr[j];
            }
        }
   };
}

#endif // __INCLUDED_BITFIELD_BITFIELD_HPP__
<|endoftext|>


<commit_before><commit_msg>small fix<commit_after><|endoftext|>


<commit_before><commit_msg>Small improvements of the behavior of bodies switched to static<commit_after><|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 * Point Cloud Library (PCL) - www.pointclouds.org
 * Copyright (c) 2010-2011, Willow Garage, Inc.
 * Copyright (c) 2012-, Open Perception, Inc.
 *
 * 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 copyright holder(s) 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 OWNER 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.
 *
 * person_classifier.cpp
 * Created on: Nov 30, 2012
 * Author: Matteo Munaro
 */

#include <pcl/people/person_classifier.h>

// Compute HOG descriptor:
void hog(double *I, int h, int w, int nCh, int sBin, int oBin, int oGran, double* H);

namespace pcl
{
	namespace people
	{

		PersonClassifier::PersonClassifier () {}

		PersonClassifier::~PersonClassifier () {}

		void
		PersonClassifier::setSVM (int window_height, int window_width, std::vector<float> SVM_weights, float SVM_offset)
		{
			window_height_ = window_height;
			window_width_ = window_width;
			SVM_weights_ = SVM_weights;
			SVM_offset_ = SVM_offset;
		}

		void
		PersonClassifier::getSVM (int& window_height, int& window_width, std::vector<float>& SVM_weights, float& SVM_offset)
		{
			window_height = window_height_;
			window_width = window_width_;
			SVM_weights = SVM_weights_;
			SVM_offset = SVM_offset_;
		}

		void
		PersonClassifier::resize (pcl::PointCloud<pcl::RGB>::Ptr& input_image, pcl::PointCloud<pcl::RGB>::Ptr& output_image,
				int width, int height)
		{
			pcl::RGB new_point;
			new_point.r = 0;
			new_point.g = 0;
			new_point.b = 0;

			// Allocate the vector of points:
			output_image->points.resize(width*height, new_point);
			output_image->height = height;
			output_image->width = width;

			// Compute scale factor:
			float scale1 = float(height) / float(input_image->height);
			float scale2 = float(width) / float(input_image->width);

			Eigen::Matrix3f T_inv;
			T_inv << 1/scale1, 0, 0,
					 0, 1/scale2, 0,
					 0,   0,   1;

			Eigen::Vector3f A;
			int c1, c2, f1, f2;
			pcl::RGB g1, g2, g3, g4;
			float w1, w2;
			for (unsigned int i = 0; i < height; i++)		// for every row
			{
				for (unsigned int j = 0; j < width; j++)	// for every column
				{
					A = T_inv * Eigen::Vector3f(i, j, 1);
					c1 = ceil(A(0));
					f1 = floor(A(0));
					c2 = ceil(A(1));
					f2 = floor(A(1));

					if ((f1 < 0) || (c1 < 0) || (f1 >= input_image->height) || (c1 >= input_image->height) || (f2 < 0) || (c2 < 0) ||
							(f2 >= input_image->width) || (c2 >= input_image->width))
					{	// if out of range, continue
						continue;
					}

					g1 = (*input_image)(f2, c1);
					g3 = (*input_image)(f2, f1);
					g4 = (*input_image)(c2, f1);
					g2 = (*input_image)(c2, c1);

					w1 = (A(0) - f1);
					w2 = (A(1) - f2);
					new_point.r = int((1 - w1) * ((1 - w2) * g1.r + w2 * g4.r) + w1 * ((1 - w2) * g3.r + w2 * g4.r));
					new_point.g = int((1 - w1) * ((1 - w2) * g1.g + w2 * g4.g) + w1 * ((1 - w2) * g3.g + w2 * g4.g));
					new_point.b = int((1 - w1) * ((1 - w2) * g1.b + w2 * g4.b) + w1 * ((1 - w2) * g3.b + w2 * g4.b));

					// Insert the point in the output image:
					(*output_image)(j,i) = new_point;
				}
			}
		}

		void
		PersonClassifier::copyMakeBorder (pcl::PointCloud<pcl::RGB>::Ptr& input_image, pcl::PointCloud<pcl::RGB>::Ptr& output_image,
				int xmin, int ymin, int width, int height)
		{
			pcl::RGB black_point;
			black_point.r = 0;
			black_point.g = 0;
			black_point.b = 0;
			output_image->points.resize(height*width, black_point);
			output_image->width = width;
			output_image->height = height;

			int x_start_in = std::max(0, xmin);
			int x_end_in = std::min(int(input_image->width-1), xmin+width-1);
			int y_start_in = std::max(0, ymin);
			int y_end_in = std::min(int(input_image->height-1), ymin+height-1);

			int x_start_out = std::max(0, -xmin);
			int x_end_out = x_start_out + (x_end_in - x_start_in);
			int y_start_out = std::max(0, -ymin);
			int y_end_out = y_start_out + (y_end_in - y_start_in);

			for (unsigned int i = 0; i < (y_end_in - y_start_in + 1); i++)
			{
				for (unsigned int j = 0; j < (x_end_in - x_start_in + 1); j++)
				{
					(*output_image)(x_start_out + j, y_start_out + i) = (*input_image)(x_start_in + j, y_start_in + i);
				}
			}
		}

		double
		PersonClassifier::evaluate (float height_person, float xc, float yc, pcl::PointCloud<pcl::RGB>::Ptr& image)
		{
			if (SVM_weights_.size() == 0)
			{
				PCL_ERROR ("[pcl::people::PersonClassifier::evaluate] SVM has not been set!\n");
				return (-1000);
			}

			int height = floor((height_person * window_height_) / (0.75 * window_height_) + 0.5);	// floor(i+0.5) = round(i)
			int width = floor((height_person * window_width_) / (0.75 * window_height_) + 0.5);
			int xmin = floor(xc - width / 2 + 0.5);
			int ymin = floor(yc - height / 2 + 0.5);

			// If near the border, fill with black
			pcl::PointCloud<pcl::RGB>::Ptr box(new pcl::PointCloud<pcl::RGB>);
			copyMakeBorder(image, box, xmin, ymin, width, height);

			// Make the image match the correct size
			pcl::PointCloud<pcl::RGB>::Ptr sample(new pcl::PointCloud<pcl::RGB>);
			resize(box, sample, window_width_, window_height_);

			//Convert the image to Matlab format
			double* sample_double = new double[sample->width * sample->height * 3];
			int delta = sample->height * sample->width;
			for(int row = 0; row < sample->height; row++)
			{
				for(int col = 0; col < sample->width; col++)
				{
					sample_double[row + sample->height * col] = (double) ((*sample)(col, row).r); //ptr[col * 3 + 2];
					sample_double[row + sample->height * col + delta] = (double) ((*sample)(col, row).g); //ptr[col * 3 + 1];
					sample_double[row + sample->height * col + delta * 2] = (double) ((*sample)(col, row).b); //ptr[col * 3];
				}
			}

			double *ris = new double[SVM_weights_.size()];

			//Calculate HOG descriptor
			hog(sample_double, sample->height, sample->width, 3, 8, 9, 10, ris);

			//Calculate confidence value by dot product
			double confidence = 0.0;
			for(uint i = 0; i < SVM_weights_.size(); i++)
			{
				confidence += SVM_weights_[i] * ris[i];
			}
			//Confidence correction
			confidence -= SVM_offset_;

			delete[] ris;
			delete[] sample_double;

			return confidence;
		}

		double
		PersonClassifier::evaluate (pcl::PointCloud<pcl::RGB>::Ptr& image, Eigen::Vector3f& bottom, Eigen::Vector3f& top, Eigen::Vector3f& centroid,
							Eigen::Matrix3f intrinsics_matrix, bool vertical)
		{
			float pixel_height;
			float pixel_width;
			if (not vertical)
			{
				pixel_height = bottom(1) - top(1);
				pixel_width = pixel_height / 2.0f;
			}
			else
			{
				pixel_width = top(0) - bottom(0);
				pixel_height = pixel_width / 2.0f;
			}
			float pixel_xc = centroid(0);
			float pixel_yc = centroid(1);

			if (not vertical)
			{
				return (evaluate(pixel_height, pixel_xc, pixel_yc, image));
			}
			else
			{
				return (evaluate(pixel_width, pixel_yc, image->height-pixel_xc+1, image));
			}
		}
	} /* namespace people */
} /* namespace pcl */
<commit_msg>Changed indentation to PCL style for PersonClassifier<commit_after>/*
 * Software License Agreement (BSD License)
 *
 * Point Cloud Library (PCL) - www.pointclouds.org
 * Copyright (c) 2010-2011, Willow Garage, Inc.
 * Copyright (c) 2012-, Open Perception, Inc.
 *
 * 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 copyright holder(s) 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 OWNER 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.
 *
 * person_classifier.cpp
 * Created on: Nov 30, 2012
 * Author: Matteo Munaro
 */

#include <pcl/people/person_classifier.h>

// Compute HOG descriptor:
void hog(double *I, int h, int w, int nCh, int sBin, int oBin, int oGran, double* H);

namespace pcl
{
  namespace people
  {

    PersonClassifier::PersonClassifier () {}

    PersonClassifier::~PersonClassifier () {}

    void
    PersonClassifier::setSVM (int window_height, int window_width, std::vector<float> SVM_weights, float SVM_offset)
    {
      window_height_ = window_height;
      window_width_ = window_width;
      SVM_weights_ = SVM_weights;
      SVM_offset_ = SVM_offset;
    }

    void
    PersonClassifier::getSVM (int& window_height, int& window_width, std::vector<float>& SVM_weights, float& SVM_offset)
    {
      window_height = window_height_;
      window_width = window_width_;
      SVM_weights = SVM_weights_;
      SVM_offset = SVM_offset_;
    }

    void
    PersonClassifier::resize (pcl::PointCloud<pcl::RGB>::Ptr& input_image,
                              pcl::PointCloud<pcl::RGB>::Ptr& output_image,
                              int width,
                              int height)
    {
      pcl::RGB new_point;
      new_point.r = 0;
      new_point.g = 0;
      new_point.b = 0;

      // Allocate the vector of points:
      output_image->points.resize(width*height, new_point);
      output_image->height = height;
      output_image->width = width;

      // Compute scale factor:
      float scale1 = float(height) / float(input_image->height);
      float scale2 = float(width) / float(input_image->width);

      Eigen::Matrix3f T_inv;
      T_inv << 1/scale1, 0, 0,
               0, 1/scale2, 0,
               0,   0,   1;

      Eigen::Vector3f A;
      int c1, c2, f1, f2;
      pcl::RGB g1, g2, g3, g4;
      float w1, w2;
      for (unsigned int i = 0; i < height; i++)		// for every row
      {
        for (unsigned int j = 0; j < width; j++)	// for every column
        {
          A = T_inv * Eigen::Vector3f(i, j, 1);
          c1 = ceil(A(0));
          f1 = floor(A(0));
          c2 = ceil(A(1));
          f2 = floor(A(1));

          if ( (f1 < 0) ||
               (c1 < 0) ||
               (f1 >= input_image->height) ||
               (c1 >= input_image->height) ||
               (f2 < 0) ||
               (c2 < 0) ||
               (f2 >= input_image->width) ||
               (c2 >= input_image->width))
          { // if out of range, continue
            continue;
          }

          g1 = (*input_image)(f2, c1);
          g3 = (*input_image)(f2, f1);
          g4 = (*input_image)(c2, f1);
          g2 = (*input_image)(c2, c1);

          w1 = (A(0) - f1);
          w2 = (A(1) - f2);
          new_point.r = int((1 - w1) * ((1 - w2) * g1.r + w2 * g4.r) + w1 * ((1 - w2) * g3.r + w2 * g4.r));
          new_point.g = int((1 - w1) * ((1 - w2) * g1.g + w2 * g4.g) + w1 * ((1 - w2) * g3.g + w2 * g4.g));
          new_point.b = int((1 - w1) * ((1 - w2) * g1.b + w2 * g4.b) + w1 * ((1 - w2) * g3.b + w2 * g4.b));

          // Insert the point in the output image:
          (*output_image)(j,i) = new_point;
        }
      }
    }

    void
    PersonClassifier::copyMakeBorder (pcl::PointCloud<pcl::RGB>::Ptr& input_image,
                                      pcl::PointCloud<pcl::RGB>::Ptr& output_image,
                                      int xmin,
                                      int ymin,
                                      int width,
                                      int height)
    {
      pcl::RGB black_point;
      black_point.r = 0;
      black_point.g = 0;
      black_point.b = 0;
      output_image->points.resize(height*width, black_point);
      output_image->width = width;
      output_image->height = height;

      int x_start_in = std::max(0, xmin);
      int x_end_in = std::min(int(input_image->width-1), xmin+width-1);
      int y_start_in = std::max(0, ymin);
      int y_end_in = std::min(int(input_image->height-1), ymin+height-1);

      int x_start_out = std::max(0, -xmin);
      int x_end_out = x_start_out + (x_end_in - x_start_in);
      int y_start_out = std::max(0, -ymin);
      int y_end_out = y_start_out + (y_end_in - y_start_in);

      for (unsigned int i = 0; i < (y_end_in - y_start_in + 1); i++)
      {
        for (unsigned int j = 0; j < (x_end_in - x_start_in + 1); j++)
        {
          (*output_image)(x_start_out + j, y_start_out + i) = (*input_image)(x_start_in + j, y_start_in + i);
        }
      }
    }

    double
    PersonClassifier::evaluate (float height_person,
                                float xc,
                                float yc,
                                pcl::PointCloud<pcl::RGB>::Ptr& image)
    {
      if (SVM_weights_.size() == 0)
      {
        PCL_ERROR ("[pcl::people::PersonClassifier::evaluate] SVM has not been set!\n");
        return (-1000);
      }

      int height = floor((height_person * window_height_) / (0.75 * window_height_) + 0.5);	// floor(i+0.5) = round(i)
      int width = floor((height_person * window_width_) / (0.75 * window_height_) + 0.5);
      int xmin = floor(xc - width / 2 + 0.5);
      int ymin = floor(yc - height / 2 + 0.5);

      // If near the border, fill with black
      pcl::PointCloud<pcl::RGB>::Ptr box(new pcl::PointCloud<pcl::RGB>);
      copyMakeBorder(image, box, xmin, ymin, width, height);

      // Make the image match the correct size
      pcl::PointCloud<pcl::RGB>::Ptr sample(new pcl::PointCloud<pcl::RGB>);
      resize(box, sample, window_width_, window_height_);

      //Convert the image to Matlab format
      double* sample_double = new double[sample->width * sample->height * 3];
      int delta = sample->height * sample->width;
      for(int row = 0; row < sample->height; row++)
      {
        for(int col = 0; col < sample->width; col++)
        {
          sample_double[row + sample->height * col] = (double) ((*sample)(col, row).r); //ptr[col * 3 + 2];
          sample_double[row + sample->height * col + delta] = (double) ((*sample)(col, row).g); //ptr[col * 3 + 1];
          sample_double[row + sample->height * col + delta * 2] = (double) ((*sample)(col, row).b); //ptr[col * 3];
        }
      }

      double *ris = new double[SVM_weights_.size()];

      //Calculate HOG descriptor
      hog(sample_double, sample->height, sample->width, 3, 8, 9, 10, ris);

      //Calculate confidence value by dot product
      double confidence = 0.0;
      for(uint i = 0; i < SVM_weights_.size(); i++)
      {
      	confidence += SVM_weights_[i] * ris[i];
      }
      //Confidence correction
      confidence -= SVM_offset_;

      delete[] ris;
      delete[] sample_double;

      return confidence;
    }

    double
    PersonClassifier::evaluate (pcl::PointCloud<pcl::RGB>::Ptr& image,
                                Eigen::Vector3f& bottom,
                                Eigen::Vector3f& top,
                                Eigen::Vector3f& centroid,
                                Eigen::Matrix3f intrinsics_matrix,
                                bool vertical)
    {
      float pixel_height;
      float pixel_width;
      if (not vertical)
      {
        pixel_height = bottom(1) - top(1);
        pixel_width = pixel_height / 2.0f;
      }
      else
      {
        pixel_width = top(0) - bottom(0);
        pixel_height = pixel_width / 2.0f;
      }
      float pixel_xc = centroid(0);
      float pixel_yc = centroid(1);

      if (not vertical)
      {
        return (evaluate(pixel_height, pixel_xc, pixel_yc, image));
      }
      else
      {
        return (evaluate(pixel_width, pixel_yc, image->height-pixel_xc+1, image));
      }
    }
  } /* namespace people */
} /* namespace pcl */
<|endoftext|>


<commit_before><commit_msg>Fix for default mapper node count when running with -ll:cpu 0.<commit_after><|endoftext|>


<commit_before>#include <gtest/gtest.h>

#include "photoeffects.hpp"

using namespace cv;

TEST(photoeffects, SepiaFakeTest) {
    Mat src(10, 10, CV_8UC1), dst;

    EXPECT_EQ(0, sepia(src, dst));
}

TEST(photoeffects, SepiaFailTest) {
    Mat src(10, 10, CV_8UC3), dst;

    EXPECT_EQ(1, sepia(src, dst));
}

/*
TEST(photoeffects, SepiaTest) {
    Mat src(10, 10, CV_8UC1), dst, hsvDst;
    vector<Mat> channels(3);

    EXPECT_EQ(0, sepia(src, dst));
    cvtColor(dst, hsvDst, CV_BGR2HSV);
    split(hsvDst, channels);
    EXPECT_EQ(src.at<uchar>(0, 0) + 20, channels[2].at<uchar>(0, 0));
}
*/
<commit_msg>Test was restored, interval [<v>-1,<v>+1] was set for hue, saturation and value.<commit_after>#include <gtest/gtest.h>

#include "photoeffects.hpp"

using namespace cv;

TEST(photoeffects, SepiaFakeTest) {
    Mat src(10, 10, CV_8UC1), dst;

    EXPECT_EQ(0, sepia(src, dst));
}

TEST(photoeffects, SepiaFailTest) {
    Mat src(10, 10, CV_8UC3), dst;

    EXPECT_EQ(1, sepia(src, dst));
}

TEST(photoeffects, SepiaTest) {
    Mat src(10, 10, CV_8UC1), dst, hsvDst;
    vector<Mat> channels(3);

    EXPECT_EQ(0, sepia(src, dst));
    cvtColor(dst, hsvDst, CV_BGR2HSV);
    split(hsvDst, channels);
    EXPECT_LE(19 - 1, channels[0].at<uchar>(0, 0)); // hue = 19
    EXPECT_GE(19 + 1, channels[0].at<uchar>(0, 0));
    EXPECT_LE(78 - 1, channels[1].at<uchar>(0, 0)); // saturation = 78
    EXPECT_GE(78 + 1, channels[1].at<uchar>(0, 0));
    EXPECT_LE(src.at<uchar>(0, 0) + 20 - 1, channels[2].at<uchar>(0, 0));
    EXPECT_GE(src.at<uchar>(0, 0) + 20 + 1, channels[2].at<uchar>(0, 0));
}

<|endoftext|>


<commit_before>// stdafx.cpp : source file that includes just the standard includes
// Base.UnitTest.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"

// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
<commit_msg>added doxygen header<commit_after>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2013 Michael Fink
//
//! \file Base\Base.UnitTest\stdafx.cpp Precompiled header support
//

// includes
#include "stdafx.h"
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <iostream>

#include "icdar/icdar_reader.hpp"

constexpr const std::size_t context = 5;
constexpr const std::size_t window = context * 2 + 1;

int main(){
    auto dataset = icdar::read_2013_dataset(
        "/home/wichtounet/datasets/icdar_2013_natural/train",
        "/home/wichtounet/datasets/icdar_2013_natural/test", 5, 1);

    if(dataset.training_labels.empty() || dataset.training_images.empty()){
        std::cout << "Problem while reading the dataset" << std::endl;

        return -1;
    }

    std::cout << dataset.training_images.size() << " training images" << std::endl;
    std::cout << dataset.test_images.size() << " test images" << std::endl;

    //TODO What about randomization ?

    for(auto& image : dataset.training_images){
        std::vector<std::vector<uint8_t>> windows;
        windows.reserve(image.width * image.height);

        for(std::size_t i = context; i < image.width - context; ++i){
            for(std::size_t j = context; j < image.height - context; ++j){

                windows.emplace_back(window * window);

                for(std::size_t a = i - context; a < i - context + window; ++a){
                    for(std::size_t b = j - context; b < j - context + window; ++b){
                        auto w_i = (a - (i - context));
                        auto w_j = (b - (j - context));
                        windows.back().at(w_i * window + w_j) = image.pixels.at(a * image.height + b).r;
                    }
                }
            }
        }

        std::cout << windows.size() << " windows extracted" << std::endl;
    }

    return 0;
}
<commit_msg>Prepare CDBN<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <iostream>

#include "dll/conv_rbm.hpp"
#include "dll/conv_dbn.hpp"
#include "dll/cpp_utils/algorithm.hpp"

#include "icdar/icdar_reader.hpp"

constexpr const std::size_t context = 5;
constexpr const std::size_t window = context * 2 + 1;

int main(){
    auto dataset = icdar::read_2013_dataset(
        "/home/wichtounet/datasets/icdar_2013_natural/train",
        "/home/wichtounet/datasets/icdar_2013_natural/test", 5, 1);

    if(dataset.training_labels.empty() || dataset.training_images.empty()){
        std::cout << "Problem while reading the dataset" << std::endl;

        return -1;
    }

    std::cout << dataset.training_images.size() << " training images" << std::endl;
    std::cout << dataset.test_images.size() << " test images" << std::endl;

    //TODO What about randomization ?

    std::vector<std::vector<uint8_t>> windows;

    for(auto& image : dataset.training_images){
        windows.reserve(windows.size() + image.width * image.height);

        for(std::size_t i = context; i < image.width - context; ++i){
            for(std::size_t j = context; j < image.height - context; ++j){

                windows.emplace_back(window * window);

                for(std::size_t a = i - context; a < i - context + window; ++a){
                    for(std::size_t b = j - context; b < j - context + window; ++b){
                        auto w_i = (a - (i - context));
                        auto w_j = (b - (j - context));
                        windows.back().at(w_i * window + w_j) = image.pixels.at(a * image.height + b).r;
                    }
                }
            }
        }
    }

    //TODO Normalization
    //TODO Gaussian

    std::cout << windows.size() << " windows extracted" << std::endl;

    typedef dll::conv_dbn_desc<
        dll::dbn_layers<
            dll::conv_rbm_desc<window, 1, 5, 40, dll::momentum, dll::batch_size<50>, dll::weight_decay<dll::decay_type::L2>, dll::sparsity<dll::sparsity_method::LEE>>::rbm_t
            >>::dbn_t dbn_t;

    auto dbn = std::make_unique<dbn_t>();

    dbn->layer<0>().pbias = 0.05;
    dbn->layer<0>().pbias_lambda = 50;

    dbn->pretrain(windows, 50);

    return 0;
}
<|endoftext|>


<commit_before>/*
	[2015/7/31] コマンドの実行は仮想関数？関数ポインタ？
		Release ビルド 100000000 回の単純呼び出しで、
		仮想関数 : 450ms
		関数ポインタ : 400ms
		微々たる差だが、関数ポインタが少しだけ有利。
*/
#pragma once

#include "../Internal.h"
#include "Device/GraphicsDriverInterface.h"
#include <Lumino/Graphics/Shader.h>
#include "RenderingCommand.h"

LN_NAMESPACE_BEGIN
LN_NAMESPACE_GRAPHICS_BEGIN

//=============================================================================
// RenderingCommand
//=============================================================================
//void* RenderingCommand::operator new(size_t size, RenderingCommandList* cmmandList)
//{
//	size_t dataIdx = cmmandList->Alloc(size, NULL);
//	RenderingCommand* cmd = (RenderingCommand*)cmmandList->GetBuffer(dataIdx);
//	cmd->m_commandList = cmmandList;
//	cmmandList->m_commandList.Add(dataIdx);
//	return cmd;
//}
//
//void RenderingCommand::operator delete(void* ptr, RenderingCommandList* cmmandList)
//{
//}

//=============================================================================
// RenderingCommandList
//=============================================================================

#define CREATE_COMMAND(name) \
	size_t dataIdx = Alloc(sizeof(name##Command), NULL); \
	name##Command* cmd = (name##Command*)&(m_commandDataBuffer.GetData()[dataIdx]); \
	cmd->Type = CommandType_##name; \
	m_commandList.Add(dataIdx);

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
RenderingCommandList::RenderingCommandList()
	: m_commandList()
	, m_commandDataBuffer()
	, m_commandDataBufferUsed(0)
	, m_extDataBuffer()
	, m_extDataBufferUsed(0)
	, m_markGCList()
	, m_currentDevice(NULL)
	, m_currentRenderer(NULL)
	, m_running(false)
	, m_idling(true)
{
	m_commandList.Reserve(DataBufferReserve);	// 適当に
	m_commandDataBuffer.Resize(DataBufferReserve, false);
	m_commandDataBufferUsed = 0;
	m_extDataBuffer.Resize(DataBufferReserve, false);
	m_extDataBufferUsed = 0;
}

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
RenderingCommandList::~RenderingCommandList()
{
}

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void RenderingCommandList::Execute(Driver::IGraphicsDevice* device/*Driver::IRenderer* renderer*/)
{
	LN_RC_TRACE("RenderingCommandList::Execute() s %p %d\n", this, m_commandList.GetCount());
	// この関数は描画スレッドから呼ばれる

	m_currentDevice = device;
	m_currentRenderer = device->GetRenderer();
	LN_FOREACH(size_t dataIdx, m_commandList)
	{
		((RenderingCommand*)GetCommand(dataIdx))->Execute();
	}
	LN_RC_TRACE("RenderingCommandList::Execute() e %p\n", this);
}

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void RenderingCommandList::PostExecute()
{
	//LN_RC_TRACE("RenderingCommandList::PostExecute() s %p\n", this);
	//LN_FOREACH(size_t dataIdx, m_commandList)
	//{
	//	((RenderingCommand*)GetCommand(dataIdx))->Release(this);
	//	((RenderingCommand*)GetCommand(dataIdx))->~RenderingCommand();
	//}
	//LN_RC_TRACE("RenderingCommandList::PostExecute() e %p\n", this);
	m_commandList.Clear();
	m_commandDataBufferUsed = 0;

	LN_FOREACH(RefObject* obj, m_markGCList)
	{
		obj->Release();
	}
	m_markGCList.Clear();
}

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
RenderingCommandList::DataHandle RenderingCommandList::AllocCommand(size_t byteCount, const void* copyData)
{
	// バッファが足りなければ拡張する
	if (m_commandDataBufferUsed + byteCount > m_commandDataBuffer.GetSize()) {
		size_t newSize = m_commandDataBuffer.GetSize() + std::max(m_commandDataBuffer.GetSize(), byteCount);	// 最低でも byteCount 分を拡張する
		m_commandDataBuffer.Resize(newSize, false);
	}

	if (copyData != NULL)
	{
		byte_t* ptr = &(m_commandDataBuffer.GetData()[m_commandDataBufferUsed]);
		size_t size = m_commandDataBuffer.GetSize() - m_commandDataBufferUsed;
		memcpy_s(ptr, size, copyData, byteCount);
	}

	size_t dataIdx = m_commandDataBufferUsed;
	m_commandDataBufferUsed += byteCount;

	return dataIdx;
}

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
RenderingCommandList::DataHandle RenderingCommandList::AllocExtData(size_t byteCount, const void* copyData)
{
	// バッファが足りなければ拡張する
	if (m_extDataBufferUsed + byteCount > m_extDataBuffer.GetSize()) {
		size_t newSize = m_extDataBuffer.GetSize() + std::max(m_extDataBuffer.GetSize(), byteCount);	// 最低でも byteCount 分を拡張する
		m_extDataBuffer.Resize(newSize, false);
	}

	if (copyData != NULL)
	{
		byte_t* ptr = &(m_extDataBuffer.GetData()[m_extDataBufferUsed]);
		size_t size = m_extDataBuffer.GetSize() - m_extDataBufferUsed;
		memcpy_s(ptr, size, copyData, byteCount);
	}

	size_t dataIdx = m_extDataBufferUsed;
	m_extDataBufferUsed += byteCount;

	return dataIdx;
}

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void* RenderingCommandList::GetExtData(DataHandle bufferIndex)
{
	return &(m_extDataBuffer.GetData()[bufferIndex]);
}

LN_NAMESPACE_GRAPHICS_END
LN_NAMESPACE_END
<commit_msg>comment<commit_after>/*
	[2015/7/31] コマンドの実行は仮想関数？関数ポインタ？
		Release ビルド 100000000 回の単純呼び出しで、
		仮想関数 : 450ms
		関数ポインタ : 400ms
		微々たる差だが、関数ポインタが少しだけ有利。
*/
#pragma once

#include "../Internal.h"
#include "Device/GraphicsDriverInterface.h"
#include <Lumino/Graphics/Shader.h>
#include "RenderingCommand.h"

LN_NAMESPACE_BEGIN
LN_NAMESPACE_GRAPHICS_BEGIN

//=============================================================================
// RenderingCommand
//=============================================================================
//void* RenderingCommand::operator new(size_t size, RenderingCommandList* cmmandList)
//{
//	size_t dataIdx = cmmandList->Alloc(size, NULL);
//	RenderingCommand* cmd = (RenderingCommand*)cmmandList->GetBuffer(dataIdx);
//	cmd->m_commandList = cmmandList;
//	cmmandList->m_commandList.Add(dataIdx);
//	return cmd;
//}
//
//void RenderingCommand::operator delete(void* ptr, RenderingCommandList* cmmandList)
//{
//}

//=============================================================================
// RenderingCommandList
//=============================================================================

#define CREATE_COMMAND(name) \
	size_t dataIdx = Alloc(sizeof(name##Command), NULL); \
	name##Command* cmd = (name##Command*)&(m_commandDataBuffer.GetData()[dataIdx]); \
	cmd->Type = CommandType_##name; \
	m_commandList.Add(dataIdx);

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
RenderingCommandList::RenderingCommandList()
	: m_commandList()
	, m_commandDataBuffer()
	, m_commandDataBufferUsed(0)
	, m_extDataBuffer()
	, m_extDataBufferUsed(0)
	, m_markGCList()
	, m_currentDevice(NULL)
	, m_currentRenderer(NULL)
	, m_running(false)
	, m_idling(true)
{
	m_commandList.Reserve(DataBufferReserve);	// 適当に
	m_commandDataBuffer.Resize(DataBufferReserve, false);
	m_commandDataBufferUsed = 0;
	m_extDataBuffer.Resize(DataBufferReserve, false);
	m_extDataBufferUsed = 0;
}

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
RenderingCommandList::~RenderingCommandList()
{
}

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void RenderingCommandList::Execute(Driver::IGraphicsDevice* device/*Driver::IRenderer* renderer*/)
{
	LN_RC_TRACE("RenderingCommandList::Execute() s %p %d\n", this, m_commandList.GetCount());
	// この関数は描画スレッドから呼ばれる

	m_currentDevice = device;
	m_currentRenderer = device->GetRenderer();
	LN_FOREACH(size_t dataIdx, m_commandList)
	{
		((RenderingCommand*)GetCommand(dataIdx))->Execute();
	}
	LN_RC_TRACE("RenderingCommandList::Execute() e %p\n", this);
}

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void RenderingCommandList::PostExecute()
{
	//LN_RC_TRACE("RenderingCommandList::PostExecute() s %p\n", this);
	//LN_FOREACH(size_t dataIdx, m_commandList)
	//{
	//	((RenderingCommand*)GetCommand(dataIdx))->Release(this);
	//	((RenderingCommand*)GetCommand(dataIdx))->~RenderingCommand();
	//}
	//LN_RC_TRACE("RenderingCommandList::PostExecute() e %p\n", this);
	m_commandList.Clear();
	m_commandDataBufferUsed = 0;

	LN_FOREACH(RefObject* obj, m_markGCList)
	{
		obj->Release();
	}
	m_markGCList.Clear();
}

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
RenderingCommandList::DataHandle RenderingCommandList::AllocCommand(size_t byteCount, const void* copyData)
{
	// バッファが足りなければ拡張する
	if (m_commandDataBufferUsed + byteCount > m_commandDataBuffer.GetSize()) {
		size_t newSize = m_commandDataBuffer.GetSize() + std::max(m_commandDataBuffer.GetSize(), byteCount);	// 最低でも byteCount 分を拡張する
		m_commandDataBuffer.Resize(newSize, false);
	}

	if (copyData != NULL)
	{
		byte_t* ptr = &(m_commandDataBuffer.GetData()[m_commandDataBufferUsed]);
		size_t size = m_commandDataBuffer.GetSize() - m_commandDataBufferUsed;
		memcpy_s(ptr, size, copyData, byteCount);
	}

	size_t dataIdx = m_commandDataBufferUsed;
	m_commandDataBufferUsed += byteCount;

	return dataIdx;
}

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
RenderingCommandList::DataHandle RenderingCommandList::AllocExtData(size_t byteCount, const void* copyData)
{
	// TODO: Bug: 確保メモリ量が増え続けている。

	// バッファが足りなければ拡張する
	if (m_extDataBufferUsed + byteCount > m_extDataBuffer.GetSize()) {
		size_t newSize = m_extDataBuffer.GetSize() + std::max(m_extDataBuffer.GetSize(), byteCount);	// 最低でも byteCount 分を拡張する
		m_extDataBuffer.Resize(newSize, false);
	}

	if (copyData != NULL)
	{
		byte_t* ptr = &(m_extDataBuffer.GetData()[m_extDataBufferUsed]);
		size_t size = m_extDataBuffer.GetSize() - m_extDataBufferUsed;
		memcpy_s(ptr, size, copyData, byteCount);
	}

	size_t dataIdx = m_extDataBufferUsed;
	m_extDataBufferUsed += byteCount;

	return dataIdx;
}

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void* RenderingCommandList::GetExtData(DataHandle bufferIndex)
{
	return &(m_extDataBuffer.GetData()[bufferIndex]);
}

LN_NAMESPACE_GRAPHICS_END
LN_NAMESPACE_END
<|endoftext|>


<commit_before>#include <cstdlib>
#include <string>
#include <node.h>
#include <node_buffer.h>
#include <v8.h>
#include <qrencode.h>
#include <png.h>

using namespace v8;

const unsigned int QRC_MAX_SIZE[] = { 2938, 2319, 1655, 1268 };

struct Qrc_Params {
  const char* data;
  QRecLevel ec_level;
  int dot_size;
  int margin;
  int version;

  Qrc_Params(std::string p_data, QRecLevel p_ec_level = QR_ECLEVEL_L, int p_dot_size = 3, int p_margin = 4, int p_version = 0) {
    data = new char[p_data.length() + 1];
    strcpy((char*)data, p_data.c_str());
    ec_level = p_ec_level;
    dot_size = p_dot_size;
    margin = p_margin;
    version = p_version;
  }

  ~Qrc_Params() {
    delete data;
  }
};

Qrc_Params* ValidateArgs(const Arguments& args) {
  struct Qrc_Params* params;

  if (args.Length() < 1 || !args[0]->IsString()) {
    ThrowException(Exception::TypeError(String::New("No source string given")));
    return NULL;
  }
  std::string data(*v8::String::Utf8Value(args[0]));
  if (data.length() < 1 || data.length() > QRC_MAX_SIZE[0]) {
    ThrowException(Exception::RangeError(String::New("Source string length out of range")));
    return NULL;
  }
  params = new Qrc_Params(data);

  if (args.Length() > 1) {
    if (!args[1]->IsObject()) {
      ThrowException(Exception::TypeError(String::New("Second argument must be an object")));
      delete params;
      return NULL;
    }
    Local<Object> paramsObj = Local<Object>::Cast(args[1]);
    Local<Value> paramsEcLevel = paramsObj->Get(String::New("ecLevel"));
    if (!paramsEcLevel->IsUndefined()) {
      if (!paramsEcLevel->IsInt32()) {
        ThrowException(Exception::TypeError(String::New("Wrong type for ec level")));
        delete params;
        return NULL;
      } else if (paramsEcLevel->IntegerValue() < QR_ECLEVEL_L || paramsEcLevel->IntegerValue() > QR_ECLEVEL_H) {
        ThrowException(Exception::RangeError(String::New("EC level value out of range")));
        delete params;
        return NULL;
      } else {
        params->ec_level = (QRecLevel) paramsEcLevel->IntegerValue();
        if (data.length() > QRC_MAX_SIZE[params->ec_level]) {
          ThrowException(Exception::RangeError(String::New("Source string length out of range")));
          delete params;
          return NULL;
        }
      }
    }
    Local<Value> paramsDotSize = paramsObj->Get(String::New("dotSize"));
    if (!paramsDotSize->IsUndefined()) {
      if (!paramsDotSize->IsInt32()) {
        ThrowException(Exception::TypeError(String::New("Wrong type for dot size")));
        delete params;
        return NULL;
      } else if (paramsDotSize->IntegerValue() < 1 || paramsDotSize->IntegerValue() > 50) {
        ThrowException(Exception::RangeError(String::New("Dot size out of range")));
        delete params;
        return NULL;
      } else {
        params->dot_size = paramsDotSize->IntegerValue();
      }
    }
    Local<Value> paramsMargin = paramsObj->Get(String::New("margin"));
    if (!paramsMargin->IsUndefined()) {
      if (!paramsMargin->IsInt32()) {
        ThrowException(Exception::TypeError(String::New("Wrong type for margin")));
        delete params;
        return NULL;
      } else if (paramsMargin->IntegerValue() < 0 || paramsMargin->IntegerValue() > 10) {
        ThrowException(Exception::RangeError(String::New("Margin size out of range")));
        delete params;
        return NULL;
      } else {
        params->margin = paramsMargin->IntegerValue();
      }
    }
    Local<Value> paramsVersion = paramsObj->Get(String::New("version"));
    if (!paramsVersion->IsUndefined()) {
      if (!paramsVersion->IsInt32()) {
        ThrowException(Exception::TypeError(String::New("Wrong type for version")));
        delete params;
        return NULL;
      } else if (paramsVersion->IntegerValue() < 1 || paramsVersion->IntegerValue() > QRSPEC_VERSION_MAX) {
        ThrowException(Exception::RangeError(String::New("Version number out of range")));
        delete params;
        return NULL;
      } else {
        params->version = paramsVersion->IntegerValue();
      }
    }
  }

  return params;
}

QRcode* Encode(Qrc_Params* params) {
  QRcode* code;
  code = QRcode_encodeString8bit((const char*)params->data, params->version, params->ec_level);
  return code;
}

Handle<Value> EncodeBuf(const Arguments& args) {
  HandleScope scope;
  Local<Object> codeObj = Object::New();

  Qrc_Params* params = ValidateArgs(args);
  if (!params) {
    return scope.Close(codeObj);
  }

  QRcode* code = Encode(params);
  delete params;
  if (code != NULL) {
    Local<node::Buffer> buffer = node::Buffer::New((const char*)code->data, code->width * code->width);
    codeObj->Set(String::NewSymbol("width"), Integer::New(code->width));
    codeObj->Set(String::NewSymbol("version"), Integer::New(code->version));
    codeObj->Set(String::NewSymbol("data"), buffer->handle_);
    QRcode_free(code);
  }
  return scope.Close(codeObj);
}

Handle<Value> EncodePNG(const Arguments& args) {
  HandleScope scope;
  Local<Object> obj = Object::New();

  Qrc_Params* params = ValidateArgs(args);
  if (!params) {
    return scope.Close(obj);
  }

  QRcode* code = Encode(params);

  if (code != NULL) {
    char* bp;
    size_t size;
    FILE* stream;

    png_structp png_ptr;
    png_infop info_ptr;

    stream = open_memstream(&bp, &size);
    if (stream == NULL) {
      delete params;
      return scope.Close(obj);
    }

    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
        NULL, NULL, NULL);
    if (!png_ptr) {
      delete params;
      return scope.Close(obj);
    }

    info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr) {
      png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
      delete params;
      return scope.Close(obj);
    }

    if (setjmp(png_jmpbuf(png_ptr))) {
      png_destroy_write_struct(&png_ptr, &info_ptr);
      delete params;
      return scope.Close(obj);
    }

    png_init_io(png_ptr, stream);

    png_set_IHDR(png_ptr, info_ptr, (code->width + params->margin * 2) * params->dot_size, (code->width + params->margin * 2) * params->dot_size, 1,
        PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
        PNG_FILTER_TYPE_DEFAULT);

    png_set_invert_mono(png_ptr);
    png_write_info(png_ptr, info_ptr);

    png_set_packing(png_ptr);

    unsigned char* row = new unsigned char[(code->width + params->margin * 2) * params->dot_size];

    for (int y = -(params->margin); y < code->width + params->margin; y++) {
      for (int x = -(params->margin * params->dot_size); x < (code->width + params->margin) * params->dot_size; x += params->dot_size) {
        for (int d = 0; d < params->dot_size; d++) {
          if (y < 0 || y > code->width - 1 || x < 0 || x > ((code->width - 1) * params->dot_size)) {
            row[x + params->margin * params->dot_size + d] = 0;
          } else {
            row[x + params->margin * params->dot_size + d] = code->data[y * code->width + x/params->dot_size] << 7;
          }
        }
      }
      for (int d = 0; d < params->dot_size; d++) {
        png_write_row(png_ptr, row);
      }
    }

    png_write_end(png_ptr, info_ptr);
    png_destroy_write_struct(&png_ptr, &info_ptr);

    fclose(stream);

    delete[] row;

    Local<node::Buffer> buffer = node::Buffer::New(bp, size);
    obj->Set(String::NewSymbol("width"), Integer::New(code->width));
    obj->Set(String::NewSymbol("version"), Integer::New(code->version));
    obj->Set(String::NewSymbol("data"), buffer->handle_);
    QRcode_free(code);
    free(bp);
  }
  delete params;
  return scope.Close(obj);
}

void init(Handle<Object> exports) {
  exports->Set(String::NewSymbol("encode"),
      FunctionTemplate::New(EncodeBuf)->GetFunction());
  exports->Set(String::NewSymbol("encodePng"),
      FunctionTemplate::New(EncodePNG)->GetFunction());
}

NODE_MODULE(qrc, init)
<commit_msg>Make memory buffering portable<commit_after>#include <cstdlib>
#include <string>
#include <node.h>
#include <node_buffer.h>
#include <v8.h>
#include <qrencode.h>
#include <png.h>

using namespace v8;

const unsigned int QRC_MAX_SIZE[] = { 2938, 2319, 1655, 1268 };

struct Qrc_Params {
  const char* data;
  QRecLevel ec_level;
  int dot_size;
  int margin;
  int version;

  Qrc_Params(std::string p_data, QRecLevel p_ec_level = QR_ECLEVEL_L, int p_dot_size = 3, int p_margin = 4, int p_version = 0) {
    data = new char[p_data.length() + 1];
    strcpy((char*)data, p_data.c_str());
    ec_level = p_ec_level;
    dot_size = p_dot_size;
    margin = p_margin;
    version = p_version;
  }

  ~Qrc_Params() {
    delete data;
  }
};

struct Qrc_Png_Buffer {
  char *data;
  size_t size;
  Qrc_Png_Buffer() {
    data = NULL;
    size = 0;
  }
  ~Qrc_Png_Buffer() {
    if (data) {
      free(data);
    }
  }
};

Qrc_Params* ValidateArgs(const Arguments& args) {
  struct Qrc_Params* params;

  if (args.Length() < 1 || !args[0]->IsString()) {
    ThrowException(Exception::TypeError(String::New("No source string given")));
    return NULL;
  }
  std::string data(*v8::String::Utf8Value(args[0]));
  if (data.length() < 1 || data.length() > QRC_MAX_SIZE[0]) {
    ThrowException(Exception::RangeError(String::New("Source string length out of range")));
    return NULL;
  }
  params = new Qrc_Params(data);

  if (args.Length() > 1) {
    if (!args[1]->IsObject()) {
      ThrowException(Exception::TypeError(String::New("Second argument must be an object")));
      delete params;
      return NULL;
    }
    Local<Object> paramsObj = Local<Object>::Cast(args[1]);
    Local<Value> paramsEcLevel = paramsObj->Get(String::New("ecLevel"));
    if (!paramsEcLevel->IsUndefined()) {
      if (!paramsEcLevel->IsInt32()) {
        ThrowException(Exception::TypeError(String::New("Wrong type for ec level")));
        delete params;
        return NULL;
      } else if (paramsEcLevel->IntegerValue() < QR_ECLEVEL_L || paramsEcLevel->IntegerValue() > QR_ECLEVEL_H) {
        ThrowException(Exception::RangeError(String::New("EC level value out of range")));
        delete params;
        return NULL;
      } else {
        params->ec_level = (QRecLevel) paramsEcLevel->IntegerValue();
        if (data.length() > QRC_MAX_SIZE[params->ec_level]) {
          ThrowException(Exception::RangeError(String::New("Source string length out of range")));
          delete params;
          return NULL;
        }
      }
    }
    Local<Value> paramsDotSize = paramsObj->Get(String::New("dotSize"));
    if (!paramsDotSize->IsUndefined()) {
      if (!paramsDotSize->IsInt32()) {
        ThrowException(Exception::TypeError(String::New("Wrong type for dot size")));
        delete params;
        return NULL;
      } else if (paramsDotSize->IntegerValue() < 1 || paramsDotSize->IntegerValue() > 50) {
        ThrowException(Exception::RangeError(String::New("Dot size out of range")));
        delete params;
        return NULL;
      } else {
        params->dot_size = paramsDotSize->IntegerValue();
      }
    }
    Local<Value> paramsMargin = paramsObj->Get(String::New("margin"));
    if (!paramsMargin->IsUndefined()) {
      if (!paramsMargin->IsInt32()) {
        ThrowException(Exception::TypeError(String::New("Wrong type for margin")));
        delete params;
        return NULL;
      } else if (paramsMargin->IntegerValue() < 0 || paramsMargin->IntegerValue() > 10) {
        ThrowException(Exception::RangeError(String::New("Margin size out of range")));
        delete params;
        return NULL;
      } else {
        params->margin = paramsMargin->IntegerValue();
      }
    }
    Local<Value> paramsVersion = paramsObj->Get(String::New("version"));
    if (!paramsVersion->IsUndefined()) {
      if (!paramsVersion->IsInt32()) {
        ThrowException(Exception::TypeError(String::New("Wrong type for version")));
        delete params;
        return NULL;
      } else if (paramsVersion->IntegerValue() < 1 || paramsVersion->IntegerValue() > QRSPEC_VERSION_MAX) {
        ThrowException(Exception::RangeError(String::New("Version number out of range")));
        delete params;
        return NULL;
      } else {
        params->version = paramsVersion->IntegerValue();
      }
    }
  }

  return params;
}

QRcode* Encode(Qrc_Params* params) {
  QRcode* code;
  code = QRcode_encodeString8bit((const char*)params->data, params->version, params->ec_level);
  return code;
}

Handle<Value> EncodeBuf(const Arguments& args) {
  HandleScope scope;
  Local<Object> codeObj = Object::New();

  Qrc_Params* params = ValidateArgs(args);
  if (!params) {
    return scope.Close(codeObj);
  }

  QRcode* code = Encode(params);
  delete params;
  if (code != NULL) {
    Local<node::Buffer> buffer = node::Buffer::New((const char*)code->data, code->width * code->width);
    codeObj->Set(String::NewSymbol("width"), Integer::New(code->width));
    codeObj->Set(String::NewSymbol("version"), Integer::New(code->version));
    codeObj->Set(String::NewSymbol("data"), buffer->handle_);
    QRcode_free(code);
  }
  return scope.Close(codeObj);
}

void Qrc_png_write_buffer(png_structp png_ptr, png_bytep data, png_size_t length) {
  Qrc_Png_Buffer* b = (Qrc_Png_Buffer *)png_get_io_ptr(png_ptr);
  size_t nsize = b->size + length;

  if (b->data) {
    b->data = (char *)realloc(b->data, nsize);
  } else {
    b->data = (char *)malloc(nsize);
  }

  if (!b->data) {
    png_error(png_ptr, "Write Error");
  }

  memcpy(b->data + b->size, data, length);
  b->size += length;
}

Handle<Value> EncodePNG(const Arguments& args) {
  HandleScope scope;
  Local<Object> obj = Object::New();

  Qrc_Params* params = ValidateArgs(args);
  if (!params) {
    return scope.Close(obj);
  }

  QRcode* code = Encode(params);

  if (code != NULL) {
    Qrc_Png_Buffer* bp = new Qrc_Png_Buffer();

    png_structp png_ptr;
    png_infop info_ptr;

    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
        NULL, NULL, NULL);
    if (!png_ptr) {
      delete params;
      return scope.Close(obj);
    }

    info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr) {
      png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
      delete params;
      return scope.Close(obj);
    }

    if (setjmp(png_jmpbuf(png_ptr))) {
      png_destroy_write_struct(&png_ptr, &info_ptr);
      delete params;
      return scope.Close(obj);
    }

    png_set_write_fn(png_ptr, bp, Qrc_png_write_buffer, NULL);

    png_set_IHDR(png_ptr, info_ptr, (code->width + params->margin * 2) * params->dot_size, (code->width + params->margin * 2) * params->dot_size, 1,
        PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
        PNG_FILTER_TYPE_DEFAULT);

    png_set_invert_mono(png_ptr);
    png_write_info(png_ptr, info_ptr);

    png_set_packing(png_ptr);

    unsigned char* row = new unsigned char[(code->width + params->margin * 2) * params->dot_size];

    for (int y = -(params->margin); y < code->width + params->margin; y++) {
      for (int x = -(params->margin * params->dot_size); x < (code->width + params->margin) * params->dot_size; x += params->dot_size) {
        for (int d = 0; d < params->dot_size; d++) {
          if (y < 0 || y > code->width - 1 || x < 0 || x > ((code->width - 1) * params->dot_size)) {
            row[x + params->margin * params->dot_size + d] = 0;
          } else {
            row[x + params->margin * params->dot_size + d] = code->data[y * code->width + x/params->dot_size] << 7;
          }
        }
      }
      for (int d = 0; d < params->dot_size; d++) {
        png_write_row(png_ptr, row);
      }
    }

    png_write_end(png_ptr, info_ptr);
    png_destroy_write_struct(&png_ptr, &info_ptr);

    delete[] row;

    Local<node::Buffer> buffer = node::Buffer::New(bp->data, bp->size);
    obj->Set(String::NewSymbol("width"), Integer::New(code->width));
    obj->Set(String::NewSymbol("version"), Integer::New(code->version));
    obj->Set(String::NewSymbol("data"), buffer->handle_);
    QRcode_free(code);
    delete bp;
  }
  delete params;
  return scope.Close(obj);
}

void init(Handle<Object> exports) {
  exports->Set(String::NewSymbol("encode"),
      FunctionTemplate::New(EncodeBuf)->GetFunction());
  exports->Set(String::NewSymbol("encodePng"),
      FunctionTemplate::New(EncodePNG)->GetFunction());
}

NODE_MODULE(qrc, init)
<|endoftext|>


<commit_before>/*
 * Copyright 2017 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "ok.h"
#include "SkSurface.h"

struct SWDst : Dst {
    SkImageInfo      info;
    sk_sp<SkSurface> surface;

    static std::unique_ptr<Dst> Create(Options options) {
        SkImageInfo info = SkImageInfo::MakeN32Premul(0,0);
        if (options("ct") == "565") { info = info.makeColorType(kRGB_565_SkColorType); }
        if (options("ct") == "f16") { info = info.makeColorType(kRGBA_F16_SkColorType); }

        SWDst dst;
        dst.info = info;
        return move_unique(dst);
    }

    Status draw(Src* src) override {
        auto size = src->size();
        surface = SkSurface::MakeRaster(info.makeWH(size.width(), size.height()));
        return src->draw(surface->getCanvas());
    }

    sk_sp<SkImage> image() override {
        return surface->makeImageSnapshot();
    }
};
static Register sw{"sw", "draw with the software backend", SWDst::Create};

static Register _565{"565", "alias for sw:ct=565", [](Options options) {
    options["ct"] = "565";
    return SWDst::Create(options);
}};
<commit_msg>ok, add sRGB support<commit_after>/*
 * Copyright 2017 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "ok.h"
#include "SkSurface.h"

struct SWDst : Dst {
    SkImageInfo      info;
    sk_sp<SkSurface> surface;

    static std::unique_ptr<Dst> Create(Options options) {
        SkImageInfo info = SkImageInfo::MakeN32Premul(0,0);
        if (options("ct") == "565") { info = info.makeColorType(kRGB_565_SkColorType); }
        if (options("ct") == "f16") { info = info.makeColorType(kRGBA_F16_SkColorType); }

        if (options("cs") == "srgb") {
            auto cs = info.colorType() == kRGBA_F16_SkColorType ? SkColorSpace::MakeSRGBLinear()
                                                                : SkColorSpace::MakeSRGB();
            info = info.makeColorSpace(std::move(cs));
        }

        SWDst dst;
        dst.info = info;
        return move_unique(dst);
    }

    Status draw(Src* src) override {
        auto size = src->size();
        surface = SkSurface::MakeRaster(info.makeWH(size.width(), size.height()));
        return src->draw(surface->getCanvas());
    }

    sk_sp<SkImage> image() override {
        return surface->makeImageSnapshot();
    }
};
static Register sw{"sw", "draw with the software backend", SWDst::Create};

static Register _565{"565", "alias for sw:ct=565", [](Options options) {
    options["ct"] = "565";
    return SWDst::Create(options);
}};

static Register srgb{"srgb", "alias for sw:cs=srgb", [](Options options) {
    options["cs"] = "srgb";
    return SWDst::Create(options);
}};

static Register f16{"f16", "alias for sw:ct=f16,cs=srgb", [](Options options) {
    options["ct"] = "f16";
    options["cs"] = "srgb";
    return SWDst::Create(options);
}};
<|endoftext|>


<commit_before>/*
 * Renderer.cpp
 *
 *  Created on: 2012-12-02
 *      Author: Nathan
 */

#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include "Renderer.h"
#include "Shaders/shaders.h"

Shader* shader;
glm::mat4 projection;

Renderer::Renderer(int width, int height) {
    this->height = height;
    this->width = width;
    std::cout << matrixStack.size() << std::endl;
    matrixStack.push_back(glm::mat4(1.0f));
    std::cout << matrixStack.size() << std::endl;
    loadShader("");
    useShader(0);
    uniforms.projection = setUniform("uprojection");
    uniforms.camera = setUniform("ucamera");
    uniforms.model = setUniform("umodel");
    uniforms.color = setUniform("ucolor");

    glm::mat4 projection = setProjection(width, height);
}

void Renderer::loadShader(const std::string &name){
    shader = new Shader("res/shaders/vert.glsl", "res/shaders/frag.glsl", width, height);
}

glm::vec3 Renderer::unProject(int x, int y, double z){
    glm::ivec4 viewport;
    glGetIntegerv(GL_VIEWPORT, glm::value_ptr(viewport));
    /*double mv[16], p[16];
      for(int i = 0; i < 16; i++){
      mv[i] = (double)(currentMatrix()).m[i];
      p[i] = (double)projection.m[i];
      }
      double wx = x, wy = y, wz = z;
      double vx = -1, vy = -1, vz = 0-1;
      gluUnProject(wx, wy, wz, mv, p, viewport, &vx, &vy, &vz);
      return glm::vec3(vx, vy, vz); */
    return glm::unProject(glm::vec3(x, y, z), currentMatrix(), projection, viewport);
}

void Renderer::setColor(float r, float g, float b, float a){
    glUniform4f(uniforms.color, r, g, b, a);
}

glm::vec3 Renderer::getCursorPos(int x, int y){
    pushMatrix();
    glm::vec3 p0 = unProject(x, y, 0.0);
    glm::vec3 p1 = unProject(x, y, 1.0);
    float u = -p0.z/(p1.z - p0.z);
    popMatrix();
    return p0 + (p1 - p0)*u;
}

void Renderer::loadFont(const std::string &name){
    _font.reset(new Font(name));
}

void Renderer::bindTexture(int texture){
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture);
    glUniform1i(uniforms.texture, 0);
}

GLuint Renderer::makeBuffer(GLenum target, const void *buffer_data, GLsizei buffer_size){
    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(target, vbo);
    glBufferData(target, buffer_size, buffer_data, GL_STATIC_DRAW);
    return vbo;
}

void Renderer::drawVertexArray(const std::vector<float> &vertices){
    GLuint vbo = makeBuffer(GL_ARRAY_BUFFER, &vertices[0], vertices.size());
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glEnableVertexAttribArray(0);
    /*
       glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
       glDrawArrays(GL_TRIANGLES, 0, vertices.size()/4);
       glDisableVertexAttribArray(0);
       */
}

void Renderer::renderString(glm::vec3 pos, const std::string &text){
    pushMatrix();
    for(unsigned i = 0; i < text.size(); ++i){
        Glyph g = _font->getGlyph(text[i]);
        float x = pos.x + g.left;
        float y = pos.y + g.top;
        float w = g.w;
        float h = g.h;
        glEnable(GL_TEXTURE);
        bindTexture(g.texture);
        glBegin(GL_QUADS);
        glVertex3f(x - w, y - h, 0);
        glVertex3f(x + w, y - h, 0);
        glVertex3f(x - w, y + h, 0);
        glVertex3f(x + w, y + h, 0);
        glEnd();
        //          glBufferData(GL_ARRAY_BUFFER, sizeof (box), box, GL_DYNAMIC_DRAW);
        //          glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        pos.x += (g.adv);
    }
    popMatrix();
}

#define NEAR_PLANE 0.0625f
#define FAR_PLANE 256.0f

glm::mat4 Renderer::setProjection(int width, int height){
    float aspectRatio = static_cast<float>(width) / static_cast<float>(height);
    projection = glm::perspective(glm::radians(45.f), aspectRatio, NEAR_PLANE, FAR_PLANE);
    glUniformMatrix4fv(uniforms.projection, 1, GL_FALSE, glm::value_ptr(projection));
    return projection;
}

void Renderer::uploadModelView(){
    glUniformMatrix4fv(uniforms.model, 1, GL_FALSE, glm::value_ptr(currentMatrix()));
}

void Renderer::setCamera(float x, float y, float z){
    camera = glm::translate(glm::mat4(1.f), -glm::vec3(x, y, z));
    glUniformMatrix4fv(uniforms.camera, 1, GL_FALSE, glm::value_ptr(camera));
}

void Renderer::pushMatrix(){
    matrixStack.push_back(matrixStack.back());
    uploadModelView();
}

void Renderer::popMatrix(){
    if(matrixStack.size() > 1) {
        matrixStack.pop_back();
        uploadModelView();
    }
}

glm::mat4 Renderer::translate(float x, float y, float z){
    glm::mat4 t = glm::translate(glm::mat4(1.f), glm::vec3(x, y, z));
    matrixStack.back() = matrixStack.back() * t;
    uploadModelView();
    return matrixStack.back();
}

glm::mat4 Renderer::rotate(const glm::vec3 &from, const glm::vec3 &to){
    auto q = glm::quat( from, to );
    auto m = glm::toMat4( q );
    matrixStack.back() = matrixStack.back() * m;
    uploadModelView();
    return matrixStack.back();
}

glm::mat4 Renderer::rotate(float angle, float x, float y, float z){
    glm::mat4 t = glm::rotate(glm::mat4(1.f), angle, glm::vec3(x, y, z));
    matrixStack.back() = matrixStack.back() * t;
    uploadModelView();
    return matrixStack.back();
}

glm::mat4 Renderer::scale(float x, float y, float z){
    glm::mat4 t = glm::scale(
            glm::mat4(1.0f),
            glm::vec3(x, y, z));
    matrixStack.back() = matrixStack.back() * t;
    uploadModelView();
    return matrixStack.back();
}

glm::mat4& Renderer::currentMatrix(){
    return matrixStack.back();
}

void Renderer::loadIdentity(){

}

GLuint Renderer::setUniform(const std::string &name){
    return shader->setUniform(name);
}

void Renderer::useShader(int id){
    shader->enable();
}

void Renderer::disableShader(){
    shader->disable();
}

Renderer::~Renderer() {}
<commit_msg>Delete commented code<commit_after>/*
 * Renderer.cpp
 *
 *  Created on: 2012-12-02
 *      Author: Nathan
 */

#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include "Renderer.h"
#include "Shaders/shaders.h"

Shader* shader;
glm::mat4 projection;

Renderer::Renderer(int width, int height) {
    this->height = height;
    this->width = width;
    std::cout << matrixStack.size() << std::endl;
    matrixStack.push_back(glm::mat4(1.0f));
    std::cout << matrixStack.size() << std::endl;
    loadShader("");
    useShader(0);
    uniforms.projection = setUniform("uprojection");
    uniforms.camera = setUniform("ucamera");
    uniforms.model = setUniform("umodel");
    uniforms.color = setUniform("ucolor");

    glm::mat4 projection = setProjection(width, height);
}

void Renderer::loadShader(const std::string &name){
    shader = new Shader("res/shaders/vert.glsl", "res/shaders/frag.glsl", width, height);
}

glm::vec3 Renderer::unProject(int x, int y, double z){
    glm::ivec4 viewport;
    glGetIntegerv(GL_VIEWPORT, glm::value_ptr(viewport));
    return glm::unProject(glm::vec3(x, y, z), currentMatrix(), projection, viewport);
}

void Renderer::setColor(float r, float g, float b, float a){
    glUniform4f(uniforms.color, r, g, b, a);
}

glm::vec3 Renderer::getCursorPos(int x, int y){
    pushMatrix();
    glm::vec3 p0 = unProject(x, y, 0.0);
    glm::vec3 p1 = unProject(x, y, 1.0);
    float u = -p0.z/(p1.z - p0.z);
    popMatrix();
    return p0 + (p1 - p0)*u;
}

void Renderer::loadFont(const std::string &name){
    _font.reset(new Font(name));
}

void Renderer::bindTexture(int texture){
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture);
    glUniform1i(uniforms.texture, 0);
}

GLuint Renderer::makeBuffer(GLenum target, const void *buffer_data, GLsizei buffer_size){
    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(target, vbo);
    glBufferData(target, buffer_size, buffer_data, GL_STATIC_DRAW);
    return vbo;
}

void Renderer::drawVertexArray(const std::vector<float> &vertices){
    GLuint vbo = makeBuffer(GL_ARRAY_BUFFER, &vertices[0], vertices.size());
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glEnableVertexAttribArray(0);
    /*
       glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
       glDrawArrays(GL_TRIANGLES, 0, vertices.size()/4);
       glDisableVertexAttribArray(0);
       */
}

void Renderer::renderString(glm::vec3 pos, const std::string &text){
    pushMatrix();
    for(unsigned i = 0; i < text.size(); ++i){
        Glyph g = _font->getGlyph(text[i]);
        float x = pos.x + g.left;
        float y = pos.y + g.top;
        float w = g.w;
        float h = g.h;
        glEnable(GL_TEXTURE);
        bindTexture(g.texture);
        glBegin(GL_QUADS);
        glVertex3f(x - w, y - h, 0);
        glVertex3f(x + w, y - h, 0);
        glVertex3f(x - w, y + h, 0);
        glVertex3f(x + w, y + h, 0);
        glEnd();
        //          glBufferData(GL_ARRAY_BUFFER, sizeof (box), box, GL_DYNAMIC_DRAW);
        //          glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        pos.x += (g.adv);
    }
    popMatrix();
}

#define NEAR_PLANE 0.0625f
#define FAR_PLANE 256.0f

glm::mat4 Renderer::setProjection(int width, int height){
    float aspectRatio = static_cast<float>(width) / static_cast<float>(height);
    projection = glm::perspective(glm::radians(45.f), aspectRatio, NEAR_PLANE, FAR_PLANE);
    glUniformMatrix4fv(uniforms.projection, 1, GL_FALSE, glm::value_ptr(projection));
    return projection;
}

void Renderer::uploadModelView(){
    glUniformMatrix4fv(uniforms.model, 1, GL_FALSE, glm::value_ptr(currentMatrix()));
}

void Renderer::setCamera(float x, float y, float z){
    camera = glm::translate(glm::mat4(1.f), -glm::vec3(x, y, z));
    glUniformMatrix4fv(uniforms.camera, 1, GL_FALSE, glm::value_ptr(camera));
}

void Renderer::pushMatrix(){
    matrixStack.push_back(matrixStack.back());
    uploadModelView();
}

void Renderer::popMatrix(){
    if(matrixStack.size() > 1) {
        matrixStack.pop_back();
        uploadModelView();
    }
}

glm::mat4 Renderer::translate(float x, float y, float z){
    glm::mat4 t = glm::translate(glm::mat4(1.f), glm::vec3(x, y, z));
    matrixStack.back() = matrixStack.back() * t;
    uploadModelView();
    return matrixStack.back();
}

glm::mat4 Renderer::rotate(const glm::vec3 &from, const glm::vec3 &to){
    auto q = glm::quat( from, to );
    auto m = glm::toMat4( q );
    matrixStack.back() = matrixStack.back() * m;
    uploadModelView();
    return matrixStack.back();
}

glm::mat4 Renderer::rotate(float angle, float x, float y, float z){
    glm::mat4 t = glm::rotate(glm::mat4(1.f), angle, glm::vec3(x, y, z));
    matrixStack.back() = matrixStack.back() * t;
    uploadModelView();
    return matrixStack.back();
}

glm::mat4 Renderer::scale(float x, float y, float z){
    glm::mat4 t = glm::scale(
            glm::mat4(1.0f),
            glm::vec3(x, y, z));
    matrixStack.back() = matrixStack.back() * t;
    uploadModelView();
    return matrixStack.back();
}

glm::mat4& Renderer::currentMatrix(){
    return matrixStack.back();
}

void Renderer::loadIdentity(){

}

GLuint Renderer::setUniform(const std::string &name){
    return shader->setUniform(name);
}

void Renderer::useShader(int id){
    shader->enable();
}

void Renderer::disableShader(){
    shader->disable();
}

Renderer::~Renderer() {}
<|endoftext|>