<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $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 either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qgraphicstransform.h"
#include "qgraphicsitem_p.h"
#include "qgraphicstransform_p.h"
#include <QDebug>

#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

QT_BEGIN_NAMESPACE

void QGraphicsTransformPrivate::setItem(QGraphicsItem *i)
{
    if (item == i)
        return;

    if (item) {
        Q_Q(QGraphicsTransform);
        QGraphicsItemPrivate *d_ptr = item->d_ptr;

        item->prepareGeometryChange();
        Q_ASSERT(d_ptr->transformData);
        d_ptr->transformData->graphicsTransforms.remove(q);
        d_ptr->dirtySceneTransform = 1;
        item = 0;
    }

    item = i;
}

void QGraphicsTransformPrivate::updateItem(QGraphicsItem *item)
{
    item->prepareGeometryChange();
    item->d_ptr->dirtySceneTransform = 1;
}

void QGraphicsTransform::update()
{
    Q_D(QGraphicsTransform);
    if (d->item)
        d->updateItem(d->item);
}

/*!
  returns this object as a QTransform.
*/
QTransform QGraphicsTransform::transform() const
{
    QTransform t;
    applyTo(&t);
    return t;
}

/*!
  \class QGraphicsTransform
  \brief The QGraphicsTransform class is an abstract base class for tranformations on QGraphicsItems.
  \since 4.6

  The classes that inherit QGraphicsTransform express different types of transformations
  that can be applied to graphics items.

  A list of these transformations can be applied to any graphics item. These
  transformations are then easily modifyable and usable from e.g. within animations.

  QGraphicsTransform is an abstract base class that is implemented by QGraphicsScale,
  QGraphicsRotation and QGraphicsRotation3D. Subclasses have to implement the applyTo method.

  \sa QGraphicsItem::transform(), QGraphicsScale, QGraphicsRotation, QGraphicsRotation3D
*/

/*!
  Constructs a new QGraphicsTransform with \a parent.
*/
QGraphicsTransform::QGraphicsTransform(QObject *parent) :
    QObject(*new QGraphicsTransformPrivate, parent)
{
}

/*!
  Destructs the graphics transform.
*/
QGraphicsTransform::~QGraphicsTransform()
{
    Q_D(QGraphicsTransform);
    d->setItem(0);
}

/*!
  \internal
*/
QGraphicsTransform::QGraphicsTransform(QGraphicsTransformPrivate &p, QObject *parent)
    : QObject(p, parent)
{
}

/*! \fn void QGraphicsTransform::applyTo(QTransform *transform) const

  This pure virtual method has to be reimplemented in derived classes.

  It applies this transformation to \a transform.
*/

/*!
  \class QGraphicsScale
  \brief The QGraphicsScale class provides a way to scale a graphics item in 2 dimensions.
  \since 4.6

  QGraphicsScale contains an \a origin around which the scaling happens, and two
  scale factors, xScale and yScale, the x and one for the y axis.
*/

class QGraphicsScalePrivate : public QGraphicsTransformPrivate
{
public:
    QGraphicsScalePrivate()
            : xScale(1), yScale(1) {}
    QPointF origin;
    qreal xScale;
    qreal yScale;
};

/*!
  Constructs a new graphics scale object with \a parent.
*/
QGraphicsScale::QGraphicsScale(QObject *parent)
    : QGraphicsTransform(*new QGraphicsScalePrivate, parent)
{
}

/*!
  Destroys the object
*/
QGraphicsScale::~QGraphicsScale()
{
}

/*!
  \property QGraphicsScale::origin
  The origin of the scale. All scaling will be done relative to this point.

  The \a origin is in other words the fixed point for the transformation.
*/
QPointF QGraphicsScale::origin() const
{
    Q_D(const QGraphicsScale);
    return d->origin;
}

void QGraphicsScale::setOrigin(const QPointF &point)
{
    Q_D(QGraphicsScale);
    d->origin = point;
    update();
    emit originChanged();
}

/*!
  \fn QGraphicsScale::originChanged()

  This signal is emitted whenever the origin of the object
  changes.
*/

/*!
  \property QGraphicsScale::xScale

  The scale factor in x direction. The x direction is
  in the graphics items logical coordinates.

  \sa yScale
*/
qreal QGraphicsScale::xScale() const
{
    Q_D(const QGraphicsScale);
    return d->xScale;
}

void QGraphicsScale::setXScale(qreal scale)
{
    Q_D(QGraphicsScale);
    if (d->xScale == scale)
        return;
    d->xScale = scale;
    update();
    emit scaleChanged();
}

/*!
  \property QGraphicsScale::yScale

  The scale factor in y direction. The y direction is
  in the graphics items logical coordinates.

  \sa xScale
*/
qreal QGraphicsScale::yScale() const
{
    Q_D(const QGraphicsScale);
    return d->yScale;
}

void QGraphicsScale::setYScale(qreal scale)
{
    Q_D(QGraphicsScale);
    if (d->yScale == scale)
        return;
    d->yScale = scale;
    update();
    emit scaleChanged();
}

/*!
  \fn QGraphicsScale::scaleChanged()

  This signal is emitted whenever the xScale or yScale of the object
  changes.
*/

/*!
  \reimp
*/
void QGraphicsScale::applyTo(QTransform *transform) const
{
    Q_D(const QGraphicsScale);
    transform->translate(d->origin.x(), d->origin.y());
    transform->scale(d->xScale, d->yScale);
    transform->translate(-d->origin.x(), -d->origin.y());
}

/*!
  \class QGraphicsRotation
  \brief The QGraphicsRotation class provides a way to rotate a graphics item in 2 dimensions.
  \since 4.6

  QGraphicsRotation contains an \a origin around which the rotation happens, and one
  angle in degrees describing the amount of the rotation.
*/

class QGraphicsRotationPrivate : public QGraphicsTransformPrivate
{
public:
    QGraphicsRotationPrivate()
            : angle(0) {}
    QPointF origin;
    qreal originY;
    qreal angle;
};

/*!
  Constructs a new graphics rotation with \a parent.
*/
QGraphicsRotation::QGraphicsRotation(QObject *parent)
    : QGraphicsTransform(*new QGraphicsRotationPrivate, parent)
{
}

/*!
  \internal
*/
QGraphicsRotation::QGraphicsRotation(QGraphicsRotationPrivate &p, QObject *parent)
    : QGraphicsTransform(p, parent)
{
}

/*!
  Destructs the object
*/
QGraphicsRotation::~QGraphicsRotation()
{
}

/*!
  \property QGraphicsRotation::origin
  The origin around which this object will rotate the graphics item.

  The \a origin is in other words the fixed point for the transformation.
*/
QPointF QGraphicsRotation::origin() const
{
    Q_D(const QGraphicsRotation);
    return d->origin;
}

void QGraphicsRotation::setOrigin(const QPointF &point)
{
    Q_D(QGraphicsRotation);
    d->origin = point;
    update();
    emit originChanged();
}

/*!
  \fn QGraphicsRotation::originChanged()

  This signal is emitted whenever the origin of the object
  changes.
*/

/*!
  \property QGraphicsRotation::angle
  The angle, in degrees, of the rotation.
*/
qreal QGraphicsRotation::angle() const
{
    Q_D(const QGraphicsRotation);
    return d->angle;
}

void QGraphicsRotation::setAngle(qreal angle)
{
    Q_D(QGraphicsRotation);
    if (d->angle == angle)
        return;
    d->angle = angle;
    update();
    emit angleChanged();
}

/*!
  \fn void QGraphicsRotation::angleChanged()

  This signal is emitted whenever the angle of the object
  changes.
*/

/*!
  \reimp
*/
void QGraphicsRotation::applyTo(QTransform *t) const
{
    Q_D(const QGraphicsRotation);
    if(d->angle) {
        t->translate(d->origin.x(), d->origin.y());
        t->rotate(d->angle);
        t->translate(-d->origin.x(), -d->origin.y());
    }
}

/*!
  \class QGraphicsRotation3D
  \brief The QGraphicsRotation3D class provides a way to rotate a graphics item in 3 dimensions.
  \since 4.6

  In addition to the origin and angle of a simple QGraphicsRotation, QGraphicsRotation3D contains
  also an axis that describes around which axis in space the rotation is supposed to happen.
*/

class QGraphicsRotation3DPrivate : public QGraphicsRotationPrivate
{
public:
    QGraphicsRotation3DPrivate() {}

    QVector3D axis;
};

/*!
  Constructs a new 3D rotation with \a parent.
*/
QGraphicsRotation3D::QGraphicsRotation3D(QObject *parent)
    : QGraphicsRotation(*new QGraphicsRotation3DPrivate, parent)
{
}

/*!
  Destroys the object
*/
QGraphicsRotation3D::~QGraphicsRotation3D()
{
}

/*!
    \property QGraphicsRotation3D::axis

    A rotation axis is specified by a vector in 3D space.
*/
QVector3D QGraphicsRotation3D::axis()
{
    Q_D(QGraphicsRotation3D);
    return d->axis;
}

void QGraphicsRotation3D::setAxis(const QVector3D &axis)
{
    Q_D(QGraphicsRotation3D);
    d->axis = axis;
    update();
}

/*!
  \fn void QGraphicsRotation3D::axisChanged()

  This signal is emitted whenever the axis of the object
  changes.
*/

const qreal inv_dist_to_plane = 1. / 1024.;

/*!
  \reimp
*/
void QGraphicsRotation3D::applyTo(QTransform *t) const
{
    Q_D(const QGraphicsRotation3D);

    if (d->angle == 0. ||
        (d->axis.z() == 0. && d->axis.y() == 0 && d->axis.x() == 0))
        return;

    qreal rad = d->angle * 2. * M_PI / 360.;
    qreal c = ::cos(rad);
    qreal s = ::sin(rad);

    qreal x = d->axis.x();
    qreal y = d->axis.y();
    qreal z = d->axis.z();

    qreal len = x * x + y * y + z * z;
    if (len != 1.) {
        len = 1./::sqrt(len);
        x *= len;
        y *= len;
        z *= len;
    }

    t->translate(d->origin.x(), d->origin.y());
    *t = QTransform(x*x*(1-c)+c, x*y*(1-c)-z*s, x*z*(1-c)+y*s*inv_dist_to_plane,
                             y*x*(1-c)+z*s, y*y*(1-c)+c, y*z*(1-c)-x*s*inv_dist_to_plane,
                             0, 0, 1) * *t;
    t->translate(-d->origin.x(), -d->origin.y());
}

#include "moc_qgraphicstransform.cpp"

QT_END_NAMESPACE
<commit_msg>fix compilation without 3d support<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $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 either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qgraphicstransform.h"
#include "qgraphicsitem_p.h"
#include "qgraphicstransform_p.h"
#include <QDebug>

#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

QT_BEGIN_NAMESPACE

void QGraphicsTransformPrivate::setItem(QGraphicsItem *i)
{
    if (item == i)
        return;

    if (item) {
        Q_Q(QGraphicsTransform);
        QGraphicsItemPrivate *d_ptr = item->d_ptr;

        item->prepareGeometryChange();
        Q_ASSERT(d_ptr->transformData);
        d_ptr->transformData->graphicsTransforms.removeAll(q);
        d_ptr->dirtySceneTransform = 1;
        item = 0;
    }

    item = i;
}

void QGraphicsTransformPrivate::updateItem(QGraphicsItem *item)
{
    item->prepareGeometryChange();
    item->d_ptr->dirtySceneTransform = 1;
}

void QGraphicsTransform::update()
{
    Q_D(QGraphicsTransform);
    if (d->item)
        d->updateItem(d->item);
}

/*!
  returns this object as a QTransform.
*/
QTransform QGraphicsTransform::transform() const
{
    QTransform t;
    applyTo(&t);
    return t;
}

/*!
  \class QGraphicsTransform
  \brief The QGraphicsTransform class is an abstract base class for tranformations on QGraphicsItems.
  \since 4.6

  The classes that inherit QGraphicsTransform express different types of transformations
  that can be applied to graphics items.

  A list of these transformations can be applied to any graphics item. These
  transformations are then easily modifyable and usable from e.g. within animations.

  QGraphicsTransform is an abstract base class that is implemented by QGraphicsScale,
  QGraphicsRotation and QGraphicsRotation3D. Subclasses have to implement the applyTo method.

  \sa QGraphicsItem::transform(), QGraphicsScale, QGraphicsRotation, QGraphicsRotation3D
*/

/*!
  Constructs a new QGraphicsTransform with \a parent.
*/
QGraphicsTransform::QGraphicsTransform(QObject *parent) :
    QObject(*new QGraphicsTransformPrivate, parent)
{
}

/*!
  Destructs the graphics transform.
*/
QGraphicsTransform::~QGraphicsTransform()
{
    Q_D(QGraphicsTransform);
    d->setItem(0);
}

/*!
  \internal
*/
QGraphicsTransform::QGraphicsTransform(QGraphicsTransformPrivate &p, QObject *parent)
    : QObject(p, parent)
{
}

/*! \fn void QGraphicsTransform::applyTo(QTransform *transform) const

  This pure virtual method has to be reimplemented in derived classes.

  It applies this transformation to \a transform.
*/

/*!
  \class QGraphicsScale
  \brief The QGraphicsScale class provides a way to scale a graphics item in 2 dimensions.
  \since 4.6

  QGraphicsScale contains an \a origin around which the scaling happens, and two
  scale factors, xScale and yScale, the x and one for the y axis.
*/

class QGraphicsScalePrivate : public QGraphicsTransformPrivate
{
public:
    QGraphicsScalePrivate()
            : xScale(1), yScale(1) {}
    QPointF origin;
    qreal xScale;
    qreal yScale;
};

/*!
  Constructs a new graphics scale object with \a parent.
*/
QGraphicsScale::QGraphicsScale(QObject *parent)
    : QGraphicsTransform(*new QGraphicsScalePrivate, parent)
{
}

/*!
  Destroys the object
*/
QGraphicsScale::~QGraphicsScale()
{
}

/*!
  \property QGraphicsScale::origin
  The origin of the scale. All scaling will be done relative to this point.

  The \a origin is in other words the fixed point for the transformation.
*/
QPointF QGraphicsScale::origin() const
{
    Q_D(const QGraphicsScale);
    return d->origin;
}

void QGraphicsScale::setOrigin(const QPointF &point)
{
    Q_D(QGraphicsScale);
    d->origin = point;
    update();
    emit originChanged();
}

/*!
  \fn QGraphicsScale::originChanged()

  This signal is emitted whenever the origin of the object
  changes.
*/

/*!
  \property QGraphicsScale::xScale

  The scale factor in x direction. The x direction is
  in the graphics items logical coordinates.

  \sa yScale
*/
qreal QGraphicsScale::xScale() const
{
    Q_D(const QGraphicsScale);
    return d->xScale;
}

void QGraphicsScale::setXScale(qreal scale)
{
    Q_D(QGraphicsScale);
    if (d->xScale == scale)
        return;
    d->xScale = scale;
    update();
    emit scaleChanged();
}

/*!
  \property QGraphicsScale::yScale

  The scale factor in y direction. The y direction is
  in the graphics items logical coordinates.

  \sa xScale
*/
qreal QGraphicsScale::yScale() const
{
    Q_D(const QGraphicsScale);
    return d->yScale;
}

void QGraphicsScale::setYScale(qreal scale)
{
    Q_D(QGraphicsScale);
    if (d->yScale == scale)
        return;
    d->yScale = scale;
    update();
    emit scaleChanged();
}

/*!
  \fn QGraphicsScale::scaleChanged()

  This signal is emitted whenever the xScale or yScale of the object
  changes.
*/

/*!
  \reimp
*/
void QGraphicsScale::applyTo(QTransform *transform) const
{
    Q_D(const QGraphicsScale);
    transform->translate(d->origin.x(), d->origin.y());
    transform->scale(d->xScale, d->yScale);
    transform->translate(-d->origin.x(), -d->origin.y());
}

/*!
  \class QGraphicsRotation
  \brief The QGraphicsRotation class provides a way to rotate a graphics item in 2 dimensions.
  \since 4.6

  QGraphicsRotation contains an \a origin around which the rotation happens, and one
  angle in degrees describing the amount of the rotation.
*/

class QGraphicsRotationPrivate : public QGraphicsTransformPrivate
{
public:
    QGraphicsRotationPrivate()
            : angle(0) {}
    QPointF origin;
    qreal originY;
    qreal angle;
};

/*!
  Constructs a new graphics rotation with \a parent.
*/
QGraphicsRotation::QGraphicsRotation(QObject *parent)
    : QGraphicsTransform(*new QGraphicsRotationPrivate, parent)
{
}

/*!
  \internal
*/
QGraphicsRotation::QGraphicsRotation(QGraphicsRotationPrivate &p, QObject *parent)
    : QGraphicsTransform(p, parent)
{
}

/*!
  Destructs the object
*/
QGraphicsRotation::~QGraphicsRotation()
{
}

/*!
  \property QGraphicsRotation::origin
  The origin around which this object will rotate the graphics item.

  The \a origin is in other words the fixed point for the transformation.
*/
QPointF QGraphicsRotation::origin() const
{
    Q_D(const QGraphicsRotation);
    return d->origin;
}

void QGraphicsRotation::setOrigin(const QPointF &point)
{
    Q_D(QGraphicsRotation);
    d->origin = point;
    update();
    emit originChanged();
}

/*!
  \fn QGraphicsRotation::originChanged()

  This signal is emitted whenever the origin of the object
  changes.
*/

/*!
  \property QGraphicsRotation::angle
  The angle, in degrees, of the rotation.
*/
qreal QGraphicsRotation::angle() const
{
    Q_D(const QGraphicsRotation);
    return d->angle;
}

void QGraphicsRotation::setAngle(qreal angle)
{
    Q_D(QGraphicsRotation);
    if (d->angle == angle)
        return;
    d->angle = angle;
    update();
    emit angleChanged();
}

/*!
  \fn void QGraphicsRotation::angleChanged()

  This signal is emitted whenever the angle of the object
  changes.
*/

/*!
  \reimp
*/
void QGraphicsRotation::applyTo(QTransform *t) const
{
    Q_D(const QGraphicsRotation);
    if(d->angle) {
        t->translate(d->origin.x(), d->origin.y());
        t->rotate(d->angle);
        t->translate(-d->origin.x(), -d->origin.y());
    }
}

/*!
  \class QGraphicsRotation3D
  \brief The QGraphicsRotation3D class provides a way to rotate a graphics item in 3 dimensions.
  \since 4.6

  In addition to the origin and angle of a simple QGraphicsRotation, QGraphicsRotation3D contains
  also an axis that describes around which axis in space the rotation is supposed to happen.
*/

class QGraphicsRotation3DPrivate : public QGraphicsRotationPrivate
{
public:
    QGraphicsRotation3DPrivate() {}

    QVector3D axis;
};

/*!
  Constructs a new 3D rotation with \a parent.
*/
QGraphicsRotation3D::QGraphicsRotation3D(QObject *parent)
    : QGraphicsRotation(*new QGraphicsRotation3DPrivate, parent)
{
}

/*!
  Destroys the object
*/
QGraphicsRotation3D::~QGraphicsRotation3D()
{
}

/*!
    \property QGraphicsRotation3D::axis

    A rotation axis is specified by a vector in 3D space.
*/
QVector3D QGraphicsRotation3D::axis()
{
    Q_D(QGraphicsRotation3D);
    return d->axis;
}

void QGraphicsRotation3D::setAxis(const QVector3D &axis)
{
    Q_D(QGraphicsRotation3D);
    d->axis = axis;
    update();
}

/*!
  \fn void QGraphicsRotation3D::axisChanged()

  This signal is emitted whenever the axis of the object
  changes.
*/

const qreal inv_dist_to_plane = 1. / 1024.;

/*!
  \reimp
*/
void QGraphicsRotation3D::applyTo(QTransform *t) const
{
    Q_D(const QGraphicsRotation3D);

    if (d->angle == 0. ||
        (d->axis.z() == 0. && d->axis.y() == 0 && d->axis.x() == 0))
        return;

    qreal rad = d->angle * 2. * M_PI / 360.;
    qreal c = ::cos(rad);
    qreal s = ::sin(rad);

    qreal x = d->axis.x();
    qreal y = d->axis.y();
    qreal z = d->axis.z();

    qreal len = x * x + y * y + z * z;
    if (len != 1.) {
        len = 1./::sqrt(len);
        x *= len;
        y *= len;
        z *= len;
    }

    t->translate(d->origin.x(), d->origin.y());
    *t = QTransform(x*x*(1-c)+c, x*y*(1-c)-z*s, x*z*(1-c)+y*s*inv_dist_to_plane,
                             y*x*(1-c)+z*s, y*y*(1-c)+c, y*z*(1-c)-x*s*inv_dist_to_plane,
                             0, 0, 1) * *t;
    t->translate(-d->origin.x(), -d->origin.y());
}

#include "moc_qgraphicstransform.cpp"

QT_END_NAMESPACE
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/hwpf/fapi2/include/mvpd_access.H $                 */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file mvpd_access.H
///
/// @brief Defines the Module VPD functions that platform must implement
///

#ifndef _FAPI2_MVPDACCESS_H_
#define _FAPI2_MVPDACCESS_H_

#include <stdint.h>
#include <return_code.H>
#include <target.H>

namespace fapi2
{
enum MvpdRecord
{
    MVPD_RECORD_CRP0 = 0x00,
    MVPD_RECORD_CP00 = 0x01,
    MVPD_RECORD_VINI = 0x02,
    MVPD_RECORD_LRP0 = 0x03,
    MVPD_RECORD_LRP1 = 0x04,
    MVPD_RECORD_LRP2 = 0x05,
    MVPD_RECORD_LRP3 = 0x06,
    MVPD_RECORD_LRP4 = 0x07,
    MVPD_RECORD_LRP5 = 0x08,
    MVPD_RECORD_LRP6 = 0x09,
    MVPD_RECORD_LRP7 = 0x0a,
    MVPD_RECORD_LRP8 = 0x0b,
    MVPD_RECORD_LRP9 = 0x0c,
    MVPD_RECORD_LRPA = 0x0d,
    MVPD_RECORD_LRPB = 0x0e,
    MVPD_RECORD_LRPC = 0x0f,
    MVPD_RECORD_LRPD = 0x10,
    MVPD_RECORD_LRPE = 0x11,
    MVPD_RECORD_LWP0 = 0x12,
    MVPD_RECORD_LWP1 = 0x13,
    MVPD_RECORD_LWP2 = 0x14,
    MVPD_RECORD_LWP3 = 0x15,
    MVPD_RECORD_LWP4 = 0x16,
    MVPD_RECORD_LWP5 = 0x17,
    MVPD_RECORD_LWP6 = 0x18,
    MVPD_RECORD_LWP7 = 0x19,
    MVPD_RECORD_LWP8 = 0x1a,
    MVPD_RECORD_LWP9 = 0x1b,
    MVPD_RECORD_LWPA = 0x1c,
    MVPD_RECORD_LWPB = 0x1d,
    MVPD_RECORD_LWPC = 0x1e,
    MVPD_RECORD_LWPD = 0x1f,
    MVPD_RECORD_LWPE = 0x20,
    MVPD_RECORD_VWML = 0x21,
    MVPD_RECORD_MER0 = 0x22,
};

enum MvpdKeyword
{
    MVPD_KEYWORD_VD  = 0x00,
    MVPD_KEYWORD_ED  = 0x01,
    MVPD_KEYWORD_TE  = 0x02,
    MVPD_KEYWORD_DD  = 0x03,
    MVPD_KEYWORD_PDP = 0x04,
    MVPD_KEYWORD_ST  = 0x05,
    MVPD_KEYWORD_DN  = 0x06,
    MVPD_KEYWORD_PG  = 0x07,
    MVPD_KEYWORD_PK  = 0x08,
    MVPD_KEYWORD_PDR = 0x09,
    MVPD_KEYWORD_PDV = 0x0a,
    MVPD_KEYWORD_PDH = 0x0b,
    MVPD_KEYWORD_SB  = 0x0c,
    MVPD_KEYWORD_DR  = 0x0d,
    MVPD_KEYWORD_VZ  = 0x0e,
    MVPD_KEYWORD_CC  = 0x0f,
    MVPD_KEYWORD_CE  = 0x10,
    MVPD_KEYWORD_FN  = 0x11,
    MVPD_KEYWORD_PN  = 0x12,
    MVPD_KEYWORD_SN  = 0x13,
    MVPD_KEYWORD_PR  = 0x14,
    MVPD_KEYWORD_HE  = 0x15,
    MVPD_KEYWORD_CT  = 0x16,
    MVPD_KEYWORD_HW  = 0x17,
    MVPD_KEYWORD_PDM = 0x18,
    MVPD_KEYWORD_IN  = 0x19,
    MVPD_KEYWORD_PD2 = 0x1a,
    MVPD_KEYWORD_PD3 = 0x1b,
    MVPD_KEYWORD_OC  = 0x1c,
    MVPD_KEYWORD_FO  = 0x1d,
    MVPD_KEYWORD_PDI = 0x1e,
    MVPD_KEYWORD_PDG = 0x1f,
    MVPD_KEYWORD_MK  = 0x20,
    MVPD_KEYWORD_PB  = 0x21,
    MVPD_KEYWORD_CH  = 0x22,
    MVPD_KEYWORD_IQ  = 0x23,
};

///
/// @brief Get Module VPD field.
///
/// A Module VPD field is specified using a record and keyword enumerator
///
/// Suggested way to call this routine is to call it once with a NULL buffer
/// pointer to to retrieve the size of the record, then allocate the proper
/// size of the buffer and call again.
///
/// @param[in] i_record     Record enumerator
/// @param[in] i_keyword    Keyword enumerator
/// @param[in] i_target     Reference to processor chip target for the record
/// @param[in] i_pBuffer    Pointer to buffer where record will be stored. If
///                         NULL then the size of record will be stored in
///                         io_fieldSize
/// @param[in,out] io_fieldSize Size of i_pBuffer in bytes
///
/// @return fapi2::ReturnCode. FAPI_RC_SUCCESS, or failure value.
///
ReturnCode getMvpdField(const MvpdRecord i_record,
                        const MvpdKeyword i_keyword,
                        const Target<TARGET_TYPE_PROC_CHIP> &i_target,
                        uint8_t * const i_pBuffer,
                        uint32_t &io_fieldSize);

///
/// @brief Set Module VPD field.
///
/// A Module VPD field is specified using a record and keyword enumerator
///
/// @param[in] i_record     Record enumerator
/// @param[in] i_keyword    Keyword enumerator
/// @param[in] i_target     Reference to processor chip target for the record
/// @param[in] i_pBuffer    Pointer to buffer where data to set is stored
/// @param[in] i_fieldSize  Size of i_pBuffer in bytes
///
/// @return fapi2::ReturnCode. FAPI_RC_SUCCESS, or failure value.
///
ReturnCode setMvpdField(const MvpdRecord i_record,
                        const MvpdKeyword i_keyword,
                        const Target<TARGET_TYPE_PROC_CHIP> &i_target,
                        const uint8_t * const i_pBuffer,
                        const uint32_t i_fieldSize);
}

#endif
<commit_msg>moved mvpd record and keyword definition to mvpd_access_defs.H<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/hwpf/fapi2/include/mvpd_access.H $                 */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file mvpd_access.H
///
/// @brief Defines the Module VPD functions that platform must implement
///

#ifndef _FAPI2_MVPDACCESS_H_
#define _FAPI2_MVPDACCESS_H_

#include <stdint.h>
#include <return_code.H>
#include <target.H>
#include <mvpd_access_defs.H>

namespace fapi2
{
///
/// @brief Get Module VPD field.
///
/// A Module VPD field is specified using a record and keyword enumerator
///
/// Suggested way to call this routine is to call it once with a NULL buffer
/// pointer to to retrieve the size of the record, then allocate the proper
/// size of the buffer and call again.
///
/// @param[in] i_record     Record enumerator
/// @param[in] i_keyword    Keyword enumerator
/// @param[in] i_target     Reference to processor chip target for the record
/// @param[in] i_pBuffer    Pointer to buffer where record will be stored. If
///                         NULL then the size of record will be stored in
///                         io_fieldSize
/// @param[in,out] io_fieldSize Size of i_pBuffer in bytes
///
/// @return fapi2::ReturnCode. FAPI_RC_SUCCESS, or failure value.
///
ReturnCode getMvpdField(const MvpdRecord i_record,
                        const MvpdKeyword i_keyword,
                        const Target<TARGET_TYPE_PROC_CHIP>& i_target,
                        uint8_t* const i_pBuffer,
                        uint32_t& io_fieldSize);

///
/// @brief Set Module VPD field.
///
/// A Module VPD field is specified using a record and keyword enumerator
///
/// @param[in] i_record     Record enumerator
/// @param[in] i_keyword    Keyword enumerator
/// @param[in] i_target     Reference to processor chip target for the record
/// @param[in] i_pBuffer    Pointer to buffer where data to set is stored
/// @param[in] i_fieldSize  Size of i_pBuffer in bytes
///
/// @return fapi2::ReturnCode. FAPI_RC_SUCCESS, or failure value.
///
ReturnCode setMvpdField(const MvpdRecord i_record,
                        const MvpdKeyword i_keyword,
                        const Target<TARGET_TYPE_PROC_CHIP>& i_target,
                        const uint8_t* const i_pBuffer,
                        const uint32_t i_fieldSize);
}

#endif
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/include/usr/hwpf/fapi/fapiReturnCodes.H $                 */
/*                                                                        */
/* IBM CONFIDENTIAL                                                       */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 2011,2014              */
/*                                                                        */
/* p1                                                                     */
/*                                                                        */
/* Object Code Only (OCO) source materials                                */
/* Licensed Internal Code Source Materials                                */
/* IBM HostBoot Licensed Internal Code                                    */
/*                                                                        */
/* The source code for this program is not published or otherwise         */
/* divested of its trade secrets, irrespective of what has been           */
/* deposited with the U.S. Copyright Office.                              */
/*                                                                        */
/* Origin: 30                                                             */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
// $Id: fapiReturnCodes.H,v 1.15 2014/04/11 13:53:50 whs Exp $
// $Source: /afs/awd/projects/eclipz/KnowledgeBase/.cvsroot/eclipz/hwpf/working/fapi/fapiReturnCodes.H,v $

/**
 *  @file fapiReturnCodes.H
 *
 *  @brief Defines the returns codes generated by HWPF code.
 */

/*
 * Change Log ******************************************************************
 * Flag     Defect/Feature  User        Date        Description
 * ------   --------------  ----------  ----------- ----------------------------
 *                          mjjones     04/13/2011  Created.
 *                          mjjones     06/07/2011  Add FAPI_RC_NOT_IMPLEMENTED
 *                          mjjones     06/30/2011  Add FAPI_RC_ATTR_UNIT_TEST_FAIL
 *                          mjjones     08/10/2011  Add FAPI_RC_FFDC_HWP_NOT_FOUND
 *                          mjjones     09/23/2011  Remove FAPI_RC_FFDC_HWP_NOT_FOUND
 *                          mjjones     10/07/2011  Add FAPI_RC_INVALID_ATTR_GET
 *                          mjjones     10/28/2011  Trim FAPI/PLAT errors
 *                          mjjones     11/10/2011  Use ecmdDataBufferBase
 *                          mjjones     01/13/2012  Name enumeration
 *                          mjjones     04/16/2012  Add FAPI_RC_INVALID_CHIP_EC_FEATURE_GET
 *                          mjjones     05/02/2012  Add FAPI_RC_PLAT_ERR_ADU_LOCKED
 *                          mjjones     11/14/2012  Add FAPI_RC_UNRECOGNIZED_SBE_ERROR
 *                          mjjones     03/26/2014  Remove FAPI_RC_UNRECOGNIZED_SBE_ERROR
 *                          whs         04/09/2014  Remove FAPI_RC_INVALID_PARAM
 */

#ifndef FAPIRETURNCODES_H_
#define FAPIRETURNCODES_H_

#include <ecmdDataBufferBase.H>

namespace fapi
{

/**
 * @brief Enumeration of return codes
 *
 * @note HWP return codes are in the HwpReturnCode enumeration in the
 *       generated fapiHwpReturnCodes.H file
 */
enum ReturnCodes
{
    FAPI_RC_SUCCESS = 0,

    //--------------------------------------------------------------------------
    // Flag bits indicating which code generated the error If no flag set then
    // it is generated by HWP
    //--------------------------------------------------------------------------
    FAPI_RC_FAPI_MASK = 0x04000000, // FAPI generated error
    FAPI_RC_PLAT_MASK = 0x02000000, // PLAT generated error
    FAPI_RC_ECMD_MASK = ECMD_ERR_ECMD, // ECMD generated error (0x01000000)

    //--------------------------------------------------------------------------
    // FAPI generated return codes
    //--------------------------------------------------------------------------

    // Initfile requested an attribute with an invalid attribute ID
    FAPI_RC_INVALID_ATTR_GET            = FAPI_RC_FAPI_MASK | 0x01,

    // HWP requested a chip EC feature with an invalid attribute ID
    FAPI_RC_INVALID_CHIP_EC_FEATURE_GET = FAPI_RC_FAPI_MASK | 0x02,

    //--------------------------------------------------------------------------
    // PLAT generated return codes. Additional details may be contained in
    // ReturnCode platData (this can only be looked at by PLAT code)
    //--------------------------------------------------------------------------

    // Generic platform error
    FAPI_RC_PLAT_ERR_SEE_DATA   = FAPI_RC_PLAT_MASK | 0x01,

    // Operation to AlterDisplay unit failed because it is locked
    FAPI_RC_PLAT_ERR_ADU_LOCKED = FAPI_RC_PLAT_MASK | 0x02,

    // Operation not supported by HB runtime
    FAPI_RC_PLAT_NOT_SUPPORTED_AT_RUNTIME = FAPI_RC_PLAT_MASK | 0x03,
};

}

#endif // FAPIRETURNCODES_H_
<commit_msg>Ensure that all FAPI errors are parsed correctly<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/include/usr/hwpf/fapi/fapiReturnCodes.H $                 */
/*                                                                        */
/* IBM CONFIDENTIAL                                                       */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 2011,2014              */
/*                                                                        */
/* p1                                                                     */
/*                                                                        */
/* Object Code Only (OCO) source materials                                */
/* Licensed Internal Code Source Materials                                */
/* IBM HostBoot Licensed Internal Code                                    */
/*                                                                        */
/* The source code for this program is not published or otherwise         */
/* divested of its trade secrets, irrespective of what has been           */
/* deposited with the U.S. Copyright Office.                              */
/*                                                                        */
/* Origin: 30                                                             */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
// $Id: fapiReturnCodes.H,v 1.17 2014/04/15 17:50:40 whs Exp $
// $Source: /afs/awd/projects/eclipz/KnowledgeBase/.cvsroot/eclipz/hwpf/working/fapi/fapiReturnCodes.H,v $

/**
 *  @file fapiReturnCodes.H
 *
 *  @brief Defines the returns codes generated by HWPF code.
 */

/*
 * Change Log ******************************************************************
 * Flag     Defect/Feature  User        Date        Description
 * ------   --------------  ----------  ----------- ----------------------------
 *                          mjjones     04/13/2011  Created.
 *                          mjjones     06/07/2011  Add FAPI_RC_NOT_IMPLEMENTED
 *                          mjjones     06/30/2011  Add FAPI_RC_ATTR_UNIT_TEST_FAIL
 *                          mjjones     08/10/2011  Add FAPI_RC_FFDC_HWP_NOT_FOUND
 *                          mjjones     09/23/2011  Remove FAPI_RC_FFDC_HWP_NOT_FOUND
 *                          mjjones     10/07/2011  Add FAPI_RC_INVALID_ATTR_GET
 *                          mjjones     10/28/2011  Trim FAPI/PLAT errors
 *                          mjjones     11/10/2011  Use ecmdDataBufferBase
 *                          mjjones     01/13/2012  Name enumeration
 *                          mjjones     04/16/2012  Add FAPI_RC_INVALID_CHIP_EC_FEATURE_GET
 *                          mjjones     05/02/2012  Add FAPI_RC_PLAT_ERR_ADU_LOCKED
 *                          mjjones     11/14/2012  Add FAPI_RC_UNRECOGNIZED_SBE_ERROR
 *                          mjjones     03/26/2014  Remove FAPI_RC_UNRECOGNIZED_SBE_ERROR
 *                          whs         04/14/2014  Remove FAPI_RC_INVALID_PARAM
 */

#ifndef FAPIRETURNCODES_H_
#define FAPIRETURNCODES_H_

#include <ecmdDataBufferBase.H>

namespace fapi
{

/**
 * @brief Enumeration of return codes
 *
 * @note HWP return codes are in the HwpReturnCode enumeration in the
 *       generated fapiHwpReturnCodes.H file
 */
enum ReturnCodes
{
    FAPI_RC_SUCCESS = 0,

    //--------------------------------------------------------------------------
    // Flag bits indicating which code generated the error If no flag set then
    // it is generated by HWP
    //--------------------------------------------------------------------------
    FAPI_RC_FAPI_MASK = 0x04000000, // FAPI generated error
    FAPI_RC_PLAT_MASK = 0x02000000, // PLAT generated error
    FAPI_RC_ECMD_MASK = ECMD_ERR_ECMD, // ECMD generated error (0x01000000)

    //--------------------------------------------------------------------------
    // FAPI generated return codes
    //--------------------------------------------------------------------------

    // Initfile requested an attribute with an invalid attribute ID
    FAPI_RC_INVALID_ATTR_GET            = FAPI_RC_FAPI_MASK | 0x01,

    // HWP requested a chip EC feature with an invalid attribute ID
    FAPI_RC_INVALID_CHIP_EC_FEATURE_GET = FAPI_RC_FAPI_MASK | 0x02,

    // Invalid multiscom parameters
    FAPI_RC_INVALID_MULTISCOM_LENGTH    = FAPI_RC_FAPI_MASK | 0x03,

    //--------------------------------------------------------------------------
    // PLAT generated return codes. Additional details may be contained in
    // ReturnCode platData (this can only be looked at by PLAT code)
    //--------------------------------------------------------------------------

    // Generic platform error
    FAPI_RC_PLAT_ERR_SEE_DATA   = FAPI_RC_PLAT_MASK | 0x01,

    // Operation to AlterDisplay unit failed because it is locked
    FAPI_RC_PLAT_ERR_ADU_LOCKED = FAPI_RC_PLAT_MASK | 0x02,

    // Operation not supported by HB runtime
    FAPI_RC_PLAT_NOT_SUPPORTED_AT_RUNTIME = FAPI_RC_PLAT_MASK | 0x03,
};

}

#endif // FAPIRETURNCODES_H_
<|endoftext|>


<commit_before>
/*
    pbrt source code is Copyright(c) 1998-2016
                        Matt Pharr, Greg Humphreys, and Wenzel Jakob.

    This file is part of pbrt.

    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.

    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
    HOLDER 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.

 */

// core/medium.cpp*
#include "medium.h"
#include "memory.h"
#include "sampler.h"
#include "stats.h"
#include "interaction.h"

namespace pbrt {

// Media Local Definitions
struct MeasuredSS {
    const char *name;
    Float sigma_prime_s[3], sigma_a[3];  // mm^-1
};

static MeasuredSS SubsurfaceParameterTable[] = {
    // From "A Practical Model for Subsurface Light Transport"
    // Jensen, Marschner, Levoy, Hanrahan
    // Proc SIGGRAPH 2001
    {
        "Apple", {2.29, 2.39, 1.97}, {0.0030, 0.0034, 0.046},
    },
    {
        "Chicken1", {0.15, 0.21, 0.38}, {0.015, 0.077, 0.19},
    },
    {
        "Chicken2", {0.19, 0.25, 0.32}, {0.018, 0.088, 0.20},
    },
    {
        "Cream", {7.38, 5.47, 3.15}, {0.0002, 0.0028, 0.0163},
    },
    {
        "Ketchup", {0.18, 0.07, 0.03}, {0.061, 0.97, 1.45},
    },
    {
        "Marble", {2.19, 2.62, 3.00}, {0.0021, 0.0041, 0.0071},
    },
    {
        "Potato", {0.68, 0.70, 0.55}, {0.0024, 0.0090, 0.12},
    },
    {
        "Skimmilk", {0.70, 1.22, 1.90}, {0.0014, 0.0025, 0.0142},
    },
    {
        "Skin1", {0.74, 0.88, 1.01}, {0.032, 0.17, 0.48},
    },
    {
        "Skin2", {1.09, 1.59, 1.79}, {0.013, 0.070, 0.145},
    },
    {
        "Spectralon", {11.6, 20.4, 14.9}, {0.00, 0.00, 0.00},
    },
    {
        "Wholemilk", {2.55, 3.21, 3.77}, {0.0011, 0.0024, 0.014},
    },

    // From "Acquiring Scattering Properties of Participating Media by
    // Dilution",
    // Narasimhan, Gupta, Donner, Ramamoorthi, Nayar, Jensen
    // Proc SIGGRAPH 2006
    {"Lowfat Milk", {0.89187, 1.5136, 2.532}, {0.002875, 0.00575, 0.0115}},
    {"Reduced Milk",
     {2.4858, 3.1669, 4.5214},
     {0.0025556, 0.0051111, 0.012778}},
    {"Regular Milk", {4.5513, 5.8294, 7.136}, {0.0015333, 0.0046, 0.019933}},
    {"Espresso", {0.72378, 0.84557, 1.0247}, {4.7984, 6.5751, 8.8493}},
    {"Mint Mocha Coffee", {0.31602, 0.38538, 0.48131}, {3.772, 5.8228, 7.82}},
    {"Lowfat Soy Milk",
     {0.30576, 0.34233, 0.61664},
     {0.0014375, 0.0071875, 0.035937}},
    {"Regular Soy Milk",
     {0.59223, 0.73866, 1.4693},
     {0.0019167, 0.0095833, 0.065167}},
    {"Lowfat Chocolate Milk",
     {0.64925, 0.83916, 1.1057},
     {0.0115, 0.0368, 0.1564}},
    {"Regular Chocolate Milk",
     {1.4585, 2.1289, 2.9527},
     {0.010063, 0.043125, 0.14375}},
    {"Coke", {8.9053e-05, 8.372e-05, 0}, {0.10014, 0.16503, 0.2468}},
    {"Pepsi", {6.1697e-05, 4.2564e-05, 0}, {0.091641, 0.14158, 0.20729}},
    {"Sprite",
     {6.0306e-06, 6.4139e-06, 6.5504e-06},
     {0.001886, 0.0018308, 0.0020025}},
    {"Gatorade",
     {0.0024574, 0.003007, 0.0037325},
     {0.024794, 0.019289, 0.008878}},
    {"Chardonnay",
     {1.7982e-05, 1.3758e-05, 1.2023e-05},
     {0.010782, 0.011855, 0.023997}},
    {"White Zinfandel",
     {1.7501e-05, 1.9069e-05, 1.288e-05},
     {0.012072, 0.016184, 0.019843}},
    {"Merlot", {2.1129e-05, 0, 0}, {0.11632, 0.25191, 0.29434}},
    {"Budweiser Beer",
     {2.4356e-05, 2.4079e-05, 1.0564e-05},
     {0.011492, 0.024911, 0.057786}},
    {"Coors Light Beer",
     {5.0922e-05, 4.301e-05, 0},
     {0.006164, 0.013984, 0.034983}},
    {"Clorox",
     {0.0024035, 0.0031373, 0.003991},
     {0.0033542, 0.014892, 0.026297}},
    {"Apple Juice",
     {0.00013612, 0.00015836, 0.000227},
     {0.012957, 0.023741, 0.052184}},
    {"Cranberry Juice",
     {0.00010402, 0.00011646, 7.8139e-05},
     {0.039437, 0.094223, 0.12426}},
    {"Grape Juice", {5.382e-05, 0, 0}, {0.10404, 0.23958, 0.29325}},
    {"Ruby Grapefruit Juice",
     {0.011002, 0.010927, 0.011036},
     {0.085867, 0.18314, 0.25262}},
    {"White Grapefruit Juice",
     {0.22826, 0.23998, 0.32748},
     {0.0138, 0.018831, 0.056781}},
    {"Shampoo",
     {0.0007176, 0.0008303, 0.0009016},
     {0.014107, 0.045693, 0.061717}},
    {"Strawberry Shampoo",
     {0.00015671, 0.00015947, 1.518e-05},
     {0.01449, 0.05796, 0.075823}},
    {"Head & Shoulders Shampoo",
     {0.023805, 0.028804, 0.034306},
     {0.084621, 0.15688, 0.20365}},
    {"Lemon Tea Powder",
     {0.040224, 0.045264, 0.051081},
     {2.4288, 4.5757, 7.2127}},
    {"Orange Powder",
     {0.00015617, 0.00017482, 0.0001762},
     {0.001449, 0.003441, 0.007863}},
    {"Pink Lemonade Powder",
     {0.00012103, 0.00013073, 0.00012528},
     {0.001165, 0.002366, 0.003195}},
    {"Cappuccino Powder", {1.8436, 2.5851, 2.1662}, {35.844, 49.547, 61.084}},
    {"Salt Powder", {0.027333, 0.032451, 0.031979}, {0.28415, 0.3257, 0.34148}},
    {"Sugar Powder",
     {0.00022272, 0.00025513, 0.000271},
     {0.012638, 0.031051, 0.050124}},
    {"Suisse Mocha Powder", {2.7979, 3.5452, 4.3365}, {17.502, 27.004, 35.433}},
    {"Pacific Ocean Surface Water",
     {0.0001764, 0.00032095, 0.00019617},
     {0.031845, 0.031324, 0.030147}}};

// Media Definitions
PhaseFunction::~PhaseFunction() { }

bool GetMediumScatteringProperties(const std::string &name, Spectrum *sigma_a,
                                   Spectrum *sigma_prime_s) {
    for (MeasuredSS &mss : SubsurfaceParameterTable) {
        if (name == mss.name) {
            *sigma_a = Spectrum::FromRGB(mss.sigma_a);
            *sigma_prime_s = Spectrum::FromRGB(mss.sigma_prime_s);
            return true;
        }
    }
    return false;
}

// HenyeyGreenstein Method Definitions
Float HenyeyGreenstein::Sample_p(const Vector3f &wo, Vector3f *wi,
                                 const Point2f &u) const {
    ProfilePhase _(Prof::PhaseFuncSampling);
    // Compute $\cos \theta$ for Henyey--Greenstein sample
    Float cosTheta;
    if (std::abs(g) < 1e-3)
        cosTheta = 1 - 2 * u[0];
    else {
        Float sqrTerm = (1 - g * g) / (1 - g + 2 * g * u[0]);
        cosTheta = (1 + g * g - sqrTerm * sqrTerm) / (2 * g);
    }

    // Compute direction _wi_ for Henyey--Greenstein sample
    Float sinTheta = std::sqrt(std::max((Float)0, 1 - cosTheta * cosTheta));
    Float phi = 2 * Pi * u[1];
    Vector3f v1, v2;
    CoordinateSystem(wo, &v1, &v2);
    *wi = SphericalDirection(sinTheta, cosTheta, phi, v1, v2, -wo);
    return PhaseHG(-cosTheta, g);
}

Float HenyeyGreenstein::p(const Vector3f &wo, const Vector3f &wi) const {
    ProfilePhase _(Prof::PhaseFuncEvaluation);
    return PhaseHG(Dot(wo, wi), g);
}

}  // namespace pbrt
<commit_msg>Fix Henyey Greenstein importance sampling sign conventions (via Jiayin Cao)<commit_after>
/*
    pbrt source code is Copyright(c) 1998-2016
                        Matt Pharr, Greg Humphreys, and Wenzel Jakob.

    This file is part of pbrt.

    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.

    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
    HOLDER 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.

 */

// core/medium.cpp*
#include "medium.h"
#include "memory.h"
#include "sampler.h"
#include "stats.h"
#include "interaction.h"

namespace pbrt {

// Media Local Definitions
struct MeasuredSS {
    const char *name;
    Float sigma_prime_s[3], sigma_a[3];  // mm^-1
};

static MeasuredSS SubsurfaceParameterTable[] = {
    // From "A Practical Model for Subsurface Light Transport"
    // Jensen, Marschner, Levoy, Hanrahan
    // Proc SIGGRAPH 2001
    {
        "Apple", {2.29, 2.39, 1.97}, {0.0030, 0.0034, 0.046},
    },
    {
        "Chicken1", {0.15, 0.21, 0.38}, {0.015, 0.077, 0.19},
    },
    {
        "Chicken2", {0.19, 0.25, 0.32}, {0.018, 0.088, 0.20},
    },
    {
        "Cream", {7.38, 5.47, 3.15}, {0.0002, 0.0028, 0.0163},
    },
    {
        "Ketchup", {0.18, 0.07, 0.03}, {0.061, 0.97, 1.45},
    },
    {
        "Marble", {2.19, 2.62, 3.00}, {0.0021, 0.0041, 0.0071},
    },
    {
        "Potato", {0.68, 0.70, 0.55}, {0.0024, 0.0090, 0.12},
    },
    {
        "Skimmilk", {0.70, 1.22, 1.90}, {0.0014, 0.0025, 0.0142},
    },
    {
        "Skin1", {0.74, 0.88, 1.01}, {0.032, 0.17, 0.48},
    },
    {
        "Skin2", {1.09, 1.59, 1.79}, {0.013, 0.070, 0.145},
    },
    {
        "Spectralon", {11.6, 20.4, 14.9}, {0.00, 0.00, 0.00},
    },
    {
        "Wholemilk", {2.55, 3.21, 3.77}, {0.0011, 0.0024, 0.014},
    },

    // From "Acquiring Scattering Properties of Participating Media by
    // Dilution",
    // Narasimhan, Gupta, Donner, Ramamoorthi, Nayar, Jensen
    // Proc SIGGRAPH 2006
    {"Lowfat Milk", {0.89187, 1.5136, 2.532}, {0.002875, 0.00575, 0.0115}},
    {"Reduced Milk",
     {2.4858, 3.1669, 4.5214},
     {0.0025556, 0.0051111, 0.012778}},
    {"Regular Milk", {4.5513, 5.8294, 7.136}, {0.0015333, 0.0046, 0.019933}},
    {"Espresso", {0.72378, 0.84557, 1.0247}, {4.7984, 6.5751, 8.8493}},
    {"Mint Mocha Coffee", {0.31602, 0.38538, 0.48131}, {3.772, 5.8228, 7.82}},
    {"Lowfat Soy Milk",
     {0.30576, 0.34233, 0.61664},
     {0.0014375, 0.0071875, 0.035937}},
    {"Regular Soy Milk",
     {0.59223, 0.73866, 1.4693},
     {0.0019167, 0.0095833, 0.065167}},
    {"Lowfat Chocolate Milk",
     {0.64925, 0.83916, 1.1057},
     {0.0115, 0.0368, 0.1564}},
    {"Regular Chocolate Milk",
     {1.4585, 2.1289, 2.9527},
     {0.010063, 0.043125, 0.14375}},
    {"Coke", {8.9053e-05, 8.372e-05, 0}, {0.10014, 0.16503, 0.2468}},
    {"Pepsi", {6.1697e-05, 4.2564e-05, 0}, {0.091641, 0.14158, 0.20729}},
    {"Sprite",
     {6.0306e-06, 6.4139e-06, 6.5504e-06},
     {0.001886, 0.0018308, 0.0020025}},
    {"Gatorade",
     {0.0024574, 0.003007, 0.0037325},
     {0.024794, 0.019289, 0.008878}},
    {"Chardonnay",
     {1.7982e-05, 1.3758e-05, 1.2023e-05},
     {0.010782, 0.011855, 0.023997}},
    {"White Zinfandel",
     {1.7501e-05, 1.9069e-05, 1.288e-05},
     {0.012072, 0.016184, 0.019843}},
    {"Merlot", {2.1129e-05, 0, 0}, {0.11632, 0.25191, 0.29434}},
    {"Budweiser Beer",
     {2.4356e-05, 2.4079e-05, 1.0564e-05},
     {0.011492, 0.024911, 0.057786}},
    {"Coors Light Beer",
     {5.0922e-05, 4.301e-05, 0},
     {0.006164, 0.013984, 0.034983}},
    {"Clorox",
     {0.0024035, 0.0031373, 0.003991},
     {0.0033542, 0.014892, 0.026297}},
    {"Apple Juice",
     {0.00013612, 0.00015836, 0.000227},
     {0.012957, 0.023741, 0.052184}},
    {"Cranberry Juice",
     {0.00010402, 0.00011646, 7.8139e-05},
     {0.039437, 0.094223, 0.12426}},
    {"Grape Juice", {5.382e-05, 0, 0}, {0.10404, 0.23958, 0.29325}},
    {"Ruby Grapefruit Juice",
     {0.011002, 0.010927, 0.011036},
     {0.085867, 0.18314, 0.25262}},
    {"White Grapefruit Juice",
     {0.22826, 0.23998, 0.32748},
     {0.0138, 0.018831, 0.056781}},
    {"Shampoo",
     {0.0007176, 0.0008303, 0.0009016},
     {0.014107, 0.045693, 0.061717}},
    {"Strawberry Shampoo",
     {0.00015671, 0.00015947, 1.518e-05},
     {0.01449, 0.05796, 0.075823}},
    {"Head & Shoulders Shampoo",
     {0.023805, 0.028804, 0.034306},
     {0.084621, 0.15688, 0.20365}},
    {"Lemon Tea Powder",
     {0.040224, 0.045264, 0.051081},
     {2.4288, 4.5757, 7.2127}},
    {"Orange Powder",
     {0.00015617, 0.00017482, 0.0001762},
     {0.001449, 0.003441, 0.007863}},
    {"Pink Lemonade Powder",
     {0.00012103, 0.00013073, 0.00012528},
     {0.001165, 0.002366, 0.003195}},
    {"Cappuccino Powder", {1.8436, 2.5851, 2.1662}, {35.844, 49.547, 61.084}},
    {"Salt Powder", {0.027333, 0.032451, 0.031979}, {0.28415, 0.3257, 0.34148}},
    {"Sugar Powder",
     {0.00022272, 0.00025513, 0.000271},
     {0.012638, 0.031051, 0.050124}},
    {"Suisse Mocha Powder", {2.7979, 3.5452, 4.3365}, {17.502, 27.004, 35.433}},
    {"Pacific Ocean Surface Water",
     {0.0001764, 0.00032095, 0.00019617},
     {0.031845, 0.031324, 0.030147}}};

// Media Definitions
PhaseFunction::~PhaseFunction() { }

bool GetMediumScatteringProperties(const std::string &name, Spectrum *sigma_a,
                                   Spectrum *sigma_prime_s) {
    for (MeasuredSS &mss : SubsurfaceParameterTable) {
        if (name == mss.name) {
            *sigma_a = Spectrum::FromRGB(mss.sigma_a);
            *sigma_prime_s = Spectrum::FromRGB(mss.sigma_prime_s);
            return true;
        }
    }
    return false;
}

// HenyeyGreenstein Method Definitions
Float HenyeyGreenstein::Sample_p(const Vector3f &wo, Vector3f *wi,
                                 const Point2f &u) const {
    ProfilePhase _(Prof::PhaseFuncSampling);
    // Compute $\cos \theta$ for Henyey--Greenstein sample
    Float cosTheta;
    if (std::abs(g) < 1e-3)
        cosTheta = 1 - 2 * u[0];
    else {
        Float sqrTerm = (1 - g * g) / (1 + g - 2 * g * u[0]);
        cosTheta = -(1 + g * g - sqrTerm * sqrTerm) / (2 * g);
    }

    // Compute direction _wi_ for Henyey--Greenstein sample
    Float sinTheta = std::sqrt(std::max((Float)0, 1 - cosTheta * cosTheta));
    Float phi = 2 * Pi * u[1];
    Vector3f v1, v2;
    CoordinateSystem(wo, &v1, &v2);
    *wi = SphericalDirection(sinTheta, cosTheta, phi, v1, v2, wo);
    return PhaseHG(cosTheta, g);
}

Float HenyeyGreenstein::p(const Vector3f &wo, const Vector3f &wi) const {
    ProfilePhase _(Prof::PhaseFuncEvaluation);
    return PhaseHG(Dot(wo, wi), g);
}

}  // namespace pbrt
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkConeSource.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkConeSource.h"

#include "vtkFloatArray.h"
#include "vtkMath.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkPolyData.h"
#include "vtkTransform.h"
#include "vtkCellArray.h"

#include <math.h>

vtkCxxRevisionMacro(vtkConeSource, "1.72");
vtkStandardNewMacro(vtkConeSource);

//----------------------------------------------------------------------------
// Construct with default resolution 6, height 1.0, radius 0.5, and capping
// on.
vtkConeSource::vtkConeSource(int res)
{
  res = (res < 0 ? 0 : res);
  this->Resolution = res;
  this->Height = 1.0;
  this->Radius = 0.5;
  this->Capping = 1;

  this->Center[0] = 0.0;
  this->Center[1] = 0.0;
  this->Center[2] = 0.0;

  this->Direction[0] = 1.0;
  this->Direction[1] = 0.0;
  this->Direction[2] = 0.0;

  this->SetNumberOfInputPorts(0);
}

//----------------------------------------------------------------------------
int vtkConeSource::RequestData(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **vtkNotUsed(inputVector),
  vtkInformationVector *outputVector)
{
  // get the info objects
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  double angle;
  int numLines, numPolys, numPts;
  double x[3], xbot;
  int i;
  vtkIdType pts[VTK_CELL_SIZE];
  vtkPoints *newPoints;
  vtkCellArray *newLines=0;
  vtkCellArray *newPolys=0;
  vtkPolyData *output = vtkPolyData::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));
  // for streaming
  int piece;
  int numPieces;
  int maxPieces;
  int start, end;
  int createBottom;

  piece = output->GetUpdatePiece();
  if (piece >= this->Resolution)
    {
    return 1;
    }
  numPieces = output->GetUpdateNumberOfPieces();
  maxPieces = this->Resolution != 0 ? this->Resolution : 1;
  if (numPieces > maxPieces)
    {
    numPieces = maxPieces;
    }
  if (piece >= maxPieces)
    {
    // Super class should do this for us,
    // but I put this condition in any way.
    return 1;
    }
  start = maxPieces * piece / numPieces;
  end = (maxPieces * (piece+1) / numPieces) - 1;
  createBottom = (this->Capping && (start == 0));

  vtkDebugMacro("ConeSource Executing");

  if ( this->Resolution )
    {
    angle = 2.0*3.141592654/this->Resolution;
    }
  else
    {
    angle = 0.0;
    }

  // Set things up; allocate memory
  //
  switch ( this->Resolution )
  {
  case 0:
    numPts = 2;
    numLines =  1;
    newLines = vtkCellArray::New();
    newLines->Allocate(newLines->EstimateSize(numLines,numPts));
    break;

  case 1: case 2:
    numPts = 2*this->Resolution + 1;
    numPolys = this->Resolution;
    newPolys = vtkCellArray::New();
    newPolys->Allocate(newPolys->EstimateSize(numPolys,3));
    break;

  default:
    if (createBottom)
      {
      // piece 0 has cap.
      numPts = this->Resolution + 1;
      numPolys = end - start + 2;
      }
    else
      {
      numPts = end - start + 3;
      numPolys = end - start + 2;
      }
    newPolys = vtkCellArray::New();
    newPolys->Allocate(newPolys->EstimateSize(numPolys,this->Resolution));
    break;
  }
  newPoints = vtkPoints::New();
  newPoints->SetDataTypeToFloat(); //used later during transformation
  newPoints->Allocate(numPts);

  // Create cone
  //
  x[0] = this->Height / 2.0; // zero-centered
  x[1] = 0.0;
  x[2] = 0.0;
  pts[0] = newPoints->InsertNextPoint(x);

  xbot = -this->Height / 2.0;

  switch (this->Resolution)
  {
  case 0:
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = 0.0;
    pts[1] = newPoints->InsertNextPoint(x);
    newLines->InsertNextCell(2,pts);
    break;

  case 2:  // fall through this case to use the code in case 1
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = -this->Radius;
    pts[1] = newPoints->InsertNextPoint(x);
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = this->Radius;
    pts[2] = newPoints->InsertNextPoint(x);
    newPolys->InsertNextCell(3,pts);

  case 1:
    x[0] = xbot;
    x[1] = -this->Radius;
    x[2] = 0.0;
    pts[1] = newPoints->InsertNextPoint(x);
    x[0] = xbot;
    x[1] = this->Radius;
    x[2] = 0.0;
    pts[2] = newPoints->InsertNextPoint(x);
    newPolys->InsertNextCell(3,pts);
    break;

  default: // General case: create Resolution triangles and single cap
    // create the bottom.
    if ( createBottom )
      {
      for (i=0; i < this->Resolution; i++)
        {
        x[0] = xbot;
        x[1] = this->Radius * cos ((double)i*angle);
        x[2] = this->Radius * sin ((double)i*angle);
        // Reverse the order
        pts[this->Resolution - i - 1] = newPoints->InsertNextPoint(x);
        }
      newPolys->InsertNextCell(this->Resolution,pts);
      }

    pts[0] = 0;
    if ( ! createBottom)
      {
      // we need to create the points also
      x[0] = xbot;
      x[1] = this->Radius * cos ((double)start*angle);
      x[2] = this->Radius * sin ((double)start*angle);
      pts[1] = newPoints->InsertNextPoint(x);
      for (i = start; i <= end; ++i)
        {
        x[1] = this->Radius * cos ((double)(i+1)*angle);
        x[2] = this->Radius * sin ((double)(i+1)*angle);
        pts[2] = newPoints->InsertNextPoint(x);
        newPolys->InsertNextCell(3,pts);
        pts[1] = pts[2];
        }
      }
    else
      {
      // bottom and points have already been created.
      for (i=start; i <= end; i++)
        {
        pts[1] = i+1;
        pts[2] = i+2;
        if (pts[2] > this->Resolution)
          {
          pts[2] = 1;
          }
        newPolys->InsertNextCell(3,pts);
        }
      } // createBottom

  } //switch

  // A non-default origin and/or direction requires transformation
  //
  if ( this->Center[0] != 0.0 || this->Center[1] != 0.0 ||
       this->Center[2] != 0.0 || this->Direction[0] != 1.0 ||
       this->Direction[1] != 0.0 || this->Direction[2] != 0.0 )
    {
    vtkTransform *t = vtkTransform::New();
    t->Translate(this->Center[0], this->Center[1], this->Center[2]);
    double vMag = vtkMath::Norm(this->Direction);
    if ( this->Direction[0] < 0.0 &&
         this->Direction[1] == 0.0 &&
         this->Direction[2] == 0.0 )
      {
      // just flip x
      t->RotateWXYZ(180.0,0,1,0);
      }
    else
      {
      t->RotateWXYZ((double)180.0, (this->Direction[0]+vMag)/2.0,
                    this->Direction[1]/2.0, this->Direction[2]/2.0);
      }
    float *ipts = ((vtkFloatArray *)newPoints->GetData())->GetPointer(0);
    for (i=0; i<numPts; i++, ipts+=3)
      {
      t->TransformPoint(ipts,ipts);
      }

    t->Delete();
    }

  // Update ourselves
  //
  output->SetPoints(newPoints);
  newPoints->Delete();

  if ( newPolys )
    {
    newPolys->Squeeze(); // we may have estimated size; reclaim some space
    output->SetPolys(newPolys);
    newPolys->Delete();
    }
  else
    {
    output->SetLines(newLines);
    newLines->Delete();
    }

  return 1;
}

//----------------------------------------------------------------------------
int vtkConeSource::RequestInformation(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **vtkNotUsed(inputVector),
  vtkInformationVector *outputVector)
{
  vtkInformation *outInfo = outputVector->GetInformationObject(0);
  outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),
               -1);
  return 1;
}

//----------------------------------------------------------------------------
void vtkConeSource::SetAngle(double angle)
{
  this->SetRadius (this->Height * tan ((double) angle*vtkMath::DegreesToRadians()));
}

//----------------------------------------------------------------------------
double vtkConeSource::GetAngle()
{
  return atan2 (this->Radius, this->Height) / vtkMath::DegreesToRadians();
}

//----------------------------------------------------------------------------
void vtkConeSource::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Resolution: " << this->Resolution << "\n";
  os << indent << "Height: " << this->Height << "\n";
  os << indent << "Radius: " << this->Radius << "\n";
  os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n");
  os << indent << "Center: (" << this->Center[0] << ", "
     << this->Center[1] << ", " << this->Center[2] << ")\n";
  os << indent << "Direction: (" << this->Direction[0] << ", "
     << this->Direction[1] << ", " << this->Direction[2] << ")\n";
}
<commit_msg>BUG: Setting Resolution to 0 should produce a line, not an empty output. (bug #2112)<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkConeSource.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkConeSource.h"

#include "vtkFloatArray.h"
#include "vtkMath.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkPolyData.h"
#include "vtkTransform.h"
#include "vtkCellArray.h"

#include <math.h>

vtkCxxRevisionMacro(vtkConeSource, "1.72.8.1");
vtkStandardNewMacro(vtkConeSource);

//----------------------------------------------------------------------------
// Construct with default resolution 6, height 1.0, radius 0.5, and capping
// on.
vtkConeSource::vtkConeSource(int res)
{
  res = (res < 0 ? 0 : res);
  this->Resolution = res;
  this->Height = 1.0;
  this->Radius = 0.5;
  this->Capping = 1;

  this->Center[0] = 0.0;
  this->Center[1] = 0.0;
  this->Center[2] = 0.0;

  this->Direction[0] = 1.0;
  this->Direction[1] = 0.0;
  this->Direction[2] = 0.0;

  this->SetNumberOfInputPorts(0);
}

//----------------------------------------------------------------------------
int vtkConeSource::RequestData(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **vtkNotUsed(inputVector),
  vtkInformationVector *outputVector)
{
  // get the info objects
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  double angle;
  int numLines, numPolys, numPts;
  double x[3], xbot;
  int i;
  vtkIdType pts[VTK_CELL_SIZE];
  vtkPoints *newPoints;
  vtkCellArray *newLines=0;
  vtkCellArray *newPolys=0;
  vtkPolyData *output = vtkPolyData::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));
  // for streaming
  int piece;
  int numPieces;
  int maxPieces;
  int start, end;
  int createBottom;

  piece = output->GetUpdatePiece();
  if (piece >= this->Resolution && !(piece == 0 && this->Resolution == 0))
    {
    return 1;
    }
  numPieces = output->GetUpdateNumberOfPieces();
  maxPieces = this->Resolution != 0 ? this->Resolution : 1;
  if (numPieces > maxPieces)
    {
    numPieces = maxPieces;
    }
  if (piece >= maxPieces)
    {
    // Super class should do this for us,
    // but I put this condition in any way.
    return 1;
    }
  start = maxPieces * piece / numPieces;
  end = (maxPieces * (piece+1) / numPieces) - 1;
  createBottom = (this->Capping && (start == 0));

  vtkDebugMacro("ConeSource Executing");

  if ( this->Resolution )
    {
    angle = 2.0*3.141592654/this->Resolution;
    }
  else
    {
    angle = 0.0;
    }

  // Set things up; allocate memory
  //
  switch ( this->Resolution )
  {
  case 0:
    numPts = 2;
    numLines =  1;
    newLines = vtkCellArray::New();
    newLines->Allocate(newLines->EstimateSize(numLines,numPts));
    break;

  case 1: case 2:
    numPts = 2*this->Resolution + 1;
    numPolys = this->Resolution;
    newPolys = vtkCellArray::New();
    newPolys->Allocate(newPolys->EstimateSize(numPolys,3));
    break;

  default:
    if (createBottom)
      {
      // piece 0 has cap.
      numPts = this->Resolution + 1;
      numPolys = end - start + 2;
      }
    else
      {
      numPts = end - start + 3;
      numPolys = end - start + 2;
      }
    newPolys = vtkCellArray::New();
    newPolys->Allocate(newPolys->EstimateSize(numPolys,this->Resolution));
    break;
  }
  newPoints = vtkPoints::New();
  newPoints->SetDataTypeToFloat(); //used later during transformation
  newPoints->Allocate(numPts);

  // Create cone
  //
  x[0] = this->Height / 2.0; // zero-centered
  x[1] = 0.0;
  x[2] = 0.0;
  pts[0] = newPoints->InsertNextPoint(x);

  xbot = -this->Height / 2.0;

  switch (this->Resolution)
  {
  case 0:
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = 0.0;
    pts[1] = newPoints->InsertNextPoint(x);
    newLines->InsertNextCell(2,pts);
    break;

  case 2:  // fall through this case to use the code in case 1
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = -this->Radius;
    pts[1] = newPoints->InsertNextPoint(x);
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = this->Radius;
    pts[2] = newPoints->InsertNextPoint(x);
    newPolys->InsertNextCell(3,pts);

  case 1:
    x[0] = xbot;
    x[1] = -this->Radius;
    x[2] = 0.0;
    pts[1] = newPoints->InsertNextPoint(x);
    x[0] = xbot;
    x[1] = this->Radius;
    x[2] = 0.0;
    pts[2] = newPoints->InsertNextPoint(x);
    newPolys->InsertNextCell(3,pts);
    break;

  default: // General case: create Resolution triangles and single cap
    // create the bottom.
    if ( createBottom )
      {
      for (i=0; i < this->Resolution; i++)
        {
        x[0] = xbot;
        x[1] = this->Radius * cos ((double)i*angle);
        x[2] = this->Radius * sin ((double)i*angle);
        // Reverse the order
        pts[this->Resolution - i - 1] = newPoints->InsertNextPoint(x);
        }
      newPolys->InsertNextCell(this->Resolution,pts);
      }

    pts[0] = 0;
    if ( ! createBottom)
      {
      // we need to create the points also
      x[0] = xbot;
      x[1] = this->Radius * cos ((double)start*angle);
      x[2] = this->Radius * sin ((double)start*angle);
      pts[1] = newPoints->InsertNextPoint(x);
      for (i = start; i <= end; ++i)
        {
        x[1] = this->Radius * cos ((double)(i+1)*angle);
        x[2] = this->Radius * sin ((double)(i+1)*angle);
        pts[2] = newPoints->InsertNextPoint(x);
        newPolys->InsertNextCell(3,pts);
        pts[1] = pts[2];
        }
      }
    else
      {
      // bottom and points have already been created.
      for (i=start; i <= end; i++)
        {
        pts[1] = i+1;
        pts[2] = i+2;
        if (pts[2] > this->Resolution)
          {
          pts[2] = 1;
          }
        newPolys->InsertNextCell(3,pts);
        }
      } // createBottom

  } //switch

  // A non-default origin and/or direction requires transformation
  //
  if ( this->Center[0] != 0.0 || this->Center[1] != 0.0 ||
       this->Center[2] != 0.0 || this->Direction[0] != 1.0 ||
       this->Direction[1] != 0.0 || this->Direction[2] != 0.0 )
    {
    vtkTransform *t = vtkTransform::New();
    t->Translate(this->Center[0], this->Center[1], this->Center[2]);
    double vMag = vtkMath::Norm(this->Direction);
    if ( this->Direction[0] < 0.0 &&
         this->Direction[1] == 0.0 &&
         this->Direction[2] == 0.0 )
      {
      // just flip x
      t->RotateWXYZ(180.0,0,1,0);
      }
    else
      {
      t->RotateWXYZ((double)180.0, (this->Direction[0]+vMag)/2.0,
                    this->Direction[1]/2.0, this->Direction[2]/2.0);
      }
    float *ipts = ((vtkFloatArray *)newPoints->GetData())->GetPointer(0);
    for (i=0; i<numPts; i++, ipts+=3)
      {
      t->TransformPoint(ipts,ipts);
      }

    t->Delete();
    }

  // Update ourselves
  //
  output->SetPoints(newPoints);
  newPoints->Delete();

  if ( newPolys )
    {
    newPolys->Squeeze(); // we may have estimated size; reclaim some space
    output->SetPolys(newPolys);
    newPolys->Delete();
    }
  else
    {
    output->SetLines(newLines);
    newLines->Delete();
    }

  return 1;
}

//----------------------------------------------------------------------------
int vtkConeSource::RequestInformation(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **vtkNotUsed(inputVector),
  vtkInformationVector *outputVector)
{
  vtkInformation *outInfo = outputVector->GetInformationObject(0);
  outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),
               -1);
  return 1;
}

//----------------------------------------------------------------------------
void vtkConeSource::SetAngle(double angle)
{
  this->SetRadius (this->Height * tan ((double) angle*vtkMath::DegreesToRadians()));
}

//----------------------------------------------------------------------------
double vtkConeSource::GetAngle()
{
  return atan2 (this->Radius, this->Height) / vtkMath::DegreesToRadians();
}

//----------------------------------------------------------------------------
void vtkConeSource::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Resolution: " << this->Resolution << "\n";
  os << indent << "Height: " << this->Height << "\n";
  os << indent << "Radius: " << this->Radius << "\n";
  os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n");
  os << indent << "Center: (" << this->Center[0] << ", "
     << this->Center[1] << ", " << this->Center[2] << ")\n";
  os << indent << "Direction: (" << this->Direction[0] << ", "
     << this->Direction[1] << ", " << this->Direction[2] << ")\n";
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkStreamLine.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

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 AUTHORS 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.

=========================================================================*/
#include "vtkStreamLine.h"
#include "vtkObjectFactory.h"
#include "vtkPolyLine.h"
#include "vtkFloatArray.h"
#include "vtkMath.h"
#include "vtkFloatArray.h"

//----------------------------------------------------------------------------
vtkStreamLine* vtkStreamLine::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkStreamLine");
  if(ret)
    {
    return (vtkStreamLine*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkStreamLine;
}

// Construct object with step size set to 1.0.
vtkStreamLine::vtkStreamLine()
{
  this->StepLength = 1.0;
  this->NumberOfStreamers = 0;
}

void vtkStreamLine::Execute()
{
  vtkStreamPoint *sPrev, *sPtr;
  vtkPoints *newPts;
  vtkFloatArray *newVectors;
  vtkFloatArray *newScalars=NULL;
  vtkCellArray *newLines;
  vtkIdType ptId, i, id;
  int j;
  vtkIdList *pts;
  float tOffset, x[3], v[3], s, r;
  float theta;
  vtkPolyLine* lineNormalGenerator = NULL;
  vtkFloatArray* normals = NULL;
  vtkFloatArray* rotation = 0;
  vtkPolyData *output=this->GetOutput();
  vtkFieldData *fd;

  this->SavePointInterval = this->StepLength;
  this->vtkStreamer::Integrate();
  if ( this->NumberOfStreamers <= 0 ) {return;}

  //fd = vtkFieldData::New();
  fd = output->GetPointData()->GetFieldData();

  pts = vtkIdList::New();
  pts->Allocate(2500);

  //
  //  Convert streamer into lines. Lines may be dashed.
  //
  newPts  = vtkPoints::New();
  newPts->Allocate(1000);
  newVectors  = vtkFloatArray::New();
  newVectors->SetNumberOfComponents(3);
  newVectors->Allocate(3000);
  if ( this->Vorticity )
    {
    lineNormalGenerator = vtkPolyLine::New();
    normals = vtkFloatArray::New();
    normals->SetNumberOfComponents(3);
    normals->Allocate(3000);
    rotation = vtkFloatArray::New();
    rotation->SetNumberOfComponents(1);
    rotation->Allocate(1000);
    rotation->SetName("Thetas");
    fd->AddArray(rotation);
    }

  if ( this->GetInput()->GetPointData()->GetScalars() || this->SpeedScalars
    || this->OrientationScalars)
    {
    newScalars = vtkFloatArray::New();
    newScalars->Allocate(1000);
    }
  newLines = vtkCellArray::New();
  newLines->Allocate(newLines->EstimateSize(2*this->NumberOfStreamers,
					    VTK_CELL_SIZE));
  //
  // Loop over all streamers generating points
  //
  for (ptId=0; ptId < this->NumberOfStreamers; ptId++)
    {
    if ( this->Streamers[ptId].GetNumberOfPoints() < 2 )
      {
      continue;
      }
    sPrev = this->Streamers[ptId].GetStreamPoint(0);
    sPtr = this->Streamers[ptId].GetStreamPoint(1);

    if ( this->Streamers[ptId].GetNumberOfPoints() == 2 && sPtr->cellId >= 0 )
      {
      continue;
      }

    tOffset = sPrev->t;

    for ( i=1;
    i < this->Streamers[ptId].GetNumberOfPoints() && sPtr->cellId >= 0;
    i++, sPrev=sPtr, sPtr=this->Streamers[ptId].GetStreamPoint(i) )
      {
      //
      // Create points for line
      //
      while ( tOffset >= sPrev->t && tOffset < sPtr->t )
        {
        r = (tOffset - sPrev->t) / (sPtr->t - sPrev->t);

        for (j=0; j<3; j++)
          {
          x[j] = sPrev->x[j] + r * (sPtr->x[j] - sPrev->x[j]);
          v[j] = sPrev->v[j] + r * (sPtr->v[j] - sPrev->v[j]);
          }

        // add point to line
        id = newPts->InsertNextPoint(x);
        pts->InsertNextId(id);
        newVectors->InsertTuple(id,v);

        if ( newScalars )
          {
          s = sPrev->s + r * (sPtr->s - sPrev->s);
          newScalars->InsertTuple(id,&s);
          }

	if ( this->Vorticity )
	  {
	  // Store the rotation values. Used after all the streamlines
	  // are generated.
	  theta = sPrev->theta + r * (sPtr->theta - sPrev->theta);
	  rotation->InsertTuple(id, &theta);
	  }

        tOffset += this->StepLength;

        } // while
      } //for this streamer

    if ( pts->GetNumberOfIds() > 1 )
      {
      newLines->InsertNextCell(pts);
      pts->Reset();
      }
    } //for all streamers

  vtkDebugMacro(<<"Created " << newPts->GetNumberOfPoints() << " points, "
               << newLines->GetNumberOfCells() << " lines");

  if (this->Vorticity)
    {
    // Rotate the normal vectors with stream vorticity
    int nPts=newPts->GetNumberOfPoints();
    float normal[3], local1[3], local2[3], length, costheta, sintheta;

    lineNormalGenerator->GenerateSlidingNormals(newPts,newLines,normals);

    for(i=0; i<nPts; i++)
      {
      normals->GetTuple(i, normal);
      newVectors->GetTuple(i, v);
      // obtain two unit orthogonal vectors on the plane perpendicular to
      // the streamline
      for(j=0; j<3; j++) { local1[j] = normal[j]; }
      length = vtkMath::Normalize(local1);
      vtkMath::Cross(local1, v, local2);
      vtkMath::Normalize(local2);
      // Rotate the normal with theta
      rotation->GetTuple(i, &theta);
      costheta = cos(theta);
      sintheta = sin(theta);
      for(j=0; j<3; j++)
	{
	normal[j] = length* (costheta*local1[j] + sintheta*local2[j]);
	}
      normals->SetTuple(i, normal);
      }
    output->GetPointData()->SetNormals(normals);
    normals->Delete();
    lineNormalGenerator->Delete();
    rotation->Delete();
    }

  output->SetPoints(newPts);
  newPts->Delete();

  output->GetPointData()->SetVectors(newVectors);
  newVectors->Delete();

  if ( newScalars )
    {
    output->GetPointData()->SetScalars(newScalars);
    newScalars->Delete();
    }

  pts->Delete();
  output->SetLines(newLines);
  newLines->Delete();

  // Delete the streamers since they are no longer needed
  delete[] this->Streamers;
  this->Streamers = 0;
  this->NumberOfStreamers = 0;

  //output->SetFieldData(fd);
  //fd->Delete();

  output->Squeeze();
}

void vtkStreamLine::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkStreamer::PrintSelf(os,indent);

  os << indent << "Step Length: " << this->StepLength << "\n";

}

<commit_msg>ERR:Reformatted<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkStreamLine.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

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 AUTHORS 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.

=========================================================================*/
#include "vtkStreamLine.h"
#include "vtkObjectFactory.h"
#include "vtkPolyLine.h"
#include "vtkFloatArray.h"
#include "vtkMath.h"
#include "vtkFloatArray.h"

//----------------------------------------------------------------------------
vtkStreamLine* vtkStreamLine::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkStreamLine");
  if(ret)
    {
    return (vtkStreamLine*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkStreamLine;
}

// Construct object with step size set to 1.0.
vtkStreamLine::vtkStreamLine()
{
  this->StepLength = 1.0;
  this->NumberOfStreamers = 0;
}

void vtkStreamLine::Execute()
{
  vtkStreamPoint *sPrev, *sPtr;
  vtkPoints *newPts;
  vtkFloatArray *newVectors;
  vtkFloatArray *newScalars=NULL;
  vtkCellArray *newLines;
  vtkIdType ptId, i, id;
  int j;
  vtkIdList *pts;
  float tOffset, x[3], v[3], s, r;
  float theta;
  vtkPolyLine* lineNormalGenerator = NULL;
  vtkFloatArray* normals = NULL;
  vtkFloatArray* rotation = 0;
  vtkPolyData *output=this->GetOutput();
  vtkFieldData *fd;

  this->SavePointInterval = this->StepLength;
  this->vtkStreamer::Integrate();
  if ( this->NumberOfStreamers <= 0 ) {return;}

  //fd = vtkFieldData::New();
  fd = output->GetPointData()->GetFieldData();

  pts = vtkIdList::New();
  pts->Allocate(2500);

  //
  //  Convert streamer into lines. Lines may be dashed.
  //
  newPts  = vtkPoints::New();
  newPts->Allocate(1000);
  newVectors  = vtkFloatArray::New();
  newVectors->SetNumberOfComponents(3);
  newVectors->Allocate(3000);
  if ( this->Vorticity )
    {
    lineNormalGenerator = vtkPolyLine::New();
    normals = vtkFloatArray::New();
    normals->SetNumberOfComponents(3);
    normals->Allocate(3000);
    rotation = vtkFloatArray::New();
    rotation->SetNumberOfComponents(1);
    rotation->Allocate(1000);
    rotation->SetName("Thetas");
    fd->AddArray(rotation);
    }

  if ( this->GetInput()->GetPointData()->GetScalars() || this->SpeedScalars
    || this->OrientationScalars)
    {
    newScalars = vtkFloatArray::New();
    newScalars->Allocate(1000);
    }
  newLines = vtkCellArray::New();
  newLines->Allocate(newLines->EstimateSize(2*this->NumberOfStreamers,
                                            VTK_CELL_SIZE));
  //
  // Loop over all streamers generating points
  //
  for (ptId=0; ptId < this->NumberOfStreamers; ptId++)
    {
    if ( this->Streamers[ptId].GetNumberOfPoints() < 2 )
      {
      continue;
      }
    sPrev = this->Streamers[ptId].GetStreamPoint(0);
    sPtr = this->Streamers[ptId].GetStreamPoint(1);

    if ( this->Streamers[ptId].GetNumberOfPoints() == 2 && sPtr->cellId >= 0 )
      {
      continue;
      }

    tOffset = sPrev->t;

    for ( i=1;
    i < this->Streamers[ptId].GetNumberOfPoints() && sPtr->cellId >= 0;
    i++, sPrev=sPtr, sPtr=this->Streamers[ptId].GetStreamPoint(i) )
      {
      //
      // Create points for line
      //
      while ( tOffset >= sPrev->t && tOffset < sPtr->t )
        {
        r = (tOffset - sPrev->t) / (sPtr->t - sPrev->t);

        for (j=0; j<3; j++)
          {
          x[j] = sPrev->x[j] + r * (sPtr->x[j] - sPrev->x[j]);
          v[j] = sPrev->v[j] + r * (sPtr->v[j] - sPrev->v[j]);
          }

        // add point to line
        id = newPts->InsertNextPoint(x);
        pts->InsertNextId(id);
        newVectors->InsertTuple(id,v);

        if ( newScalars )
          {
          s = sPrev->s + r * (sPtr->s - sPrev->s);
          newScalars->InsertTuple(id,&s);
          }

        if ( this->Vorticity )
          {
          // Store the rotation values. Used after all the streamlines
          // are generated.
          theta = sPrev->theta + r * (sPtr->theta - sPrev->theta);
          rotation->InsertTuple(id, &theta);
          }

        tOffset += this->StepLength;

        } // while
      } //for this streamer

    if ( pts->GetNumberOfIds() > 1 )
      {
      newLines->InsertNextCell(pts);
      pts->Reset();
      }
    } //for all streamers

  vtkDebugMacro(<<"Created " << newPts->GetNumberOfPoints() << " points, "
               << newLines->GetNumberOfCells() << " lines");

  if (this->Vorticity)
    {
    // Rotate the normal vectors with stream vorticity
    int nPts=newPts->GetNumberOfPoints();
    float normal[3], local1[3], local2[3], length, costheta, sintheta;

    lineNormalGenerator->GenerateSlidingNormals(newPts,newLines,normals);

    for(i=0; i<nPts; i++)
      {
      normals->GetTuple(i, normal);
      newVectors->GetTuple(i, v);
      // obtain two unit orthogonal vectors on the plane perpendicular to
      // the streamline
      for(j=0; j<3; j++) { local1[j] = normal[j]; }
      length = vtkMath::Normalize(local1);
      vtkMath::Cross(local1, v, local2);
      vtkMath::Normalize(local2);
      // Rotate the normal with theta
      rotation->GetTuple(i, &theta);
      costheta = cos(theta);
      sintheta = sin(theta);
      for(j=0; j<3; j++)
        {
        normal[j] = length* (costheta*local1[j] + sintheta*local2[j]);
        }
      normals->SetTuple(i, normal);
      }
    output->GetPointData()->SetNormals(normals);
    normals->Delete();
    lineNormalGenerator->Delete();
    rotation->Delete();
    }

  output->SetPoints(newPts);
  newPts->Delete();

  output->GetPointData()->SetVectors(newVectors);
  newVectors->Delete();

  if ( newScalars )
    {
    output->GetPointData()->SetScalars(newScalars);
    newScalars->Delete();
    }

  pts->Delete();
  output->SetLines(newLines);
  newLines->Delete();

  // Delete the streamers since they are no longer needed
  delete[] this->Streamers;
  this->Streamers = 0;
  this->NumberOfStreamers = 0;

  //output->SetFieldData(fd);
  //fd->Delete();

  output->Squeeze();
}

void vtkStreamLine::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkStreamer::PrintSelf(os,indent);

  os << indent << "Step Length: " << this->StepLength << "\n";

}

<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 1999-2007 Gunnar Raetsch
 * Written (W) 1999-2007 Soeren Sonnenburg
 * Copyright (C) 1999-2007 Fraunhofer Institute FIRST and Max-Planck-Society
 */

#include "lib/common.h"
#include "lib/io.h"
#include "kernel/LocalityImprovedStringKernel.h"
#include "features/Features.h"
#include "features/StringFeatures.h"

CLocalityImprovedStringKernel::CLocalityImprovedStringKernel(LONG size, INT l, INT d1, INT d2)
  : CStringKernel<CHAR>(size),length(l),inner_degree(d1),outer_degree(d2),match(NULL)
{
	SG_INFO( "LIK with parms: l=%d, d1=%d, d2=%d created!\n", l, d1, d2);
}

CLocalityImprovedStringKernel::~CLocalityImprovedStringKernel()
{
	cleanup();
}

bool CLocalityImprovedStringKernel::init(CFeatures* l, CFeatures* r)
{
	bool result = CStringKernel<CHAR>::init(l,r);

	if (!result)
		return false;
	match = new CHAR[((CStringFeatures<CHAR>*) l)->get_max_vector_length()];
	return match? true : false;
}

void CLocalityImprovedStringKernel::cleanup()
{
	delete[] match;
	match = NULL;
}

bool CLocalityImprovedStringKernel::load_init(FILE* src)
{
	return false;
}

bool CLocalityImprovedStringKernel::save_init(FILE* dest)
{
	return false;
}

DREAL CLocalityImprovedStringKernel::compute(INT idx_a, INT idx_b)
{
	INT alen, blen;

	CHAR* avec=((CStringFeatures<CHAR>*) lhs)->get_feature_vector(idx_a, alen);
	CHAR* bvec=((CStringFeatures<CHAR>*) rhs)->get_feature_vector(idx_b, blen);

	// can only deal with strings of same length
	ASSERT(alen==blen);

	INT i,j,t;

	// initialize match table 1 -> match;  0 -> no match
	for (i=0; i<alen; i++)
		match[i] = (avec[i] == bvec[i])? 1 : 0;

	DREAL outer_sum=0;

	for (t=0; t<alen-length; t++)
	{
	  INT sum=0;
	  for (i=0; i<length; i++)
		  sum+=(i+1)*match[t+i]+(length-i)*match[t+i+length+1];

	  //add middle element + normalize with sum_i=0^2l+1 i = (2l+1)(l+1)
	  DREAL inner_sum= ((DREAL) sum + (length+1)*match[t+length]) / ((2*length+1)*(length+1));
	  DREAL s=inner_sum;

	  for (j=1; j<inner_degree; j++)
		  inner_sum*=s;

	  outer_sum+=inner_sum;
	}

	double result=outer_sum;

	for (i=1; i<outer_degree; i++)
	  result*=outer_sum;

	return (double) result;
}
<commit_msg>LocalityImprovedStringKernel: More trivial whitespace cleanups<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 1999-2007 Gunnar Raetsch
 * Written (W) 1999-2007 Soeren Sonnenburg
 * Copyright (C) 1999-2007 Fraunhofer Institute FIRST and Max-Planck-Society
 */

#include "lib/common.h"
#include "lib/io.h"
#include "kernel/LocalityImprovedStringKernel.h"
#include "features/Features.h"
#include "features/StringFeatures.h"

CLocalityImprovedStringKernel::CLocalityImprovedStringKernel(LONG size, INT l, INT d1, INT d2)
  : CStringKernel<CHAR>(size),length(l),inner_degree(d1),outer_degree(d2),match(NULL)
{
	SG_INFO( "LIK with parms: l=%d, d1=%d, d2=%d created!\n", l, d1, d2);
}

CLocalityImprovedStringKernel::~CLocalityImprovedStringKernel()
{
	cleanup();
}

bool CLocalityImprovedStringKernel::init(CFeatures* l, CFeatures* r)
{
	bool result = CStringKernel<CHAR>::init(l,r);

	if (!result)
		return false;
	match = new CHAR[((CStringFeatures<CHAR>*) l)->get_max_vector_length()];
	return match? true : false;
}

void CLocalityImprovedStringKernel::cleanup()
{
	delete[] match;
	match = NULL;
}

bool CLocalityImprovedStringKernel::load_init(FILE* src)
{
	return false;
}

bool CLocalityImprovedStringKernel::save_init(FILE* dest)
{
	return false;
}

DREAL CLocalityImprovedStringKernel::compute(INT idx_a, INT idx_b)
{
	INT alen, blen;

	CHAR* avec = ((CStringFeatures<CHAR>*) lhs)->get_feature_vector(idx_a, alen);
	CHAR* bvec = ((CStringFeatures<CHAR>*) rhs)->get_feature_vector(idx_b, blen);

	// can only deal with strings of same length
	ASSERT(alen == blen);

	INT i,j,t;

	// initialize match table 1 -> match;  0 -> no match
	for (i=0; i<alen; i++)
		match[i] = (avec[i] == bvec[i])? 1 : 0;

	DREAL outer_sum=0;

	for (t=0; t<alen-length; t++)
	{
		INT sum = 0;
		for (i=0; i<length; i++)
			sum += (i+1)*match[t+i]+(length-i)*match[t+i+length+1];

		//add middle element + normalize with sum_i=0^2l+1 i = (2l+1)(l+1)
		DREAL inner_sum = ((DREAL) sum + (length+1)*match[t+length]) / ((2*length+1)*(length+1));
		DREAL s = inner_sum;

		for (j = 1; j<inner_degree; j++)
			inner_sum *= s;

		outer_sum += inner_sum;
	}

	double result = outer_sum;

	for (i=1; i<outer_degree; i++)
		result *= outer_sum;

	return (double) result;
}
<|endoftext|>