<commit_before>/*
 * Copyright (C) 2011, British Broadcasting Corporation
 * All Rights Reserved.
 *
 * Author: Philip de Nier
 *
 * 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 British Broadcasting Corporation 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.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "bmx_scm_version.h"

#include <cstdio>
#include <cstring>
#include <ctime>

#include <bmx/Version.h>
#include <bmx/Utils.h>

using namespace std;
using namespace bmx;

namespace bmx
{
bool BMX_REGRESSION_TEST = false;
};

static const char* BMX_COMPANY_NAME = "BBC";
static const bmx::UUID BMX_PRODUCT_UID =
    {0xb8, 0x60, 0x4d, 0x31, 0x2e, 0x15, 0x47, 0x99, 0xa3, 0xc6, 0x04, 0x7e, 0xd0, 0xe6, 0xf9, 0xa1};
static const mxfProductVersion BMX_MXF_PRODUCT_VERSION = {BMX_VERSION_MAJOR,
                                                          BMX_VERSION_MINOR,
                                                          BMX_VERSION_MICRO,
                                                          0,
                                                          BMX_MXF_VERSION_RELEASE};

static const bmx::UUID REGTEST_PRODUCT_UID =
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const mxfProductVersion REGTEST_MXF_PRODUCT_VERSION = {1, 0, 0, 0, 0};

string bmx::get_bmx_library_name()
{
    if (BMX_REGRESSION_TEST)
        return "RegLib";
    else
        return BMX_LIBRARY_NAME;
}

string bmx::get_bmx_version_string()
{
    if (BMX_REGRESSION_TEST) {
        return "0.0.0";
    } else {
        char buffer[32];
        bmx_snprintf(buffer, sizeof(buffer), "%d.%d.%d", BMX_VERSION_MAJOR, BMX_VERSION_MINOR, BMX_VERSION_MICRO);
        return buffer;
    }
}

string bmx::get_bmx_scm_version_string()
{
    if (BMX_REGRESSION_TEST)
        return "regtest-head";
    else
        return BMX_SCM_VERSION;
}

string bmx::get_bmx_build_string()
{
    if (BMX_REGRESSION_TEST)
        return "1970-01-01 00:00:00";
    else
        return __DATE__ " " __TIME__;
}

Timestamp bmx::get_bmx_build_timestamp()
{
    static const char* month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
                                        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

    Timestamp timestamp;
    memset(&timestamp, 0, sizeof(timestamp));

    if (BMX_REGRESSION_TEST) {
        timestamp.year  = 1970;
        timestamp.month = 1;
        timestamp.day   = 1;
        timestamp.hour  = 0;
        timestamp.min   = 0;
        timestamp.sec   = 0;
        timestamp.qmsec = 0;
        return timestamp;
    }

    const char *date_str = __DATE__;
    const char *time_str = __TIME__;
    if (strlen(date_str) < 11 || strlen(time_str) < 8)
        return timestamp;

    struct tm build_ltm;

    // date: Mmm dd yyyy
    int i;
    for (i = 0; i < 12; i++) {
        if (strncmp(month_names[i], date_str, 3) == 0)
            break;
    }
    if (i >= 12)
        return timestamp;
    build_ltm.tm_mon = i;
    if (sscanf(&date_str[4], "%d %d", &build_ltm.tm_mday, &build_ltm.tm_year) != 2)
        return timestamp;
    build_ltm.tm_year -= 1900;

    // time: hh:mm:ss
    if (sscanf(time_str, "%d:%d:%d", &build_ltm.tm_hour, &build_ltm.tm_min, &build_ltm.tm_sec) != 3)
        return timestamp;

    time_t build_ltt = mktime(&build_ltm);

    struct tm build_gmt;
#if HAVE_GMTIME_R
    if (!gmtime_r(&build_ltt, &build_gmt))
        return timestamp;
#elif defined(_MSC_VER)
    if (gmtime_s(&build_gmt, &build_ltt) != 0)
        return timestamp;
#else
    const struct tm *gmt_ptr = gmtime(&build_ltt);
    if (!gmt_ptr)
        return timestamp;
    build_gmt = *gmt_ptr;
#endif

    timestamp.year  = build_gmt.tm_year + 1900;
    timestamp.month = build_gmt.tm_mon + 1;
    timestamp.day   = build_gmt.tm_mday;
    timestamp.hour  = build_gmt.tm_hour;
    timestamp.min   = build_gmt.tm_min;
    timestamp.sec   = build_gmt.tm_sec;
    timestamp.qmsec = 0;

    return timestamp;
}

string bmx::get_bmx_company_name()
{
    if (BMX_REGRESSION_TEST)
        return "RegCo";
    else
        return BMX_COMPANY_NAME;
}

bmx::UUID bmx::get_bmx_product_uid()
{
    if (BMX_REGRESSION_TEST)
        return REGTEST_PRODUCT_UID;
    else
        return BMX_PRODUCT_UID;
}

mxfProductVersion bmx::get_bmx_mxf_product_version()
{
    if (BMX_REGRESSION_TEST)
        return REGTEST_MXF_PRODUCT_VERSION;
    else
        return BMX_MXF_PRODUCT_VERSION;
}

string bmx::get_bmx_mxf_version_string()
{
    if (BMX_REGRESSION_TEST) {
        return "0.0.0";
    } else {
        char buffer[64];
        bmx_snprintf(buffer, sizeof(buffer), "%d.%d.%d (scm %s)",
                     BMX_VERSION_MAJOR, BMX_VERSION_MINOR, BMX_VERSION_MICRO,
                     BMX_SCM_VERSION);
        return buffer;
    }
}

<commit_msg>init time struct to avoid uninitialised use<commit_after>/*
 * Copyright (C) 2011, British Broadcasting Corporation
 * All Rights Reserved.
 *
 * Author: Philip de Nier
 *
 * 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 British Broadcasting Corporation 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.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "bmx_scm_version.h"

#include <cstdio>
#include <cstring>
#include <ctime>

#include <bmx/Version.h>
#include <bmx/Utils.h>

using namespace std;
using namespace bmx;

namespace bmx
{
bool BMX_REGRESSION_TEST = false;
};

static const char* BMX_COMPANY_NAME = "BBC";
static const bmx::UUID BMX_PRODUCT_UID =
    {0xb8, 0x60, 0x4d, 0x31, 0x2e, 0x15, 0x47, 0x99, 0xa3, 0xc6, 0x04, 0x7e, 0xd0, 0xe6, 0xf9, 0xa1};
static const mxfProductVersion BMX_MXF_PRODUCT_VERSION = {BMX_VERSION_MAJOR,
                                                          BMX_VERSION_MINOR,
                                                          BMX_VERSION_MICRO,
                                                          0,
                                                          BMX_MXF_VERSION_RELEASE};

static const bmx::UUID REGTEST_PRODUCT_UID =
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const mxfProductVersion REGTEST_MXF_PRODUCT_VERSION = {1, 0, 0, 0, 0};

string bmx::get_bmx_library_name()
{
    if (BMX_REGRESSION_TEST)
        return "RegLib";
    else
        return BMX_LIBRARY_NAME;
}

string bmx::get_bmx_version_string()
{
    if (BMX_REGRESSION_TEST) {
        return "0.0.0";
    } else {
        char buffer[32];
        bmx_snprintf(buffer, sizeof(buffer), "%d.%d.%d", BMX_VERSION_MAJOR, BMX_VERSION_MINOR, BMX_VERSION_MICRO);
        return buffer;
    }
}

string bmx::get_bmx_scm_version_string()
{
    if (BMX_REGRESSION_TEST)
        return "regtest-head";
    else
        return BMX_SCM_VERSION;
}

string bmx::get_bmx_build_string()
{
    if (BMX_REGRESSION_TEST)
        return "1970-01-01 00:00:00";
    else
        return __DATE__ " " __TIME__;
}

Timestamp bmx::get_bmx_build_timestamp()
{
    static const char* month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
                                        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

    Timestamp timestamp;
    memset(&timestamp, 0, sizeof(timestamp));

    if (BMX_REGRESSION_TEST) {
        timestamp.year  = 1970;
        timestamp.month = 1;
        timestamp.day   = 1;
        timestamp.hour  = 0;
        timestamp.min   = 0;
        timestamp.sec   = 0;
        timestamp.qmsec = 0;
        return timestamp;
    }

    const char *date_str = __DATE__;
    const char *time_str = __TIME__;
    if (strlen(date_str) < 11 || strlen(time_str) < 8)
        return timestamp;

    struct tm build_ltm;
    memset(&build_ltm, 0, sizeof(build_ltm));

    // date: Mmm dd yyyy
    int i;
    for (i = 0; i < 12; i++) {
        if (strncmp(month_names[i], date_str, 3) == 0)
            break;
    }
    if (i >= 12)
        return timestamp;
    build_ltm.tm_mon = i;
    if (sscanf(&date_str[4], "%d %d", &build_ltm.tm_mday, &build_ltm.tm_year) != 2)
        return timestamp;
    build_ltm.tm_year -= 1900;

    // time: hh:mm:ss
    if (sscanf(time_str, "%d:%d:%d", &build_ltm.tm_hour, &build_ltm.tm_min, &build_ltm.tm_sec) != 3)
        return timestamp;

    time_t build_ltt = mktime(&build_ltm);

    struct tm build_gmt;
#if HAVE_GMTIME_R
    if (!gmtime_r(&build_ltt, &build_gmt))
        return timestamp;
#elif defined(_MSC_VER)
    if (gmtime_s(&build_gmt, &build_ltt) != 0)
        return timestamp;
#else
    const struct tm *gmt_ptr = gmtime(&build_ltt);
    if (!gmt_ptr)
        return timestamp;
    build_gmt = *gmt_ptr;
#endif

    timestamp.year  = build_gmt.tm_year + 1900;
    timestamp.month = build_gmt.tm_mon + 1;
    timestamp.day   = build_gmt.tm_mday;
    timestamp.hour  = build_gmt.tm_hour;
    timestamp.min   = build_gmt.tm_min;
    timestamp.sec   = build_gmt.tm_sec;
    timestamp.qmsec = 0;

    return timestamp;
}

string bmx::get_bmx_company_name()
{
    if (BMX_REGRESSION_TEST)
        return "RegCo";
    else
        return BMX_COMPANY_NAME;
}

bmx::UUID bmx::get_bmx_product_uid()
{
    if (BMX_REGRESSION_TEST)
        return REGTEST_PRODUCT_UID;
    else
        return BMX_PRODUCT_UID;
}

mxfProductVersion bmx::get_bmx_mxf_product_version()
{
    if (BMX_REGRESSION_TEST)
        return REGTEST_MXF_PRODUCT_VERSION;
    else
        return BMX_MXF_PRODUCT_VERSION;
}

string bmx::get_bmx_mxf_version_string()
{
    if (BMX_REGRESSION_TEST) {
        return "0.0.0";
    } else {
        char buffer[64];
        bmx_snprintf(buffer, sizeof(buffer), "%d.%d.%d (scm %s)",
                     BMX_VERSION_MAJOR, BMX_VERSION_MINOR, BMX_VERSION_MICRO,
                     BMX_SCM_VERSION);
        return buffer;
    }
}

<|endoftext|>


<commit_before>#pragma once

#include <QtGlobal>

#define CHATTERINO_VERSION "2.1.4-beta-2"

#if defined(Q_OS_WIN)
#    define CHATTERINO_OS "win"
#elif defined(Q_OS_MACOS)
#    define CHATTERINO_OS "macos"
#elif defined(Q_OS_LINUX)
#    define CHATTERINO_OS "linux"
#else
#    define CHATTERINO_OS "unknown"
#endif
<commit_msg>2.1.4<commit_after>#pragma once

#include <QtGlobal>

#define CHATTERINO_VERSION "2.1.4"

#if defined(Q_OS_WIN)
#    define CHATTERINO_OS "win"
#elif defined(Q_OS_MACOS)
#    define CHATTERINO_OS "macos"
#elif defined(Q_OS_LINUX)
#    define CHATTERINO_OS "linux"
#else
#    define CHATTERINO_OS "unknown"
#endif
<|endoftext|>


<commit_before>/* BZWorkbench
 * Copyright (c) 1993 - 2008 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "commonControls.h"
#include <FL/Fl_File_Chooser.H>

std::map<bzwb_eCommonControlType,controlHanderList>	commonControlHandlers;

controlHanderList getControlHandlers ( bzwb_eCommonControlType type )
{
	controlHanderList list;
	if ( commonControlHandlers.find(type) == commonControlHandlers.end())
		return list;
	return commonControlHandlers.find(type)->second;
}

void addControlHandler ( bzwb_eCommonControlType type, bzwb_BaseCommonControlHandler* handler )
{
	if (!handler )
		return;

	if ( commonControlHandlers.find(type) == commonControlHandlers.end())
	{
		controlHanderList list;
		commonControlHandlers[type] = list;
	}
	commonControlHandlers[type].push_back(handler);
}

void removeControlHandler ( bzwb_eCommonControlType type, bzwb_BaseCommonControlHandler* handler )
{
	if (!handler)
		return;

	if ( commonControlHandlers.find(type) == commonControlHandlers.end())
		return;

	std::map<bzwb_eCommonControlType,controlHanderList>::iterator itr = commonControlHandlers.find(type);
	for ( int i = 0; i < (int) itr->second.size(); i++ )
	{
		if (handler == itr->second[i])
		{
			itr->second.erase(itr->second.begin()+i);
			return;
		}
	}
}

bool callOpenFileDialog ( std::string  &result, const char* file, const char *dir, const char *extension, const char* description  )
{
	// see if anyone wants to handle it.
	controlHanderList handlers = getControlHandlers(eOpenFileDialog);
	for (int i = 0; i < (int)handlers.size(); i++)
	{
		bzw_OpenDialogControlHandler *handler = (bzw_OpenDialogControlHandler*)handlers[i];

		handler->file = file;
		handler->extension = extension;
		handler->directory = dir;
		handler->sucsessful = false;
		handler->description = description;
		handler->parent = bzwb_getOSMainWindowHandle();

		if ( handlers[i]->handle() )
		{
			result = handler->file;
			return handler->sucsessful;
		}
	}

	//if not, let the FLTK do it
	Fl_File_Chooser* fc = new Fl_File_Chooser(dir, extension, Fl_File_Chooser::SINGLE, description);
	fc->value(file);
	fc->show();

	// wait for a value
	while( fc->shown() ) { Fl::wait(); }

	// fcStaticBuffer is still safe to use after fc is deleted, see FLTK docs
	const char* fcStaticBuffer = fc->value();
	delete fc;

	// get a value (the selected filename )
	if(fcStaticBuffer == NULL)
		return false;

	result = fcStaticBuffer;
	return true;
}

bool callSaveFileDialog ( std::string  &result, const char* file, const char *dir, const char *extension, const char* description )
{
	// see if anyone wants to handle it.
	controlHanderList handlers = getControlHandlers(eSaveFileDialog);
	for (int i = 0; i < (int)handlers.size(); i++)
	{
		bzw_SaveDialogControlHandler *handler = (bzw_SaveDialogControlHandler*)handlers[i];

		handler->file = file;
		handler->extension = extension;
		handler->directory = dir;
		handler->sucsessful = false;
		handler->description = description;
		handler->parent = bzwb_getOSMainWindowHandle();

		if ( handlers[i]->handle() )
		{
			result = handler->file;
			return handler->sucsessful;
		}
	}

	Fl_File_Chooser* fc = new Fl_File_Chooser(dir, extension, Fl_File_Chooser::CREATE, description);

	if(file)
		fc->value(file);
	fc->show();

	// wait for a value
	while( fc->shown() ) { Fl::wait(); }

	if(fc->value() == NULL)
		return false;

	result = fc->value();
	return true;
}

<commit_msg>don't read from memory that has been deallocated<commit_after>/* BZWorkbench
 * Copyright (c) 1993 - 2008 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "commonControls.h"
#include <FL/Fl_File_Chooser.H>

std::map<bzwb_eCommonControlType,controlHanderList>	commonControlHandlers;

controlHanderList getControlHandlers ( bzwb_eCommonControlType type )
{
	controlHanderList list;
	if ( commonControlHandlers.find(type) == commonControlHandlers.end())
		return list;
	return commonControlHandlers.find(type)->second;
}

void addControlHandler ( bzwb_eCommonControlType type, bzwb_BaseCommonControlHandler* handler )
{
	if (!handler )
		return;

	if ( commonControlHandlers.find(type) == commonControlHandlers.end())
	{
		controlHanderList list;
		commonControlHandlers[type] = list;
	}
	commonControlHandlers[type].push_back(handler);
}

void removeControlHandler ( bzwb_eCommonControlType type, bzwb_BaseCommonControlHandler* handler )
{
	if (!handler)
		return;

	if ( commonControlHandlers.find(type) == commonControlHandlers.end())
		return;

	std::map<bzwb_eCommonControlType,controlHanderList>::iterator itr = commonControlHandlers.find(type);
	for ( int i = 0; i < (int) itr->second.size(); i++ )
	{
		if (handler == itr->second[i])
		{
			itr->second.erase(itr->second.begin()+i);
			return;
		}
	}
}

bool callOpenFileDialog ( std::string  &result, const char* file, const char *dir, const char *extension, const char* description  )
{
	// see if anyone wants to handle it.
	controlHanderList handlers = getControlHandlers(eOpenFileDialog);
	for (int i = 0; i < (int)handlers.size(); i++)
	{
		bzw_OpenDialogControlHandler *handler = (bzw_OpenDialogControlHandler*)handlers[i];

		handler->file = file;
		handler->extension = extension;
		handler->directory = dir;
		handler->sucsessful = false;
		handler->description = description;
		handler->parent = bzwb_getOSMainWindowHandle();

		if ( handlers[i]->handle() )
		{
			result = handler->file;
			return handler->sucsessful;
		}
	}

	//if not, let the FLTK do it
	Fl_File_Chooser* fc = new Fl_File_Chooser(dir, extension, Fl_File_Chooser::SINGLE, description);
	fc->value(file);
	fc->show();

	// wait for a value
	while( fc->shown() ) { Fl::wait(); }

	// make sure we got something
	if (fc->value() == NULL)
	{
		delete fc;
		return false;
	}

	result = fc->value();
	delete fc;
	return true;
}

bool callSaveFileDialog ( std::string  &result, const char* file, const char *dir, const char *extension, const char* description )
{
	// see if anyone wants to handle it.
	controlHanderList handlers = getControlHandlers(eSaveFileDialog);
	for (int i = 0; i < (int)handlers.size(); i++)
	{
		bzw_SaveDialogControlHandler *handler = (bzw_SaveDialogControlHandler*)handlers[i];

		handler->file = file;
		handler->extension = extension;
		handler->directory = dir;
		handler->sucsessful = false;
		handler->description = description;
		handler->parent = bzwb_getOSMainWindowHandle();

		if ( handlers[i]->handle() )
		{
			result = handler->file;
			return handler->sucsessful;
		}
	}

	Fl_File_Chooser* fc = new Fl_File_Chooser(dir, extension, Fl_File_Chooser::CREATE, description);

	if(file)
		fc->value(file);
	fc->show();

	// wait for a value
	while( fc->shown() ) { Fl::wait(); }

	if(fc->value() == NULL)
		return false;

	result = fc->value();
	return true;
}

<|endoftext|>


<commit_before>#include "io/pipe.h"

#include <cstdint>
#include <cstring>
#include <deque>
#include <memory>
#include <vector>

#include "base/logging.h"

namespace io {

namespace {
struct ReadOp {
  event::Task* task;
  char* out;
  std::size_t* n;
  std::size_t min;
  std::size_t max;

  ReadOp(event::Task* t, char* o, std::size_t* n, std::size_t mn,
         std::size_t mx) noexcept : task(t),
                                    out(o),
                                    n(n),
                                    min(mn),
                                    max(mx) {}
};

struct PipeGuts {
  mutable std::mutex mu;
  bool write_closed;
  bool read_closed;
  std::vector<char> buffer;
  std::deque<ReadOp> readq;

  PipeGuts() noexcept : write_closed(false), read_closed(false) {}

  bool process_one(const ReadOp& op) {
    if (buffer.size() >= op.min) {
      std::size_t count = buffer.size();
      if (count > op.max) count = op.max;
      ::memcpy(op.out, buffer.data(), count);
      *op.n = count;
      auto it = buffer.begin();
      buffer.erase(it, it + count);
      op.task->finish_ok();
      return true;
    }
    if (write_closed) {
      ::memcpy(op.out, buffer.data(), buffer.size());
      *op.n = buffer.size();
      buffer.clear();
      op.task->finish(base::Result::eof());
      return true;
    }
    return false;
  }

  void process() {
    while (!readq.empty()) {
      const auto& op = readq.front();
      if (!process_one(op)) break;
      readq.pop_front();
    }
  }
};

class PipeReader : public ReaderImpl {
 public:
  PipeReader(std::shared_ptr<PipeGuts> g, Options o) noexcept
      : ReaderImpl(std::move(o)),
        guts_(std::move(g)) {}

  void read(event::Task* task, char* out, std::size_t* n, std::size_t min,
            std::size_t max) override {
    if (!prologue(task, out, n, min, max)) return;
    auto lock = base::acquire_lock(guts_->mu);
    if (guts_->read_closed) {
      task->finish(base::Result::failed_precondition("pipe is closed"));
      return;
    }
    guts_->readq.emplace_back(task, out, n, min, max);
    guts_->process();
  }

  void close(event::Task* task) override {
    if (!prologue(task)) return;
    auto lock = base::acquire_lock(guts_->mu);
    if (guts_->read_closed) {
      task->finish(base::Result::failed_precondition("pipe is closed"));
      return;
    }
    guts_->write_closed = true;
    guts_->read_closed = true;
    for (const auto& op : guts_->readq) {
      op.task->finish_cancel();
    }
    guts_->buffer.clear();
    guts_->readq.clear();
    task->finish_ok();
  }

 private:
  std::shared_ptr<PipeGuts> guts_;
};

class PipeWriter : public WriterImpl {
 public:
  PipeWriter(std::shared_ptr<PipeGuts> g, Options o) noexcept
      : WriterImpl(std::move(o)),
        guts_(std::move(g)) {}

  void write(event::Task* task, std::size_t* n, const char* ptr,
             std::size_t len) override {
    if (!prologue(task, n, ptr, len)) return;
    auto lock = base::acquire_lock(guts_->mu);
    if (guts_->write_closed) {
      task->finish(base::Result::failed_precondition("pipe is closed"));
      return;
    }
    auto& buf = guts_->buffer;
    buf.insert(buf.end(), ptr, ptr + len);
    *n = len;
    task->finish_ok();
    guts_->process();
  }

  void close(event::Task* task) override {
    if (!prologue(task)) return;
    auto lock = base::acquire_lock(guts_->mu);
    if (guts_->write_closed) {
      task->finish(base::Result::failed_precondition("pipe is closed"));
      return;
    }
    guts_->write_closed = true;
    task->finish_ok();
    guts_->process();
  }

 private:
  std::shared_ptr<PipeGuts> guts_;
};
}  // anonymous namespace

void make_pipe(Reader* r, Writer* w, Options o) {
  CHECK_NOTNULL(r);
  CHECK_NOTNULL(w);
  auto guts = std::make_shared<PipeGuts>();
  *r = Reader(std::make_shared<PipeReader>(guts, o));
  *w = Writer(std::make_shared<PipeWriter>(std::move(guts), std::move(o)));
}

}  // namespace io
<commit_msg>Auto-close pipe when destructor runs.<commit_after>#include "io/pipe.h"

#include <cstdint>
#include <cstring>
#include <deque>
#include <memory>
#include <vector>

#include "base/logging.h"

namespace io {

namespace {
struct ReadOp {
  event::Task* task;
  char* out;
  std::size_t* n;
  std::size_t min;
  std::size_t max;

  ReadOp(event::Task* t, char* o, std::size_t* n, std::size_t mn,
         std::size_t mx) noexcept : task(t),
                                    out(o),
                                    n(n),
                                    min(mn),
                                    max(mx) {}
};

struct PipeGuts {
  mutable std::mutex mu;
  bool write_closed;
  bool read_closed;
  std::vector<char> buffer;
  std::deque<ReadOp> readq;

  PipeGuts() noexcept : write_closed(false), read_closed(false) {}

  bool process_one(const ReadOp& op) {
    if (buffer.size() >= op.min) {
      std::size_t count = buffer.size();
      if (count > op.max) count = op.max;
      ::memcpy(op.out, buffer.data(), count);
      *op.n = count;
      auto it = buffer.begin();
      buffer.erase(it, it + count);
      op.task->finish_ok();
      return true;
    }
    if (write_closed) {
      ::memcpy(op.out, buffer.data(), buffer.size());
      *op.n = buffer.size();
      buffer.clear();
      op.task->finish(base::Result::eof());
      return true;
    }
    return false;
  }

  void process() {
    while (!readq.empty()) {
      const auto& op = readq.front();
      if (!process_one(op)) break;
      readq.pop_front();
    }
  }
};

class PipeReader : public ReaderImpl {
 public:
  PipeReader(std::shared_ptr<PipeGuts> g, Options o) noexcept
      : ReaderImpl(std::move(o)),
        guts_(std::move(g)) {}

  ~PipeReader() noexcept {
    auto lock = base::acquire_lock(guts_->mu);
    close_guts();
  }

  void read(event::Task* task, char* out, std::size_t* n, std::size_t min,
            std::size_t max) override {
    if (!prologue(task, out, n, min, max)) return;
    auto lock = base::acquire_lock(guts_->mu);
    if (guts_->read_closed) {
      task->finish(base::Result::failed_precondition("pipe is closed"));
      return;
    }
    guts_->readq.emplace_back(task, out, n, min, max);
    guts_->process();
  }

  void close(event::Task* task) override {
    if (!prologue(task)) return;
    auto lock = base::acquire_lock(guts_->mu);
    if (guts_->read_closed) {
      task->finish(base::Result::failed_precondition("pipe is closed"));
      return;
    }
    close_guts();
    task->finish_ok();
  }

 private:
  void close_guts() noexcept {
    guts_->write_closed = true;
    guts_->read_closed = true;
    for (const auto& op : guts_->readq) {
      op.task->finish_cancel();
    }
    guts_->buffer.clear();
    guts_->readq.clear();
  }

  std::shared_ptr<PipeGuts> guts_;
};

class PipeWriter : public WriterImpl {
 public:
  PipeWriter(std::shared_ptr<PipeGuts> g, Options o) noexcept
      : WriterImpl(std::move(o)),
        guts_(std::move(g)) {}

  ~PipeWriter() noexcept {
    auto lock = base::acquire_lock(guts_->mu);
    guts_->write_closed = true;
    guts_->process();
  }

  void write(event::Task* task, std::size_t* n, const char* ptr,
             std::size_t len) override {
    if (!prologue(task, n, ptr, len)) return;
    auto lock = base::acquire_lock(guts_->mu);
    if (guts_->write_closed) {
      task->finish(base::Result::failed_precondition("pipe is closed"));
      return;
    }
    auto& buf = guts_->buffer;
    buf.insert(buf.end(), ptr, ptr + len);
    *n = len;
    task->finish_ok();
    guts_->process();
  }

  void close(event::Task* task) override {
    if (!prologue(task)) return;
    auto lock = base::acquire_lock(guts_->mu);
    if (guts_->write_closed) {
      task->finish(base::Result::failed_precondition("pipe is closed"));
      return;
    }
    guts_->write_closed = true;
    task->finish_ok();
    guts_->process();
  }

 private:
  std::shared_ptr<PipeGuts> guts_;
};
}  // anonymous namespace

void make_pipe(Reader* r, Writer* w, Options o) {
  CHECK_NOTNULL(r);
  CHECK_NOTNULL(w);
  auto guts = std::make_shared<PipeGuts>();
  *r = Reader(std::make_shared<PipeReader>(guts, o));
  *w = Writer(std::make_shared<PipeWriter>(std::move(guts), std::move(o)));
}

}  // namespace io
<|endoftext|>


<commit_before>//
//  Mat4.cpp
//  G3MiOSSDK
//
//  Created by José Miguel S N on 06/06/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#include "MutableMatrix44D.hpp"

#include <stdio.h>

#include "Vector3D.hpp"
#include "Angle.hpp"
#include "MutableVector3D.hpp"

MutableMatrix44D MutableMatrix44D::multiply(const MutableMatrix44D& m) const {
  double R[16];
  for (int j = 0; j < 4; j++)
    for (int i = 0; i < 4; i++)
      R[j * 4 + i] = m.get(j * 4) * _m[i] +
      m.get(j * 4 + 1) * _m[4 + i] +
      m.get(j * 4 + 2) * _m[8 + i] +
      m.get(j * 4 + 3) * _m[12 + i];

  return MutableMatrix44D(R);
}

void MutableMatrix44D::print(const std::string& name, const ILogger* log) const
{
  log->logInfo("MATRIX %s:\n", name.c_str());
  for (int j = 0; j < 4; j++)
    log->logInfo("%.2f  %.2f %.2f %.2f\n", _m[j * 4], _m[j * 4 + 1],_m[j * 4 + 2], _m[j * 4 + 3] );
  log->logInfo("\n");
}

/*
 * Compute inverse of 4x4 transformation matrix.
 * Code contributed by Jacques Leroy jle@star.be
 * Return GL_TRUE for success, GL_FALSE for failure (singular matrix)
 */
bool MutableMatrix44D::invert_matrix(const double m[16], double out[16]) {
  //NEW METHOD FOR ENHANCING JAVA TRANSLATION
  double inv[16], det;
  int i;

  inv[0] = m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15]
  + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10];
  inv[4] = -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15]
  - m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10];
  inv[8] = m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15]
  + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9];
  inv[12] = -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14]
  - m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9];
  inv[1] = -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15]
  - m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10];
  inv[5] = m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15]
  + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10];
  inv[9] = -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15]
  - m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9];
  inv[13] = m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14]
  + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9];
  inv[2] = m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15]
  + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6];
  inv[6] = -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15]
  - m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6];
  inv[10] = m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15]
  + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5];
  inv[14] = -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14]
  - m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5];
  inv[3] = -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11]
  - m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6];
  inv[7] = m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11]
  + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6];
  inv[11] = -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11]
  - m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5];
  inv[15] = m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10]
  + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5];

  det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];
  if (det == 0)
    return false;

  det = 1.0 / det;

  for (i = 0; i < 16; i++)
    out[i] = inv[i] * det;

  return true;
}

MutableMatrix44D MutableMatrix44D::inverse() const
{
  double out[16];
  invert_matrix(_m, out);

  return MutableMatrix44D(out);
}

void MutableMatrix44D::transformPoint(double out[4], const double in[4]) {
#define M(row,col)  _m[col*4+row]
  out[0] =
  M(0, 0) * in[0] + M(0, 1) * in[1] + M(0, 2) * in[2] + M(0, 3) * in[3];
  out[1] =
  M(1, 0) * in[0] + M(1, 1) * in[1] + M(1, 2) * in[2] + M(1, 3) * in[3];
  out[2] =
  M(2, 0) * in[0] + M(2, 1) * in[1] + M(2, 2) * in[2] + M(2, 3) * in[3];
  out[3] =
  M(3, 0) * in[0] + M(3, 1) * in[1] + M(3, 2) * in[2] + M(3, 3) * in[3];
#undef M
}

/*
 This function is intended to be used on a ModelView matrix. ModelView = Projection * Model
 */
Vector3D MutableMatrix44D::unproject(const Vector3D& pixel3D, const int viewport[4]) const {

  const double winx = pixel3D.x();
  const double winy = pixel3D.y();
  const double winz = pixel3D.z();

  /* matrice de transformation */
  double in[4], out[4];

  /* transformation coordonnees normalisees entre -1 et 1 */
  in[0] = (winx - viewport[0]) * 2 / viewport[2] - 1.0;
  in[1] = (winy - viewport[1]) * 2 / viewport[3] - 1.0;
  in[2] = 2 * winz - 1.0;
  in[3] = 1.0;

  /* calcul transformation inverse */
  MutableMatrix44D m = this->inverse();

  /* d'ou les coordonnees objets */
  m.transformPoint(out, in);
  if (out[3] == 0.0)
    return Vector3D::nan();

  const double objx = out[0] / out[3];
  const double objy = out[1] / out[3];
  const double objz = out[2] / out[3];

  return Vector3D(objx, objy, objz);
}

MutableMatrix44D MutableMatrix44D::createTranslationMatrix(const Vector3D& t) {
  const double T[16] = {
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    t.x(), t.y(), t.z(), 1
  };

  return MutableMatrix44D(T);
}

MutableMatrix44D MutableMatrix44D::createRotationMatrix(const Angle& angle, const Vector3D& p)
{
  const Vector3D p0 = p.normalized();

  const double c = angle.cosinus();
  const double s = angle.sinus();

  const double R[16] = {
    p0.x() * p0.x() * (1 - c) + c, p0.x() * p0.y() * (1 - c) + p0.z() * s, p0.x() * p0.z() * (1 - c) - p0.y() * s, 0,
    p0.y() * p0.x() * (1 - c) - p0.z() * s, p0.y() * p0.y() * (1 - c) + c, p0.y() * p0.z() * (1 - c) + p0.x() * s, 0,
    p0.x() * p0.z() * (1 - c) + p0.y() * s, p0.y() * p0.z() * (1 - c) - p0.x() * s, p0.z() * p0.z() * (1 - c) + c, 0,
    0, 0, 0, 1
  };

  return MutableMatrix44D(R);
}

MutableMatrix44D MutableMatrix44D::createModelMatrix(const MutableVector3D& pos,
                                                     const MutableVector3D& center,
                                                     const MutableVector3D& up) {
  const MutableVector3D w = center.sub(pos).normalized();
  const double pe = w.dot(up);
  const MutableVector3D v = up.sub(w.times(pe)).normalized();
  const MutableVector3D u = w.cross(v);
  const double LA[16] = {
    u.x(), v.x(), -w.x(), 0,
    u.y(), v.y(), -w.y(), 0,
    u.z(), v.z(), -w.z(), 0,
    -pos.dot(u), -pos.dot(v), pos.dot(w), 1
  };
  return MutableMatrix44D(LA);
}

MutableMatrix44D MutableMatrix44D::createProjectionMatrix(double left, double right,
                                                          double bottom, double top,
                                                          double znear, double zfar) {
  // set frustum matrix in double
  const double rl = right - left;
  const double tb = top - bottom;
  const double fn = zfar - znear;

  double P[16];
  P[0] = 2 * znear / rl;
  P[1] = P[2] = P[3] = P[4] = 0;
  P[5] = 2 * znear / tb;
  P[6] = P[7] = 0;
  P[8] = (right + left) / rl;
  P[9] = (top + bottom) / tb;
  P[10] = -(zfar + znear) / fn;
  P[11] = -1;
  P[12] = P[13] = 0;
  P[14] = -2 * zfar / fn * znear;
  P[15] = 0;

  return MutableMatrix44D(P);
}

MutableMatrix44D MutableMatrix44D::fromTranslation(const MutableVector3D& translation) {
  return MutableMatrix44D(1.0, 0.0, 0.0, translation.x(),
                          0.0, 1.0, 0.0, translation.y(),
                          0.0, 0.0, 1.0, translation.z(),
                          0.0, 0.0, 0.0, 1.0);
}

MutableMatrix44D MutableMatrix44D::fromScale(const MutableVector3D& scale) {
  return MutableMatrix44D(scale.x(), 0.0, 0.0, 0,
                          0.0, scale.y(), 0.0, 0,
                          0.0, 0.0, scale.z(), 0,
                          0.0, 0.0, 0.0, 1.0);

}

<commit_msg>advanced in TileRendering<commit_after>//
//  Mat4.cpp
//  G3MiOSSDK
//
//  Created by José Miguel S N on 06/06/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#include "MutableMatrix44D.hpp"

#include <stdio.h>

#include "Vector3D.hpp"
#include "Angle.hpp"
#include "MutableVector3D.hpp"

MutableMatrix44D MutableMatrix44D::multiply(const MutableMatrix44D& m) const {
  double R[16];
  for (int j = 0; j < 4; j++) {
    for (int i = 0; i < 4; i++) {
      R[j * 4 + i] = m.get(j * 4) * _m[i] + m.get(j * 4 + 1) * _m[4 + i] + m.get(j * 4 + 2) * _m[8 + i] + m.get(j * 4 + 3) * _m[12 + i];
    }
  }

  return MutableMatrix44D(R);
}

void MutableMatrix44D::print(const std::string& name, const ILogger* log) const
{
  log->logInfo("MATRIX %s:\n", name.c_str());
  for (int j = 0; j < 4; j++) {
    log->logInfo("%.2f  %.2f %.2f %.2f\n", _m[j * 4], _m[j * 4 + 1],_m[j * 4 + 2], _m[j * 4 + 3] );
  }
  log->logInfo("\n");
}

/*
 * Compute inverse of 4x4 transformation matrix.
 * Code contributed by Jacques Leroy jle@star.be
 * Return GL_TRUE for success, GL_FALSE for failure (singular matrix)
 */
bool MutableMatrix44D::invert_matrix(const double m[16], double out[16]) {
  //NEW METHOD FOR ENHANCING JAVA TRANSLATION
  double inv[16], det;
  int i;

  inv[0] = m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15]
  + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10];
  inv[4] = -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15]
  - m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10];
  inv[8] = m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15]
  + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9];
  inv[12] = -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14]
  - m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9];
  inv[1] = -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15]
  - m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10];
  inv[5] = m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15]
  + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10];
  inv[9] = -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15]
  - m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9];
  inv[13] = m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14]
  + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9];
  inv[2] = m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15]
  + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6];
  inv[6] = -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15]
  - m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6];
  inv[10] = m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15]
  + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5];
  inv[14] = -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14]
  - m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5];
  inv[3] = -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11]
  - m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6];
  inv[7] = m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11]
  + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6];
  inv[11] = -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11]
  - m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5];
  inv[15] = m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10]
  + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5];

  det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];
  if (det == 0)
    return false;

  det = 1.0 / det;

  for (i = 0; i < 16; i++)
    out[i] = inv[i] * det;

  return true;
}

MutableMatrix44D MutableMatrix44D::inverse() const
{
  double out[16];
  invert_matrix(_m, out);

  return MutableMatrix44D(out);
}

void MutableMatrix44D::transformPoint(double out[4], const double in[4]) {
#define M(row,col)  _m[col*4+row]
  out[0] =
  M(0, 0) * in[0] + M(0, 1) * in[1] + M(0, 2) * in[2] + M(0, 3) * in[3];
  out[1] =
  M(1, 0) * in[0] + M(1, 1) * in[1] + M(1, 2) * in[2] + M(1, 3) * in[3];
  out[2] =
  M(2, 0) * in[0] + M(2, 1) * in[1] + M(2, 2) * in[2] + M(2, 3) * in[3];
  out[3] =
  M(3, 0) * in[0] + M(3, 1) * in[1] + M(3, 2) * in[2] + M(3, 3) * in[3];
#undef M
}

/*
 This function is intended to be used on a ModelView matrix. ModelView = Projection * Model
 */
Vector3D MutableMatrix44D::unproject(const Vector3D& pixel3D, const int viewport[4]) const {

  const double winx = pixel3D.x();
  const double winy = pixel3D.y();
  const double winz = pixel3D.z();

  /* matrice de transformation */
  double in[4], out[4];

  /* transformation coordonnees normalisees entre -1 et 1 */
  in[0] = (winx - viewport[0]) * 2 / viewport[2] - 1.0;
  in[1] = (winy - viewport[1]) * 2 / viewport[3] - 1.0;
  in[2] = 2 * winz - 1.0;
  in[3] = 1.0;

  /* calcul transformation inverse */
  MutableMatrix44D m = this->inverse();

  /* d'ou les coordonnees objets */
  m.transformPoint(out, in);
  if (out[3] == 0.0)
    return Vector3D::nan();

  const double objx = out[0] / out[3];
  const double objy = out[1] / out[3];
  const double objz = out[2] / out[3];

  return Vector3D(objx, objy, objz);
}

MutableMatrix44D MutableMatrix44D::createTranslationMatrix(const Vector3D& t) {
  const double T[16] = {
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    t.x(), t.y(), t.z(), 1
  };

  return MutableMatrix44D(T);
}

MutableMatrix44D MutableMatrix44D::createRotationMatrix(const Angle& angle, const Vector3D& p)
{
  const Vector3D p0 = p.normalized();

  const double c = angle.cosinus();
  const double s = angle.sinus();

  const double R[16] = {
    p0.x() * p0.x() * (1 - c) + c, p0.x() * p0.y() * (1 - c) + p0.z() * s, p0.x() * p0.z() * (1 - c) - p0.y() * s, 0,
    p0.y() * p0.x() * (1 - c) - p0.z() * s, p0.y() * p0.y() * (1 - c) + c, p0.y() * p0.z() * (1 - c) + p0.x() * s, 0,
    p0.x() * p0.z() * (1 - c) + p0.y() * s, p0.y() * p0.z() * (1 - c) - p0.x() * s, p0.z() * p0.z() * (1 - c) + c, 0,
    0, 0, 0, 1
  };

  return MutableMatrix44D(R);
}

MutableMatrix44D MutableMatrix44D::createModelMatrix(const MutableVector3D& pos,
                                                     const MutableVector3D& center,
                                                     const MutableVector3D& up) {
  const MutableVector3D w = center.sub(pos).normalized();
  const double pe = w.dot(up);
  const MutableVector3D v = up.sub(w.times(pe)).normalized();
  const MutableVector3D u = w.cross(v);
  const double LA[16] = {
    u.x(), v.x(), -w.x(), 0,
    u.y(), v.y(), -w.y(), 0,
    u.z(), v.z(), -w.z(), 0,
    -pos.dot(u), -pos.dot(v), pos.dot(w), 1
  };
  return MutableMatrix44D(LA);
}

MutableMatrix44D MutableMatrix44D::createProjectionMatrix(double left, double right,
                                                          double bottom, double top,
                                                          double znear, double zfar) {
  // set frustum matrix in double
  const double rl = right - left;
  const double tb = top - bottom;
  const double fn = zfar - znear;

  double P[16];
  P[0] = 2 * znear / rl;
  P[1] = P[2] = P[3] = P[4] = 0;
  P[5] = 2 * znear / tb;
  P[6] = P[7] = 0;
  P[8] = (right + left) / rl;
  P[9] = (top + bottom) / tb;
  P[10] = -(zfar + znear) / fn;
  P[11] = -1;
  P[12] = P[13] = 0;
  P[14] = -2 * zfar / fn * znear;
  P[15] = 0;

  return MutableMatrix44D(P);
}

MutableMatrix44D MutableMatrix44D::fromTranslation(const MutableVector3D& translation) {
  return MutableMatrix44D(1.0, 0.0, 0.0, translation.x(),
                          0.0, 1.0, 0.0, translation.y(),
                          0.0, 0.0, 1.0, translation.z(),
                          0.0, 0.0, 0.0, 1.0);
}

MutableMatrix44D MutableMatrix44D::fromScale(const MutableVector3D& scale) {
  return MutableMatrix44D(scale.x(), 0.0, 0.0, 0,
                          0.0, scale.y(), 0.0, 0,
                          0.0, 0.0, scale.z(), 0,
                          0.0, 0.0, 0.0, 1.0);

}

<|endoftext|>


<commit_before>/**************************************************************************
Copyright 2015 Odin Holmes
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
****************************************************************************/
#pragma once
#include "../../../../Register/Register.hpp"

namespace Kvasir{
namespace System{
namespace PowerConfiguration {
	template<int I>
	using Helper = Register::RWLocation<0x40074208, (1u << I),unsigned(0x07 | (1 << 7) | (0x7F << 25))>;
	//bits 2:0 reserved
	static constexpr 	Helper<3>		ircOscillatorOutputPoweredDown{};
	static constexpr	Helper<4>		ircOscillatorPoweredDown{};
	static constexpr 	Helper<5>		flashPoweredDown{};
	static constexpr 	Helper<6>		eepromPoweredDown{};
	//bit 7 reserved
	static constexpr 	Helper<8>		brownOutDetectPoweredDown{};
	static constexpr 	Helper<9>		usbPhyPoweredDown{};
	static constexpr 	Helper<10>		adc0PoweredDown{};
	static constexpr 	Helper<11>		adc1PoweredDown{};
	static constexpr 	Helper<12>		dacPoweredDown{};
	static constexpr 	Helper<13>		analogComperator0PoweredDown{};
	static constexpr 	Helper<14>		analogComparator1PoweredDown{};
	static constexpr 	Helper<15>		analogComparator2PoweredDown{};
	static constexpr 	Helper<16>		analogComparator3PoweredDown{};
	static constexpr 	Helper<17>		internalVoltageRefPoweredDown{};
	static constexpr 	Helper<18>		temperaturSensorPoweredDown{};
	static constexpr 	Helper<19>		vddaDivPoweredDown{};
	static constexpr 	Helper<20>		watchdogOscillatorPoweredDown{};
	static constexpr 	Helper<21>		systemOscillatorPoweredDown{};
	static constexpr 	Helper<22>		systemPllPoweredDown{};
	static constexpr 	Helper<23>		usbPllPoweredDown{};
	static constexpr 	Helper<24>		sctPllPoweredDown{};
	//bits 31:25 reserved
}

namespace PowerControl {
	template<int I>
	using Helper = Register::RWLocation<0x4003C000, (1u << I),~unsigned((1 << 3) | (1 << 8) | (1 << 11))>;
	//bits 2:0 reserved
	static constexpr 	Helper<3>		noPowerDown{};
	//bits 7:4 reserved
	static constexpr	Helper<8>		ircOscillatorDisabled{};
	//bits 10:9 reserved
	static constexpr 	Helper<11>		flashDisabled{};
	//bits 31:12 reserved
}

namespace ClockSource{
	namespace Main{
		constexpr int address = 0x40074080;
		namespace Detail{
			using SourceAIrc = Register::BlindWriteActionT<address,0x03,0>;
			using SourceASystemOscillator = Register::BlindWriteActionT<address,0x03,1>;
			using SourceAWatchdogOscillator = Register::BlindWriteActionT<address,0x03,2>;
			using SourceBSourceA = Register::BlindWriteActionT<address+4,0x03,0>;
		}
		constexpr MPL::List<Detail::SourceAIrc,Detail::SourceBSourceA> irc{};
		constexpr MPL::List<Detail::SourceASystemOscillator,Detail::SourceBSourceA> systemOscillator{};
		constexpr MPL::List<Detail::SourceAWatchdogOscillator,Detail::SourceBSourceA> watchdogOscillator{};
		constexpr Register::BlindWriteActionT<address+4,0x03,1> pllInput{};
		constexpr Register::BlindWriteActionT<address+4,0x03,2> pllOutput{};
		constexpr Register::BlindWriteActionT<address+4,0x03,3> rtcOscillator{};
	}
	namespace Usb{
		enum class Source{ircOscillator,systemOscillator,usbPllOut,mainClock};
		constexpr Register::RWLocation<0x40074088,0x03,~0x03,Source> source;
	}
}

namespace ClockDivide{
	constexpr Register::RWLocation<0x400740CC,0xFF,~0xFF> systick;
	constexpr Register::RWLocation<0x400740D0,0xFF,~0xFF> usart;
	constexpr Register::RWLocation<0x400740D4,0xFF,~0xFF> ioconGlitchFilter;
	constexpr Register::RWLocation<0x400740D8,0xFF,~0xFF> armTrace;
	constexpr Register::RWLocation<0x400740EC,0xFF,~0xFF> usb;
	constexpr Register::RWLocation<0x400740F0,0xFF,~0xFF> adcSync;
	constexpr Register::RWLocation<0x400740F8,0xFF,~0xFF> clkOut;
}

namespace Pll{
	enum class PostDividerRatio {div1, div2, div4, div8};
	struct ClockSource{
		static constexpr int address{0x400740A0};
		static constexpr Register::WriteActionT<address,0x03,0x00> 		internalRc{};
		static constexpr Register::WriteActionT<address,0x03,0x01> 		systemOscillator{};
	};

	struct Control{
		static constexpr unsigned address{0x40074198u};
		static constexpr unsigned writable{0xFFFFFF00u};
		static constexpr Register::RWLocation<address,0x3F,writable> feedbackDivider{};
		static constexpr Register::RWLocation<address,(3 << 6),writable,PostDividerRatio> postDivider{};
	};
	constexpr Register::ROLocation<0x4007419C,0x01> statusLocked{};

}

namespace UsbPll{
	struct ClockSource{
		static constexpr int address{0x400740A4};
		static constexpr Register::WriteActionT<address,0x03,0x00> 		internalRc{};
		static constexpr Register::WriteActionT<address,0x03,0x01> 		systemOscillator{};
	};
	struct Control{
		static constexpr int address{0x400741A0};
		static constexpr unsigned writable{0xFFFFFF00u};
		static constexpr Register::RWLocation<address,0x3F,writable> feedbackDivider{};
		static constexpr Register::RWLocation<address,(3 << 6),writable,Pll::PostDividerRatio> postDivider{};
	};
	constexpr Register::ROLocation<0x400741A4,0x01> statusLocked{};
}

struct AHBClock{
	struct Enabled{
		template<int Bit>
		using Helper1 = Register::RWLocation<0x400740C4,(1u << Bit),~unsigned((1<<0) | (1<<2) | (3<<5) | ( 1<<8) | (1<<10) | (1<<17) | (7<<24) | (1<<31))>;
		template<int Bit>
		using Helper2 = Register::RWLocation<0x400740C8,(1u << Bit),~unsigned((1<<8) | (3<<11) | (7<<14) | ( 1<<20) | (1<<22) | (0xFF<<24))>;

		//bit 0 is sys which is always on
		static constexpr	Helper1<1>		rom{};
		//bit 2 reserved
		static constexpr	Helper1<3>		ram1{};
		static constexpr	Helper1<4>		ram2{};
		//bit 6:5 reserved
		static constexpr	Helper1<7>		flashReg{};
		//bit 8 reserved
		static constexpr 	Helper1<9>		eeprom{};
		//bit 10 reserved
		static constexpr	Helper1<11>		inputMux{};
		static constexpr	Helper1<12>		switchMatrix{};
		static constexpr	Helper1<13>		iocon{};
		static constexpr	Helper1<14>		gpio0{};
		static constexpr	Helper1<15>		gpio1{};
		static constexpr	Helper1<16>		gpio2{};
		//bit 17 reserved
		static constexpr	Helper1<18>		pinInt{};
		static constexpr	Helper1<19>		groupedPinInt{};
		static constexpr	Helper1<20>		dma{};
		static constexpr	Helper1<21>		crc{};
		static constexpr	Helper1<22>		wwdt{};
		static constexpr	Helper1<23>		rtc{};
		//bit 26:24 reserved
		static constexpr	Helper1<27>		adc0{};
		static constexpr	Helper1<28>		adc1{};
		static constexpr	Helper1<29>		dac{};
		static constexpr	Helper1<30>		analogComparator{};
		//bit 31 reserved

		//SYSAHBCLKCTRL1
		static constexpr	Helper2<0>	mrt{};
		static constexpr	Helper2<1>	rit{};
		static constexpr	Helper2<2>	sct0{};
		static constexpr	Helper2<3>	sct1{};
		static constexpr	Helper2<4>	sct2{};
		static constexpr	Helper2<5>	sct3{};
		static constexpr 	Helper2<6>	sctIpu{};
		static constexpr	Helper2<7>	cCan{};
		//bit 8 is reserved
		static constexpr	Helper2<9>	spi0{};
		static constexpr	Helper2<10>	spi1{};
		//bit 12:11 are reserved
		static constexpr	Helper2<13>	i2c0Int{};
		//bit 16:14
		static constexpr	Helper2<17>	uart0{};
		static constexpr	Helper2<18>	uart1{};
		static constexpr 	Helper2<19>	uart2{};
		//bit 20 reserved
		static constexpr	Helper1<21>	qei{};
		//bit 22 reserved
		static constexpr	Helper2<23>	usb{};
		//bits 31:24 reserved
	};

	// SYSAHBCLKDIV
	static constexpr Register::RWLocation<0x400740C0,0xFF,~0xFF> divider{};
};

namespace Flash{
	static constexpr int address{0x40074124};
	template<int I>
	struct MakeAction : Register::WriteActionT<address,(0x0F << 12),(I << 12)>{};
	template<int I>
	using MakeActionT = typename MakeAction<I>::Type;
	static constexpr MakeActionT<0> oneSysclock{};		//up to 25mhz
	static constexpr MakeActionT<1> twoSysclock{};		//up to 55mhz
	static constexpr MakeActionT<2> threeSysclock{};	//up to 72mhz
};

namespace PeripheralResetEnabled{			//PRESETCTRL register actions
	constexpr int address{0x40074044};
	template<int Bit>
	using Helper1 = Register::RWLocation<0x40074044,(1u << Bit),~unsigned((7<<0) | (1<<8) | (1<<10) | ( 1<<12) | (0xF<<14) | (0x1F<<22) | (1<<29) | (1<<31))>;
	template<int Bit>
	using Helper2 = Register::RWLocation<0x40074048,(1u << Bit),~unsigned((1<<8) | (3<<11) | (7<<14) | ( 1<<20) | (1<<22) | (0xFF<<24))>;

	//bit 6:0 reserved
	static constexpr	Helper1<7>		flash{};
	//bit 8 reserved
	static constexpr	Helper1<9>		eeprom{};
	//bit 10 reserved
	static constexpr	Helper1<11>		inputMux{};
	//bit 12 reserved
	static constexpr	Helper1<13>		ioCon{};
	//bit 17:14 reserved
	static constexpr	Helper1<18>		pinInterrupt{};
	static constexpr	Helper1<19>		groupedInterrupt{};
	static constexpr	Helper1<20>		dma{};
	static constexpr	Helper1<21>		crc{};
	//bit 26:22 reserved
	static constexpr	Helper1<27>		adc0{};
	static constexpr	Helper1<18>		adc1{};
	//bit 29 reserved
	static constexpr	Helper1<30>		analogComparator{};
	//bit 31 reserved

	static constexpr	Helper2<0>	multirateTimer{};
	static constexpr	Helper2<1>	rit{};
	static constexpr	Helper2<2>	sct0{};
	static constexpr	Helper2<3>	sct1{};
	static constexpr	Helper2<4>	sct2{};
	static constexpr	Helper2<5>	sct3{};
	static constexpr	Helper2<6>	sctInput{};
	static constexpr	Helper2<7>	cCan{};
	//bit 8 reserved
	static constexpr	Helper2<9>	spi0{};
	static constexpr	Helper2<10>	spi1{};
	//bit 12:11 reserved
	static constexpr	Helper2<13>	i2c0{};
	//bit 16:14 reserved
	static constexpr	Helper2<17>	uart0{};
	static constexpr	Helper2<18>	uart1{};
	static constexpr	Helper2<19>	uart2{};
	//bit 20 reserved
	static constexpr	Helper2<21>	qei{};
	//bit 22 reserved
	static constexpr	Helper2<23>	usb{};
	//bit 31:24 reserved

};

}
}
<commit_msg>fixed typo<commit_after>/**************************************************************************
Copyright 2015 Odin Holmes
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
****************************************************************************/
#pragma once
#include "../../../../Register/Register.hpp"

namespace Kvasir{
namespace System{
namespace PowerConfiguration {
	template<int I>
	using Helper = Register::RWLocation<0x40074208, (1u << I),unsigned(0x07 | (1 << 7) | (0x7F << 25))>;
	//bits 2:0 reserved
	static constexpr 	Helper<3>		ircOscillatorOutputPoweredDown{};
	static constexpr	Helper<4>		ircOscillatorPoweredDown{};
	static constexpr 	Helper<5>		flashPoweredDown{};
	static constexpr 	Helper<6>		eepromPoweredDown{};
	//bit 7 reserved
	static constexpr 	Helper<8>		brownOutDetectPoweredDown{};
	static constexpr 	Helper<9>		usbPhyPoweredDown{};
	static constexpr 	Helper<10>		adc0PoweredDown{};
	static constexpr 	Helper<11>		adc1PoweredDown{};
	static constexpr 	Helper<12>		dacPoweredDown{};
	static constexpr 	Helper<13>		analogComperator0PoweredDown{};
	static constexpr 	Helper<14>		analogComparator1PoweredDown{};
	static constexpr 	Helper<15>		analogComparator2PoweredDown{};
	static constexpr 	Helper<16>		analogComparator3PoweredDown{};
	static constexpr 	Helper<17>		internalVoltageRefPoweredDown{};
	static constexpr 	Helper<18>		temperaturSensorPoweredDown{};
	static constexpr 	Helper<19>		vddaDivPoweredDown{};
	static constexpr 	Helper<20>		watchdogOscillatorPoweredDown{};
	static constexpr 	Helper<21>		systemOscillatorPoweredDown{};
	static constexpr 	Helper<22>		systemPllPoweredDown{};
	static constexpr 	Helper<23>		usbPllPoweredDown{};
	static constexpr 	Helper<24>		sctPllPoweredDown{};
	//bits 31:25 reserved
}

namespace PowerControl {
	template<int I>
	using Helper = Register::RWLocation<0x4003C000, (1u << I),~unsigned((1 << 3) | (1 << 8) | (1 << 11))>;
	//bits 2:0 reserved
	static constexpr 	Helper<3>		noPowerDown{};
	//bits 7:4 reserved
	static constexpr	Helper<8>		ircOscillatorDisabled{};
	//bits 10:9 reserved
	static constexpr 	Helper<11>		flashDisabled{};
	//bits 31:12 reserved
}

namespace ClockSource{
	namespace Main{
		constexpr int address = 0x40074080;
		namespace Detail{
			using SourceAIrc = Register::BlindWriteActionT<address,0x03,0>;
			using SourceASystemOscillator = Register::BlindWriteActionT<address,0x03,1>;
			using SourceAWatchdogOscillator = Register::BlindWriteActionT<address,0x03,2>;
			using SourceBSourceA = Register::BlindWriteActionT<address+4,0x03,0>;
		}
		constexpr MPL::List<Detail::SourceAIrc,Detail::SourceBSourceA> irc{};
		constexpr MPL::List<Detail::SourceASystemOscillator,Detail::SourceBSourceA> systemOscillator{};
		constexpr MPL::List<Detail::SourceAWatchdogOscillator,Detail::SourceBSourceA> watchdogOscillator{};
		constexpr Register::BlindWriteActionT<address+4,0x03,1> pllInput{};
		constexpr Register::BlindWriteActionT<address+4,0x03,2> pllOutput{};
		constexpr Register::BlindWriteActionT<address+4,0x03,3> rtcOscillator{};
	}
	namespace Usb{
		enum class Source{ircOscillator,systemOscillator,usbPllOut,mainClock};
		constexpr Register::RWLocation<0x40074088,0x03,~0x03,Source> source;
	}
}

namespace ClockDivide{
	constexpr Register::RWLocation<0x400740CC,0xFF,~0xFF> systick;
	constexpr Register::RWLocation<0x400740D0,0xFF,~0xFF> usart;
	constexpr Register::RWLocation<0x400740D4,0xFF,~0xFF> ioconGlitchFilter;
	constexpr Register::RWLocation<0x400740D8,0xFF,~0xFF> armTrace;
	constexpr Register::RWLocation<0x400740EC,0xFF,~0xFF> usb;
	constexpr Register::RWLocation<0x400740F0,0xFF,~0xFF> adcSync;
	constexpr Register::RWLocation<0x400740F8,0xFF,~0xFF> clkOut;
}

namespace Pll{
	enum class PostDividerRatio {div1, div2, div4, div8};
	struct ClockSource{
		static constexpr int address{0x400740A0};
		static constexpr Register::WriteActionT<address,0x03,0x00> 		internalRc{};
		static constexpr Register::WriteActionT<address,0x03,0x01> 		systemOscillator{};
	};

	struct Control{
		static constexpr unsigned address{0x40074198u};
		static constexpr unsigned writable{0xFFFFFF00u};
		static constexpr Register::RWLocation<address,0x3F,writable> feedbackDivider{};
		static constexpr Register::RWLocation<address,(3 << 6),writable,PostDividerRatio> postDivider{};
	};
	constexpr Register::ROLocation<0x4007419C,0x01> statusLocked{};

}

namespace UsbPll{
	struct ClockSource{
		static constexpr int address{0x400740A4};
		static constexpr Register::WriteActionT<address,0x03,0x00> 		internalRc{};
		static constexpr Register::WriteActionT<address,0x03,0x01> 		systemOscillator{};
	};
	struct Control{
		static constexpr int address{0x400741A0};
		static constexpr unsigned writable{0xFFFFFF00u};
		static constexpr Register::RWLocation<address,0x3F,writable> feedbackDivider{};
		static constexpr Register::RWLocation<address,(3 << 6),writable,Pll::PostDividerRatio> postDivider{};
	};
	constexpr Register::ROLocation<0x400741A4,0x01> statusLocked{};
}

struct AHBClock{
	struct Enabled{
		template<int Bit>
		using Helper1 = Register::RWLocation<0x400740C4,(1u << Bit),~unsigned((1<<0) | (1<<2) | (3<<5) | ( 1<<8) | (1<<10) | (1<<17) | (7<<24) | (1<<31))>;
		template<int Bit>
		using Helper2 = Register::RWLocation<0x400740C8,(1u << Bit),~unsigned((1<<8) | (3<<11) | (7<<14) | ( 1<<20) | (1<<22) | (0xFF<<24))>;

		//bit 0 is sys which is always on
		static constexpr	Helper1<1>		rom{};
		//bit 2 reserved
		static constexpr	Helper1<3>		ram1{};
		static constexpr	Helper1<4>		ram2{};
		//bit 6:5 reserved
		static constexpr	Helper1<7>		flashReg{};
		//bit 8 reserved
		static constexpr 	Helper1<9>		eeprom{};
		//bit 10 reserved
		static constexpr	Helper1<11>		inputMux{};
		static constexpr	Helper1<12>		switchMatrix{};
		static constexpr	Helper1<13>		iocon{};
		static constexpr	Helper1<14>		gpio0{};
		static constexpr	Helper1<15>		gpio1{};
		static constexpr	Helper1<16>		gpio2{};
		//bit 17 reserved
		static constexpr	Helper1<18>		pinInt{};
		static constexpr	Helper1<19>		groupedPinInt{};
		static constexpr	Helper1<20>		dma{};
		static constexpr	Helper1<21>		crc{};
		static constexpr	Helper1<22>		wwdt{};
		static constexpr	Helper1<23>		rtc{};
		//bit 26:24 reserved
		static constexpr	Helper1<27>		adc0{};
		static constexpr	Helper1<28>		adc1{};
		static constexpr	Helper1<29>		dac{};
		static constexpr	Helper1<30>		analogComparator{};
		//bit 31 reserved

		//SYSAHBCLKCTRL1
		static constexpr	Helper2<0>	mrt{};
		static constexpr	Helper2<1>	rit{};
		static constexpr	Helper2<2>	sct0{};
		static constexpr	Helper2<3>	sct1{};
		static constexpr	Helper2<4>	sct2{};
		static constexpr	Helper2<5>	sct3{};
		static constexpr 	Helper2<6>	sctIpu{};
		static constexpr	Helper2<7>	cCan{};
		//bit 8 is reserved
		static constexpr	Helper2<9>	spi0{};
		static constexpr	Helper2<10>	spi1{};
		//bit 12:11 are reserved
		static constexpr	Helper2<13>	i2c0{};
		//bit 16:14
		static constexpr	Helper2<17>	uart0{};
		static constexpr	Helper2<18>	uart1{};
		static constexpr 	Helper2<19>	uart2{};
		//bit 20 reserved
		static constexpr	Helper1<21>	qei{};
		//bit 22 reserved
		static constexpr	Helper2<23>	usb{};
		//bits 31:24 reserved
	};

	// SYSAHBCLKDIV
	static constexpr Register::RWLocation<0x400740C0,0xFF,~0xFF> divider{};
};

namespace Flash{
	static constexpr int address{0x40074124};
	template<int I>
	struct MakeAction : Register::WriteActionT<address,(0x0F << 12),(I << 12)>{};
	template<int I>
	using MakeActionT = typename MakeAction<I>::Type;
	static constexpr MakeActionT<0> oneSysclock{};		//up to 25mhz
	static constexpr MakeActionT<1> twoSysclock{};		//up to 55mhz
	static constexpr MakeActionT<2> threeSysclock{};	//up to 72mhz
};

namespace PeripheralResetEnabled{			//PRESETCTRL register actions
	constexpr int address{0x40074044};
	template<int Bit>
	using Helper1 = Register::RWLocation<0x40074044,(1u << Bit),~unsigned((7<<0) | (1<<8) | (1<<10) | ( 1<<12) | (0xF<<14) | (0x1F<<22) | (1<<29) | (1<<31))>;
	template<int Bit>
	using Helper2 = Register::RWLocation<0x40074048,(1u << Bit),~unsigned((1<<8) | (3<<11) | (7<<14) | ( 1<<20) | (1<<22) | (0xFF<<24))>;

	//bit 6:0 reserved
	static constexpr	Helper1<7>		flash{};
	//bit 8 reserved
	static constexpr	Helper1<9>		eeprom{};
	//bit 10 reserved
	static constexpr	Helper1<11>		inputMux{};
	//bit 12 reserved
	static constexpr	Helper1<13>		ioCon{};
	//bit 17:14 reserved
	static constexpr	Helper1<18>		pinInterrupt{};
	static constexpr	Helper1<19>		groupedInterrupt{};
	static constexpr	Helper1<20>		dma{};
	static constexpr	Helper1<21>		crc{};
	//bit 26:22 reserved
	static constexpr	Helper1<27>		adc0{};
	static constexpr	Helper1<18>		adc1{};
	//bit 29 reserved
	static constexpr	Helper1<30>		analogComparator{};
	//bit 31 reserved

	static constexpr	Helper2<0>	multirateTimer{};
	static constexpr	Helper2<1>	rit{};
	static constexpr	Helper2<2>	sct0{};
	static constexpr	Helper2<3>	sct1{};
	static constexpr	Helper2<4>	sct2{};
	static constexpr	Helper2<5>	sct3{};
	static constexpr	Helper2<6>	sctInput{};
	static constexpr	Helper2<7>	cCan{};
	//bit 8 reserved
	static constexpr	Helper2<9>	spi0{};
	static constexpr	Helper2<10>	spi1{};
	//bit 12:11 reserved
	static constexpr	Helper2<13>	i2c0{};
	//bit 16:14 reserved
	static constexpr	Helper2<17>	uart0{};
	static constexpr	Helper2<18>	uart1{};
	static constexpr	Helper2<19>	uart2{};
	//bit 20 reserved
	static constexpr	Helper2<21>	qei{};
	//bit 22 reserved
	static constexpr	Helper2<23>	usb{};
	//bit 31:24 reserved

};

}
}
<|endoftext|>


<commit_before>#include "Button.hpp"
#include <iostream>
namespace cstr
{
	const sf::Color COLOR_CHANGE = {40, 40, 40, 0};
	const int BORDER_SIZE = 2;

	Button::Button(sf::Vector2u size, const sf::Texture& tex, const std::function<void()>& f)
		:	baseColor({128, 128, 128}),
			string(""),
			callback(f),
			textSize(0)
	{
		sprite.setTexture(tex);
		sprite.setColor(baseColor);
		sprite.setScale(size.x / sprite.getGlobalBounds().width, size.y / sprite.getGlobalBounds().height);
	}

	Button::~Button()
	{
	}

	void Button::update(sf::Event& event)
	{
		switch(event.type)
		{
			case sf::Event::MouseMoved:
				if(sprite.getGlobalBounds().contains({static_cast<float>(event.mouseMove.x), static_cast<float>(event.mouseMove.y)}))
				{
					mouseOn = true;
					sprite.setColor(baseColor + COLOR_CHANGE);
				}
				else
				{
					mouseOn = false;
					sprite.setColor(baseColor);
				}
				break;
			case sf::Event::MouseButtonPressed:
				if(mouseOn)
				{
					sprite.setColor(baseColor - COLOR_CHANGE);
				}
				break;
			case sf::Event::MouseButtonReleased:
				if(mouseOn)
				{
					callback();
					sprite.setColor(baseColor);
				}
				break;
			default:
				break;
		}
	}

	void Button::call()
	{
		callback();
	}

	sf::FloatRect Button::getGlobalBounds() const
	{
		return sprite.getGlobalBounds();
	}

	void Button::setString(const std::string& str, const sf::Font& f, unsigned ts)
	{
		string = str;
		text.setFont(f);
		text.setString(string);
		textSize = ts;

		if(textSize != 0)
		{
			std::cerr << "text size isn';t 0\n";
			text.setCharacterSize(ts);
		}
		else
		{
			std::cerr << "text size is 0\n";
			text.setCharacterSize(100);
			text.setCharacterSize(text.getCharacterSize() * (sprite.getGlobalBounds().height - 2 * BORDER_SIZE) / text.getLocalBounds().height);
			text.setCharacterSize(text.getCharacterSize() * (sprite.getGlobalBounds().width - 2 * BORDER_SIZE) / text.getLocalBounds().width);
		}

		text.setOrigin({text.getLocalBounds().left + text.getLocalBounds().width / 2, text.getLocalBounds().top + text.getLocalBounds().height / 2});
		text.setPosition({sprite.getGlobalBounds().left + sprite.getGlobalBounds().width / 2, sprite.getGlobalBounds().top + sprite.getGlobalBounds().height / 2});
	}

	void Button::setString(const std::string& str, unsigned ts)
	{
		setString(str, *text.getFont(), ts);
	}

	const std::string& Button::getString() const
	{
		return string;
	}

	void Button::setPosition(sf::Vector2i pos)
	{
		sprite.setPosition(static_cast<sf::Vector2f>(pos));
		text.setPosition({sprite.getGlobalBounds().left + sprite.getGlobalBounds().width / 2, sprite.getGlobalBounds().top + sprite.getGlobalBounds().height / 2});
	}

	void Button::setSize(sf::Vector2u size)
	{
		sprite.scale(size.x / sprite.getGlobalBounds().width, size.y / sprite.getGlobalBounds().height);

		if(string != "")
			setString(string, *text.getFont(), textSize);
	}

	void Button::draw(sf::RenderTarget& target, sf::RenderStates states) const
	{
		target.draw(sprite, states);
		if(string.length() > 0)
			target.draw(text, states);
	}
}
<commit_msg>Spacing fixes<commit_after>#include "Button.hpp"

namespace cstr
{
	const sf::Color COLOR_CHANGE = {40, 40, 40, 0};
	const int BORDER_SIZE = 2;

	Button::Button(sf::Vector2u size, const sf::Texture& tex, const std::function<void()>& f)
		:	baseColor({128, 128, 128}),
			string(""),
			callback(f),
			textSize(0)
	{
		sprite.setTexture(tex);
		sprite.setColor(baseColor);
		sprite.setScale(size.x / sprite.getGlobalBounds().width, size.y / sprite.getGlobalBounds().height);
	}

	Button::~Button()
	{
	}

	void Button::update(sf::Event& event)
	{
		switch(event.type)
		{
			case sf::Event::MouseMoved:
				if(sprite.getGlobalBounds().contains({static_cast<float>(event.mouseMove.x), static_cast<float>(event.mouseMove.y)}))
				{
					mouseOn = true;
					sprite.setColor(baseColor + COLOR_CHANGE);
				}
				else
				{
					mouseOn = false;
					sprite.setColor(baseColor);
				}
				break;
			case sf::Event::MouseButtonPressed:
				if(mouseOn)
				{
					sprite.setColor(baseColor - COLOR_CHANGE);
				}
				break;
			case sf::Event::MouseButtonReleased:
				if(mouseOn)
				{
					callback();
					sprite.setColor(baseColor);
				}
				break;
			default:
				break;
		}
	}

	void Button::call()
	{
		callback();
	}

	sf::FloatRect Button::getGlobalBounds() const
	{
		return sprite.getGlobalBounds();
	}

	void Button::setString(const std::string& str, const sf::Font& f, unsigned ts)
	{
		string = str;
		text.setFont(f);
		text.setString(string);
		textSize = ts;

		if(textSize != 0)
		{
			text.setCharacterSize(ts);
		}
		else
		{
			text.setCharacterSize(100);
			text.setCharacterSize(text.getCharacterSize() * (sprite.getGlobalBounds().height - 2 * BORDER_SIZE) / text.getLocalBounds().height);
			text.setCharacterSize(text.getCharacterSize() * (sprite.getGlobalBounds().width - 2 * BORDER_SIZE) / text.getLocalBounds().width);
		}

		text.setOrigin({text.getLocalBounds().left + text.getLocalBounds().width / 2, text.getLocalBounds().top + text.getLocalBounds().height / 2});
		text.setPosition({sprite.getGlobalBounds().left + sprite.getGlobalBounds().width / 2, sprite.getGlobalBounds().top + sprite.getGlobalBounds().height / 2});
	}

	void Button::setString(const std::string& str, unsigned ts)
	{
		setString(str, *text.getFont(), ts);
	}

	const std::string& Button::getString() const
	{
		return string;
	}

	void Button::setPosition(sf::Vector2i pos)
	{
		sprite.setPosition(static_cast<sf::Vector2f>(pos));
		text.setPosition({sprite.getGlobalBounds().left + sprite.getGlobalBounds().width / 2, sprite.getGlobalBounds().top + sprite.getGlobalBounds().height / 2});
	}

	void Button::setSize(sf::Vector2u size)
	{
		sprite.scale(size.x / sprite.getGlobalBounds().width, size.y / sprite.getGlobalBounds().height);

		if(string != "")
			setString(string, *text.getFont(), textSize);
	}

	void Button::draw(sf::RenderTarget& target, sf::RenderStates states) const
	{
		target.draw(sprite, states);
		if(string.length() > 0)
			target.draw(text, states);
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * Copyright 2016 Realm Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 **************************************************************************/

#ifndef REALM_IMPL_INPUT_STREAM_HPP
#define REALM_IMPL_INPUT_STREAM_HPP

#include <algorithm>

#include <realm/binary_data.hpp>
#include <realm/impl/continuous_transactions_history.hpp>
#include <realm/util/buffer.hpp>

namespace realm {
namespace _impl {

class InputStream {
public:
    /// Read bytes from this input stream and place them in the specified
    /// buffer. The returned value is the actual number of bytes that were read,
    /// and this is some number `n` such that `n <= min(size, m)` where `m` is
    /// the number of bytes that could have been read from this stream before
    /// reaching its end. Also, `n` cannot be zero unless `m` or `size` is
    /// zero. The intention is that `size` should be non-zero, a the return
    /// value used as the end-of-input indicator.
    ///
    /// Implementations are only allowed to block (put the calling thread to
    /// sleep) up until the point in time where the first byte can be made
    /// availble.
    virtual size_t read(char* buffer, size_t size) = 0;

    virtual ~InputStream() noexcept
    {
    }
};

class SimpleInputStream : public InputStream {
public:
    SimpleInputStream(const char* data, size_t size) noexcept
        : m_ptr(data)
        , m_end(data + size)
    {
    }
    size_t read(char* buffer, size_t size) override
    {
        size_t n = std::min(size, size_t(m_end - m_ptr));
        const char* begin = m_ptr;
        m_ptr += n;
        const char* end = m_ptr;
        std::copy_n(begin, end - begin, buffer);
        return n;
    }

private:
    const char* m_ptr;
    const char* const m_end;
};

class NoCopyInputStream {
public:
    /// \return if any bytes was read.
    /// A value of false indicates end-of-input.
    /// If return value is true, \a begin and \a end are
    /// updated to reflect the start and limit of a
    /// contiguous memory chunk.
    virtual bool next_block(const char*& begin, const char*& end) = 0;

    virtual ~NoCopyInputStream() noexcept
    {
    }
};

class NoCopyInputStreamAdaptor : public NoCopyInputStream {
public:
    NoCopyInputStreamAdaptor(InputStream& in, char* buffer, size_t buffer_size) noexcept
        : m_in(in)
        , m_buffer(buffer)
        , m_buffer_size(buffer_size)
    {
    }
    bool next_block(const char*& begin, const char*& end) override
    {
        size_t n = m_in.read(m_buffer, m_buffer_size);
        begin = m_buffer;
        end = m_buffer + n;
        return n;
    }

private:
    InputStream& m_in;
    char* m_buffer;
    size_t m_buffer_size;
};

class SimpleNoCopyInputStream : public NoCopyInputStream {
public:
    SimpleNoCopyInputStream(const char* data, size_t size)
        : m_data(data)
        , m_size(size)
    {
    }

    bool next_block(const char*& begin, const char*& end) override
    {
        if (m_size == 0)
            return 0;
        size_t size = m_size;
        begin = m_data;
        end = m_data + size;
        m_size = 0;
        return size;
    }

private:
    const char* m_data;
    size_t m_size;
};

class MultiLogNoCopyInputStream : public NoCopyInputStream {
public:
    MultiLogNoCopyInputStream(const BinaryData* logs_begin, const BinaryData* logs_end)
        : m_logs_begin(logs_begin)
        , m_logs_end(logs_end)
    {
        if (m_logs_begin != m_logs_end)
            m_curr_buf_remaining_size = m_logs_begin->size();
    }

    size_t read(char* buffer, size_t size)
    {
        if (m_logs_begin == m_logs_end)
            return 0;
        for (;;) {
            if (m_curr_buf_remaining_size > 0) {
                size_t offset = m_logs_begin->size() - m_curr_buf_remaining_size;
                const char* data = m_logs_begin->data() + offset;
                size_t size_2 = std::min(m_curr_buf_remaining_size, size);
                m_curr_buf_remaining_size -= size_2;
                // FIXME: Eliminate the need for copying by changing the API of
                // Replication::InputStream such that blocks can be handed over
                // without copying. This is a straight forward change, but the
                // result is going to be more complicated and less conventional.
                std::copy_n(data, size_2, buffer);
                return size_2;
            }

            ++m_logs_begin;
            if (m_logs_begin == m_logs_end)
                return 0;
            m_curr_buf_remaining_size = m_logs_begin->size();
        }
    }

    bool next_block(const char*& begin, const char*& end) override
    {
        while (m_logs_begin < m_logs_end) {
            size_t result = m_logs_begin->size();
            const char* data = m_logs_begin->data();
            m_logs_begin++;
            if (result == 0)
                continue; // skip empty blocks
            begin = data;
            end = data + result;
            return result;
        }
        return 0;
    }

private:
    const BinaryData* m_logs_begin;
    const BinaryData* m_logs_end;
    size_t m_curr_buf_remaining_size;
};

class ChangesetInputStream : public NoCopyInputStream {
public:
    using version_type = History::version_type;
    static constexpr unsigned NB_BUFFERS = 8;

    ChangesetInputStream(History& hist, version_type begin_version, version_type end_version)
        : m_history(hist)
        , m_begin_version(begin_version)
        , m_end_version(end_version)
    {
        get_changeset();
    }

    bool next_block(const char*& begin, const char*& end) override
    {
        while (m_valid) {
            BinaryData actual = m_changesets_begin->get_next();

            if (actual.size() > 0) {
                begin = actual.data();
                end = actual.data() + actual.size();
                return true;
            }

            m_changesets_begin++;

            if (REALM_UNLIKELY(m_changesets_begin == m_changesets_end)) {
                get_changeset();
            }
        }
        return false; // End of input
    }

private:
    History& m_history;
    version_type m_begin_version, m_end_version;
    BinaryIterator m_changesets[NB_BUFFERS]; // Buffer
    BinaryIterator* m_changesets_begin = nullptr;
    BinaryIterator* m_changesets_end = nullptr;
    bool m_valid;

    void get_changeset()
    {
        auto versions_to_get = m_end_version - m_begin_version;
        m_valid = versions_to_get > 0;
        if (m_valid) {
            if (versions_to_get > NB_BUFFERS)
                versions_to_get = NB_BUFFERS;
            version_type end_version = m_begin_version + versions_to_get;
            m_history.get_changesets(m_begin_version, end_version, m_changesets);
            m_begin_version = end_version;
            m_changesets_begin = m_changesets;
            m_changesets_end = m_changesets_begin + versions_to_get;
        }
    }
};

} // namespace _impl
} // namespace realm

#endif // REALM_IMPL_INPUT_STREAM_HPP
<commit_msg>Update input_stream.hpp<commit_after>/*************************************************************************
 *
 * Copyright 2016 Realm Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 **************************************************************************/

#ifndef REALM_IMPL_INPUT_STREAM_HPP
#define REALM_IMPL_INPUT_STREAM_HPP

#include <algorithm>

#include <realm/binary_data.hpp>
#include <realm/impl/continuous_transactions_history.hpp>
#include <realm/util/buffer.hpp>

namespace realm {
namespace _impl {

class InputStream {
public:
    /// Read bytes from this input stream and place them in the specified
    /// buffer. The returned value is the actual number of bytes that were read,
    /// and this is some number `n` such that `n <= min(size, m)` where `m` is
    /// the number of bytes that could have been read from this stream before
    /// reaching its end. Also, `n` cannot be zero unless `m` or `size` is
    /// zero. The intention is that `size` should be non-zero, a the return
    /// value used as the end-of-input indicator.
    ///
    /// Implementations are only allowed to block (put the calling thread to
    /// sleep) up until the point in time where the first byte can be made
    /// availble.
    virtual size_t read(char* buffer, size_t size) = 0;

    virtual ~InputStream() noexcept
    {
    }
};

class SimpleInputStream : public InputStream {
public:
    SimpleInputStream(const char* data, size_t size) noexcept
        : m_ptr(data)
        , m_end(data + size)
    {
    }
    size_t read(char* buffer, size_t size) override
    {
        size_t n = std::min(size, size_t(m_end - m_ptr));
        const char* begin = m_ptr;
        m_ptr += n;
        std::copy_n(begin, n, buffer);
        return n;
    }

private:
    const char* m_ptr;
    const char* const m_end;
};

class NoCopyInputStream {
public:
    /// \return if any bytes was read.
    /// A value of false indicates end-of-input.
    /// If return value is true, \a begin and \a end are
    /// updated to reflect the start and limit of a
    /// contiguous memory chunk.
    virtual bool next_block(const char*& begin, const char*& end) = 0;

    virtual ~NoCopyInputStream() noexcept
    {
    }
};

class NoCopyInputStreamAdaptor : public NoCopyInputStream {
public:
    NoCopyInputStreamAdaptor(InputStream& in, char* buffer, size_t buffer_size) noexcept
        : m_in(in)
        , m_buffer(buffer)
        , m_buffer_size(buffer_size)
    {
    }
    bool next_block(const char*& begin, const char*& end) override
    {
        size_t n = m_in.read(m_buffer, m_buffer_size);
        begin = m_buffer;
        end = m_buffer + n;
        return n;
    }

private:
    InputStream& m_in;
    char* m_buffer;
    size_t m_buffer_size;
};

class SimpleNoCopyInputStream : public NoCopyInputStream {
public:
    SimpleNoCopyInputStream(const char* data, size_t size)
        : m_data(data)
        , m_size(size)
    {
    }

    bool next_block(const char*& begin, const char*& end) override
    {
        if (m_size == 0)
            return 0;
        size_t size = m_size;
        begin = m_data;
        end = m_data + size;
        m_size = 0;
        return size;
    }

private:
    const char* m_data;
    size_t m_size;
};

class MultiLogNoCopyInputStream : public NoCopyInputStream {
public:
    MultiLogNoCopyInputStream(const BinaryData* logs_begin, const BinaryData* logs_end)
        : m_logs_begin(logs_begin)
        , m_logs_end(logs_end)
    {
        if (m_logs_begin != m_logs_end)
            m_curr_buf_remaining_size = m_logs_begin->size();
    }

    size_t read(char* buffer, size_t size)
    {
        if (m_logs_begin == m_logs_end)
            return 0;
        for (;;) {
            if (m_curr_buf_remaining_size > 0) {
                size_t offset = m_logs_begin->size() - m_curr_buf_remaining_size;
                const char* data = m_logs_begin->data() + offset;
                size_t size_2 = std::min(m_curr_buf_remaining_size, size);
                m_curr_buf_remaining_size -= size_2;
                // FIXME: Eliminate the need for copying by changing the API of
                // Replication::InputStream such that blocks can be handed over
                // without copying. This is a straight forward change, but the
                // result is going to be more complicated and less conventional.
                std::copy_n(data, size_2, buffer);
                return size_2;
            }

            ++m_logs_begin;
            if (m_logs_begin == m_logs_end)
                return 0;
            m_curr_buf_remaining_size = m_logs_begin->size();
        }
    }

    bool next_block(const char*& begin, const char*& end) override
    {
        while (m_logs_begin < m_logs_end) {
            size_t result = m_logs_begin->size();
            const char* data = m_logs_begin->data();
            m_logs_begin++;
            if (result == 0)
                continue; // skip empty blocks
            begin = data;
            end = data + result;
            return result;
        }
        return 0;
    }

private:
    const BinaryData* m_logs_begin;
    const BinaryData* m_logs_end;
    size_t m_curr_buf_remaining_size;
};

class ChangesetInputStream : public NoCopyInputStream {
public:
    using version_type = History::version_type;
    static constexpr unsigned NB_BUFFERS = 8;

    ChangesetInputStream(History& hist, version_type begin_version, version_type end_version)
        : m_history(hist)
        , m_begin_version(begin_version)
        , m_end_version(end_version)
    {
        get_changeset();
    }

    bool next_block(const char*& begin, const char*& end) override
    {
        while (m_valid) {
            BinaryData actual = m_changesets_begin->get_next();

            if (actual.size() > 0) {
                begin = actual.data();
                end = actual.data() + actual.size();
                return true;
            }

            m_changesets_begin++;

            if (REALM_UNLIKELY(m_changesets_begin == m_changesets_end)) {
                get_changeset();
            }
        }
        return false; // End of input
    }

private:
    History& m_history;
    version_type m_begin_version, m_end_version;
    BinaryIterator m_changesets[NB_BUFFERS]; // Buffer
    BinaryIterator* m_changesets_begin = nullptr;
    BinaryIterator* m_changesets_end = nullptr;
    bool m_valid;

    void get_changeset()
    {
        auto versions_to_get = m_end_version - m_begin_version;
        m_valid = versions_to_get > 0;
        if (m_valid) {
            if (versions_to_get > NB_BUFFERS)
                versions_to_get = NB_BUFFERS;
            version_type end_version = m_begin_version + versions_to_get;
            m_history.get_changesets(m_begin_version, end_version, m_changesets);
            m_begin_version = end_version;
            m_changesets_begin = m_changesets;
            m_changesets_end = m_changesets_begin + versions_to_get;
        }
    }
};

} // namespace _impl
} // namespace realm

#endif // REALM_IMPL_INPUT_STREAM_HPP
<|endoftext|>


<commit_before>/*=========================================================================

  Library   : Image Registration Toolkit (IRTK)
  Module    : $Id$
  Copyright : Imperial College, Department of Computing
              Visual Information Processing (VIP), 2008 onwards
  Date      : $Date$
  Version   : $Revision$
  Changes   : $Author$

=========================================================================*/

#include <irtkImage.h>

#include <irtkImageFunction.h>

irtkLinearInterpolateImageFunction2D::irtkLinearInterpolateImageFunction2D()
{}

irtkLinearInterpolateImageFunction2D::~irtkLinearInterpolateImageFunction2D(void)
{}

const char *irtkLinearInterpolateImageFunction2D::NameOfClass()
{
  return "irtkLinearInterpolateImageFunction2D";
}

void irtkLinearInterpolateImageFunction2D::Initialize()
{
  /// Initialize baseclass
  this->irtkImageFunction::Initialize();

  // Check if image is 2D
  if (this->_input->GetZ() != 1) {
    cerr << "irtkLinearInterpolateImageFunction2D::Initialize(): ";
    cerr << "Input image is not 2D" << endl;
    exit(1);
  }

  // Compute size of image
  this->_x = this->_input->GetX();
  this->_y = this->_input->GetY();

  // Compute domain on which the linear interpolation is defined
  this->_x1 = 0;
  this->_y1 = 0;
  this->_x2 = this->_input->GetX() - 1;
  this->_y2 = this->_input->GetY() - 1;

  // Calculate offsets for fast pixel access
  this->_offset1 = 0;
  this->_offset2 = 1;
  this->_offset3 = this->_input->GetX();
  this->_offset4 = this->_input->GetX()+1;
}

double irtkLinearInterpolateImageFunction2D::EvaluateInside(double x, double y, double z, double time)
{
  int i, j;
  double t1, t2, u1, u2;

  // Calculated integer coordinates
  i  = int(x);
  j  = int(y);

  // Calculated fractional coordinates
  t1 = x - i;
  u1 = y - j;
  t2 = 1 - t1;
  u2 = 1 - u1;

  // Get pointer to data
  switch (this->_input->GetScalarType()) {
  case IRTK_VOXEL_UNSIGNED_SHORT: {
      // Get pointer to data
      unsigned short *ptr = (unsigned short *)this->_input->GetScalarPointer(i, j, round(z), round(time));

      // Linear interpolation
      return (t1 * (u2 * ptr[this->_offset2] + u1 * ptr[this->_offset4]) +
              t2 * (u2 * ptr[this->_offset1] + u1 * ptr[this->_offset3]));

      break;
    }
  case IRTK_VOXEL_SHORT: {
      // Get pointer to data
      short *ptr = (short *)this->_input->GetScalarPointer(i, j, round(z), round(time));

      // Linear interpolation
      return (t1 * (u2 * ptr[this->_offset2] + u1 * ptr[this->_offset4]) +
              t2 * (u2 * ptr[this->_offset1] + u1 * ptr[this->_offset3]));

      break;
    }
  case IRTK_VOXEL_FLOAT: {
      // Get pointer to data
      float *ptr = (float *)this->_input->GetScalarPointer(i, j, round(z), round(time));

      // Linear interpolation
      return (t1 * (u2 * ptr[this->_offset2] + u1 * ptr[this->_offset4]) +
              t2 * (u2 * ptr[this->_offset1] + u1 * ptr[this->_offset3]));

      break;
    }
  default:
    cerr << "irtkLinearInterpolateImageFunction2D::EvaluateInside: Unknown scalar type" << endl;
    exit(1);

  }
}

double irtkLinearInterpolateImageFunction2D::Evaluate(double x, double y, double z, double time)
{
  double val;
  int i, j, k, l, m, t;

  i = (int)floor(x);
  j = (int)floor(y);
  k = round(z);
  t = round(time);

  val = 0;
  for (l = i; l <= i+1; l++) {
    if ((l >= 0) && (l < this->_x)) {
      for (m = j; m <= j+1; m++) {
        if ((m >= 0) && (m < this->_y)) {
          val += (1 - fabs(l - x))*(1 - fabs(m - y))*this->_input->GetAsDouble(l, m, k, t);
        }
      }
    }
  }
  return val;
}

<commit_msg>Allow 2D interpolator to work on double data.<commit_after>/*=========================================================================

  Library   : Image Registration Toolkit (IRTK)
  Module    : $Id$
  Copyright : Imperial College, Department of Computing
              Visual Information Processing (VIP), 2008 onwards
  Date      : $Date$
  Version   : $Revision$
  Changes   : $Author$

=========================================================================*/

#include <irtkImage.h>

#include <irtkImageFunction.h>

irtkLinearInterpolateImageFunction2D::irtkLinearInterpolateImageFunction2D()
{}

irtkLinearInterpolateImageFunction2D::~irtkLinearInterpolateImageFunction2D(void)
{}

const char *irtkLinearInterpolateImageFunction2D::NameOfClass()
{
  return "irtkLinearInterpolateImageFunction2D";
}

void irtkLinearInterpolateImageFunction2D::Initialize()
{
  /// Initialize baseclass
  this->irtkImageFunction::Initialize();

  // Check if image is 2D
  if (this->_input->GetZ() != 1) {
    cerr << "irtkLinearInterpolateImageFunction2D::Initialize(): ";
    cerr << "Input image is not 2D" << endl;
    exit(1);
  }

  // Compute size of image
  this->_x = this->_input->GetX();
  this->_y = this->_input->GetY();

  // Compute domain on which the linear interpolation is defined
  this->_x1 = 0;
  this->_y1 = 0;
  this->_x2 = this->_input->GetX() - 1;
  this->_y2 = this->_input->GetY() - 1;

  // Calculate offsets for fast pixel access
  this->_offset1 = 0;
  this->_offset2 = 1;
  this->_offset3 = this->_input->GetX();
  this->_offset4 = this->_input->GetX()+1;
}

double irtkLinearInterpolateImageFunction2D::EvaluateInside(double x, double y, double z, double time)
{
  int i, j;
  double t1, t2, u1, u2;

  // Calculated integer coordinates
  i  = int(x);
  j  = int(y);

  // Calculated fractional coordinates
  t1 = x - i;
  u1 = y - j;
  t2 = 1 - t1;
  u2 = 1 - u1;

  // Get pointer to data
  switch (this->_input->GetScalarType()) {
  case IRTK_VOXEL_UNSIGNED_SHORT: {
      // Get pointer to data
      unsigned short *ptr = (unsigned short *)this->_input->GetScalarPointer(i, j, round(z), round(time));

      // Linear interpolation
      return (t1 * (u2 * ptr[this->_offset2] + u1 * ptr[this->_offset4]) +
              t2 * (u2 * ptr[this->_offset1] + u1 * ptr[this->_offset3]));

      break;
    }
  case IRTK_VOXEL_SHORT: {
      // Get pointer to data
      short *ptr = (short *)this->_input->GetScalarPointer(i, j, round(z), round(time));

      // Linear interpolation
      return (t1 * (u2 * ptr[this->_offset2] + u1 * ptr[this->_offset4]) +
              t2 * (u2 * ptr[this->_offset1] + u1 * ptr[this->_offset3]));

      break;
    }
  case IRTK_VOXEL_FLOAT: {
      // Get pointer to data
      float *ptr = (float *)this->_input->GetScalarPointer(i, j, round(z), round(time));

      // Linear interpolation
      return (t1 * (u2 * ptr[this->_offset2] + u1 * ptr[this->_offset4]) +
              t2 * (u2 * ptr[this->_offset1] + u1 * ptr[this->_offset3]));

      break;
    }
  case IRTK_VOXEL_DOUBLE: {
      // Get pointer to data
      double *ptr = (double *)this->_input->GetScalarPointer(i, j, round(z), round(time));

      // Linear interpolation
      return (t1 * (u2 * ptr[this->_offset2] + u1 * ptr[this->_offset4]) +
              t2 * (u2 * ptr[this->_offset1] + u1 * ptr[this->_offset3]));

      break;
    }
  default:
    cerr << "irtkLinearInterpolateImageFunction2D::EvaluateInside: Unknown scalar type" << endl;
    exit(1);

  }
}

double irtkLinearInterpolateImageFunction2D::Evaluate(double x, double y, double z, double time)
{
  double val;
  int i, j, k, l, m, t;

  i = (int)floor(x);
  j = (int)floor(y);
  k = round(z);
  t = round(time);

  val = 0;
  for (l = i; l <= i+1; l++) {
    if ((l >= 0) && (l < this->_x)) {
      for (m = j; m <= j+1; m++) {
        if ((m >= 0) && (m < this->_y)) {
          val += (1 - fabs(l - x))*(1 - fabs(m - y))*this->_input->GetAsDouble(l, m, k, t);
        }
      }
    }
  }
  return val;
}

<|endoftext|>


<commit_before>//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//

#include "sys_dev_gpio_native.h"

// clang-format off

static const CLR_RT_MethodHandler method_lookup[] =
{
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioController::get_PinCount___I4,
    NULL,
    NULL,
    NULL,
    NULL,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioController::DisposeNative___VOID,
    NULL,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioController::IsPinModeSupported___BOOLEAN__I4__SystemDeviceGpioPinMode,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioController::IsPinOpen___BOOLEAN__I4,
    NULL,
    NULL,
    NULL,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioController::SetPinMode___VOID__I4__SystemDeviceGpioPinMode,
    NULL,
    NULL,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioController::NativeRead___U1__I4,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioController::NativeWrite___VOID__I4__U1,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Read___SystemDeviceGpioPinValue,
    NULL,
    NULL,
    NULL,
    NULL,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Toggle___VOID,
    NULL,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::DisposeNative___VOID,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeIsDriveModeSupported___BOOLEAN__SystemDeviceGpioPinMode,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetDriveMode___VOID__SystemDeviceGpioPinMode,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeInit___BOOLEAN__I4,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetDebounceTimeout___VOID,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::WriteNative___VOID__SystemDeviceGpioPinValue,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetAlternateFunction___VOID__I4,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
};

const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_System_Device_Gpio =
{
    "System.Device.Gpio",
    0x4F4DD7A8,
    method_lookup,
    { 100, 1, 0, 0 }
};

// clang-format on
<commit_msg>Update System.Device.Gpio assembly (#1734)<commit_after>//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//

#include "sys_dev_gpio_native.h"

// clang-format off

static const CLR_RT_MethodHandler method_lookup[] =
{
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Read___SystemDeviceGpioPinValue,
    NULL,
    NULL,
    NULL,
    NULL,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Toggle___VOID,
    NULL,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::DisposeNative___VOID,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeIsDriveModeSupported___BOOLEAN__SystemDeviceGpioPinMode,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetDriveMode___VOID__SystemDeviceGpioPinMode,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeInit___BOOLEAN__I4,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetDebounceTimeout___VOID,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::WriteNative___VOID__SystemDeviceGpioPinValue,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetAlternateFunction___VOID__I4,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioController::get_PinCount___I4,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioController::DisposeNative___VOID,
    NULL,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioController::IsPinModeSupported___BOOLEAN__I4__SystemDeviceGpioPinMode,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioController::IsPinOpen___BOOLEAN__I4,
    NULL,
    NULL,
    NULL,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioController::SetPinMode___VOID__I4__SystemDeviceGpioPinMode,
    NULL,
    NULL,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioController::NativeRead___U1__I4,
    Library_sys_dev_gpio_native_System_Device_Gpio_GpioController::NativeWrite___VOID__I4__U1,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
};

const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_System_Device_Gpio =
{
    "System.Device.Gpio",
    0xB88842A6,
    method_lookup,
    { 100, 1, 0, 1 }
};

// clang-format on
<|endoftext|>