<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "colorscheme.h"

#include "texteditorconstants.h"

#include <QtCore/QFile>
#include <QtCore/QCoreApplication>
#include <QtXml/QXmlStreamWriter>

using namespace TextEditor;

static const char *trueString = "true";

// Format

Format::Format() :
    m_foreground(Qt::black),
    m_background(Qt::white),
    m_bold(false),
    m_italic(false)
{
}

void Format::setForeground(const QColor &foreground)
{
    m_foreground = foreground;
}

void Format::setBackground(const QColor &background)
{
    m_background = background;
}

void Format::setBold(bool bold)
{
    m_bold = bold;
}

void Format::setItalic(bool italic)
{
    m_italic = italic;
}

static QColor stringToColor(const QString &string)
{
    if (string == QLatin1String("invalid"))
        return QColor();
    return QColor(string);
}

bool Format::equals(const Format &f) const
{
    return m_foreground ==  f.m_foreground && m_background == f.m_background &&
           m_bold == f.m_bold && m_italic == f.m_italic;
}

bool Format::fromString(const QString &str)
{
    *this = Format();

    const QStringList lst = str.split(QLatin1Char(';'));
    if (lst.count() != 4)
        return false;

    m_foreground = stringToColor(lst.at(0));
    m_background = stringToColor(lst.at(1));
    m_bold = lst.at(2) == QLatin1String(trueString);
    m_italic = lst.at(3) == QLatin1String(trueString);
    return true;
}

// ColorScheme

ColorScheme::ColorScheme()
{
}

bool ColorScheme::contains(const QString &category) const
{
    return m_formats.contains(category);
}

Format &ColorScheme::formatFor(const QString &category)
{
    return m_formats[category];
}

Format ColorScheme::formatFor(const QString &category) const
{
    return m_formats.value(category);
}

void ColorScheme::setFormatFor(const QString &category, const Format &format)
{
    m_formats[category] = format;
}

void ColorScheme::clear()
{
    m_formats.clear();
}

bool ColorScheme::save(const QString &fileName) const
{
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly))
        return false;

    QXmlStreamWriter w(&file);
    w.setAutoFormatting(true);
    w.setAutoFormattingIndent(2);

    w.writeStartDocument();
    w.writeStartElement(QLatin1String("style-scheme"));
    w.writeAttribute(QLatin1String("version"), QLatin1String("1.0"));
    if (!m_displayName.isEmpty())
        w.writeAttribute(QLatin1String("name"), m_displayName);

    QMapIterator<QString, Format> i(m_formats);
    while (i.hasNext()) {
        const Format &format = i.next().value();
        w.writeStartElement(QLatin1String("style"));
        w.writeAttribute(QLatin1String("name"), i.key());
        if (format.foreground().isValid())
            w.writeAttribute(QLatin1String("foreground"), format.foreground().name().toLower());
        if (format.background().isValid())
            w.writeAttribute(QLatin1String("background"), format.background().name().toLower());
        if (format.bold())
            w.writeAttribute(QLatin1String("bold"), QLatin1String(trueString));
        if (format.italic())
            w.writeAttribute(QLatin1String("italic"), QLatin1String(trueString));
        w.writeEndElement();
    }

    w.writeEndElement();
    w.writeEndDocument();

    return true;
}

namespace {

class ColorSchemeReader : public QXmlStreamReader
{
public:
    ColorSchemeReader() :
        m_scheme(0)
    {}

    bool read(const QString &fileName, ColorScheme *scheme);
    QString readName(const QString &fileName);

private:
    bool readNextStartElement();
    void skipCurrentElement();
    void readStyleScheme();
    void readStyle();

    ColorScheme *m_scheme;
    QString m_name;
};

bool ColorSchemeReader::read(const QString &fileName, ColorScheme *scheme)
{
    m_scheme = scheme;

    if (m_scheme)
        m_scheme->clear();

    QFile file(fileName);
    if (!file.open(QFile::ReadOnly | QFile::Text))
        return false;

    setDevice(&file);

    if (readNextStartElement() && name() == QLatin1String("style-scheme"))
        readStyleScheme();
    else
        raiseError(QCoreApplication::translate("TextEditor::Internal::ColorScheme", "Not a color scheme file."));

    return true;
}

QString ColorSchemeReader::readName(const QString &fileName)
{
    read(fileName, 0);
    return m_name;
}

bool ColorSchemeReader::readNextStartElement()
{
    while (readNext() != Invalid) {
        if (isStartElement())
            return true;
        else if (isEndElement())
            return false;
    }
    return false;
}

void ColorSchemeReader::skipCurrentElement()
{
    while (readNextStartElement())
        skipCurrentElement();
}

void ColorSchemeReader::readStyleScheme()
{
    Q_ASSERT(isStartElement() && name() == QLatin1String("style-scheme"));

    const QXmlStreamAttributes attr = attributes();
    m_name = attr.value(QLatin1String("name")).toString();
    if (!m_scheme)
        // We're done
        raiseError(QLatin1String("name loaded"));
    else
        m_scheme->setDisplayName(m_name);

    while (readNextStartElement()) {
        if (name() == QLatin1String("style"))
            readStyle();
        else
            skipCurrentElement();
    }
}

void ColorSchemeReader::readStyle()
{
    Q_ASSERT(isStartElement() && name() == QLatin1String("style"));

    const QXmlStreamAttributes attr = attributes();
    QString name = attr.value(QLatin1String("name")).toString();
    QString foreground = attr.value(QLatin1String("foreground")).toString();
    QString background = attr.value(QLatin1String("background")).toString();
    bool bold = attr.value(QLatin1String("bold")) == QLatin1String(trueString);
    bool italic = attr.value(QLatin1String("italic")) == QLatin1String(trueString);

    Format format;
    format.setForeground(QColor(foreground));
    format.setBackground(QColor(background));
    format.setBold(bold);
    format.setItalic(italic);

    m_scheme->setFormatFor(name, format);

    skipCurrentElement();
}

} // anonymous namespace

bool ColorScheme::load(const QString &fileName)
{
    ColorSchemeReader reader;
    return reader.read(fileName, this) && !reader.hasError();
}

QString ColorScheme::readNameOfScheme(const QString &fileName)
{
    return ColorSchemeReader().readName(fileName);
}
<commit_msg>Work around a warning in the QColor constructor<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "colorscheme.h"

#include "texteditorconstants.h"

#include <QtCore/QFile>
#include <QtCore/QCoreApplication>
#include <QtXml/QXmlStreamWriter>

using namespace TextEditor;

static const char *trueString = "true";

// Format

Format::Format() :
    m_foreground(Qt::black),
    m_background(Qt::white),
    m_bold(false),
    m_italic(false)
{
}

void Format::setForeground(const QColor &foreground)
{
    m_foreground = foreground;
}

void Format::setBackground(const QColor &background)
{
    m_background = background;
}

void Format::setBold(bool bold)
{
    m_bold = bold;
}

void Format::setItalic(bool italic)
{
    m_italic = italic;
}

static QColor stringToColor(const QString &string)
{
    if (string == QLatin1String("invalid"))
        return QColor();
    return QColor(string);
}

bool Format::equals(const Format &f) const
{
    return m_foreground ==  f.m_foreground && m_background == f.m_background &&
           m_bold == f.m_bold && m_italic == f.m_italic;
}

bool Format::fromString(const QString &str)
{
    *this = Format();

    const QStringList lst = str.split(QLatin1Char(';'));
    if (lst.count() != 4)
        return false;

    m_foreground = stringToColor(lst.at(0));
    m_background = stringToColor(lst.at(1));
    m_bold = lst.at(2) == QLatin1String(trueString);
    m_italic = lst.at(3) == QLatin1String(trueString);
    return true;
}

// ColorScheme

ColorScheme::ColorScheme()
{
}

bool ColorScheme::contains(const QString &category) const
{
    return m_formats.contains(category);
}

Format &ColorScheme::formatFor(const QString &category)
{
    return m_formats[category];
}

Format ColorScheme::formatFor(const QString &category) const
{
    return m_formats.value(category);
}

void ColorScheme::setFormatFor(const QString &category, const Format &format)
{
    m_formats[category] = format;
}

void ColorScheme::clear()
{
    m_formats.clear();
}

bool ColorScheme::save(const QString &fileName) const
{
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly))
        return false;

    QXmlStreamWriter w(&file);
    w.setAutoFormatting(true);
    w.setAutoFormattingIndent(2);

    w.writeStartDocument();
    w.writeStartElement(QLatin1String("style-scheme"));
    w.writeAttribute(QLatin1String("version"), QLatin1String("1.0"));
    if (!m_displayName.isEmpty())
        w.writeAttribute(QLatin1String("name"), m_displayName);

    QMapIterator<QString, Format> i(m_formats);
    while (i.hasNext()) {
        const Format &format = i.next().value();
        w.writeStartElement(QLatin1String("style"));
        w.writeAttribute(QLatin1String("name"), i.key());
        if (format.foreground().isValid())
            w.writeAttribute(QLatin1String("foreground"), format.foreground().name().toLower());
        if (format.background().isValid())
            w.writeAttribute(QLatin1String("background"), format.background().name().toLower());
        if (format.bold())
            w.writeAttribute(QLatin1String("bold"), QLatin1String(trueString));
        if (format.italic())
            w.writeAttribute(QLatin1String("italic"), QLatin1String(trueString));
        w.writeEndElement();
    }

    w.writeEndElement();
    w.writeEndDocument();

    return true;
}

namespace {

class ColorSchemeReader : public QXmlStreamReader
{
public:
    ColorSchemeReader() :
        m_scheme(0)
    {}

    bool read(const QString &fileName, ColorScheme *scheme);
    QString readName(const QString &fileName);

private:
    bool readNextStartElement();
    void skipCurrentElement();
    void readStyleScheme();
    void readStyle();

    ColorScheme *m_scheme;
    QString m_name;
};

bool ColorSchemeReader::read(const QString &fileName, ColorScheme *scheme)
{
    m_scheme = scheme;

    if (m_scheme)
        m_scheme->clear();

    QFile file(fileName);
    if (!file.open(QFile::ReadOnly | QFile::Text))
        return false;

    setDevice(&file);

    if (readNextStartElement() && name() == QLatin1String("style-scheme"))
        readStyleScheme();
    else
        raiseError(QCoreApplication::translate("TextEditor::Internal::ColorScheme", "Not a color scheme file."));

    return true;
}

QString ColorSchemeReader::readName(const QString &fileName)
{
    read(fileName, 0);
    return m_name;
}

bool ColorSchemeReader::readNextStartElement()
{
    while (readNext() != Invalid) {
        if (isStartElement())
            return true;
        else if (isEndElement())
            return false;
    }
    return false;
}

void ColorSchemeReader::skipCurrentElement()
{
    while (readNextStartElement())
        skipCurrentElement();
}

void ColorSchemeReader::readStyleScheme()
{
    Q_ASSERT(isStartElement() && name() == QLatin1String("style-scheme"));

    const QXmlStreamAttributes attr = attributes();
    m_name = attr.value(QLatin1String("name")).toString();
    if (!m_scheme)
        // We're done
        raiseError(QLatin1String("name loaded"));
    else
        m_scheme->setDisplayName(m_name);

    while (readNextStartElement()) {
        if (name() == QLatin1String("style"))
            readStyle();
        else
            skipCurrentElement();
    }
}

void ColorSchemeReader::readStyle()
{
    Q_ASSERT(isStartElement() && name() == QLatin1String("style"));

    const QXmlStreamAttributes attr = attributes();
    QString name = attr.value(QLatin1String("name")).toString();
    QString foreground = attr.value(QLatin1String("foreground")).toString();
    QString background = attr.value(QLatin1String("background")).toString();
    bool bold = attr.value(QLatin1String("bold")) == QLatin1String(trueString);
    bool italic = attr.value(QLatin1String("italic")) == QLatin1String(trueString);

    Format format;

    if (QColor::isValidColor(foreground))
        format.setForeground(QColor(foreground));
    else
        format.setForeground(QColor());

    if (QColor::isValidColor(background))
        format.setBackground(QColor(background));
    else
        format.setBackground(QColor());

    format.setBold(bold);
    format.setItalic(italic);

    m_scheme->setFormatFor(name, format);

    skipCurrentElement();
}

} // anonymous namespace

bool ColorScheme::load(const QString &fileName)
{
    ColorSchemeReader reader;
    return reader.read(fileName, this) && !reader.hasError();
}

QString ColorScheme::readNameOfScheme(const QString &fileName)
{
    return ColorSchemeReader().readName(fileName);
}
<|endoftext|>


<commit_before>//
// Libor Novak
// 03/12/2017
//
// Detects objects by using a single scale detector on an image pyramid
//

#include <caffe/caffe.hpp>

// This code only works with OpenCV!
#ifdef USE_OPENCV

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <algorithm>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include <boost/program_options.hpp>
namespace po = boost::program_options;

/**
 * @brief Wraps the input layer into a vector of cv::Mat so we could assign data to it more easily
 * @param input_layer Pointer to the net input layer blob
 * @param input_channels Vector of cv::Mat, which will be assigned
 */
void wrapInputLayer (caffe::Blob<float>* input_layer, std::vector<cv::Mat> &out_input_channels)
{
    out_input_channels.clear();

    int height = input_layer->shape(2);
    int width  = input_layer->shape(3);

    float* input_data = input_layer->mutable_cpu_data();

    for (int i = 0; i < input_layer->shape(1); ++i)
    {
        cv::Mat channel(height, width, CV_32FC1, input_data);
        out_input_channels.push_back(channel);
        input_data += width * height;
    }
}

void runPyramidDetection (const std::string &path_prototxt, const std::string &path_caffemodel,
                          const std::string &path_image_list)
{
#ifdef CPU_ONLY
    caffe::Caffe::set_mode(caffe::Caffe::CPU);
#else
    caffe::Caffe::set_mode(caffe::Caffe::GPU);
#endif

    const std::vector<double> scales = {2.25, 1.5, 1.0, 0.66, 0.44, 0.29};

    // Create network and load trained weights from caffemodel file
    auto net = std::make_shared<caffe::Net<float>>(path_prototxt, caffe::TEST);
    net->CopyTrainedLayersFrom(path_caffemodel);

    caffe::Blob<float>* input_layer  = net->input_blobs()[0];
    LOG(INFO) << "We have " << net->output_blobs().size() << " accumulators on the output";

    CHECK_EQ(net->num_inputs(), 1) << "Network should have exactly one input.";
    CHECK_EQ(input_layer->shape(1), 3) << "Input layer must have 3 channels.";
    for (const auto output_layer: net->output_blobs())
    {
        CHECK_EQ(output_layer->shape(1), 5) << "Output layer must have 5 channels";
    }

    // Prepare the input channels
    std::vector<cv::Mat> input_channels;
    wrapInputLayer(input_layer, input_channels);

    std::ifstream infile(path_image_list.c_str());
    CHECK(infile) << "Unable to open image list TXT file '" << path_image_list << "'!";
    std::string line; int i = 0;
    while (std::getline(infile, line))
    {
        LOG(INFO) << line;
        CHECK(boost::filesystem::exists(line)) << "Image '" << line << "' not found!";

        // Load the image
        cv::Mat image = cv::imread(line, CV_LOAD_IMAGE_COLOR);
        cv::Mat imagef; image.convertTo(imagef, CV_32FC3);

        // Convert to zero mean and unit variance
        imagef -= cv::Scalar(128.0f, 128.0f, 128.0f);
        imagef *= 1.0f/128.0f;

        // Build the image pyramid and run detection on each scale of the pyramid
        for (double s: scales)
        {
            cv::Mat imagef_scaled; cv::resize(imagef, imagef_scaled, cv::Size(), s, s);
            std::cout << "Current size: " << imagef_scaled.size() << " (" << s << ")" << std::endl;

            if (imagef_scaled.rows != input_layer->shape(2) || imagef_scaled.cols != input_layer->shape(3))
            {
                // Reshape the network
                input_layer->Reshape(1, input_layer->shape(1), imagef_scaled.rows, imagef_scaled.cols);
                net->Reshape();

                wrapInputLayer(input_layer, input_channels);
            }

            // Copy the image to the input layer of the network
            cv::split(imagef_scaled, input_channels);

            net->Forward();

            // Show the result
            caffe::Blob<float>* output = net->output_blobs()[0];
            float *data_output = output->mutable_cpu_data();
            cv::Mat acc_prob(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 0));
            cv::Mat acc_xmin(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 1));
            cv::Mat acc_ymin(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 2));
            cv::Mat acc_xmax(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 3));
            cv::Mat acc_ymax(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 4));

            double mx;
            cv::minMaxLoc(acc_prob, 0, &mx);
            std::cout << mx << std::endl;

            cv::imshow("Accumulator " + net->blob_names()[net->output_blob_indices()[0]] + " (" + std::to_string(s) + ")", acc_prob);

            // Draw detected boxes
            for (int i = 0; i < acc_prob.rows; ++i)
            {
                for (int j = 0; j < acc_prob.cols; ++j)
                {
                    float conf = acc_prob.at<float>(i, j);
                    if (conf >= 0.7)
                    {
                        int xmin = (4*j + (80*(acc_xmin.at<float>(i, j) - 0.5))) / s;
                        int ymin = (4*i + (80*(acc_ymin.at<float>(i, j) - 0.5))) / s;
                        int xmax = (4*j + (80*(acc_xmax.at<float>(i, j) - 0.5))) / s;
                        int ymax = (4*i + (80*(acc_ymax.at<float>(i, j) - 0.5))) / s;

                        std::cout << acc_xmin.at<float>(i, j) << " " << acc_ymin.at<float>(i, j) << " " << acc_xmax.at<float>(i, j) << " " << acc_ymax.at<float>(i, j) << std::endl;

                        if (xmin >= xmax || ymin >= ymax)
                        {
                            // This does not make sense
                            std::cout << "WARNING: Coordinates do not make sense! [" << xmin << "," << ymin << "," << xmax << "," << ymax << "]" << std::endl;
                            continue;
                        }

                        cv::rectangle(image, cv::Rect(xmin, ymin, xmax-xmin, ymax-ymin), cv::Scalar(0,0,255));
                        cv::circle(image, cv::Point(4*j/s, 4*i/s), 2, cv::Scalar(0,255,0), -1);
                    }
                }
            }
        }

        cv::imshow("Image", image);
        cv::waitKey(0);
    }
}

// -----------------------------------------------  MAIN  ------------------------------------------------ //

struct ProgramArguments
{
    std::string path_prototxt;
    std::string path_caffemodel;
    std::string path_image_list;
};

/**
 * @brief Parses arguments of the program
 */
void parseArguments (int argc, char** argv, ProgramArguments &pa)
{
    try {
        po::options_description desc("Arguments");
        desc.add_options()
            ("help", "Print help")
            ("prototxt", po::value<std::string>(&pa.path_prototxt)->required(),
             "Model file of the network (*.prototxt)")
            ("caffemodel", po::value<std::string>(&pa.path_caffemodel)->required(),
             "Weight file of the network (*.caffemodel)")
            ("image_list", po::value<std::string>(&pa.path_image_list)->required(),
             "Path to a TXT file with paths to the images to be tested")
        ;

        po::positional_options_description positional;
        positional.add("prototxt", 1);
        positional.add("caffemodel", 1);
        positional.add("image_list", 1);

        // Parse the input arguments
        po::variables_map vm;
        po::store(po::command_line_parser(argc, argv).options(desc).positional(positional).run(), vm);

        if (vm.count("help")) {
            std::cout << "Usage: ./detect_accumulator path/f.prototxt path/f.caffemodel path/image_list.txt\n";
            std::cout << desc;
            exit(EXIT_SUCCESS);
        }

        po::notify(vm);

        if (!boost::filesystem::exists(pa.path_prototxt))
        {
            std::cerr << "ERROR: File '" << pa.path_prototxt << "' does not exist!" << std::endl;
            exit(EXIT_FAILURE);
        }
        if (!boost::filesystem::exists(pa.path_caffemodel))
        {
            std::cerr << "ERROR: File '" << pa.path_caffemodel << "' does not exist!" << std::endl;
            exit(EXIT_FAILURE);
        }
        if (!boost::filesystem::exists(pa.path_image_list))
        {
            std::cerr << "ERROR: File '" << pa.path_image_list << "' does not exist!" << std::endl;
            exit(EXIT_FAILURE);
        }
    }
    catch(std::exception& e)
    {
        std::cerr << e.what() << "\n";
        exit(EXIT_FAILURE);
    }
}

int main (int argc, char** argv)
{
    ::google::InitGoogleLogging(argv[0]);

    ProgramArguments pa;
    parseArguments(argc, argv, pa);

    runPyramidDetection(pa.path_prototxt, pa.path_caffemodel, pa.path_image_list);

    return EXIT_SUCCESS;
}

#else
int main(int argc, char** argv) {
    LOG(FATAL) << "This example requires OpenCV; compile with USE_OPENCV.";
}
#endif  // USE_OPENCV
<commit_msg>Detect pyramid changed to support 3D bounding boxes<commit_after>//
// Libor Novak
// 03/12/2017
//
// Detects objects by using a single scale detector on an image pyramid
//

#include <caffe/caffe.hpp>

// This code only works with OpenCV!
#ifdef USE_OPENCV

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <algorithm>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include <boost/program_options.hpp>
namespace po = boost::program_options;

/**
 * @brief Wraps the input layer into a vector of cv::Mat so we could assign data to it more easily
 * @param input_layer Pointer to the net input layer blob
 * @param input_channels Vector of cv::Mat, which will be assigned
 */
void wrapInputLayer (caffe::Blob<float>* input_layer, std::vector<cv::Mat> &out_input_channels)
{
    out_input_channels.clear();

    int height = input_layer->shape(2);
    int width  = input_layer->shape(3);

    float* input_data = input_layer->mutable_cpu_data();

    for (int i = 0; i < input_layer->shape(1); ++i)
    {
        cv::Mat channel(height, width, CV_32FC1, input_data);
        out_input_channels.push_back(channel);
        input_data += width * height;
    }
}

void runPyramidDetection (const std::string &path_prototxt, const std::string &path_caffemodel,
                          const std::string &path_image_list)
{
#ifdef CPU_ONLY
    caffe::Caffe::set_mode(caffe::Caffe::CPU);
#else
    caffe::Caffe::set_mode(caffe::Caffe::GPU);
#endif

    const std::vector<double> scales = {2.25, 1.5, 1.0, 0.66, 0.44, 0.29};

    // Create network and load trained weights from caffemodel file
    auto net = std::make_shared<caffe::Net<float>>(path_prototxt, caffe::TEST);
    net->CopyTrainedLayersFrom(path_caffemodel);

    caffe::Blob<float>* input_layer  = net->input_blobs()[0];
    LOG(INFO) << "We have " << net->output_blobs().size() << " accumulators on the output";

    CHECK_EQ(net->num_inputs(), 1) << "Network should have exactly one input.";
    CHECK_EQ(input_layer->shape(1), 3) << "Input layer must have 3 channels.";

    // Prepare the input channels
    std::vector<cv::Mat> input_channels;
    wrapInputLayer(input_layer, input_channels);

    std::ifstream infile(path_image_list.c_str());
    CHECK(infile) << "Unable to open image list TXT file '" << path_image_list << "'!";
    std::string line; int i = 0;
    while (std::getline(infile, line))
    {
        LOG(INFO) << line;
        CHECK(boost::filesystem::exists(line)) << "Image '" << line << "' not found!";

        // Load the image
        cv::Mat image = cv::imread(line, CV_LOAD_IMAGE_COLOR);
        cv::Mat imagef; image.convertTo(imagef, CV_32FC3);

        // Convert to zero mean and unit variance
        imagef -= cv::Scalar(128.0f, 128.0f, 128.0f);
        imagef *= 1.0f/128.0f;

        // Build the image pyramid and run detection on each scale of the pyramid
        for (double s: scales)
        {
            cv::Mat imagef_scaled; cv::resize(imagef, imagef_scaled, cv::Size(), s, s);
            std::cout << "Current size: " << imagef_scaled.size() << " (" << s << ")" << std::endl;

            if (imagef_scaled.rows != input_layer->shape(2) || imagef_scaled.cols != input_layer->shape(3))
            {
                // Reshape the network
                input_layer->Reshape(1, input_layer->shape(1), imagef_scaled.rows, imagef_scaled.cols);
                net->Reshape();

                wrapInputLayer(input_layer, input_channels);
            }

            // Copy the image to the input layer of the network
            cv::split(imagef_scaled, input_channels);

            net->Forward();

            // Show the result
            caffe::Blob<float>* output = net->output_blobs()[0];
            float *data_output = output->mutable_cpu_data();

            cv::Mat acc_prob(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 0));

            if (output->shape(1) == 5)
            {
                // 2D bounding box
                cv::Mat acc_xmin(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 1));
                cv::Mat acc_ymin(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 2));
                cv::Mat acc_xmax(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 3));
                cv::Mat acc_ymax(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 4));

                double mx;
                cv::minMaxLoc(acc_prob, 0, &mx);
                std::cout << mx << std::endl;

                cv::imshow("Accumulator " + net->blob_names()[net->output_blob_indices()[0]] + " (" + std::to_string(s) + ")", acc_prob);

                // Draw detected boxes
                for (int i = 0; i < acc_prob.rows; ++i)
                {
                    for (int j = 0; j < acc_prob.cols; ++j)
                    {
                        float conf = acc_prob.at<float>(i, j);
                        if (conf >= 0.7)
                        {
                            int xmin = (4*j + (80*(acc_xmin.at<float>(i, j) - 0.5))) / s;
                            int ymin = (4*i + (80*(acc_ymin.at<float>(i, j) - 0.5))) / s;
                            int xmax = (4*j + (80*(acc_xmax.at<float>(i, j) - 0.5))) / s;
                            int ymax = (4*i + (80*(acc_ymax.at<float>(i, j) - 0.5))) / s;

                            std::cout << acc_xmin.at<float>(i, j) << " " << acc_ymin.at<float>(i, j) << " " << acc_xmax.at<float>(i, j) << " " << acc_ymax.at<float>(i, j) << std::endl;

                            if (xmin >= xmax || ymin >= ymax)
                            {
                                // This does not make sense
                                std::cout << "WARNING: Coordinates do not make sense! [" << xmin << "," << ymin << "," << xmax << "," << ymax << "]" << std::endl;
                                continue;
                            }

                            cv::rectangle(image, cv::Rect(xmin, ymin, xmax-xmin, ymax-ymin), cv::Scalar(0,0,255));
                            cv::circle(image, cv::Point(4*j/s, 4*i/s), 2, cv::Scalar(0,255,0), -1);
                        }
                    }
                }
            }
            else if (output->shape(1) == 8)
            {
                // 3D bounding box
                // fblx, fbly, fbrx, fbry, rblx, rbly, ftly
                cv::Mat acc_fblx(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 1));
                cv::Mat acc_fbly(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 2));
                cv::Mat acc_fbrx(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 3));
                cv::Mat acc_fbry(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 4));
                cv::Mat acc_rblx(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 5));
                cv::Mat acc_rbly(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 6));
                cv::Mat acc_ftly(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 7));

                double mx;
                cv::minMaxLoc(acc_prob, 0, &mx);
                std::cout << mx << std::endl;

                cv::imshow("Accumulator " + net->blob_names()[net->output_blob_indices()[0]] + " (" + std::to_string(s) + ")", acc_prob);

                // Draw detected 3D boxes
                for (int i = 0; i < acc_prob.rows; ++i)
                {
                    for (int j = 0; j < acc_prob.cols; ++j)
                    {
                        float conf = acc_prob.at<float>(i, j);
                        if (conf >= 0.7)
                        {
                            int fblx = (4*j + (80*(acc_fblx.at<float>(i, j) - 0.5))) / s;
                            int fbly = (4*i + (80*(acc_fbly.at<float>(i, j) - 0.5))) / s;
                            int fbrx = (4*j + (80*(acc_fbrx.at<float>(i, j) - 0.5))) / s;
                            int fbry = (4*i + (80*(acc_fbry.at<float>(i, j) - 0.5))) / s;
                            int rblx = (4*j + (80*(acc_rblx.at<float>(i, j) - 0.5))) / s;
                            int rbly = (4*i + (80*(acc_rbly.at<float>(i, j) - 0.5))) / s;
                            int ftly = (4*i + (80*(acc_ftly.at<float>(i, j) - 0.5))) / s;

                            cv::line(image, cv::Point(fblx, fbly), cv::Point(fbrx, fbry), cv::Scalar(0, 0, 255));
                            cv::line(image, cv::Point(fblx, fbly), cv::Point(fblx, ftly), cv::Scalar(0, 0, 255));
                            cv::line(image, cv::Point(fblx, fbly), cv::Point(rblx, rbly), cv::Scalar(0, 255, 0));

                            cv::circle(image, cv::Point(4*j/s, 4*i/s), 2, cv::Scalar(0,255,0), -1);
                        }
                    }
                }
            }
        }

        cv::imshow("Image", image);
        cv::waitKey(0);
    }
}

// -----------------------------------------------  MAIN  ------------------------------------------------ //

struct ProgramArguments
{
    std::string path_prototxt;
    std::string path_caffemodel;
    std::string path_image_list;
};

/**
 * @brief Parses arguments of the program
 */
void parseArguments (int argc, char** argv, ProgramArguments &pa)
{
    try {
        po::options_description desc("Arguments");
        desc.add_options()
            ("help", "Print help")
            ("prototxt", po::value<std::string>(&pa.path_prototxt)->required(),
             "Model file of the network (*.prototxt)")
            ("caffemodel", po::value<std::string>(&pa.path_caffemodel)->required(),
             "Weight file of the network (*.caffemodel)")
            ("image_list", po::value<std::string>(&pa.path_image_list)->required(),
             "Path to a TXT file with paths to the images to be tested")
        ;

        po::positional_options_description positional;
        positional.add("prototxt", 1);
        positional.add("caffemodel", 1);
        positional.add("image_list", 1);

        // Parse the input arguments
        po::variables_map vm;
        po::store(po::command_line_parser(argc, argv).options(desc).positional(positional).run(), vm);

        if (vm.count("help")) {
            std::cout << "Usage: ./detect_accumulator path/f.prototxt path/f.caffemodel path/image_list.txt\n";
            std::cout << desc;
            exit(EXIT_SUCCESS);
        }

        po::notify(vm);

        if (!boost::filesystem::exists(pa.path_prototxt))
        {
            std::cerr << "ERROR: File '" << pa.path_prototxt << "' does not exist!" << std::endl;
            exit(EXIT_FAILURE);
        }
        if (!boost::filesystem::exists(pa.path_caffemodel))
        {
            std::cerr << "ERROR: File '" << pa.path_caffemodel << "' does not exist!" << std::endl;
            exit(EXIT_FAILURE);
        }
        if (!boost::filesystem::exists(pa.path_image_list))
        {
            std::cerr << "ERROR: File '" << pa.path_image_list << "' does not exist!" << std::endl;
            exit(EXIT_FAILURE);
        }
    }
    catch(std::exception& e)
    {
        std::cerr << e.what() << "\n";
        exit(EXIT_FAILURE);
    }
}

int main (int argc, char** argv)
{
    ::google::InitGoogleLogging(argv[0]);

    ProgramArguments pa;
    parseArguments(argc, argv, pa);

    runPyramidDetection(pa.path_prototxt, pa.path_caffemodel, pa.path_image_list);

    return EXIT_SUCCESS;
}

#else
int main(int argc, char** argv) {
    LOG(FATAL) << "This example requires OpenCV; compile with USE_OPENCV.";
}
#endif  // USE_OPENCV
<|endoftext|>


<commit_before>/*

Copyright (c) 2007, Un Shyam
All rights reserved.

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

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

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

*/

#ifndef TORRENT_DISABLE_ENCRYPTION

#ifndef TORRENT_PE_CRYPTO_HPP_INCLUDED
#define TORRENT_PE_CRYPTO_HPP_INCLUDED

#include <openssl/dh.h>
#include <openssl/engine.h>
#include <openssl/rc4.h>

#include "libtorrent/peer_id.hpp" // For sha1_hash
#include "libtorrent/assert.hpp"

namespace libtorrent
{
	class dh_key_exchange
	{
	public:
		dh_key_exchange();
		~dh_key_exchange();
		bool good() const { return m_dh; }

		// Get local public key, always 96 bytes
		char const* get_local_key() const;

		// read remote_pubkey, generate and store shared secret in
		// m_dh_secret.
		int compute_secret(const char* remote_pubkey);

		char const* get_secret() const { return m_dh_secret; }

		sha1_hash const& get_hash_xor_mask() const { return m_xor_mask; }

	private:
		int get_local_key_size() const
		{
			TORRENT_ASSERT(m_dh);
			return BN_num_bytes(m_dh->pub_key);
		}

		DH* m_dh;

		char m_dh_local_key[96];
		char m_dh_secret[96];
		sha1_hash m_xor_mask;
	};

	class RC4_handler // Non copyable
	{
	public:
		// Input longkeys must be 20 bytes
		RC4_handler(const sha1_hash& rc4_local_longkey,
					 const sha1_hash& rc4_remote_longkey)

		{
			RC4_set_key(&m_local_key, 20,
						 reinterpret_cast<unsigned char const*>(rc4_local_longkey.begin()));
			RC4_set_key(&m_remote_key, 20,
						 reinterpret_cast<unsigned char const*>(rc4_remote_longkey.begin()));

			// Discard first 1024 bytes
			char buf[1024];
			encrypt(buf, 1024);
			decrypt(buf, 1024);
		};

		~RC4_handler() {};

		void encrypt(char* pos, int len)
		{
			TORRENT_ASSERT(len >= 0);
			TORRENT_ASSERT(pos);

			RC4 (&m_local_key, len, reinterpret_cast<unsigned char const*>(pos),
				 reinterpret_cast<unsigned char*>(pos));
		}

		void decrypt(char* pos, int len)
		{
			TORRENT_ASSERT(len >= 0);
			TORRENT_ASSERT(pos);

			RC4 (&m_remote_key, len, reinterpret_cast<unsigned char const*>(pos),
				 reinterpret_cast<unsigned char*>(pos));
		}

	private:
		RC4_KEY m_local_key; // Key to encrypt outgoing data
		RC4_KEY m_remote_key; // Key to decrypt incoming data
	};

} // namespace libtorrent

#endif // TORRENT_PE_CRYPTO_HPP_INCLUDED
#endif // TORRENT_DISABLE_ENCRYPTION

<commit_msg>formatting fixes for pe_crypto.cpp<commit_after>/*

Copyright (c) 2007, Un Shyam
All rights reserved.

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

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

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

*/

#ifndef TORRENT_DISABLE_ENCRYPTION

#ifndef TORRENT_PE_CRYPTO_HPP_INCLUDED
#define TORRENT_PE_CRYPTO_HPP_INCLUDED

#include <openssl/dh.h>
#include <openssl/engine.h>
#include <openssl/rc4.h>

#include "libtorrent/peer_id.hpp" // For sha1_hash
#include "libtorrent/assert.hpp"

namespace libtorrent
{
	class dh_key_exchange
	{
	public:
		dh_key_exchange();
		~dh_key_exchange();
		bool good() const { return m_dh; }

		// Get local public key, always 96 bytes
		char const* get_local_key() const;

		// read remote_pubkey, generate and store shared secret in
		// m_dh_secret.
		int compute_secret(const char* remote_pubkey);

		char const* get_secret() const { return m_dh_secret; }

		sha1_hash const& get_hash_xor_mask() const { return m_xor_mask; }

	private:
		int get_local_key_size() const
		{
			TORRENT_ASSERT(m_dh);
			return BN_num_bytes(m_dh->pub_key);
		}

		DH* m_dh;

		char m_dh_local_key[96];
		char m_dh_secret[96];
		sha1_hash m_xor_mask;
	};

	class RC4_handler // Non copyable
	{
	public:
		// Input longkeys must be 20 bytes
		RC4_handler(const sha1_hash& rc4_local_longkey,
			const sha1_hash& rc4_remote_longkey)
		{
			RC4_set_key(&m_local_key, 20,
				reinterpret_cast<unsigned char const*>(rc4_local_longkey.begin()));
			RC4_set_key(&m_remote_key, 20,
				reinterpret_cast<unsigned char const*>(rc4_remote_longkey.begin()));

			// Discard first 1024 bytes
			char buf[1024];
			encrypt(buf, 1024);
			decrypt(buf, 1024);
		};

		~RC4_handler() {};

		void encrypt(char* pos, int len)
		{
			TORRENT_ASSERT(len >= 0);
			TORRENT_ASSERT(pos);

			RC4(&m_local_key, len, reinterpret_cast<unsigned char const*>(pos),
				reinterpret_cast<unsigned char*>(pos));
		}

		void decrypt(char* pos, int len)
		{
			TORRENT_ASSERT(len >= 0);
			TORRENT_ASSERT(pos);

			RC4(&m_remote_key, len, reinterpret_cast<unsigned char const*>(pos),
				reinterpret_cast<unsigned char*>(pos));
		}

	private:
		RC4_KEY m_local_key; // Key to encrypt outgoing data
		RC4_KEY m_remote_key; // Key to decrypt incoming data
	};

} // namespace libtorrent

#endif // TORRENT_PE_CRYPTO_HPP_INCLUDED
#endif // TORRENT_DISABLE_ENCRYPTION

<|endoftext|>


<commit_before><commit_msg>GetTables uses now a Statement, instead of a PreparedStatement.<commit_after><|endoftext|>


<commit_before>/*

Copyright (c) 2007, Un Shyam
All rights reserved.

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

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

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

*/

#ifndef TORRENT_DISABLE_ENCRYPTION

#ifndef TORRENT_PE_CRYPTO_HPP_INCLUDED
#define TORRENT_PE_CRYPTO_HPP_INCLUDED

#include "libtorrent/config.hpp"

#ifdef TORRENT_USE_GCRYPT
#include <gcrypt.h>
#elif defined TORRENT_USE_OPENSSL
#include <openssl/rc4.h>
#include <openssl/evp.h>
#include <openssl/aes.h>
#else
// RC4 state from libtomcrypt
struct rc4 {
	int x, y;
	unsigned char buf[256];
};

void TORRENT_EXPORT rc4_init(const unsigned char* in, unsigned long len, rc4 *state);
unsigned long TORRENT_EXPORT rc4_encrypt(unsigned char *out, unsigned long outlen, rc4 *state);
#endif

#include "libtorrent/peer_id.hpp" // For sha1_hash
#include "libtorrent/assert.hpp"

namespace libtorrent
{
	class TORRENT_EXPORT dh_key_exchange
	{
	public:
		dh_key_exchange();
		bool good() const { return true; }

		// Get local public key, always 96 bytes
		char const* get_local_key() const;

		// read remote_pubkey, generate and store shared secret in
		// m_dh_shared_secret.
		int compute_secret(const char* remote_pubkey);

		char const* get_secret() const { return m_dh_shared_secret; }

		sha1_hash const& get_hash_xor_mask() const { return m_xor_mask; }

	private:

		int get_local_key_size() const
		{ return sizeof(m_dh_local_key); }

		char m_dh_local_key[96];
		char m_dh_local_secret[96];
		char m_dh_shared_secret[96];
		sha1_hash m_xor_mask;
	};

	struct encryption_handler
	{
		virtual void set_incoming_key(unsigned char const* key, int len) = 0;
		virtual void set_outgoing_key(unsigned char const* key, int len) = 0;
		virtual void encrypt(char* pos, int len) = 0;
		virtual void decrypt(char* pos, int len) = 0;
	};

	struct rc4_handler : encryption_handler
	{
	public:
		// Input longkeys must be 20 bytes
		rc4_handler()
			: m_encrypt(false)
			, m_decrypt(false)
		{
#ifdef TORRENT_USE_GCRYPT
			gcry_cipher_open(&m_rc4_incoming, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);
			gcry_cipher_open(&m_rc4_outgoing, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);
#endif
		};

		void set_incoming_key(unsigned char const* key, int len)
		{
			m_decrypt = true;
#ifdef TORRENT_USE_GCRYPT
			gcry_cipher_close(m_rc4_incoming);
			gcry_cipher_open(&m_rc4_incoming, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);
			gcry_cipher_setkey(m_rc4_incoming, key, len);
#elif defined TORRENT_USE_OPENSSL
			RC4_set_key(&m_remote_key, len, key);
#else
			rc4_init(key, len, &m_rc4_incoming);
#endif
			// Discard first 1024 bytes
			char buf[1024];
			decrypt(buf, 1024);
		}

		void set_outgoing_key(unsigned char const* key, int len)
		{
			m_encrypt = true;
#ifdef TORRENT_USE_GCRYPT
			gcry_cipher_close(m_rc4_outgoing);
			gcry_cipher_open(&m_rc4_outgoing, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);
			gcry_cipher_setkey(m_rc4_outgoing, key, len);
#elif defined TORRENT_USE_OPENSSL
			RC4_set_key(&m_local_key, len, key);
#else
			rc4_init(key, len, &m_rc4_outgoing);
#endif
			// Discard first 1024 bytes
			char buf[1024];
			encrypt(buf, 1024);
		}

		~rc4_handler()
		{
#ifdef TORRENT_USE_GCRYPT
			gcry_cipher_close(m_rc4_incoming);
			gcry_cipher_close(m_rc4_outgoing);
#endif
		};

		void encrypt(char* pos, int len)
		{
			if (!m_encrypt) return;

			TORRENT_ASSERT(len >= 0);
			TORRENT_ASSERT(pos);

#ifdef TORRENT_USE_GCRYPT
			gcry_cipher_encrypt(m_rc4_outgoing, pos, len, 0, 0);
#elif defined TORRENT_USE_OPENSSL
			RC4(&m_local_key, len, (const unsigned char*)pos, (unsigned char*)pos);
#else
			rc4_encrypt((unsigned char*)pos, len, &m_rc4_outgoing);
#endif
		}

		void decrypt(char* pos, int len)
		{
			if (!m_decrypt) return;

			TORRENT_ASSERT(len >= 0);
			TORRENT_ASSERT(pos);

#ifdef TORRENT_USE_GCRYPT
			gcry_cipher_decrypt(m_rc4_incoming, pos, len, 0, 0);
#elif defined TORRENT_USE_OPENSSL
			RC4(&m_remote_key, len, (const unsigned char*)pos, (unsigned char*)pos);
#else
			rc4_encrypt((unsigned char*)pos, len, &m_rc4_incoming);
#endif
		}

	private:
#ifdef TORRENT_USE_GCRYPT
		gcry_cipher_hd_t m_rc4_incoming;
		gcry_cipher_hd_t m_rc4_outgoing;
#elif defined TORRENT_USE_OPENSSL
		RC4_KEY m_local_key; // Key to encrypt outgoing data
		RC4_KEY m_remote_key; // Key to decrypt incoming data
#else
		rc4 m_rc4_incoming;
		rc4 m_rc4_outgoing;
#endif
		// determines whether or not encryption and decryption is enabled
		bool m_encrypt;
		bool m_decrypt;
	};

#ifdef TORRENT_USE_OPENSSL
	struct aes256_handler : encryption_handler
	{
		aes256_handler() : m_enc_pos(0), m_dec_pos(0)
		{
			EVP_CIPHER_CTX_init(&m_enc);
			EVP_CIPHER_CTX_init(&m_dec);
		}

		~aes256_handler()
		{
			EVP_CIPHER_CTX_cleanup(&m_enc);
			EVP_CIPHER_CTX_cleanup(&m_dec);
		}

		void set_incoming_key(unsigned char const* in_key, int len)
		{
			const int nrounds = 5;
			boost::uint8_t salt[8] = { 0xf1, 0x03, 0x46, 0xe2, 0xb1, 0xa8, 0x29, 0x63 };
			boost::uint8_t key[32];
			boost::uint8_t iv[32];

			int i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), salt, in_key, len, nrounds, key, iv);
			TORRENT_ASSERT(len == 32);
			EVP_EncryptInit_ex(&m_enc, EVP_aes_256_cbc(), NULL, key, iv);
			// since we're using the AES as a stream cipher, both the encrypt and
			// decrypt context will in fact only _encrypt_ stuff, so initializing
			// this as encrypt is not a typo
			EVP_EncryptInit_ex(&m_dec, EVP_aes_256_cbc(), NULL, key, iv);
			m_enc_pos = 0;
			m_dec_pos = 0;
			std::memcpy(m_enc_state, iv, sizeof(m_enc_state));
			std::memcpy(m_dec_state, iv, sizeof(m_enc_state));
		}
		void set_outgoing_key(unsigned char const* key, int len) { /* no-op */ }
		void encrypt(char* pos, int len)
		{
			while (len > 0)
			{
				while (m_enc_pos < AES_BLOCK_SIZE && len > 0)
				{
					*pos ^= m_enc_state[m_enc_pos];
					++m_enc_pos;
					++pos;
					--len;
				}

				if (m_enc_pos == AES_BLOCK_SIZE)
				{
					next_block(&m_enc, m_enc_state);
					m_enc_pos = 0;
				}
			}
		}

		void decrypt(char* pos, int len)
		{
			while (len > 0)
			{
				while (m_dec_pos < AES_BLOCK_SIZE && len > 0)
				{
					*pos ^= m_dec_state[m_dec_pos];
					++m_dec_pos;
					++pos;
					--len;
				}

				if (m_dec_pos == AES_BLOCK_SIZE)
				{
					next_block(&m_dec, m_dec_state);
					m_dec_pos = 0;
				}
			}
		}

	private:

		// we're turning the AES block-cipher into a stream cipher. This
		// function will produce the next block in the sequence of
		// block-sized buffers. We're using "Output feedback" (OFB) mode.
		void next_block(EVP_CIPHER_CTX* ctx, boost::uint8_t* pad)
		{
			int outlen = AES_BLOCK_SIZE;
			EVP_EncryptUpdate(ctx, pad, &outlen, pad, AES_BLOCK_SIZE);
			TORRENT_ASSERT(outlen == AES_BLOCK_SIZE);
		}

		EVP_CIPHER_CTX m_enc;
		EVP_CIPHER_CTX m_dec;

		boost::uint8_t m_enc_state[AES_BLOCK_SIZE];
		boost::uint8_t m_dec_state[AES_BLOCK_SIZE];
		int m_enc_pos;
		int m_dec_pos;

	};
#endif // TORRENT_USE_OPENSSL

} // namespace libtorrent

#endif // TORRENT_PE_CRYPTO_HPP_INCLUDED
#endif // TORRENT_DISABLE_ENCRYPTION

<commit_msg>fix some encryption warnings<commit_after>/*

Copyright (c) 2007, Un Shyam
All rights reserved.

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

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

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

*/

#ifndef TORRENT_DISABLE_ENCRYPTION

#ifndef TORRENT_PE_CRYPTO_HPP_INCLUDED
#define TORRENT_PE_CRYPTO_HPP_INCLUDED

#include "libtorrent/config.hpp"

#ifdef TORRENT_USE_GCRYPT
#include <gcrypt.h>
#elif defined TORRENT_USE_OPENSSL
#include <openssl/rc4.h>
#include <openssl/evp.h>
#include <openssl/aes.h>
#else
// RC4 state from libtomcrypt
struct rc4 {
	int x, y;
	unsigned char buf[256];
};

void TORRENT_EXPORT rc4_init(const unsigned char* in, unsigned long len, rc4 *state);
unsigned long TORRENT_EXPORT rc4_encrypt(unsigned char *out, unsigned long outlen, rc4 *state);
#endif

#include "libtorrent/peer_id.hpp" // For sha1_hash
#include "libtorrent/assert.hpp"

namespace libtorrent
{
	class TORRENT_EXPORT dh_key_exchange
	{
	public:
		dh_key_exchange();
		bool good() const { return true; }

		// Get local public key, always 96 bytes
		char const* get_local_key() const;

		// read remote_pubkey, generate and store shared secret in
		// m_dh_shared_secret.
		int compute_secret(const char* remote_pubkey);

		char const* get_secret() const { return m_dh_shared_secret; }

		sha1_hash const& get_hash_xor_mask() const { return m_xor_mask; }

	private:

		int get_local_key_size() const
		{ return sizeof(m_dh_local_key); }

		char m_dh_local_key[96];
		char m_dh_local_secret[96];
		char m_dh_shared_secret[96];
		sha1_hash m_xor_mask;
	};

	struct encryption_handler
	{
		virtual void set_incoming_key(unsigned char const* key, int len) = 0;
		virtual void set_outgoing_key(unsigned char const* key, int len) = 0;
		virtual void encrypt(char* pos, int len) = 0;
		virtual void decrypt(char* pos, int len) = 0;
		virtual ~encryption_handler() {}
	};

	struct rc4_handler : encryption_handler
	{
	public:
		// Input longkeys must be 20 bytes
		rc4_handler()
			: m_encrypt(false)
			, m_decrypt(false)
		{
#ifdef TORRENT_USE_GCRYPT
			gcry_cipher_open(&m_rc4_incoming, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);
			gcry_cipher_open(&m_rc4_outgoing, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);
#endif
		};

		void set_incoming_key(unsigned char const* key, int len)
		{
			m_decrypt = true;
#ifdef TORRENT_USE_GCRYPT
			gcry_cipher_close(m_rc4_incoming);
			gcry_cipher_open(&m_rc4_incoming, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);
			gcry_cipher_setkey(m_rc4_incoming, key, len);
#elif defined TORRENT_USE_OPENSSL
			RC4_set_key(&m_remote_key, len, key);
#else
			rc4_init(key, len, &m_rc4_incoming);
#endif
			// Discard first 1024 bytes
			char buf[1024];
			decrypt(buf, 1024);
		}

		void set_outgoing_key(unsigned char const* key, int len)
		{
			m_encrypt = true;
#ifdef TORRENT_USE_GCRYPT
			gcry_cipher_close(m_rc4_outgoing);
			gcry_cipher_open(&m_rc4_outgoing, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);
			gcry_cipher_setkey(m_rc4_outgoing, key, len);
#elif defined TORRENT_USE_OPENSSL
			RC4_set_key(&m_local_key, len, key);
#else
			rc4_init(key, len, &m_rc4_outgoing);
#endif
			// Discard first 1024 bytes
			char buf[1024];
			encrypt(buf, 1024);
		}

		~rc4_handler()
		{
#ifdef TORRENT_USE_GCRYPT
			gcry_cipher_close(m_rc4_incoming);
			gcry_cipher_close(m_rc4_outgoing);
#endif
		};

		void encrypt(char* pos, int len)
		{
			if (!m_encrypt) return;

			TORRENT_ASSERT(len >= 0);
			TORRENT_ASSERT(pos);

#ifdef TORRENT_USE_GCRYPT
			gcry_cipher_encrypt(m_rc4_outgoing, pos, len, 0, 0);
#elif defined TORRENT_USE_OPENSSL
			RC4(&m_local_key, len, (const unsigned char*)pos, (unsigned char*)pos);
#else
			rc4_encrypt((unsigned char*)pos, len, &m_rc4_outgoing);
#endif
		}

		void decrypt(char* pos, int len)
		{
			if (!m_decrypt) return;

			TORRENT_ASSERT(len >= 0);
			TORRENT_ASSERT(pos);

#ifdef TORRENT_USE_GCRYPT
			gcry_cipher_decrypt(m_rc4_incoming, pos, len, 0, 0);
#elif defined TORRENT_USE_OPENSSL
			RC4(&m_remote_key, len, (const unsigned char*)pos, (unsigned char*)pos);
#else
			rc4_encrypt((unsigned char*)pos, len, &m_rc4_incoming);
#endif
		}

	private:
#ifdef TORRENT_USE_GCRYPT
		gcry_cipher_hd_t m_rc4_incoming;
		gcry_cipher_hd_t m_rc4_outgoing;
#elif defined TORRENT_USE_OPENSSL
		RC4_KEY m_local_key; // Key to encrypt outgoing data
		RC4_KEY m_remote_key; // Key to decrypt incoming data
#else
		rc4 m_rc4_incoming;
		rc4 m_rc4_outgoing;
#endif
		// determines whether or not encryption and decryption is enabled
		bool m_encrypt;
		bool m_decrypt;
	};

#ifdef TORRENT_USE_OPENSSL
	struct aes256_handler : encryption_handler
	{
		aes256_handler() : m_enc_pos(0), m_dec_pos(0)
		{
			EVP_CIPHER_CTX_init(&m_enc);
			EVP_CIPHER_CTX_init(&m_dec);
		}

		~aes256_handler()
		{
			EVP_CIPHER_CTX_cleanup(&m_enc);
			EVP_CIPHER_CTX_cleanup(&m_dec);
		}

		void set_incoming_key(unsigned char const* in_key, int len)
		{
			const int nrounds = 5;
			boost::uint8_t salt[8] = { 0xf1, 0x03, 0x46, 0xe2, 0xb1, 0xa8, 0x29, 0x63 };
			boost::uint8_t key[32];
			boost::uint8_t iv[32];

			EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), salt, in_key, len, nrounds, key, iv);
			TORRENT_ASSERT(len == 32);
			EVP_EncryptInit_ex(&m_enc, EVP_aes_256_cbc(), NULL, key, iv);
			// since we're using the AES as a stream cipher, both the encrypt and
			// decrypt context will in fact only _encrypt_ stuff, so initializing
			// this as encrypt is not a typo
			EVP_EncryptInit_ex(&m_dec, EVP_aes_256_cbc(), NULL, key, iv);
			m_enc_pos = 0;
			m_dec_pos = 0;
			std::memcpy(m_enc_state, iv, sizeof(m_enc_state));
			std::memcpy(m_dec_state, iv, sizeof(m_enc_state));
		}
		void set_outgoing_key(unsigned char const* key, int len) { /* no-op */ }
		void encrypt(char* pos, int len)
		{
			while (len > 0)
			{
				while (m_enc_pos < AES_BLOCK_SIZE && len > 0)
				{
					*pos ^= m_enc_state[m_enc_pos];
					++m_enc_pos;
					++pos;
					--len;
				}

				if (m_enc_pos == AES_BLOCK_SIZE)
				{
					next_block(&m_enc, m_enc_state);
					m_enc_pos = 0;
				}
			}
		}

		void decrypt(char* pos, int len)
		{
			while (len > 0)
			{
				while (m_dec_pos < AES_BLOCK_SIZE && len > 0)
				{
					*pos ^= m_dec_state[m_dec_pos];
					++m_dec_pos;
					++pos;
					--len;
				}

				if (m_dec_pos == AES_BLOCK_SIZE)
				{
					next_block(&m_dec, m_dec_state);
					m_dec_pos = 0;
				}
			}
		}

	private:

		// we're turning the AES block-cipher into a stream cipher. This
		// function will produce the next block in the sequence of
		// block-sized buffers. We're using "Output feedback" (OFB) mode.
		void next_block(EVP_CIPHER_CTX* ctx, boost::uint8_t* pad)
		{
			int outlen = AES_BLOCK_SIZE;
			EVP_EncryptUpdate(ctx, pad, &outlen, pad, AES_BLOCK_SIZE);
			TORRENT_ASSERT(outlen == AES_BLOCK_SIZE);
		}

		EVP_CIPHER_CTX m_enc;
		EVP_CIPHER_CTX m_dec;

		boost::uint8_t m_enc_state[AES_BLOCK_SIZE];
		boost::uint8_t m_dec_state[AES_BLOCK_SIZE];
		int m_enc_pos;
		int m_dec_pos;

	};
#endif // TORRENT_USE_OPENSSL

} // namespace libtorrent

#endif // TORRENT_PE_CRYPTO_HPP_INCLUDED
#endif // TORRENT_DISABLE_ENCRYPTION

<|endoftext|>


<commit_before>/***************************************************************************//**
 * FILE : graphicsmaterial.hpp
 */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is libZinc.
 *
 * The Initial Developer of the Original Code is
 * Auckland Uniservices Ltd, Auckland, New Zealand.
 * Portions created by the Initial Developer are Copyright (C) 2012
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
#ifndef __ZN_CMISS_GRAPHICS_MATERIAL_HPP__
#define __ZN_CMISS_GRAPHICS_MATERIAL_HPP__

#include "zinc/graphicsmaterial.h"
#include "zinc/fieldimage.h"
#include "zinc/field.hpp"

namespace zinc
{

class GraphicsMaterial
{

protected:
	Cmiss_graphics_material_id id;

public:

	GraphicsMaterial() : id(0)
	{ }

	// takes ownership of C handle, responsibility for destroying it
	explicit GraphicsMaterial(Cmiss_graphics_material_id graphics_material_id) :
		id(graphics_material_id)
	{ }

	GraphicsMaterial(const GraphicsMaterial& graphicsMaterial) :
		id(Cmiss_graphics_material_access(graphicsMaterial.id))
	{ }

	GraphicsMaterial& operator=(const GraphicsMaterial& graphicsMaterial)
	{
		Cmiss_graphics_material_id temp_id = Cmiss_graphics_material_access(graphicsMaterial.id);
		if (0 != id)
		{
			Cmiss_graphics_material_destroy(&id);
		}
		id = temp_id;
		return *this;
	}

	~GraphicsMaterial()
	{
		if (0 != id)
		{
			Cmiss_graphics_material_destroy(&id);
		}
	}

	bool isValid()
	{
		return (0 != id);
	}

	Cmiss_graphics_material_id getId()
	{
		return id;
	}

	enum Attribute
	{
		ATTRIBUTE_INVALID = CMISS_GRAPHICS_MATERIAL_ATTRIBUTE_INVALID,
		ATTRIBUTE_ALPHA = CMISS_GRAPHICS_MATERIAL_ATTRIBUTE_ALPHA,
		ATTRIBUTE_AMBIENT = CMISS_GRAPHICS_MATERIAL_ATTRIBUTE_AMBIENT,
		ATTRIBUTE_DIFFUSE = CMISS_GRAPHICS_MATERIAL_ATTRIBUTE_DIFFUSE,
		ATTRIBUTE_EMISSION = CMISS_GRAPHICS_MATERIAL_ATTRIBUTE_EMISSION,
		ATTRIBUTE_SHININESS = CMISS_GRAPHICS_MATERIAL_ATTRIBUTE_SHININESS,
		ATTRIBUTE_SPECULAR = CMISS_GRAPHICS_MATERIAL_ATTRIBUTE_SPECULAR
	};

	bool isManaged()
	{
		return Cmiss_graphics_material_is_managed(id);
	}

	int setManaged(bool value)
	{
		return Cmiss_graphics_material_set_managed(id, value);
	}

	double getAttributeReal(Attribute attribute)
	{
		return Cmiss_graphics_material_get_attribute_real(id,
			static_cast<Cmiss_graphics_material_attribute>(attribute));
	}

	int setAttributeReal(Attribute attribute, double value)
	{
		return Cmiss_graphics_material_set_attribute_real(id,
			static_cast<Cmiss_graphics_material_attribute>(attribute), value);
	}

	int getAttributeReal3(Attribute attribute, double *outValues)
	{
		return Cmiss_graphics_material_get_attribute_real3(id,
			static_cast<Cmiss_graphics_material_attribute>(attribute), outValues);
	}

	int setAttributeReal3(Attribute attribute, const double *values)
	{
		return Cmiss_graphics_material_set_attribute_real3(id,
			static_cast<Cmiss_graphics_material_attribute>(attribute), values);
	}

	char *getName()
	{
		return Cmiss_graphics_material_get_name(id);
	}

	int setName(const char *name)
	{
		return Cmiss_graphics_material_set_name(id, name);
	}

	int setImageField(int imageNumber, Field &imageField)
	{
		Cmiss_field_image_id field_image = Cmiss_field_cast_image(imageField.getId());
		int result = Cmiss_graphics_material_set_image_field(id, imageNumber, field_image);
		Cmiss_field_image_destroy(&field_image);

		return result;
	}

};

class GraphicsMaterialModule
{
protected:
	Cmiss_graphics_material_module_id id;

public:

	GraphicsMaterialModule() : id(0)
	{  }

	// takes ownership of C handle, responsibility for destroying it
	explicit GraphicsMaterialModule(Cmiss_graphics_material_module_id in_graphics_material_module_id) :
		id(in_graphics_material_module_id)
	{  }

	GraphicsMaterialModule(const GraphicsMaterialModule& graphicsMaterialModule) :
		id(Cmiss_graphics_material_module_access(graphicsMaterialModule.id))
	{  }

	GraphicsMaterialModule& operator=(const GraphicsMaterialModule& graphicsMaterialModule)
	{
		Cmiss_graphics_material_module_id temp_id = Cmiss_graphics_material_module_access(
			graphicsMaterialModule.id);
		if (0 != id)
		{
			Cmiss_graphics_material_module_destroy(&id);
		}
		id = temp_id;
		return *this;
	}

	~GraphicsMaterialModule()
	{
		if (0 != id)
		{
			Cmiss_graphics_material_module_destroy(&id);
		}
	}

	bool isValid()
	{
		return (0 != id);
	}

	Cmiss_graphics_material_module_id getId()
	{
		return id;
	}

	GraphicsMaterial createGraphicsMaterial()
	{
		return GraphicsMaterial(Cmiss_graphics_material_module_create_material(id));
	}

	GraphicsMaterial findGraphicsMaterialByName(const char *name)
	{
		return GraphicsMaterial(Cmiss_graphics_material_module_find_material_by_name(id, name));
	}

	int beginChange()
	{
		return Cmiss_graphics_material_module_begin_change(id);
	}

	int endChange()
	{
		return Cmiss_graphics_material_module_end_change(id);
	}

	int defineStandardMaterials()
	{
		return Cmiss_graphics_material_module_define_standard_materials(id);
	}

	GraphicsMaterial getDefaultGraphicsMaterial()
	{
		return GraphicsMaterial(Cmiss_graphics_material_module_get_default_material(id));
	}

	int setDefaultGraphicsMaterial(GraphicsMaterial &graphicsMaterial)
	{
		return Cmiss_graphics_material_module_set_default_material(id, graphicsMaterial.getId());
	}

	GraphicsMaterial getDefaultSelectedGraphicsMaterial()
	{
		return GraphicsMaterial(Cmiss_graphics_material_module_get_default_selected_material(id));
	}

	int setDefaultSelectedGraphicsMaterial(GraphicsMaterial &graphicsMaterial)
	{
		return Cmiss_graphics_material_module_set_default_selected_material(id, graphicsMaterial.getId());
	}
};

} // namespace Cmiss

#endif /* __ZN_CMISS_GRAPHICS_MATERIAL_HPP__ */
<commit_msg>Changed cpp graphics material module to use a shorter name. https://tracker.physiomeproject.org/show_bug.cgi?id=3589<commit_after>/***************************************************************************//**
 * FILE : graphicsmaterial.hpp
 */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is libZinc.
 *
 * The Initial Developer of the Original Code is
 * Auckland Uniservices Ltd, Auckland, New Zealand.
 * Portions created by the Initial Developer are Copyright (C) 2012
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
#ifndef __ZN_CMISS_GRAPHICS_MATERIAL_HPP__
#define __ZN_CMISS_GRAPHICS_MATERIAL_HPP__

#include "zinc/graphicsmaterial.h"
#include "zinc/fieldimage.h"
#include "zinc/field.hpp"

namespace zinc
{

class GraphicsMaterial
{

protected:
	Cmiss_graphics_material_id id;

public:

	GraphicsMaterial() : id(0)
	{ }

	// takes ownership of C handle, responsibility for destroying it
	explicit GraphicsMaterial(Cmiss_graphics_material_id graphics_material_id) :
		id(graphics_material_id)
	{ }

	GraphicsMaterial(const GraphicsMaterial& graphicsMaterial) :
		id(Cmiss_graphics_material_access(graphicsMaterial.id))
	{ }

	GraphicsMaterial& operator=(const GraphicsMaterial& graphicsMaterial)
	{
		Cmiss_graphics_material_id temp_id = Cmiss_graphics_material_access(graphicsMaterial.id);
		if (0 != id)
		{
			Cmiss_graphics_material_destroy(&id);
		}
		id = temp_id;
		return *this;
	}

	~GraphicsMaterial()
	{
		if (0 != id)
		{
			Cmiss_graphics_material_destroy(&id);
		}
	}

	bool isValid()
	{
		return (0 != id);
	}

	Cmiss_graphics_material_id getId()
	{
		return id;
	}

	enum Attribute
	{
		ATTRIBUTE_INVALID = CMISS_GRAPHICS_MATERIAL_ATTRIBUTE_INVALID,
		ATTRIBUTE_ALPHA = CMISS_GRAPHICS_MATERIAL_ATTRIBUTE_ALPHA,
		ATTRIBUTE_AMBIENT = CMISS_GRAPHICS_MATERIAL_ATTRIBUTE_AMBIENT,
		ATTRIBUTE_DIFFUSE = CMISS_GRAPHICS_MATERIAL_ATTRIBUTE_DIFFUSE,
		ATTRIBUTE_EMISSION = CMISS_GRAPHICS_MATERIAL_ATTRIBUTE_EMISSION,
		ATTRIBUTE_SHININESS = CMISS_GRAPHICS_MATERIAL_ATTRIBUTE_SHININESS,
		ATTRIBUTE_SPECULAR = CMISS_GRAPHICS_MATERIAL_ATTRIBUTE_SPECULAR
	};

	bool isManaged()
	{
		return Cmiss_graphics_material_is_managed(id);
	}

	int setManaged(bool value)
	{
		return Cmiss_graphics_material_set_managed(id, value);
	}

	double getAttributeReal(Attribute attribute)
	{
		return Cmiss_graphics_material_get_attribute_real(id,
			static_cast<Cmiss_graphics_material_attribute>(attribute));
	}

	int setAttributeReal(Attribute attribute, double value)
	{
		return Cmiss_graphics_material_set_attribute_real(id,
			static_cast<Cmiss_graphics_material_attribute>(attribute), value);
	}

	int getAttributeReal3(Attribute attribute, double *outValues)
	{
		return Cmiss_graphics_material_get_attribute_real3(id,
			static_cast<Cmiss_graphics_material_attribute>(attribute), outValues);
	}

	int setAttributeReal3(Attribute attribute, const double *values)
	{
		return Cmiss_graphics_material_set_attribute_real3(id,
			static_cast<Cmiss_graphics_material_attribute>(attribute), values);
	}

	char *getName()
	{
		return Cmiss_graphics_material_get_name(id);
	}

	int setName(const char *name)
	{
		return Cmiss_graphics_material_set_name(id, name);
	}

	int setImageField(int imageNumber, Field &imageField)
	{
		Cmiss_field_image_id field_image = Cmiss_field_cast_image(imageField.getId());
		int result = Cmiss_graphics_material_set_image_field(id, imageNumber, field_image);
		Cmiss_field_image_destroy(&field_image);

		return result;
	}

};

class GraphicsMaterialModule
{
protected:
	Cmiss_graphics_material_module_id id;

public:

	GraphicsMaterialModule() : id(0)
	{  }

	// takes ownership of C handle, responsibility for destroying it
	explicit GraphicsMaterialModule(Cmiss_graphics_material_module_id in_graphics_material_module_id) :
		id(in_graphics_material_module_id)
	{  }

	GraphicsMaterialModule(const GraphicsMaterialModule& graphicsMaterialModule) :
		id(Cmiss_graphics_material_module_access(graphicsMaterialModule.id))
	{  }

	GraphicsMaterialModule& operator=(const GraphicsMaterialModule& graphicsMaterialModule)
	{
		Cmiss_graphics_material_module_id temp_id = Cmiss_graphics_material_module_access(
			graphicsMaterialModule.id);
		if (0 != id)
		{
			Cmiss_graphics_material_module_destroy(&id);
		}
		id = temp_id;
		return *this;
	}

	~GraphicsMaterialModule()
	{
		if (0 != id)
		{
			Cmiss_graphics_material_module_destroy(&id);
		}
	}

	bool isValid()
	{
		return (0 != id);
	}

	Cmiss_graphics_material_module_id getId()
	{
		return id;
	}

	GraphicsMaterial createMaterial()
	{
		return GraphicsMaterial(Cmiss_graphics_material_module_create_material(id));
	}

	GraphicsMaterial findMaterialByName(const char *name)
	{
		return GraphicsMaterial(Cmiss_graphics_material_module_find_material_by_name(id, name));
	}

	int beginChange()
	{
		return Cmiss_graphics_material_module_begin_change(id);
	}

	int endChange()
	{
		return Cmiss_graphics_material_module_end_change(id);
	}

	int defineStandardMaterials()
	{
		return Cmiss_graphics_material_module_define_standard_materials(id);
	}

	GraphicsMaterial getDefaultMaterial()
	{
		return GraphicsMaterial(Cmiss_graphics_material_module_get_default_material(id));
	}

	int setDefaultMaterial(GraphicsMaterial &graphicsMaterial)
	{
		return Cmiss_graphics_material_module_set_default_material(id, graphicsMaterial.getId());
	}

	GraphicsMaterial getDefaultSelectedMaterial()
	{
		return GraphicsMaterial(Cmiss_graphics_material_module_get_default_selected_material(id));
	}

	int setDefaultSelectedMaterial(GraphicsMaterial &graphicsMaterial)
	{
		return Cmiss_graphics_material_module_set_default_selected_material(id, graphicsMaterial.getId());
	}
};

} // namespace Cmiss

#endif /* __ZN_CMISS_GRAPHICS_MATERIAL_HPP__ */
<|endoftext|>