<commit_before>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

#include "NormalMap.h"
#include "Filter.h"
#include "FloatImage.h"
#include "Image.h"

#include "nvmath/Color.inl"
#include "nvmath/Vector.h"

#include "nvcore/Ptr.h"

using namespace nv;

// Create normal map using the given kernels.
static FloatImage * createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, const Kernel2 * kdu, const Kernel2 * kdv)
{
    nvDebugCheck(kdu != NULL);
    nvDebugCheck(kdv != NULL);
    nvDebugCheck(img != NULL);

    const uint w = img->width();
    const uint h = img->height();

    AutoPtr<FloatImage> fimage(new FloatImage());
    fimage->allocate(4, w, h);

    // Compute height and store in alpha channel:
    float * alphaChannel = fimage->channel(3);
    for(uint i = 0; i < w * h; i++)
    {
        Vector4 color = toVector4(img->pixel(i));
        alphaChannel[i] = dot(color, heightWeights);
    }

    float heightScale = 1.0f / 16.0f;	// @@ Use a user defined factor.

    for(uint y = 0; y < h; y++)
    {
        for(uint x = 0; x < w; x++)
        {
            const float du = fimage->applyKernelXY(kdu, x, y, 0, 3, wm);
            const float dv = fimage->applyKernelXY(kdv, x, y, 0, 3, wm);

            Vector3 n = normalize(Vector3(du, dv, heightScale));

            fimage->pixel(x, y, 0, 0) = 0.5f * n.x + 0.5f;
            fimage->pixel(x, y, 0, 1) = 0.5f * n.y + 0.5f;
            fimage->pixel(x, y, 0, 2) = 0.5f * n.z + 0.5f;
        }
    }

    return fimage.release();
}

// Create normal map using the given kernels.
static FloatImage * createNormalMap(const FloatImage * img, FloatImage::WrapMode wm, const Kernel2 * kdu, const Kernel2 * kdv)
{
    nvDebugCheck(kdu != NULL);
    nvDebugCheck(kdv != NULL);
    nvDebugCheck(img != NULL);

#pragma NV_MESSAGE("FIXME: Height scale parameter should go away. It should be a sensible value that produces good results when the heightmap is in the [0, 1] range.")
    const float heightScale = 1.0f / 16.0f;

    const uint w = img->width();
    const uint h = img->height();

    AutoPtr<FloatImage> img_out(new FloatImage());
    img_out->allocate(4, w, h);

    for (uint y = 0; y < h; y++)
    {
        for (uint x = 0; x < w; x++)
        {
            const float du = img->applyKernelXY(kdu, x, y, 0, 3, wm);
            const float dv = img->applyKernelXY(kdv, x, y, 0, 3, wm);

            Vector3 n = normalize(Vector3(du, dv, heightScale));

	    img_out->pixel(x, y, 0, 0) = n.x;
	    img_out->pixel(x, y, 0, 1) = n.y;
	    img_out->pixel(x, y, 0, 2) = n.z;
	}
    }

    // Copy alpha channel.
    for (uint y = 0; y < h; y++)
    {
        for (uint x = 0; x < w; x++)
        {
            img_out->pixel(x, y, 0, 3) = img->pixel(x, y, 0, 3);
        }
    }

    return img_out.release();
}

/// Create normal map using the given filter.
FloatImage * nv::createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, NormalMapFilter filter /*= Sobel3x3*/)
{
    nvDebugCheck(img != NULL);

    // Init the kernels.
    Kernel2 * kdu = NULL;
    Kernel2 * kdv = NULL;

    switch(filter)
    {
        case NormalMapFilter_Sobel3x3:
            kdu = new Kernel2(3);
            break;
        case NormalMapFilter_Sobel5x5:
            kdu = new Kernel2(5);
            break;
        case NormalMapFilter_Sobel7x7:
            kdu = new Kernel2(7);
            break;
        case NormalMapFilter_Sobel9x9:
            kdu = new Kernel2(9);
            break;
        default:
            nvDebugCheck(false);
    };

    kdu->initSobel();
    kdu->normalize();

    kdv = new Kernel2(*kdu);
    kdv->transpose();

    return ::createNormalMap(img, wm, heightWeights, kdu, kdv);
}

/// Create normal map combining multiple sobel filters.
FloatImage * nv::createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, Vector4::Arg filterWeights)
{
    nvDebugCheck(img != NULL);

    Kernel2 * kdu = NULL;
    Kernel2 * kdv = NULL;

    kdu = new Kernel2(9);
    kdu->initBlendedSobel(filterWeights);
    kdu->normalize();

    kdv = new Kernel2(*kdu);
    kdv->transpose();

    return ::createNormalMap(img, wm, heightWeights, kdu, kdv);
}

FloatImage * nv::createNormalMap(const FloatImage * img, FloatImage::WrapMode wm, Vector4::Arg filterWeights)
{
    nvDebugCheck(img != NULL);

    Kernel2 * kdu = NULL;
    Kernel2 * kdv = NULL;

    kdu = new Kernel2(9);
    kdu->initBlendedSobel(filterWeights);
    kdu->normalize();

    kdv = new Kernel2(*kdu);
    kdv->transpose();

    return ::createNormalMap(img, wm, kdu, kdv);
}

/// Normalize the given image in place.
void nv::normalizeNormalMap(FloatImage * img)
{
    nvDebugCheck(img != NULL);

    img->normalize(0);
}

<commit_msg>Fix issue 206.<commit_after>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

#include "NormalMap.h"
#include "Filter.h"
#include "FloatImage.h"
#include "Image.h"

#include "nvmath/Color.inl"
#include "nvmath/Vector.h"

#include "nvcore/Ptr.h"

#include <string.h> // memcpy

using namespace nv;

// Create normal map using the given kernels.
static FloatImage * createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, const Kernel2 * kdu, const Kernel2 * kdv)
{
    nvDebugCheck(kdu != NULL);
    nvDebugCheck(kdv != NULL);
    nvDebugCheck(img != NULL);

    const uint w = img->width();
    const uint h = img->height();

    AutoPtr<FloatImage> fimage(new FloatImage());
    fimage->allocate(4, w, h);

    // Compute height and store in alpha channel:
    float * alphaChannel = fimage->channel(3);
    for(uint i = 0; i < w * h; i++)
    {
        Vector4 color = toVector4(img->pixel(i));
        alphaChannel[i] = dot(color, heightWeights);
    }

    float heightScale = 1.0f / 16.0f;	// @@ Use a user defined factor.

    for(uint y = 0; y < h; y++)
    {
        for(uint x = 0; x < w; x++)
        {
            const float du = fimage->applyKernelXY(kdu, x, y, 0, 3, wm);
            const float dv = fimage->applyKernelXY(kdv, x, y, 0, 3, wm);

            Vector3 n = normalize(Vector3(du, dv, heightScale));

            fimage->pixel(0, x, y, 0) = 0.5f * n.x + 0.5f;
            fimage->pixel(1, x, y, 0) = 0.5f * n.y + 0.5f;
            fimage->pixel(2, x, y, 0) = 0.5f * n.z + 0.5f;
        }
    }

    return fimage.release();
}

// Create normal map using the given kernels.
static FloatImage * createNormalMap(const FloatImage * img, FloatImage::WrapMode wm, const Kernel2 * kdu, const Kernel2 * kdv)
{
    nvDebugCheck(kdu != NULL);
    nvDebugCheck(kdv != NULL);
    nvDebugCheck(img != NULL);

#pragma NV_MESSAGE("FIXME: Height scale parameter should go away. It should be a sensible value that produces good results when the heightmap is in the [0, 1] range.")
    const float heightScale = 1.0f / 16.0f;

    const uint w = img->width();
    const uint h = img->height();

    AutoPtr<FloatImage> img_out(new FloatImage());
    img_out->allocate(4, w, h);

    for (uint y = 0; y < h; y++)
    {
        for (uint x = 0; x < w; x++)
        {
            const float du = img->applyKernelXY(kdu, x, y, 0, 3, wm);
            const float dv = img->applyKernelXY(kdv, x, y, 0, 3, wm);

            Vector3 n = normalize(Vector3(du, dv, heightScale));

            img_out->pixel(0, x, y, 0) = n.x;
            img_out->pixel(1, x, y, 0) = n.y;
            img_out->pixel(2, x, y, 0) = n.z;
        }
    }

    // Copy alpha channel.
    /*for (uint y = 0; y < h; y++)
    {
        for (uint x = 0; x < w; x++)
        {

            img_out->pixel(3, x, y, 0) = img->pixel(3, x, y, 0);
        }
    }*/
    memcpy(img_out->channel(3), img->channel(3), w * h * sizeof(float));

    return img_out.release();
}

/// Create normal map using the given filter.
FloatImage * nv::createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, NormalMapFilter filter /*= Sobel3x3*/)
{
    nvDebugCheck(img != NULL);

    // Init the kernels.
    Kernel2 * kdu = NULL;
    Kernel2 * kdv = NULL;

    switch(filter)
    {
        case NormalMapFilter_Sobel3x3:
            kdu = new Kernel2(3);
            break;
        case NormalMapFilter_Sobel5x5:
            kdu = new Kernel2(5);
            break;
        case NormalMapFilter_Sobel7x7:
            kdu = new Kernel2(7);
            break;
        case NormalMapFilter_Sobel9x9:
            kdu = new Kernel2(9);
            break;
        default:
            nvDebugCheck(false);
    };

    kdu->initSobel();
    kdu->normalize();

    kdv = new Kernel2(*kdu);
    kdv->transpose();

    return ::createNormalMap(img, wm, heightWeights, kdu, kdv);
}

/// Create normal map combining multiple sobel filters.
FloatImage * nv::createNormalMap(const Image * img, FloatImage::WrapMode wm, Vector4::Arg heightWeights, Vector4::Arg filterWeights)
{
    nvDebugCheck(img != NULL);

    Kernel2 * kdu = NULL;
    Kernel2 * kdv = NULL;

    kdu = new Kernel2(9);
    kdu->initBlendedSobel(filterWeights);
    kdu->normalize();

    kdv = new Kernel2(*kdu);
    kdv->transpose();

    return ::createNormalMap(img, wm, heightWeights, kdu, kdv);
}

FloatImage * nv::createNormalMap(const FloatImage * img, FloatImage::WrapMode wm, Vector4::Arg filterWeights)
{
    nvDebugCheck(img != NULL);

    Kernel2 * kdu = NULL;
    Kernel2 * kdv = NULL;

    kdu = new Kernel2(9);
    kdu->initBlendedSobel(filterWeights);
    kdu->normalize();

    kdv = new Kernel2(*kdu);
    kdv->transpose();

    return ::createNormalMap(img, wm, kdu, kdv);
}

/// Normalize the given image in place.
void nv::normalizeNormalMap(FloatImage * img)
{
    nvDebugCheck(img != NULL);

    img->normalize(0);
}

<|endoftext|>


<commit_before>#include "Halide.h"
#include "HalideRuntimeCuda.h"

using namespace Halide;

int main(int argc, char **argv) {
    Target target = get_jit_target_from_environment();

    if (!target.has_gpu_feature() && !target.has_feature(Target::OpenGLCompute)) {
        printf("This is a gpu-specific test. Skipping it\n");
        return 0;
    }

    // We'll have two input buffers. For one we'll copy to the device
    // explicitly. For the other we'll do a device malloc and set
    // host_dirty.
    Buffer<float> a(100, 100), b(100, 100);

    assert(!a.host_dirty());
    a.fill(2.0f);
    assert(!a.has_device_allocation());
    assert(a.host_dirty());
    a.copy_to_device();
    assert(a.has_device_allocation());
    assert(!a.host_dirty());

    assert(!b.host_dirty());
    b.fill(3.0f);
    assert(!b.has_device_allocation());
    assert(b.host_dirty());
    b.device_malloc();
    assert(b.has_device_allocation());
    assert(b.host_dirty());

    Func f;
    Var x, y;
    f(x, y) = a(x, y) + b(x, y) + 2;
    f.gpu_tile(x, y, 8, 8);

    Buffer<float> out = f.realize(100, 100);

    // Here's a wart: b was copied to the device, but it still has
    // host_dirty set, because it is a *copy* of b's buffer_t that is
    // held by the pipeline, and this copy was passed to
    // copy_to_device. It's hard to fix this without keeping
    // references to user Buffers (which may leave scope before the
    // pipeline does!).
    assert(b.host_dirty()); // :(

    out.for_each_value([&](float f) {
        if (f != 7.0f) {
            printf("%f != 4.0f\n", f);
            abort();
        }
    });

    printf("Success!\n");
    return 0;
}
<commit_msg>Delete unnecessary include<commit_after>#include "Halide.h"

using namespace Halide;

int main(int argc, char **argv) {
    Target target = get_jit_target_from_environment();

    if (!target.has_gpu_feature() && !target.has_feature(Target::OpenGLCompute)) {
        printf("This is a gpu-specific test. Skipping it\n");
        return 0;
    }

    // We'll have two input buffers. For one we'll copy to the device
    // explicitly. For the other we'll do a device malloc and set
    // host_dirty.
    Buffer<float> a(100, 100), b(100, 100);

    assert(!a.host_dirty());
    a.fill(2.0f);
    assert(!a.has_device_allocation());
    assert(a.host_dirty());
    a.copy_to_device();
    assert(a.has_device_allocation());
    assert(!a.host_dirty());

    assert(!b.host_dirty());
    b.fill(3.0f);
    assert(!b.has_device_allocation());
    assert(b.host_dirty());
    b.device_malloc();
    assert(b.has_device_allocation());
    assert(b.host_dirty());

    Func f;
    Var x, y;
    f(x, y) = a(x, y) + b(x, y) + 2;
    f.gpu_tile(x, y, 8, 8);

    Buffer<float> out = f.realize(100, 100);

    // Here's a wart: b was copied to the device, but it still has
    // host_dirty set, because it is a *copy* of b's buffer_t that is
    // held by the pipeline, and this copy was passed to
    // copy_to_device. It's hard to fix this without keeping
    // references to user Buffers (which may leave scope before the
    // pipeline does!).
    assert(b.host_dirty()); // :(

    out.for_each_value([&](float f) {
        if (f != 7.0f) {
            printf("%f != 4.0f\n", f);
            abort();
        }
    });

    printf("Success!\n");
    return 0;
}
<|endoftext|>


<commit_before>/**
 *  Copyright (C) 2015 3D Repo Ltd
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

//------------------------------------------------------------------------------
// GUI
#include "repodialoguser.h"
#include "ui_repodialoguser.h"
#include "../primitives/repo_fontawesome.h"
#include "../primitives/repocomboboxeditor.h"

//------------------------------------------------------------------------------
// Qt
#include <QComboBox>
#include <QItemDelegate>
#include <QItemEditorFactory>
#include <QStandardItemEditorCreator>

repo::gui::RepoDialogUser::RepoDialogUser(
        core::RepoUser user,
        const std::list<std::string> &databaseList,
        QWidget *parent)
    : QDialog(parent)
    , user(user)
    , databaseList(databaseList)
    , ui(new Ui::RepoDialogUser)
{
    ui->setupUi(this);

    setWindowIcon(getIcon());

//    ui->addPushButton->setIcon(RepoFontAwesome::getInstance().getIcon(
//                                       RepoFontAwesome::fa_plus,
//                                       QColor(Qt::darkGreen)));
//    ui->deletePushButton->setIcon(RepoFontAwesome::getInstance().getIcon(
//                                       RepoFontAwesome::fa_minus,
//                                       QColor(Qt::darkRed)));
    ui->avatarPushButton->setIcon(RepoFontAwesome::getInstance().getIcon(
                                       RepoFontAwesome::fa_user,
                                       QColor(Qt::gray)));

    // Enable drop down selectors for editing delegate
    // See http://doc.qt.io/qt-5/qtwidgets-itemviews-coloreditorfactory-example.html
    QItemEditorFactory *factory = new QItemEditorFactory();

//    QItemEditorCreatorBase *itemListCreator =
//        new QStandardItemEditorCreator<RepoComboBoxEditor>();

    QItemEditorCreatorBase * myCombo = new RepoComboBoxEditor(databaseList);
    factory->registerEditor(QVariant::Color, myCombo);
    //QItemEditorFactory::setDefaultFactory(factory);

    QItemDelegate *delegate = new QItemDelegate();
    delegate->setItemEditorFactory(factory);
    ui->projectsTreeView->setItemDelegateForColumn(RepoProjectsColumns::OWNER, delegate);

    //--------------------------------------------------------------------------
    // Projects
    projectsModel = new QStandardItemModel(this);
    projectsModel->setColumnCount(2);
    projectsModel->setHeaderData(
                RepoProjectsColumns::OWNER,
                Qt::Horizontal,
                tr("Owner"));
    projectsModel->setHeaderData(
                RepoProjectsColumns::PROJECT,
                Qt::Horizontal,
                tr("Project"));
    ui->projectsTreeView->setModel(projectsModel);
    ui->projectsTreeView->sortByColumn(RepoProjectsColumns::OWNER, Qt::SortOrder::AscendingOrder);

    //--------------------------------------------------------------------------
    // DB Roles
    rolesModel = new QStandardItemModel(this);
    rolesModel->setColumnCount(2);
    rolesModel->setHeaderData(
                RepoProjectsColumns::OWNER,
                Qt::Horizontal,
                tr("Database"));
    rolesModel->setHeaderData(
                RepoProjectsColumns::PROJECT,
                Qt::Horizontal,
                tr("Role"));
    //ui->rolesTreeView->setModel(rolesModel);
    //ui->rolesTreeView->sortByColumn(RepoProjectsColumns::OWNER, Qt::SortOrder::AscendingOrder);

    //--------------------------------------------------------------------------
    // Populate user data
    if (!user.isEmpty())
    {
        ui->usernameLineEdit->setText(QString::fromStdString(user.getUsername()));
        ui->usernameLineEdit->setEnabled(false);
        ui->passwordLineEdit->setText(QString::fromStdString(user.getPassword()));
        ui->firstNameLineEdit->setText(QString::fromStdString(user.getFirstName()));
        ui->lastNameLineEdit->setText(QString::fromStdString(user.getLastName()));
        ui->emailLineEdit->setText(QString::fromStdString(user.getEmail()));

        //----------------------------------------------------------------------
        // Projects
        std::vector<std::pair<std::string, std::string> > projects = user.getProjects();
        this->populateModel(projectsModel, projects);

        //----------------------------------------------------------------------
        // DB Roles
        std::vector<std::pair<std::string, std::string> > roles = user.getRoles();
        this->populateModel(rolesModel, roles);

        QList<QTreeWidgetItem *> items;
        for (unsigned int i = 0; i < roles.size(); ++i)
        {

            QStringList list;
            list.append(QString::fromStdString(roles[i].first));
            list.append(QString::fromStdString(roles[i].second));

            QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0, list);
            ui->rolesTreeWidget->insertTopLevelItem(0, item);

            QComboBox *databaseComboBox = new QComboBox();
            databaseComboBox->addItem(QString::fromStdString(roles[i].first));
            databaseComboBox->addItem("admin");
            databaseComboBox->addItem("test");
            ui->rolesTreeWidget->setItemWidget(item, 0, databaseComboBox);

            QComboBox *roleComboBox = new QComboBox();
            roleComboBox->addItem(QString::fromStdString(roles[i].second));
            roleComboBox->addItem("admin");
            roleComboBox->addItem("test");
            ui->rolesTreeWidget->setItemWidget(item, 1, roleComboBox);

        }
    }
}

repo::gui::RepoDialogUser::~RepoDialogUser()
{
    delete projectsModel;
    delete rolesModel;
    delete ui;
}

QIcon repo::gui::RepoDialogUser::getIcon()
{
   return RepoFontAwesome::getInstance().getIcon(RepoFontAwesome::fa_user);
}

void repo::gui::RepoDialogUser::populateModel(
        QStandardItemModel *model,
        const std::vector<std::pair<std::string, std::string> > &data)
{
    for (unsigned int i = 0; i < data.size(); ++i)
    {
        QList<QStandardItem *> row;
        row.append(new QStandardItem(QString::fromStdString(data[i].first)));

        QStandardItem *item = new QStandardItem();//QString::fromStdString(data[i].second));
        item->setData(QColor("springgreen"), Qt::DisplayRole);
        row.append(item);
        model->invisibleRootItem()->appendRow(row);

       // model->setData(model->index(i, 0), new QComboBox());
    }
}

<commit_msg>Minor fix.<commit_after>/**
 *  Copyright (C) 2015 3D Repo Ltd
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

//------------------------------------------------------------------------------
// GUI
#include "repodialoguser.h"
#include "ui_repodialoguser.h"
#include "../primitives/repo_fontawesome.h"
#include "../primitives/repocomboboxeditor.h"

//------------------------------------------------------------------------------
// Qt
#include <QComboBox>
#include <QItemDelegate>
#include <QItemEditorFactory>
#include <QStandardItemEditorCreator>

repo::gui::RepoDialogUser::RepoDialogUser(
        core::RepoUser user,
        const std::list<std::string> &databaseList,
        QWidget *parent)
    : QDialog(parent)
    , user(user)
    , databaseList(databaseList)
    , ui(new Ui::RepoDialogUser)
{
    ui->setupUi(this);

    setWindowIcon(getIcon());

//    ui->addPushButton->setIcon(RepoFontAwesome::getInstance().getIcon(
//                                       RepoFontAwesome::fa_plus,
//                                       QColor(Qt::darkGreen)));
//    ui->deletePushButton->setIcon(RepoFontAwesome::getInstance().getIcon(
//                                       RepoFontAwesome::fa_minus,
//                                       QColor(Qt::darkRed)));
    ui->avatarPushButton->setIcon(RepoFontAwesome::getInstance().getIcon(
                                       RepoFontAwesome::fa_user,
                                       QColor(Qt::gray)));

    // Enable drop down selectors for editing delegate
    // See http://doc.qt.io/qt-5/qtwidgets-itemviews-coloreditorfactory-example.html
    QItemEditorFactory *factory = new QItemEditorFactory();

//    QItemEditorCreatorBase *itemListCreator =
//        new QStandardItemEditorCreator<RepoComboBoxEditor>();

    QItemEditorCreatorBase * myCombo = new RepoComboBoxEditor(databaseList);
    factory->registerEditor(QVariant::Color, myCombo);
    //QItemEditorFactory::setDefaultFactory(factory);

    QItemDelegate *delegate = new QItemDelegate();
    delegate->setItemEditorFactory(factory);
    ui->projectsTreeView->setItemDelegateForColumn(RepoProjectsColumns::PROJECT, delegate);

    //--------------------------------------------------------------------------
    // Projects
    projectsModel = new QStandardItemModel(this);
    projectsModel->setColumnCount(2);
    projectsModel->setHeaderData(
                RepoProjectsColumns::OWNER,
                Qt::Horizontal,
                tr("Owner"));
    projectsModel->setHeaderData(
                RepoProjectsColumns::PROJECT,
                Qt::Horizontal,
                tr("Project"));
    ui->projectsTreeView->setModel(projectsModel);
    ui->projectsTreeView->sortByColumn(RepoProjectsColumns::OWNER, Qt::SortOrder::AscendingOrder);

    //--------------------------------------------------------------------------
    // DB Roles
    rolesModel = new QStandardItemModel(this);
    rolesModel->setColumnCount(2);
    rolesModel->setHeaderData(
                RepoProjectsColumns::OWNER,
                Qt::Horizontal,
                tr("Database"));
    rolesModel->setHeaderData(
                RepoProjectsColumns::PROJECT,
                Qt::Horizontal,
                tr("Role"));
    //ui->rolesTreeView->setModel(rolesModel);
    //ui->rolesTreeView->sortByColumn(RepoProjectsColumns::OWNER, Qt::SortOrder::AscendingOrder);

    //--------------------------------------------------------------------------
    // Populate user data
    if (!user.isEmpty())
    {
        ui->usernameLineEdit->setText(QString::fromStdString(user.getUsername()));
        ui->usernameLineEdit->setEnabled(false);
        ui->passwordLineEdit->setText(QString::fromStdString(user.getPassword()));
        ui->firstNameLineEdit->setText(QString::fromStdString(user.getFirstName()));
        ui->lastNameLineEdit->setText(QString::fromStdString(user.getLastName()));
        ui->emailLineEdit->setText(QString::fromStdString(user.getEmail()));

        //----------------------------------------------------------------------
        // Projects
        std::vector<std::pair<std::string, std::string> > projects = user.getProjects();
        this->populateModel(projectsModel, projects);

        //----------------------------------------------------------------------
        // DB Roles
        std::vector<std::pair<std::string, std::string> > roles = user.getRoles();
        this->populateModel(rolesModel, roles);

        QList<QTreeWidgetItem *> items;
        for (unsigned int i = 0; i < roles.size(); ++i)
        {

            QStringList list;
            list.append(QString::fromStdString(roles[i].first));
            list.append(QString::fromStdString(roles[i].second));

            QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0, list);
            ui->rolesTreeWidget->insertTopLevelItem(0, item);

            QComboBox *databaseComboBox = new QComboBox();
            databaseComboBox->addItem(QString::fromStdString(roles[i].first));
            databaseComboBox->addItem("admin");
            databaseComboBox->addItem("test");
            ui->rolesTreeWidget->setItemWidget(item, 0, databaseComboBox);

            QComboBox *roleComboBox = new QComboBox();
            roleComboBox->addItem(QString::fromStdString(roles[i].second));
            roleComboBox->addItem("admin");
            roleComboBox->addItem("test");
            ui->rolesTreeWidget->setItemWidget(item, 1, roleComboBox);

        }
    }
}

repo::gui::RepoDialogUser::~RepoDialogUser()
{
    delete projectsModel;
    delete rolesModel;
    delete ui;
}

QIcon repo::gui::RepoDialogUser::getIcon()
{
   return RepoFontAwesome::getInstance().getIcon(RepoFontAwesome::fa_user);
}

void repo::gui::RepoDialogUser::populateModel(
        QStandardItemModel *model,
        const std::vector<std::pair<std::string, std::string> > &data)
{
    for (unsigned int i = 0; i < data.size(); ++i)
    {
        QList<QStandardItem *> row;
        row.append(new QStandardItem(QString::fromStdString(data[i].first)));

        QStandardItem *item = new QStandardItem();//QString::fromStdString(data[i].second));
        item->setData(QColor("springgreen"), Qt::DisplayRole);
        row.append(item);
        model->invisibleRootItem()->appendRow(row);

       // model->setData(model->index(i, 0), new QComboBox());
    }
}

<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "sppmphotontracer.h"

// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/kernel/lighting/sppm/sppmphoton.h"
#include "renderer/kernel/lighting/lightsampler.h"
#include "renderer/kernel/lighting/pathtracer.h"
#include "renderer/kernel/lighting/pathvertex.h"
#include "renderer/kernel/shading/shadingpoint.h"
#include "renderer/kernel/shading/shadingray.h"
#include "renderer/modeling/bsdf/bsdf.h"
#include "renderer/modeling/edf/edf.h"
#include "renderer/modeling/input/inputevaluator.h"
#include "renderer/modeling/scene/assemblyinstance.h"
#include "renderer/utility/transformsequence.h"

// appleseed.foundation headers.
#include "foundation/math/basis.h"
#include "foundation/math/hash.h"
#include "foundation/math/rng.h"
#include "foundation/math/vector.h"
#include "foundation/platform/types.h"
#include "foundation/utility/string.h"

// Standard headers.
#include <cassert>
#include <cstddef>

using namespace foundation;

namespace renderer
{

SPPMPhotonTracer::SPPMPhotonTracer(
    const LightSampler&     light_sampler,
    const TraceContext&     trace_context,
    TextureStore&           texture_store)
  : m_light_sampler(light_sampler)
  , m_texture_cache(texture_store)
  , m_intersector(trace_context, m_texture_cache /*, m_params.m_report_self_intersections*/)
{
}

void SPPMPhotonTracer::trace_photons(
    SPPMPhotonVector&       photons,
    const size_t            pass_hash,
    const size_t            photon_count)
{
    RENDERER_LOG_INFO(
        "tracing %s sppm %s...",
        pretty_uint(photon_count).c_str(),
        photon_count > 1 ? "photons" : "photon");

    MersenneTwister rng(static_cast<uint32>(pass_hash));
    SamplingContext sampling_context(
        rng,
        4,
        0,                  // number of samples -- unknown
        pass_hash);

    photons.reserve(photon_count);

    for (size_t i = 0; i < photon_count; ++i)
        trace_photon(photons, sampling_context);
}

void SPPMPhotonTracer::trace_photon(
    SPPMPhotonVector&       photons,
    SamplingContext&        sampling_context)
{
    LightSample light_sample;
    m_light_sampler.sample(sampling_context.next_vector2<4>(), light_sample);

    if (light_sample.m_triangle)
    {
        trace_emitting_triangle_photon(
            photons,
            sampling_context,
            light_sample);
    }
    else
    {
        trace_non_physical_light_photon(
            photons,
            sampling_context,
            light_sample);
    }
}

namespace
{
    struct PathVisitor
    {
        const Spectrum          m_initial_flux;         // initial particle flux (in W)
        const bool              m_cast_indirect_light;
        SPPMPhotonVector&       m_photons;

        PathVisitor(
            const Spectrum&     initial_flux,
            const bool          cast_indirect_light,
            SPPMPhotonVector&   photons)
          : m_initial_flux(initial_flux)
          , m_cast_indirect_light(cast_indirect_light)
          , m_photons(photons)
        {
        }

        bool accept_scattering_mode(
            const BSDF::Mode    prev_bsdf_mode,
            const BSDF::Mode    bsdf_mode) const
        {
            assert(bsdf_mode != BSDF::Absorption);
            return true;
        }

        bool visit_vertex(const PathVertex& vertex)
        {
            assert(vertex.m_path_length == 1 || m_cast_indirect_light);

            // Don't store photons on surfaces without a BSDF.
            if (vertex.m_bsdf == 0)
                return true;

            // Don't store photons on purely specular surfaces.
            if (vertex.m_bsdf->is_purely_specular())
                return true;

            SPPMPhoton photon;
            photon.m_position = vertex.get_point();
            photon.m_data.m_incoming = Vector3f(vertex.m_outgoing);
            photon.m_data.m_geometric_normal = Vector3f(vertex.get_geometric_normal());
            photon.m_data.m_flux = m_initial_flux;
            photon.m_data.m_flux *= vertex.m_throughput;
            m_photons.push_back(photon);

            return m_cast_indirect_light;
        }

        void visit_environment(
            const ShadingPoint& shading_point,
            const Vector3d&     outgoing,
            const BSDF::Mode    prev_bsdf_mode,
            const double        prev_bsdf_prob,
            const Spectrum&     throughput)
        {
            // The photon escapes, nothing to do.
        }
    };
}

void SPPMPhotonTracer::trace_emitting_triangle_photon(
    SPPMPhotonVector&       photons,
    SamplingContext&        sampling_context,
    LightSample&            light_sample)
{
    // Make sure the geometric normal of the light sample is in the same hemisphere as the shading normal.
    light_sample.m_geometric_normal =
        flip_to_same_hemisphere(
            light_sample.m_geometric_normal,
            light_sample.m_shading_normal);

    const EDF* edf = light_sample.m_triangle->m_edf;

    // Evaluate the EDF inputs.
    InputEvaluator input_evaluator(m_texture_cache);
    const void* edf_data =
        input_evaluator.evaluate(edf->get_inputs(), light_sample.m_bary);

    // Sample the EDF.
    SamplingContext child_sampling_context = sampling_context.split(2, 1);
    Vector3d emission_direction;
    Spectrum edf_value;
    double edf_prob;
    edf->sample(
        edf_data,
        light_sample.m_geometric_normal,
        Basis3d(light_sample.m_shading_normal),
        child_sampling_context.next_vector2<2>(),
        emission_direction,
        edf_value,
        edf_prob);

    // Compute the initial particle weight.
    Spectrum initial_flux = edf_value;
    initial_flux *=
        static_cast<float>(
            dot(emission_direction, light_sample.m_shading_normal)
                / (light_sample.m_probability * edf_prob));

    // Make a shading point that will be used to avoid self-intersections with the light sample.
    ShadingPoint parent_shading_point;
    light_sample.make_shading_point(
        parent_shading_point,
        emission_direction,
        m_intersector);

    // Build the light ray.
    child_sampling_context.split_in_place(1, 1);
    const ShadingRay light_ray(
        light_sample.m_point,
        emission_direction,
        child_sampling_context.next_double2(),
        ~0);

    // Build the path tracer.
    const bool cast_indirect_light = (edf->get_flags() & EDF::CastIndirectLight) != 0;
    PathVisitor path_visitor(
        initial_flux,
        cast_indirect_light,
        photons);
    PathTracer<PathVisitor, true> path_tracer(      // true = adjoint
        path_visitor,
        3,                                          // m_params.m_rr_min_path_length
        ~0,                                         // m_params.m_max_path_length
        1000);                                      // m_params.m_max_iterations

    // Trace the light path.
    const size_t path_length =
        path_tracer.trace(
            child_sampling_context,
            m_intersector,
            m_texture_cache,
            light_ray,
            &parent_shading_point);

    // Update path statistics.
    //++m_path_count;
    //m_path_length.insert(path_length);
}

void SPPMPhotonTracer::trace_non_physical_light_photon(
    SPPMPhotonVector&       photons,
    SamplingContext&        sampling_context,
    LightSample&            light_sample)
{
}

}   // namespace renderer
<commit_msg>the sppm lighting engine now supports non-physical lights.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "sppmphotontracer.h"

// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/kernel/lighting/sppm/sppmphoton.h"
#include "renderer/kernel/lighting/lightsampler.h"
#include "renderer/kernel/lighting/pathtracer.h"
#include "renderer/kernel/lighting/pathvertex.h"
#include "renderer/kernel/shading/shadingpoint.h"
#include "renderer/kernel/shading/shadingray.h"
#include "renderer/modeling/bsdf/bsdf.h"
#include "renderer/modeling/edf/edf.h"
#include "renderer/modeling/input/inputevaluator.h"
#include "renderer/modeling/light/light.h"
#include "renderer/modeling/scene/assemblyinstance.h"
#include "renderer/utility/transformsequence.h"

// appleseed.foundation headers.
#include "foundation/math/basis.h"
#include "foundation/math/hash.h"
#include "foundation/math/rng.h"
#include "foundation/math/transform.h"
#include "foundation/math/vector.h"
#include "foundation/platform/types.h"
#include "foundation/utility/string.h"

// Standard headers.
#include <cassert>
#include <cstddef>

using namespace foundation;

namespace renderer
{

SPPMPhotonTracer::SPPMPhotonTracer(
    const LightSampler&     light_sampler,
    const TraceContext&     trace_context,
    TextureStore&           texture_store)
  : m_light_sampler(light_sampler)
  , m_texture_cache(texture_store)
  , m_intersector(trace_context, m_texture_cache /*, m_params.m_report_self_intersections*/)
{
}

void SPPMPhotonTracer::trace_photons(
    SPPMPhotonVector&       photons,
    const size_t            pass_hash,
    const size_t            photon_count)
{
    RENDERER_LOG_INFO(
        "tracing %s sppm %s...",
        pretty_uint(photon_count).c_str(),
        photon_count > 1 ? "photons" : "photon");

    MersenneTwister rng(static_cast<uint32>(pass_hash));
    SamplingContext sampling_context(
        rng,
        4,
        0,                  // number of samples -- unknown
        pass_hash);

    photons.reserve(photon_count);

    for (size_t i = 0; i < photon_count; ++i)
        trace_photon(photons, sampling_context);
}

void SPPMPhotonTracer::trace_photon(
    SPPMPhotonVector&       photons,
    SamplingContext&        sampling_context)
{
    LightSample light_sample;
    m_light_sampler.sample(sampling_context.next_vector2<4>(), light_sample);

    if (light_sample.m_triangle)
    {
        trace_emitting_triangle_photon(
            photons,
            sampling_context,
            light_sample);
    }
    else
    {
        trace_non_physical_light_photon(
            photons,
            sampling_context,
            light_sample);
    }
}

namespace
{
    struct PathVisitor
    {
        const Spectrum          m_initial_flux;         // initial particle flux (in W)
        const bool              m_cast_indirect_light;
        SPPMPhotonVector&       m_photons;

        PathVisitor(
            const Spectrum&     initial_flux,
            const bool          cast_indirect_light,
            SPPMPhotonVector&   photons)
          : m_initial_flux(initial_flux)
          , m_cast_indirect_light(cast_indirect_light)
          , m_photons(photons)
        {
        }

        bool accept_scattering_mode(
            const BSDF::Mode    prev_bsdf_mode,
            const BSDF::Mode    bsdf_mode) const
        {
            assert(bsdf_mode != BSDF::Absorption);
            return true;
        }

        bool visit_vertex(const PathVertex& vertex)
        {
            assert(vertex.m_path_length == 1 || m_cast_indirect_light);

            // Don't store photons on surfaces without a BSDF.
            if (vertex.m_bsdf == 0)
                return true;

            // Don't store photons on purely specular surfaces.
            if (vertex.m_bsdf->is_purely_specular())
                return true;

            SPPMPhoton photon;
            photon.m_position = vertex.get_point();
            photon.m_data.m_incoming = Vector3f(vertex.m_outgoing);
            photon.m_data.m_geometric_normal = Vector3f(vertex.get_geometric_normal());
            photon.m_data.m_flux = m_initial_flux;
            photon.m_data.m_flux *= vertex.m_throughput;
            m_photons.push_back(photon);

            return m_cast_indirect_light;
        }

        void visit_environment(
            const ShadingPoint& shading_point,
            const Vector3d&     outgoing,
            const BSDF::Mode    prev_bsdf_mode,
            const double        prev_bsdf_prob,
            const Spectrum&     throughput)
        {
            // The photon escapes, nothing to do.
        }
    };
}

void SPPMPhotonTracer::trace_emitting_triangle_photon(
    SPPMPhotonVector&       photons,
    SamplingContext&        sampling_context,
    LightSample&            light_sample)
{
    // Make sure the geometric normal of the light sample is in the same hemisphere as the shading normal.
    light_sample.m_geometric_normal =
        flip_to_same_hemisphere(
            light_sample.m_geometric_normal,
            light_sample.m_shading_normal);

    const EDF* edf = light_sample.m_triangle->m_edf;

    // Evaluate the EDF inputs.
    InputEvaluator input_evaluator(m_texture_cache);
    const void* edf_data =
        input_evaluator.evaluate(edf->get_inputs(), light_sample.m_bary);

    // Sample the EDF.
    SamplingContext child_sampling_context = sampling_context.split(2, 1);
    Vector3d emission_direction;
    Spectrum edf_value;
    double edf_prob;
    edf->sample(
        edf_data,
        light_sample.m_geometric_normal,
        Basis3d(light_sample.m_shading_normal),
        child_sampling_context.next_vector2<2>(),
        emission_direction,
        edf_value,
        edf_prob);

    // Compute the initial particle weight.
    Spectrum initial_flux = edf_value;
    initial_flux *=
        static_cast<float>(
            dot(emission_direction, light_sample.m_shading_normal)
                / (light_sample.m_probability * edf_prob));

    // Make a shading point that will be used to avoid self-intersections with the light sample.
    ShadingPoint parent_shading_point;
    light_sample.make_shading_point(
        parent_shading_point,
        emission_direction,
        m_intersector);

    // Build the light ray.
    child_sampling_context.split_in_place(1, 1);
    const ShadingRay light_ray(
        light_sample.m_point,
        emission_direction,
        child_sampling_context.next_double2(),
        ~0);

    // Build the path tracer.
    const bool cast_indirect_light = (edf->get_flags() & EDF::CastIndirectLight) != 0;
    PathVisitor path_visitor(
        initial_flux,
        cast_indirect_light,
        photons);
    PathTracer<PathVisitor, true> path_tracer(      // true = adjoint
        path_visitor,
        3,                                          // m_params.m_rr_min_path_length
        ~0,                                         // m_params.m_max_path_length
        1000);                                      // m_params.m_max_iterations

    // Trace the light path.
    const size_t path_length =
        path_tracer.trace(
            child_sampling_context,
            m_intersector,
            m_texture_cache,
            light_ray,
            &parent_shading_point);

    // Update path statistics.
    //++m_path_count;
    //m_path_length.insert(path_length);
}

void SPPMPhotonTracer::trace_non_physical_light_photon(
    SPPMPhotonVector&       photons,
    SamplingContext&        sampling_context,
    LightSample&            light_sample)
{
    // Sample the light.
    InputEvaluator input_evaluator(m_texture_cache);
    SamplingContext child_sampling_context = sampling_context.split(2, 1);
    Vector3d emission_position, emission_direction;
    Spectrum light_value;
    double light_prob;
    light_sample.m_light->sample(
        input_evaluator,
        child_sampling_context.next_vector2<2>(),
        emission_position,
        emission_direction,
        light_value,
        light_prob);

    // Transform the emission position and direction from assembly space to world space.
    emission_position = light_sample.m_light_transform.point_to_parent(emission_position);
    emission_direction = normalize(light_sample.m_light_transform.vector_to_parent(emission_direction));

    // Compute the initial particle weight.
    Spectrum initial_flux = light_value;
    initial_flux /= static_cast<float>(light_sample.m_probability * light_prob);

    // Build the light ray.
    child_sampling_context.split_in_place(1, 1);
    const ShadingRay light_ray(
        emission_position,
        emission_direction,
        child_sampling_context.next_double2(),
        ~0);

    // Build the path tracer.
    const bool cast_indirect_light = (light_sample.m_light->get_flags() & EDF::CastIndirectLight) != 0;
    PathVisitor path_visitor(
        initial_flux,
        cast_indirect_light,
        photons);
    PathTracer<PathVisitor, true> path_tracer(      // true = adjoint
        path_visitor,
        3,                                          // m_params.m_rr_min_path_length
        ~0,                                         // m_params.m_max_path_length
        1000);                                      // m_params.m_max_iterations

    // Trace the light path.
    const size_t path_length =
        path_tracer.trace(
            child_sampling_context,
            m_intersector,
            m_texture_cache,
            light_ray);

    // Update path statistics.
    //++m_path_count;
    //m_path_length.insert(path_length);
}

}   // namespace renderer
<|endoftext|>


<commit_before>// This file serves to seperate encoding of data outputs from the main mastercore.cpp/h files.
#include "omnicore_encoding.h"

#include "mastercore.h"
#include "mastercore_script.h"
#include "omnicore_utils.h"

#include "base58.h"
#include "pubkey.h"
#include "random.h"
#include "script/script.h"
#include "script/standard.h"
#include "utilstrencodings.h"

#include <stdint.h>
#include <string>
#include <utility>
#include <vector>

bool OmniCore_Encode_ClassB(const std::string& senderAddress, const CPubKey& redeemingPubKey, const std::vector<unsigned char>& vecPayload, std::vector<std::pair <CScript,int64_t> >& vecOutputs)
{
    int nRemainingBytes = vecPayload.size();
    int nNextByte = 0;
    unsigned char seqNum = 1;
    std::string strObfuscatedHashes[1+MAX_SHA256_OBFUSCATION_TIMES];
    PrepareObfuscatedHashes(senderAddress, strObfuscatedHashes);
    while (nRemainingBytes > 0) {
        int nKeys = 1; // assume one key of data since we have data remaining
        if (nRemainingBytes > (PACKET_SIZE - 1)) { nKeys += 1; } // we have enough data for 2 keys in this output
        std::vector<CPubKey> keys;
        keys.push_back(redeemingPubKey); // always include the redeeming pubkey
        for (int i = 0; i < nKeys; i++) {
            std::vector<unsigned char> fakeKey;
            fakeKey.push_back(seqNum); // add sequence number
            int numBytes = nRemainingBytes < (PACKET_SIZE - 1) ? nRemainingBytes: (PACKET_SIZE - 1); // add up to 30 bytes of data
            fakeKey.insert(fakeKey.end(), vecPayload.begin() + nNextByte, vecPayload.begin() + nNextByte + numBytes);
            nNextByte += numBytes;
            nRemainingBytes -= numBytes;
            while (fakeKey.size() < PACKET_SIZE) { fakeKey.push_back(0); } // pad to 31 total bytes with zeros
            std::vector<unsigned char>hash = ParseHex(strObfuscatedHashes[seqNum]);
            for (int j = 0; j < PACKET_SIZE; j++) { // xor in the obfuscation
                fakeKey[j] = fakeKey[j] ^ hash[j];
            }
            fakeKey.insert(fakeKey.begin(), 2); // prepend the 2
            CPubKey pubKey;
            fakeKey.resize(33);
            unsigned char random_byte = (unsigned char)(GetRand(256)); // fix up the ecdsa code point
            for (int j = 0; i < 256 ; j++) {
                fakeKey[32] = random_byte;
                pubKey = CPubKey(fakeKey);
                if (pubKey.IsFullyValid()) break;
                ++random_byte; // cycle 256 times, if we must to find a valid ECDSA point
            }
            keys.push_back(pubKey);
            seqNum++;
        }
        CScript multisig_output = GetScriptForMultisig(1, keys);
        vecOutputs.push_back(std::make_pair(multisig_output, GetDustThreshold(multisig_output)));
    }
    CScript scriptPubKey = GetScriptForDestination(CBitcoinAddress(exodus_address).Get());
    vecOutputs.push_back(std::make_pair(scriptPubKey, GetDustThreshold(scriptPubKey))); // add the Exodus marker
    return true;
}

bool OmniCore_Encode_ClassC(const std::vector<unsigned char>& vecPayload, std::vector<std::pair <CScript,int64_t> >& vecOutputs)
{
    const unsigned char bytes[] = {0x6f,0x6d}; // define Omni marker bytes
    if (vecPayload.size()+sizeof(bytes)/sizeof(bytes[0]) > nMaxDatacarrierBytes) { return false; } // we shouldn't see this since classAgnostic_send handles size vs class, but include check here for safety
    std::vector<unsigned char> omniBytesPlusData(bytes, bytes+sizeof(bytes)/sizeof(bytes[0]));
    omniBytesPlusData.insert(omniBytesPlusData.end(), vecPayload.begin(), vecPayload.end());
    CScript script;
    script << OP_RETURN << omniBytesPlusData;
    vecOutputs.push_back(std::make_pair(script, 0));
    return true;
}
<commit_msg>Encoding: add encoding documentation and refine code consistency<commit_after>#include "omnicore_encoding.h"

#include "mastercore.h"
#include "mastercore_script.h"
#include "omnicore_utils.h"

#include "base58.h"
#include "pubkey.h"
#include "random.h"
#include "script/script.h"
#include "script/standard.h"
#include "utilstrencodings.h"

#include <stdint.h>
#include <string>
#include <utility>
#include <vector>

/**
 * Embedds a payload in obfuscated multisig outputs, and adds an Exodus marker output.
 *
 * @see The class B transaction encoding specification:
 * https://github.com/mastercoin-MSC/spec#class-b-transactions-also-known-as-the-multisig-method
 */
bool OmniCore_Encode_ClassB(const std::string& senderAddress, const CPubKey& redeemingPubKey,
        const std::vector<unsigned char>& vchPayload, std::vector<std::pair<CScript, int64_t> >& vecOutputs)
{
    int nRemainingBytes = vchPayload.size();
    int nNextByte = 0;
    unsigned char chSeqNum = 1;
    std::string strObfuscatedHashes[1+MAX_SHA256_OBFUSCATION_TIMES];
    PrepareObfuscatedHashes(senderAddress, strObfuscatedHashes);
    while (nRemainingBytes > 0) {
        int nKeys = 1; // Assume one key of data, because we have data remaining
        if (nRemainingBytes > (PACKET_SIZE - 1)) { nKeys += 1; } // ... or enough data to embed in 2 keys
        std::vector<CPubKey> vKeys;
        vKeys.push_back(redeemingPubKey); // Always include the redeeming pubkey
        for (int i = 0; i < nKeys; i++) {
            // Add up to 30 bytes of data
            int nCurrentBytes = nRemainingBytes < (PACKET_SIZE - 1) ? nRemainingBytes: (PACKET_SIZE - 1);
            std::vector<unsigned char> vchFakeKey;
            vchFakeKey.insert(vchFakeKey.end(), chSeqNum); // Add sequence number
            vchFakeKey.insert(vchFakeKey.end(), vchPayload.begin() + nNextByte,
                                                vchPayload.begin() + nNextByte + nCurrentBytes);
            vchFakeKey.resize(PACKET_SIZE); // Pad to 31 total bytes with zeros
            nNextByte += nCurrentBytes;
            nRemainingBytes -= nCurrentBytes;
            std::vector<unsigned char> vchHash = ParseHex(strObfuscatedHashes[chSeqNum]);
            for (int j = 0; j < PACKET_SIZE; j++) { // Xor in the obfuscation
                vchFakeKey[j] = vchFakeKey[j] ^ vchHash[j];
            }
            vchFakeKey.insert(vchFakeKey.begin(), 0x02); // Prepend a public key prefix
            vchFakeKey.resize(33);
            CPubKey pubKey;
            unsigned char chRandom = static_cast<unsigned char>(GetRand(256));
            for (int j = 0; i < 256 ; j++) { // Fix ECDSA coodinate
                vchFakeKey[32] = chRandom;
                pubKey = CPubKey(vchFakeKey);
                if (pubKey.IsFullyValid()) break;
                ++chRandom; // ... but cycle no more than 256 times to find a valid point
            }
            vKeys.push_back(pubKey);
            chSeqNum++;
        }

        // Push back a bare multisig output with obfuscated data
        CScript scriptMultisigOut = GetScriptForMultisig(1, vKeys);
        vecOutputs.push_back(std::make_pair(scriptMultisigOut, GetDustThreshold(scriptMultisigOut)));
    }

    // Add the Exodus marker output
    CScript scriptExodusOut = GetScriptForDestination(CBitcoinAddress(exodus_address).Get());
    vecOutputs.push_back(std::make_pair(scriptExodusOut, GetDustThreshold(scriptExodusOut)));
    return true;
}

/**
 * @return The marker for class C transactions.
 */
static inline std::vector<unsigned char> GetOmMarker()
{
    const unsigned char pch[] = {0x6f, 0x6d}; // Hex-encoded: "om"

    return std::vector<unsigned char>(pch, pch + sizeof (pch) / sizeof (pch[0]));
}

/**
 * Embedds a payload in an OP_RETURN output, prefixed with a transaction marker.
 *
 * The request is rejected, if the size of the payload with marker is larger than
 * the allowed data carrier size ("-datacarriersize=n").
 */
bool OmniCore_Encode_ClassC(const std::vector<unsigned char>& vchPayload,
        std::vector<std::pair <CScript, int64_t> >& vecOutputs)
{
    std::vector<unsigned char> vchData;
    std::vector<unsigned char> vchOmBytes = GetOmMarker();
    vchData.insert(vchData.end(), vchOmBytes.begin(), vchOmBytes.end());
    vchData.insert(vchData.end(), vchPayload.begin(), vchPayload.end());
    if (vchData.size() > nMaxDatacarrierBytes) { return false; }

    CScript script;
    script << OP_RETURN << vchData;
    vecOutputs.push_back(std::make_pair(script, 0));
    return true;
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/logging.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "googleurl/src/gurl.h"
#include "net/base/mock_host_resolver.h"

class ExtensionResourceRequestPolicyTest : public ExtensionApiTest {
 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kAllowLegacyExtensionManifests);
  }
};

// Note, this mostly tests the logic of chrome/renderer/extensions/
// extension_resource_request_policy.*, but we have it as a browser test so that
// can make sure it works end-to-end.
IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, OriginPrivileges) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());
  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("extension_resource_request_policy")
      .AppendASCII("extension")));

  GURL web_resource(
      test_server()->GetURL(
          "files/extensions/api_test/extension_resource_request_policy/"
          "index.html"));

  std::string host_a("a.com");
  GURL::Replacements make_host_a_com;
  make_host_a_com.SetHostStr(host_a);

  std::string host_b("b.com");
  GURL::Replacements make_host_b_com;
  make_host_b_com.SetHostStr(host_b);

  // A web host that has permission.
  ui_test_utils::NavigateToURL(
      browser(), web_resource.ReplaceComponents(make_host_a_com));
  std::string result;
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
    browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
    &result));
  EXPECT_EQ(result, "Loaded");

  // A web host that loads a non-existent extension.
  GURL non_existent_extension(
      test_server()->GetURL(
          "files/extensions/api_test/extension_resource_request_policy/"
          "non_existent_extension.html"));
  ui_test_utils::NavigateToURL(browser(), non_existent_extension);
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
    browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
    &result));
  EXPECT_EQ(result, "Image failed to load");

  // A data URL. Data URLs should always be able to load chrome-extension://
  // resources.
  std::string file_source;
  ASSERT_TRUE(file_util::ReadFileToString(
      test_data_dir_.AppendASCII("extension_resource_request_policy")
                    .AppendASCII("index.html"), &file_source));
  ui_test_utils::NavigateToURL(browser(),
      GURL(std::string("data:text/html;charset=utf-8,") + file_source));
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
      browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
      &result));
  EXPECT_EQ(result, "Loaded");

  // A different extension. Extensions should always be able to load each
  // other's resources.
  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("extension_resource_request_policy")
      .AppendASCII("extension2")));
  ui_test_utils::NavigateToURL(
      browser(),
      GURL("chrome-extension://pbkkcbgdkliohhfaeefcijaghglkahja/index.html"));
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
      browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
      &result));
  EXPECT_EQ(result, "Loaded");
}

IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest,
                       ExtensionCanLoadHostedAppIcons) {
  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("extension_resource_request_policy")
      .AppendASCII("extension")));

  ASSERT_TRUE(RunExtensionSubtest(
      "extension_resource_request_policy/extension2/",
      "can_load_icons_from_hosted_apps.html"));
}

IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, Audio) {
  EXPECT_TRUE(RunExtensionSubtest(
      "extension_resource_request_policy/extension2",
      "audio.html"));
}

#if defined(OS_MACOSX)
// http://crbug.com/95274 - Video is flaky on Mac.
#define MAYBE_Video DISABLED_Video
#else
#define MAYBE_Video Video
#endif

IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, MAYBE_Video) {
  EXPECT_TRUE(RunExtensionSubtest(
      "extension_resource_request_policy/extension2",
      "video.html"));
}

IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest,
                       WebAccessibleResources) {
  std::string result;
  ASSERT_TRUE(test_server()->Start());
  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("extension_resource_request_policy")
      .AppendASCII("web_accessible")));

  GURL accessible_resource(
      test_server()->GetURL(
          "files/extensions/api_test/extension_resource_request_policy/"
          "web_accessible/accessible_resource.html"));
  ui_test_utils::NavigateToURL(browser(), accessible_resource);
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
    browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
    &result));
  EXPECT_EQ("Loaded", result);

  GURL xhr_accessible_resource(
      test_server()->GetURL(
          "files/extensions/api_test/extension_resource_request_policy/"
          "web_accessible/xhr_accessible_resource.html"));
  ui_test_utils::NavigateToURL(
      browser(), xhr_accessible_resource);
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
    browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
    &result));
  EXPECT_EQ("XHR completed with status: 200", result);

  GURL xhr_inaccessible_resource(
      test_server()->GetURL(
          "files/extensions/api_test/extension_resource_request_policy/"
          "web_accessible/xhr_inaccessible_resource.html"));
  ui_test_utils::NavigateToURL(
      browser(), xhr_inaccessible_resource);
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
    browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
    &result));
  EXPECT_EQ("XHR failed to load resource", result);

  GURL nonaccessible_resource(
      test_server()->GetURL(
          "files/extensions/api_test/extension_resource_request_policy/"
          "web_accessible/nonaccessible_resource.html"));
  ui_test_utils::NavigateToURL(browser(), nonaccessible_resource);
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
    browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
    &result));
  EXPECT_EQ("Image failed to load", result);

  GURL nonexistent_resource(
      test_server()->GetURL(
          "files/extensions/api_test/extension_resource_request_policy/"
          "web_accessible/nonexistent_resource.html"));
  ui_test_utils::NavigateToURL(browser(), nonexistent_resource);
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
    browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
    &result));
  EXPECT_EQ("Image failed to load", result);
}

<commit_msg>Mark ExtensionResourceRequestPolicyTest.Audio as FLAKY on ChromeOS<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/logging.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "googleurl/src/gurl.h"
#include "net/base/mock_host_resolver.h"

class ExtensionResourceRequestPolicyTest : public ExtensionApiTest {
 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kAllowLegacyExtensionManifests);
  }
};

// Note, this mostly tests the logic of chrome/renderer/extensions/
// extension_resource_request_policy.*, but we have it as a browser test so that
// can make sure it works end-to-end.
IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, OriginPrivileges) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());
  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("extension_resource_request_policy")
      .AppendASCII("extension")));

  GURL web_resource(
      test_server()->GetURL(
          "files/extensions/api_test/extension_resource_request_policy/"
          "index.html"));

  std::string host_a("a.com");
  GURL::Replacements make_host_a_com;
  make_host_a_com.SetHostStr(host_a);

  std::string host_b("b.com");
  GURL::Replacements make_host_b_com;
  make_host_b_com.SetHostStr(host_b);

  // A web host that has permission.
  ui_test_utils::NavigateToURL(
      browser(), web_resource.ReplaceComponents(make_host_a_com));
  std::string result;
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
    browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
    &result));
  EXPECT_EQ(result, "Loaded");

  // A web host that loads a non-existent extension.
  GURL non_existent_extension(
      test_server()->GetURL(
          "files/extensions/api_test/extension_resource_request_policy/"
          "non_existent_extension.html"));
  ui_test_utils::NavigateToURL(browser(), non_existent_extension);
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
    browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
    &result));
  EXPECT_EQ(result, "Image failed to load");

  // A data URL. Data URLs should always be able to load chrome-extension://
  // resources.
  std::string file_source;
  ASSERT_TRUE(file_util::ReadFileToString(
      test_data_dir_.AppendASCII("extension_resource_request_policy")
                    .AppendASCII("index.html"), &file_source));
  ui_test_utils::NavigateToURL(browser(),
      GURL(std::string("data:text/html;charset=utf-8,") + file_source));
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
      browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
      &result));
  EXPECT_EQ(result, "Loaded");

  // A different extension. Extensions should always be able to load each
  // other's resources.
  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("extension_resource_request_policy")
      .AppendASCII("extension2")));
  ui_test_utils::NavigateToURL(
      browser(),
      GURL("chrome-extension://pbkkcbgdkliohhfaeefcijaghglkahja/index.html"));
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
      browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
      &result));
  EXPECT_EQ(result, "Loaded");
}

IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest,
                       ExtensionCanLoadHostedAppIcons) {
  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("extension_resource_request_policy")
      .AppendASCII("extension")));

  ASSERT_TRUE(RunExtensionSubtest(
      "extension_resource_request_policy/extension2/",
      "can_load_icons_from_hosted_apps.html"));
}

#if defined(OS_CHROMEOS)
// http://crbug.com/114478 - Audio crashes occasionally on ChromeOS
#define MAYBE_Audio FLAKY_Audio
#else
#define MAYBE_Audio Audio
#endif
IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, MAYBE_Audio) {
  EXPECT_TRUE(RunExtensionSubtest(
      "extension_resource_request_policy/extension2",
      "audio.html"));
}

#if defined(OS_MACOSX)
// http://crbug.com/95274 - Video is flaky on Mac.
#define MAYBE_Video DISABLED_Video
#else
#define MAYBE_Video Video
#endif

IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest, MAYBE_Video) {
  EXPECT_TRUE(RunExtensionSubtest(
      "extension_resource_request_policy/extension2",
      "video.html"));
}

IN_PROC_BROWSER_TEST_F(ExtensionResourceRequestPolicyTest,
                       WebAccessibleResources) {
  std::string result;
  ASSERT_TRUE(test_server()->Start());
  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("extension_resource_request_policy")
      .AppendASCII("web_accessible")));

  GURL accessible_resource(
      test_server()->GetURL(
          "files/extensions/api_test/extension_resource_request_policy/"
          "web_accessible/accessible_resource.html"));
  ui_test_utils::NavigateToURL(browser(), accessible_resource);
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
    browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
    &result));
  EXPECT_EQ("Loaded", result);

  GURL xhr_accessible_resource(
      test_server()->GetURL(
          "files/extensions/api_test/extension_resource_request_policy/"
          "web_accessible/xhr_accessible_resource.html"));
  ui_test_utils::NavigateToURL(
      browser(), xhr_accessible_resource);
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
    browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
    &result));
  EXPECT_EQ("XHR completed with status: 200", result);

  GURL xhr_inaccessible_resource(
      test_server()->GetURL(
          "files/extensions/api_test/extension_resource_request_policy/"
          "web_accessible/xhr_inaccessible_resource.html"));
  ui_test_utils::NavigateToURL(
      browser(), xhr_inaccessible_resource);
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
    browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
    &result));
  EXPECT_EQ("XHR failed to load resource", result);

  GURL nonaccessible_resource(
      test_server()->GetURL(
          "files/extensions/api_test/extension_resource_request_policy/"
          "web_accessible/nonaccessible_resource.html"));
  ui_test_utils::NavigateToURL(browser(), nonaccessible_resource);
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
    browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
    &result));
  EXPECT_EQ("Image failed to load", result);

  GURL nonexistent_resource(
      test_server()->GetURL(
          "files/extensions/api_test/extension_resource_request_policy/"
          "web_accessible/nonexistent_resource.html"));
  ui_test_utils::NavigateToURL(browser(), nonexistent_resource);
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
    browser()->GetSelectedWebContents()->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title)",
    &result));
  EXPECT_EQ("Image failed to load", result);
}

<|endoftext|>


<commit_before><commit_msg>fix2<commit_after><|endoftext|>


<commit_before>#include <stan/math/prim.hpp>
#include <test/unit/util.hpp>
#include <gtest/gtest.h>

TEST(MathMatrixPrim, Zero) {
  stan::math::matrix_d m0(0, 0);
  stan::math::matrix_d ginv = stan::math::generalized_inverse(m0);
  EXPECT_EQ(0, ginv.rows());
  EXPECT_EQ(0, ginv.cols());
}

TEST(MathMatrixPrim, Equal) {
  using stan::math::generalized_inverse;

  stan::math::matrix_d m1(3, 2);
  m1 << 1, 2, 2, 4, 1, 2;

  stan::math::matrix_d m2(2, 3);
  m2 << 1 / 30.0, 1 / 15.0, 1 / 30.0, 1 / 15.0, 2 / 15.0, 1 / 15.0;
  stan::math::matrix_d m3 = generalized_inverse(m1);
  for (int j = 0; j < m3.cols(); j++)
    for (int i = 0; i < m3.rows(); i++)
      EXPECT_NEAR(m2(i, j), m3(i, j), 1e-5);
}
<commit_msg>Update test/unit/math/prim/fun/generalized_inverse_test.cpp<commit_after>#include <stan/math/prim.hpp>
#include <test/unit/util.hpp>
#include <gtest/gtest.h>

TEST(MathMatrixPrim, Zero) {
  stan::math::matrix_d m0(0, 0);
  stan::math::matrix_d ginv = stan::math::generalized_inverse(m0);
  EXPECT_EQ(0, ginv.rows());
  EXPECT_EQ(0, ginv.cols());
}

TEST(MathMatrixPrim, Equal) {
  using stan::math::generalized_inverse;

  stan::math::matrix_d m1(3, 2);
  m1 << 1, 2, 2, 4, 1, 2;

  stan::math::matrix_d m2(2, 3);
  m2 << 1 / 30.0, 1 / 15.0, 1 / 30.0, 1 / 15.0, 2 / 15.0, 1 / 15.0;
  stan::math::matrix_d m3 = generalized_inverse(m1);
  EXPECT_MATRIX_NEAR(m2, m3, 1e-5);
}
<|endoftext|>


<commit_before>//Code for COP 3503 Computer Programming for CS Majors II Lab/HW - Andrew Silver Problem 1. Code compiles. with g++ -std=c++0x -o p1 p1.cpp on Ubuntu 12.04 and with current stuff on Mac OS X. Implementation of RLE encoding for the Lab 3 for COP3503. Version 6.0 - includes working implementation of new-style encoding for COP 3503 HW 6. 1 + 1 = 2 ---> 11 + 11 = 12. Single digits get 1s before, and the no digit check was commented out.

//for more information, look up variations of the run-length encoding algorithm. for hello world, it prints he2lo world. for 1111, it prints 41, etc.

#include <iostream>

bool makestring(char* p1){
  bool result = false; //result of this function
  while(*p1){ //as long as the cstring is not at the delimiting whitespace. If the number 0 is in the cstring, this loop will stop evaluating and the else st
    if(!(*p1 - '0' < 10 && *p1 - '0' >= 0)){ //casts the element to an int. If it was a character, then the output would be not between 1 and 9, and this would execute (since it is ! ). If it was an int, then the output would be nonzero (the value of the int) and because of the ! this following code would not evaluate.
      result = true; //no number found, so good to go
    }
       else{ //if there is a number in the list.
    result = false;
    break; //ends the for loop, a number was found
  }
    ++p1; //go to the next address to check
   } //ends while loop

  return result; //if there is a 0 digit in the cstring that is not the whitespace, then it will obviously return false, since a number exists, and it does not need to cycle through any more positions.
}

//this function takes a pointer to element at index 0 of an array (a cstring). It will cycle through and determine the length.
unsigned int lengthstring(char* p2){
  unsigned int length = 0; //the length of the cstring that will be determined.

  while(*p2){ //as long as the value at the address the pointer points to is not the delimiter 0. i.e., as long as the pointer does not point to the end of the array. Note that this does not include the delimiting 0 at the end in the calculation, as expected by the sample output. This could be added by just setting length to 1 at the start.
    ++length; //adds 1 to the length
    ++p2; //goes to the next address in the array
  }
  // std::cout << length; this part prints 5 if hello is passed in
  return length;

}

//function takes a cstring and replaces matching characters with the number of times they match
char* matchingstring(char* p3){
  int looptimes = 0; //the number of times the loop has occured through the values
  unsigned int length = 0; //length of the inputted cstring, which will be called from the function lengthstring
  char counting = '1'; //conversion for counter to a char to be stored
  int counter = 1; //the counter to track how many times the same element appears, starts at 1.
  char* repeat = p3; //tracker pointer to store the character that repeats, I don't want to increment the original array, copies address of p3 into repeat
  length = lengthstring(p3); //gets the length of the inputted string and stores it in counter
   char* output = new char[length](); //creates memory for pointer to the first element of a new array and default initializes the values to 0.
   char* array = output; //gets the value of the array, i.e., the address of the first element
  while(*p3){ //while not at the end of the array, i.e. the delimiter
    if((*(p3 + 1) == *p3)){ //if the next element in the array is equal to the current
      while(*(p3 + 1) == *repeat && counter != 11){ //runs until the next element in the array is different than the current element and the numbers for counter are between 1 and 10
	++counter; //increase the counter to determine the number of repeats
	++p3; //moves p3 forward in the array to keep checking for more repeats
	// this evaluates std::cout << "yea this works" << std::endl;
      }
      if(counter >= 11){ //if the counter is greater than 10, then add a 0 for the first ten and keep going
	*array = '0';
	++array;
	*array = *p3;
      }
      else if (counter == 10){ //if the counter is equal to 10, change it to 0
	*array = '0';
      }
      else {
	counting = (counter + '0'); //converts the int counter to a character
	*array = counting; //the element in the array gets the number of repeats
      }
      ++array; //go to the next index
      *array = *repeat; //the element in the array gets the repeated char
    }
    else if ( ((*p3 - '0' >= 0) && (*p3 - '0' < 10)) && ( ( (((*p3 - '0')/10 == 0 ) && (looptimes != 1) && (*(p3 + 1) == ' ' || *(p3 + 1) == '\0') )) || ( (*(p3 + 1) == ' ') && (*(p3 - 1) == ' ')) || ( (*(p3 +1) == '\0') && (*(p3 - 1) == ' ')))  ) { //additional implementation to RLE encoding. If there is a digit by itself, a 1 comes before it. The ' ' statements don't seem to work in the beginning of the pointer, so I created a "looptimes" variable that increments each time p3 goes to the next index. This means that this condition will always be false and I wouldn't have random '1's everywhere.
      *array = '1'; //1 digit found
      ++array;
      *array = *p3;
      ++p3; //goes to next index in P3
      *repeat = *p3; //resets repeat to current element at p3
      ++array; //goes to the next index position for the array
    }
    else{ //base case, if no matches are found, i.e. if the next element is not equal to the current
      *array = *p3;
      ++p3; //go to the next index in p3
      *repeat = *p3; //resets repeat to the current element at p3
      ++array; //goes to next index position for the array
    }
    counter = 1; // reset counter to 1
    looptimes = 1; //once past the first element of the cstring, no longer run the first if condition
  }
  *array = '\0'; //adds the delimiting character to the end, making this a cstring
  return output; //returns a pointer to the first element of a cstring. Since the array was default initialized to 0, the last element will be '0'.
}

//the starting point of the program
int main(){

  int const buffer_size = 256; //create a buffer size
  char buffer[ buffer_size ]; //make a buffer
char* pointer = buffer; //pointer to the first element of buffer

// old version with no digits std::cout << "Type a sentence that does not contain any digits and press [RETURN], please." << std::endl;

 std::cout << "Type a sentence and press [RETURN], please." << std::endl;
  std::cin.getline( buffer, buffer_size ); //grab the input from the shell

 while(lengthstring(pointer)) //as long as length does not equal 0, i.e. the null string
   {

  char* checklength = buffer; //a pointer to the first element of buffer that will be passed into the length method call
  unsigned int originallength = lengthstring(buffer); //length of the original cstring, originally checklength
  unsigned int RLElength = 0; //length of the new cstring, which will be checked later

  /*  if(makestring(test) == false){ //calls the makestring method on the pointer, if the user enters a number, keep prompting. not used in new-style version
    std::cout << "Yeaaa bro don't give me numbers. That's not cool. Only use characters." << std::endl;
std::cout << "Type a sentence that does not contain any digits and press [RETURN], please." << std::endl;
  std::cin.getline( buffer, buffer_size );

  } */

  //  else{ //if makestring(test) is true, i.e., there are no numbers in the cstring, removed in new style version
    char* RLE = matchingstring(buffer); //grabs a pointer to the first element of the RLE encoded version of the array, originally pointer
    RLElength = lengthstring(RLE); //checks the length of RLE version
    while(*RLE){ //while not at a delimeter
    std::cout << *RLE;
    ++RLE; //go to the next index position
    }
    std::cout << "" <<std::endl; //prints a newline
    if(originallength >= RLElength){ //if the RLE compressed version is shorter than the original
    std::cout << "The RLE version is " << (originallength - RLElength) << " shorter than the original" << std::endl;
    }
    else{ //when using new style RLE compression, the RLElength could actually be longer.
      std::cout << "The RLE version is " << (RLElength - originallength) << " longer than the original" << std::endl;
    }
 if(lengthstring(pointer)){
 delete []RLE; //deletes the memory allocated for the encoded array
 }
 //std::cout << "Type a sentence that does not contain any digits and press [RETURN], please." << std::endl; NOT USED IN RLE NEW STYLE ENCODING
 std::cout << "Type a sentence and press [RETURN], please." <<std::endl;
  std::cin.getline( buffer, buffer_size );
}
 //} closes else statement, removed in new style version
  return 0;
}
<commit_msg>deleted unneeded pointers<commit_after>//Code for COP 3503 Computer Programming for CS Majors II Lab/HW - Andrew Silver Problem 1. Code compiles. with g++ -std=c++0x -o p1 p1.cpp on Ubuntu 12.04 and with current stuff on Mac OS X. Implementation of RLE encoding for the Lab 3 for COP3503. Version 6.0 - includes working implementation of new-style encoding for COP 3503 HW 6. 1 + 1 = 2 ---> 11 + 11 = 12. Single digits get 1s before, and the no digit check was commented out.

//for more information, look up variations of the run-length encoding algorithm. for hello world, it prints he2lo world. for 1111, it prints 41, etc.

#include <iostream>

bool makestring(char* p1){
  bool result = false; //result of this function
  while(*p1){ //as long as the cstring is not at the delimiting whitespace. If the number 0 is in the cstring, this loop will stop evaluating and the else st
    if(!(*p1 - '0' < 10 && *p1 - '0' >= 0)){ //casts the element to an int. If it was a character, then the output would be not between 1 and 9, and this would execute (since it is ! ). If it was an int, then the output would be nonzero (the value of the int) and because of the ! this following code would not evaluate.
      result = true; //no number found, so good to go
    }
       else{ //if there is a number in the list.
    result = false;
    break; //ends the for loop, a number was found
  }
    ++p1; //go to the next address to check
   } //ends while loop

  return result; //if there is a 0 digit in the cstring that is not the whitespace, then it will obviously return false, since a number exists, and it does not need to cycle through any more positions.
}

//this function takes a pointer to element at index 0 of an array (a cstring). It will cycle through and determine the length.
unsigned int lengthstring(char* p2){
  unsigned int length = 0; //the length of the cstring that will be determined.

  while(*p2){ //as long as the value at the address the pointer points to is not the delimiter 0. i.e., as long as the pointer does not point to the end of the array. Note that this does not include the delimiting 0 at the end in the calculation, as expected by the sample output. This could be added by just setting length to 1 at the start.
    ++length; //adds 1 to the length
    ++p2; //goes to the next address in the array
  }
  // std::cout << length; this part prints 5 if hello is passed in
  return length;

}

//function takes a cstring and replaces matching characters with the number of times they match
char* matchingstring(char* p3){
  int looptimes = 0; //the number of times the loop has occured through the values
  unsigned int length = 0; //length of the inputted cstring, which will be called from the function lengthstring
  char counting = '1'; //conversion for counter to a char to be stored
  int counter = 1; //the counter to track how many times the same element appears, starts at 1.
  char* repeat = p3; //tracker pointer to store the character that repeats, I don't want to increment the original array, copies address of p3 into repeat
  length = lengthstring(p3); //gets the length of the inputted string and stores it in counter
   char* output = new char[length](); //creates memory for pointer to the first element of a new array and default initializes the values to 0.
   char* array = output; //gets the value of the array, i.e., the address of the first element
  while(*p3){ //while not at the end of the array, i.e. the delimiter
    if((*(p3 + 1) == *p3)){ //if the next element in the array is equal to the current
      while(*(p3 + 1) == *repeat && counter != 11){ //runs until the next element in the array is different than the current element and the numbers for counter are between 1 and 10
	++counter; //increase the counter to determine the number of repeats
	++p3; //moves p3 forward in the array to keep checking for more repeats
	// this evaluates std::cout << "yea this works" << std::endl;
      }
      if(counter >= 11){ //if the counter is greater than 10, then add a 0 for the first ten and keep going
	*array = '0';
	++array;
	*array = *p3;
      }
      else if (counter == 10){ //if the counter is equal to 10, change it to 0
	*array = '0';
      }
      else {
	counting = (counter + '0'); //converts the int counter to a character
	*array = counting; //the element in the array gets the number of repeats
      }
      ++array; //go to the next index
      *array = *repeat; //the element in the array gets the repeated char
    }
    else if ( ((*p3 - '0' >= 0) && (*p3 - '0' < 10)) && ( ( (((*p3 - '0')/10 == 0 ) && (looptimes != 1) && (*(p3 + 1) == ' ' || *(p3 + 1) == '\0') )) || ( (*(p3 + 1) == ' ') && (*(p3 - 1) == ' ')) || ( (*(p3 +1) == '\0') && (*(p3 - 1) == ' ')))  ) { //additional implementation to RLE encoding. If there is a digit by itself, a 1 comes before it. The ' ' statements don't seem to work in the beginning of the pointer, so I created a "looptimes" variable that increments each time p3 goes to the next index. This means that this condition will always be false and I wouldn't have random '1's everywhere.
      *array = '1'; //1 digit found
      ++array;
      *array = *p3;
      ++p3; //goes to next index in P3
      *repeat = *p3; //resets repeat to current element at p3
      ++array; //goes to the next index position for the array
    }
    else{ //base case, if no matches are found, i.e. if the next element is not equal to the current
      *array = *p3;
      ++p3; //go to the next index in p3
      *repeat = *p3; //resets repeat to the current element at p3
      ++array; //goes to next index position for the array
    }
    counter = 1; // reset counter to 1
    looptimes = 1; //once past the first element of the cstring, no longer run the first if condition
  }
  *array = '\0'; //adds the delimiting character to the end, making this a cstring
  return output; //returns a pointer to the first element of a cstring. Since the array was default initialized to 0, the last element will be '0'.
}

//the starting point of the program
int main(){

  int const buffer_size = 256; //create a buffer size
  char buffer[ buffer_size ]; //make a buffer

// old version with no digits std::cout << "Type a sentence that does not contain any digits and press [RETURN], please." << std::endl;

 std::cout << "Type a sentence and press [RETURN], please." << std::endl;
  std::cin.getline( buffer, buffer_size ); //grab the input from the shell

 while(lengthstring(buffer)) //as long as pointer length does not equal 0, i.e. the null string
   {

  unsigned int originallength = lengthstring(buffer); //length of the original cstring, originally checklength
  unsigned int RLElength = 0; //length of the new cstring, which will be checked later

  /*  if(makestring(test) == false){ //calls the makestring method on the pointer, if the user enters a number, keep prompting. not used in new-style version
    std::cout << "Yeaaa bro don't give me numbers. That's not cool. Only use characters." << std::endl;
std::cout << "Type a sentence that does not contain any digits and press [RETURN], please." << std::endl;
  std::cin.getline( buffer, buffer_size );

  } */

  //  else{ //if makestring(test) is true, i.e., there are no numbers in the cstring, removed in new style version
    char* RLE = matchingstring(buffer); //grabs a pointer to the first element of the RLE encoded version of the array, originally pointer
    RLElength = lengthstring(RLE); //checks the length of RLE version
    while(*RLE){ //while not at a delimeter
    std::cout << *RLE;
    ++RLE; //go to the next index position
    }
    std::cout << "" <<std::endl; //prints a newline
    if(originallength >= RLElength){ //if the RLE compressed version is shorter than the original
    std::cout << "The RLE version is " << (originallength - RLElength) << " shorter than the original" << std::endl;
    }
    else{ //when using new style RLE compression, the RLElength could actually be longer.
      std::cout << "The RLE version is " << (RLElength - originallength) << " longer than the original" << std::endl;
    }
 if(lengthstring(buffer)){
 delete []RLE; //deletes the memory allocated for the encoded array
 }
 //std::cout << "Type a sentence that does not contain any digits and press [RETURN], please." << std::endl; NOT USED IN RLE NEW STYLE ENCODING
 std::cout << "Type a sentence and press [RETURN], please." <<std::endl;
  std::cin.getline( buffer, buffer_size );
}
 //} closes else statement, removed in new style version
  return 0;
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>

void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd)
{
    ROS_INFO("I heard: [%f]", vel_cmd.linear.y);
    std::cout << "Twist Received " << std::endl;
}

int main( int argc, char* argv[] )
{
ros::init(argc, argv, "toeminator_publisher" );

ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/cmd_vel", 1000, cmd_vel_callback);

while( n.ok() )
{
    ros::spin();
}

return 1;
}
<commit_msg>change base_controller_node.cpp<commit_after>#include <iostream>
#include <stdio.h>   								/* Standard input/output definitions */
#include <stdlib.h>  								/* exit */
#include <string.h>  								/* String function definitions */
#include <unistd.h>  								/* UNIX standard function definitions */
#include <fcntl.h>  	 							/* File control definitions */
#include <errno.h>   								/* Error number definitions */
#include <termios.h> 								/* POSIX terminal control definitions */
#include <ctype.h>   								/* isxxx() */

#include <ros/ros.h>
#include <geometry_msgs/Twist.h>

struct termios orig;
int filedesc;
int fd;
unsigned char serialBuffer[16];						// Serial buffer to store data for I/O

int openSerialPort(const char * device, int bps)
{
   struct termios neu;
   char buf[128];

   fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);

   if (fd == -1)
   {
      sprintf(buf, "openSerialPort %s error", device);
      perror(buf);
   }
   else
   {
      tcgetattr(fd, &orig); 						/* save current serial settings */
      tcgetattr(fd, &neu);
      cfmakeraw(&neu);
      //fprintf(stderr, "speed=%d\n", bps);
      cfsetispeed(&neu, bps);
      cfsetospeed(&neu, bps);
      tcsetattr(fd, TCSANOW, &neu); 				/* set new serial settings */
      fcntl (fd, F_SETFL, O_RDWR);
   }
   return fd;
}

void writeBytes(int descriptor, int count) {
    if ((write(descriptor, serialBuffer, count)) == -1) {	// Send data out
        perror("Error writing");
        close(descriptor);				// Close port if there is an error
        exit(1);
    }
    //write(fd,serialBuffer, count);

}

void readBytes(int descriptor, int count) {
    if (read(descriptor, serialBuffer, count) == -1) {	// Read back data into buf[]
        perror("Error reading ");
        close(descriptor);				// Close port if there is an error
        exit(1);
    }
}

void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd)
{
    ROS_INFO("I heard: [%f]", vel_cmd.linear.y);
    std::cout << "Twist Received " << std::endl;

    //hier code um msg in seriellen Befehl umzuwandeln

        //code

    //
}

int main( int argc, char* argv[] )
{
ros::init(argc, argv, "toeminator_publisher" );

ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/cmd_vel", 1000, cmd_vel_callback);

filedesc = openSerialPort("/dev/ttyAMA0", B38400);
if (filedesc == -1) exit(1);
usleep(40000);									// Sleep for UART to power up and set options

printf("serial Port opened \n");

while( n.ok() )
{
    ros::spin();
}

return 1;
}
<|endoftext|>


<commit_before><commit_msg>drt: fix compiler warning<commit_after><|endoftext|>