<commit_before>/*
 cbuf.cpp - Circular buffer implementation
 Copyright (c) 2014 Ivan Grokhotkov. All rights reserved.
 This file is part of the esp8266 core for Arduino environment.

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "cbuf.h"
#include "c_types.h"

cbuf::cbuf(size_t size) :
        _size(size), _buf(new char[size]), _bufend(_buf + size), _begin(_buf), _end(_begin) {
}

cbuf::~cbuf() {
    delete[] _buf;
}

size_t cbuf::resizeAdd(size_t addSize) {
    return resize(_size + addSize);
}

size_t cbuf::resize(size_t newSize) {

    size_t available = getSize();

    if((available > newSize) || (newSize == _size)) {
        return _size;
    }

    char *newbuf = new char[newSize];
    char *oldbuf = _buf;

    if(!newbuf) {
        return _size;
    }

    if(_buf) {
        read(newbuf, available);
        memset((newbuf + available), 0x00, (newSize - available));
    }

    _begin = newbuf;
    _end = newbuf + available;
    _bufend = newbuf + newSize;
    _size = newSize;

    _buf = newbuf;
    delete[] oldbuf;

    return _size;
}

size_t ICACHE_RAM_ATTR cbuf::getSize() const {
    if(_end >= _begin) {
        return _end - _begin;
    }
    return _size - (_begin - _end);
}

size_t cbuf::room() const {
    if(_end >= _begin) {
        return _size - (_end - _begin) - 1;
    }
    return _begin - _end - 1;
}

int cbuf::peek() {
    if(empty())
        return -1;

    return static_cast<int>(*_begin);
}

size_t cbuf::peek(char *dst, size_t size) {
    size_t bytes_available = getSize();
    size_t size_to_read = (size < bytes_available) ? size : bytes_available;
    size_t size_read = size_to_read;
    char * begin = _begin;
    if(_end < _begin && size_to_read > (size_t) (_bufend - _begin)) {
        size_t top_size = _bufend - _begin;
        memcpy(dst, _begin, top_size);
        begin = _buf;
        size_to_read -= top_size;
        dst += top_size;
    }
    memcpy(dst, begin, size_to_read);
    return size_read;
}

int ICACHE_RAM_ATTR cbuf::read() {
    if(empty())
        return -1;

    char result = *_begin;
    _begin = wrap_if_bufend(_begin + 1);
    return static_cast<int>(result);
}

size_t cbuf::read(char* dst, size_t size) {
    size_t bytes_available = getSize();
    size_t size_to_read = (size < bytes_available) ? size : bytes_available;
    size_t size_read = size_to_read;
    if(_end < _begin && size_to_read > (size_t) (_bufend - _begin)) {
        size_t top_size = _bufend - _begin;
        memcpy(dst, _begin, top_size);
        _begin = _buf;
        size_to_read -= top_size;
        dst += top_size;
    }
    memcpy(dst, _begin, size_to_read);
    _begin = wrap_if_bufend(_begin + size_to_read);
    return size_read;
}

size_t ICACHE_RAM_ATTR cbuf::write(char c) {
    if(full())
        return 0;

    *_end = c;
    _end = wrap_if_bufend(_end + 1);
    return 1;
}

size_t cbuf::write(const char* src, size_t size) {
    size_t bytes_available = room();
    size_t size_to_write = (size < bytes_available) ? size : bytes_available;
    size_t size_written = size_to_write;
    if(_end >= _begin && size_to_write > (size_t) (_bufend - _end)) {
        size_t top_size = _bufend - _end;
        memcpy(_end, src, top_size);
        _end = _buf;
        size_to_write -= top_size;
        src += top_size;
    }
    memcpy(_end, src, size_to_write);
    _end = wrap_if_bufend(_end + size_to_write);
    return size_written;
}

void cbuf::flush() {
    _begin = _buf;
    _end = _buf;
}

size_t cbuf::remove(size_t size) {
    size_t bytes_available = getSize();
    if(size >= bytes_available) {
        flush();
        return 0;
    }
    size_t size_to_remove = (size < bytes_available) ? size : bytes_available;
    if(_end < _begin && size_to_remove > (size_t) (_bufend - _begin)) {
        size_t top_size = _bufend - _begin;
        _begin = _buf;
        size_to_remove -= top_size;
    }
    _begin = wrap_if_bufend(_begin + size_to_remove);
    return getSize();
}
<commit_msg>make resize easier to read and add note<commit_after>/*
 cbuf.cpp - Circular buffer implementation
 Copyright (c) 2014 Ivan Grokhotkov. All rights reserved.
 This file is part of the esp8266 core for Arduino environment.

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "cbuf.h"
#include "c_types.h"

cbuf::cbuf(size_t size) :
        _size(size), _buf(new char[size]), _bufend(_buf + size), _begin(_buf), _end(_begin) {
}

cbuf::~cbuf() {
    delete[] _buf;
}

size_t cbuf::resizeAdd(size_t addSize) {
    return resize(_size + addSize);
}

size_t cbuf::resize(size_t newSize) {

    size_t available = getSize();

	// not lose any data
	// if data can be lost use remove or flush before resize
    if((newSize < available) || (newSize == _size)) {
        return _size;
    }

    char *newbuf = new char[newSize];
    char *oldbuf = _buf;

    if(!newbuf) {
        return _size;
    }

    if(_buf) {
        read(newbuf, available);
        memset((newbuf + available), 0x00, (newSize - available));
    }

    _begin = newbuf;
    _end = newbuf + available;
    _bufend = newbuf + newSize;
    _size = newSize;

    _buf = newbuf;
    delete[] oldbuf;

    return _size;
}

size_t ICACHE_RAM_ATTR cbuf::getSize() const {
    if(_end >= _begin) {
        return _end - _begin;
    }
    return _size - (_begin - _end);
}

size_t cbuf::room() const {
    if(_end >= _begin) {
        return _size - (_end - _begin) - 1;
    }
    return _begin - _end - 1;
}

int cbuf::peek() {
    if(empty())
        return -1;

    return static_cast<int>(*_begin);
}

size_t cbuf::peek(char *dst, size_t size) {
    size_t bytes_available = getSize();
    size_t size_to_read = (size < bytes_available) ? size : bytes_available;
    size_t size_read = size_to_read;
    char * begin = _begin;
    if(_end < _begin && size_to_read > (size_t) (_bufend - _begin)) {
        size_t top_size = _bufend - _begin;
        memcpy(dst, _begin, top_size);
        begin = _buf;
        size_to_read -= top_size;
        dst += top_size;
    }
    memcpy(dst, begin, size_to_read);
    return size_read;
}

int ICACHE_RAM_ATTR cbuf::read() {
    if(empty())
        return -1;

    char result = *_begin;
    _begin = wrap_if_bufend(_begin + 1);
    return static_cast<int>(result);
}

size_t cbuf::read(char* dst, size_t size) {
    size_t bytes_available = getSize();
    size_t size_to_read = (size < bytes_available) ? size : bytes_available;
    size_t size_read = size_to_read;
    if(_end < _begin && size_to_read > (size_t) (_bufend - _begin)) {
        size_t top_size = _bufend - _begin;
        memcpy(dst, _begin, top_size);
        _begin = _buf;
        size_to_read -= top_size;
        dst += top_size;
    }
    memcpy(dst, _begin, size_to_read);
    _begin = wrap_if_bufend(_begin + size_to_read);
    return size_read;
}

size_t ICACHE_RAM_ATTR cbuf::write(char c) {
    if(full())
        return 0;

    *_end = c;
    _end = wrap_if_bufend(_end + 1);
    return 1;
}

size_t cbuf::write(const char* src, size_t size) {
    size_t bytes_available = room();
    size_t size_to_write = (size < bytes_available) ? size : bytes_available;
    size_t size_written = size_to_write;
    if(_end >= _begin && size_to_write > (size_t) (_bufend - _end)) {
        size_t top_size = _bufend - _end;
        memcpy(_end, src, top_size);
        _end = _buf;
        size_to_write -= top_size;
        src += top_size;
    }
    memcpy(_end, src, size_to_write);
    _end = wrap_if_bufend(_end + size_to_write);
    return size_written;
}

void cbuf::flush() {
    _begin = _buf;
    _end = _buf;
}

size_t cbuf::remove(size_t size) {
    size_t bytes_available = getSize();
    if(size >= bytes_available) {
        flush();
        return 0;
    }
    size_t size_to_remove = (size < bytes_available) ? size : bytes_available;
    if(_end < _begin && size_to_remove > (size_t) (_bufend - _begin)) {
        size_t top_size = _bufend - _begin;
        _begin = _buf;
        size_to_remove -= top_size;
    }
    _begin = wrap_if_bufend(_begin + size_to_remove);
    return getSize();
}
<|endoftext|>


<commit_before>#include "TwoLevelDetection.h"
#include <opencv2/imgproc/imgproc.hpp>

void TwoLevelDetection(const cv::Mat& input, cv::Mat& output, double detectionLevel, double measurementLevel, TwoLevelDetectionTemp& temp)
{
    if (measurementLevel > detectionLevel) {
        throw std::runtime_error("TwoLevelDetection: it is required that measurementLevel <= detectionLevel");
    }

    cv::threshold(input, output, measurementLevel, 1, cv::THRESH_BINARY);

    temp.contours.clear();
    cv::findContours(output, temp.contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);

    temp.mask.create(input.size(), CV_8UC1);

    output.setTo(0);

    for (size_t i = 0, end = temp.contours.size(); i < end; ++i) {
        temp.mask.setTo(0);
        cv::drawContours(temp.mask, temp.contours, static_cast<int>(i), 255, -1);

        double minVal, maxVal;
        cv::minMaxIdx(input, &minVal, &maxVal, NULL, NULL, temp.mask);

        if (maxVal >= detectionLevel) {
            output.setTo(1, temp.mask);
        }
    }
}
<commit_msg>Change two-level detection result output to 255 (was 1).<commit_after>#include "TwoLevelDetection.h"
#include <opencv2/imgproc/imgproc.hpp>

void TwoLevelDetection(const cv::Mat& input, cv::Mat& output, double detectionLevel, double measurementLevel, TwoLevelDetectionTemp& temp)
{
    if (measurementLevel > detectionLevel) {
        throw std::runtime_error("TwoLevelDetection: it is required that measurementLevel <= detectionLevel");
    }

    cv::threshold(input, output, measurementLevel, 1, cv::THRESH_BINARY);

    temp.contours.clear();
    cv::findContours(output, temp.contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);

    temp.mask.create(input.size(), CV_8UC1);

    output.setTo(0);

    for (size_t i = 0, end = temp.contours.size(); i < end; ++i) {
        temp.mask.setTo(0);
        cv::drawContours(temp.mask, temp.contours, static_cast<int>(i), 255, -1);

        double minVal, maxVal;
        cv::minMaxIdx(input, &minVal, &maxVal, NULL, NULL, temp.mask);

        if (maxVal >= detectionLevel) {
            output.setTo(std::numeric_limits<unsigned char>::max(), temp.mask);
        }
    }
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qgeopositioninfosource.h"

/*!
    \class QGeoPositionInfoSource
    \brief The QGeoPositionInfoSource class is an abstract base class for the distribution of positional updates.

    The static function QGeoPositionInfoSource::createSource() creates a default
    position source that is appropriate for the platform, if one is available.
    Otherwise, QGeoPositionInfoSource can be subclassed to create an appropriate
    custom source of position data.

    Users of a QGeoPositionInfoSource subclass can request the current position using
    requestUpdate(), or start and stop regular position updates using
    startUpdates() and stopUpdates(). When an update is available,
    positionUpdate() is emitted. The last known position can be accessed with
    lastUpdate().

    If regular position updates are required, setUpdateInterval() can be used
    to specify how often these updates should be emitted. (If no interval is
    specified, updates are simply provided whenever they are available.)
    For example:

    \code
        // Emit updates every 10 seconds if available
        QGeoPositionInfoSource *source = QGeoPositionInfoSource::createSource();
        source->setUpdateInterval(10000);
    \endcode

    To remove an update interval that was previously set, call
    setUpdateInterval() with a value of 0.

    Note that the position source may have a minimum value requirement for
    update intervals, as returned by minimumIntervalForType().
*/

/*!
    \enum QGeoPositionInfoSource::PositioningMethod
    Defines the types of positioning methods.

    \value SatellitePositioningMethods Satellite-based positioning methods such as GPS.
    \value NonSatellitePositioningMethods Other positioning methods.
    \value AllPositioningMethods A flag that matches all positioning methods.
*/

class QGeoPositionInfoSourcePrivate
{
public:
    int interval;
    QGeoPositionInfoSource::PositioningMethods methods;
};

/*!
    Creates a position source with the specified \a parent.
*/

QGeoPositionInfoSource::QGeoPositionInfoSource(QObject *parent)
    : QObject(parent),
      d(new QGeoPositionInfoSourcePrivate)
{
    d->interval = 0;
    d->methods = 0;
}

/*!
    Destroys the position source.
*/
QGeoPositionInfoSource::~QGeoPositionInfoSource()
{
    delete d;
}

/*!
    Sets the source to emit updates every \a msec milliseconds.
    If \a msec is 0, interval-based updates are disabled and the source
    provides updates whenever they are available.

    If \a msec is not 0 and is less than the value returned by
    minimumUpdateInterval(), the interval will be set to the minimum interval.

    Note that implementations may not provide updates at the exact
    interval specified. For example, a given millisecond interval value may be
    rounded to the nearest second if the implementation does not support
    intervals specified to millisecond precision.

    \bold {Note:} When reimplementing this method, subclasses must call the
    base method implementation to ensure updateInterval() returns the correct
    value.
*/
void QGeoPositionInfoSource::setUpdateInterval(int msec)
{
    d->interval = msec;
}

/*!
    Returns the interval value set by setUpdateInterval().

    Returns 0 if no interval has been set.
*/
int QGeoPositionInfoSource::updateInterval() const
{
    return d->interval;
}

/*!
    Sets the preferred positioning methods for this source to \a methods.

    \bold {Note:} When reimplementing this method, subclasses must call the
    base method implementation to ensure preferredPositioningMethods() returns the correct value.

    \sa supportedPositioningMethods()
*/

void QGeoPositionInfoSource::setPreferredPositioningMethods(PositioningMethods methods)
{
    d->methods = methods;
}

/*!
    Returns the positioning methods set by setPreferredPositioningMethods().
*/
QGeoPositionInfoSource::PositioningMethods QGeoPositionInfoSource::preferredPositioningMethods() const
{
    return d->methods;
}

/*!
    Creates and returns a position source with the given \a parent that
    reads from the system's default sources of location data.

    Returns 0 if the system has no default position source.
*/

QGeoPositionInfoSource *QGeoPositionInfoSource::createSource(QObject *)
{
    return 0;
}

/*!
    \fn QGeoPositionInfo QGeoPositionInfoSource::lastKnownPosition(bool fromSatellitePositioningMethodsOnly = false) const = 0;

    Returns an update containing the last known position, or a null update
    if none is available.

    If \a fromSatellitePositioningMethodsOnly is true, this returns the last
    known position received from a satellite positioning method; if none
    is available, a null update is returned.
*/

/*!
    \fn virtual PositioningMethods QGeoPositionInfoSource::supportedPositioningMethods() const = 0;

    Returns the positioning methods available to this source.

    \sa setPreferredPositioningMethods()
*/

/*!
    \fn virtual int QGeoPositionInfoSource::minimumUpdateInterval() const = 0;

    Returns the minimum value accepted by setUpdateInterval().
*/

/*!
    \fn virtual void QGeoPositionInfoSource::startUpdates() = 0;

    Starts emitting updates at regular intervals as specified by setUpdateInterval().

    If setUpdateInterval() has not been called, the source will emit updates
    as soon as they become available.
*/

/*!
    \fn virtual void QGeoPositionInfoSource::stopUpdates() = 0;

    Stops emitting updates at regular intervals.
*/

/*!
    \fn virtual void QGeoPositionInfoSource::requestUpdate(int timeout = 5000);

    Attempts to get the current position and emit positionUpdated() with
    this information. This is useful if you do not need the regular updates
    provided by startUpdates(). If the current position cannot be found
    within the given \a timeout (in milliseconds), requestTimeout() is
    emitted.

    This does nothing if another update request is in progress. However
    it can be called even if startUpdates() has already been called and
    regular updates are in progress.

    If the source uses multiple positioning methods, it tries to gets the
    current position from the most accurate positioning method within the
    given timeout.
*/

/*!
    \fn void QGeoPositionInfoSource::positionUpdated(const QGeoPositionInfo &update);

    If startUpdates() or requestUpdate() is called, this signal is emitted
    when an update becomes available.

    The \a update value holds the value of the new update.
*/

/*!
    \fn void QGeoPositionInfoSource::requestTimeout();

    Emitted if requestUpdate() was called and the current position could
    not be retrieved within the specified timeout.
*/
<commit_msg>Update docs.<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qgeopositioninfosource.h"

/*!
    \class QGeoPositionInfoSource
    \brief The QGeoPositionInfoSource class is an abstract base class for the distribution of positional updates.

    The static function QGeoPositionInfoSource::createSource() creates a default
    position source that is appropriate for the platform, if one is available.
    Otherwise, QGeoPositionInfoSource can be subclassed to create an appropriate
    custom source of position data.

    Users of a QGeoPositionInfoSource subclass can request the current position using
    requestUpdate(), or start and stop regular position updates using
    startUpdates() and stopUpdates(). When an update is available,
    positionUpdate() is emitted. The last known position can be accessed with
    lastUpdate().

    If regular position updates are required, setUpdateInterval() can be used
    to specify how often these updates should be emitted. (If no interval is
    specified, updates are simply provided whenever they are available.)
    For example:

    \code
        // Emit updates every 10 seconds if available
        QGeoPositionInfoSource *source = QGeoPositionInfoSource::createSource();
        source->setUpdateInterval(10000);
    \endcode

    To remove an update interval that was previously set, call
    setUpdateInterval() with a value of 0.

    Note that the position source may have a minimum value requirement for
    update intervals, as returned by minimumIntervalForType().
*/

/*!
    \enum QGeoPositionInfoSource::PositioningMethod
    Defines the types of positioning methods.

    \value SatellitePositioningMethods Satellite-based positioning methods such as GPS.
    \value NonSatellitePositioningMethods Other positioning methods.
    \value AllPositioningMethods A flag that matches all positioning methods.
*/

class QGeoPositionInfoSourcePrivate
{
public:
    int interval;
    QGeoPositionInfoSource::PositioningMethods methods;
};

/*!
    Creates a position source with the specified \a parent.
*/

QGeoPositionInfoSource::QGeoPositionInfoSource(QObject *parent)
    : QObject(parent),
      d(new QGeoPositionInfoSourcePrivate)
{
    d->interval = 0;
    d->methods = 0;
}

/*!
    Destroys the position source.
*/
QGeoPositionInfoSource::~QGeoPositionInfoSource()
{
    delete d;
}

/*!
    Sets the source to emit updates every \a msec milliseconds.
    If \a msec is 0, interval-based updates are disabled and the source
    provides updates whenever they are available.

    If \a msec is not 0 and is less than the value returned by
    minimumUpdateInterval(), the interval will be set to the minimum interval.

    Note that implementations may not provide updates at the exact
    interval specified. For example, a given millisecond interval value may be
    rounded to the nearest second if the implementation does not support
    intervals specified to millisecond precision.

    If an implementation cannot provide an update at a particular interval,
    it will provide the next update as soon as it becomes available.

    \bold {Note:} When reimplementing this method, subclasses must call the
    base method implementation to ensure updateInterval() returns the correct
    value.
*/
void QGeoPositionInfoSource::setUpdateInterval(int msec)
{
    d->interval = msec;
}

/*!
    Returns the interval value set by setUpdateInterval().

    Returns 0 if no interval has been set.
*/
int QGeoPositionInfoSource::updateInterval() const
{
    return d->interval;
}

/*!
    Sets the preferred positioning methods for this source to \a methods.

    \bold {Note:} When reimplementing this method, subclasses must call the
    base method implementation to ensure preferredPositioningMethods() returns the correct value.

    \sa supportedPositioningMethods()
*/

void QGeoPositionInfoSource::setPreferredPositioningMethods(PositioningMethods methods)
{
    d->methods = methods;
}

/*!
    Returns the positioning methods set by setPreferredPositioningMethods().
*/
QGeoPositionInfoSource::PositioningMethods QGeoPositionInfoSource::preferredPositioningMethods() const
{
    return d->methods;
}

/*!
    Creates and returns a position source with the given \a parent that
    reads from the system's default sources of location data.

    Returns 0 if the system has no default position source.
*/

QGeoPositionInfoSource *QGeoPositionInfoSource::createSource(QObject *)
{
    return 0;
}

/*!
    \fn QGeoPositionInfo QGeoPositionInfoSource::lastKnownPosition(bool fromSatellitePositioningMethodsOnly = false) const = 0;

    Returns an update containing the last known position, or a null update
    if none is available.

    If \a fromSatellitePositioningMethodsOnly is true, this returns the last
    known position received from a satellite positioning method; if none
    is available, a null update is returned.
*/

/*!
    \fn virtual PositioningMethods QGeoPositionInfoSource::supportedPositioningMethods() const = 0;

    Returns the positioning methods available to this source.

    \sa setPreferredPositioningMethods()
*/

/*!
    \fn virtual int QGeoPositionInfoSource::minimumUpdateInterval() const = 0;

    Returns the minimum value accepted by setUpdateInterval().
*/

/*!
    \fn virtual void QGeoPositionInfoSource::startUpdates() = 0;

    Starts emitting updates at regular intervals as specified by setUpdateInterval().

    If setUpdateInterval() has not been called, the source will emit updates
    as soon as they become available.
*/

/*!
    \fn virtual void QGeoPositionInfoSource::stopUpdates() = 0;

    Stops emitting updates at regular intervals.
*/

/*!
    \fn virtual void QGeoPositionInfoSource::requestUpdate(int timeout = 5000);

    Attempts to get the current position and emit positionUpdated() with
    this information. This is useful if you do not need the regular updates
    provided by startUpdates(). If the current position cannot be found
    within the given \a timeout (in milliseconds), requestTimeout() is
    emitted.

    This does nothing if another update request is in progress. However
    it can be called even if startUpdates() has already been called and
    regular updates are in progress.

    If the source uses multiple positioning methods, it tries to gets the
    current position from the most accurate positioning method within the
    given timeout.
*/

/*!
    \fn void QGeoPositionInfoSource::positionUpdated(const QGeoPositionInfo &update);

    If startUpdates() or requestUpdate() is called, this signal is emitted
    when an update becomes available.

    The \a update value holds the value of the new update.
*/

/*!
    \fn void QGeoPositionInfoSource::requestTimeout();

    Emitted if requestUpdate() was called and the current position could
    not be retrieved within the specified timeout.
*/
<|endoftext|>


<commit_before>//
//  main.cpp
//  TraceRay
//
//  Created by LazyLie on 15/5/10.
//  Copyright (c) 2015年 LeonardXu. All rights reserved.
//

#include <iostream>
#include "scene.h"

Scene scene;

int main(int argc, const char * argv[]) {
  scene.MC_NUM = 5000;

  scene.camera.position = Vector(5, 5, 20);
  scene.camera.filmCenter = Vector(5, 5, 10);
  scene.camera.pixHeight = 500;
  scene.camera.pixWidth = 500;
  scene.camera.filmHeight = Vector(0, -10, 0);
  scene.camera.filmWidth = Vector(10, 0, 0);
  scene.camera.aperture = 0.001;
  scene.camera.sample = 0;
  scene.camera.dis = 4;

  scene.MAX_DEP = 5;

  //ceil
  Rect *rect = new Rect();
  rect->position = Vector(0, 10, 0);
  rect->dx = Vector(10, 0, 0);
  rect->dy = Vector(0, 0, 10);
  rect->attribute.ks = Vector(0, 0, 0);
  rect->attribute.kd = Vector(0.8, 0.8, 0.8);
  rect->attribute.ka = Vector(0, 0, 0);
  rect->attribute.kt = Vector(0, 0, 0);
  scene.item.push_back(make_pair(RECT, rect));

  //floor
  rect = new Rect();
  rect->position = Vector(0, 0, 0);
  rect->dx = Vector(0, 0, 10);
  rect->dy = Vector(10, 0, 0);
  rect->attribute.ks = Vector(0, 0, 0);
  rect->attribute.kd = Vector(0.8, 0.8, 0.8);
  rect->attribute.ka = Vector(0, 0, 0);
  rect->attribute.kt = Vector(0, 0, 0);
//  rect->attribute.loadImg("floor.png");
  scene.item.push_back(make_pair(RECT, rect));

  //left
  rect = new Rect();
  rect->position = Vector(0, 0, 0);
  rect->dx = Vector(0, 10, 0);
  rect->dy = Vector(0, 0, 10);
  rect->attribute.ks = Vector(0, 0, 0);
  rect->attribute.kd = Vector(0.8, 0, 0);
  rect->attribute.ka = Vector(0, 0, 0);
  rect->attribute.kt = Vector(0, 0, 0);
  scene.item.push_back(make_pair(RECT, rect));

  //right
  rect = new Rect();
  rect->position = Vector(10, 0, 0);
  rect->dx = Vector(0, 0, 10);
  rect->dy = Vector(0, 10, 0);
  rect->attribute.ks = Vector(0, 0, 0);
  rect->attribute.kd = Vector(0, 0, 0.8);
  rect->attribute.ka = Vector(0, 0, 0);
  rect->attribute.kt = Vector(0, 0, 0);
  scene.item.push_back(make_pair(RECT, rect));

  //back
  rect = new Rect();
  rect->position = Vector(0, 0, 0);
  rect->dx = Vector(10, 0, 0);
  rect->dy = Vector(0, 10, 0);
  rect->attribute.ks = Vector(0, 0, 0);
  rect->attribute.kd = Vector(0.8, 0.8, 0.8);
  rect->attribute.ka = Vector(0, 0, 0);
  rect->attribute.kt = Vector(0, 0, 0);
  scene.item.push_back(make_pair(RECT, rect));

  Ball *ball = new Ball();
  ball->position = Vector(5, 2, 5);
  ball->radius = 2;
  ball->attribute.ks = Vector(0, 0, 0);
  ball->attribute.kd = Vector(0, 0, 0);
  ball->attribute.ka = Vector(0, 0, 0);
  ball->attribute.kt = Vector(1, 1, 1);
  ball->attribute.index = 1.7;
  scene.item.push_back(make_pair(BALL, ball));

//  Attribute attr;
//  attr.ks = Vector(0.3, 0.3, 0.3);
//  attr.kd = Vector(0.6, 0.6, 0.6);
//  attr.ka = Vector(0, 0, 0);
//  attr.kt = Vector(0, 0, 0);
////  attr.loadImg("marble.png");
//  insertBox(scene.item, Vector(1, 0, 4), Vector(2, 0, -2), Vector(0, 6, 0), Vector(2, 0, 2), attr);
//  insertBox(scene.item, Vector(5, 0, 7), Vector(2, 0, 0), Vector(0, 3, 0), Vector(0, 0, 2), attr);

  Rect lit;
  lit.position = Vector(3, 9.99, 3);
  lit.dx = Vector(4, 0, 0);
  lit.dy = Vector(0, 0, 4);
  lit.attribute.ka = Vector(1, 1, 1);
  lit.attribute.kd = Vector(0, 0, 0);
  lit.attribute.ks = Vector(0, 0, 0);
  lit.attribute.kt = Vector(0, 0, 0);
  scene.light = lit;
  scene.lightSample = 5;

  scene.render();
  scene.save("out.png");
  return 0;
}
<commit_msg>change color<commit_after>//
//  main.cpp
//  TraceRay
//
//  Created by LazyLie on 15/5/10.
//  Copyright (c) 2015年 LeonardXu. All rights reserved.
//

#include <iostream>
#include "scene.h"

Scene scene;

int main(int argc, const char * argv[]) {
  scene.MC_NUM = 1000;

  scene.camera.position = Vector(5, 5, 20);
  scene.camera.filmCenter = Vector(5, 5, 10);
  scene.camera.pixHeight = 500;
  scene.camera.pixWidth = 500;
  scene.camera.filmHeight = Vector(0, -10, 0);
  scene.camera.filmWidth = Vector(10, 0, 0);
  scene.camera.aperture = 0.001;
  scene.camera.sample = 0;
  scene.camera.dis = 4;

  scene.MAX_DEP = 5;

  //ceil
  Rect *rect = new Rect();
  rect->position = Vector(0, 10, 0);
  rect->dx = Vector(10, 0, 0);
  rect->dy = Vector(0, 0, 10);
  rect->attribute.ks = Vector(0, 0, 0);
  rect->attribute.kd = Vector(0.95, 0.95, 0.8);
  rect->attribute.ka = Vector(0, 0, 0);
  rect->attribute.kt = Vector(0, 0, 0);
  scene.item.push_back(make_pair(RECT, rect));

  //floor
  rect = new Rect();
  rect->position = Vector(0, 0, 0);
  rect->dx = Vector(0, 0, 10);
  rect->dy = Vector(10, 0, 0);
  rect->attribute.ks = Vector(0, 0, 0);
  rect->attribute.kd = Vector(0.95, 0.95, 0.8);
  rect->attribute.ka = Vector(0, 0, 0);
  rect->attribute.kt = Vector(0, 0, 0);
//  rect->attribute.loadImg("floor.png");
  scene.item.push_back(make_pair(RECT, rect));

  //left
  rect = new Rect();
  rect->position = Vector(0, 0, 0);
  rect->dx = Vector(0, 10, 0);
  rect->dy = Vector(0, 0, 10);
  rect->attribute.ks = Vector(0, 0, 0);
  rect->attribute.kd = Vector(0.7, 0.15, 0.15);
  rect->attribute.ka = Vector(0, 0, 0);
  rect->attribute.kt = Vector(0, 0, 0);
  scene.item.push_back(make_pair(RECT, rect));

  //right
  rect = new Rect();
  rect->position = Vector(10, 0, 0);
  rect->dx = Vector(0, 0, 10);
  rect->dy = Vector(0, 10, 0);
  rect->attribute.ks = Vector(0, 0, 0);
  rect->attribute.kd = Vector(0.4, 0.2, 0.6);
  rect->attribute.ka = Vector(0, 0, 0);
  rect->attribute.kt = Vector(0, 0, 0);
  scene.item.push_back(make_pair(RECT, rect));

  //back
  rect = new Rect();
  rect->position = Vector(0, 0, 0);
  rect->dx = Vector(10, 0, 0);
  rect->dy = Vector(0, 10, 0);
  rect->attribute.ks = Vector(0, 0, 0);
  rect->attribute.kd = Vector(0.95, 0.95, 0.8);
  rect->attribute.ka = Vector(0, 0, 0);
  rect->attribute.kt = Vector(0, 0, 0);
  scene.item.push_back(make_pair(RECT, rect));

  Ball *ball = new Ball();
  ball->position = Vector(7, 2.1, 7);
  ball->radius = 2;
  ball->attribute.ks = Vector(0, 0, 0);
  ball->attribute.kd = Vector(0, 0, 0);
  ball->attribute.ka = Vector(0, 0, 0);
  ball->attribute.kt = Vector(1, 1, 1);
  ball->attribute.index = 1.7;
  scene.item.push_back(make_pair(BALL, ball));

  ball = new Ball();
  ball->position = Vector(3, 2.1, 3);
  ball->radius = 2;
  ball->attribute.ks = Vector(1, 1, 1);
  ball->attribute.kd = Vector(0, 0, 0);
  ball->attribute.ka = Vector(0, 0, 0);
  ball->attribute.kt = Vector(0, 0, 0);
  ball->attribute.index = 1.7;
  scene.item.push_back(make_pair(BALL, ball));

//  Attribute attr;
//  attr.ks = Vector(0.3, 0.3, 0.3);
//  attr.kd = Vector(0.6, 0.6, 0.6);
//  attr.ka = Vector(0, 0, 0);
//  attr.kt = Vector(0, 0, 0);
////  attr.loadImg("marble.png");
//  insertBox(scene.item, Vector(1, 0, 4), Vector(2, 0, -2), Vector(0, 6, 0), Vector(2, 0, 2), attr);
//  insertBox(scene.item, Vector(5, 0, 7), Vector(2, 0, 0), Vector(0, 3, 0), Vector(0, 0, 2), attr);

  Rect lit;
  lit.position = Vector(3, 9.999, 3);
  lit.dx = Vector(4, 0, 0);
  lit.dy = Vector(0, 0, 4);
  lit.attribute.ka = Vector(1, 1, 1);
  lit.attribute.kd = Vector(0, 0, 0);
  lit.attribute.ks = Vector(0, 0, 0);
  lit.attribute.kt = Vector(0, 0, 0);
  scene.light = lit;
  scene.lightSample = 5;

  scene.render();
  scene.save("out.png");
  return 0;
}
<|endoftext|>


<commit_before>#ifndef PYTHONIC_INCLUDE_TYPES_LIST_HPP
#define PYTHONIC_INCLUDE_TYPES_LIST_HPP

#include "pythonic/include/types/assignable.hpp"
#include "pythonic/include/types/empty_iterator.hpp"
#include "pythonic/include/types/nditerator.hpp"
#include "pythonic/include/utils/shared_ref.hpp"
#include "pythonic/include/utils/nested_container.hpp"
#include "pythonic/include/utils/int_.hpp"
#include "pythonic/include/utils/reserve.hpp"
#include "pythonic/include/types/slice.hpp"

#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <iterator>

#ifdef USE_BOOST_SIMD
#include <boost/simd/sdk/simd/native.hpp>
#include <boost/simd/include/functions/load.hpp>
#include <boost/simd/include/functions/store.hpp>
#endif

namespace pythonic
{

  namespace types
  {

    static const size_t DEFAULT_LIST_CAPACITY = 16;

    /* forward declaration */
    struct empty_list;
    template <class T>
    class list;
    template <class T, class S>
    class sliced_list;
    template <class T, size_t N>
    struct ndarray;
    template <class T>
    struct is_list {
      static const bool value = false;
    };
    template <class T>
    struct is_list<list<T>> {
      static const bool value = true;
    };
    template <class T, class S>
    struct is_list<sliced_list<T, S>> {
      static const bool value = true;
    };

    /* for type disambiguification */
    struct single_value {
    };

    /* list view */
    template <class T, class S = slice>
    class sliced_list
    {

      // data holder
      typedef
          typename std::remove_cv<typename std::remove_reference<T>::type>::type
              _type;
      typedef std::vector<_type> container_type;
      utils::shared_ref<container_type> data;

      template <class U>
      friend class list;

      typename S::normalized_type slicing;

    public:
      //  types
      typedef typename container_type::reference reference;
      typedef typename container_type::const_reference const_reference;
      typedef typename container_type::iterator iterator;
      typedef typename container_type::const_iterator const_iterator;
      typedef typename container_type::size_type size_type;
      typedef typename container_type::difference_type difference_type;
      typedef typename container_type::value_type value_type;
      typedef typename container_type::allocator_type allocator_type;
      typedef typename container_type::pointer pointer;
      typedef typename container_type::const_pointer const_pointer;
      typedef typename container_type::reverse_iterator reverse_iterator;
      typedef typename container_type::const_reverse_iterator
          const_reverse_iterator;

      // minimal ndarray interface
      typedef
          typename utils::nested_container_value_type<sliced_list>::type dtype;
      static const size_t value =
          utils::nested_container_depth<sliced_list>::value;
      static const bool is_vectorizable = false; // overly cautious \simeq lazy

      // constructor
      sliced_list();
      sliced_list(sliced_list<T, S> const &s);
      sliced_list(list<T> &other, S const &s);

      // assignment
      sliced_list &operator=(list<T> const &);
      sliced_list &operator=(sliced_list<T, S> const &);
      list<T> operator+(list<T> const &);
      list<T> operator+(sliced_list<T, S> const &);

      // iterators
      iterator begin();
      const_iterator begin() const;
      iterator end();
      const_iterator end() const;

      // size
      long size() const;

      // accessor
      T const &operator[](long i) const;
      T &operator[](long i);

      // comparison
      template <class K>
      bool operator==(list<K> const &other) const;
      bool operator==(empty_list const &other) const;
    };

    /* list */
    template <class T>
    class list
    {

      // data holder
      typedef
          typename std::remove_cv<typename std::remove_reference<T>::type>::type
              _type;
      typedef std::vector<_type> container_type;
      utils::shared_ref<container_type> data;

      template <class U, class S>
      friend class sliced_list;

      template <class U>
      friend class list;

    public:
      // types
      typedef typename container_type::value_type value_type;
      typedef typename container_type::reference reference;
      typedef typename container_type::const_reference const_reference;
      typedef typename container_type::iterator iterator;
      typedef typename container_type::const_iterator const_iterator;
      typedef typename container_type::size_type size_type;
      typedef typename container_type::difference_type difference_type;
      typedef typename container_type::allocator_type allocator_type;
      typedef typename container_type::pointer pointer;
      typedef typename container_type::const_pointer const_pointer;
      typedef typename container_type::reverse_iterator reverse_iterator;
      typedef typename container_type::const_reverse_iterator
          const_reverse_iterator;

      // minimal ndarray interface
      typedef typename utils::nested_container_value_type<list>::type dtype;
      static const size_t value = utils::nested_container_depth<list>::value;
      static const bool is_vectorizable = true;
      static const bool is_strided = false;

      // constructors
      list();
      template <class InputIterator>
      list(InputIterator start, InputIterator stop);
      list(empty_list const &);
      list(size_type sz);
      list(T const &value, single_value);
      list(std::initializer_list<T> l);
      list(list<T> &&other);
      list(list<T> const &other);
      template <class F>
      list(list<F> const &other);
      template <class S>
      list(sliced_list<T, S> const &other);
      list<T> &operator=(list<T> &&other);
      template <class F>
      list<T> &operator=(list<F> const &other);
      list<T> &operator=(list<T> const &other);
      list<T> &operator=(empty_list const &);
      template <class S>
      list<T> &operator=(sliced_list<T, S> const &other);

      list &operator=(ndarray<T, 1> const &); // implemented in ndarray.hpp

      template <class S>
      list<T> &operator+=(sliced_list<T, S> const &other);
      template <class S>
      list<T> operator+(sliced_list<T, S> const &other) const;

      // io
      template <class S>
      friend std::ostream &operator<<(std::ostream &os, list<S> const &v);

      // comparison
      template <class K>
      bool operator==(list<K> const &other) const;
      bool operator==(empty_list const &) const;
      template <class K>
      bool operator!=(list<K> const &other) const;
      bool operator!=(empty_list const &) const;

      // iterators
      iterator begin();
      const_iterator begin() const;
      iterator end();
      const_iterator end() const;
      reverse_iterator rbegin();
      const_reverse_iterator rbegin() const;
      reverse_iterator rend();
      const_reverse_iterator rend() const;

      // comparison
      int operator<(list<T> const &other) const;

// element access
#ifdef USE_BOOST_SIMD
      using simd_iterator = const_simd_nditerator<list>;
      simd_iterator vbegin() const;
      simd_iterator vend() const;
      auto load(long i) const -> decltype(boost::simd::load<
          boost::simd::native<T, BOOST_SIMD_DEFAULT_EXTENSION>>((*this->data),
                                                                i));
      template <class V>
      void store(V &&v, long i);
#endif
      reference fast(long n);
      reference operator[](long n);

      const_reference fast(long n) const;
      const_reference operator[](long n) const;

      list<T> operator[](slice const &s) const;
      list<T> operator[](contiguous_slice const &s) const;

      sliced_list<T, slice> operator()(slice const &s) const;
      sliced_list<T, contiguous_slice>
      operator()(contiguous_slice const &s) const;

      // modifiers
      void push_back(T const &x);
      void insert(long i, T const &x);

      void reserve(size_t n);
      void resize(size_t n);
      iterator erase(size_t n);

      T pop(long x = -1);

      // TODO: have to raise a valueError
      none_type remove(T const &x);

      // Misc
      // TODO: have to raise a valueError
      long index(T const &x) const;

      // list interface
      explicit operator bool() const;

      template <class F>
      list<decltype(std::declval<T>() +
                    std::declval<typename list<F>::value_type>())>
      operator+(list<F> const &s) const;

      template <class F, class S>
      list<decltype(std::declval<T>() +
                    std::declval<typename sliced_list<F, S>::value_type>())>
      operator+(sliced_list<F, S> const &s) const;

      list<T> operator+(empty_list const &) const;
      list<T> operator*(long t) const;

      template <class F>
      list<T> &operator+=(list<F> const &s);
      long size() const;
      template <class E>
      long _flat_size(E const &e, utils::int_<1>) const;
      template <class E, size_t L>
      long _flat_size(E const &e, utils::int_<L>) const;
      long flat_size() const;

      template <class V>
      bool contains(V const &v) const;
      intptr_t id() const;

      long count(T const &x) const;
      array<long, value> shape() const;
    };

    /* empty list implementation */
    struct empty_list {
      typedef void value_type;
      typedef empty_iterator iterator;
      typedef empty_iterator const_iterator;
      template <class T>
      list<T> operator+(list<T> const &s) const;
      template <class T, class S>
      sliced_list<T, S> operator+(sliced_list<T, S> const &s) const;
      empty_list operator+(empty_list const &) const;
      operator bool() const;
      template <class T>
      operator list<T>() const;
      static constexpr long size();
    };

    std::ostream &operator<<(std::ostream &os, empty_list const &);
  }

  namespace utils
  {
    /**
     * Reserve enough space to save all values generated from f.
     *
     * We use a dummy arguments (p) to reserve only when f have a
     * const_iterator type.
     */
    template <class T, class From>
    void reserve(types::list<T> &l, From const &f,
                 typename From::const_iterator *p = nullptr);
  }

  template <class T>
  struct assignable<types::list<T>> {
    typedef types::list<typename assignable<T>::type> type;
  };
}

/* overload std::get */
namespace std
{
  template <size_t I, class T>
  typename pythonic::types::list<T>::reference get(pythonic::types::list<T> &t);

  template <size_t I, class T>
  typename pythonic::types::list<T>::const_reference
  get(pythonic::types::list<T> const &t);

  template <size_t I, class T>
  typename pythonic::types::list<T>::value_type
  get(pythonic::types::list<T> &&t);

  template <size_t I, class T>
  typename pythonic::types::sliced_list<T>::reference
  get(pythonic::types::sliced_list<T> &t);

  template <size_t I, class T>
  typename pythonic::types::sliced_list<T>::const_reference
  get(pythonic::types::sliced_list<T> const &t);

  template <size_t I, class T>
  typename pythonic::types::sliced_list<T>::value_type
  get(pythonic::types::sliced_list<T> &&t);

  template <size_t I, class T>
  struct tuple_element<I, pythonic::types::list<T>> {
    typedef typename pythonic::types::list<T>::value_type type;
  };
  template <size_t I, class T>
  struct tuple_element<I, pythonic::types::sliced_list<T>> {
    typedef typename pythonic::types::sliced_list<T>::value_type type;
  };
}

/* type inference stuff  {*/
#include "pythonic/include/types/combined.hpp"

template <class A>
struct __combined<container<A>, pythonic::types::empty_list> {
  typedef pythonic::types::list<A> type;
};

template <class A>
struct __combined<pythonic::types::empty_list, container<A>> {
  typedef pythonic::types::list<A> type;
};

template <class A, class B>
struct __combined<container<A>, pythonic::types::list<B>> {
  typedef pythonic::types::list<typename __combined<A, B>::type> type;
};

template <class A, class B>
struct __combined<pythonic::types::list<B>, container<A>> {
  typedef pythonic::types::list<typename __combined<A, B>::type> type;
};

template <class K, class V>
struct __combined<indexable<K>, pythonic::types::list<V>> {
  typedef pythonic::types::list<V> type;
};

template <class V, class K>
struct __combined<pythonic::types::list<V>, indexable<K>> {
  typedef pythonic::types::list<V> type;
};

template <class K, class V0, class V1>
struct __combined<indexable_container<K, V0>, pythonic::types::list<V1>> {
  typedef pythonic::types::list<typename __combined<V0, V1>::type> type;
};

template <class K, class V0, class V1>
struct __combined<pythonic::types::list<V1>, indexable_container<K, V0>> {
  typedef pythonic::types::list<typename __combined<V0, V1>::type> type;
};

template <class K, class V>
struct __combined<indexable_container<K, V>, pythonic::types::empty_list> {
  typedef pythonic::types::list<V> type;
};

template <class K, class V>
struct __combined<pythonic::types::empty_list, indexable_container<K, V>> {
  typedef pythonic::types::list<V> type;
};

template <class T0, class T1>
struct __combined<pythonic::types::list<T0>, pythonic::types::list<T1>> {
  typedef pythonic::types::list<typename __combined<T0, T1>::type> type;
};

/* } */

#ifdef ENABLE_PYTHON_MODULE

namespace pythonic
{
  template <typename T>
  struct to_python<types::list<T>> {
    static PyObject *convert(types::list<T> const &v);
  };
  template <>
  struct to_python<types::empty_list> {
    static PyObject *convert(types::empty_list const &);
  };

  template <class T>
  struct from_python<types::list<T>> {

    static bool is_convertible(PyObject *obj);

    static types::list<T> convert(PyObject *obj);
  };
}

#endif

#endif
<commit_msg>Handle std::vector<bool> specialization<commit_after>#ifndef PYTHONIC_INCLUDE_TYPES_LIST_HPP
#define PYTHONIC_INCLUDE_TYPES_LIST_HPP

#include "pythonic/include/types/assignable.hpp"
#include "pythonic/include/types/empty_iterator.hpp"
#include "pythonic/include/types/nditerator.hpp"
#include "pythonic/include/utils/shared_ref.hpp"
#include "pythonic/include/utils/nested_container.hpp"
#include "pythonic/include/utils/int_.hpp"
#include "pythonic/include/utils/reserve.hpp"
#include "pythonic/include/types/slice.hpp"

#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <iterator>

#ifdef USE_BOOST_SIMD
#include <boost/simd/sdk/simd/native.hpp>
#include <boost/simd/include/functions/load.hpp>
#include <boost/simd/include/functions/store.hpp>
#endif

namespace pythonic
{

  namespace types
  {
    template <class T>
    using container = std::vector<T>;

    static const size_t DEFAULT_LIST_CAPACITY = 16;

    /* forward declaration */
    struct empty_list;
    template <class T>
    class list;
    template <class T, class S>
    class sliced_list;
    template <class T, size_t N>
    struct ndarray;
    template <class T>
    struct is_list {
      static const bool value = false;
    };
    template <class T>
    struct is_list<list<T>> {
      static const bool value = true;
    };
    template <class T, class S>
    struct is_list<sliced_list<T, S>> {
      static const bool value = true;
    };

    /* for type disambiguification */
    struct single_value {
    };

    /* list view */
    template <class T, class S = slice>
    class sliced_list
    {

      // data holder
      typedef
          typename std::remove_cv<typename std::remove_reference<T>::type>::type
              _type;
      typedef container<_type> container_type;
      utils::shared_ref<container_type> data;

      template <class U>
      friend class list;

      typename S::normalized_type slicing;

    public:
      //  types
      typedef typename container_type::reference reference;
      typedef typename container_type::const_reference const_reference;
      typedef typename container_type::iterator iterator;
      typedef typename container_type::const_iterator const_iterator;
      typedef typename container_type::size_type size_type;
      typedef typename container_type::difference_type difference_type;
      typedef typename container_type::value_type value_type;
      typedef typename container_type::allocator_type allocator_type;
      typedef typename container_type::pointer pointer;
      typedef typename container_type::const_pointer const_pointer;
      typedef typename container_type::reverse_iterator reverse_iterator;
      typedef typename container_type::const_reverse_iterator
          const_reverse_iterator;

      // minimal ndarray interface
      typedef
          typename utils::nested_container_value_type<sliced_list>::type dtype;
      static const size_t value =
          utils::nested_container_depth<sliced_list>::value;
      static const bool is_vectorizable = false; // overly cautious \simeq lazy

      // constructor
      sliced_list();
      sliced_list(sliced_list<T, S> const &s);
      sliced_list(list<T> &other, S const &s);

      // assignment
      sliced_list &operator=(list<T> const &);
      sliced_list &operator=(sliced_list<T, S> const &);
      list<T> operator+(list<T> const &);
      list<T> operator+(sliced_list<T, S> const &);

      // iterators
      iterator begin();
      const_iterator begin() const;
      iterator end();
      const_iterator end() const;

      // size
      long size() const;

      // accessor
      T const &operator[](long i) const;
      T &operator[](long i);

      // comparison
      template <class K>
      bool operator==(list<K> const &other) const;
      bool operator==(empty_list const &other) const;
    };

    /* list */
    template <class T>
    class list
    {

      // data holder
      typedef
          typename std::remove_cv<typename std::remove_reference<T>::type>::type
              _type;
      typedef container<_type> container_type;
      utils::shared_ref<container_type> data;

      template <class U, class S>
      friend class sliced_list;

      template <class U>
      friend class list;

    public:
      // types
      typedef typename container_type::value_type value_type;
      typedef typename container_type::reference reference;
      typedef typename container_type::const_reference const_reference;
      typedef typename container_type::iterator iterator;
      typedef typename container_type::const_iterator const_iterator;
      typedef typename container_type::size_type size_type;
      typedef typename container_type::difference_type difference_type;
      typedef typename container_type::allocator_type allocator_type;
      typedef typename container_type::pointer pointer;
      typedef typename container_type::const_pointer const_pointer;
      typedef typename container_type::reverse_iterator reverse_iterator;
      typedef typename container_type::const_reverse_iterator
          const_reverse_iterator;

      // minimal ndarray interface
      typedef typename utils::nested_container_value_type<list>::type dtype;
      static const size_t value = utils::nested_container_depth<list>::value;
      static const bool is_vectorizable = true;
      static const bool is_strided = false;

      // constructors
      list();
      template <class InputIterator>
      list(InputIterator start, InputIterator stop);
      list(empty_list const &);
      list(size_type sz);
      list(T const &value, single_value);
      list(std::initializer_list<T> l);
      list(list<T> &&other);
      list(list<T> const &other);
      template <class F>
      list(list<F> const &other);
      template <class S>
      list(sliced_list<T, S> const &other);
      list<T> &operator=(list<T> &&other);
      template <class F>
      list<T> &operator=(list<F> const &other);
      list<T> &operator=(list<T> const &other);
      list<T> &operator=(empty_list const &);
      template <class S>
      list<T> &operator=(sliced_list<T, S> const &other);

      list &operator=(ndarray<T, 1> const &); // implemented in ndarray.hpp

      template <class S>
      list<T> &operator+=(sliced_list<T, S> const &other);
      template <class S>
      list<T> operator+(sliced_list<T, S> const &other) const;

      // io
      template <class S>
      friend std::ostream &operator<<(std::ostream &os, list<S> const &v);

      // comparison
      template <class K>
      bool operator==(list<K> const &other) const;
      bool operator==(empty_list const &) const;
      template <class K>
      bool operator!=(list<K> const &other) const;
      bool operator!=(empty_list const &) const;

      // iterators
      iterator begin();
      const_iterator begin() const;
      iterator end();
      const_iterator end() const;
      reverse_iterator rbegin();
      const_reverse_iterator rbegin() const;
      reverse_iterator rend();
      const_reverse_iterator rend() const;

      // comparison
      int operator<(list<T> const &other) const;

// element access
#ifdef USE_BOOST_SIMD
      using simd_iterator = const_simd_nditerator<list>;
      simd_iterator vbegin() const;
      simd_iterator vend() const;
      auto load(long i) const -> decltype(boost::simd::load<
          boost::simd::native<T, BOOST_SIMD_DEFAULT_EXTENSION>>((*this->data),
                                                                i));
      template <class V>
      void store(V &&v, long i);
#endif
      reference fast(long n);
      reference operator[](long n);

      const_reference fast(long n) const;
      const_reference operator[](long n) const;

      list<T> operator[](slice const &s) const;
      list<T> operator[](contiguous_slice const &s) const;

      sliced_list<T, slice> operator()(slice const &s) const;
      sliced_list<T, contiguous_slice>
      operator()(contiguous_slice const &s) const;

      // modifiers
      void push_back(T const &x);
      void insert(long i, T const &x);

      void reserve(size_t n);
      void resize(size_t n);
      iterator erase(size_t n);

      T pop(long x = -1);

      // TODO: have to raise a valueError
      none_type remove(T const &x);

      // Misc
      // TODO: have to raise a valueError
      long index(T const &x) const;

      // list interface
      explicit operator bool() const;

      template <class F>
      list<decltype(std::declval<T>() +
                    std::declval<typename list<F>::value_type>())>
      operator+(list<F> const &s) const;

      template <class F, class S>
      list<decltype(std::declval<T>() +
                    std::declval<typename sliced_list<F, S>::value_type>())>
      operator+(sliced_list<F, S> const &s) const;

      list<T> operator+(empty_list const &) const;
      list<T> operator*(long t) const;

      template <class F>
      list<T> &operator+=(list<F> const &s);
      long size() const;
      template <class E>
      long _flat_size(E const &e, utils::int_<1>) const;
      template <class E, size_t L>
      long _flat_size(E const &e, utils::int_<L>) const;
      long flat_size() const;

      template <class V>
      bool contains(V const &v) const;
      intptr_t id() const;

      long count(T const &x) const;
      array<long, value> shape() const;
    };

    /* empty list implementation */
    struct empty_list {
      typedef void value_type;
      typedef empty_iterator iterator;
      typedef empty_iterator const_iterator;
      template <class T>
      list<T> operator+(list<T> const &s) const;
      template <class T, class S>
      sliced_list<T, S> operator+(sliced_list<T, S> const &s) const;
      empty_list operator+(empty_list const &) const;
      operator bool() const;
      template <class T>
      operator list<T>() const;
      static constexpr long size();
    };

    std::ostream &operator<<(std::ostream &os, empty_list const &);
  }

  namespace utils
  {
    /**
     * Reserve enough space to save all values generated from f.
     *
     * We use a dummy arguments (p) to reserve only when f have a
     * const_iterator type.
     */
    template <class T, class From>
    void reserve(types::list<T> &l, From const &f,
                 typename From::const_iterator *p = nullptr);
  }

  template <class T>
  struct assignable<types::list<T>> {
    typedef types::list<typename assignable<T>::type> type;
  };

  // to cope with std::vector<bool> specialization
  template <>
  struct returnable<types::list<bool>::reference> {
    using type = bool;
  };
}

/* overload std::get */
namespace std
{
  template <size_t I, class T>
  typename pythonic::types::list<T>::reference get(pythonic::types::list<T> &t);

  template <size_t I, class T>
  typename pythonic::types::list<T>::const_reference
  get(pythonic::types::list<T> const &t);

  template <size_t I, class T>
  typename pythonic::types::list<T>::value_type
  get(pythonic::types::list<T> &&t);

  template <size_t I, class T>
  typename pythonic::types::sliced_list<T>::reference
  get(pythonic::types::sliced_list<T> &t);

  template <size_t I, class T>
  typename pythonic::types::sliced_list<T>::const_reference
  get(pythonic::types::sliced_list<T> const &t);

  template <size_t I, class T>
  typename pythonic::types::sliced_list<T>::value_type
  get(pythonic::types::sliced_list<T> &&t);

  template <size_t I, class T>
  struct tuple_element<I, pythonic::types::list<T>> {
    typedef typename pythonic::types::list<T>::value_type type;
  };
  template <size_t I, class T>
  struct tuple_element<I, pythonic::types::sliced_list<T>> {
    typedef typename pythonic::types::sliced_list<T>::value_type type;
  };
}

/* type inference stuff  {*/
#include "pythonic/include/types/combined.hpp"

template <class A>
struct __combined<container<A>, pythonic::types::empty_list> {
  typedef pythonic::types::list<A> type;
};

template <class A>
struct __combined<pythonic::types::empty_list, container<A>> {
  typedef pythonic::types::list<A> type;
};

template <class A, class B>
struct __combined<container<A>, pythonic::types::list<B>> {
  typedef pythonic::types::list<typename __combined<A, B>::type> type;
};

template <class A, class B>
struct __combined<pythonic::types::list<B>, container<A>> {
  typedef pythonic::types::list<typename __combined<A, B>::type> type;
};

template <class K, class V>
struct __combined<indexable<K>, pythonic::types::list<V>> {
  typedef pythonic::types::list<V> type;
};

template <class V, class K>
struct __combined<pythonic::types::list<V>, indexable<K>> {
  typedef pythonic::types::list<V> type;
};

template <class K, class V0, class V1>
struct __combined<indexable_container<K, V0>, pythonic::types::list<V1>> {
  typedef pythonic::types::list<typename __combined<V0, V1>::type> type;
};

template <class K, class V0, class V1>
struct __combined<pythonic::types::list<V1>, indexable_container<K, V0>> {
  typedef pythonic::types::list<typename __combined<V0, V1>::type> type;
};

template <class K, class V>
struct __combined<indexable_container<K, V>, pythonic::types::empty_list> {
  typedef pythonic::types::list<V> type;
};

template <class K, class V>
struct __combined<pythonic::types::empty_list, indexable_container<K, V>> {
  typedef pythonic::types::list<V> type;
};

template <class T0, class T1>
struct __combined<pythonic::types::list<T0>, pythonic::types::list<T1>> {
  typedef pythonic::types::list<typename __combined<T0, T1>::type> type;
};

/* } */

#ifdef ENABLE_PYTHON_MODULE

namespace pythonic
{
  template <typename T>
  struct to_python<types::list<T>> {
    static PyObject *convert(types::list<T> const &v);
  };
  template <>
  struct to_python<types::empty_list> {
    static PyObject *convert(types::empty_list const &);
  };

  template <class T>
  struct from_python<types::list<T>> {

    static bool is_convertible(PyObject *obj);

    static types::list<T> convert(PyObject *obj);
  };
}

#endif

#endif
<|endoftext|>


<commit_before>#include "TuringMachine.h"

//  void insertInstruction();
//  void removeInstruction();
//  void run(Tape*);
//  TuringMachine();

int TuringMachine::insertInstruction(int state, int symbol, int newState,
                                     int newSymbol, char instruction)
{
  return this.table.insertInstruction(state, symbol, newState, newSymbol,
                                      instruction);
}
<commit_msg>Stub out methods for TuringMachine class<commit_after>#include "TuringMachine.h"

//  void insertInstruction();
//  void removeInstruction();
//  void run(Tape*);
//  TuringMachine();

TuringMachine::TuringMachine()
{
  this.table = new Table();
}

int TuringMachine::insertInstruction(int state, int symbol, int newState,
                                     int newSymbol, char instruction)
{
  return this.table.insertInstruction(state, symbol, newState, newSymbol,
                                      instruction);
}

void TuringMachine::run(Tape*)
{
}
<|endoftext|>


<commit_before>#include "velocity.h"

using namespace std;
using namespace cv;

static void drawCircle(Mat &imageData, CircleData &cercle)
{
    Scalar color = Scalar(0,255,0);
    circle(imageData, cercle.center, cercle.radius, color, 1, 8, 0);

    //Show results
    //namedWindow("Detection", MAX_ROWS);
    //imshow("Detection", imageData);
}

static void rectToCircle(Rect r, CircleData &circle)
{
    int a, b;
    a = round(r.width/2);
    b = round(r.height/2);
    circle.center = Point(r.x + a, r.y + b);
    circle.radius = hypotf(a,b);
}

static void velocityXYZ(Velocity &vel, CircleData ini, CircleData fi, float sample_time)
{
    vel.velX = (fi.center.x - ini.center.x)/sample_time*PX_TO_MM;
    vel.velY = (fi.center.y - ini.center.y)/sample_time*PX_TO_MM;
    vel.velZ = (1-ini.radius/fi.radius)*H_SAT*FOCAL_LENGTH/(ini.radius*sample_time*PX_TO_MM);
}

int main(int argc, char *argv[])
{
    double time_elapsed;
    float sample_time = 2.0;    //Sample time in miliseconds

    Rect rectangle1 = Rect(MAX_ROWS/4, MAX_COLS/4, 30, 30);
    Rect rectangle2 = Rect(MAX_ROWS/2, MAX_COLS/4, 40, 40);

    CircleData c1;
	CircleData c2;
    rectToCircle(rectangle1, c1);
    rectToCircle(rectangle2, c2);

    Velocity velocity;
    clock_t begin = clock();
    velocityXYZ(velocity, c1, c2, sample_time);
  	clock_t end = clock();

    time_elapsed = double(end - begin) / CLOCKS_PER_SEC;

    printf("Velocity in X: %.2f m/s\n", velocity.velX);
    printf("Velocity in Y: %.2f m/s\n", velocity.velY);
    printf("Velocity in Z: %.2f m/s\n", velocity.velZ);
    printf("Time elapsed to compute the velocity: %.1lf us\n", time_elapsed*1e6);

    return 0;
}
<commit_msg>Minor bug fixed<commit_after>#include "velocity.h"

using namespace std;
using namespace cv;

static void drawCircle(Mat &imageData, CircleData &cercle)
{
    Scalar color = Scalar(0,255,0);
    circle(imageData, cercle.center, cercle.radius, color, 1, 8, 0);

    //Show results
    //namedWindow("Detection", MAX_ROWS);
    //imshow("Detection", imageData);
}

static void rectToCircle(Rect r, CircleData &circle)
{
    int a, b;
    a = round(r.width/2);
    b = round(r.height/2);
    circle.center = Point(r.x + a, r.y + b);
    circle.radius = hypotf(a,b);
}

static void velocityXYZ(Velocity &vel, CircleData ini, CircleData fi, float sample_time)
{
    vel.velX = (fi.center.x - ini.center.x)/sample_time*PX_TO_MM;
    vel.velY = (fi.center.y - ini.center.y)/sample_time*PX_TO_MM;
    vel.velZ = (1-ini.radius/fi.radius)*H_SAT*FOCAL_LENGTH/(ini.radius*sample_time*PX_TO_MM);
}

int main(int argc, char *argv[])
{
    double time_elapsed;
    float sample_time = 2.0;    //Sample time in miliseconds

    Rect rectangle1 = Rect(MAX_ROWS/4, MAX_COLS/4, 30, 30);
    Rect rectangle2 = Rect(MAX_ROWS/2, MAX_COLS/4, 40, 40);

    CircleData c1;
    CircleData c2;
    rectToCircle(rectangle1, c1);
    rectToCircle(rectangle2, c2);

    Velocity velocity;
    clock_t begin = clock();
    velocityXYZ(velocity, c1, c2, sample_time);
    clock_t end = clock();

    time_elapsed = double(end - begin) / CLOCKS_PER_SEC;

    printf("Velocity in X: %.2f m/s\n", velocity.velX);
    printf("Velocity in Y: %.2f m/s\n", velocity.velY);
    printf("Velocity in Z: %.2f m/s\n", velocity.velZ);
    printf("Time elapsed to compute the velocity: %.1lf us\n", time_elapsed*1e6);

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Terminal.cpp
 *
 *  Created on: Jan 30, 2015
 *      Author: mailmindlin
 */

#include "Terminal.h"

#include "../std/strlen.h"

struct FrameBufferDescription;

static const size_t VGA_WIDTH = 80;
static const size_t VGA_HEIGHT = 24;

Terminal::Terminal() :
		width(VGA_WIDTH), height(VGA_HEIGHT) {
	initialize();
}

Terminal::Terminal(size_t twidth, size_t theight) :
		width(twidth), height(theight) {
	initialize();
}

uint8_t Terminal::makeColor(enum VGAColor fg, enum VGAColor bg) {
	return fg | bg << 4;
}

uint16_t Terminal::makeVGAEntry(char c, uint8_t color) {
	uint16_t c16 = c;
	uint16_t color16 = color;
	return c16 | color16 << 8;
}

void Terminal::initialize() {
	row = 0;
	column = 0;
	color = makeColor(COLOR_LIGHT_GREY, COLOR_BLACK);
	buffer = (uint16_t*) 0xB8000;
	for (size_t y = 0; y < VGA_HEIGHT; y++) {
		for (size_t x = 0; x < VGA_WIDTH; x++) {
			const size_t index = y * VGA_WIDTH + x;
			Terminal::buffer[index] = makeVGAEntry(' ', color);
		}
	}
	for(int i = 0; i < 8; i++)
		chars[0][i]=0;
	//'A'
	chars[65][0] =	0b00000000;
	chars[65][1] =	0b00111000;
	chars[65][2] =	0b01101100;
	chars[65][3] =	0b11000110;
	chars[65][4] =	0b11000110;
	chars[65][5] =	0b11111110;
	chars[65][6] =	0b11000110;
	chars[65][7] =	0b11000110;
	//'B'
	chars[66][0] =	0b00000000;
	chars[66][1] =	0b11111100;
	chars[66][2] =	0b11000110;
	chars[66][3] =	0b11000110;
	chars[66][4] =	0b11111100;
	chars[66][5] =	0b11000110;
	chars[66][6] =	0b11000110;
	chars[66][7] =	0b11111110;
	//'C'
	chars[67][0] =	0b00000000;
	chars[67][1] =	0b00111100;
	chars[67][2] =	0b01100110;
	chars[67][3] =	0b11000000;
	chars[67][4] =	0b11000000;
	chars[67][5] =	0b11000000;
	chars[67][6] =	0b01100110;
	chars[67][7] =	0b00111100;
	//'D'
	chars[68][0] =	0b00000000;
	chars[68][1] =	0b11111000;
	chars[68][2] =	0b11001100;
	chars[68][3] =	0b11000110;
	chars[68][4] =	0b11000110;
	chars[68][5] =	0b11000110;
	chars[68][6] =	0b11001100;
	chars[68][7] =	0b11111000;
	//'E'
	chars[69][0] =	0b00000000;
	chars[69][1] =	0b11111110;
	chars[69][2] =	0b11000000;
	chars[69][3] =	0b11000000;
	chars[69][4] =	0b11111000;
	chars[69][5] =	0b11000000;
	chars[69][6] =	0b11000000;
	chars[69][7] =	0b11111110;
	//'F'
	chars[70][0] =	0b00000000;
	chars[70][1] =	0b11111110;
	chars[70][2] =	0b11000000;
	chars[70][3] =	0b11000000;
	chars[70][4] =	0b11111100;
	chars[70][5] =	0b11000000;
	chars[70][6] =	0b11000000;
	chars[70][7] =	0b11000000;
	//'G'
	chars[71][0] =	0b00000000;
	chars[71][1] =	0b00111100;
	chars[71][2] =	0b01100110;
	chars[71][3] =	0b11000000;
	chars[71][4] =	0b11001110;
	chars[71][5] =	0b11000110;
	chars[71][6] =	0b01100110;
	chars[71][7] =	0b00111100;
	//'H'
	chars[72][0] =	0b00000000;
	chars[72][1] =	0b11000110;
	chars[72][2] =	0b11000110;
	chars[72][3] =	0b11000110;
	chars[72][4] =	0b11111110;
	chars[72][5] =	0b11000110;
	chars[72][6] =	0b11000110;
	chars[72][7] =	0b11000110;
	//'I'
	chars[73][0] =	0b00000000;
	chars[73][1] =	0b00011000;
	chars[73][2] =	0b00011000;
	chars[73][3] =	0b00011000;
	chars[73][4] =	0b00011000;
	chars[73][5] =	0b00011000;
	chars[73][6] =	0b00011000;
	chars[73][7] =	0b00011000;

	//'J'
	/*
	chars[7][0] =	0b;
	chars[7][1] =	0b;
	chars[7][2] =	0b;
	chars[7][3] =	0b;
	chars[7][4] =	0b;
	chars[7][5] =	0b;
	chars[7][6] =	0b;
	chars[7][7] =	0b;
	*/
}

void drawCharAt(uint32_t x, uint32_t y, FrameBufferDescription* buffer, uint8_t* data, uint16_t color) {
	for(int i = 0; i < 8; i++)
		for(int j = 0; j < 8; j++)
			if((data[i] >> j) & 1 == 0)
				Displays::GPU::setPixel(buffer, x + i, y + j, color);
}

void Terminal::draw() {
	int x = 10, y = 10;
	for(int i = 0; i < VGA_WIDTH; i++)
		for(int j = 0; j < VGA_HEIGHT; j++) {
			char c = buffer[i * j];
			uint8_t* g = chars[c];
			drawCharAt(x, y, fb, g, colors[i * j]);
			if((x += 8) > fb->vWidth) {
				x = 0;
				y += 8;
			}
		}
}

void Terminal::setColor(uint8_t color) {
	this->color = color;
}

void Terminal::putEntryAt(char c, uint16_t color, size_t x, size_t y) {
	const size_t index = y * VGA_WIDTH + x;
	Terminal::buffer[index] = c;
	Terminal::colors[index] = color;
}

void Terminal::putChar(char c) {
	if(c == '\n') {
		row++;
		column=0;
		//clear row
		for(int i = 0; i < VGA_WIDTH; i++)
			colors[i*row]=buffer[i*row]='\0';
	} else if(c=='\t') {
		column+=4;
	} else if(c<32) {

	}else if(c==32) {
		column++;
	}else if(c==127) {
		column--;
		buffer[row*column]=0;
	} else {
		putEntryAt(c, color, column, row);
		column++;
	}
	if (column == VGA_WIDTH) {
		column = 0;
		if (++row == VGA_HEIGHT) {
			row = 0;
		}
	}
}

void Terminal::writeString(const char* data) {
	size_t datalen = strlen(data);
	for (size_t i = 0; i < datalen; i++)
		putChar(data[i]);
}
Terminal::~Terminal() {
	//do nothing
}
<commit_msg>Optimized writeString()<commit_after>/*
 * Terminal.cpp
 *
 *  Created on: Jan 30, 2015
 *      Author: mailmindlin
 */

#include "Terminal.h"

#include "../std/strlen.h"

struct FrameBufferDescription;

static const size_t VGA_WIDTH = 80;
static const size_t VGA_HEIGHT = 24;

Terminal::Terminal() :
		width(VGA_WIDTH), height(VGA_HEIGHT) {
	initialize();
}

Terminal::Terminal(size_t twidth, size_t theight) :
		width(twidth), height(theight) {
	initialize();
}

uint8_t Terminal::makeColor(enum VGAColor fg, enum VGAColor bg) {
	return fg | bg << 4;
}

uint16_t Terminal::makeVGAEntry(char c, uint8_t color) {
	uint16_t c16 = c;
	uint16_t color16 = color;
	return c16 | color16 << 8;
}

void Terminal::initialize() {
	row = 0;
	column = 0;
	color = makeColor(COLOR_LIGHT_GREY, COLOR_BLACK);
	buffer = (uint16_t*) 0xB8000;
	for (size_t y = 0; y < VGA_HEIGHT; y++) {
		for (size_t x = 0; x < VGA_WIDTH; x++) {
			const size_t index = y * VGA_WIDTH + x;
			Terminal::buffer[index] = makeVGAEntry(' ', color);
		}
	}
	for(int i = 0; i < 8; i++)
		chars[0][i]=0;
	//'A'
	chars[65][0] =	0b00000000;
	chars[65][1] =	0b00111000;
	chars[65][2] =	0b01101100;
	chars[65][3] =	0b11000110;
	chars[65][4] =	0b11000110;
	chars[65][5] =	0b11111110;
	chars[65][6] =	0b11000110;
	chars[65][7] =	0b11000110;
	//'B'
	chars[66][0] =	0b00000000;
	chars[66][1] =	0b11111100;
	chars[66][2] =	0b11000110;
	chars[66][3] =	0b11000110;
	chars[66][4] =	0b11111100;
	chars[66][5] =	0b11000110;
	chars[66][6] =	0b11000110;
	chars[66][7] =	0b11111110;
	//'C'
	chars[67][0] =	0b00000000;
	chars[67][1] =	0b00111100;
	chars[67][2] =	0b01100110;
	chars[67][3] =	0b11000000;
	chars[67][4] =	0b11000000;
	chars[67][5] =	0b11000000;
	chars[67][6] =	0b01100110;
	chars[67][7] =	0b00111100;
	//'D'
	chars[68][0] =	0b00000000;
	chars[68][1] =	0b11111000;
	chars[68][2] =	0b11001100;
	chars[68][3] =	0b11000110;
	chars[68][4] =	0b11000110;
	chars[68][5] =	0b11000110;
	chars[68][6] =	0b11001100;
	chars[68][7] =	0b11111000;
	//'E'
	chars[69][0] =	0b00000000;
	chars[69][1] =	0b11111110;
	chars[69][2] =	0b11000000;
	chars[69][3] =	0b11000000;
	chars[69][4] =	0b11111000;
	chars[69][5] =	0b11000000;
	chars[69][6] =	0b11000000;
	chars[69][7] =	0b11111110;
	//'F'
	chars[70][0] =	0b00000000;
	chars[70][1] =	0b11111110;
	chars[70][2] =	0b11000000;
	chars[70][3] =	0b11000000;
	chars[70][4] =	0b11111100;
	chars[70][5] =	0b11000000;
	chars[70][6] =	0b11000000;
	chars[70][7] =	0b11000000;
	//'G'
	chars[71][0] =	0b00000000;
	chars[71][1] =	0b00111100;
	chars[71][2] =	0b01100110;
	chars[71][3] =	0b11000000;
	chars[71][4] =	0b11001110;
	chars[71][5] =	0b11000110;
	chars[71][6] =	0b01100110;
	chars[71][7] =	0b00111100;
	//'H'
	chars[72][0] =	0b00000000;
	chars[72][1] =	0b11000110;
	chars[72][2] =	0b11000110;
	chars[72][3] =	0b11000110;
	chars[72][4] =	0b11111110;
	chars[72][5] =	0b11000110;
	chars[72][6] =	0b11000110;
	chars[72][7] =	0b11000110;
	//'I'
	chars[73][0] =	0b00000000;
	chars[73][1] =	0b00011000;
	chars[73][2] =	0b00011000;
	chars[73][3] =	0b00011000;
	chars[73][4] =	0b00011000;
	chars[73][5] =	0b00011000;
	chars[73][6] =	0b00011000;
	chars[73][7] =	0b00011000;

	//'J'
	/*
	chars[7][0] =	0b;
	chars[7][1] =	0b;
	chars[7][2] =	0b;
	chars[7][3] =	0b;
	chars[7][4] =	0b;
	chars[7][5] =	0b;
	chars[7][6] =	0b;
	chars[7][7] =	0b;
	*/
}

void drawCharAt(uint32_t x, uint32_t y, FrameBufferDescription* buffer, uint8_t* data, uint16_t color) {
	for(int i = 0; i < 8; i++)
		for(int j = 0; j < 8; j++)
			if((data[i] >> j) & 1 == 0)
				Displays::GPU::setPixel(buffer, x + i, y + j, color);
}

void Terminal::draw() {
	int x = 10, y = 10;
	for(int i = 0; i < VGA_WIDTH; i++)
		for(int j = 0; j < VGA_HEIGHT; j++) {
			char c = buffer[i * j];
			uint8_t* g = chars[c];
			drawCharAt(x, y, fb, g, colors[i * j]);
			if((x += 8) > fb->vWidth) {
				x = 0;
				y += 8;
			}
		}
}

void Terminal::setColor(uint8_t color) {
	this->color = color;
}

void Terminal::putEntryAt(char c, uint16_t color, size_t x, size_t y) {
	const size_t index = y * VGA_WIDTH + x;
	Terminal::buffer[index] = c;
	Terminal::colors[index] = color;
}

void Terminal::putChar(char c) {
	if(c == '\n') {
		row++;
		column=0;
		//clear row
		for(int i = 0; i < VGA_WIDTH; i++)
			colors[i*row]=buffer[i*row]='\0';
	} else if(c=='\t') {
		column+=4;
	} else if(c<32) {

	}else if(c==32) {
		column++;
	}else if(c==127) {
		column--;
		buffer[row*column]=0;
	} else {
		putEntryAt(c, color, column, row);
		column++;
	}
	if (column == VGA_WIDTH) {
		column = 0;
		if (++row == VGA_HEIGHT) {
			row = 0;
		}
	}
}

void Terminal::writeString(const char* data) {
	char c;
	while (c = *data++)
		putChar(c);
}

Terminal::~Terminal() {
	//do nothing
}
<|endoftext|>


<commit_before>#ifndef __GLOBALS_HPP_INCLUDED
#define __GLOBALS_HPP_INCLUDED

// GCC (at least g++ 4.7.2) and Visual Studio 2015 do support
// setting default values of a struct using C++11 syntax.
// Clang 3.7.0 and Visual Studio 2013 do not support
// setting default values of a struct using C++11 syntax.
// Visual Studio 2013 fails to compile, whereas Clang-compiled
// executable with code with setting default values of a struct
// causes Segmentation fault upon execution of the program.
// Compilers that don't support setting default values of a struct
// are handled by setting the default values in a macro.
// http://stackoverflow.com/questions/16782103/initializing-default-values-in-a-struct/16783513#16783513
#ifdef __clang__
#elif defined(__GNUC__)
#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#elif defined(_WIN32)
#if (_MSC_VER >= 1900)
#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#endif
#endif

// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif

// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <string>
#include <vector>   // std::vector
#include <stdint.h> // uint32_t etc.

#ifndef WINDOW_WIDTH
#define WINDOW_WIDTH (1600.0f)
#endif

#ifndef WINDOW_HEIGHT
#define WINDOW_HEIGHT (900.0f)
#endif

#ifndef ASPECT_RATIO
#define ASPECT_RATIO (WINDOW_WIDTH / WINDOW_HEIGHT)
#endif

#ifndef PI
#define PI 3.14159265359f
#endif

#ifndef EARTH_RADIUS
#define EARTH_RADIUS 6371000.0f
#endif

#ifndef TEXT_SIZE
#define TEXT_SIZE 40
#endif

#ifndef FONT_SIZE
#define FONT_SIZE 16
#endif

#ifndef MAX_FPS
#define MAX_FPS 60
#endif

extern glm::mat4 ProjectionMatrix;
extern glm::mat4 ViewMatrix;
extern glm::vec3 position;
extern GLfloat gravity;
extern bool is_flight_mode_in_use;
extern bool in_help_mode;
extern GLfloat fallSpeed;
extern double horizontalAngle;
extern double verticalAngle;
extern GLfloat initialFoV;
extern double earth_radius;
extern bool hasMouseEverMoved;
extern bool is_invert_mouse_in_use;
extern bool is_key_I_released;
extern bool is_key_F_released;
extern bool is_key_F1_released;
extern bool is_world_loaded;        // no more than one world object can be loaded. TODO: check that no more than one world is loaded!
extern bool is_world_spherical;

extern GLfloat speed;
extern GLfloat turbo_factor;
extern GLfloat twin_turbo_factor;
extern GLfloat mouseSpeed;

extern glm::vec3 camera_position;

typedef struct
{
    void *parent_pointer;        // pointer to the world (draw list).
    std::string vertex_shader;   // filename of vertex shader.
    std::string fragment_shader; // filename of fragment shader.
} ShaderStruct;

#define SHADERSTRUCT(x) ShaderStruct x; x.parent_pointer = NULL

typedef struct
{
    void *parent_pointer;            // pointer to the shader.
    std::string texture_file_format; // type of the texture file. supported file formats so far: `"bmp"`/`"BMP"`, `"dds"`/`"DDS"`.
    std::string texture_filename;    // filename of the model file.
    std::string image_path;
} TextureStruct;

#define TEXTURESTRUCT(x) TextureStruct x; x.parent_pointer = NULL

typedef struct
{
    GLuint nodeID;
    void *parent_pointer;
    glm::vec3 coordinate_vector;
    std::vector<uint32_t> neighbor_nodeIDs;
} NodeStruct;

#define NODESTRUCT(x) NodeStruct x; x.parent_pointer = NULL

typedef struct
{
    void *parent_pointer;            // pointer to the species.
    glm::vec3 original_scale_vector; // original scale vector.
    GLfloat rotate_angle;            // rotate angle.
    bool is_character;               // The parent of a character object is a Glyph. The parent of a regular object is a Species.
    glm::vec3 coordinate_vector;     // coordinate vector.
    glm::vec3 rotate_vector;         // rotate vector.
    glm::vec3 translate_vector;      // translate vector.
    glm::mat4 model_matrix;          // model matrix.
    glm::mat4 MVP_matrix;            // model view projection matrix.
} ObjectStruct;

#define OBJECTSTRUCT(x) ObjectStruct x; x.parent_pointer = NULL; x.original_scale_vector = glm::vec3(1.0f, 1.0f, 1.0f); x.rotate_angle = NAN; x.is_character = false

typedef struct
{
    // used for all files (for all species).
#ifdef __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
    void *parent_pointer = NULL;             // pointer to the texture object.
    bool is_world = false;                   // worlds currently do not rotate nor translate.
    double world_radius = NAN;               // radius of sea level in meters. used only for worlds.
#else
    void *parent_pointer;                    // pointer to the texture object.
    bool is_world;                           // worlds currently do not rotate nor translate.
    double world_radius;                     // radius of sea level in meters. used only for worlds.
#endif
    std::string model_file_format;           // type of the model file. supported file formats so far: `"bmp"`/`"BMP"`, `"obj"`/`"OBJ"`.
                                             // TODO: add support for `"SRTM"`.
    std::string model_filename;              // filename of the model file.
    // for `"bmp"` model files.
    std::string color_channel;               // color channel to use for altitude data.

    glm::vec3 light_position;                // light position.
    std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
    std::string coordinate_system;           // used only for worlds (`is_world` == `true`). valid values: `"cartesian"`.
                                             // TODO: add support for `"spherical"`. `"spherical"` is used eg. in SRTM heightmaps.

} SpeciesStruct;

#ifdef __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#define SPECIESSTRUCT(x) \
SpeciesStruct x
#else
#define SPECIESSTRUCT(x) \
SpeciesStruct x; x.parent_pointer = NULL; x.is_world = false; x.world_radius = NAN
#endif

#define DEFAULT_VERTEX_SCALING_FACTOR (0.001f)

typedef struct
{
    // used for all files (for all font).
#ifdef __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
    void *parent_pointer = NULL;            // pointer to the texture object.
    GLfloat vertex_scaling_factor = DEFAULT_VERTEX_SCALING_FACTOR;
#else
    void *parent_pointer;                   // pointer to the texture object.
    GLfloat vertex_scaling_factor;
#endif
    std::string font_file_format;           // type of the font file. supported file formats so far: `"svg"`/`"SVG"`.
    std::string font_filename;              // filename of the font file.
} FontStruct;

#ifdef __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#define FONTSTRUCT(x) \
FontStruct x
#else
#define FONTSTRUCT(x) \
FontStruct x; x.parent_pointer = NULL; x.vertex_scaling_factor = DEFAULT_VERTEX_SCALING_FACTOR
#endif

typedef struct
{
    // used for all files (for all glyph).
#ifdef __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
    void *parent_pointer = NULL;             // pointer to the font object.
#else
    void *parent_pointer;                    // pointer to the font object.
#endif
    glm::vec3 light_position;                // light position.
    std::vector<ObjectStruct> object_vector; // vector of individual objects of this glyph.
} GlyphStruct;

#ifdef __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#define GLYPHSTRUCT(x) \
GlyphStruct x
#else
#define GLYPHSTRUCT(x) \
GlyphStruct x; x.parent_pointer = NULL
#endif

typedef struct
{
    GLuint screen_width;
    GLuint screen_height;
    GLuint x;
    GLuint y;
    GLuint text_size;
    GLuint font_size;
    const char* text;
    const char* char_font_texture_file_format;
    const char* horizontal_alignment;
    const char* vertical_alignment;
} PrintingStruct;

typedef struct
{
    double rho;
    double theta;
    double phi;
} SphericalCoordinatesStruct;

typedef struct
{
    double southern_latitude;
    double northern_latitude;
    double western_longitude;
    double eastern_longitude;
} SphericalWorldStruct;

extern SphericalCoordinatesStruct spherical_position;

#endif
<commit_msg>Refaktoroitu koodia: `typedef struct {` ... `} SpeciesStruct;`.<commit_after>#ifndef __GLOBALS_HPP_INCLUDED
#define __GLOBALS_HPP_INCLUDED

// GCC (at least g++ 4.7.2) and Visual Studio 2015 do support
// setting default values of a struct using C++11 syntax.
// Clang 3.7.0 and Visual Studio 2013 do not support
// setting default values of a struct using C++11 syntax.
// Visual Studio 2013 fails to compile, whereas Clang-compiled
// executable with code with setting default values of a struct
// causes Segmentation fault upon execution of the program.
// Compilers that don't support setting default values of a struct
// are handled by setting the default values in a macro.
// http://stackoverflow.com/questions/16782103/initializing-default-values-in-a-struct/16783513#16783513
#ifdef __clang__
#elif defined(__GNUC__)
#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#elif defined(_WIN32)
#if (_MSC_VER >= 1900)
#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#endif
#endif

// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif

// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <string>
#include <vector>   // std::vector
#include <stdint.h> // uint32_t etc.

#ifndef WINDOW_WIDTH
#define WINDOW_WIDTH (1600.0f)
#endif

#ifndef WINDOW_HEIGHT
#define WINDOW_HEIGHT (900.0f)
#endif

#ifndef ASPECT_RATIO
#define ASPECT_RATIO (WINDOW_WIDTH / WINDOW_HEIGHT)
#endif

#ifndef PI
#define PI 3.14159265359f
#endif

#ifndef EARTH_RADIUS
#define EARTH_RADIUS 6371000.0f
#endif

#ifndef TEXT_SIZE
#define TEXT_SIZE 40
#endif

#ifndef FONT_SIZE
#define FONT_SIZE 16
#endif

#ifndef MAX_FPS
#define MAX_FPS 60
#endif

extern glm::mat4 ProjectionMatrix;
extern glm::mat4 ViewMatrix;
extern glm::vec3 position;
extern GLfloat gravity;
extern bool is_flight_mode_in_use;
extern bool in_help_mode;
extern GLfloat fallSpeed;
extern double horizontalAngle;
extern double verticalAngle;
extern GLfloat initialFoV;
extern double earth_radius;
extern bool hasMouseEverMoved;
extern bool is_invert_mouse_in_use;
extern bool is_key_I_released;
extern bool is_key_F_released;
extern bool is_key_F1_released;
extern bool is_world_loaded;        // no more than one world object can be loaded. TODO: check that no more than one world is loaded!
extern bool is_world_spherical;

extern GLfloat speed;
extern GLfloat turbo_factor;
extern GLfloat twin_turbo_factor;
extern GLfloat mouseSpeed;

extern glm::vec3 camera_position;

typedef struct
{
    void *parent_pointer;        // pointer to the world (draw list).
    std::string vertex_shader;   // filename of vertex shader.
    std::string fragment_shader; // filename of fragment shader.
} ShaderStruct;

#define SHADERSTRUCT(x) ShaderStruct x; x.parent_pointer = NULL

typedef struct
{
    void *parent_pointer;            // pointer to the shader.
    std::string texture_file_format; // type of the texture file. supported file formats so far: `"bmp"`/`"BMP"`, `"dds"`/`"DDS"`.
    std::string texture_filename;    // filename of the model file.
    std::string image_path;
} TextureStruct;

#define TEXTURESTRUCT(x) TextureStruct x; x.parent_pointer = NULL

typedef struct
{
    GLuint nodeID;
    void *parent_pointer;
    glm::vec3 coordinate_vector;
    std::vector<uint32_t> neighbor_nodeIDs;
} NodeStruct;

#define NODESTRUCT(x) NodeStruct x; x.parent_pointer = NULL

typedef struct
{
    void *parent_pointer;            // pointer to the species.
    glm::vec3 original_scale_vector; // original scale vector.
    GLfloat rotate_angle;            // rotate angle.
    bool is_character;               // The parent of a character object is a Glyph. The parent of a regular object is a Species.
    glm::vec3 coordinate_vector;     // coordinate vector.
    glm::vec3 rotate_vector;         // rotate vector.
    glm::vec3 translate_vector;      // translate vector.
    glm::mat4 model_matrix;          // model matrix.
    glm::mat4 MVP_matrix;            // model view projection matrix.
} ObjectStruct;

#define OBJECTSTRUCT(x) ObjectStruct x; x.parent_pointer = NULL; x.original_scale_vector = glm::vec3(1.0f, 1.0f, 1.0f); x.rotate_angle = NAN; x.is_character = false

typedef struct
{
    // used for all files (for all species).
    void *parent_pointer;                    // pointer to the texture object.
    bool is_world;                           // worlds currently do not rotate nor translate.
    double world_radius;                     // radius of sea level in meters. used only for worlds.
    std::string model_file_format;           // type of the model file. supported file formats so far: `"bmp"`/`"BMP"`, `"obj"`/`"OBJ"`.
                                             // TODO: add support for `"SRTM"`.
    std::string model_filename;              // filename of the model file.
    // for `"bmp"` model files.
    std::string color_channel;               // color channel to use for altitude data.

    glm::vec3 light_position;                // light position.
    std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
    std::string coordinate_system;           // used only for worlds (`is_world` == `true`). valid values: `"cartesian"`.
                                             // TODO: add support for `"spherical"`. `"spherical"` is used eg. in SRTM heightmaps.

} SpeciesStruct;

#define SPECIESSTRUCT(x) SpeciesStruct x; x.parent_pointer = NULL; x.is_world = false; x.world_radius = NAN

#define DEFAULT_VERTEX_SCALING_FACTOR (0.001f)

typedef struct
{
    // used for all files (for all font).
#ifdef __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
    void *parent_pointer = NULL;            // pointer to the texture object.
    GLfloat vertex_scaling_factor = DEFAULT_VERTEX_SCALING_FACTOR;
#else
    void *parent_pointer;                   // pointer to the texture object.
    GLfloat vertex_scaling_factor;
#endif
    std::string font_file_format;           // type of the font file. supported file formats so far: `"svg"`/`"SVG"`.
    std::string font_filename;              // filename of the font file.
} FontStruct;

#ifdef __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#define FONTSTRUCT(x) \
FontStruct x
#else
#define FONTSTRUCT(x) \
FontStruct x; x.parent_pointer = NULL; x.vertex_scaling_factor = DEFAULT_VERTEX_SCALING_FACTOR
#endif

typedef struct
{
    // used for all files (for all glyph).
#ifdef __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
    void *parent_pointer = NULL;             // pointer to the font object.
#else
    void *parent_pointer;                    // pointer to the font object.
#endif
    glm::vec3 light_position;                // light position.
    std::vector<ObjectStruct> object_vector; // vector of individual objects of this glyph.
} GlyphStruct;

#ifdef __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#define GLYPHSTRUCT(x) \
GlyphStruct x
#else
#define GLYPHSTRUCT(x) \
GlyphStruct x; x.parent_pointer = NULL
#endif

typedef struct
{
    GLuint screen_width;
    GLuint screen_height;
    GLuint x;
    GLuint y;
    GLuint text_size;
    GLuint font_size;
    const char* text;
    const char* char_font_texture_file_format;
    const char* horizontal_alignment;
    const char* vertical_alignment;
} PrintingStruct;

typedef struct
{
    double rho;
    double theta;
    double phi;
} SphericalCoordinatesStruct;

typedef struct
{
    double southern_latitude;
    double northern_latitude;
    double western_longitude;
    double eastern_longitude;
} SphericalWorldStruct;

extern SphericalCoordinatesStruct spherical_position;

#endif
<|endoftext|>