<commit_before>#include <QDebug>
#include <QFileInfo>
#include <QIcon>
#include <QPixmap>
#include <QUrl>
#include <QMimeData>

#include "MediaListModel.h"
#include "LibraryTreeItem.h"
#include "MediaLoader.h"
#include "MediaFile.h"

MediaListModel::MediaListModel(QObject *parent)
    : QAbstractListModel(parent)
{
    qRegisterMetaType<MediaFilePtr>("MediaFilePtr");
}

MediaListModel::~MediaListModel()
{
    if (m_library_tree_item != NULL)
        m_library_tree_item->setWatcher(NULL);
}

int MediaListModel::rowCount(const QModelIndex &parent) const
{
    if (parent.column() > 0)
        return 0;

    if (m_library_tree_item == NULL)
        return 0;

    return m_library_tree_item->mediaFileCount();
}

int MediaListModel::dataColumnCount() const
{
    return 1;
}

int MediaListModel::columnCount(const QModelIndex &parent) const
{
    if (parent.column() > 0)
        return 0;

    return dataColumnCount();
}

QVariant MediaListModel::decorationFromMediaFile(MediaFilePtr media_file, int column) const
{
    return QVariant();
}

QVariant MediaListModel::displayFromMediaFile(MediaFilePtr media_file, int column) const
{
    return QVariant();
}

QVariant MediaListModel::toolTipFromMediaFile(MediaFilePtr media_file, int column) const
{
    return displayFromMediaFile(media_file, column);
}

QVariant MediaListModel::sortValueFromMediaFile(MediaFilePtr media_file, int column) const
{
    return displayFromMediaFile(media_file, column);
}

QVariant MediaListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    MediaFilePtr media_file = m_library_tree_item->mediaFileAt(index.row());

    if (role == Qt::DecorationRole)
    {
        return decorationFromMediaFile(media_file, index.column());
    }

    if (role == Qt::DisplayRole)
    {
        return displayFromMediaFile(media_file, index.column());
    }

    if (role == Qt::ToolTipRole)
    {
        return toolTipFromMediaFile(media_file, index.column());
    }

    if (role == FullPathRole)
    {
        return media_file->filePath();
    }

    if (role == SortRole)
    {
        return sortValueFromMediaFile(media_file, index.column());
    }

    return QVariant();
}

void MediaListModel::setLibraryTreeItem(LibraryTreeItemPtr library_tree_item)
{
    if (m_library_tree_item != NULL)
        m_library_tree_item->setWatcher(NULL);

    if (library_tree_item != NULL)
        library_tree_item->setWatcher(this);

    if (rowCount() > 0)
    {
        beginRemoveRows(QModelIndex(), 0, rowCount()-1);

        m_library_tree_item.reset();

        endRemoveRows();
    }

    if (library_tree_item->mediaFileCount() > 0)
    {
        beginInsertRows(QModelIndex(), 0, library_tree_item->mediaFileCount()-1);

        m_library_tree_item = library_tree_item;

        endInsertRows();
    }
}

void MediaListModel::libraryTreeItemChanged()
{
    setLibraryTreeItem(m_library_tree_item);
}

void MediaListModel::mediaLoaded(MediaFilePtr media_file)
{
    unsigned row = m_library_tree_item->indexOfMediaFile(media_file);

    if ( row != INDEX_NOT_FOUND )
    {
        QModelIndex model_index_left = index(row, 0);
        QModelIndex model_index_right = index(row, columnCount()-1);

        dataChanged(model_index_left, model_index_right);
    }
}

Qt::ItemFlags MediaListModel::flags(const QModelIndex &index) const
{
    Qt::ItemFlags defaultFlags = QAbstractListModel::flags(index);

    if (index.isValid())
        return Qt::ItemIsDragEnabled | defaultFlags;
    else
        return defaultFlags;
}

QStringList MediaListModel::mimeTypes() const
{
    QStringList mime_types;
    mime_types << "text/uri-list";
    return mime_types;
}

QMimeData *MediaListModel::mimeData(const QModelIndexList &indexes) const
{
    QMimeData *mimeData = new QMimeData();

    QList<QUrl> urls;

    Q_FOREACH(QModelIndex index, indexes) {
        if (index.isValid() && index.column() == 0) {
            QString file_path = qVariantValue<QString>(data(index, FullPathRole));
            urls.push_back(QUrl::fromLocalFile(file_path));
        }
    }

    mimeData->setUrls(urls);

    return mimeData;
}

void MediaListModel::resetTasks(const QModelIndexList &index_list)
{
}
<commit_msg>Fixed bug in tree replacement.<commit_after>#include <QDebug>
#include <QFileInfo>
#include <QIcon>
#include <QPixmap>
#include <QUrl>
#include <QMimeData>

#include "MediaListModel.h"
#include "LibraryTreeItem.h"
#include "MediaLoader.h"
#include "MediaFile.h"

MediaListModel::MediaListModel(QObject *parent)
    : QAbstractListModel(parent)
{
    qRegisterMetaType<MediaFilePtr>("MediaFilePtr");
}

MediaListModel::~MediaListModel()
{
    if (m_library_tree_item != NULL)
        m_library_tree_item->setWatcher(NULL);
}

int MediaListModel::rowCount(const QModelIndex &parent) const
{
    if (parent.column() > 0)
        return 0;

    if (m_library_tree_item == NULL)
        return 0;

    return m_library_tree_item->mediaFileCount();
}

int MediaListModel::dataColumnCount() const
{
    return 1;
}

int MediaListModel::columnCount(const QModelIndex &parent) const
{
    if (parent.column() > 0)
        return 0;

    return dataColumnCount();
}

QVariant MediaListModel::decorationFromMediaFile(MediaFilePtr media_file, int column) const
{
    return QVariant();
}

QVariant MediaListModel::displayFromMediaFile(MediaFilePtr media_file, int column) const
{
    return QVariant();
}

QVariant MediaListModel::toolTipFromMediaFile(MediaFilePtr media_file, int column) const
{
    return displayFromMediaFile(media_file, column);
}

QVariant MediaListModel::sortValueFromMediaFile(MediaFilePtr media_file, int column) const
{
    return displayFromMediaFile(media_file, column);
}

QVariant MediaListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    MediaFilePtr media_file = m_library_tree_item->mediaFileAt(index.row());

    if (role == Qt::DecorationRole)
    {
        return decorationFromMediaFile(media_file, index.column());
    }

    if (role == Qt::DisplayRole)
    {
        return displayFromMediaFile(media_file, index.column());
    }

    if (role == Qt::ToolTipRole)
    {
        return toolTipFromMediaFile(media_file, index.column());
    }

    if (role == FullPathRole)
    {
        return media_file->filePath();
    }

    if (role == SortRole)
    {
        return sortValueFromMediaFile(media_file, index.column());
    }

    return QVariant();
}

void MediaListModel::setLibraryTreeItem(LibraryTreeItemPtr library_tree_item)
{
    if (m_library_tree_item != NULL)
        m_library_tree_item->setWatcher(NULL);

    if (library_tree_item != NULL)
        library_tree_item->setWatcher(this);

    if (rowCount() > 0)
    {
        beginRemoveRows(QModelIndex(), 0, rowCount()-1);

        m_library_tree_item.reset();

        endRemoveRows();
    }

    if (library_tree_item->mediaFileCount() > 0)
    {
        beginInsertRows(QModelIndex(), 0, library_tree_item->mediaFileCount()-1);

        m_library_tree_item = library_tree_item;

        endInsertRows();
    }
    else
    {
        m_library_tree_item = library_tree_item;
    }
}

void MediaListModel::libraryTreeItemChanged()
{
    setLibraryTreeItem(m_library_tree_item);
}

void MediaListModel::mediaLoaded(MediaFilePtr media_file)
{
    unsigned row = m_library_tree_item->indexOfMediaFile(media_file);

    if ( row != INDEX_NOT_FOUND )
    {
        QModelIndex model_index_left = index(row, 0);
        QModelIndex model_index_right = index(row, columnCount()-1);

        dataChanged(model_index_left, model_index_right);
    }
}

Qt::ItemFlags MediaListModel::flags(const QModelIndex &index) const
{
    Qt::ItemFlags defaultFlags = QAbstractListModel::flags(index);

    if (index.isValid())
        return Qt::ItemIsDragEnabled | defaultFlags;
    else
        return defaultFlags;
}

QStringList MediaListModel::mimeTypes() const
{
    QStringList mime_types;
    mime_types << "text/uri-list";
    return mime_types;
}

QMimeData *MediaListModel::mimeData(const QModelIndexList &indexes) const
{
    QMimeData *mimeData = new QMimeData();

    QList<QUrl> urls;

    Q_FOREACH(QModelIndex index, indexes) {
        if (index.isValid() && index.column() == 0) {
            QString file_path = qVariantValue<QString>(data(index, FullPathRole));
            urls.push_back(QUrl::fromLocalFile(file_path));
        }
    }

    mimeData->setUrls(urls);

    return mimeData;
}

void MediaListModel::resetTasks(const QModelIndexList &index_list)
{
}
<|endoftext|>


<commit_before>#include <QClipboard>
#include <QDateTime>
#include <QDesktopWidget>
#include <QGraphicsPixmapItem>
#include <QFileDialog>
#include <QMessageBox>
#include <QNetworkReply>
#include <QDir>
#include <QTimer>

#include "Uploader.hpp"
#include "ResultWindow.hpp"
#include "SettingsDialog.hpp"

ResultWindow::ResultWindow(QPixmap screenshot) : mScreenshot(screenshot) {
    mUi.setupUi(this);
    mScene.addPixmap(mScreenshot)->setTransformationMode(Qt::SmoothTransformation);
    mUi.graphicsView->setScene(&mScene);
    mUi.graphicsView->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing);
    mUi.uploadProgress->setVisible(false);

    // Center on screen
    QRect screen = QApplication::desktop()->screenGeometry();
    move(screen.center() - rect().center());

    // User interface signals
    connect(mUi.editButton, SIGNAL(pressed()), this, SLOT(editPressed()));
    connect(mUi.saveButton, SIGNAL(pressed()), this, SLOT(savePressed()));
    connect(mUi.uploadButton, SIGNAL(pressed()), this, SLOT(uploadPressed()));
    connect(mUi.settingsAction, SIGNAL(triggered(bool)), this, SLOT(openSettings()));

    // Upload signals
    connect(&mNetworkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(uploadFinished(QNetworkReply*)));
}

// Methods

/**
 * Cleans up after the edit process.
 */
void ResultWindow::cleanupEdit() {
    mUi.editButton->setEnabled(true);

    if (mEditFile != NULL) {
        mEditFile->deleteLater();
        mEditFile = NULL;
    }

    if (mEditProcess != NULL) {
        mEditProcess->deleteLater();
        mEditProcess = NULL;
    }
}

/**
 * Called on window resize. Scales the screenshot to either fit in the preview widget or to its
 * maximum size.
 */
void ResultWindow::resizeEvent(QResizeEvent *event) {
    QRect view = mUi.graphicsView->rect();
    if (mScreenshot.width() >= view.width() || mScreenshot.height() >= view.height()) {
        mUi.graphicsView->fitInView(mScreenshot.rect(), Qt::KeepAspectRatio);
    } else {
        mUi.graphicsView->fitInView(view);
    }
}

/**
 * Saves the current screenshot into a temporary file. May return null on failure.
 */
QTemporaryFile* ResultWindow::saveToTemp() {
    QTemporaryFile *file = new QTemporaryFile(QDir::tempPath() + "/vendace-XXXXXXX.png", this);
    if (file->open() && mScreenshot.save(file->fileName(), "PNG")) {
        return file;
    } else {
        QMessageBox::critical(this, tr("Failed to save"), tr("Couldn't save the screenshot to a temporary file."));
        file->deleteLater();
        return NULL;
    }
}

// Slots

/*
 * Called when the editor button is pressed.
 */
void ResultWindow::editPressed() {
    if (mSettings.editorPath().isEmpty()) {
        QMessageBox::information(this, tr("Editor not set"), tr("You haven't selected the editor to use yet. You can set an editor from File -> Settings."));
    } else {
        openEditor();
    }
}

/**
 * Opens the editor.
 */
void ResultWindow::openEditor() {
    mEditFile = saveToTemp();
    if (mEditFile != NULL) {
        mEditProcess = new QProcess(this);
        connect(mEditProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(editProcessError(QProcess::ProcessError)));
        connect(mEditProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(editFinished()));

        QStringList args;
        args << mEditFile->fileName();
        mEditProcess->start(mSettings.editorPath(), args);

        mUi.editButton->setEnabled(false);
    }
}

/**
 * Handles editor process errors.
 */
void ResultWindow::editProcessError(QProcess::ProcessError error) {
    QMessageBox::critical(this, tr("Error"), tr("The editor could not be started."));
    cleanupEdit();
}

/**
 * Handles the end of the edit process and loads the edited image.
 */
void ResultWindow::editFinished() {
    mScreenshot.load(mEditFile->fileName(), "PNG");
    mScene.addPixmap(mScreenshot);
    cleanupEdit();
}

/**
 * Called when the upload button is pressed.
 */
void ResultWindow::uploadPressed() {
    // Show progress
    mUi.uploadProgress->setVisible(true);
    mUi.uploadButton->setEnabled(false);

    // Save image to temporary file
    QTemporaryFile *temp = saveToTemp();
    if (temp != NULL) {
        // Send request
        QNetworkRequest req = mUploader.makeRequest();
        QHttpMultiPart *params = mUploader.makeMultiPart(temp);
        QNetworkReply *reply = mNetworkManager.post(req, params);
        params->setParent(reply);
    }
}

/**
 * Called when the upload is finished. Copies the resulting URL to the clipboard or shows an
 * error.
 */
void ResultWindow::uploadFinished(QNetworkReply *reply) {
    if (reply->error() == QNetworkReply::NoError) {
        // Copy URL
        QClipboard* clipboard = QApplication::clipboard();
        clipboard->setText(mUploader.getUrlFromReply(reply));
        QMessageBox::information(this, tr("Upload complete"), tr("The image link has been copied to your clipboard."));

        // Stick around for a minute to keep the clipboard
        hide();
        QTimer *timer = new QTimer(this);
        connect(timer, SIGNAL(timeout()), this, SLOT(close()));
        timer->start(60000);
    } else {
        QMessageBox::critical(this, tr("Upload error"), tr("The upload failed. Try again later."));
        mUi.uploadProgress->setVisible(false);
        mUi.uploadButton->setEnabled(true);
    }

    reply->deleteLater();
}

/**
 * Called when the save button is pressed.
 */
void ResultWindow::savePressed() {
    QString filename = QDateTime::currentDateTime().toString() + ".png";
    QString path = QFileDialog::getSaveFileName(this, tr("Save screenshot"), filename, "PNG image (*.png)");
    if (!path.isEmpty()) {
        if (mScreenshot.save(path)) {
            close();
        } else {
            QMessageBox::critical(this, tr("Error"), tr("Failed to save screenshot."));
        }
    }
}

/**
 * Opens a settings dialog.
 */
void ResultWindow::openSettings() {
    SettingsDialog settings(this);
    settings.exec();
}
<commit_msg>Handle edit load failure<commit_after>#include <QClipboard>
#include <QDateTime>
#include <QDesktopWidget>
#include <QGraphicsPixmapItem>
#include <QFileDialog>
#include <QMessageBox>
#include <QNetworkReply>
#include <QDir>
#include <QTimer>

#include "Uploader.hpp"
#include "ResultWindow.hpp"
#include "SettingsDialog.hpp"

ResultWindow::ResultWindow(QPixmap screenshot) : mScreenshot(screenshot) {
    mUi.setupUi(this);
    mScene.addPixmap(mScreenshot)->setTransformationMode(Qt::SmoothTransformation);
    mUi.graphicsView->setScene(&mScene);
    mUi.graphicsView->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing);
    mUi.uploadProgress->setVisible(false);

    // Center on screen
    QRect screen = QApplication::desktop()->screenGeometry();
    move(screen.center() - rect().center());

    // User interface signals
    connect(mUi.editButton, SIGNAL(pressed()), this, SLOT(editPressed()));
    connect(mUi.saveButton, SIGNAL(pressed()), this, SLOT(savePressed()));
    connect(mUi.uploadButton, SIGNAL(pressed()), this, SLOT(uploadPressed()));
    connect(mUi.settingsAction, SIGNAL(triggered(bool)), this, SLOT(openSettings()));

    // Upload signals
    connect(&mNetworkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(uploadFinished(QNetworkReply*)));
}

// Methods

/**
 * Cleans up after the edit process.
 */
void ResultWindow::cleanupEdit() {
    mUi.editButton->setEnabled(true);

    if (mEditFile != NULL) {
        mEditFile->deleteLater();
        mEditFile = NULL;
    }

    if (mEditProcess != NULL) {
        mEditProcess->deleteLater();
        mEditProcess = NULL;
    }
}

/**
 * Called on window resize. Scales the screenshot to either fit in the preview widget or to its
 * maximum size.
 */
void ResultWindow::resizeEvent(QResizeEvent *event) {
    QRect view = mUi.graphicsView->rect();
    if (mScreenshot.width() >= view.width() || mScreenshot.height() >= view.height()) {
        mUi.graphicsView->fitInView(mScreenshot.rect(), Qt::KeepAspectRatio);
    } else {
        mUi.graphicsView->fitInView(view);
    }
}

/**
 * Saves the current screenshot into a temporary file. May return null on failure.
 */
QTemporaryFile* ResultWindow::saveToTemp() {
    QTemporaryFile *file = new QTemporaryFile(QDir::tempPath() + "/vendace-XXXXXXX.png", this);
    if (file->open() && mScreenshot.save(file->fileName(), "PNG")) {
        return file;
    } else {
        QMessageBox::critical(this, tr("Failed to save"), tr("Couldn't save the screenshot to a temporary file."));
        file->deleteLater();
        return NULL;
    }
}

// Slots

/*
 * Called when the editor button is pressed.
 */
void ResultWindow::editPressed() {
    if (mSettings.editorPath().isEmpty()) {
        QMessageBox::information(this, tr("Editor not set"), tr("You haven't selected the editor to use yet. You can set an editor from File -> Settings."));
    } else {
        openEditor();
    }
}

/**
 * Opens the editor.
 */
void ResultWindow::openEditor() {
    mEditFile = saveToTemp();
    if (mEditFile != NULL) {
        mEditProcess = new QProcess(this);
        connect(mEditProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(editProcessError(QProcess::ProcessError)));
        connect(mEditProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(editFinished()));

        QStringList args;
        args << mEditFile->fileName();
        mEditProcess->start(mSettings.editorPath(), args);

        mUi.editButton->setEnabled(false);
    }
}

/**
 * Handles editor process errors.
 */
void ResultWindow::editProcessError(QProcess::ProcessError error) {
    QMessageBox::critical(this, tr("Error"), tr("The editor could not be started."));
    cleanupEdit();
}

/**
 * Handles the end of the edit process and loads the edited image.
 */
void ResultWindow::editFinished() {
    if (mScreenshot.load(mEditFile->fileName(), "PNG")) {
        mScene.addPixmap(mScreenshot);
    } else {
        QMessageBox::critical(this, tr("Error"), tr("Failed to load edited file."));
    }

    cleanupEdit();
}

/**
 * Called when the upload button is pressed.
 */
void ResultWindow::uploadPressed() {
    // Show progress
    mUi.uploadProgress->setVisible(true);
    mUi.uploadButton->setEnabled(false);

    // Save image to temporary file
    QTemporaryFile *temp = saveToTemp();
    if (temp != NULL) {
        // Send request
        QNetworkRequest req = mUploader.makeRequest();
        QHttpMultiPart *params = mUploader.makeMultiPart(temp);
        QNetworkReply *reply = mNetworkManager.post(req, params);
        params->setParent(reply);
    }
}

/**
 * Called when the upload is finished. Copies the resulting URL to the clipboard or shows an
 * error.
 */
void ResultWindow::uploadFinished(QNetworkReply *reply) {
    if (reply->error() == QNetworkReply::NoError) {
        // Copy URL
        QClipboard* clipboard = QApplication::clipboard();
        clipboard->setText(mUploader.getUrlFromReply(reply));
        QMessageBox::information(this, tr("Upload complete"), tr("The image link has been copied to your clipboard."));

        // Stick around for a minute to keep the clipboard
        hide();
        QTimer *timer = new QTimer(this);
        connect(timer, SIGNAL(timeout()), this, SLOT(close()));
        timer->start(60000);
    } else {
        QMessageBox::critical(this, tr("Upload error"), tr("The upload failed. Try again later."));
        mUi.uploadProgress->setVisible(false);
        mUi.uploadButton->setEnabled(true);
    }

    reply->deleteLater();
}

/**
 * Called when the save button is pressed.
 */
void ResultWindow::savePressed() {
    QString filename = QDateTime::currentDateTime().toString() + ".png";
    QString path = QFileDialog::getSaveFileName(this, tr("Save screenshot"), filename, "PNG image (*.png)");
    if (!path.isEmpty()) {
        if (mScreenshot.save(path)) {
            close();
        } else {
            QMessageBox::critical(this, tr("Error"), tr("Failed to save screenshot."));
        }
    }
}

/**
 * Opens a settings dialog.
 */
void ResultWindow::openSettings() {
    SettingsDialog settings(this);
    settings.exec();
}
<|endoftext|>


<commit_before>// World.cpp - Copyright 2013-2016 Will Cassella, All Rights Reserved

#include "../include/Engine/World.h"
#include "../include/Engine/Components/Rendering/LineStructureComponent.h"
#include "../include/Engine/Systems/RenderSystem.h"
#include "Physics/PhysicsWorld.h"

//////////////////////
///   Reflection   ///

BUILD_REFLECTION(Willow::World)
.Data("GameObjects", &World::_gameObjects, DF_Transient)
.Data("Entities", &World::_entities, DF_Transient)
.Data("Components", &World::_components, DF_Transient)
.Data("Destroyed", &World::_destroyedObjects, DF_Transient)
.Data("NextGameObjectID", &World::_nextGameObjectID)
.Field("Events", &World::Events)
.Field("TimeDilation", &World::TimeDilation, "The time dilation of the world. Default is 1.")
.Field("TimeStep", &World::TimeStep, "The amount of time (ms) that each update of the world represents.");

Willow::LineStructureComponent* lineStructure;

class DebugDraw : public btIDebugDraw
{
	void drawLine(const btVector3& from, const btVector3& to, const btVector3& color) override
	{
		Willow::LineStructureComponent::Line line;
		line.Start = Willow::ConvertFromBullet(from);
		line.End = Willow::ConvertFromBullet(to);
		line.Color = Willow::ConvertFromBullet(color);
		lineStructure->Lines.Add(line);
	}

	void drawContactPoint(const btVector3& /*PointOnB*/, const btVector3& /*normalOnB*/, btScalar /*distance*/, int /*lifeTime*/, const btVector3& /*color*/) override
	{
		// Do nothing
	}

	void reportErrorWarning(const char* warningString) override
	{
		Console::Warning("Bullet: @", warningString);
	}

	void draw3dText(const btVector3& /*location*/, const char* /*textString*/) override
	{
		// Do nothing
	}

	void setDebugMode(int /*debugMode*/) override
	{
		// Do nothing
	}

	int	getDebugMode() const override
	{
		return DBG_DrawWireframe | DBG_DrawAabb;
	}
};

namespace Willow
{
	////////////////////////
	///   Constructors   ///

	World::World()
	{
		_physicsWorld = std::make_unique<PhysicsWorld>();
		_nextGameObjectID = 1;
		_physicsWorld->GetDynamicsWorld().setDebugDrawer(new DebugDraw{});
	}

	World::~World()
	{
		// Do nothing
	}

	///////////////////
	///   Methods   ///

	void World::ToArchive(ArchiveWriter& writer) const
	{
		writer.SetID(this);
		writer.PushValue("TimeDilation", this->TimeDilation);
		writer.PushValue("TimeStep", this->TimeStep);
		writer.PushValue("NextID", _nextGameObjectID);

		// Save all entites/components
		writer.AddChild("GameObjects", [this](auto& child)
		{
			for (const auto& kv : this->_gameObjects)
			{
				// Push the given value into this archive, wrapping it in a Node containing its type name and address
				child.PushValueWithID(kv.Second->GetType().GetName(), *kv.Second);
			}
		});
	}

	void World::FromArchive(const ArchiveReader& reader)
	{
		reader.MapID(this);
		reader.PullValue("TimeDilation", this->TimeDilation);
		reader.PullValue("TimeStep", this->TimeStep);
		reader.PullValue("NextID", _nextGameObjectID);

		// Load all entities/components
		reader.GetChild("GameObjects", [&](auto& child)
		{
			Queue<Owned<GameObject>> unloadedObjects;

			// Do a first pass, instantiate everything
			child.EnumerateChildren([&](auto& gameobject)
			{
				// Find the type of GameObject that this node is referring to
				auto type = Application::FindType(gameobject.GetName());

				if (!type || !type->IsCastableTo(TypeOf<GameObject>()))
				{
					// Type isn't a GameObject type, go to next object
					gameobject.MapID(nullptr);
					unloadedObjects.Push(nullptr);
				}
				else
				{
					// Instantiate it
					auto object = StaticPointerCast<GameObject>(DynamicNew(*type));

					// Map the address of the new instantiation to the address in the archive
					gameobject.MapID(object.GetManagedPointer());
					unloadedObjects.Push(std::move(object));
				}
			});

			// Do a second pass, deserialize everything
			child.EnumerateChildren([&](auto& gameobject)
			{
				// If the object is not null, deserialize it
				if (auto object = unloadedObjects.Pop())
				{
					object->FromArchive(gameobject);
					this->SpawnGameObject(std::move(object));
				}
			});
		});

		lineStructure = &this->Spawn<LineStructureComponent>();
	}

	void World::Update()
	{
		auto quat = btQuaternion::getIdentity();

		Events.DispatchEvent("Update", this->TimeDilation);
		Events.Flush();

		// Remove stale objects
		while (!_destroyedObjects.IsEmpty())
		{
			auto object = _destroyedObjects.Pop();
			_entities.Remove(object->GetID());
			_components.Remove(object->GetID());
			_gameObjects.Remove(object->GetID());
		}

		// Simulate physics
		_physicsWorld->GetDynamicsWorld().stepSimulation(TimeStep, 10);

		lineStructure->Lines.Clear();
		_physicsWorld->GetDynamicsWorld().debugDrawWorld();
	}

	void World::DestroyGameObject(GameObject& object)
	{
		assert(object._state >= GameObject::State::Spawned);

		if (object._state != GameObject::State::Destroyed)
		{
			object._state = GameObject::State::Destroyed;
			_destroyedObjects.Push(&object);
			object.OnDestroy();
		}
	}

	void World::SpawnGameObject(Owned<GameObject> owner)
	{
		auto& object = *owner;

		// Give the object an ID
		assert(object._state == GameObject::State::Uninitialized);
		object._id = _nextGameObjectID++;
		object._state = GameObject::State::Initialized;

		// Add it to the world
		_gameObjects[object.GetID()] = std::move(owner);

		if (auto entity = Cast<Entity>(object))
		{
			_entities[object.GetID()] = entity;
		}
		else if (auto component = Cast<Component>(object))
		{
			_components[object.GetID()] = component;
		}

		// Spawn it
		object._state = GameObject::State::Spawning;
		object.OnSpawn();
		object._state = GameObject::State::Spawned;
	}

	PhysicsWorld& World::INTERNAL_GetPhysicsWorld()
	{
		return *_physicsWorld;
	}

	const PhysicsWorld& World::INTERNAL_GetPhysicsWorld() const
	{
		return *_physicsWorld;
	}
}
<commit_msg>Fixed another linux warning<commit_after>// World.cpp - Copyright 2013-2016 Will Cassella, All Rights Reserved

#include "../include/Engine/World.h"
#include "../include/Engine/Components/Rendering/LineStructureComponent.h"
#include "../include/Engine/Systems/RenderSystem.h"
#include "Physics/PhysicsWorld.h"

//////////////////////
///   Reflection   ///

BUILD_REFLECTION(Willow::World)
.Data("GameObjects", &World::_gameObjects, DF_Transient)
.Data("Entities", &World::_entities, DF_Transient)
.Data("Components", &World::_components, DF_Transient)
.Data("Destroyed", &World::_destroyedObjects, DF_Transient)
.Data("NextGameObjectID", &World::_nextGameObjectID)
.Field("Events", &World::Events)
.Field("TimeDilation", &World::TimeDilation, "The time dilation of the world. Default is 1.")
.Field("TimeStep", &World::TimeStep, "The amount of time (ms) that each update of the world represents.");

Willow::LineStructureComponent* lineStructure;

class DebugDraw : public btIDebugDraw
{
	void drawLine(const btVector3& from, const btVector3& to, const btVector3& color) override
	{
		Willow::LineStructureComponent::Line line;
		line.Start = Willow::ConvertFromBullet(from);
		line.End = Willow::ConvertFromBullet(to);
		line.Color = Willow::ConvertFromBullet(color);
		lineStructure->Lines.Add(line);
	}

	void drawContactPoint(const btVector3& /*PointOnB*/, const btVector3& /*normalOnB*/, btScalar /*distance*/, int /*lifeTime*/, const btVector3& /*color*/) override
	{
		// Do nothing
	}

	void reportErrorWarning(const char* warningString) override
	{
		Console::Warning("Bullet: @", warningString);
	}

	void draw3dText(const btVector3& /*location*/, const char* /*textString*/) override
	{
		// Do nothing
	}

	void setDebugMode(int /*debugMode*/) override
	{
		// Do nothing
	}

	int	getDebugMode() const override
	{
		return DBG_DrawWireframe | DBG_DrawAabb;
	}
};

namespace Willow
{
	////////////////////////
	///   Constructors   ///

	World::World()
	{
		_physicsWorld = std::make_unique<PhysicsWorld>();
		_nextGameObjectID = 1;
		_physicsWorld->GetDynamicsWorld().setDebugDrawer(new DebugDraw{});
	}

	World::~World()
	{
		// Do nothing
	}

	///////////////////
	///   Methods   ///

	void World::ToArchive(ArchiveWriter& writer) const
	{
		writer.SetID(this);
		writer.PushValue("TimeDilation", this->TimeDilation);
		writer.PushValue("TimeStep", this->TimeStep);
		writer.PushValue("NextID", _nextGameObjectID);

		// Save all entites/components
		writer.AddChild("GameObjects", [this](auto& child)
		{
			for (const auto& kv : this->_gameObjects)
			{
				// Push the given value into this archive, wrapping it in a Node containing its type name and address
				child.PushValueWithID(kv.Second->GetType().GetName(), *kv.Second);
			}
		});
	}

	void World::FromArchive(const ArchiveReader& reader)
	{
		reader.MapID(this);
		reader.PullValue("TimeDilation", this->TimeDilation);
		reader.PullValue("TimeStep", this->TimeStep);
		reader.PullValue("NextID", _nextGameObjectID);

		// Load all entities/components
		reader.GetChild("GameObjects", [&](auto& child)
		{
			Queue<Owned<GameObject>> unloadedObjects;

			// Do a first pass, instantiate everything
			child.EnumerateChildren([&](auto& gameobject)
			{
				// Find the type of GameObject that this node is referring to
				auto type = Application::FindType(gameobject.GetName());

				if (!type || !type->IsCastableTo(TypeOf<GameObject>()))
				{
					// Type isn't a GameObject type, go to next object
					gameobject.MapID(nullptr);
					unloadedObjects.Push(nullptr);
				}
				else
				{
					// Instantiate it
					auto object = StaticPointerCast<GameObject>(DynamicNew(*type));

					// Map the address of the new instantiation to the address in the archive
					gameobject.MapID(object.GetManagedPointer());
					unloadedObjects.Push(std::move(object));
				}
			});

			// Do a second pass, deserialize everything
			child.EnumerateChildren([&](auto& gameobject)
			{
				// If the object is not null, deserialize it
				if (auto object = unloadedObjects.Pop())
				{
					object->FromArchive(gameobject);
					this->SpawnGameObject(std::move(object));
				}
			});
		});

		lineStructure = &this->Spawn<LineStructureComponent>();
	}

	void World::Update()
	{
		Events.DispatchEvent("Update", this->TimeDilation);
		Events.Flush();

		// Remove stale objects
		while (!_destroyedObjects.IsEmpty())
		{
			auto object = _destroyedObjects.Pop();
			_entities.Remove(object->GetID());
			_components.Remove(object->GetID());
			_gameObjects.Remove(object->GetID());
		}

		// Simulate physics
		_physicsWorld->GetDynamicsWorld().stepSimulation(TimeStep, 10);

		lineStructure->Lines.Clear();
		_physicsWorld->GetDynamicsWorld().debugDrawWorld();
	}

	void World::DestroyGameObject(GameObject& object)
	{
		assert(object._state >= GameObject::State::Spawned);

		if (object._state != GameObject::State::Destroyed)
		{
			object._state = GameObject::State::Destroyed;
			_destroyedObjects.Push(&object);
			object.OnDestroy();
		}
	}

	void World::SpawnGameObject(Owned<GameObject> owner)
	{
		auto& object = *owner;

		// Give the object an ID
		assert(object._state == GameObject::State::Uninitialized);
		object._id = _nextGameObjectID++;
		object._state = GameObject::State::Initialized;

		// Add it to the world
		_gameObjects[object.GetID()] = std::move(owner);

		if (auto entity = Cast<Entity>(object))
		{
			_entities[object.GetID()] = entity;
		}
		else if (auto component = Cast<Component>(object))
		{
			_components[object.GetID()] = component;
		}

		// Spawn it
		object._state = GameObject::State::Spawning;
		object.OnSpawn();
		object._state = GameObject::State::Spawned;
	}

	PhysicsWorld& World::INTERNAL_GetPhysicsWorld()
	{
		return *_physicsWorld;
	}

	const PhysicsWorld& World::INTERNAL_GetPhysicsWorld() const
	{
		return *_physicsWorld;
	}
}
<|endoftext|>


<commit_before>//============================================================================
// Name        : Sniffles.cpp
// Author      : Fritz Sedlazeck
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
// phil: cd ~/hetero/philipp/pacbio/example-svs/reads
//For mac: cmake -D CMAKE_C_COMPILER=/opt/local/bin/gcc-mp-4.7 -D CMAKE_CXX_COMPILER=/opt/local/bin/g++-mp-4.7 ..
#include <iostream>
#include "Paramer.h"
#include "tree/IntervallTree.h"
#include <tclap/CmdLine.h>
#include "print/VCFPrinter.h"
#include "Parser/VCFParser.h"
#include "Parser/BEDParser.h"
#include "Parser/GFFParser.h"

Parameter* Parameter::m_pInstance = NULL;
//cmake -D CMAKE_C_COMPILER=/opt/local/bin/gcc-mp-4.7 -D CMAKE_CXX_COMPILER=/opt/local/bin/g++-mp-4.7 ..

void read_parameters(int argc, char *argv[]) {
	TCLAP::CmdLine cmd("Sniffles version 0.0.1", ' ', "0.0.1");
	TCLAP::ValueArg<std::string> arg_svvcf("i", "svvcf", "The vcf file that we should annotate", true, "", "string");
	TCLAP::ValueArg<std::string> arg_vcf("v", "vcf", "VCF input file name(s)", false, "", "string");
	TCLAP::ValueArg<std::string> arg_bed("b", "bed", " bed annotation(s)", false, "", "string");
	TCLAP::ValueArg<std::string> arg_gff("g", "gff", " gff annotation(s)", false, "", "string");
	TCLAP::ValueArg<std::string> arg_out("o", "output", " output file name", false, "", "string");
	TCLAP::ValueArg<int> arg_svsdist("", "svs_distance", "Maximum distance to group SV together. Default: 1000", false, 1000, "int");
	TCLAP::ValueArg<int> arg_annodist("", "anno_distance", "Maximum distance to assign annotations to SVs. Default: 1000", false, 1000, "int");
	TCLAP::ValueArg<int> arg_minlength("l", "min_length", "Minimum length of SV to be reported. Default: 20", false, 20, "int");

	cmd.add(arg_svvcf);
	cmd.add(arg_svsdist);
	cmd.add(arg_annodist);
	cmd.add(arg_bed);
	cmd.add(arg_gff);
	cmd.add(arg_vcf);
	cmd.add(arg_minlength);
	cmd.add(arg_out);

	//parse cmd:
	cmd.parse(argc, argv);
	std::cout<<"BED FILE: "<< arg_bed.getValue()<<std::endl;
	Parameter::Instance()->parse_intput(Parameter::Instance()->bed_files, arg_bed.getValue());
	Parameter::Instance()->parse_intput(Parameter::Instance()->vcf_files, arg_vcf.getValue());
	Parameter::Instance()->parse_intput(Parameter::Instance()->gff_files, arg_gff.getValue());
	Parameter::Instance()->debug = true;
	Parameter::Instance()->output = arg_out.getValue();
	Parameter::Instance()->max_caller = Parameter::Instance()->vcf_files.size() + 1; //+1 because of the inital vcf
	Parameter::Instance()->sv_vcf = arg_svvcf.getValue();
	Parameter::Instance()->svs_dist = arg_svsdist.getValue();
	Parameter::Instance()->anno_dist = arg_annodist.getValue();
	Parameter::Instance()->use_type=false;
}

//TODO: check overlap for annotation depending on the type!!!
//TODO: add annotation exp. to the vcf node!

int main(int argc, char *argv[]) {
	try {
		//init parameter and reads user defined parameter from command line.
		read_parameters(argc, argv);

		IntervallTree bst;
		TNode *root = NULL;

		//TODO extend for parameter.
		Parameter::Instance()->use_type = true;

		//Run through the vcf files to merge them!
		VCFParser * parser_vcf = new VCFParser();
		std::vector<std::string> entry_lines;
		std::string header=parser_vcf->get_header(Parameter::Instance()->sv_vcf);
		std::vector<entry_str> entries = parser_vcf->parse_entries(Parameter::Instance()->sv_vcf);
		for (size_t j = 0; j < entries.size(); j++) {
			if (entries[j].stop.chr.empty()) {
				entries[j].stop.chr = entries[j].start.chr; //some files do just report the first chr;
			}
			bst.insert(entries[j].start, entries[j].stop, entries[j].type,entries[j].line, entries[j].num_reads, 0, root);
		}

		//Annotate with additional vcf files:
		for (size_t i = 0; i < Parameter::Instance()->vcf_files.size(); i++) {
			std::vector<entry_str> entries = parser_vcf->parse_entries(Parameter::Instance()->vcf_files[i]);
			//add to tree;
			for (size_t j = 0; j < entries.size(); j++) {
				if (entries[j].stop.chr.empty()) {
					entries[j].stop.chr = entries[j].start.chr; //some files do just report the first chr;
				}
				bst.add_vcf(entries[j].start, entries[j].stop, entries[j].type, i + 1, root);
			}
		}
		delete parser_vcf;

		//Annotate with additional bed files:
		BEDParser * parser_bed = new BEDParser();
		for (size_t i = 0; i < Parameter::Instance()->bed_files.size(); i++) {
			std::vector<Anno_str> entries = parser_bed->parse_bed(Parameter::Instance()->bed_files[i]);
			//annotate tree;
			for (size_t j = 0; j < entries.size(); j++) {
				if( entries[j].exp.empty()){
					 entries[j].exp=Parameter::Instance()->bed_files[i];
				}
				bst.add_anno(entries[j].start, entries[j].stop, entries[j].exp, root);
			}
		}
		delete parser_bed;

		//Annotate with additional gff files:
		GFFParser * parser_gff = new GFFParser();
		for (size_t i = 0; i < Parameter::Instance()->gff_files.size(); i++) {
			std::vector<Anno_str> entries = parser_gff->parse_gff(Parameter::Instance()->gff_files[i]);
			//annotate tree;
			for (size_t j = 0; j < entries.size(); j++) {
				bst.add_anno(entries[j].start, entries[j].stop, entries[j].exp, root);
			}
		}
		delete parser_gff;

		//init printer:
		VCFPrinter * printer = new VCFPrinter();
		printer->init();
		std::vector<SVS_Node *> points;
		bst.get_breakpoints(root, points);

		for (size_t i = 0; i < points.size(); i++) {
			//we have to collapse the tra again!
			if (points[i]->type == 3) {
				if (i + 1 < points.size() && (points[i]->stop.position == points[i]->start.position && points[i + 1]->stop.position == points[i]->start.position)) {
					points[i]->stop.position = -1;
					points[i]->start.position = -1;
					points[i]->annotations.clear();
					points[i]->caller.clear();
					//is prob a place holder for the next!
					for (size_t j = 0; j < points[i]->annotations.size(); j++) {
						points[i + 1]->annotations.push_back(points[i]->annotations[j]);
					}
				}
			}
		}

		std::cout<<"start printing"<<std::endl;
		//print:
		std::pair<int, int> summary;
		int num=0;
		std::vector<std::string> file;

		std::cout<<"print entries "<<std::endl;
		printer->print_header(header);
		for (size_t i = 0; i < points.size(); i++) {
			if (!points[i]->caller.empty()) {
				num++;
				printer->print_orig_entry(points[i], i, summary);
			}
		}
		printer->close_file();

		std::cout << "Successfully finished" << std::endl;
		std::cout << "total entries: " << num << std::endl;
		std::cout << "overlapping vcf entries: " << summary.first << std::endl;
		std::cout << "overlapping annotations: " << summary.second << std::endl;
	} catch (TCLAP::ArgException &e) {  // catch any exceptions
		std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
	}
	return 0;
}
<commit_msg>Naming changes<commit_after>//============================================================================
// Name        : Sniffles.cpp
// Author      : Fritz Sedlazeck
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
// phil: cd ~/hetero/philipp/pacbio/example-svs/reads
//For mac: cmake -D CMAKE_C_COMPILER=/opt/local/bin/gcc-mp-4.7 -D CMAKE_CXX_COMPILER=/opt/local/bin/g++-mp-4.7 ..
#include <iostream>
#include "Paramer.h"
#include "tree/IntervallTree.h"
#include <tclap/CmdLine.h>
#include "print/VCFPrinter.h"
#include "Parser/VCFParser.h"
#include "Parser/BEDParser.h"
#include "Parser/GFFParser.h"

Parameter* Parameter::m_pInstance = NULL;
//cmake -D CMAKE_C_COMPILER=/opt/local/bin/gcc-mp-4.7 -D CMAKE_CXX_COMPILER=/opt/local/bin/g++-mp-4.7 ..

void read_parameters(int argc, char *argv[]) {
	TCLAP::CmdLine cmd("SURVIVOR_ant version 0.0.1", ' ', "0.0.1");
	TCLAP::ValueArg<std::string> arg_svvcf("i", "svvcf", "The vcf file that we should annotate", true, "", "string");
	TCLAP::ValueArg<std::string> arg_vcf("v", "vcf", "VCF input file name(s)", false, "", "string");
	TCLAP::ValueArg<std::string> arg_bed("b", "bed", " bed annotation(s)", false, "", "string");
	TCLAP::ValueArg<std::string> arg_gff("g", "gff", " gff annotation(s)", false, "", "string");
	TCLAP::ValueArg<std::string> arg_out("o", "output", " output file name", false, "", "string");
	TCLAP::ValueArg<int> arg_svsdist("", "svs_distance", "Maximum distance to group SV together. Default: 1000", false, 1000, "int");
	TCLAP::ValueArg<int> arg_annodist("", "anno_distance", "Maximum distance to assign annotations to SVs. Default: 1000", false, 1000, "int");
	TCLAP::ValueArg<int> arg_minlength("l", "min_length", "Minimum length of SV to be reported. Default: 20", false, 20, "int");

	cmd.add(arg_svvcf);
	cmd.add(arg_svsdist);
	cmd.add(arg_annodist);
	cmd.add(arg_bed);
	cmd.add(arg_gff);
	cmd.add(arg_vcf);
	cmd.add(arg_minlength);
	cmd.add(arg_out);

	//parse cmd:
	cmd.parse(argc, argv);
	std::cout<<"BED FILE: "<< arg_bed.getValue()<<std::endl;
	Parameter::Instance()->parse_intput(Parameter::Instance()->bed_files, arg_bed.getValue());
	Parameter::Instance()->parse_intput(Parameter::Instance()->vcf_files, arg_vcf.getValue());
	Parameter::Instance()->parse_intput(Parameter::Instance()->gff_files, arg_gff.getValue());
	Parameter::Instance()->debug = true;
	Parameter::Instance()->output = arg_out.getValue();
	Parameter::Instance()->max_caller = Parameter::Instance()->vcf_files.size() + 1; //+1 because of the inital vcf
	Parameter::Instance()->sv_vcf = arg_svvcf.getValue();
	Parameter::Instance()->svs_dist = arg_svsdist.getValue();
	Parameter::Instance()->anno_dist = arg_annodist.getValue();
	Parameter::Instance()->use_type=false;
}

//TODO: check overlap for annotation depending on the type!!!
//TODO: add annotation exp. to the vcf node!

int main(int argc, char *argv[]) {
	try {
		//init parameter and reads user defined parameter from command line.
		read_parameters(argc, argv);

		IntervallTree bst;
		TNode *root = NULL;

		//TODO extend for parameter.
		Parameter::Instance()->use_type = true;

		//Run through the vcf files to merge them!
		VCFParser * parser_vcf = new VCFParser();
		std::vector<std::string> entry_lines;
		std::string header=parser_vcf->get_header(Parameter::Instance()->sv_vcf);
		std::vector<entry_str> entries = parser_vcf->parse_entries(Parameter::Instance()->sv_vcf);
		for (size_t j = 0; j < entries.size(); j++) {
			if (entries[j].stop.chr.empty()) {
				entries[j].stop.chr = entries[j].start.chr; //some files do just report the first chr;
			}
			bst.insert(entries[j].start, entries[j].stop, entries[j].type,entries[j].line, entries[j].num_reads, 0, root);
		}

		//Annotate with additional vcf files:
		for (size_t i = 0; i < Parameter::Instance()->vcf_files.size(); i++) {
			std::vector<entry_str> entries = parser_vcf->parse_entries(Parameter::Instance()->vcf_files[i]);
			//add to tree;
			for (size_t j = 0; j < entries.size(); j++) {
				if (entries[j].stop.chr.empty()) {
					entries[j].stop.chr = entries[j].start.chr; //some files do just report the first chr;
				}
				bst.add_vcf(entries[j].start, entries[j].stop, entries[j].type, i + 1, root);
			}
		}
		delete parser_vcf;

		//Annotate with additional bed files:
		BEDParser * parser_bed = new BEDParser();
		for (size_t i = 0; i < Parameter::Instance()->bed_files.size(); i++) {
			std::vector<Anno_str> entries = parser_bed->parse_bed(Parameter::Instance()->bed_files[i]);
			//annotate tree;
			for (size_t j = 0; j < entries.size(); j++) {
				if( entries[j].exp.empty()){
					 entries[j].exp=Parameter::Instance()->bed_files[i];
				}
				bst.add_anno(entries[j].start, entries[j].stop, entries[j].exp, root);
			}
		}
		delete parser_bed;

		//Annotate with additional gff files:
		GFFParser * parser_gff = new GFFParser();
		for (size_t i = 0; i < Parameter::Instance()->gff_files.size(); i++) {
			std::vector<Anno_str> entries = parser_gff->parse_gff(Parameter::Instance()->gff_files[i]);
			//annotate tree;
			for (size_t j = 0; j < entries.size(); j++) {
				bst.add_anno(entries[j].start, entries[j].stop, entries[j].exp, root);
			}
		}
		delete parser_gff;

		//init printer:
		VCFPrinter * printer = new VCFPrinter();
		printer->init();
		std::vector<SVS_Node *> points;
		bst.get_breakpoints(root, points);

		for (size_t i = 0; i < points.size(); i++) {
			//we have to collapse the tra again!
			if (points[i]->type == 3) {
				if (i + 1 < points.size() && (points[i]->stop.position == points[i]->start.position && points[i + 1]->stop.position == points[i]->start.position)) {
					points[i]->stop.position = -1;
					points[i]->start.position = -1;
					points[i]->annotations.clear();
					points[i]->caller.clear();
					//is prob a place holder for the next!
					for (size_t j = 0; j < points[i]->annotations.size(); j++) {
						points[i + 1]->annotations.push_back(points[i]->annotations[j]);
					}
				}
			}
		}

		std::cout<<"start printing"<<std::endl;
		//print:
		std::pair<int, int> summary;
		int num=0;
		std::vector<std::string> file;

		std::cout<<"print entries "<<std::endl;
		printer->print_header(header);
		for (size_t i = 0; i < points.size(); i++) {
			if (!points[i]->caller.empty()) {
				num++;
				printer->print_orig_entry(points[i], i, summary);
			}
		}
		printer->close_file();

		std::cout << "Successfully finished" << std::endl;
		std::cout << "total entries: " << num << std::endl;
		std::cout << "overlapping vcf entries: " << summary.first << std::endl;
		std::cout << "overlapping annotations: " << summary.second << std::endl;
	} catch (TCLAP::ArgException &e) {  // catch any exceptions
		std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
	}
	return 0;
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016-present, Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "caffe2/operators/slice_op.h"

namespace caffe2 {

REGISTER_CPU_OPERATOR(Slice, SliceOp<int, CPUContext>);
REGISTER_CPU_OPERATOR(SliceGradient, SliceGradientOp<int, CPUContext>);

OPERATOR_SCHEMA(Slice)
    .NumInputs(1, 3)
    .NumOutputs(1)
    .SetDoc(R"DOC(
Produces a slice of the input tensor. Currently, only slicing in a single
dimension is supported.
Slices are passed as 2 1D vectors or as two keyword argument lists with starting
and end indices for each dimension of the input `data` tensor. End indices are
non-inclusive. If a negative value is passed for any of the start or end
indices, it represent number of elements before the end of that dimension.

Example:

  data = [
      [1, 2, 3, 4],
      [5, 6, 7, 8],
  ]
  starts = [0, 1]
  ends = [-1, 3]

  result = [
      [2, 3],
      [6, 7],
  ]
)DOC")
    .Input(0, "data", "Tensor of data to extract slices from.")
    .Input(1, "starts", "1D tensor: start-indices for each dimension of data.")
    .Input(2, "ends", "1D tensor: end-indices for each dimension of data.")
    .Arg("starts", "List of starting indices")
    .Arg("ends", "List of ending indices")
    .TensorInferenceFunction([](const OperatorDef& def,
                                const vector<TensorShape>& in) {
      if (in.size() > 1) {
        // Cannot compute shape inference when the splits are defined
        // in data.
        return vector<TensorShape>();
      }
      auto const& data = in[0];

      ArgumentHelper helper(def);
      auto starts = helper.GetRepeatedArgument<int>("starts", vector<int>());
      auto ends = helper.GetRepeatedArgument<int>("ends", vector<int>());
      vector<int> dst_sizes(data.dims_size());

      for (int i = 0; i < data.dims_size(); ++i) {
        if (i >= starts.size()) {
          continue;
        }
        if (data.dims_size() > 0) {
          auto start = starts[i];
          auto end = ends[i];
          if (start < 0) {
            start = data.dims(i) + 1 + start;
          }
          if (end < 0) {
            end = data.dims(i) + 1 + end;
          }
          dst_sizes[i] = end - start;
        } else {
          dst_sizes[i] = 0;
        }
      }
      return vector<TensorShape>{
          CreateTensorShape(dst_sizes, data.data_type())};
    })
    .Output(0, "output", "Sliced data tensor.");

OPERATOR_SCHEMA(SliceGradient);

namespace {
struct GetSliceGradient : public GradientMakerBase {
  using GradientMakerBase::GradientMakerBase;
  vector<OperatorDef> GetGradientDefs() override {
    if (def_.input_size() > 1) {
      return vector<OperatorDef>{CreateOperatorDef(
          "SliceGradient",
          "",
          std::vector<string>{I(0), I(1), I(2), GO(0)},
          std::vector<string>{GI(0)})};
    } else {
      return vector<OperatorDef>{CreateOperatorDef(
          "SliceGradient",
          "",
          std::vector<string>{I(0), GO(0)},
          std::vector<string>{GI(0)})};
    }
  }
};
}
REGISTER_GRADIENT(Slice, GetSliceGradient);
} // namespace caffe2
<commit_msg>Clarify Slice operator documentation<commit_after>/**
 * Copyright (c) 2016-present, Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "caffe2/operators/slice_op.h"

namespace caffe2 {

REGISTER_CPU_OPERATOR(Slice, SliceOp<int, CPUContext>);
REGISTER_CPU_OPERATOR(SliceGradient, SliceGradientOp<int, CPUContext>);

OPERATOR_SCHEMA(Slice)
    .NumInputs(1, 3)
    .NumOutputs(1)
    .SetDoc(R"DOC(
Produces a slice of the input tensor. Currently, only slicing in a single
dimension is supported.
Slices are passed as 2 1D vectors or as two keyword argument lists with starting
and end indices for each dimension of the input `data` tensor. If a negative
value is passed for any of the start or end indices, it represents the number of
elements before the end of that dimension. End indices are non-inclusive unless
negative (end index -1 means up to and including the last element).

Example:

  data = [
      [1, 2, 3, 4],
      [5, 6, 7, 8],
  ]
  starts = [0, 1]
  ends = [-1, 3]

  result = [
      [2, 3],
      [6, 7],
  ]
)DOC")
    .Input(0, "data", "Tensor of data to extract slices from.")
    .Input(1, "starts", "1D tensor: start-indices for each dimension of data.")
    .Input(2, "ends", "1D tensor: end-indices for each dimension of data.")
    .Arg("starts", "List of starting indices")
    .Arg("ends", "List of ending indices")
    .TensorInferenceFunction([](const OperatorDef& def,
                                const vector<TensorShape>& in) {
      if (in.size() > 1) {
        // Cannot compute shape inference when the splits are defined
        // in data.
        return vector<TensorShape>();
      }
      auto const& data = in[0];

      ArgumentHelper helper(def);
      auto starts = helper.GetRepeatedArgument<int>("starts", vector<int>());
      auto ends = helper.GetRepeatedArgument<int>("ends", vector<int>());
      vector<int> dst_sizes(data.dims_size());

      for (int i = 0; i < data.dims_size(); ++i) {
        if (i >= starts.size()) {
          continue;
        }
        if (data.dims_size() > 0) {
          auto start = starts[i];
          auto end = ends[i];
          if (start < 0) {
            start = data.dims(i) + 1 + start;
          }
          if (end < 0) {
            end = data.dims(i) + 1 + end;
          }
          dst_sizes[i] = end - start;
        } else {
          dst_sizes[i] = 0;
        }
      }
      return vector<TensorShape>{
          CreateTensorShape(dst_sizes, data.data_type())};
    })
    .Output(0, "output", "Sliced data tensor.");

OPERATOR_SCHEMA(SliceGradient);

namespace {
struct GetSliceGradient : public GradientMakerBase {
  using GradientMakerBase::GradientMakerBase;
  vector<OperatorDef> GetGradientDefs() override {
    if (def_.input_size() > 1) {
      return vector<OperatorDef>{CreateOperatorDef(
          "SliceGradient",
          "",
          std::vector<string>{I(0), I(1), I(2), GO(0)},
          std::vector<string>{GI(0)})};
    } else {
      return vector<OperatorDef>{CreateOperatorDef(
          "SliceGradient",
          "",
          std::vector<string>{I(0), GO(0)},
          std::vector<string>{GI(0)})};
    }
  }
};
}
REGISTER_GRADIENT(Slice, GetSliceGradient);
} // namespace caffe2
<|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 "ui/views/controls/button/label_button_border.h"

#include "base/logging.h"
#include "grit/ui_resources.h"
#include "ui/base/animation/animation.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/rect.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/native_theme_delegate.h"

namespace views {

namespace {

// The button image IDs and focused images IDs used in lieu of a focus border.
const int kNormalImages[] = IMAGE_GRID(IDR_BUTTON_NORMAL);
const int kHoveredImages[] = IMAGE_GRID(IDR_BUTTON_HOVER);
const int kPressedImages[] = IMAGE_GRID(IDR_BUTTON_PRESSED);
const int kFocusedNormalImages[] = IMAGE_GRID(IDR_BUTTON_FOCUSED_NORMAL);
const int kFocusedHoveredImages[] = IMAGE_GRID(IDR_BUTTON_FOCUSED_HOVER);
const int kFocusedPressedImages[] = IMAGE_GRID(IDR_BUTTON_FOCUSED_PRESSED);

// The text-button hot and pushed image IDs; normal is unadorned by default.
const int kTextHoveredImages[] = IMAGE_GRID(IDR_TEXTBUTTON_HOVER);
const int kTextPressedImages[] = IMAGE_GRID(IDR_TEXTBUTTON_PRESSED);

Button::ButtonState GetButtonState(ui::NativeTheme::State state) {
  switch(state) {
    case ui::NativeTheme::kDisabled: return Button::STATE_DISABLED;
    case ui::NativeTheme::kHovered:  return Button::STATE_HOVERED;
    case ui::NativeTheme::kNormal:   return Button::STATE_NORMAL;
    case ui::NativeTheme::kPressed:  return Button::STATE_PRESSED;
    case ui::NativeTheme::kMaxState: NOTREACHED() << "Unknown state: " << state;
  }
  return Button::STATE_NORMAL;
}

// A helper function to paint the native theme or images as appropriate.
void PaintHelper(LabelButtonBorder* border,
                 gfx::Canvas* canvas,
                 const ui::NativeTheme* theme,
                 ui::NativeTheme::Part part,
                 ui::NativeTheme::State state,
                 const gfx::Rect& rect,
                 const ui::NativeTheme::ExtraParams& extra) {
  if (border->style() == Button::STYLE_NATIVE_TEXTBUTTON) {
    theme->Paint(canvas->sk_canvas(), part, state, rect, extra);
  } else {
    Painter* painter =
        border->GetPainter(extra.button.is_focused, GetButtonState(state));
    // Paint any corresponding unfocused painter if there is no focused painter.
    if (!painter && extra.button.is_focused)
      painter = border->GetPainter(false, GetButtonState(state));
    if (painter)
      painter->Paint(canvas, rect.size());
  }
}

}  // namespace

LabelButtonBorder::LabelButtonBorder(Button::ButtonStyle style)
    : style_(style) {
  if (style == Button::STYLE_BUTTON) {
    SetPainter(false, Button::STATE_NORMAL,
               Painter::CreateImageGridPainter(kNormalImages));
    SetPainter(false, Button::STATE_HOVERED,
               Painter::CreateImageGridPainter(kHoveredImages));
    SetPainter(false, Button::STATE_PRESSED,
               Painter::CreateImageGridPainter(kPressedImages));
    SetPainter(false, Button::STATE_DISABLED,
               Painter::CreateImageGridPainter(kNormalImages));
    SetPainter(true, Button::STATE_NORMAL,
               Painter::CreateImageGridPainter(kFocusedNormalImages));
    SetPainter(true, Button::STATE_HOVERED,
               Painter::CreateImageGridPainter(kFocusedHoveredImages));
    SetPainter(true, Button::STATE_PRESSED,
               Painter::CreateImageGridPainter(kFocusedPressedImages));
    SetPainter(true, Button::STATE_DISABLED,
               Painter::CreateImageGridPainter(kNormalImages));
  } else if (style == Button::STYLE_TEXTBUTTON) {
    SetPainter(false, Button::STATE_HOVERED,
               Painter::CreateImageGridPainter(kTextHoveredImages));
    SetPainter(false, Button::STATE_PRESSED,
               Painter::CreateImageGridPainter(kTextPressedImages));
  }
}

LabelButtonBorder::~LabelButtonBorder() {}

void LabelButtonBorder::Paint(const View& view, gfx::Canvas* canvas) {
  DCHECK(!strcmp(view.GetClassName(), LabelButton::kViewClassName));
  const NativeThemeDelegate* native_theme_delegate =
      static_cast<const LabelButton*>(&view);
  ui::NativeTheme::Part part = native_theme_delegate->GetThemePart();
  gfx::Rect rect(native_theme_delegate->GetThemePaintRect());
  ui::NativeTheme::ExtraParams extra;
  const ui::NativeTheme* theme = view.GetNativeTheme();
  const ui::Animation* animation = native_theme_delegate->GetThemeAnimation();
  ui::NativeTheme::State state = native_theme_delegate->GetThemeState(&extra);

  if (animation && animation->is_animating()) {
    // Composite the background and foreground painters during state animations.
    int alpha = animation->CurrentValueBetween(0, 0xff);
    state = native_theme_delegate->GetBackgroundThemeState(&extra);
    canvas->SaveLayerAlpha(static_cast<uint8>(0xff - alpha));
    PaintHelper(this, canvas, theme, part, state, rect, extra);
    canvas->Restore();

    state = native_theme_delegate->GetForegroundThemeState(&extra);
    canvas->SaveLayerAlpha(static_cast<uint8>(alpha));
    PaintHelper(this, canvas, theme, part, state, rect, extra);
    canvas->Restore();
  } else if (state == ui::NativeTheme::kDisabled &&
             style() == Button::STYLE_BUTTON) {
    canvas->SaveLayerAlpha(static_cast<uint8>(0xff / 2));
    PaintHelper(this, canvas, theme, part, state, rect, extra);
    canvas->Restore();
  } else {
    PaintHelper(this, canvas, theme, part, state, rect, extra);
  }

  // Draw the Views focus border for the native theme style.
  if (style() == Button::STYLE_NATIVE_TEXTBUTTON &&
      view.focus_border() && extra.button.is_focused)
    view.focus_border()->Paint(view, canvas);
}

gfx::Insets LabelButtonBorder::GetInsets() const {
  // Return the style-specific insets between button contents and edges.
  if (style() == Button::STYLE_BUTTON)
    return gfx::Insets(9, 13, 9, 13);
  if (style() == Button::STYLE_TEXTBUTTON)
    return gfx::Insets(5, 6, 5, 6);
  if (style() == Button::STYLE_NATIVE_TEXTBUTTON)
    return gfx::Insets(5, 12, 5, 12);
  NOTREACHED();
  return gfx::Insets();
}

Painter* LabelButtonBorder::GetPainter(bool focused,
                                       Button::ButtonState state) {
  return painters_[focused ? 1 : 0][state].get();
}

void LabelButtonBorder::SetPainter(bool focused,
                                   Button::ButtonState state,
                                   Painter* painter) {
  painters_[focused ? 1 : 0][state].reset(painter);
}

}  // namespace views
<commit_msg>Use new disabled button assets, not 50% alpha.<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 "ui/views/controls/button/label_button_border.h"

#include "base/logging.h"
#include "grit/ui_resources.h"
#include "ui/base/animation/animation.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/rect.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/native_theme_delegate.h"

namespace views {

namespace {

// The button image IDs and focused images IDs used in lieu of a focus border.
const int kNormalImages[] = IMAGE_GRID(IDR_BUTTON_NORMAL);
const int kHoveredImages[] = IMAGE_GRID(IDR_BUTTON_HOVER);
const int kPressedImages[] = IMAGE_GRID(IDR_BUTTON_PRESSED);
const int kDisabledImages[] = IMAGE_GRID(IDR_BUTTON_DISABLED);
const int kFocusedNormalImages[] = IMAGE_GRID(IDR_BUTTON_FOCUSED_NORMAL);
const int kFocusedHoveredImages[] = IMAGE_GRID(IDR_BUTTON_FOCUSED_HOVER);
const int kFocusedPressedImages[] = IMAGE_GRID(IDR_BUTTON_FOCUSED_PRESSED);

// The text-button hot and pushed image IDs; normal is unadorned by default.
const int kTextHoveredImages[] = IMAGE_GRID(IDR_TEXTBUTTON_HOVER);
const int kTextPressedImages[] = IMAGE_GRID(IDR_TEXTBUTTON_PRESSED);

Button::ButtonState GetButtonState(ui::NativeTheme::State state) {
  switch(state) {
    case ui::NativeTheme::kDisabled: return Button::STATE_DISABLED;
    case ui::NativeTheme::kHovered:  return Button::STATE_HOVERED;
    case ui::NativeTheme::kNormal:   return Button::STATE_NORMAL;
    case ui::NativeTheme::kPressed:  return Button::STATE_PRESSED;
    case ui::NativeTheme::kMaxState: NOTREACHED() << "Unknown state: " << state;
  }
  return Button::STATE_NORMAL;
}

// A helper function to paint the native theme or images as appropriate.
void PaintHelper(LabelButtonBorder* border,
                 gfx::Canvas* canvas,
                 const ui::NativeTheme* theme,
                 ui::NativeTheme::Part part,
                 ui::NativeTheme::State state,
                 const gfx::Rect& rect,
                 const ui::NativeTheme::ExtraParams& extra) {
  if (border->style() == Button::STYLE_NATIVE_TEXTBUTTON) {
    theme->Paint(canvas->sk_canvas(), part, state, rect, extra);
  } else {
    Painter* painter =
        border->GetPainter(extra.button.is_focused, GetButtonState(state));
    // Paint any corresponding unfocused painter if there is no focused painter.
    if (!painter && extra.button.is_focused)
      painter = border->GetPainter(false, GetButtonState(state));
    if (painter)
      painter->Paint(canvas, rect.size());
  }
}

}  // namespace

LabelButtonBorder::LabelButtonBorder(Button::ButtonStyle style)
    : style_(style) {
  if (style == Button::STYLE_BUTTON) {
    SetPainter(false, Button::STATE_NORMAL,
               Painter::CreateImageGridPainter(kNormalImages));
    SetPainter(false, Button::STATE_HOVERED,
               Painter::CreateImageGridPainter(kHoveredImages));
    SetPainter(false, Button::STATE_PRESSED,
               Painter::CreateImageGridPainter(kPressedImages));
    SetPainter(false, Button::STATE_DISABLED,
               Painter::CreateImageGridPainter(kDisabledImages));
    SetPainter(true, Button::STATE_NORMAL,
               Painter::CreateImageGridPainter(kFocusedNormalImages));
    SetPainter(true, Button::STATE_HOVERED,
               Painter::CreateImageGridPainter(kFocusedHoveredImages));
    SetPainter(true, Button::STATE_PRESSED,
               Painter::CreateImageGridPainter(kFocusedPressedImages));
    SetPainter(true, Button::STATE_DISABLED,
               Painter::CreateImageGridPainter(kDisabledImages));
  } else if (style == Button::STYLE_TEXTBUTTON) {
    SetPainter(false, Button::STATE_HOVERED,
               Painter::CreateImageGridPainter(kTextHoveredImages));
    SetPainter(false, Button::STATE_PRESSED,
               Painter::CreateImageGridPainter(kTextPressedImages));
  }
}

LabelButtonBorder::~LabelButtonBorder() {}

void LabelButtonBorder::Paint(const View& view, gfx::Canvas* canvas) {
  DCHECK(!strcmp(view.GetClassName(), LabelButton::kViewClassName));
  const NativeThemeDelegate* native_theme_delegate =
      static_cast<const LabelButton*>(&view);
  ui::NativeTheme::Part part = native_theme_delegate->GetThemePart();
  gfx::Rect rect(native_theme_delegate->GetThemePaintRect());
  ui::NativeTheme::ExtraParams extra;
  const ui::NativeTheme* theme = view.GetNativeTheme();
  const ui::Animation* animation = native_theme_delegate->GetThemeAnimation();
  ui::NativeTheme::State state = native_theme_delegate->GetThemeState(&extra);

  if (animation && animation->is_animating()) {
    // Composite the background and foreground painters during state animations.
    int alpha = animation->CurrentValueBetween(0, 0xff);
    state = native_theme_delegate->GetBackgroundThemeState(&extra);
    canvas->SaveLayerAlpha(static_cast<uint8>(0xff - alpha));
    PaintHelper(this, canvas, theme, part, state, rect, extra);
    canvas->Restore();

    state = native_theme_delegate->GetForegroundThemeState(&extra);
    canvas->SaveLayerAlpha(static_cast<uint8>(alpha));
    PaintHelper(this, canvas, theme, part, state, rect, extra);
    canvas->Restore();
  } else {
    PaintHelper(this, canvas, theme, part, state, rect, extra);
  }

  // Draw the Views focus border for the native theme style.
  if (style() == Button::STYLE_NATIVE_TEXTBUTTON &&
      view.focus_border() && extra.button.is_focused)
    view.focus_border()->Paint(view, canvas);
}

gfx::Insets LabelButtonBorder::GetInsets() const {
  // Return the style-specific insets between button contents and edges.
  if (style() == Button::STYLE_BUTTON)
    return gfx::Insets(9, 13, 9, 13);
  if (style() == Button::STYLE_TEXTBUTTON)
    return gfx::Insets(5, 6, 5, 6);
  if (style() == Button::STYLE_NATIVE_TEXTBUTTON)
    return gfx::Insets(5, 12, 5, 12);
  NOTREACHED();
  return gfx::Insets();
}

Painter* LabelButtonBorder::GetPainter(bool focused,
                                       Button::ButtonState state) {
  return painters_[focused ? 1 : 0][state].get();
}

void LabelButtonBorder::SetPainter(bool focused,
                                   Button::ButtonState state,
                                   Painter* painter) {
  painters_[focused ? 1 : 0][state].reset(painter);
}

}  // namespace views
<|endoftext|>


<commit_before>{
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*
//*-*  This program creates :
//*-*    - a one dimensional histogram
//*-*    - a two dimensional histogram
//*-*    - a profile histogram
//*-*    - a memory-resident ntuple
//*-*
//*-*  These objects are filled with some random numbers and saved on a file.
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

  gROOT->Reset();

// Create a new canvas.
  c1 = new TCanvas("c1","Dynamic Filling Example",200,10,700,500);
  c1->SetFillColor(42);
  c1->GetFrame()->SetFillColor(21);
  c1->GetFrame()->SetBorderSize(6);
  c1->GetFrame()->SetBorderMode(-1);

// Create a new ROOT binary machine independent file.
// Note that this file may contain any kind of ROOT objects, histograms,
// pictures, graphics objects, detector geometries, tracks, events, etc..
// This file is now becoming the current directory.

  TFile *hfile = (TFile*)gROOT->FindObject("hsimple.root"); if (hfile) hfile->Close();
  hfile = new TFile("hsimple.root","RECREATE","Demo ROOT file with histograms");

// Create some histograms, a profile histogram and an ntuple
  hpx    = new TH1F("hpx","This is the px distribution",100,-4,4);
  hpxpy  = new TH2F("hpxpy","py vs px",40,-4,4,40,-4,4);
  hprof  = new TProfile("hprof","Profile of pz versus px",100,-4,4,0,20);
  ntuple = new TNtuple("ntuple","Demo ntuple","px:py:pz:random:i");

//  Set canvas/frame attributes (save old attributes)
  hpx->SetFillColor(48);

  gBenchmark->Start("hsimple");

// Fill histograms randomly
  gRandom->SetSeed();
  Float_t px, py, pz;
  const Int_t kUPDATE = 1000;
  for (Int_t i = 0; i < 25000; i++) {
     gRandom->Rannor(px,py);
     pz = px*px + py*py;
     Float_t random = gRandom->Rndm(1);
     hpx->Fill(px);
     hpxpy->Fill(px,py);
     hprof->Fill(px,pz);
     ntuple->Fill(px,py,pz,random,i);
     if (i && (i%kUPDATE) == 0) {
        if (i == kUPDATE) hpx->Draw();
        c1->Modified();
        c1->Update();
        if (gSystem->ProcessEvents())
           break;
     }
  }
  gBenchmark->Show("hsimple");

// Save all objects in this file
  hpx->SetFillColor(0);
  hfile->Write();
  hpx->SetFillColor(48);

// Note that the file is automatically close when application terminates
// or when the file destructor is called.
}
<commit_msg>Add the statement c1->Modified() at the end of hsimple.C to force the update of the canvas when the macro terminates.<commit_after>{
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*
//*-*  This program creates :
//*-*    - a one dimensional histogram
//*-*    - a two dimensional histogram
//*-*    - a profile histogram
//*-*    - a memory-resident ntuple
//*-*
//*-*  These objects are filled with some random numbers and saved on a file.
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

  gROOT->Reset();

// Create a new canvas.
  c1 = new TCanvas("c1","Dynamic Filling Example",200,10,700,500);
  c1->SetFillColor(42);
  c1->GetFrame()->SetFillColor(21);
  c1->GetFrame()->SetBorderSize(6);
  c1->GetFrame()->SetBorderMode(-1);

// Create a new ROOT binary machine independent file.
// Note that this file may contain any kind of ROOT objects, histograms,
// pictures, graphics objects, detector geometries, tracks, events, etc..
// This file is now becoming the current directory.

  TFile *hfile = (TFile*)gROOT->FindObject("hsimple.root"); if (hfile) hfile->Close();
  hfile = new TFile("hsimple.root","RECREATE","Demo ROOT file with histograms");

// Create some histograms, a profile histogram and an ntuple
  hpx    = new TH1F("hpx","This is the px distribution",100,-4,4);
  hpxpy  = new TH2F("hpxpy","py vs px",40,-4,4,40,-4,4);
  hprof  = new TProfile("hprof","Profile of pz versus px",100,-4,4,0,20);
  ntuple = new TNtuple("ntuple","Demo ntuple","px:py:pz:random:i");

//  Set canvas/frame attributes (save old attributes)
  hpx->SetFillColor(48);

  gBenchmark->Start("hsimple");

// Fill histograms randomly
  gRandom->SetSeed();
  Float_t px, py, pz;
  const Int_t kUPDATE = 1000;
  for (Int_t i = 0; i < 25000; i++) {
     gRandom->Rannor(px,py);
     pz = px*px + py*py;
     Float_t random = gRandom->Rndm(1);
     hpx->Fill(px);
     hpxpy->Fill(px,py);
     hprof->Fill(px,pz);
     ntuple->Fill(px,py,pz,random,i);
     if (i && (i%kUPDATE) == 0) {
        if (i == kUPDATE) hpx->Draw();
        c1->Modified();
        c1->Update();
        if (gSystem->ProcessEvents())
           break;
     }
  }
  gBenchmark->Show("hsimple");

// Save all objects in this file
  hpx->SetFillColor(0);
  hfile->Write();
  hpx->SetFillColor(48);
  c1->Modified();

// Note that the file is automatically close when application terminates
// or when the file destructor is called.
}
<|endoftext|>


<commit_before>#include "SoundManager.h"
#include "Log.h"

SoundManager::SoundManager()
{
    Mix_OpenAudio(SOUND_FREQUENCY, SOUND_FORMAT, SOUND_CHANNELS, SOUND_CHUNKSIZE);
}

SoundManager &SoundManager::instance()
{
    static SoundManager m_instance;
    return m_instance;
}

bool SoundManager::loadSound(std::string keyName, std::string fileName, audio_type type) {
    if(type == SOUND_SFX)
    {
        Mix_Chunk *chunk = Mix_LoadWAV(fileName.c_str());
        if(chunk == 0) {
            Log::Error("Failed to load SFX :  " + fileName);
            Log::Error(Mix_GetError());
            return false;
        }
        else {
            m_soundbuffers[keyName] = chunk;
            return true;
        }
    }

    else if(type == SOUND_MUSIC)
    {

    }

    else {
        Log::Error("Failed to load invalid file type " + fileName);
        return false;
    }

}

void SoundManager::playSound(std::string keyName, bool loop) {

}

void SoundManager::playMusic(std::string keyName, bool loop) {

}
<commit_msg>SoundManager music loader<commit_after>#include "SoundManager.h"
#include "Log.h"

SoundManager::SoundManager()
{
    Mix_OpenAudio(SOUND_FREQUENCY, SOUND_FORMAT, SOUND_CHANNELS, SOUND_CHUNKSIZE);
}

SoundManager &SoundManager::instance()
{
    static SoundManager m_instance;
    return m_instance;
}

bool SoundManager::loadSound(std::string keyName, std::string fileName, audio_type type) {
    if(type == SOUND_SFX)
    {
        Mix_Chunk *chunk = Mix_LoadWAV(fileName.c_str());
        if(chunk == 0) {
            Log::Error("Failed to load SFX :  " + fileName);
            Log::Error(Mix_GetError());
            return false;
        }
        else {
            m_soundbuffers[keyName] = chunk;
            return true;
        }
    }

    else if(type == SOUND_MUSIC)
    {
        Mix_Music *chunk = Mix_LoadMUS(fileName.c_str());
        if(chunk == 0) {
            Log::Error("Failed to load Music :  " + fileName);
            Log::Error(Mix_GetError());
            return false;
        }
        else {
            m_musicbuffers[keyName] = chunk;
            return true;
        }
    }

    else {
        Log::Error("Failed to load invalid file type " + fileName);
        return false;
    }

}

void SoundManager::playSound(std::string keyName, bool loop) {

}

void SoundManager::playMusic(std::string keyName, bool loop) {

}
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2016
// Mehdi Goli    Codeplay Software Ltd.
// Ralph Potter  Codeplay Software Ltd.
// Luke Iwanski  Codeplay Software Ltd.
// Contact: <eigen@codeplay.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#define EIGEN_TEST_NO_LONGDOUBLE
#define EIGEN_TEST_NO_COMPLEX
#define EIGEN_TEST_FUNC cxx11_tensor_builtins_sycl
#define EIGEN_DEFAULT_DENSE_INDEX_TYPE int
#define EIGEN_USE_SYCL

#include "main.h"
#include <unsupported/Eigen/CXX11/Tensor>

using Eigen::array;
using Eigen::SyclDevice;
using Eigen::Tensor;
using Eigen::TensorMap;

namespace std {
template <typename T> T rsqrt(T x) { return 1 / std::sqrt(x); }
template <typename T> T square(T x) { return x * x; }
template <typename T> T cube(T x) { return x * x * x; }
template <typename T> T inverse(T x) { return 1 / x; }
}

#define TEST_UNARY_BUILTINS_FOR_SCALAR(FUNC, SCALAR)                           \
  {                                                                            \
    Tensor<SCALAR, 3> in(tensorRange);                                         \
    Tensor<SCALAR, 3> out(tensorRange);                                        \
    in = in.random() + static_cast<SCALAR>(0.01);                              \
    SCALAR *gpu_data = static_cast<SCALAR *>(                                  \
        sycl_device.allocate(in.size() * sizeof(SCALAR)));                     \
    SCALAR *gpu_data_out = static_cast<SCALAR *>(                              \
        sycl_device.allocate(out.size() * sizeof(SCALAR)));                    \
    TensorMap<Tensor<SCALAR, 3>> gpu(gpu_data, tensorRange);                   \
    TensorMap<Tensor<SCALAR, 3>> gpu_out(gpu_data_out, tensorRange);           \
    sycl_device.memcpyHostToDevice(gpu_data, in.data(),                        \
                                   (in.size()) * sizeof(SCALAR));              \
    gpu_out.device(sycl_device) = gpu.FUNC();                                  \
    sycl_device.memcpyDeviceToHost(out.data(), gpu_data_out,                   \
                                   (out.size()) * sizeof(SCALAR));             \
    for (int i = 0; i < in.size(); ++i) {                                      \
      VERIFY_IS_APPROX(out(i), std::FUNC(in(i)));                              \
    }                                                                          \
    sycl_device.deallocate(gpu_data);                                          \
    sycl_device.deallocate(gpu_data_out);                                      \
  }

#define TEST_UNARY_BUILTINS(SCALAR)                                            \
  TEST_UNARY_BUILTINS_FOR_SCALAR(abs, SCALAR)                                  \
  TEST_UNARY_BUILTINS_FOR_SCALAR(sqrt, SCALAR)                                 \
  TEST_UNARY_BUILTINS_FOR_SCALAR(rsqrt, SCALAR)                                \
  TEST_UNARY_BUILTINS_FOR_SCALAR(square, SCALAR)                               \
  TEST_UNARY_BUILTINS_FOR_SCALAR(cube, SCALAR)                                 \
  TEST_UNARY_BUILTINS_FOR_SCALAR(inverse, SCALAR)                              \
  TEST_UNARY_BUILTINS_FOR_SCALAR(tanh, SCALAR)                                 \
  TEST_UNARY_BUILTINS_FOR_SCALAR(exp, SCALAR)                                  \
  TEST_UNARY_BUILTINS_FOR_SCALAR(log, SCALAR)                                  \
  TEST_UNARY_BUILTINS_FOR_SCALAR(abs, SCALAR)                                  \
  TEST_UNARY_BUILTINS_FOR_SCALAR(ceil, SCALAR)                                 \
  TEST_UNARY_BUILTINS_FOR_SCALAR(floor, SCALAR)                                \
  TEST_UNARY_BUILTINS_FOR_SCALAR(round, SCALAR)                                \
  TEST_UNARY_BUILTINS_FOR_SCALAR(log1p, SCALAR)

static void test_builtin_unary_sycl(const Eigen::SyclDevice &sycl_device) {
  int sizeDim1 = 100;
  int sizeDim2 = 100;
  int sizeDim3 = 100;
  array<int, 3> tensorRange = {{sizeDim1, sizeDim2, sizeDim3}};

  TEST_UNARY_BUILTINS(float)
  TEST_UNARY_BUILTINS(double)

}

void test_cxx11_tensor_builtins_sycl() {
  cl::sycl::gpu_selector s;
  Eigen::SyclDevice sycl_device(s);
  CALL_SUBTEST(test_builtin_unary_sycl(sycl_device));
}
<commit_msg>Now testing out (+=, =) in.FUNC() and out (+=, =) out.FUNC()<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2016
// Mehdi Goli    Codeplay Software Ltd.
// Ralph Potter  Codeplay Software Ltd.
// Luke Iwanski  Codeplay Software Ltd.
// Contact: <eigen@codeplay.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#define EIGEN_TEST_NO_LONGDOUBLE
#define EIGEN_TEST_NO_COMPLEX
#define EIGEN_TEST_FUNC cxx11_tensor_builtins_sycl
#define EIGEN_DEFAULT_DENSE_INDEX_TYPE int
#define EIGEN_USE_SYCL

#include "main.h"
#include <unsupported/Eigen/CXX11/Tensor>

using Eigen::array;
using Eigen::SyclDevice;
using Eigen::Tensor;
using Eigen::TensorMap;

namespace std {
template <typename T> T rsqrt(T x) { return 1 / std::sqrt(x); }
template <typename T> T square(T x) { return x * x; }
template <typename T> T cube(T x) { return x * x * x; }
template <typename T> T inverse(T x) { return 1 / x; }
}

#define TEST_UNARY_BUILTINS_FOR_SCALAR(FUNC, SCALAR, OPERATOR)                 \
  {                                                                            \
    /* out OPERATOR in.FUNC() */                                               \
    Tensor<SCALAR, 3> in(tensorRange);                                         \
    Tensor<SCALAR, 3> out(tensorRange);                                        \
    in = in.random() + static_cast<SCALAR>(0.01);                              \
    out = out.random() + static_cast<SCALAR>(0.01);                            \
    Tensor<SCALAR, 3> reference(out);                                          \
    SCALAR *gpu_data = static_cast<SCALAR *>(                                  \
        sycl_device.allocate(in.size() * sizeof(SCALAR)));                     \
    SCALAR *gpu_data_out = static_cast<SCALAR *>(                              \
        sycl_device.allocate(out.size() * sizeof(SCALAR)));                    \
    TensorMap<Tensor<SCALAR, 3>> gpu(gpu_data, tensorRange);                   \
    TensorMap<Tensor<SCALAR, 3>> gpu_out(gpu_data_out, tensorRange);           \
    sycl_device.memcpyHostToDevice(gpu_data, in.data(),                        \
                                   (in.size()) * sizeof(SCALAR));              \
    sycl_device.memcpyHostToDevice(gpu_data_out, out.data(),                   \
                                   (out.size()) * sizeof(SCALAR));             \
    gpu_out.device(sycl_device) OPERATOR gpu.FUNC();                           \
    sycl_device.memcpyDeviceToHost(out.data(), gpu_data_out,                   \
                                   (out.size()) * sizeof(SCALAR));             \
    for (int i = 0; i < out.size(); ++i) {                                     \
      SCALAR ver = reference(i);                                               \
      ver OPERATOR std::FUNC(in(i));                                           \
      VERIFY_IS_APPROX(out(i), ver);                                           \
    }                                                                          \
    sycl_device.deallocate(gpu_data);                                          \
    sycl_device.deallocate(gpu_data_out);                                      \
  }                                                                            \
  {                                                                            \
    /* out OPERATOR out.FUNC() */                                              \
    Tensor<SCALAR, 3> out(tensorRange);                                        \
    out = out.random() + static_cast<SCALAR>(0.01);                            \
    Tensor<SCALAR, 3> reference(out);                                          \
    SCALAR *gpu_data_out = static_cast<SCALAR *>(                              \
        sycl_device.allocate(out.size() * sizeof(SCALAR)));                    \
    TensorMap<Tensor<SCALAR, 3>> gpu_out(gpu_data_out, tensorRange);           \
    sycl_device.memcpyHostToDevice(gpu_data_out, out.data(),                   \
                                   (out.size()) * sizeof(SCALAR));             \
    gpu_out.device(sycl_device) OPERATOR gpu_out.FUNC();                       \
    sycl_device.memcpyDeviceToHost(out.data(), gpu_data_out,                   \
                                   (out.size()) * sizeof(SCALAR));             \
    for (int i = 0; i < out.size(); ++i) {                                     \
      SCALAR ver = reference(i);                                               \
      ver OPERATOR std::FUNC(reference(i));                                    \
      VERIFY_IS_APPROX(out(i), ver);                                           \
    }                                                                          \
    sycl_device.deallocate(gpu_data_out);                                      \
  }

#define TEST_UNARY_BUILTINS_OPERATOR(SCALAR, OPERATOR)                         \
  TEST_UNARY_BUILTINS_FOR_SCALAR(abs, SCALAR, OPERATOR)                        \
  TEST_UNARY_BUILTINS_FOR_SCALAR(sqrt, SCALAR, OPERATOR)                       \
  TEST_UNARY_BUILTINS_FOR_SCALAR(rsqrt, SCALAR, OPERATOR)                      \
  TEST_UNARY_BUILTINS_FOR_SCALAR(square, SCALAR, OPERATOR)                     \
  TEST_UNARY_BUILTINS_FOR_SCALAR(cube, SCALAR, OPERATOR)                       \
  TEST_UNARY_BUILTINS_FOR_SCALAR(inverse, SCALAR, OPERATOR)                    \
  TEST_UNARY_BUILTINS_FOR_SCALAR(tanh, SCALAR, OPERATOR)                       \
  TEST_UNARY_BUILTINS_FOR_SCALAR(exp, SCALAR, OPERATOR)                        \
  TEST_UNARY_BUILTINS_FOR_SCALAR(log, SCALAR, OPERATOR)                        \
  TEST_UNARY_BUILTINS_FOR_SCALAR(abs, SCALAR, OPERATOR)                        \
  TEST_UNARY_BUILTINS_FOR_SCALAR(ceil, SCALAR, OPERATOR)                       \
  TEST_UNARY_BUILTINS_FOR_SCALAR(floor, SCALAR, OPERATOR)                      \
  TEST_UNARY_BUILTINS_FOR_SCALAR(round, SCALAR, OPERATOR)                      \
  TEST_UNARY_BUILTINS_FOR_SCALAR(log1p, SCALAR, OPERATOR)

#define TEST_UNARY_BUILTINS(SCALAR)                                            \
  TEST_UNARY_BUILTINS_OPERATOR(SCALAR, += )                                    \
  TEST_UNARY_BUILTINS_OPERATOR(SCALAR, = )

static void test_builtin_unary_sycl(const Eigen::SyclDevice &sycl_device) {
  int sizeDim1 = 10;
  int sizeDim2 = 10;
  int sizeDim3 = 10;
  array<int, 3> tensorRange = {{sizeDim1, sizeDim2, sizeDim3}};

  TEST_UNARY_BUILTINS(float)
  TEST_UNARY_BUILTINS(double)
}

void test_cxx11_tensor_builtins_sycl() {
  cl::sycl::gpu_selector s;
  Eigen::SyclDevice sycl_device(s);
  CALL_SUBTEST(test_builtin_unary_sycl(sycl_device));
}
<|endoftext|>


<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <common/config.h>

#if VSNRAY_COMMON_HAVE_PTEX

#include <visionaray/kernels.h> // make_kernel_params()

#include <common/ptex.h>

#include "render.h"

namespace visionaray
{

void render_instances_ptex_cpp(
        index_bvh<index_bvh<basic_triangle<3, float>>::bvh_inst>& bvh,
        aligned_vector<vec3> const&                               geometric_normals,
        aligned_vector<vec3> const&                               shading_normals,
        aligned_vector<ptex::face_id_t> const&                    face_ids,
        aligned_vector<generic_material_t> const&                 materials,
        aligned_vector<ptex::texture> const&                      textures,
        aligned_vector<generic_light_t> const&                    lights,
        unsigned                                                  bounces,
        float                                                     epsilon,
        vec4                                                      bgcolor,
        vec4                                                      ambient,
        host_device_rt&                                           rt,
        host_sched_t<ray_type_cpu>&                               sched,
        camera_t const&                                           cam,
        unsigned&                                                 frame_num,
        algorithm                                                 algo,
        unsigned                                                  ssaa_samples
        )
{
    using bvh_ref = index_bvh<index_bvh<basic_triangle<3, float>>::bvh_inst>::bvh_ref;

    aligned_vector<bvh_ref> primitives;

    primitives.push_back(bvh.ref());

    auto kparams = make_kernel_params(
            normals_per_face_binding{},
            primitives.data(),
            primitives.data() + primitives.size(),
            geometric_normals.data(),
            face_ids.data(),
            materials.data(),
            textures.begin(),
            lights.data(),
            lights.data() + lights.size(),
            bounces,
            epsilon,
            bgcolor,
            ambient
            );

    call_kernel( algo, sched, kparams, frame_num, ssaa_samples, cam, rt );
}

} // visionaray

#endif // VSNRAY_COMMON_HAVE_PTEX
<commit_msg>Moana model also has shading normals<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <common/config.h>

#if VSNRAY_COMMON_HAVE_PTEX

#include <visionaray/kernels.h> // make_kernel_params()

#include <common/ptex.h>

#include "render.h"

namespace visionaray
{

void render_instances_ptex_cpp(
        index_bvh<index_bvh<basic_triangle<3, float>>::bvh_inst>& bvh,
        aligned_vector<vec3> const&                               geometric_normals,
        aligned_vector<vec3> const&                               shading_normals,
        aligned_vector<ptex::face_id_t> const&                    face_ids,
        aligned_vector<generic_material_t> const&                 materials,
        aligned_vector<ptex::texture> const&                      textures,
        aligned_vector<generic_light_t> const&                    lights,
        unsigned                                                  bounces,
        float                                                     epsilon,
        vec4                                                      bgcolor,
        vec4                                                      ambient,
        host_device_rt&                                           rt,
        host_sched_t<ray_type_cpu>&                               sched,
        camera_t const&                                           cam,
        unsigned&                                                 frame_num,
        algorithm                                                 algo,
        unsigned                                                  ssaa_samples
        )
{
    using bvh_ref = index_bvh<index_bvh<basic_triangle<3, float>>::bvh_inst>::bvh_ref;

    aligned_vector<bvh_ref> primitives;

    primitives.push_back(bvh.ref());

    auto kparams = make_kernel_params(
            normals_per_vertex_binding{},
            primitives.data(),
            primitives.data() + primitives.size(),
            shading_normals.data(),
            face_ids.data(),
            materials.data(),
            textures.begin(),
            lights.data(),
            lights.data() + lights.size(),
            bounces,
            epsilon,
            bgcolor,
            ambient
            );

    call_kernel( algo, sched, kparams, frame_num, ssaa_samples, cam, rt );
}

} // visionaray

#endif // VSNRAY_COMMON_HAVE_PTEX
<|endoftext|>