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

#include "crumblepath.h"
#include "stylehelper.h"

#include <QtCore/QList>
#include <QtGui/QHBoxLayout>
#include <QtGui/QPushButton>
#include <QtGui/QMenu>
#include <QtGui/QStyle>
#include <QtGui/QResizeEvent>
#include <QtGui/QPainter>
#include <QtGui/QImage>

#include <qtcassert.h>

namespace Utils {

static const int ArrowBorderSize = 12;

class CrumblePathButton : public QPushButton
{
public:
    enum SegmentType {
        LastSegment = 1,
        MiddleSegment = 2,
        FirstSegment = 4
    };

    explicit CrumblePathButton(const QString &title, QWidget *parent = 0);
    void setSegmentType(int type);
    void select(bool s);
    void setData(const QVariant &data);
    QVariant data() const;

protected:
    void paintEvent(QPaintEvent *);
    void mouseMoveEvent(QMouseEvent *e);
    void leaveEvent(QEvent *);
    void mousePressEvent(QMouseEvent *e);
    void mouseReleaseEvent(QMouseEvent *e);

private:
    void tintImages();

private:
    bool m_isHovering;
    bool m_isPressed;
    bool m_isSelected;
    bool m_isEnd;
    QColor m_baseColor;
    QImage m_segment;
    QImage m_segmentEnd;
    QImage m_segmentSelected;
    QImage m_segmentSelectedEnd;
    QImage m_segmentHover;
    QImage m_segmentHoverEnd;
    QImage m_triangleIcon;
    QPoint m_textPos;

    QVariant m_data;
};

CrumblePathButton::CrumblePathButton(const QString &title, QWidget *parent)
    : QPushButton(title, parent), m_isHovering(false), m_isPressed(false), m_isSelected(false), m_isEnd(true)
{
    setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
    setToolTip(title);
    setMinimumHeight(25);
    setMaximumHeight(25);
    setMouseTracking(true);
    m_textPos.setX(18);
    m_textPos.setY(height());
    m_baseColor = StyleHelper::baseColor();

    m_segment = QImage(":/utils/images/crumblepath-segment.png");
    m_segmentSelected = QImage(":/utils/images/crumblepath-segment-selected.png");
    m_segmentHover = QImage(":/utils/images/crumblepath-segment-hover.png");
    m_segmentEnd = QImage(":/utils/images/crumblepath-segment-end.png");
    m_segmentSelectedEnd = QImage(":/utils/images/crumblepath-segment-selected-end.png");
    m_segmentHoverEnd = QImage(":/utils/images/crumblepath-segment-hover-end.png");
    m_triangleIcon = QImage(":/utils/images/triangle_vert.png");

    tintImages();
}

void CrumblePathButton::paintEvent(QPaintEvent *)
{
    QPainter p(this);
    QRect geom(0, 0, geometry().width(), geometry().height());

    if (StyleHelper::baseColor() != m_baseColor) {
        m_baseColor = StyleHelper::baseColor();
        tintImages();
    }

    if (m_isEnd) {
        if (m_isPressed || m_isSelected) {
            Utils::StyleHelper::drawCornerImage(m_segmentSelectedEnd, &p, geom, 2, 0, 2, 0);
        } else if (m_isHovering) {
            Utils::StyleHelper::drawCornerImage(m_segmentHoverEnd, &p, geom, 2, 0, 2, 0);
        } else {
            Utils::StyleHelper::drawCornerImage(m_segmentEnd, &p, geom, 2, 0, 2, 0);
        }
    } else {
        if (m_isPressed || m_isSelected) {
            Utils::StyleHelper::drawCornerImage(m_segmentSelected, &p, geom, 2, 0, 12, 0);
        } else if (m_isHovering) {
            Utils::StyleHelper::drawCornerImage(m_segmentHover, &p, geom, 2, 0, 12, 0);
        } else {
            Utils::StyleHelper::drawCornerImage(m_segment, &p, geom, 2, 0, 12, 0);
        }
    }
    p.setPen(StyleHelper::panelTextColor());
    QFontMetrics fm(p.font());
    QString textToDraw = fm.elidedText(text(), Qt::ElideRight, geom.width() - m_textPos.x());

    p.drawText(QRectF(m_textPos.x(), 4, geom.width(), geom.height()), textToDraw);

    if (menu()) {
        p.drawImage(geom.width() - m_triangleIcon.width() - 6,
                    geom.center().y() - m_triangleIcon.height() / 2,
                    m_triangleIcon);
    }
}

void CrumblePathButton::tintImages()
{
    StyleHelper::tintImage(m_segmentEnd, m_baseColor);
    StyleHelper::tintImage(m_segmentSelectedEnd, m_baseColor);
    StyleHelper::tintImage(m_segmentHoverEnd, m_baseColor);
    StyleHelper::tintImage(m_segmentSelected, m_baseColor);
    StyleHelper::tintImage(m_segmentHover, m_baseColor);
    StyleHelper::tintImage(m_segment, m_baseColor);
}

void CrumblePathButton::leaveEvent(QEvent *e)
{
    QPushButton::leaveEvent(e);
    m_isHovering = false;
    update();
}

void CrumblePathButton::mouseMoveEvent(QMouseEvent *e)
{
    QPushButton::mouseMoveEvent(e);
    m_isHovering = true;
    update();
}

void CrumblePathButton::mousePressEvent(QMouseEvent *e)
{
    QPushButton::mousePressEvent(e);
    m_isPressed = true;
    update();
}

void CrumblePathButton::mouseReleaseEvent(QMouseEvent *e)
{
    QPushButton::mouseReleaseEvent(e);
    m_isPressed = false;
    update();
}

void CrumblePathButton::select(bool s)
{
    m_isSelected = s;
    update();
}

void CrumblePathButton::setSegmentType(int type)
{
    bool useLeftPadding = !(type & FirstSegment);
    m_isEnd = (type & LastSegment);
    m_textPos.setX(useLeftPadding ? 18 : 4);
}

void CrumblePathButton::setData(const QVariant &data)
{
    m_data = data;
}

QVariant CrumblePathButton::data() const
{
    return m_data;
}

///////////////////////////////////////////////////////////////////////////////

struct CrumblePathPrivate
{
    explicit CrumblePathPrivate(CrumblePath *q);

    QList<CrumblePathButton*> m_buttons;
};

CrumblePathPrivate::CrumblePathPrivate(CrumblePath *q)
{
    Q_UNUSED(q)
}

//
// CrumblePath
//
CrumblePath::CrumblePath(QWidget *parent) :
    QWidget(parent), d(new CrumblePathPrivate(this))
{
    setMinimumHeight(25);
    setMaximumHeight(25);
    setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
}

CrumblePath::~CrumblePath()
{
    qDeleteAll(d->m_buttons);
    d->m_buttons.clear();
}

void CrumblePath::selectIndex(int index)
{
    if (index > -1 && index < d->m_buttons.length())
        d->m_buttons[index]->select(true);
}

QVariant CrumblePath::dataForIndex(int index) const
{
    if (index > -1 && index < d->m_buttons.length())
        return d->m_buttons[index]->data();
    return QVariant();
}

void CrumblePath::pushElement(const QString &title, const QVariant &data)
{
    CrumblePathButton *newButton = new CrumblePathButton(title, this);
    newButton->hide();
    connect(newButton, SIGNAL(clicked()), SLOT(mapClickToIndex()));

    int segType = CrumblePathButton::MiddleSegment;
    if (!d->m_buttons.isEmpty()) {
        if (d->m_buttons.length() == 1)
            segType = segType | CrumblePathButton::FirstSegment;
        d->m_buttons.last()->setSegmentType(segType);
    } else {
        segType = CrumblePathButton::FirstSegment | CrumblePathButton::LastSegment;
        newButton->setSegmentType(segType);
    }
    newButton->setData(data);
    d->m_buttons.append(newButton);

    resizeButtons();
}

void CrumblePath::addChild(const QString &title, const QVariant &data)
{
    QTC_ASSERT(d->m_buttons.count() > 0,return);

    QPushButton *lastButton = d->m_buttons.last();

    QMenu *childList = lastButton->menu();
    if (childList == 0)
        childList = new QMenu(lastButton);

    QAction *childAction = new QAction(title, lastButton);
    childAction->setData(data);
    connect(childAction, SIGNAL(triggered()), this, SLOT(mapClickToIndex()));
    childList->addAction(childAction);
    lastButton->setMenu(childList);
}

void CrumblePath::popElement()
{
    QWidget *last = d->m_buttons.last();
    d->m_buttons.removeLast();
    last->setParent(0);
    last->deleteLater();

    int segType = CrumblePathButton::MiddleSegment | CrumblePathButton::LastSegment;
    if (!d->m_buttons.isEmpty()) {
        if (d->m_buttons.length() == 1)
            segType = CrumblePathButton::FirstSegment | CrumblePathButton::LastSegment;
        d->m_buttons.last()->setSegmentType(segType);
    }
    resizeButtons();
}

void CrumblePath::clear()
{
    while (!d->m_buttons.isEmpty())
        popElement();
}

void CrumblePath::resizeEvent(QResizeEvent *)
{
    resizeButtons();
}

void CrumblePath::resizeButtons()
{
    int totalWidthLeft = width();

    if (d->m_buttons.length() >= 1) {
        QPoint nextElementPosition(0, 0);

        d->m_buttons.first()->raise();
        // rearrange all items so that the first item is on top (added last).

        // compute relative sizes
        QList<int> sizes;
        int totalSize = 0;
        for (int i = 0; i < d->m_buttons.length() ; ++i) {
            CrumblePathButton *button = d->m_buttons.at(i);

            QFontMetrics fm(button->font());
            int originalSize = ArrowBorderSize + fm.width(button->text()) + ArrowBorderSize + 12;
            sizes << originalSize;
            totalSize += originalSize - ArrowBorderSize;
        }

        for (int i = 0; i < d->m_buttons.length() ; ++i) {
            CrumblePathButton *button = d->m_buttons.at(i);

            int candidateSize = (sizes.at(i) * totalWidthLeft) / totalSize;
            if (candidateSize < ArrowBorderSize)
                candidateSize = ArrowBorderSize;
            if (candidateSize > sizes.at(i) * 1.3)
                candidateSize = sizes.at(i) * 1.3;

            button->setMinimumWidth(candidateSize);
            button->setMaximumWidth(candidateSize);
            button->move(nextElementPosition);

            nextElementPosition.rx() += button->width() - ArrowBorderSize;

            button->show();
            if (i > 0)
                button->stackUnder(d->m_buttons[i - 1]);
        }
    }
}

void CrumblePath::mapClickToIndex()
{
    QObject *element = sender();
    if (QString("QAction") == element->metaObject()->className())
        emit elementClicked(static_cast<QAction *>(element)->data().toInt());
    else if (QString("QPushButton") == element->metaObject()->className())
        emit elementClicked(static_cast<CrumblePathButton *>(element)->data().toInt());
}

} // namespace Utils
<commit_msg>QmlDebug: Fix crash on Mac OS X<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "crumblepath.h"
#include "stylehelper.h"

#include <QtCore/QList>
#include <QtGui/QHBoxLayout>
#include <QtGui/QPushButton>
#include <QtGui/QMenu>
#include <QtGui/QStyle>
#include <QtGui/QResizeEvent>
#include <QtGui/QPainter>
#include <QtGui/QImage>

#include <qtcassert.h>

namespace Utils {

static const int ArrowBorderSize = 12;

class CrumblePathButton : public QPushButton
{
public:
    enum SegmentType {
        LastSegment = 1,
        MiddleSegment = 2,
        FirstSegment = 4
    };

    explicit CrumblePathButton(const QString &title, QWidget *parent = 0);
    void setSegmentType(int type);
    void select(bool s);
    void setData(const QVariant &data);
    QVariant data() const;

protected:
    void paintEvent(QPaintEvent *);
    void mouseMoveEvent(QMouseEvent *e);
    void leaveEvent(QEvent *);
    void mousePressEvent(QMouseEvent *e);
    void mouseReleaseEvent(QMouseEvent *e);

private:
    void tintImages();

private:
    bool m_isHovering;
    bool m_isPressed;
    bool m_isSelected;
    bool m_isEnd;
    QColor m_baseColor;
    QImage m_segment;
    QImage m_segmentEnd;
    QImage m_segmentSelected;
    QImage m_segmentSelectedEnd;
    QImage m_segmentHover;
    QImage m_segmentHoverEnd;
    QImage m_triangleIcon;
    QPoint m_textPos;

    QVariant m_data;
};

CrumblePathButton::CrumblePathButton(const QString &title, QWidget *parent)
    : QPushButton(title, parent), m_isHovering(false), m_isPressed(false), m_isSelected(false), m_isEnd(true)
{
    setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
    setToolTip(title);
    setMinimumHeight(25);
    setMaximumHeight(25);
    setMouseTracking(true);
    m_textPos.setX(18);
    m_textPos.setY(height());
    m_baseColor = StyleHelper::baseColor();

    m_segment = QImage(":/utils/images/crumblepath-segment.png");
    m_segmentSelected = QImage(":/utils/images/crumblepath-segment-selected.png");
    m_segmentHover = QImage(":/utils/images/crumblepath-segment-hover.png");
    m_segmentEnd = QImage(":/utils/images/crumblepath-segment-end.png");
    m_segmentSelectedEnd = QImage(":/utils/images/crumblepath-segment-selected-end.png");
    m_segmentHoverEnd = QImage(":/utils/images/crumblepath-segment-hover-end.png");
    m_triangleIcon = QImage(":/utils/images/triangle_vert.png");

    tintImages();
}

void CrumblePathButton::paintEvent(QPaintEvent *)
{
    QPainter p(this);
    QRect geom(0, 0, geometry().width(), geometry().height());

    if (StyleHelper::baseColor() != m_baseColor) {
        m_baseColor = StyleHelper::baseColor();
        tintImages();
    }

    if (m_isEnd) {
        if (m_isPressed || m_isSelected) {
            Utils::StyleHelper::drawCornerImage(m_segmentSelectedEnd, &p, geom, 2, 0, 2, 0);
        } else if (m_isHovering) {
            Utils::StyleHelper::drawCornerImage(m_segmentHoverEnd, &p, geom, 2, 0, 2, 0);
        } else {
            Utils::StyleHelper::drawCornerImage(m_segmentEnd, &p, geom, 2, 0, 2, 0);
        }
    } else {
        if (m_isPressed || m_isSelected) {
            Utils::StyleHelper::drawCornerImage(m_segmentSelected, &p, geom, 2, 0, 12, 0);
        } else if (m_isHovering) {
            Utils::StyleHelper::drawCornerImage(m_segmentHover, &p, geom, 2, 0, 12, 0);
        } else {
            Utils::StyleHelper::drawCornerImage(m_segment, &p, geom, 2, 0, 12, 0);
        }
    }
    p.setPen(StyleHelper::panelTextColor());
    QFontMetrics fm(p.font());
    QString textToDraw = fm.elidedText(text(), Qt::ElideRight, geom.width() - m_textPos.x());

    p.drawText(QRectF(m_textPos.x(), 4, geom.width(), geom.height()), textToDraw);

    if (menu()) {
        p.drawImage(geom.width() - m_triangleIcon.width() - 6,
                    geom.center().y() - m_triangleIcon.height() / 2,
                    m_triangleIcon);
    }
}

void CrumblePathButton::tintImages()
{
    StyleHelper::tintImage(m_segmentEnd, m_baseColor);
    StyleHelper::tintImage(m_segmentSelectedEnd, m_baseColor);
    StyleHelper::tintImage(m_segmentHoverEnd, m_baseColor);
    StyleHelper::tintImage(m_segmentSelected, m_baseColor);
    StyleHelper::tintImage(m_segmentHover, m_baseColor);
    StyleHelper::tintImage(m_segment, m_baseColor);
}

void CrumblePathButton::leaveEvent(QEvent *e)
{
    QPushButton::leaveEvent(e);
    m_isHovering = false;
    update();
}

void CrumblePathButton::mouseMoveEvent(QMouseEvent *e)
{
    QPushButton::mouseMoveEvent(e);
    m_isHovering = true;
    update();
}

void CrumblePathButton::mousePressEvent(QMouseEvent *e)
{
    QPushButton::mousePressEvent(e);
    m_isPressed = true;
    update();
}

void CrumblePathButton::mouseReleaseEvent(QMouseEvent *e)
{
    QPushButton::mouseReleaseEvent(e);
    m_isPressed = false;
    update();
}

void CrumblePathButton::select(bool s)
{
    m_isSelected = s;
    update();
}

void CrumblePathButton::setSegmentType(int type)
{
    bool useLeftPadding = !(type & FirstSegment);
    m_isEnd = (type & LastSegment);
    m_textPos.setX(useLeftPadding ? 18 : 4);
}

void CrumblePathButton::setData(const QVariant &data)
{
    m_data = data;
}

QVariant CrumblePathButton::data() const
{
    return m_data;
}

///////////////////////////////////////////////////////////////////////////////

struct CrumblePathPrivate
{
    explicit CrumblePathPrivate(CrumblePath *q);

    QList<CrumblePathButton*> m_buttons;
};

CrumblePathPrivate::CrumblePathPrivate(CrumblePath *q)
{
    Q_UNUSED(q)
}

//
// CrumblePath
//
CrumblePath::CrumblePath(QWidget *parent) :
    QWidget(parent), d(new CrumblePathPrivate(this))
{
    setMinimumHeight(25);
    setMaximumHeight(25);
    setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
}

CrumblePath::~CrumblePath()
{
    qDeleteAll(d->m_buttons);
    d->m_buttons.clear();
}

void CrumblePath::selectIndex(int index)
{
    if (index > -1 && index < d->m_buttons.length())
        d->m_buttons[index]->select(true);
}

QVariant CrumblePath::dataForIndex(int index) const
{
    if (index > -1 && index < d->m_buttons.length())
        return d->m_buttons[index]->data();
    return QVariant();
}

void CrumblePath::pushElement(const QString &title, const QVariant &data)
{
    CrumblePathButton *newButton = new CrumblePathButton(title, this);
    newButton->hide();
    connect(newButton, SIGNAL(clicked()), SLOT(mapClickToIndex()));

    int segType = CrumblePathButton::MiddleSegment;
    if (!d->m_buttons.isEmpty()) {
        if (d->m_buttons.length() == 1)
            segType = segType | CrumblePathButton::FirstSegment;
        d->m_buttons.last()->setSegmentType(segType);
    } else {
        segType = CrumblePathButton::FirstSegment | CrumblePathButton::LastSegment;
        newButton->setSegmentType(segType);
    }
    newButton->setData(data);
    d->m_buttons.append(newButton);

    resizeButtons();
}

void CrumblePath::addChild(const QString &title, const QVariant &data)
{
    QTC_ASSERT(d->m_buttons.count() > 0,return);

    QPushButton *lastButton = d->m_buttons.last();

    QMenu *childList = lastButton->menu();
    if (childList == 0)
        childList = new QMenu(lastButton);

    QAction *childAction = new QAction(title, lastButton);
    childAction->setData(data);
    connect(childAction, SIGNAL(triggered()), this, SLOT(mapClickToIndex()));
    childList->addAction(childAction);
    lastButton->setMenu(childList);
}

void CrumblePath::popElement()
{
    QWidget *last = d->m_buttons.last();
    d->m_buttons.removeLast();
    last->setParent(0);
    last->deleteLater();

    int segType = CrumblePathButton::MiddleSegment | CrumblePathButton::LastSegment;
    if (!d->m_buttons.isEmpty()) {
        if (d->m_buttons.length() == 1)
            segType = CrumblePathButton::FirstSegment | CrumblePathButton::LastSegment;
        d->m_buttons.last()->setSegmentType(segType);
    }
    resizeButtons();
}

void CrumblePath::clear()
{
    while (!d->m_buttons.isEmpty())
        popElement();
}

void CrumblePath::resizeEvent(QResizeEvent *)
{
    resizeButtons();
}

void CrumblePath::resizeButtons()
{
    int totalWidthLeft = width();

    if (d->m_buttons.length() >= 1) {
        QPoint nextElementPosition(0, 0);

        d->m_buttons.first()->raise();
        // rearrange all items so that the first item is on top (added last).

        // compute relative sizes
        QList<int> sizes;
        int totalSize = 0;
        for (int i = 0; i < d->m_buttons.length() ; ++i) {
            CrumblePathButton *button = d->m_buttons.at(i);

            QFontMetrics fm(button->font());
            int originalSize = ArrowBorderSize + fm.width(button->text()) + ArrowBorderSize + 12;
            sizes << originalSize;
            totalSize += originalSize - ArrowBorderSize;
        }

        for (int i = 0; i < d->m_buttons.length() ; ++i) {
            CrumblePathButton *button = d->m_buttons.at(i);

            int candidateSize = (sizes.at(i) * totalWidthLeft) / totalSize;
            if (candidateSize < ArrowBorderSize)
                candidateSize = ArrowBorderSize;
            if (candidateSize > sizes.at(i) * 1.3)
                candidateSize = sizes.at(i) * 1.3;

            button->setMinimumWidth(candidateSize);
            button->setMaximumWidth(candidateSize);
            button->move(nextElementPosition);

            nextElementPosition.rx() += button->width() - ArrowBorderSize;

            button->show();
            if (i > 0) {
                // work-around for a compiler / optimization bug in i686-apple-darwin9-g
                // without volatile, the optimizer (-O2) seems to do the wrong thing (tm
                // the d->m_buttons array with an invalid argument.
                volatile int prevIndex = i - 1;
                button->stackUnder(d->m_buttons[prevIndex]);
            }
        }
    }
}

void CrumblePath::mapClickToIndex()
{
    QObject *element = sender();
    if (QString("QAction") == element->metaObject()->className())
        emit elementClicked(static_cast<QAction *>(element)->data().toInt());
    else if (QString("QPushButton") == element->metaObject()->className())
        emit elementClicked(static_cast<CrumblePathButton *>(element)->data().toInt());
}

} // namespace Utils
<|endoftext|>


<commit_before>#ifndef slic3r_TriangleMesh_hpp_
#define slic3r_TriangleMesh_hpp_

#include "libslic3r.h"
#include <admesh/stl.h>
#include <functional>
#include <vector>
#include <boost/thread.hpp>
#include "BoundingBox.hpp"
#include "Line.hpp"
#include "Point.hpp"
#include "Polygon.hpp"
#include "ExPolygon.hpp"

namespace Slic3r {

class TriangleMesh;
class TriangleMeshSlicer;
typedef std::vector<TriangleMesh*> TriangleMeshPtrs;

class TriangleMesh
{
public:
    TriangleMesh() : repaired(false) {}
    TriangleMesh(const Pointf3s &points, const std::vector<Vec3crd> &facets);
	void clear() { this->stl.clear(); this->its.clear(); this->repaired = false; }
    bool ReadSTLFile(const char* input_file) { return stl_open(&stl, input_file); }
    bool write_ascii(const char* output_file) { return stl_write_ascii(&this->stl, output_file, ""); }
    bool write_binary(const char* output_file) { return stl_write_binary(&this->stl, output_file, ""); }
    void repair(bool update_shared_vertices = true);
    float volume();
    void check_topology();
    bool is_manifold() const { return this->stl.stats.connected_facets_3_edge == (int)this->stl.stats.number_of_facets; }
    void WriteOBJFile(const char* output_file) const;
    void scale(float factor);
    void scale(const Vec3d &versor);
    void translate(float x, float y, float z);
    void translate(const Vec3f &displacement);
    void rotate(float angle, const Axis &axis);
    void rotate(float angle, const Vec3d& axis);
    void rotate_x(float angle) { this->rotate(angle, X); }
    void rotate_y(float angle) { this->rotate(angle, Y); }
    void rotate_z(float angle) { this->rotate(angle, Z); }
    void mirror(const Axis &axis);
    void mirror_x() { this->mirror(X); }
    void mirror_y() { this->mirror(Y); }
    void mirror_z() { this->mirror(Z); }
    void transform(const Transform3d& t, bool fix_left_handed = false);
	void transform(const Matrix3d& t, bool fix_left_handed = false);
    void align_to_origin();
    void rotate(double angle, Point* center);
    TriangleMeshPtrs split() const;
    void merge(const TriangleMesh &mesh);
    ExPolygons horizontal_projection() const;
    const float* first_vertex() const { return this->stl.facet_start.empty() ? nullptr : &this->stl.facet_start.front().vertex[0](0); }
    // 2D convex hull of a 3D mesh projected into the Z=0 plane.
    Polygon convex_hull();
    BoundingBoxf3 bounding_box() const;
    // Returns the bbox of this TriangleMesh transformed by the given transformation
    BoundingBoxf3 transformed_bounding_box(const Transform3d &trafo) const;
    // Return the size of the mesh in coordinates.
    Vec3d size() const { return stl.stats.size.cast<double>(); }
    /// Return the center of the related bounding box.
	Vec3d center() const { return this->bounding_box().center(); }
    // Returns the convex hull of this TriangleMesh
    TriangleMesh convex_hull_3d() const;
    // Slice this mesh at the provided Z levels and return the vector
    std::vector<ExPolygons> slice(const std::vector<double>& z);
    void reset_repair_stats();
    bool needed_repair() const;
    void require_shared_vertices();
    bool   has_shared_vertices() const { return ! this->its.vertices.empty(); }
    size_t facets_count() const { return this->stl.stats.number_of_facets; }
    bool   empty() const { return this->facets_count() == 0; }
    bool is_splittable() const;
    // Estimate of the memory occupied by this structure, important for keeping an eye on the Undo / Redo stack allocation.
    size_t memsize() const;
    // Release optional data from the mesh if the object is on the Undo / Redo stack only. Returns the amount of memory released.
    size_t release_optional();
	// Restore optional data possibly released by release_optional().
	void restore_optional();

    stl_file stl;
    indexed_triangle_set its;
    bool repaired;

private:
    std::deque<uint32_t> find_unvisited_neighbors(std::vector<unsigned char> &facet_visited) const;
};

enum FacetEdgeType {
    // A general case, the cutting plane intersect a face at two different edges.
    feGeneral,
    // Two vertices are aligned with the cutting plane, the third vertex is below the cutting plane.
    feTop,
    // Two vertices are aligned with the cutting plane, the third vertex is above the cutting plane.
    feBottom,
    // All three vertices of a face are aligned with the cutting plane.
    feHorizontal
};

class IntersectionReference
{
public:
    IntersectionReference() : point_id(-1), edge_id(-1) {};
    IntersectionReference(int point_id, int edge_id) : point_id(point_id), edge_id(edge_id) {}
    // Where is this intersection point located? On mesh vertex or mesh edge?
    // Only one of the following will be set, the other will remain set to -1.
    // Index of the mesh vertex.
    int point_id;
    // Index of the mesh edge.
    int edge_id;
};

class IntersectionPoint : public Point, public IntersectionReference
{
public:
    IntersectionPoint() {};
    IntersectionPoint(int point_id, int edge_id, const Point &pt) : IntersectionReference(point_id, edge_id), Point(pt) {}
    IntersectionPoint(const IntersectionReference &ir, const Point &pt) : IntersectionReference(ir), Point(pt) {}
    // Inherits coord_t x, y
};

class IntersectionLine : public Line
{
public:
    IntersectionLine() : a_id(-1), b_id(-1), edge_a_id(-1), edge_b_id(-1), edge_type(feGeneral), flags(0) {}

    bool skip() const { return (this->flags & SKIP) != 0; }
    void set_skip() { this->flags |= SKIP; }

    bool is_seed_candidate() const { return (this->flags & NO_SEED) == 0 && ! this->skip(); }
    void set_no_seed(bool set) { if (set) this->flags |= NO_SEED; else this->flags &= ~NO_SEED; }

    // Inherits Point a, b
    // For each line end point, either {a,b}_id or {a,b}edge_a_id is set, the other is left to -1.
    // Vertex indices of the line end points.
    int             a_id;
    int             b_id;
    // Source mesh edges of the line end points.
    int             edge_a_id;
    int             edge_b_id;
    // feGeneral, feTop, feBottom, feHorizontal
    FacetEdgeType   edge_type;
    // Used by TriangleMeshSlicer::slice() to skip duplicate edges.
    enum {
        // Triangle edge added, because it has no neighbor.
        EDGE0_NO_NEIGHBOR   = 0x001,
        EDGE1_NO_NEIGHBOR   = 0x002,
        EDGE2_NO_NEIGHBOR   = 0x004,
        // Triangle edge added, because it makes a fold with another horizontal edge.
        EDGE0_FOLD          = 0x010,
        EDGE1_FOLD          = 0x020,
        EDGE2_FOLD          = 0x040,
        // The edge cannot be a seed of a greedy loop extraction (folds are not safe to become seeds).
        NO_SEED             = 0x100,
        SKIP                = 0x200,
    };
    uint32_t        flags;
};
typedef std::vector<IntersectionLine> IntersectionLines;
typedef std::vector<IntersectionLine*> IntersectionLinePtrs;

class TriangleMeshSlicer
{
public:
    typedef std::function<void()> throw_on_cancel_callback_type;
    TriangleMeshSlicer() : mesh(nullptr) {}
	TriangleMeshSlicer(const TriangleMesh* mesh) { this->init(mesh, [](){}); }
    void init(const TriangleMesh *mesh, throw_on_cancel_callback_type throw_on_cancel);
    void slice(const std::vector<float> &z, std::vector<Polygons>* layers, throw_on_cancel_callback_type throw_on_cancel) const;
    void slice(const std::vector<float> &z, const float closing_radius, std::vector<ExPolygons>* layers, throw_on_cancel_callback_type throw_on_cancel) const;
    enum FacetSliceType {
        NoSlice = 0,
        Slicing = 1,
        Cutting = 2
    };
    FacetSliceType slice_facet(float slice_z, const stl_facet &facet, const int facet_idx,
        const float min_z, const float max_z, IntersectionLine *line_out) const;
    void cut(float z, TriangleMesh* upper, TriangleMesh* lower) const;
    void set_up_direction(const Vec3f& up);

private:
    const TriangleMesh      *mesh;
    // Map from a facet to an edge index.
    std::vector<int>         facets_edges;
    // Scaled copy of this->mesh->stl.v_shared
    std::vector<stl_vertex>  v_scaled_shared;
    // Quaternion that will be used to rotate every facet before the slicing
    Eigen::Quaternion<float, Eigen::DontAlign> m_quaternion;
    // Whether or not the above quaterion should be used
    bool                     m_use_quaternion = false;

    void _slice_do(size_t facet_idx, std::vector<IntersectionLines>* lines, boost::mutex* lines_mutex, const std::vector<float> &z) const;
    void make_loops(std::vector<IntersectionLine> &lines, Polygons* loops) const;
    void make_expolygons(const Polygons &loops, const float closing_radius, ExPolygons* slices) const;
    void make_expolygons_simple(std::vector<IntersectionLine> &lines, ExPolygons* slices) const;
    void make_expolygons(std::vector<IntersectionLine> &lines, const float closing_radius, ExPolygons* slices) const;
};

TriangleMesh make_cube(double x, double y, double z);

// Generate a TriangleMesh of a cylinder
TriangleMesh make_cylinder(double r, double h, double fa=(2*PI/360));

TriangleMesh make_sphere(double rho, double fa=(2*PI/360));

}

// Serialization through the Cereal library
#include <cereal/access.hpp>
namespace cereal {
	template <class Archive> struct specialize<Archive, Slic3r::TriangleMesh, cereal::specialization::non_member_load_save> {};
	template<class Archive> void load(Archive &archive, Slic3r::TriangleMesh &mesh) {
        stl_file &stl = mesh.stl;
        stl.stats.type = inmemory;
		archive(stl.stats.number_of_facets, stl.stats.original_num_facets);
        stl_allocate(&stl);
		archive.loadBinary((char*)stl.facet_start.data(), stl.facet_start.size() * 50);
        stl_get_size(&stl);
        mesh.repair();
	}
	template<class Archive> void save(Archive &archive, const Slic3r::TriangleMesh &mesh) {
		const stl_file& stl = mesh.stl;
		archive(stl.stats.number_of_facets, stl.stats.original_num_facets);
		archive.saveBinary((char*)stl.facet_start.data(), stl.facet_start.size() * 50);
	}
}

#endif
<commit_msg>Add free functions to slice a TriangleMesh<commit_after>#ifndef slic3r_TriangleMesh_hpp_
#define slic3r_TriangleMesh_hpp_

#include "libslic3r.h"
#include <admesh/stl.h>
#include <functional>
#include <vector>
#include <boost/thread.hpp>
#include "BoundingBox.hpp"
#include "Line.hpp"
#include "Point.hpp"
#include "Polygon.hpp"
#include "ExPolygon.hpp"

namespace Slic3r {

class TriangleMesh;
class TriangleMeshSlicer;
typedef std::vector<TriangleMesh*> TriangleMeshPtrs;

class TriangleMesh
{
public:
    TriangleMesh() : repaired(false) {}
    TriangleMesh(const Pointf3s &points, const std::vector<Vec3crd> &facets);
	void clear() { this->stl.clear(); this->its.clear(); this->repaired = false; }
    bool ReadSTLFile(const char* input_file) { return stl_open(&stl, input_file); }
    bool write_ascii(const char* output_file) { return stl_write_ascii(&this->stl, output_file, ""); }
    bool write_binary(const char* output_file) { return stl_write_binary(&this->stl, output_file, ""); }
    void repair(bool update_shared_vertices = true);
    float volume();
    void check_topology();
    bool is_manifold() const { return this->stl.stats.connected_facets_3_edge == (int)this->stl.stats.number_of_facets; }
    void WriteOBJFile(const char* output_file) const;
    void scale(float factor);
    void scale(const Vec3d &versor);
    void translate(float x, float y, float z);
    void translate(const Vec3f &displacement);
    void rotate(float angle, const Axis &axis);
    void rotate(float angle, const Vec3d& axis);
    void rotate_x(float angle) { this->rotate(angle, X); }
    void rotate_y(float angle) { this->rotate(angle, Y); }
    void rotate_z(float angle) { this->rotate(angle, Z); }
    void mirror(const Axis &axis);
    void mirror_x() { this->mirror(X); }
    void mirror_y() { this->mirror(Y); }
    void mirror_z() { this->mirror(Z); }
    void transform(const Transform3d& t, bool fix_left_handed = false);
	void transform(const Matrix3d& t, bool fix_left_handed = false);
    void align_to_origin();
    void rotate(double angle, Point* center);
    TriangleMeshPtrs split() const;
    void merge(const TriangleMesh &mesh);
    ExPolygons horizontal_projection() const;
    const float* first_vertex() const { return this->stl.facet_start.empty() ? nullptr : &this->stl.facet_start.front().vertex[0](0); }
    // 2D convex hull of a 3D mesh projected into the Z=0 plane.
    Polygon convex_hull();
    BoundingBoxf3 bounding_box() const;
    // Returns the bbox of this TriangleMesh transformed by the given transformation
    BoundingBoxf3 transformed_bounding_box(const Transform3d &trafo) const;
    // Return the size of the mesh in coordinates.
    Vec3d size() const { return stl.stats.size.cast<double>(); }
    /// Return the center of the related bounding box.
	Vec3d center() const { return this->bounding_box().center(); }
    // Returns the convex hull of this TriangleMesh
    TriangleMesh convex_hull_3d() const;
    // Slice this mesh at the provided Z levels and return the vector
    std::vector<ExPolygons> slice(const std::vector<double>& z);
    void reset_repair_stats();
    bool needed_repair() const;
    void require_shared_vertices();
    bool   has_shared_vertices() const { return ! this->its.vertices.empty(); }
    size_t facets_count() const { return this->stl.stats.number_of_facets; }
    bool   empty() const { return this->facets_count() == 0; }
    bool is_splittable() const;
    // Estimate of the memory occupied by this structure, important for keeping an eye on the Undo / Redo stack allocation.
    size_t memsize() const;
    // Release optional data from the mesh if the object is on the Undo / Redo stack only. Returns the amount of memory released.
    size_t release_optional();
	// Restore optional data possibly released by release_optional().
	void restore_optional();

    stl_file stl;
    indexed_triangle_set its;
    bool repaired;

private:
    std::deque<uint32_t> find_unvisited_neighbors(std::vector<unsigned char> &facet_visited) const;
};

enum FacetEdgeType {
    // A general case, the cutting plane intersect a face at two different edges.
    feGeneral,
    // Two vertices are aligned with the cutting plane, the third vertex is below the cutting plane.
    feTop,
    // Two vertices are aligned with the cutting plane, the third vertex is above the cutting plane.
    feBottom,
    // All three vertices of a face are aligned with the cutting plane.
    feHorizontal
};

class IntersectionReference
{
public:
    IntersectionReference() : point_id(-1), edge_id(-1) {};
    IntersectionReference(int point_id, int edge_id) : point_id(point_id), edge_id(edge_id) {}
    // Where is this intersection point located? On mesh vertex or mesh edge?
    // Only one of the following will be set, the other will remain set to -1.
    // Index of the mesh vertex.
    int point_id;
    // Index of the mesh edge.
    int edge_id;
};

class IntersectionPoint : public Point, public IntersectionReference
{
public:
    IntersectionPoint() {};
    IntersectionPoint(int point_id, int edge_id, const Point &pt) : IntersectionReference(point_id, edge_id), Point(pt) {}
    IntersectionPoint(const IntersectionReference &ir, const Point &pt) : IntersectionReference(ir), Point(pt) {}
    // Inherits coord_t x, y
};

class IntersectionLine : public Line
{
public:
    IntersectionLine() : a_id(-1), b_id(-1), edge_a_id(-1), edge_b_id(-1), edge_type(feGeneral), flags(0) {}

    bool skip() const { return (this->flags & SKIP) != 0; }
    void set_skip() { this->flags |= SKIP; }

    bool is_seed_candidate() const { return (this->flags & NO_SEED) == 0 && ! this->skip(); }
    void set_no_seed(bool set) { if (set) this->flags |= NO_SEED; else this->flags &= ~NO_SEED; }

    // Inherits Point a, b
    // For each line end point, either {a,b}_id or {a,b}edge_a_id is set, the other is left to -1.
    // Vertex indices of the line end points.
    int             a_id;
    int             b_id;
    // Source mesh edges of the line end points.
    int             edge_a_id;
    int             edge_b_id;
    // feGeneral, feTop, feBottom, feHorizontal
    FacetEdgeType   edge_type;
    // Used by TriangleMeshSlicer::slice() to skip duplicate edges.
    enum {
        // Triangle edge added, because it has no neighbor.
        EDGE0_NO_NEIGHBOR   = 0x001,
        EDGE1_NO_NEIGHBOR   = 0x002,
        EDGE2_NO_NEIGHBOR   = 0x004,
        // Triangle edge added, because it makes a fold with another horizontal edge.
        EDGE0_FOLD          = 0x010,
        EDGE1_FOLD          = 0x020,
        EDGE2_FOLD          = 0x040,
        // The edge cannot be a seed of a greedy loop extraction (folds are not safe to become seeds).
        NO_SEED             = 0x100,
        SKIP                = 0x200,
    };
    uint32_t        flags;
};
typedef std::vector<IntersectionLine> IntersectionLines;
typedef std::vector<IntersectionLine*> IntersectionLinePtrs;

class TriangleMeshSlicer
{
public:
    typedef std::function<void()> throw_on_cancel_callback_type;
    TriangleMeshSlicer() : mesh(nullptr) {}
	TriangleMeshSlicer(const TriangleMesh* mesh) { this->init(mesh, [](){}); }
    void init(const TriangleMesh *mesh, throw_on_cancel_callback_type throw_on_cancel);
    void slice(const std::vector<float> &z, std::vector<Polygons>* layers, throw_on_cancel_callback_type throw_on_cancel) const;
    void slice(const std::vector<float> &z, const float closing_radius, std::vector<ExPolygons>* layers, throw_on_cancel_callback_type throw_on_cancel) const;
    enum FacetSliceType {
        NoSlice = 0,
        Slicing = 1,
        Cutting = 2
    };
    FacetSliceType slice_facet(float slice_z, const stl_facet &facet, const int facet_idx,
        const float min_z, const float max_z, IntersectionLine *line_out) const;
    void cut(float z, TriangleMesh* upper, TriangleMesh* lower) const;
    void set_up_direction(const Vec3f& up);

private:
    const TriangleMesh      *mesh;
    // Map from a facet to an edge index.
    std::vector<int>         facets_edges;
    // Scaled copy of this->mesh->stl.v_shared
    std::vector<stl_vertex>  v_scaled_shared;
    // Quaternion that will be used to rotate every facet before the slicing
    Eigen::Quaternion<float, Eigen::DontAlign> m_quaternion;
    // Whether or not the above quaterion should be used
    bool                     m_use_quaternion = false;

    void _slice_do(size_t facet_idx, std::vector<IntersectionLines>* lines, boost::mutex* lines_mutex, const std::vector<float> &z) const;
    void make_loops(std::vector<IntersectionLine> &lines, Polygons* loops) const;
    void make_expolygons(const Polygons &loops, const float closing_radius, ExPolygons* slices) const;
    void make_expolygons_simple(std::vector<IntersectionLine> &lines, ExPolygons* slices) const;
    void make_expolygons(std::vector<IntersectionLine> &lines, const float closing_radius, ExPolygons* slices) const;
};

inline void slice_mesh(
    const TriangleMesh &                              mesh,
    const std::vector<float> &                        z,
    std::vector<Polygons> &                           layers,
    TriangleMeshSlicer::throw_on_cancel_callback_type thr = nullptr)
{
    if (mesh.empty()) return;
    TriangleMeshSlicer slicer(&mesh);
    slicer.slice(z, &layers, thr);
}

inline void slice_mesh(
    const TriangleMesh &                              mesh,
    const std::vector<float> &                        z,
    std::vector<ExPolygons> &                         layers,
    float                                             closing_radius,
    TriangleMeshSlicer::throw_on_cancel_callback_type thr = nullptr)
{
    if (mesh.empty()) return;
    TriangleMeshSlicer slicer(&mesh);
    slicer.slice(z, closing_radius, &layers, thr);
}

TriangleMesh make_cube(double x, double y, double z);

// Generate a TriangleMesh of a cylinder
TriangleMesh make_cylinder(double r, double h, double fa=(2*PI/360));

TriangleMesh make_sphere(double rho, double fa=(2*PI/360));

}

// Serialization through the Cereal library
#include <cereal/access.hpp>
namespace cereal {
	template <class Archive> struct specialize<Archive, Slic3r::TriangleMesh, cereal::specialization::non_member_load_save> {};
	template<class Archive> void load(Archive &archive, Slic3r::TriangleMesh &mesh) {
        stl_file &stl = mesh.stl;
        stl.stats.type = inmemory;
		archive(stl.stats.number_of_facets, stl.stats.original_num_facets);
        stl_allocate(&stl);
		archive.loadBinary((char*)stl.facet_start.data(), stl.facet_start.size() * 50);
        stl_get_size(&stl);
        mesh.repair();
	}
	template<class Archive> void save(Archive &archive, const Slic3r::TriangleMesh &mesh) {
		const stl_file& stl = mesh.stl;
		archive(stl.stats.number_of_facets, stl.stats.original_num_facets);
		archive.saveBinary((char*)stl.facet_start.data(), stl.facet_start.size() * 50);
	}
}

#endif
<|endoftext|>


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

#include "projwrapper_p.h"
#include <proj_api.h>
#include <QSharedData>
#include <QString>
#include <QPolygonF>
#include <QPointF>

QTM_BEGIN_NAMESPACE

class ProjCoordinateSystemPrivate : public QSharedData
{
public:
    ProjCoordinateSystemPrivate(const QString &projection, bool latLon);
    ProjCoordinateSystemPrivate(const ProjCoordinateSystemPrivate &other);
    ~ProjCoordinateSystemPrivate();

    projPJ projection;
    bool latLon;
};

ProjCoordinateSystemPrivate::ProjCoordinateSystemPrivate(const QString &projStr, bool isLatLon)
{
    projection = pj_init_plus(projStr.toLatin1().constData());
    Q_ASSERT_X(projection, "pj_init_plus", "invalid projection string");
    latLon = isLatLon;
}

ProjCoordinateSystemPrivate::ProjCoordinateSystemPrivate(const ProjCoordinateSystemPrivate &other) :
    QSharedData(other), projection(other.projection)
{}

ProjCoordinateSystemPrivate::~ProjCoordinateSystemPrivate()
{}

ProjCoordinateSystem::ProjCoordinateSystem(const QString &projection, bool latLon) :
    d(new ProjCoordinateSystemPrivate(projection, latLon))
{}

ProjCoordinateSystem::ProjCoordinateSystem(const ProjCoordinateSystem &other) :
    d(other.d)
{}

ProjCoordinateSystem::~ProjCoordinateSystem()
{}

bool ProjCoordinateSystem::isLatLon() const
{
    return d->latLon;
}

class ProjCoordinatePrivate
{
public:
    ProjCoordinateSystem currentSystem;
    double x;
    double y;
    double z;
};

ProjCoordinate::ProjCoordinate(double x, double y, double z, const ProjCoordinateSystem &system) :
    d(new ProjCoordinatePrivate)
{
    d->x = x;
    d->y = y;
    d->z = z;
    d->currentSystem = system;
}

ProjCoordinate::ProjCoordinate(const ProjCoordinate &other) :
    d(new ProjCoordinatePrivate)
{
    d->x = other.d->x;
    d->y = other.d->y;
    d->z = other.d->z;
    d->currentSystem = other.d->currentSystem;
}

ProjCoordinate::~ProjCoordinate()
{}

double ProjCoordinate::x() const
{
    return d->x;
}

double ProjCoordinate::y() const
{
    return d->y;
}

double ProjCoordinate::z() const
{
    return d->z;
}

bool ProjCoordinate::convert(const ProjCoordinateSystem &system)
{
    int result;
    double x = d->x, y = d->y, z = d->z;

    if (d->currentSystem.isLatLon()) {
        x *= DEG_TO_RAD;
        y *= DEG_TO_RAD;
    }

    result = pj_transform(d->currentSystem.d->projection,
                          system.d->projection,
                          1, 1, &x, &y, &z);
    if (result) {
        return false;
    } else {
        if (system.isLatLon()) {
            x *= RAD_TO_DEG;
            y *= RAD_TO_DEG;
        }
        d->x = x;
        d->y = y;
        d->z = z;
        d->currentSystem = system;
        return true;
    }
}

class ProjPolygonPrivate
{
public:
    ProjCoordinateSystem currentSystem;
};

ProjPolygon::ProjPolygon(const ProjCoordinateSystem &system) :
    QList<ProjCoordinate>(),
    d(new ProjPolygonPrivate)
{
    d->currentSystem = system;
}

ProjPolygon::ProjPolygon(const QPolygonF &poly, const ProjCoordinateSystem &system, double scale) :
    QList<ProjCoordinate>(),
    d(new ProjPolygonPrivate)
{
    d->currentSystem = system;
    foreach (QPointF point, poly) {
        double x = point.x();
        x /= scale;
        double y = point.y();
        y /= scale;
        append(ProjCoordinate(x, y, 0.0, system));
    }
}

bool ProjPolygon::convert(const ProjCoordinateSystem &system)
{
    for (int i=0; i<size(); ++i) {
        ProjCoordinate coord = at(i);
        if (!coord.convert(system))
            return false;
        replace(i, coord);
    }

    d->currentSystem = system;
    return true;
}

QPolygonF ProjPolygon::toPolygonF(double scale) const
{
    QPolygonF poly;
    for (int i=0; i<size(); ++i) {
        const ProjCoordinate &coord = at(i);
        double x = coord.x() * scale;
        double y = coord.y() * scale;
        poly << QPointF(x, y);
    }
    return poly;
}

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

#include "projwrapper_p.h"
#include <proj_api.h>
#include <QSharedData>
#include <QString>
#include <QPolygonF>
#include <QPointF>

QTM_BEGIN_NAMESPACE

class ProjCoordinateSystemPrivate : public QSharedData
{
public:
    ProjCoordinateSystemPrivate(const QString &projection, bool latLon);
    ProjCoordinateSystemPrivate(const ProjCoordinateSystemPrivate &other);
    ~ProjCoordinateSystemPrivate();

    projPJ projection;
    bool latLon;
};

ProjCoordinateSystemPrivate::ProjCoordinateSystemPrivate(const QString &projStr, bool isLatLon)
{
    projection = pj_init_plus(projStr.toLatin1().constData());
    Q_ASSERT_X(projection, "pj_init_plus", "invalid projection string");
    latLon = isLatLon;
}

ProjCoordinateSystemPrivate::ProjCoordinateSystemPrivate(const ProjCoordinateSystemPrivate &other) :
    QSharedData(other), projection(other.projection)
{}

ProjCoordinateSystemPrivate::~ProjCoordinateSystemPrivate()
{}

ProjCoordinateSystem::ProjCoordinateSystem(const QString &projection, bool latLon) :
    d(new ProjCoordinateSystemPrivate(projection, latLon))
{}

ProjCoordinateSystem::ProjCoordinateSystem(const ProjCoordinateSystem &other) :
    d(other.d)
{}

ProjCoordinateSystem::~ProjCoordinateSystem()
{}

bool ProjCoordinateSystem::isLatLon() const
{
    return d->latLon;
}

class ProjCoordinatePrivate
{
public:
    ProjCoordinateSystem currentSystem;
    double x;
    double y;
    double z;
};

ProjCoordinate::ProjCoordinate(double x, double y, double z, const ProjCoordinateSystem &system) :
    d(new ProjCoordinatePrivate)
{
    d->x = x;
    d->y = y;
    d->z = z;
    d->currentSystem = system;
}

ProjCoordinate::ProjCoordinate(const ProjCoordinate &other) :
    d(new ProjCoordinatePrivate)
{
    d->x = other.d->x;
    d->y = other.d->y;
    d->z = other.d->z;
    d->currentSystem = other.d->currentSystem;
}

ProjCoordinate::~ProjCoordinate()
{}

double ProjCoordinate::x() const
{
    return d->x;
}

double ProjCoordinate::y() const
{
    return d->y;
}

double ProjCoordinate::z() const
{
    return d->z;
}

bool ProjCoordinate::convert(const ProjCoordinateSystem &system)
{
    int result;
    double x = d->x, y = d->y, z = d->z;

    if (d->currentSystem.isLatLon()) {
        x *= DEG_TO_RAD;
        y *= DEG_TO_RAD;
    }

    result = pj_transform(d->currentSystem.d->projection,
                          system.d->projection,
                          1, 1, &x, &y, &z);
    if (result) {
        return false;
    } else {
        if (system.isLatLon()) {
            x *= RAD_TO_DEG;
            y *= RAD_TO_DEG;
        }
        d->x = x;
        d->y = y;
        d->z = z;
        d->currentSystem = system;
        return true;
    }
}

class ProjPolygonPrivate
{
public:
    ProjCoordinateSystem currentSystem;
};

ProjPolygon::ProjPolygon(const ProjCoordinateSystem &system) :
    QList<ProjCoordinate>(),
    d(new ProjPolygonPrivate)
{
    d->currentSystem = system;
}

ProjPolygon::ProjPolygon(const QPolygonF &poly, const ProjCoordinateSystem &system, double scale) :
    QList<ProjCoordinate>(),
    d(new ProjPolygonPrivate)
{
    d->currentSystem = system;
    foreach (QPointF point, poly) {
        double x = point.x();
        x /= scale;
        double y = point.y();
        y /= scale;
        append(ProjCoordinate(x, y, 0.0, system));
    }
}

ProjPolygon::~ProjPolygon()
{}

bool ProjPolygon::convert(const ProjCoordinateSystem &system)
{
    for (int i=0; i<size(); ++i) {
        ProjCoordinate coord = at(i);
        if (!coord.convert(system))
            return false;
        replace(i, coord);
    }

    d->currentSystem = system;
    return true;
}

QPolygonF ProjPolygon::toPolygonF(double scale) const
{
    QPolygonF poly;
    for (int i=0; i<size(); ++i) {
        const ProjCoordinate &coord = at(i);
        double x = coord.x() * scale;
        double y = coord.y() * scale;
        poly << QPointF(x, y);
    }
    return poly;
}

QTM_END_NAMESPACE
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2002-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders 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.
 *
 * Authors: Nathan Binkert
 *          Steve Reinhardt
 */

#include <cstring>
#include <fstream>
#include <list>
#include <string>
#include <vector>

#include "base/misc.hh"
#include "params/Root.hh"
#include "sim/sim_object.hh"

// Dummy Object
struct Root : public SimObject
{
    Root(RootParams *params) : SimObject(params) {}
};

Root *
RootParams::create()
{
    static bool created = false;
    if (created)
        panic("only one root object allowed!");

    created = true;

    return new Root(this);
}
<commit_msg>Root: Get rid of unnecessary includes in root.cc.<commit_after>/*
 * Copyright (c) 2002-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders 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.
 *
 * Authors: Nathan Binkert
 *          Steve Reinhardt
 */

#include "base/misc.hh"
#include "params/Root.hh"
#include "sim/sim_object.hh"

// Dummy Object
struct Root : public SimObject
{
    Root(RootParams *params) : SimObject(params) {}
};

Root *
RootParams::create()
{
    static bool created = false;
    if (created)
        panic("only one root object allowed!");

    created = true;

    return new Root(this);
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore/qvariant.h>
#include <QtCore/qdebug.h>

#if defined(HAVE_WIDGETS)
#include <QtWidgets/qwidget.h>
#endif

#include "qgstreamerplayerservice.h"
#include "qgstreamerplayercontrol.h"
#include "qgstreamerplayersession.h"
#include "qgstreamermetadataprovider.h"
#include "qgstreameravailabilitycontrol.h"

#if defined(HAVE_WIDGETS)
#include <private/qgstreamervideooverlay_p.h>
#include <private/qgstreamervideowindow_p.h>
#include <private/qgstreamervideowidget_p.h>
#endif

#include <private/qgstreamervideorenderer_p.h>

#if defined(Q_WS_MAEMO_6) && defined(__arm__)
#include "private/qgstreamergltexturerenderer.h"
#endif

#if defined(HAVE_MIR) && defined (__arm__)
#include "private/qgstreamermirtexturerenderer_p.h"
#endif

#include "qgstreamerstreamscontrol.h"
#include <private/qgstreameraudioprobecontrol_p.h>
#include <private/qgstreamervideoprobecontrol_p.h>

#include <private/qmediaplaylistnavigator_p.h>
#include <qmediaplaylist.h>
#include <private/qmediaresourceset_p.h>

QT_BEGIN_NAMESPACE

QGstreamerPlayerService::QGstreamerPlayerService(QObject *parent):
     QMediaService(parent)
     , m_videoOutput(0)
     , m_videoRenderer(0)
#if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS)
     , m_videoWindow(0)
     , m_videoWidget(0)
#endif
     , m_videoReferenceCount(0)
{
    m_session = new QGstreamerPlayerSession(this);
    m_control = new QGstreamerPlayerControl(m_session, this);
    m_metaData = new QGstreamerMetaDataProvider(m_session, this);
    m_streamsControl = new QGstreamerStreamsControl(m_session,this);
    m_availabilityControl = new QGStreamerAvailabilityControl(m_control->resources(), this);

#if defined(Q_WS_MAEMO_6) && defined(__arm__)
    m_videoRenderer = new QGstreamerGLTextureRenderer(this);
// TODO: Implement HAVE_UBUNTU_TOUCH configure check and remove QGstreamerMirTextureRenderer from the else case
#elif defined(HAVE_MIR) && defined (__arm__)
    m_videoRenderer = new QGstreamerMirTextureRenderer(this, m_session);
#else
    //m_videoRenderer = new QGstreamerMirTextureRenderer(this, m_session);
    m_videoRenderer = new QGstreamerVideoRenderer(this);
#endif

#if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS)
#ifdef Q_WS_MAEMO_6
    m_videoWindow = new QGstreamerVideoWindow(this, "omapxvsink");
// TODO: Implement Q_WS_UBUNTU_TOUCH configure check and remove mirsink from the else case
//#elif defined(HAVE_MIR)
//    m_videoWindow = new QGstreamerVideoWindow(this, "mirsink");
#else
    qDebug() << "Creating new QGstreamerVideoWindow, passing 'this'" << endl;
    //m_videoWindow = new QGstreamerVideoWindow(this, "mirsink");
    m_videoWindow = new QGstreamerVideoOverlay(this);
#endif
    m_videoWidget = new QGstreamerVideoWidgetControl(this);
#endif
}

QGstreamerPlayerService::~QGstreamerPlayerService()
{
}

QMediaControl *QGstreamerPlayerService::requestControl(const char *name)
{
    if (qstrcmp(name,QMediaPlayerControl_iid) == 0)
        return m_control;

    if (qstrcmp(name,QMetaDataReaderControl_iid) == 0)
        return m_metaData;

    if (qstrcmp(name,QMediaStreamsControl_iid) == 0)
        return m_streamsControl;

    if (qstrcmp(name, QMediaAvailabilityControl_iid) == 0)
        return m_availabilityControl;

    if (qstrcmp(name,QMediaVideoProbeControl_iid) == 0) {
        if (m_session) {
            QGstreamerVideoProbeControl *probe = new QGstreamerVideoProbeControl(this);
            increaseVideoRef();
            m_session->addProbe(probe);
            return probe;
        }
        return 0;
    }

    if (qstrcmp(name,QMediaAudioProbeControl_iid) == 0) {
        if (m_session) {
            QGstreamerAudioProbeControl *probe = new QGstreamerAudioProbeControl(this);
            m_session->addProbe(probe);
            return probe;
        }
        return 0;
    }

    if (!m_videoOutput) {
        if (qstrcmp(name, QVideoRendererControl_iid) == 0)
            m_videoOutput = m_videoRenderer;
#if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS)
        else if (qstrcmp(name, QVideoWidgetControl_iid) == 0)
            m_videoOutput = m_videoWidget;
        else  if (qstrcmp(name, QVideoWindowControl_iid) == 0)
            m_videoOutput = m_videoWindow;
#endif

        if (m_videoOutput) {
            increaseVideoRef();
            m_control->setVideoOutput(m_videoOutput);
            return m_videoOutput;
        }
    }

    return 0;
}

void QGstreamerPlayerService::releaseControl(QMediaControl *control)
{
    if (control == m_videoOutput) {
        m_videoOutput = 0;
        m_control->setVideoOutput(0);
        decreaseVideoRef();
    }

    QGstreamerVideoProbeControl* videoProbe = qobject_cast<QGstreamerVideoProbeControl*>(control);
    if (videoProbe) {
        if (m_session) {
            m_session->removeProbe(videoProbe);
            decreaseVideoRef();
        }
        delete videoProbe;
        return;
    }

    QGstreamerAudioProbeControl* audioProbe = qobject_cast<QGstreamerAudioProbeControl*>(control);
    if (audioProbe) {
        if (m_session)
            m_session->removeProbe(audioProbe);
        delete audioProbe;
        return;
    }
}

void QGstreamerPlayerService::increaseVideoRef()
{
    m_videoReferenceCount++;
    if (m_videoReferenceCount == 1) {
        m_control->resources()->setVideoEnabled(true);
    }
}

void QGstreamerPlayerService::decreaseVideoRef()
{
    m_videoReferenceCount--;
    if (m_videoReferenceCount == 0) {
        m_control->resources()->setVideoEnabled(false);
    }
}

QT_END_NAMESPACE
<commit_msg>Clean up the renderer choosing code after adding support for creating a QGstreamerMirTextureRenderer instance.<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore/qvariant.h>
#include <QtCore/qdebug.h>

#if defined(HAVE_WIDGETS)
#include <QtWidgets/qwidget.h>
#endif

#include "qgstreamerplayerservice.h"
#include "qgstreamerplayercontrol.h"
#include "qgstreamerplayersession.h"
#include "qgstreamermetadataprovider.h"
#include "qgstreameravailabilitycontrol.h"

#if defined(HAVE_WIDGETS)
#include <private/qgstreamervideooverlay_p.h>
#include <private/qgstreamervideowindow_p.h>
#include <private/qgstreamervideowidget_p.h>
#endif

#include <private/qgstreamervideorenderer_p.h>

#if defined(Q_WS_MAEMO_6) && defined(__arm__)
#include "private/qgstreamergltexturerenderer.h"
#endif

#if defined(HAVE_MIR) && defined (__arm__)
#include "private/qgstreamermirtexturerenderer_p.h"
#endif

#include "qgstreamerstreamscontrol.h"
#include <private/qgstreameraudioprobecontrol_p.h>
#include <private/qgstreamervideoprobecontrol_p.h>

#include <private/qmediaplaylistnavigator_p.h>
#include <qmediaplaylist.h>
#include <private/qmediaresourceset_p.h>

QT_BEGIN_NAMESPACE

QGstreamerPlayerService::QGstreamerPlayerService(QObject *parent):
     QMediaService(parent)
     , m_videoOutput(0)
     , m_videoRenderer(0)
#if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS)
     , m_videoWindow(0)
     , m_videoWidget(0)
#endif
     , m_videoReferenceCount(0)
{
    m_session = new QGstreamerPlayerSession(this);
    m_control = new QGstreamerPlayerControl(m_session, this);
    m_metaData = new QGstreamerMetaDataProvider(m_session, this);
    m_streamsControl = new QGstreamerStreamsControl(m_session,this);
    m_availabilityControl = new QGStreamerAvailabilityControl(m_control->resources(), this);

#if defined(Q_WS_MAEMO_6) && defined(__arm__)
    m_videoRenderer = new QGstreamerGLTextureRenderer(this);
#elif defined(HAVE_MIR) && defined (__arm__)
    m_videoRenderer = new QGstreamerMirTextureRenderer(this, m_session);
#else
    m_videoRenderer = new QGstreamerVideoRenderer(this);
#endif

#if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS)
#ifdef Q_WS_MAEMO_6
    m_videoWindow = new QGstreamerVideoWindow(this, "omapxvsink");
#else
    m_videoWindow = new QGstreamerVideoOverlay(this);
#endif
    m_videoWidget = new QGstreamerVideoWidgetControl(this);
#endif
}

QGstreamerPlayerService::~QGstreamerPlayerService()
{
}

QMediaControl *QGstreamerPlayerService::requestControl(const char *name)
{
    if (qstrcmp(name,QMediaPlayerControl_iid) == 0)
        return m_control;

    if (qstrcmp(name,QMetaDataReaderControl_iid) == 0)
        return m_metaData;

    if (qstrcmp(name,QMediaStreamsControl_iid) == 0)
        return m_streamsControl;

    if (qstrcmp(name, QMediaAvailabilityControl_iid) == 0)
        return m_availabilityControl;

    if (qstrcmp(name,QMediaVideoProbeControl_iid) == 0) {
        if (m_session) {
            QGstreamerVideoProbeControl *probe = new QGstreamerVideoProbeControl(this);
            increaseVideoRef();
            m_session->addProbe(probe);
            return probe;
        }
        return 0;
    }

    if (qstrcmp(name,QMediaAudioProbeControl_iid) == 0) {
        if (m_session) {
            QGstreamerAudioProbeControl *probe = new QGstreamerAudioProbeControl(this);
            m_session->addProbe(probe);
            return probe;
        }
        return 0;
    }

    if (!m_videoOutput) {
        if (qstrcmp(name, QVideoRendererControl_iid) == 0)
            m_videoOutput = m_videoRenderer;
#if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS)
        else if (qstrcmp(name, QVideoWidgetControl_iid) == 0)
            m_videoOutput = m_videoWidget;
        else  if (qstrcmp(name, QVideoWindowControl_iid) == 0)
            m_videoOutput = m_videoWindow;
#endif

        if (m_videoOutput) {
            increaseVideoRef();
            m_control->setVideoOutput(m_videoOutput);
            return m_videoOutput;
        }
    }

    return 0;
}

void QGstreamerPlayerService::releaseControl(QMediaControl *control)
{
    if (control == m_videoOutput) {
        m_videoOutput = 0;
        m_control->setVideoOutput(0);
        decreaseVideoRef();
    }

    QGstreamerVideoProbeControl* videoProbe = qobject_cast<QGstreamerVideoProbeControl*>(control);
    if (videoProbe) {
        if (m_session) {
            m_session->removeProbe(videoProbe);
            decreaseVideoRef();
        }
        delete videoProbe;
        return;
    }

    QGstreamerAudioProbeControl* audioProbe = qobject_cast<QGstreamerAudioProbeControl*>(control);
    if (audioProbe) {
        if (m_session)
            m_session->removeProbe(audioProbe);
        delete audioProbe;
        return;
    }
}

void QGstreamerPlayerService::increaseVideoRef()
{
    m_videoReferenceCount++;
    if (m_videoReferenceCount == 1) {
        m_control->resources()->setVideoEnabled(true);
    }
}

void QGstreamerPlayerService::decreaseVideoRef()
{
    m_videoReferenceCount--;
    if (m_videoReferenceCount == 0) {
        m_control->resources()->setVideoEnabled(false);
    }
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>#include <alvar_logger/alvar_logger_node.h>
#include <sensor_msgs/image_encodings.h>
#include <cv_bridge/cv_bridge.h>

AlvarLoggerNode::AlvarLoggerNode(ros::NodeHandle &nh) : nh_(nh), it_(nh), frame_number_(0)
{
    std::string camera_info_topic;
    if (!nh_.getParam("camera_info_topic", camera_info_topic))
    {
        ROS_ERROR("Camera info topic needs to be specified");
        exit(0);
    }

    cam_ = new alvar::Camera(nh_, camera_info_topic);

    std::string log_file_name;
    if (!nh_.getParam("log_file", log_file_name))
    {
        ROS_ERROR("Log file needs to be specified");
        exit(0);
    }

    if (!nh_.hasParam("video_file"))
    {
        ROS_ERROR("Video file needs to be specified");
        exit(0);
    }

    file_out_.open(log_file_name.c_str());

    image_publisher_ = it_.advertise("detected_markers", 1);
    image_subscriber_ = it_.subscribe("input_image", 0, &AlvarLoggerNode::imageCallback, this);
}

AlvarLoggerNode::~AlvarLoggerNode()
{
    file_out_.close();
    delete cam_;
}

void AlvarLoggerNode::imageCallback(const sensor_msgs::ImageConstPtr &image)
{
    if (cam_->getCamInfo_)
    {
        if (!video_writer_.isOpened())
        {
            cv::Size image_size(image->width, image->height);
            double frame_rate = 30.0;
            std::string video_file_name;
            nh_.getParam("video_file", video_file_name);
            video_writer_.open(video_file_name, CV_FOURCC('D','I','V','X'), frame_rate, image_size, true);
        }
        cv_bridge::CvImagePtr cv_image = cv_bridge::toCvCopy(image, sensor_msgs::image_encodings::BGR8);
        IplImage ipl_image = cv_image->image;
        marker_detector_.Detect(&ipl_image, cam_);

        video_writer_.write(cv_image->image);

        cv::Mat debug_image;
        cv_image->image.copyTo(debug_image);

        for (size_t i = 0; i < marker_detector_.markers->size(); i++)
        {
            int id = (*(marker_detector_.markers))[i].GetId();
            std::vector<alvar::PointDouble> marker_corners = (*(marker_detector_.markers))[i].marker_corners_img;
            for (int i = 0; i < marker_corners.size() - 1; i++)
            {
                cv::Point start_point(marker_corners.at(i).x, marker_corners.at(i).y);
                cv::Point end_point(marker_corners.at(i + 1).x, marker_corners.at(i + 1).y);
                cv::line(debug_image, start_point, end_point, CV_RGB(255, 0, 0), 3, CV_AA, 0);
                if (i == 0)
                {
                    file_out_ << id << ", " << frame_number_ << ", " << start_point.x << ", " << start_point.y;
                }
                else
                {
                    file_out_ << ", " << start_point.x << ", " << start_point.y;
                }
            }
            cv::Point start_point(marker_corners.at(marker_corners.size() - 1).x, marker_corners.at(marker_corners.size() - 1).y);
            cv::Point end_point(marker_corners.at(0).x, marker_corners.at(0).y);
            cv::line(debug_image, start_point, end_point, CV_RGB(255, 0, 0), 3, CV_AA, 0);
            file_out_ << ", " << start_point.x << ", " << start_point.y << std::endl;
        }
        cv_bridge::CvImage debug_image_msg;
        debug_image_msg.encoding = sensor_msgs::image_encodings::BGR8;
        debug_image_msg.image = debug_image;
        image_publisher_.publish(debug_image_msg.toImageMsg());
    }

    frame_number_++;
}

int main(int argc, char **argv)
{
    ros::init(argc, argv, "alvar_logger");

    ros::NodeHandle n("~");

    ROS_INFO("[alvar_logger] node started");

    AlvarLoggerNode alvar_logger_node(n);

    ros::spin();

    return 0;
}
<commit_msg>log frame id first then  marker id<commit_after>#include <alvar_logger/alvar_logger_node.h>
#include <sensor_msgs/image_encodings.h>
#include <cv_bridge/cv_bridge.h>

AlvarLoggerNode::AlvarLoggerNode(ros::NodeHandle &nh) : nh_(nh), it_(nh), frame_number_(0)
{
    std::string camera_info_topic;
    if (!nh_.getParam("camera_info_topic", camera_info_topic))
    {
        ROS_ERROR("Camera info topic needs to be specified");
        exit(0);
    }

    cam_ = new alvar::Camera(nh_, camera_info_topic);

    std::string log_file_name;
    if (!nh_.getParam("log_file", log_file_name))
    {
        ROS_ERROR("Log file needs to be specified");
        exit(0);
    }

    if (!nh_.hasParam("video_file"))
    {
        ROS_ERROR("Video file needs to be specified");
        exit(0);
    }

    file_out_.open(log_file_name.c_str());

    image_publisher_ = it_.advertise("detected_markers", 1);
    image_subscriber_ = it_.subscribe("input_image", 0, &AlvarLoggerNode::imageCallback, this);
}

AlvarLoggerNode::~AlvarLoggerNode()
{
    file_out_.close();
    delete cam_;
}

void AlvarLoggerNode::imageCallback(const sensor_msgs::ImageConstPtr &image)
{
    if (cam_->getCamInfo_)
    {
        if (!video_writer_.isOpened())
        {
            cv::Size image_size(image->width, image->height);
            double frame_rate = 30.0;
            std::string video_file_name;
            nh_.getParam("video_file", video_file_name);
            video_writer_.open(video_file_name, CV_FOURCC('D','I','V','X'), frame_rate, image_size, true);
        }
        cv_bridge::CvImagePtr cv_image = cv_bridge::toCvCopy(image, sensor_msgs::image_encodings::BGR8);
        IplImage ipl_image = cv_image->image;
        marker_detector_.Detect(&ipl_image, cam_);

        video_writer_.write(cv_image->image);

        cv::Mat debug_image;
        cv_image->image.copyTo(debug_image);

        for (size_t i = 0; i < marker_detector_.markers->size(); i++)
        {
            int id = (*(marker_detector_.markers))[i].GetId();
            std::vector<alvar::PointDouble> marker_corners = (*(marker_detector_.markers))[i].marker_corners_img;
            for (int i = 0; i < marker_corners.size() - 1; i++)
            {
                cv::Point start_point(marker_corners.at(i).x, marker_corners.at(i).y);
                cv::Point end_point(marker_corners.at(i + 1).x, marker_corners.at(i + 1).y);
                cv::line(debug_image, start_point, end_point, CV_RGB(255, 0, 0), 3, CV_AA, 0);
                if (i == 0)
                {
                    file_out_ << frame_number_ << ", " << id << ", " << start_point.x << ", " << start_point.y;
                }
                else
                {
                    file_out_ << ", " << start_point.x << ", " << start_point.y;
                }
            }
            cv::Point start_point(marker_corners.at(marker_corners.size() - 1).x, marker_corners.at(marker_corners.size() - 1).y);
            cv::Point end_point(marker_corners.at(0).x, marker_corners.at(0).y);
            cv::line(debug_image, start_point, end_point, CV_RGB(255, 0, 0), 3, CV_AA, 0);
            file_out_ << ", " << start_point.x << ", " << start_point.y << std::endl;
        }
        cv_bridge::CvImage debug_image_msg;
        debug_image_msg.encoding = sensor_msgs::image_encodings::BGR8;
        debug_image_msg.image = debug_image;
        image_publisher_.publish(debug_image_msg.toImageMsg());
    }

    frame_number_++;
}

int main(int argc, char **argv)
{
    ros::init(argc, argv, "alvar_logger");

    ros::NodeHandle n("~");

    ROS_INFO("[alvar_logger] node started");

    AlvarLoggerNode alvar_logger_node(n);

    ros::spin();

    return 0;
}
<|endoftext|>