<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
**
**************************************************************************/

#include <QtCore/QDebug>
#include <QtCore/QSysInfo>
#include <QtCore/QLocale>
#include <QtGui/QDesktopServices>
#include <QtGui/QLineEdit>
#include <QtNetwork/QHttp>
#include <QtNetwork/QNetworkProxyFactory>

#include <coreplugin/coreconstants.h>

#include "rssfetcher.h"

#ifdef Q_OS_UNIX
#include <sys/utsname.h>
#endif

using namespace Welcome::Internal;

static const QString getOsString()
{
    QString osString;
#if defined(Q_OS_WIN)
    switch (QSysInfo::WindowsVersion) {
    case (QSysInfo::WV_4_0):
        osString += QLatin1String("WinNT4.0");
        break;
    case (QSysInfo::WV_5_0):
        osString += QLatin1String("Windows NT 5.0");
        break;
    case (QSysInfo::WV_5_1):
        osString += QLatin1String("Windows NT 5.1");
        break;
    case (QSysInfo::WV_5_2):
        osString += QLatin1String("Windows NT 5.2");
        break;
    case (QSysInfo::WV_6_0):
        osString += QLatin1String("Windows NT 6.0");
        break;
    case (QSysInfo::WV_6_1):
        osString += QLatin1String("Windows NT 6.1");
        break;
    default:
        osString += QLatin1String("Windows NT (Unknown)");
        break;
    }
#elif defined (Q_OS_MAC)
    if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
        osString += QLatin1String("PPC ");
    else
        osString += QLatin1String("Intel ");
    osString += QLatin1String("Mac OS X ");
    switch (QSysInfo::MacintoshVersion) {
    case (QSysInfo::MV_10_3):
        osString += QLatin1String("10_3");
        break;
    case (QSysInfo::MV_10_4):
        osString += QLatin1String("10_4");
        break;
    case (QSysInfo::MV_10_5):
        osString += QLatin1String("10_5");
        break;
    case (QSysInfo::MV_10_6):
        osString += QLatin1String("10_6");
        break;
    default:
        osString += QLatin1String("(Unknown)");
        break;
    }
#elif defined (Q_OS_UNIX)
    struct utsname uts;
    if (uname(&uts) == 0)
        osString += QString("%1 %2").arg(QLatin1String(uts.sysname))
                        .arg(QLatin1String(uts.release));
    else
        osString += QLatin1String("Unix (Unknown)");
#else
    ossttring = QLatin1String("Unknown OS");
#endif
    return osString;
}

RSSFetcher::RSSFetcher(int maxItems, QObject *parent)
    : QObject(parent), m_items(0), m_maxItems(maxItems)
{
    connect(&m_http, SIGNAL(readyRead(const QHttpResponseHeader &)),
             this, SLOT(readData(const QHttpResponseHeader &)));

    connect(&m_http, SIGNAL(requestFinished(int, bool)),
             this, SLOT(finished(int, bool)));
}

void RSSFetcher::fetch(const QUrl &url)
{
    m_http.setProxy(QNetworkProxyFactory::systemProxyForQuery(QNetworkProxyQuery(url)).first());
    m_http.setHost(url.host());
    QString agentStr = QString("Qt-Creator/%1 (QHttp %2; %3; %4; %5 bit)")
                    .arg(Core::Constants::IDE_VERSION_LONG).arg(qVersion())
                    .arg(getOsString()).arg(QLocale::system().name())
                    .arg(QSysInfo::WordSize);
    QHttpRequestHeader header("GET", url.path());
    //qDebug() << agentStr;
    header.setValue("User-Agent", agentStr);
    header.setValue("Host", url.host());
    m_connectionId = m_http.request(header);
}

void RSSFetcher::readData(const QHttpResponseHeader &resp)
{
    if (resp.statusCode() != 200)
        m_http.abort();
    else {
        m_xml.addData(m_http.readAll());
        parseXml();
    }
}

void RSSFetcher::finished(int id, bool error)
{
    Q_UNUSED(id)
    m_items = 0;
    emit finished(error);
}

void RSSFetcher::parseXml()
{
    while (!m_xml.atEnd()) {
        m_xml.readNext();
        if (m_xml.isStartElement()) {
            if (m_xml.name() == "item") {
                m_titleString.clear();
                m_descriptionString.clear();
                m_linkString.clear();
            }
            m_currentTag = m_xml.name().toString();
        } else if (m_xml.isEndElement()) {
            if (m_xml.name() == "item") {
                m_items++;
                if (m_items > m_maxItems)
                    return;
                emit newsItemReady(m_titleString, m_descriptionString, m_linkString);
            }

        } else if (m_xml.isCharacters() && !m_xml.isWhitespace()) {
            if (m_currentTag == "title")
                m_titleString += m_xml.text().toString();
            else if (m_currentTag == "description")
                m_descriptionString += m_xml.text().toString();
            else if (m_currentTag == "link")
                m_linkString += m_xml.text().toString();
        }
    }
    if (m_xml.error() && m_xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) {
        qWarning() << "XML ERROR:" << m_xml.lineNumber() << ": " << m_xml.errorString();
        m_http.abort();
    }
}
<commit_msg>Do not crash on some system when no proxy is set<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
**
**************************************************************************/

#include <QtCore/QDebug>
#include <QtCore/QSysInfo>
#include <QtCore/QLocale>
#include <QtGui/QDesktopServices>
#include <QtGui/QLineEdit>
#include <QtNetwork/QHttp>
#include <QtNetwork/QNetworkProxyFactory>

#include <coreplugin/coreconstants.h>

#include "rssfetcher.h"

#ifdef Q_OS_UNIX
#include <sys/utsname.h>
#endif

using namespace Welcome::Internal;

static const QString getOsString()
{
    QString osString;
#if defined(Q_OS_WIN)
    switch (QSysInfo::WindowsVersion) {
    case (QSysInfo::WV_4_0):
        osString += QLatin1String("WinNT4.0");
        break;
    case (QSysInfo::WV_5_0):
        osString += QLatin1String("Windows NT 5.0");
        break;
    case (QSysInfo::WV_5_1):
        osString += QLatin1String("Windows NT 5.1");
        break;
    case (QSysInfo::WV_5_2):
        osString += QLatin1String("Windows NT 5.2");
        break;
    case (QSysInfo::WV_6_0):
        osString += QLatin1String("Windows NT 6.0");
        break;
    case (QSysInfo::WV_6_1):
        osString += QLatin1String("Windows NT 6.1");
        break;
    default:
        osString += QLatin1String("Windows NT (Unknown)");
        break;
    }
#elif defined (Q_OS_MAC)
    if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
        osString += QLatin1String("PPC ");
    else
        osString += QLatin1String("Intel ");
    osString += QLatin1String("Mac OS X ");
    switch (QSysInfo::MacintoshVersion) {
    case (QSysInfo::MV_10_3):
        osString += QLatin1String("10_3");
        break;
    case (QSysInfo::MV_10_4):
        osString += QLatin1String("10_4");
        break;
    case (QSysInfo::MV_10_5):
        osString += QLatin1String("10_5");
        break;
    case (QSysInfo::MV_10_6):
        osString += QLatin1String("10_6");
        break;
    default:
        osString += QLatin1String("(Unknown)");
        break;
    }
#elif defined (Q_OS_UNIX)
    struct utsname uts;
    if (uname(&uts) == 0)
        osString += QString("%1 %2").arg(QLatin1String(uts.sysname))
                        .arg(QLatin1String(uts.release));
    else
        osString += QLatin1String("Unix (Unknown)");
#else
    ossttring = QLatin1String("Unknown OS");
#endif
    return osString;
}

RSSFetcher::RSSFetcher(int maxItems, QObject *parent)
    : QObject(parent), m_items(0), m_maxItems(maxItems)
{
    connect(&m_http, SIGNAL(readyRead(const QHttpResponseHeader &)),
             this, SLOT(readData(const QHttpResponseHeader &)));

    connect(&m_http, SIGNAL(requestFinished(int, bool)),
             this, SLOT(finished(int, bool)));
}

void RSSFetcher::fetch(const QUrl &url)
{
    QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery(QNetworkProxyQuery(url));
    if (proxies.count() > 0)
        m_http.setProxy(proxies.first());
    m_http.setHost(url.host());
    QString agentStr = QString("Qt-Creator/%1 (QHttp %2; %3; %4; %5 bit)")
                    .arg(Core::Constants::IDE_VERSION_LONG).arg(qVersion())
                    .arg(getOsString()).arg(QLocale::system().name())
                    .arg(QSysInfo::WordSize);
    QHttpRequestHeader header("GET", url.path());
    //qDebug() << agentStr;
    header.setValue("User-Agent", agentStr);
    header.setValue("Host", url.host());
    m_connectionId = m_http.request(header);
}

void RSSFetcher::readData(const QHttpResponseHeader &resp)
{
    if (resp.statusCode() != 200)
        m_http.abort();
    else {
        m_xml.addData(m_http.readAll());
        parseXml();
    }
}

void RSSFetcher::finished(int id, bool error)
{
    Q_UNUSED(id)
    m_items = 0;
    emit finished(error);
}

void RSSFetcher::parseXml()
{
    while (!m_xml.atEnd()) {
        m_xml.readNext();
        if (m_xml.isStartElement()) {
            if (m_xml.name() == "item") {
                m_titleString.clear();
                m_descriptionString.clear();
                m_linkString.clear();
            }
            m_currentTag = m_xml.name().toString();
        } else if (m_xml.isEndElement()) {
            if (m_xml.name() == "item") {
                m_items++;
                if (m_items > m_maxItems)
                    return;
                emit newsItemReady(m_titleString, m_descriptionString, m_linkString);
            }

        } else if (m_xml.isCharacters() && !m_xml.isWhitespace()) {
            if (m_currentTag == "title")
                m_titleString += m_xml.text().toString();
            else if (m_currentTag == "description")
                m_descriptionString += m_xml.text().toString();
            else if (m_currentTag == "link")
                m_linkString += m_xml.text().toString();
        }
    }
    if (m_xml.error() && m_xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) {
        qWarning() << "XML ERROR:" << m_xml.lineNumber() << ": " << m_xml.errorString();
        m_http.abort();
    }
}
<|endoftext|>


<commit_before>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Graphics/Sprite.hpp>
#include <Nazara/Core/Error.hpp>
#include <memory>
#include <Nazara/Graphics/Debug.hpp>

namespace Nz
{
	/*!
	* \brief Constructs a Sprite object by default
	*/

	inline Sprite::Sprite() :
	m_color(Color::White),
	m_textureCoords(0.f, 0.f, 1.f, 1.f),
	m_size(64.f, 64.f),
	m_origin(Nz::Vector3f::Zero())
	{
		for (Color& color : m_cornerColor)
			color = Color::White;

		SetDefaultMaterial();
	}

	/*!
	* \brief Constructs a Sprite object with a reference to a material
	*
	* \param material Reference to a material
	*/
	inline Sprite::Sprite(MaterialRef material) :
	Sprite()
	{
		SetMaterial(std::move(material), true);
	}

	/*!
	* \brief Constructs a Sprite object with a pointer to a texture
	*
	* \param texture Pointer to a texture
	*/

	inline Sprite::Sprite(Texture* texture) :
	Sprite()
	{
		SetTexture(texture, true);
	}

	/*!
	* \brief Constructs a Sprite object by assignation
	*
	* \param sprite Sprite to copy into this
	*/

	inline Sprite::Sprite(const Sprite& sprite) :
	InstancedRenderable(sprite),
	m_color(sprite.m_color),
	m_textureCoords(sprite.m_textureCoords),
	m_size(sprite.m_size),
	m_origin(sprite.m_origin)
	{
	}

	/*!
	* \brief Gets the color of the sprite
	*
	* This is the global color of the sprite, independent from corner colors
	*
	* \return Current color
	*
	* \see GetCornerColor
	* \see SetColor
	*/
	inline const Color& Sprite::GetColor() const
	{
		return m_color;
	}

	/*!
	* \brief Gets the color setup on a corner of the sprite
	*
	* \return Current color
	*
	* \param corner Corner of the sprite to query
	*
	* \see SetCornerColor
	*/
	inline const Color& Sprite::GetCornerColor(RectCorner corner) const
	{
		NazaraAssert(static_cast<std::size_t>(corner) < m_cornerColor.size(), "Invalid corner");

		return m_cornerColor[corner];
	}

	/*!
	* \brief Gets the origin of the sprite
	*
	* \return Current material
	*
	* \see SetOrigin
	*/
	inline const Vector3f& Sprite::GetOrigin() const
	{
		return m_origin;
	}

	/*!
	* \brief Gets the size of the sprite
	* \return Current size
	*/

	inline const Vector2f& Sprite::GetSize() const
	{
		return m_size;
	}

	/*!
	* \brief Gets the texture coordinates of the sprite
	* \return Current texture coordinates
	*/
	inline const Rectf& Sprite::GetTextureCoords() const
	{
		return m_textureCoords;
	}

	/*!
	* \brief Sets the global color of the sprite
	*
	* This is independent from the corner color of the sprite
	*
	* \param color Color for the sprite
	*
	* \see GetColor
	* \see SetCornerColor
	*/
	inline void Sprite::SetColor(const Color& color)
	{
		m_color = color;

		InvalidateVertices();
	}

	/*!
	* \brief Sets a color for a corner of the sprite
	*
	* This is independent from the sprite global color, which gets multiplied by the corner color when rendering the sprite.
	*
	* \param corner Corner of the sprite to set
	* \param color Color for the sprite
	*
	* \see GetCornerColor
	* \see SetColor
	*/
	inline void Sprite::SetCornerColor(RectCorner corner, const Color& color)
	{
		NazaraAssert(static_cast<std::size_t>(corner) < m_cornerColor.size(), "Invalid corner");

		m_cornerColor[corner] = color;

		InvalidateVertices();
	}

	/*!
	* \brief Sets the default material of the sprite (just default material)
	*/

	inline void Sprite::SetDefaultMaterial()
	{
		MaterialRef material = Material::New();
		material->EnableFaceCulling(false);

		SetMaterial(std::move(material));
	}

	/*!
	* \brief Changes the material of the sprite
	*
	* \param material Material for the sprite
	* \param resizeSprite Should billboard be resized to the material size (diffuse map)
	*/
	inline void Sprite::SetMaterial(MaterialRef material, bool resizeSprite)
	{
		SetMaterial(GetSkin(), std::move(material), resizeSprite);
	}

	/*!
	* \brief Sets the material of the sprite
	*
	* \param skinIndex Skin index to change
	* \param material Material for the sprite
	* \param resizeBillboard Should billboard be resized to the material size (diffuse map)
	*/
	inline void Sprite::SetMaterial(std::size_t skinIndex, MaterialRef material, bool resizeSprite)
	{
		InstancedRenderable::SetMaterial(skinIndex, 0, std::move(material));

		if (resizeSprite)
		{
			if (const MaterialRef& material = GetMaterial())
			{
				const TextureRef& diffuseMap = material->GetDiffuseMap();
				if (diffuseMap && diffuseMap->IsValid())
					SetSize(Vector2f(Vector2ui(diffuseMap->GetSize())));
			}
		}
	}

	/*!
	* \brief Sets the origin of the sprite
	*
	* The origin is the center of translation/rotation/scaling of the sprite.
	*
	* \param origin New origin for the sprite
	*
	* \see GetOrigin
	*/
	inline void Sprite::SetOrigin(const Vector3f& origin)
	{
		m_origin = origin;

		// On invalide la bounding box
		InvalidateBoundingVolume();
		InvalidateVertices();
	}

	/*!
	* \brief Sets the size of the sprite
	*
	* \param size Size for the sprite
	*/

	inline void Sprite::SetSize(const Vector2f& size)
	{
		m_size = size;

		// On invalide la bounding box
		InvalidateBoundingVolume();
		InvalidateVertices();
	}

	/*!
	* \brief Sets the size of the sprite
	*
	* \param sizeX Size in X for the sprite
	* \param sizeY Size in Y for the sprite
	*/

	inline void Sprite::SetSize(float sizeX, float sizeY)
	{
		SetSize(Vector2f(sizeX, sizeY));
	}

	/*!
	* \brief Sets the texture of the sprite for the current skin
	*
	* This function changes the diffuse map of the material associated with the current skin
	*
	* \param texture Texture for the sprite
	* \param resizeSprite Should the sprite be resized to the texture size?
	*
	* \remark The sprite material gets copied to prevent accidentally changing other drawable materials
	*/
	inline void Sprite::SetTexture(TextureRef texture, bool resizeSprite)
	{
		SetTexture(GetSkin(), std::move(texture), resizeSprite);
	}

	/*!
	* \brief Sets the texture of the sprite for a specific skin
	*
	* This function changes the diffuse map of the material associated with the specified skin
	*
	* \param skinIndex Skin index to change
	* \param texture Texture for the sprite
	* \param resizeSprite Should the sprite be resized to the texture size?
	*
	* \remark The sprite material gets copied to prevent accidentally changing other drawable materials
	*/
	inline void Sprite::SetTexture(std::size_t skinIndex, TextureRef texture, bool resizeSprite)
	{
		if (resizeSprite && texture && texture->IsValid())
			SetSize(Vector2f(Vector2ui(texture->GetSize())));

		const MaterialRef& material = GetMaterial(skinIndex);

		if (material->GetReferenceCount() > 1)
		{
			MaterialRef newMat = Material::New(*material); // Copy
			newMat->SetDiffuseMap(std::move(texture));

			SetMaterial(skinIndex, std::move(newMat));
		}
		else
			material->SetDiffuseMap(std::move(texture));
	}

	/*!
	* \brief Sets the texture coordinates of the sprite
	*
	* \param coords Texture coordinates
	*/

	inline void Sprite::SetTextureCoords(const Rectf& coords)
	{
		m_textureCoords = coords;

		InvalidateVertices();
	}

	/*!
	* \brief Sets the texture rectangle of the sprite
	*
	* \param rect Rectangles symbolizing the size of the texture
	*
	* \remark Produces a NazaraAssert if material is invalid
	* \remark Produces a NazaraAssert if material has no diffuse map
	*/

	inline void Sprite::SetTextureRect(const Rectui& rect)
	{
		const MaterialRef& material = GetMaterial();
		NazaraAssert(material->HasDiffuseMap(), "Sprite material has no diffuse map");

		Texture* diffuseMap = material->GetDiffuseMap();

		float invWidth = 1.f / diffuseMap->GetWidth();
		float invHeight = 1.f / diffuseMap->GetHeight();

		SetTextureCoords(Rectf(invWidth * rect.x, invHeight * rect.y, invWidth * rect.width, invHeight * rect.height));
	}

	/*!
	* \brief Sets the current sprite with the content of the other one
	* \return A reference to this
	*
	* \param sprite The other Sprite
	*/

	inline Sprite& Sprite::operator=(const Sprite& sprite)
	{
		InstancedRenderable::operator=(sprite);

		m_color = sprite.m_color;
		m_origin = sprite.m_origin;
		m_textureCoords = sprite.m_textureCoords;
		m_size = sprite.m_size;

		// We do not copy final vertices because it's highly probable that our parameters are modified and they must be regenerated
		InvalidateBoundingVolume();
		InvalidateVertices();

		return *this;
	}

	/*!
	* \brief Invalidates the vertices
	*/

	inline void Sprite::InvalidateVertices()
	{
		InvalidateInstanceData(0);
	}

	/*!
	* \brief Creates a new sprite from the arguments
	* \return A reference to the newly created sprite
	*
	* \param args Arguments for the sprite
	*/

	template<typename... Args>
	SpriteRef Sprite::New(Args&&... args)
	{
		std::unique_ptr<Sprite> object(new Sprite(std::forward<Args>(args)...));
		object->SetPersistent(false);

		return object.release();
	}
}

#include <Nazara/Graphics/DebugOff.hpp>
<commit_msg>Graphics/Sprite: Fix sprites not initializing materials<commit_after>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Graphics/Sprite.hpp>
#include <Nazara/Core/Error.hpp>
#include <memory>
#include <Nazara/Graphics/Debug.hpp>

namespace Nz
{
	/*!
	* \brief Constructs a Sprite object by default
	*/

	inline Sprite::Sprite() :
	m_color(Color::White),
	m_textureCoords(0.f, 0.f, 1.f, 1.f),
	m_size(64.f, 64.f),
	m_origin(Nz::Vector3f::Zero())
	{
		ResetMaterials(1);

		for (Color& color : m_cornerColor)
			color = Color::White;

		SetDefaultMaterial();
	}

	/*!
	* \brief Constructs a Sprite object with a reference to a material
	*
	* \param material Reference to a material
	*/
	inline Sprite::Sprite(MaterialRef material) :
	Sprite()
	{
		SetMaterial(std::move(material), true);
	}

	/*!
	* \brief Constructs a Sprite object with a pointer to a texture
	*
	* \param texture Pointer to a texture
	*/

	inline Sprite::Sprite(Texture* texture) :
	Sprite()
	{
		SetTexture(texture, true);
	}

	/*!
	* \brief Constructs a Sprite object by assignation
	*
	* \param sprite Sprite to copy into this
	*/

	inline Sprite::Sprite(const Sprite& sprite) :
	InstancedRenderable(sprite),
	m_color(sprite.m_color),
	m_textureCoords(sprite.m_textureCoords),
	m_size(sprite.m_size),
	m_origin(sprite.m_origin)
	{
	}

	/*!
	* \brief Gets the color of the sprite
	*
	* This is the global color of the sprite, independent from corner colors
	*
	* \return Current color
	*
	* \see GetCornerColor
	* \see SetColor
	*/
	inline const Color& Sprite::GetColor() const
	{
		return m_color;
	}

	/*!
	* \brief Gets the color setup on a corner of the sprite
	*
	* \return Current color
	*
	* \param corner Corner of the sprite to query
	*
	* \see SetCornerColor
	*/
	inline const Color& Sprite::GetCornerColor(RectCorner corner) const
	{
		NazaraAssert(static_cast<std::size_t>(corner) < m_cornerColor.size(), "Invalid corner");

		return m_cornerColor[corner];
	}

	/*!
	* \brief Gets the origin of the sprite
	*
	* \return Current material
	*
	* \see SetOrigin
	*/
	inline const Vector3f& Sprite::GetOrigin() const
	{
		return m_origin;
	}

	/*!
	* \brief Gets the size of the sprite
	* \return Current size
	*/

	inline const Vector2f& Sprite::GetSize() const
	{
		return m_size;
	}

	/*!
	* \brief Gets the texture coordinates of the sprite
	* \return Current texture coordinates
	*/
	inline const Rectf& Sprite::GetTextureCoords() const
	{
		return m_textureCoords;
	}

	/*!
	* \brief Sets the global color of the sprite
	*
	* This is independent from the corner color of the sprite
	*
	* \param color Color for the sprite
	*
	* \see GetColor
	* \see SetCornerColor
	*/
	inline void Sprite::SetColor(const Color& color)
	{
		m_color = color;

		InvalidateVertices();
	}

	/*!
	* \brief Sets a color for a corner of the sprite
	*
	* This is independent from the sprite global color, which gets multiplied by the corner color when rendering the sprite.
	*
	* \param corner Corner of the sprite to set
	* \param color Color for the sprite
	*
	* \see GetCornerColor
	* \see SetColor
	*/
	inline void Sprite::SetCornerColor(RectCorner corner, const Color& color)
	{
		NazaraAssert(static_cast<std::size_t>(corner) < m_cornerColor.size(), "Invalid corner");

		m_cornerColor[corner] = color;

		InvalidateVertices();
	}

	/*!
	* \brief Sets the default material of the sprite (just default material)
	*/

	inline void Sprite::SetDefaultMaterial()
	{
		MaterialRef material = Material::New();
		material->EnableFaceCulling(false);

		SetMaterial(std::move(material));
	}

	/*!
	* \brief Changes the material of the sprite
	*
	* \param material Material for the sprite
	* \param resizeSprite Should billboard be resized to the material size (diffuse map)
	*/
	inline void Sprite::SetMaterial(MaterialRef material, bool resizeSprite)
	{
		SetMaterial(GetSkin(), std::move(material), resizeSprite);
	}

	/*!
	* \brief Sets the material of the sprite
	*
	* \param skinIndex Skin index to change
	* \param material Material for the sprite
	* \param resizeBillboard Should billboard be resized to the material size (diffuse map)
	*/
	inline void Sprite::SetMaterial(std::size_t skinIndex, MaterialRef material, bool resizeSprite)
	{
		InstancedRenderable::SetMaterial(skinIndex, 0, std::move(material));

		if (resizeSprite)
		{
			if (const MaterialRef& material = GetMaterial())
			{
				const TextureRef& diffuseMap = material->GetDiffuseMap();
				if (diffuseMap && diffuseMap->IsValid())
					SetSize(Vector2f(Vector2ui(diffuseMap->GetSize())));
			}
		}
	}

	/*!
	* \brief Sets the origin of the sprite
	*
	* The origin is the center of translation/rotation/scaling of the sprite.
	*
	* \param origin New origin for the sprite
	*
	* \see GetOrigin
	*/
	inline void Sprite::SetOrigin(const Vector3f& origin)
	{
		m_origin = origin;

		// On invalide la bounding box
		InvalidateBoundingVolume();
		InvalidateVertices();
	}

	/*!
	* \brief Sets the size of the sprite
	*
	* \param size Size for the sprite
	*/

	inline void Sprite::SetSize(const Vector2f& size)
	{
		m_size = size;

		// On invalide la bounding box
		InvalidateBoundingVolume();
		InvalidateVertices();
	}

	/*!
	* \brief Sets the size of the sprite
	*
	* \param sizeX Size in X for the sprite
	* \param sizeY Size in Y for the sprite
	*/

	inline void Sprite::SetSize(float sizeX, float sizeY)
	{
		SetSize(Vector2f(sizeX, sizeY));
	}

	/*!
	* \brief Sets the texture of the sprite for the current skin
	*
	* This function changes the diffuse map of the material associated with the current skin
	*
	* \param texture Texture for the sprite
	* \param resizeSprite Should the sprite be resized to the texture size?
	*
	* \remark The sprite material gets copied to prevent accidentally changing other drawable materials
	*/
	inline void Sprite::SetTexture(TextureRef texture, bool resizeSprite)
	{
		SetTexture(GetSkin(), std::move(texture), resizeSprite);
	}

	/*!
	* \brief Sets the texture of the sprite for a specific skin
	*
	* This function changes the diffuse map of the material associated with the specified skin
	*
	* \param skinIndex Skin index to change
	* \param texture Texture for the sprite
	* \param resizeSprite Should the sprite be resized to the texture size?
	*
	* \remark The sprite material gets copied to prevent accidentally changing other drawable materials
	*/
	inline void Sprite::SetTexture(std::size_t skinIndex, TextureRef texture, bool resizeSprite)
	{
		if (resizeSprite && texture && texture->IsValid())
			SetSize(Vector2f(Vector2ui(texture->GetSize())));

		const MaterialRef& material = GetMaterial(skinIndex);

		if (material->GetReferenceCount() > 1)
		{
			MaterialRef newMat = Material::New(*material); // Copy
			newMat->SetDiffuseMap(std::move(texture));

			SetMaterial(skinIndex, std::move(newMat));
		}
		else
			material->SetDiffuseMap(std::move(texture));
	}

	/*!
	* \brief Sets the texture coordinates of the sprite
	*
	* \param coords Texture coordinates
	*/

	inline void Sprite::SetTextureCoords(const Rectf& coords)
	{
		m_textureCoords = coords;

		InvalidateVertices();
	}

	/*!
	* \brief Sets the texture rectangle of the sprite
	*
	* \param rect Rectangles symbolizing the size of the texture
	*
	* \remark Produces a NazaraAssert if material is invalid
	* \remark Produces a NazaraAssert if material has no diffuse map
	*/

	inline void Sprite::SetTextureRect(const Rectui& rect)
	{
		const MaterialRef& material = GetMaterial();
		NazaraAssert(material->HasDiffuseMap(), "Sprite material has no diffuse map");

		Texture* diffuseMap = material->GetDiffuseMap();

		float invWidth = 1.f / diffuseMap->GetWidth();
		float invHeight = 1.f / diffuseMap->GetHeight();

		SetTextureCoords(Rectf(invWidth * rect.x, invHeight * rect.y, invWidth * rect.width, invHeight * rect.height));
	}

	/*!
	* \brief Sets the current sprite with the content of the other one
	* \return A reference to this
	*
	* \param sprite The other Sprite
	*/

	inline Sprite& Sprite::operator=(const Sprite& sprite)
	{
		InstancedRenderable::operator=(sprite);

		m_color = sprite.m_color;
		m_origin = sprite.m_origin;
		m_textureCoords = sprite.m_textureCoords;
		m_size = sprite.m_size;

		// We do not copy final vertices because it's highly probable that our parameters are modified and they must be regenerated
		InvalidateBoundingVolume();
		InvalidateVertices();

		return *this;
	}

	/*!
	* \brief Invalidates the vertices
	*/

	inline void Sprite::InvalidateVertices()
	{
		InvalidateInstanceData(0);
	}

	/*!
	* \brief Creates a new sprite from the arguments
	* \return A reference to the newly created sprite
	*
	* \param args Arguments for the sprite
	*/

	template<typename... Args>
	SpriteRef Sprite::New(Args&&... args)
	{
		std::unique_ptr<Sprite> object(new Sprite(std::forward<Args>(args)...));
		object->SetPersistent(false);

		return object.release();
	}
}

#include <Nazara/Graphics/DebugOff.hpp>
<|endoftext|>


<commit_before>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#ifndef HPP_CORE_CONSTRAINT_SET_HH
# define HPP_CORE_CONSTRAINT_SET_HH

# include <deque>
# include <hpp/core/constraint.hh>

namespace hpp {
  namespace core {
    /// \addtogroup constraints
    /// \{

    /// Set of constraints applicable to a robot configuration
    ///
    /// \warning If the set is to contain a ConfigProjector and several
    /// LockedJoint instances, the configProjector should be inserted first
    /// since following numerical projections might affect locked degrees of
    /// freedom.
    class HPP_CORE_DLLAPI ConstraintSet : public Constraint
    {
    public:
      /// Return shared pointer to new object
      static ConstraintSetPtr_t create (const DevicePtr_t& robot,
					const std::string& name)
      {
	ConstraintSet* ptr = new ConstraintSet (robot, name);
	ConstraintSetPtr_t shPtr (ptr);
	ptr->init (shPtr);
	return shPtr;
      }

      /// Return shared pointer to new object
      static ConstraintSetPtr_t createCopy (const ConstraintSetPtr_t& cs)
      {
	ConstraintSet* ptr = new ConstraintSet (*cs);
	ConstraintSetPtr_t shPtr (ptr);
	ptr->init (shPtr);
	return shPtr;
      }

      /// return shared pointer to copy
      virtual ConstraintPtr_t copy () const;

      /// Add a constraint to the set
      void addConstraint (const ConstraintPtr_t& constraint)
      {
	constraint->addToConstraintSet (weak_.lock ());
      }

      /// Return pointer to config projector if any
      const ConfigProjectorPtr_t& configProjector () const
      {
	return configProjector_;
      }

      /// Check whether a configuration statisfies the constraint.
      virtual bool isSatisfied (ConfigurationIn_t config);

      /// Check whether a configuration statisfies the constraint.
      ///
      /// \param config the configuration to check
      /// \retval error concatenation of errors of each constraint.
      virtual bool isSatisfied (ConfigurationIn_t config, vector_t& error);

      /// \name Compression of locked degrees of freedom
      ///
      /// Degrees of freedom related to locked joint are not taken into
      /// account in numerical constraint resolution. The following methods
      /// Compress or uncompress vectors or matrices by removing lines and
      /// columns corresponding to locked degrees of freedom.
      /// \{

      /// Get number of non-locked degrees of freedom
      size_type numberNonLockedDof () const;

      /// Compress Velocity vector by removing locked degrees of freedom
      ///
      /// \param normal input velocity vector
      /// \retval small compressed velocity vectors
      void compressVector (vectorIn_t normal, vectorOut_t small) const;

      /// Expand compressed velocity vector
      ///
      /// \param small compressed velocity vector without locked degrees of
      ///              freedom,
      /// \retval normal uncompressed velocity vector.
      /// \note locked degree of freedom are not set. They should be initialized
      ///       to zero.
      void uncompressVector (vectorIn_t small, vectorOut_t normal) const;

      /// Compress matrix
      ///
      /// \param normal input matrix
      /// \retval small compressed matrix
      /// \param rows whether to compress rows and colums or only columns
      void compressMatrix (matrixIn_t normal, matrixOut_t small,
			   bool rows = true) const;

      /// Uncompress matrix
      ///
      /// \param small input matrix
      /// \retval normal uncompressed matrix
      /// \param rows whether to uncompress rows and colums or only columns
      void uncompressMatrix (matrixIn_t small, matrixOut_t normal,
			     bool rows = true) const;
      /// \}

    protected:
      typedef std::deque <ConstraintPtr_t> Constraints_t;
      ConstraintSet (const DevicePtr_t& robot, const std::string& name);
      /// Copy constructor
      ConstraintSet (const ConstraintSet& other);
      /// Store weak pointer to itself.
      void init (const ConstraintSetPtr_t& self)
      {
	Constraint::init (self);
	weak_ = self;
      }
      virtual bool impl_compute (ConfigurationOut_t configuration);
    private:
      virtual void addToConstraintSet (const ConstraintSetPtr_t& constraintSet)
      {
	for (Constraints_t::iterator itConstraint = constraints_.begin ();
	     itConstraint != constraints_.end (); itConstraint ++) {
	  (*itConstraint)->addToConstraintSet (constraintSet);
	}
      }

      void removeFirstElement ();

      virtual std::ostream& print (std::ostream& os) const
      {
	os << "Constraint set " << name () << ", contains" << std::endl;
	for (Constraints_t::const_iterator itConstraint = constraints_.begin ();
	     itConstraint != constraints_.end (); itConstraint++) {
	  os << "  " << **itConstraint << std::endl;
	}
	return os;
      }

      Constraints_t constraints_;
      ConfigProjectorPtr_t configProjector_;
      ConfigProjectorPtr_t trivialOrNotConfigProjector_;
      ConstraintSetWkPtr_t weak_;

      friend class LockedJoint;
      friend class Constraint;
      friend class ConfigProjector;
    }; // class ConstraintSet
    /// \}
  } // namespace core
} // namespace hpp

#endif // HPP_CORE_CONSTRAINT_SET_HH
<commit_msg>Cosmetic change: fix typo in comment.<commit_after>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#ifndef HPP_CORE_CONSTRAINT_SET_HH
# define HPP_CORE_CONSTRAINT_SET_HH

# include <deque>
# include <hpp/core/constraint.hh>

namespace hpp {
  namespace core {
    /// \addtogroup constraints
    /// \{

    /// Set of constraints applicable to a robot configuration
    ///
    /// \warning If the set is to contain a ConfigProjector and several
    /// LockedJoint instances, the configProjector should be inserted first
    /// since following numerical projections might affect locked degrees of
    /// freedom.
    class HPP_CORE_DLLAPI ConstraintSet : public Constraint
    {
    public:
      /// Return shared pointer to new object
      static ConstraintSetPtr_t create (const DevicePtr_t& robot,
					const std::string& name)
      {
	ConstraintSet* ptr = new ConstraintSet (robot, name);
	ConstraintSetPtr_t shPtr (ptr);
	ptr->init (shPtr);
	return shPtr;
      }

      /// Return shared pointer to new object
      static ConstraintSetPtr_t createCopy (const ConstraintSetPtr_t& cs)
      {
	ConstraintSet* ptr = new ConstraintSet (*cs);
	ConstraintSetPtr_t shPtr (ptr);
	ptr->init (shPtr);
	return shPtr;
      }

      /// return shared pointer to copy
      virtual ConstraintPtr_t copy () const;

      /// Add a constraint to the set
      void addConstraint (const ConstraintPtr_t& constraint)
      {
	constraint->addToConstraintSet (weak_.lock ());
      }

      /// Return pointer to config projector if any
      const ConfigProjectorPtr_t& configProjector () const
      {
	return configProjector_;
      }

      /// Check whether a configuration statisfies the constraint.
      virtual bool isSatisfied (ConfigurationIn_t config);

      /// Check whether a configuration satisfies the constraint.
      ///
      /// \param config the configuration to check
      /// \retval error concatenation of errors of each constraint.
      virtual bool isSatisfied (ConfigurationIn_t config, vector_t& error);

      /// \name Compression of locked degrees of freedom
      ///
      /// Degrees of freedom related to locked joint are not taken into
      /// account in numerical constraint resolution. The following methods
      /// Compress or uncompress vectors or matrices by removing lines and
      /// columns corresponding to locked degrees of freedom.
      /// \{

      /// Get number of non-locked degrees of freedom
      size_type numberNonLockedDof () const;

      /// Compress Velocity vector by removing locked degrees of freedom
      ///
      /// \param normal input velocity vector
      /// \retval small compressed velocity vectors
      void compressVector (vectorIn_t normal, vectorOut_t small) const;

      /// Expand compressed velocity vector
      ///
      /// \param small compressed velocity vector without locked degrees of
      ///              freedom,
      /// \retval normal uncompressed velocity vector.
      /// \note locked degree of freedom are not set. They should be initialized
      ///       to zero.
      void uncompressVector (vectorIn_t small, vectorOut_t normal) const;

      /// Compress matrix
      ///
      /// \param normal input matrix
      /// \retval small compressed matrix
      /// \param rows whether to compress rows and colums or only columns
      void compressMatrix (matrixIn_t normal, matrixOut_t small,
			   bool rows = true) const;

      /// Uncompress matrix
      ///
      /// \param small input matrix
      /// \retval normal uncompressed matrix
      /// \param rows whether to uncompress rows and colums or only columns
      void uncompressMatrix (matrixIn_t small, matrixOut_t normal,
			     bool rows = true) const;
      /// \}

    protected:
      typedef std::deque <ConstraintPtr_t> Constraints_t;
      ConstraintSet (const DevicePtr_t& robot, const std::string& name);
      /// Copy constructor
      ConstraintSet (const ConstraintSet& other);
      /// Store weak pointer to itself.
      void init (const ConstraintSetPtr_t& self)
      {
	Constraint::init (self);
	weak_ = self;
      }
      virtual bool impl_compute (ConfigurationOut_t configuration);
    private:
      virtual void addToConstraintSet (const ConstraintSetPtr_t& constraintSet)
      {
	for (Constraints_t::iterator itConstraint = constraints_.begin ();
	     itConstraint != constraints_.end (); itConstraint ++) {
	  (*itConstraint)->addToConstraintSet (constraintSet);
	}
      }

      void removeFirstElement ();

      virtual std::ostream& print (std::ostream& os) const
      {
	os << "Constraint set " << name () << ", contains" << std::endl;
	for (Constraints_t::const_iterator itConstraint = constraints_.begin ();
	     itConstraint != constraints_.end (); itConstraint++) {
	  os << "  " << **itConstraint << std::endl;
	}
	return os;
      }

      Constraints_t constraints_;
      ConfigProjectorPtr_t configProjector_;
      ConfigProjectorPtr_t trivialOrNotConfigProjector_;
      ConstraintSetWkPtr_t weak_;

      friend class LockedJoint;
      friend class Constraint;
      friend class ConfigProjector;
    }; // class ConstraintSet
    /// \}
  } // namespace core
} // namespace hpp

#endif // HPP_CORE_CONSTRAINT_SET_HH
<|endoftext|>


<commit_before>
#include <sstream>

#include <fitsio.h>

inline void C3::assert_fits_status( const int cfitsio_status )
{
    if( cfitsio_status == 0 ) return;
    throw C3::FitsException( cfitsio_status );
}

inline C3::FitsException::FitsException( const int cfitsio_status ) :
    C3::Exception( C3::FitsException::status_string( cfitsio_status ) )
{}

inline std::string C3::FitsException::status_string( const int cfitsio_status )
{
    char status_message[ FLEN_STATUS ];
    fits_get_errstatus( cfitsio_status, status_message );

    std::stringstream ss;
    ss << "CFITSIO error code " << cfitsio_status;
    ss << " | "                 << status_message;
    return ss.str();

}
<commit_msg>Style.<commit_after>
#include <sstream>

#include <fitsio.h>

inline void C3::assert_fits_status( const int cfitsio_status )
{
    if( cfitsio_status == 0 ) return;
    throw C3::FitsException( cfitsio_status );
}

inline C3::FitsException::FitsException( const int cfitsio_status ) :
    C3::Exception( C3::FitsException::status_string( cfitsio_status ) )
{}

inline std::string C3::FitsException::status_string( const int cfitsio_status )
{

    char status_message[ FLEN_STATUS ];
    fits_get_errstatus( cfitsio_status, status_message );

    std::stringstream ss;
    ss << "CFITSIO error code " << cfitsio_status;
    ss << " | "                 << status_message;
    return ss.str();

}
<|endoftext|>


<commit_before>/*

Copyright (c) 2012, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

*/

#ifndef TORRENT_STRING_UTIL_HPP_INCLUDED
#define TORRENT_STRING_UTIL_HPP_INCLUDED

#include "libtorrent/config.hpp"

namespace libtorrent
{
	TORRENT_EXTRA_EXPORT bool is_alpha(char c);
	TORRENT_EXTRA_EXPORT bool is_digit(char c);
	TORRENT_EXTRA_EXPORT bool is_print(char c);
	TORRENT_EXTRA_EXPORT bool is_space(char c);
	TORRENT_EXTRA_EXPORT char to_lower(char c);

	TORRENT_EXTRA_EXPORT int split_string(char const** tags, int buf_size, char* in);
	TORRENT_EXTRA_EXPORT bool string_begins_no_case(char const* s1, char const* s2);
	TORRENT_EXTRA_EXPORT bool string_equal_no_case(char const* s1, char const* s2);

	TORRENT_EXTRA_EXPORT void url_random(char* begin, char* end);

	// strdup is not part of the C standard. Some systems
	// don't have it and it won't be available when building
	// in strict ansi mode
	char* allocate_string_copy(char const* str);

	// returns p + x such that the pointer is 8 bytes aligned
	// x cannot be greater than 7
	void* align_pointer(void* p);

}

#endif

<commit_msg>fix python binding build with shared linking<commit_after>/*

Copyright (c) 2012, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

*/

#ifndef TORRENT_STRING_UTIL_HPP_INCLUDED
#define TORRENT_STRING_UTIL_HPP_INCLUDED

#include "libtorrent/config.hpp"

namespace libtorrent
{
	TORRENT_EXTRA_EXPORT bool is_alpha(char c);
	// this is used by bdecode_recursive's header file
	TORRENT_EXPORT bool is_digit(char c);
	TORRENT_EXTRA_EXPORT bool is_print(char c);
	TORRENT_EXTRA_EXPORT bool is_space(char c);
	TORRENT_EXTRA_EXPORT char to_lower(char c);

	TORRENT_EXTRA_EXPORT int split_string(char const** tags, int buf_size, char* in);
	TORRENT_EXTRA_EXPORT bool string_begins_no_case(char const* s1, char const* s2);
	TORRENT_EXTRA_EXPORT bool string_equal_no_case(char const* s1, char const* s2);

	TORRENT_EXTRA_EXPORT void url_random(char* begin, char* end);

	// strdup is not part of the C standard. Some systems
	// don't have it and it won't be available when building
	// in strict ansi mode
	char* allocate_string_copy(char const* str);

	// returns p + x such that the pointer is 8 bytes aligned
	// x cannot be greater than 7
	void* align_pointer(void* p);

}

#endif

<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * 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
 *
 *****************************************************************************/

#ifndef MAPNIK_VERTEX_ADAPTERS_HPP
#define MAPNIK_VERTEX_ADAPTERS_HPP

#include <mapnik/geometry.hpp>

namespace mapnik { namespace geometry {

struct point_vertex_adapter
{
    point_vertex_adapter(point const& pt)
        : pt_(pt),
          first_(true) {}

    unsigned vertex(double*x, double*y) const
    {
        if (first_)
        {
            *x = pt_.x;
            *y = pt_.y;
            first_ = false;
            return mapnik::SEG_MOVETO;
        }
        return mapnik::SEG_END;
    }

    void rewind(unsigned) const
    {
        first_ = true;
    }

    inline geometry_types type () const
    {
        return geometry_types::Point;
    }

    point const& pt_;
    mutable bool first_;
};

struct line_string_vertex_adapter
{
    line_string_vertex_adapter(line_string const& line)
        : line_(line),
          current_index_(0),
          end_index_(line.size())
    {}

    unsigned vertex(double*x, double*y) const
    {
        if (current_index_ != end_index_)
        {
            point const& coord = line_[current_index_++];
            *x = coord.x;
            *y = coord.y;
            if (current_index_ == 1)
            {
                return mapnik::SEG_MOVETO;
            }
            else
            {
                return mapnik::SEG_LINETO;
            }
        }
        return mapnik::SEG_END;
    }

    void rewind(unsigned) const
    {
        current_index_ = 0;
    }

    inline geometry_types type () const
    {
        return geometry_types::LineString;
    }

    line_string const& line_;
    mutable std::size_t current_index_;
    const std::size_t end_index_;

};

struct polygon_vertex_adapter
{
    polygon_vertex_adapter(polygon const& poly)
        : poly_(poly),
          rings_itr_(0),
          rings_end_(poly_.interior_rings.size() + 1),
          current_index_(0),
          end_index_((rings_itr_ < rings_end_) ? poly_.exterior_ring.size() : 0),
          start_loop_(true),
          close_loop_(false) {}

    void rewind(unsigned) const
    {
        rings_itr_ = 0;
        rings_end_ = poly_.interior_rings.size() + 1;
        current_index_ = 0;
        end_index_ = (rings_itr_ < rings_end_) ? poly_.exterior_ring.size() : 0;
        start_loop_ = true;
        close_loop_ = false;
    }

    unsigned vertex(double* x, double* y) const
    {
        if (close_loop_)
        {
            close_loop_ = false;
            return SEG_CLOSE;
        }
        if (rings_itr_ == rings_end_)
            return mapnik::SEG_END;
        if (current_index_ < end_index_)
        {
            point const& coord = (rings_itr_ == 0) ?
                poly_.exterior_ring[current_index_++] : poly_.interior_rings[rings_itr_- 1][current_index_++];
            *x = coord.x;
            *y = coord.y;
            if (start_loop_)
            {
                start_loop_= false;
                return mapnik::SEG_MOVETO;
            }
            if (current_index_ == end_index_)
            {
                close_loop_ = true;
                //return mapnik::SEG_CLOSE;
            }
            return mapnik::SEG_LINETO;
        }
        else if (++rings_itr_ != rings_end_)
        {
            current_index_ = 0;
            end_index_ = poly_.interior_rings[rings_itr_ - 1].size();
            point const& coord = poly_.interior_rings[rings_itr_ - 1][current_index_++];
            *x = coord.x;
            *y = coord.y;
            return mapnik::SEG_MOVETO;
        }
        return mapnik::SEG_END;
    }

    inline geometry_types type () const
    {
        return geometry_types::Polygon;
    }

private:
    polygon const& poly_;
    mutable std::size_t rings_itr_;
    mutable std::size_t rings_end_;
    mutable std::size_t current_index_;
    mutable std::size_t end_index_;
    mutable bool start_loop_;
    mutable bool close_loop_;
};

template <typename T>
struct vertex_adapter_traits{};

template <>
struct vertex_adapter_traits<point>
{
    using type = point_vertex_adapter;
};

template <>
struct vertex_adapter_traits<line_string>
{
    using type = line_string_vertex_adapter;
};

template <>
struct vertex_adapter_traits<polygon>
{
    using type = polygon_vertex_adapter;
};

template <>
struct vertex_adapter_traits<multi_point>
{
    using type = point_vertex_adapter;
};

template <>
struct vertex_adapter_traits<multi_line_string>
{
    using type = line_string_vertex_adapter;
};

template <>
struct vertex_adapter_traits<multi_polygon>
{
    using type = polygon_vertex_adapter;
};

}}

#endif //MAPNIK_VERTEX_ADAPTERS_HPP
<commit_msg>don't output last-vertex (== first-vertex) - SEG_CLOSE should be sufficient<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * 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
 *
 *****************************************************************************/

#ifndef MAPNIK_VERTEX_ADAPTERS_HPP
#define MAPNIK_VERTEX_ADAPTERS_HPP

#include <mapnik/geometry.hpp>

namespace mapnik { namespace geometry {

struct point_vertex_adapter
{
    point_vertex_adapter(point const& pt)
        : pt_(pt),
          first_(true) {}

    unsigned vertex(double*x, double*y) const
    {
        if (first_)
        {
            *x = pt_.x;
            *y = pt_.y;
            first_ = false;
            return mapnik::SEG_MOVETO;
        }
        return mapnik::SEG_END;
    }

    void rewind(unsigned) const
    {
        first_ = true;
    }

    inline geometry_types type () const
    {
        return geometry_types::Point;
    }

    point const& pt_;
    mutable bool first_;
};

struct line_string_vertex_adapter
{
    line_string_vertex_adapter(line_string const& line)
        : line_(line),
          current_index_(0),
          end_index_(line.size())
    {}

    unsigned vertex(double*x, double*y) const
    {
        if (current_index_ != end_index_)
        {
            point const& coord = line_[current_index_++];
            *x = coord.x;
            *y = coord.y;
            if (current_index_ == 1)
            {
                return mapnik::SEG_MOVETO;
            }
            else
            {
                return mapnik::SEG_LINETO;
            }
        }
        return mapnik::SEG_END;
    }

    void rewind(unsigned) const
    {
        current_index_ = 0;
    }

    inline geometry_types type () const
    {
        return geometry_types::LineString;
    }

    line_string const& line_;
    mutable std::size_t current_index_;
    const std::size_t end_index_;

};

struct polygon_vertex_adapter
{
    polygon_vertex_adapter(polygon const& poly)
        : poly_(poly),
          rings_itr_(0),
          rings_end_(poly_.interior_rings.size() + 1),
          current_index_(0),
          end_index_((rings_itr_ < rings_end_) ? poly_.exterior_ring.size() : 0),
          start_loop_(true),
          close_loop_(false) {}

    void rewind(unsigned) const
    {
        rings_itr_ = 0;
        rings_end_ = poly_.interior_rings.size() + 1;
        current_index_ = 0;
        end_index_ = (rings_itr_ < rings_end_) ? poly_.exterior_ring.size() : 0;
        start_loop_ = true;
        close_loop_ = false;
    }

    unsigned vertex(double* x, double* y) const
    {
/*
        if (close_loop_)
        {
            close_loop_ = false;
            point const& coord = (rings_itr_ == 0) ?
                poly_.exterior_ring[0] : poly_.interior_rings[rings_itr_- 1][0];
            *x = coord.x;
            *y = coord.y;
            return SEG_CLOSE;
        }
*/
        if (rings_itr_ == rings_end_)
            return mapnik::SEG_END;
        if (current_index_ < end_index_)
        {
            point const& coord = (rings_itr_ == 0) ?
                poly_.exterior_ring[current_index_++] : poly_.interior_rings[rings_itr_- 1][current_index_++];
            *x = coord.x;
            *y = coord.y;
            if (start_loop_)
            {
                start_loop_= false;
                return mapnik::SEG_MOVETO;
            }
            if (current_index_ == end_index_)
            {
                //close_loop_ = true;
                *x = 0;
                *y = 0;
                return mapnik::SEG_CLOSE;
            }
            return mapnik::SEG_LINETO;
        }
        else if (++rings_itr_ != rings_end_)
        {
            current_index_ = 0;
            end_index_ = poly_.interior_rings[rings_itr_ - 1].size();
            point const& coord = poly_.interior_rings[rings_itr_ - 1][current_index_++];
            *x = coord.x;
            *y = coord.y;
            return mapnik::SEG_MOVETO;
        }
        return mapnik::SEG_END;
    }

    inline geometry_types type () const
    {
        return geometry_types::Polygon;
    }

private:
    polygon const& poly_;
    mutable std::size_t rings_itr_;
    mutable std::size_t rings_end_;
    mutable std::size_t current_index_;
    mutable std::size_t end_index_;
    mutable bool start_loop_;
    mutable bool close_loop_;
};

template <typename T>
struct vertex_adapter_traits{};

template <>
struct vertex_adapter_traits<point>
{
    using type = point_vertex_adapter;
};

template <>
struct vertex_adapter_traits<line_string>
{
    using type = line_string_vertex_adapter;
};

template <>
struct vertex_adapter_traits<polygon>
{
    using type = polygon_vertex_adapter;
};

template <>
struct vertex_adapter_traits<multi_point>
{
    using type = point_vertex_adapter;
};

template <>
struct vertex_adapter_traits<multi_line_string>
{
    using type = line_string_vertex_adapter;
};

template <>
struct vertex_adapter_traits<multi_polygon>
{
    using type = polygon_vertex_adapter;
};

}}

#endif //MAPNIK_VERTEX_ADAPTERS_HPP
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Eran Pe'er.
 *
 * This program is made available under the terms of the MIT License.
 *
 * Created on Mar 10, 2014
 */

#ifndef DynamicProxy_h__
#define DynamicProxy_h__

#include <functional>
#include <type_traits>
#include <vector>
#include <array>
#include <new>

#ifdef _MSC_VER
#include "mockutils/mscpp/VirtualTable.hpp"
#else
#include "mockutils/gcc/VirtualTable.hpp"
#endif

#include "mockutils/union_cast.hpp"
#include "mockutils/MethodInvocationHandler.hpp"
#include "mockutils/VTUtils.hpp"
#include "mockutils/FakeObject.hpp"

namespace fakeit {

    struct InvocationHandlerCollection {
        virtual Destructable* getInvocatoinHandlerPtr(unsigned int index) = 0;
    };

    static InvocationHandlerCollection * getInvocationHandlerCollection(void * instance) {
        VirtualTableBase & vt = VirtualTableBase::getVTable(instance);
        InvocationHandlerCollection * invocationHandlerCollection = (InvocationHandlerCollection*) vt.getCookie(0);
        return invocationHandlerCollection;
    }

    struct MethodProxy {

        MethodProxy(unsigned int offset, void * vMethod) :
                _vMethod(vMethod), _offset(offset) {
        }

        unsigned int getOffset() const {
            return _offset;
        }

        void * getProxy() const {
            return union_cast<void *>(_vMethod);
        }

    private:
        void * _vMethod;
        unsigned int _offset;
    };

    template<typename R, typename ... arglist>
    class MethodProxyCreatorBase{
    protected:

        MethodProxy newMethodProxy(unsigned int offset, R(MethodProxyCreatorBase::*vMethod)(arglist...)) {
            return MethodProxy(offset, union_cast<void *>(vMethod));
        }

    public:

        MethodProxy createMethodProxy(unsigned int offset) {
            return newMethodProxy(offset, getMethodProxyPtr(offset));
        }

    protected:

        R methodProxy(unsigned int index, arglist& ... args) {
            InvocationHandlerCollection * dynamicProxy = getInvocationHandlerCollection(this);
            MethodInvocationHandler<R, arglist...> * methodMock =
                (MethodInvocationHandler<R, arglist...> *)dynamicProxy->getInvocatoinHandlerPtr(index);
            return methodMock->handleMethodInvocation(args...);
        }

        template<int offset>
        R methodProxyX(arglist ... args) {
            return methodProxy(offset, args...);
        }

        using MethodProxyPtrType = R(MethodProxyCreatorBase::*)(arglist...);
        MethodProxyPtrType getMethodProxyPtr(unsigned int offset){
            R(MethodProxyCreatorBase::*vMethod)(arglist...) = 0;
            switch (offset) {
            case 0:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 0 > ;
                break;
            case 1:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 1 > ;
                break;
            case 2:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 2 > ;
                break;
            case 3:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 3 > ;
                break;
            case 4:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 4 > ;
                break;
            case 5:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 5 > ;
                break;
            case 6:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 6 > ;
                break;
            case 7:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 7 > ;
                break;
            case 8:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 8 > ;
                break;
            case 9:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 9 > ;
                break;
            case 10:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 10 > ;
                break;
            case 11:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 11 > ;
                break;
            case 12:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 12 > ;
                break;
            case 13:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 13 > ;
                break;
            case 14:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 14 > ;
                break;
            case 15:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 15 > ;
                break;
            case 16:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 16 > ;
                break;
            case 17:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 17 > ;
                break;
            case 18:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 18 > ;
                break;
            case 19:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 19 > ;
                break;
            case 20:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 20 > ;
                break;
            case 21:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 21 > ;
                break;
            case 22:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 22 > ;
                break;
            case 23:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 23 > ;
                break;
            case 24:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 24 > ;
                break;
            case 25:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 25 > ;
                break;
            case 26:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 26 > ;
                break;
            case 27:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 27 > ;
                break;
            case 28:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 28 > ;
                break;
            case 29:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 29 > ;
                break;
            case 30:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 30 > ;
                break;
            case 31:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 31 > ;
                break;
            case 32:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 32 > ;
                break;
            case 33:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 33 > ;
                break;
            case 34:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 34 > ;
                break;
            case 35:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 35 > ;
                break;
            case 36:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 36 > ;
                break;
            case 37:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 37 > ;
                break;
            case 38:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 38 > ;
                break;
            case 39:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 39 > ;
                break;
            case 40:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 40 > ;
                break;
            case 41:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 41 > ;
                break;
            case 42:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 42 > ;
                break;
            case 43:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 43 > ;
                break;
            case 44:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 44 > ;
                break;
            case 45:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 45 > ;
                break;
            case 46:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 46 > ;
                break;
            case 47:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 47 > ;
                break;
            case 48:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 48 > ;
                break;
            case 49:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 49 > ;
                break;
            }
            return vMethod;
        }
    };

    template<typename C, typename ... baseclasses>
    struct DynamicProxy {

        class InvocationHandlers : public InvocationHandlerCollection {
            std::array<std::shared_ptr<Destructable>, 50>& _methodMocks;
        public:
            InvocationHandlers(std::array<std::shared_ptr<Destructable>, 50>& methodMocks) : _methodMocks(methodMocks){
            }

            Destructable* getInvocatoinHandlerPtr(unsigned int offset) override {
                std::shared_ptr<Destructable> ptr = _methodMocks[offset];
                return ptr.get();
            }
        };

        static_assert(std::is_polymorphic<C>::value, "DynamicProxy requires a polymorphic type");

        DynamicProxy(C& instance) :
            instance(instance), originalVtHandle(VirtualTable<C, baseclasses...>::getVTable(instance).createHandle()),
            _methodMocks(),
            _invocationHandlers(_methodMocks)
        {
            _cloneVt.copyFrom(originalVtHandle.restore());
            _cloneVt.setCookie(0, &_invocationHandlers);
            getFake().setVirtualTable(_cloneVt);
        }

        void detach()
        {
            getFake().setVirtualTable(originalVtHandle.restore());
        }

        ~DynamicProxy() {
            _cloneVt.dispose();
        }

        C& get() {
            return instance;
        }

        void Reset() {
            _methodMocks = { {} };
            _members = {};
            _cloneVt.copyFrom(originalVtHandle.restore());
        }

        template<typename R, typename ... arglist>
        void stubMethod(R(C::*vMethod)(arglist...), MethodInvocationHandler<R, arglist...>* methodInvocationHandler) {
            MethodProxyCreator<R, arglist...> creator;
            bindMethod(creator.createMethodProxy(vMethod), methodInvocationHandler);
        }

        void stubDtor(MethodInvocationHandler<void>* methodInvocationHandler) {
            MethodProxyCreator<void> creator;
            bindDtor(creator.createDtorProxy(), methodInvocationHandler);
        }

        template<typename R, typename ... arglist>
        bool isMethodStubbed(R(C::*vMethod)(arglist...)) {
            unsigned int offset = MethodProxyCreator<R, arglist...>::getOffset(vMethod);
            return isBinded(offset);
        }

        bool isDtorStubbed() {
            unsigned int offset = VTUtils::getDestructorOffset<C>();
            return isBinded((unsigned int) offset);
        }

        template<typename R, typename ... arglist>
        Destructable * getMethodMock(R(C::*vMethod)(arglist...)) {
            auto offset = MethodProxyCreator<R, arglist...>::getOffset(vMethod);
            std::shared_ptr<Destructable> ptr = _methodMocks[offset];
            return ptr.get();
        }

        Destructable * getDtorMock() {
            auto offset = VTUtils::getDestructorOffset<C>();
            std::shared_ptr<Destructable> ptr = _methodMocks[offset];
            return ptr.get();
        }

        template<typename DATA_TYPE, typename ... arglist>
        void stubDataMember(DATA_TYPE C::*member, const arglist&... initargs) {
            DATA_TYPE C::*theMember = (DATA_TYPE C::*) member;
            C& mock = get();
            DATA_TYPE *memberPtr = &(mock.*theMember);
            _members.push_back(
                std::shared_ptr < DataMemeberWrapper<DATA_TYPE, arglist...> > {new DataMemeberWrapper<DATA_TYPE, arglist...>(memberPtr,
                initargs...)});
        }

        template<typename DATA_TYPE>
        void getMethodMocks(std::vector<DATA_TYPE>& into) const {
            for (std::shared_ptr<Destructable> ptr : _methodMocks) {
                DATA_TYPE p = dynamic_cast<DATA_TYPE>(ptr.get());
                if (p) {
                    into.push_back(p);
                }
            }
        }

        VirtualTable<C, baseclasses...>& getOriginalVT() {
            VirtualTable<C, baseclasses...>& vt = originalVtHandle.restore();
            return vt;
        }

    private:

        template<typename R, typename ... arglist>
        class MethodProxyCreator : public MethodProxyCreatorBase < R, arglist... > {
        public:

            MethodProxy createMethodProxy(R(C::*vMethod)(arglist...)) {
                auto offset = getOffset(vMethod);
                return MethodProxyCreatorBase < R, arglist... >::createMethodProxy(offset);
            }

            MethodProxy createDtorProxy() {
                auto offset = VTUtils::getDestructorOffset<C>();
                return MethodProxyCreatorBase < R, arglist... >::createMethodProxy(offset);
            }

            static unsigned int getOffset(R(C::*vMethod)(arglist...)) {
                return VTUtils::getOffset(vMethod);
            }

        };

        template<typename DATA_TYPE, typename ... arglist>
        class DataMemeberWrapper : public Destructable {
        private:
            DATA_TYPE *dataMember;
        public:
            DataMemeberWrapper(DATA_TYPE *dataMember, const arglist&... initargs) :
                dataMember(dataMember) {
                new (dataMember) DATA_TYPE{ initargs ... };
            }
            ~DataMemeberWrapper() {
                dataMember->~DATA_TYPE();
            }
        };

        static_assert(sizeof(C) == sizeof(FakeObject<C, baseclasses...>), "This is a problem");

        C& instance;
        typename VirtualTable<C, baseclasses...>::Handle originalVtHandle; // avoid delete!! this is the original!
        VirtualTable<C, baseclasses...> _cloneVt;//
        std::array<std::shared_ptr<Destructable>, 50> _methodMocks;
        std::vector<std::shared_ptr<Destructable>> _members;
        InvocationHandlers _invocationHandlers;

        FakeObject<C, baseclasses...>& getFake() {
            return reinterpret_cast<FakeObject<C, baseclasses...>&>(instance);
        }

        template<typename R, typename ... arglist>
        void bindMethod(const MethodProxy &methodProxy, MethodInvocationHandler<R, arglist...> *invocationHandler) {
            auto offset = methodProxy.getOffset();
            getFake().setMethod(offset, methodProxy.getProxy());
            Destructable * destructable = invocationHandler;
            _methodMocks[offset].reset(destructable);
        }

        void bindDtor(const MethodProxy &methodProxy, MethodInvocationHandler<void> *invocationHandler) {
            auto offset = methodProxy.getOffset();
            getFake().setDtor(methodProxy.getProxy());
            Destructable * destructable = invocationHandler;
            _methodMocks[offset].reset(destructable);
        }

        template<typename DATA_TYPE>
        DATA_TYPE getMethodMock(unsigned int offset) {
            std::shared_ptr<Destructable> ptr = _methodMocks[offset];
            return dynamic_cast<DATA_TYPE>(ptr.get());
        }

        template<typename BaseClass>
        void checkMultipleInheritance() {
            C* ptr = (C*) (unsigned int) 1;
            BaseClass* basePtr = ptr;
            int delta = (unsigned long) basePtr - (unsigned long) ptr;
            if (delta > 0) {
                // base class does not start on same position as derived class.
                // this is multiple inheritance.
                throw std::invalid_argument(std::string("multiple inheritance is not supported"));
            }
        }

        bool isBinded(unsigned int offset) {
            std::shared_ptr<Destructable> ptr = _methodMocks[offset];
            return ptr.get() != nullptr;
        }

    };
}
#endif // DynamicProxy_h__
<commit_msg>cleanup<commit_after>/*
 * Copyright (c) 2014 Eran Pe'er.
 *
 * This program is made available under the terms of the MIT License.
 *
 * Created on Mar 10, 2014
 */

#ifndef DynamicProxy_h__
#define DynamicProxy_h__

#include <functional>
#include <type_traits>
#include <vector>
#include <array>
#include <new>

#ifdef _MSC_VER
#include "mockutils/mscpp/VirtualTable.hpp"
#else
#include "mockutils/gcc/VirtualTable.hpp"
#endif

#include "mockutils/union_cast.hpp"
#include "mockutils/MethodInvocationHandler.hpp"
#include "mockutils/VTUtils.hpp"
#include "mockutils/FakeObject.hpp"

namespace fakeit {

    struct InvocationHandlerCollection {
        virtual Destructable* getInvocatoinHandlerPtr(unsigned int index) = 0;
    };

    static InvocationHandlerCollection * getInvocationHandlerCollection(void * instance) {
        VirtualTableBase & vt = VirtualTableBase::getVTable(instance);
        InvocationHandlerCollection * invocationHandlerCollection = (InvocationHandlerCollection*) vt.getCookie(0);
        return invocationHandlerCollection;
    }

    struct MethodProxy {

        MethodProxy(unsigned int offset, void * vMethod) :
                _vMethod(vMethod), _offset(offset) {
        }

        unsigned int getOffset() const {
            return _offset;
        }

        void * getProxy() const {
            return union_cast<void *>(_vMethod);
        }

    private:
        void * _vMethod;
        unsigned int _offset;
    };

    template<typename R, typename ... arglist>
    class MethodProxyCreatorBase{
    protected:

        MethodProxy newMethodProxy(unsigned int offset, R(MethodProxyCreatorBase::*vMethod)(arglist...)) {
            return MethodProxy(offset, union_cast<void *>(vMethod));
        }

    public:

        MethodProxy createMethodProxy(unsigned int offset) {
            return newMethodProxy(offset, getMethodProxyPtr(offset));
        }

    protected:

        R methodProxy(unsigned int index, arglist& ... args) {
            InvocationHandlerCollection *invocationHandlerCollection = getInvocationHandlerCollection(this);
            MethodInvocationHandler<R, arglist...> *invocationHandler =
                (MethodInvocationHandler<R, arglist...> *) invocationHandlerCollection->getInvocatoinHandlerPtr(index);
            return invocationHandler->handleMethodInvocation(args...);
        }

        template<int offset>
        R methodProxyX(arglist ... args) {
            return methodProxy(offset, args...);
        }

        using MethodProxyPtrType = R(MethodProxyCreatorBase::*)(arglist...);
        MethodProxyPtrType getMethodProxyPtr(unsigned int offset){
            R(MethodProxyCreatorBase::*vMethod)(arglist...) = 0;
            switch (offset) {
            case 0:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 0 > ;
                break;
            case 1:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 1 > ;
                break;
            case 2:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 2 > ;
                break;
            case 3:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 3 > ;
                break;
            case 4:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 4 > ;
                break;
            case 5:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 5 > ;
                break;
            case 6:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 6 > ;
                break;
            case 7:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 7 > ;
                break;
            case 8:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 8 > ;
                break;
            case 9:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 9 > ;
                break;
            case 10:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 10 > ;
                break;
            case 11:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 11 > ;
                break;
            case 12:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 12 > ;
                break;
            case 13:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 13 > ;
                break;
            case 14:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 14 > ;
                break;
            case 15:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 15 > ;
                break;
            case 16:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 16 > ;
                break;
            case 17:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 17 > ;
                break;
            case 18:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 18 > ;
                break;
            case 19:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 19 > ;
                break;
            case 20:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 20 > ;
                break;
            case 21:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 21 > ;
                break;
            case 22:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 22 > ;
                break;
            case 23:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 23 > ;
                break;
            case 24:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 24 > ;
                break;
            case 25:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 25 > ;
                break;
            case 26:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 26 > ;
                break;
            case 27:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 27 > ;
                break;
            case 28:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 28 > ;
                break;
            case 29:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 29 > ;
                break;
            case 30:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 30 > ;
                break;
            case 31:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 31 > ;
                break;
            case 32:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 32 > ;
                break;
            case 33:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 33 > ;
                break;
            case 34:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 34 > ;
                break;
            case 35:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 35 > ;
                break;
            case 36:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 36 > ;
                break;
            case 37:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 37 > ;
                break;
            case 38:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 38 > ;
                break;
            case 39:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 39 > ;
                break;
            case 40:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 40 > ;
                break;
            case 41:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 41 > ;
                break;
            case 42:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 42 > ;
                break;
            case 43:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 43 > ;
                break;
            case 44:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 44 > ;
                break;
            case 45:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 45 > ;
                break;
            case 46:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 46 > ;
                break;
            case 47:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 47 > ;
                break;
            case 48:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 48 > ;
                break;
            case 49:
                vMethod = &MethodProxyCreatorBase::methodProxyX < 49 > ;
                break;
            }
            return vMethod;
        }
    };

    template<typename C, typename ... baseclasses>
    struct DynamicProxy {

        class InvocationHandlers : public InvocationHandlerCollection {
            std::array<std::shared_ptr<Destructable>, 50>& _methodMocks;
        public:
            InvocationHandlers(std::array<std::shared_ptr<Destructable>, 50>& methodMocks) : _methodMocks(methodMocks){
            }

            Destructable* getInvocatoinHandlerPtr(unsigned int offset) override {
                std::shared_ptr<Destructable> ptr = _methodMocks[offset];
                return ptr.get();
            }
        };

        static_assert(std::is_polymorphic<C>::value, "DynamicProxy requires a polymorphic type");

        DynamicProxy(C& instance) :
            instance(instance), originalVtHandle(VirtualTable<C, baseclasses...>::getVTable(instance).createHandle()),
            _methodMocks(),
            _invocationHandlers(_methodMocks)
        {
            _cloneVt.copyFrom(originalVtHandle.restore());
            _cloneVt.setCookie(0, &_invocationHandlers);
            getFake().setVirtualTable(_cloneVt);
        }

        void detach()
        {
            getFake().setVirtualTable(originalVtHandle.restore());
        }

        ~DynamicProxy() {
            _cloneVt.dispose();
        }

        C& get() {
            return instance;
        }

        void Reset() {
            _methodMocks = { {} };
            _members = {};
            _cloneVt.copyFrom(originalVtHandle.restore());
        }

        template<typename R, typename ... arglist>
        void stubMethod(R(C::*vMethod)(arglist...), MethodInvocationHandler<R, arglist...>* methodInvocationHandler) {
            MethodProxyCreator<R, arglist...> creator;
            bindMethod(creator.createMethodProxy(vMethod), methodInvocationHandler);
        }

        void stubDtor(MethodInvocationHandler<void>* methodInvocationHandler) {
            MethodProxyCreator<void> creator;
            bindDtor(creator.createDtorProxy(), methodInvocationHandler);
        }

        template<typename R, typename ... arglist>
        bool isMethodStubbed(R(C::*vMethod)(arglist...)) {
            unsigned int offset = MethodProxyCreator<R, arglist...>::getOffset(vMethod);
            return isBinded(offset);
        }

        bool isDtorStubbed() {
            unsigned int offset = VTUtils::getDestructorOffset<C>();
            return isBinded((unsigned int) offset);
        }

        template<typename R, typename ... arglist>
        Destructable * getMethodMock(R(C::*vMethod)(arglist...)) {
            auto offset = MethodProxyCreator<R, arglist...>::getOffset(vMethod);
            std::shared_ptr<Destructable> ptr = _methodMocks[offset];
            return ptr.get();
        }

        Destructable * getDtorMock() {
            auto offset = VTUtils::getDestructorOffset<C>();
            std::shared_ptr<Destructable> ptr = _methodMocks[offset];
            return ptr.get();
        }

        template<typename DATA_TYPE, typename ... arglist>
        void stubDataMember(DATA_TYPE C::*member, const arglist&... initargs) {
            DATA_TYPE C::*theMember = (DATA_TYPE C::*) member;
            C& mock = get();
            DATA_TYPE *memberPtr = &(mock.*theMember);
            _members.push_back(
                std::shared_ptr < DataMemeberWrapper<DATA_TYPE, arglist...> > {new DataMemeberWrapper<DATA_TYPE, arglist...>(memberPtr,
                initargs...)});
        }

        template<typename DATA_TYPE>
        void getMethodMocks(std::vector<DATA_TYPE>& into) const {
            for (std::shared_ptr<Destructable> ptr : _methodMocks) {
                DATA_TYPE p = dynamic_cast<DATA_TYPE>(ptr.get());
                if (p) {
                    into.push_back(p);
                }
            }
        }

        VirtualTable<C, baseclasses...>& getOriginalVT() {
            VirtualTable<C, baseclasses...>& vt = originalVtHandle.restore();
            return vt;
        }

    private:

        template<typename R, typename ... arglist>
        class MethodProxyCreator : public MethodProxyCreatorBase < R, arglist... > {
        public:

            MethodProxy createMethodProxy(R(C::*vMethod)(arglist...)) {
                auto offset = getOffset(vMethod);
                return MethodProxyCreatorBase < R, arglist... >::createMethodProxy(offset);
            }

            MethodProxy createDtorProxy() {
                auto offset = VTUtils::getDestructorOffset<C>();
                return MethodProxyCreatorBase < R, arglist... >::createMethodProxy(offset);
            }

            static unsigned int getOffset(R(C::*vMethod)(arglist...)) {
                return VTUtils::getOffset(vMethod);
            }

        };

        template<typename DATA_TYPE, typename ... arglist>
        class DataMemeberWrapper : public Destructable {
        private:
            DATA_TYPE *dataMember;
        public:
            DataMemeberWrapper(DATA_TYPE *dataMember, const arglist&... initargs) :
                dataMember(dataMember) {
                new (dataMember) DATA_TYPE{ initargs ... };
            }
            ~DataMemeberWrapper() {
                dataMember->~DATA_TYPE();
            }
        };

        static_assert(sizeof(C) == sizeof(FakeObject<C, baseclasses...>), "This is a problem");

        C& instance;
        typename VirtualTable<C, baseclasses...>::Handle originalVtHandle; // avoid delete!! this is the original!
        VirtualTable<C, baseclasses...> _cloneVt;//
        std::array<std::shared_ptr<Destructable>, 50> _methodMocks;
        std::vector<std::shared_ptr<Destructable>> _members;
        InvocationHandlers _invocationHandlers;

        FakeObject<C, baseclasses...>& getFake() {
            return reinterpret_cast<FakeObject<C, baseclasses...>&>(instance);
        }

        template<typename R, typename ... arglist>
        void bindMethod(const MethodProxy &methodProxy, MethodInvocationHandler<R, arglist...> *invocationHandler) {
            auto offset = methodProxy.getOffset();
            getFake().setMethod(offset, methodProxy.getProxy());
            Destructable * destructable = invocationHandler;
            _methodMocks[offset].reset(destructable);
        }

        void bindDtor(const MethodProxy &methodProxy, MethodInvocationHandler<void> *invocationHandler) {
            auto offset = methodProxy.getOffset();
            getFake().setDtor(methodProxy.getProxy());
            Destructable * destructable = invocationHandler;
            _methodMocks[offset].reset(destructable);
        }

        template<typename DATA_TYPE>
        DATA_TYPE getMethodMock(unsigned int offset) {
            std::shared_ptr<Destructable> ptr = _methodMocks[offset];
            return dynamic_cast<DATA_TYPE>(ptr.get());
        }

        template<typename BaseClass>
        void checkMultipleInheritance() {
            C* ptr = (C*) (unsigned int) 1;
            BaseClass* basePtr = ptr;
            int delta = (unsigned long) basePtr - (unsigned long) ptr;
            if (delta > 0) {
                // base class does not start on same position as derived class.
                // this is multiple inheritance.
                throw std::invalid_argument(std::string("multiple inheritance is not supported"));
            }
        }

        bool isBinded(unsigned int offset) {
            std::shared_ptr<Destructable> ptr = _methodMocks[offset];
            return ptr.get() != nullptr;
        }

    };
}
#endif // DynamicProxy_h__
<|endoftext|>


<commit_before>#ifndef CENTROID_HPP
#define CENTROID_HPP
#include "mtao/types.hpp"
#include "mtao/util.h"
#include <numeric>
#include <cassert>

namespace mtao::geometry {
    template <typename Derived, typename BeginIt, typename EndIt>
        auto curve_centroid( const Eigen::MatrixBase<Derived> & V, const BeginIt& beginit, const EndIt& endit) {
            static_assert(
                    V::RowsAtCompileTime == 2 ||
                    V::RowsAtCompileTime == 3 ||
                    V::RowsAtCompileTime == Eigen::Dynamic);
            auto it = beginit;
            auto it1 = beginit;
            it1++;
            typename Derived::Scalar vol = 0;
            mtao::Vector<typename Derived::Scalar,Derived::RowsAtCompileTime> ret(V.rows());
            ret.setZero();
            for(; it != endit; ++it, ++it1) {
                if(it1 == endit) {
                    it1 = beginit;
                }
                auto a = V.col(*it);
                auto b = V.col(*it1);
                typename Derived::Scalar v;
                if constexpr(V::RowsAtCompileTime == 2) {
                    v = a.x() * b.y() - a.y() * b.x();
                } else if constexpr(V::RowsAtCompileTime == 3) {
                    v = a.cross(b).norm();
                } else if constexpr(V::RowsAtCompileTime == Eigen::Dynamic) {
                    if(V.rows() == 2) {
                        v = a.x() * b.y() - a.y() * b.x();
                    } else if(V.rows() == 3) {

                        v = a.cross(b).norm();
                    }
                }
                vol += v;
                ret += v * (a + b) / 3;

            }
            if(vol > 1e-10) {
            ret /= vol;
            }
            return ret;

        }
    template <typename Derived, typename Container>
        auto curve_centroid( const Eigen::MatrixBase<Derived> & V, const Container& C) {
            return curve_centroid(V,C.begin(),C.end());
        }
}
#endif//CENTROID_HPP
<commit_msg>was i drink?<commit_after>#ifndef CENTROID_HPP
#define CENTROID_HPP
#include "mtao/types.hpp"
#include "mtao/util.h"
#include <numeric>
#include <cassert>

namespace mtao::geometry {
    template <typename Derived, typename BeginIt, typename EndIt>
        auto curve_centroid( const Eigen::MatrixBase<Derived> & V, const BeginIt& beginit, const EndIt& endit) {
            static_assert(
                    Derived::RowsAtCompileTime == 2 ||
                    Derived::RowsAtCompileTime == 3 ||
                    Derived::RowsAtCompileTime == Eigen::Dynamic);
            auto it = beginit;
            auto it1 = beginit;
            it1++;
            typename Derived::Scalar vol = 0;
            mtao::Vector<typename Derived::Scalar,Derived::RowsAtCompileTime> ret(V.rows());
            ret.setZero();
            for(; it != endit; ++it, ++it1) {
                if(it1 == endit) {
                    it1 = beginit;
                }
                auto a = V.col(*it);
                auto b = V.col(*it1);
                typename Derived::Scalar v;
                if constexpr(Derived::RowsAtCompileTime == 2) {
                    v = a.x() * b.y() - a.y() * b.x();
                } else if constexpr(Derived::RowsAtCompileTime == 3) {
                    v = a.cross(b).norm();
                } else if constexpr(Derived::RowsAtCompileTime == Eigen::Dynamic) {
                    if(V.rows() == 2) {
                        v = a.x() * b.y() - a.y() * b.x();
                    } else if(V.rows() == 3) {

                        v = a.cross(b).norm();
                    }
                }
                vol += v;
                ret += v * (a + b) / 3;

            }
            if(vol > 1e-10) {
            ret /= vol;
            }
            return ret;

        }
    template <typename Derived, typename Container>
        auto curve_centroid( const Eigen::MatrixBase<Derived> & V, const Container& C) {
            return curve_centroid(V,C.begin(),C.end());
        }
}
#endif//CENTROID_HPP
<|endoftext|>