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

#include "maemomanager.h"
#include "qtversionmanager.h"

#include "maemodeviceconfigurations.h"
#include "maemopackagecreationfactory.h"
#include "maemorunfactories.h"
#include "maemosettingspage.h"
#include "maemotoolchain.h"
#include "maemorunconfiguration.h"

#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <coreplugin/modemanager.h>
#include <extensionsystem/pluginmanager.h>

#include <coreplugin/actionmanager/command.h>

#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QList>
#include <QtCore/QTextStream>

#include <QtGui/QAction>

namespace Qt4ProjectManager {
    namespace Internal {

MaemoManager *MaemoManager::m_instance = 0;

const QSize iconSize = QSize(24, 20);

MaemoManager::MaemoManager()
    : QObject(0)
    , m_runControlFactory(new MaemoRunControlFactory(this))
    , m_runConfigurationFactory(new MaemoRunConfigurationFactory(this))
    , m_packageCreationFactory(new MaemoPackageCreationFactory(this))
    , m_settingsPage(new MaemoSettingsPage(this))
    , m_qemuCommand(0)
{
    Q_ASSERT(!m_instance);

    m_instance = this;
    MaemoDeviceConfigurations::instance(this);

    icon.addFile(":/qt-maemo/images/qemu-run.png", iconSize);
    icon.addFile(":/qt-maemo/images/qemu-stop.png", iconSize, QIcon::Normal,
        QIcon::On);

    ExtensionSystem::PluginManager *pluginManager
        = ExtensionSystem::PluginManager::instance();
    pluginManager->addObject(m_runControlFactory);
    pluginManager->addObject(m_runConfigurationFactory);
    pluginManager->addObject(m_packageCreationFactory);
    pluginManager->addObject(m_settingsPage);
}

MaemoManager::~MaemoManager()
{
    ExtensionSystem::PluginManager *pluginManager
        = ExtensionSystem::PluginManager::instance();
    pluginManager->removeObject(m_runControlFactory);
    pluginManager->removeObject(m_runConfigurationFactory);
    pluginManager->removeObject(m_packageCreationFactory);
    pluginManager->removeObject(m_settingsPage);

    m_instance = 0;
}

MaemoManager &MaemoManager::instance()
{
    Q_ASSERT(m_instance);
    return *m_instance;
}

bool
MaemoManager::isValidMaemoQtVersion(const Qt4ProjectManager::QtVersion *version) const
{
    QString path = QDir::cleanPath(version->qmakeCommand());
    path = path.remove(QLatin1String("/bin/qmake" EXEC_SUFFIX));

    QDir dir(path);
    dir.cdUp(); dir.cdUp();

    QFile file(dir.absolutePath() + QLatin1String("/cache/madde.conf"));
    if (file.exists() && file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        const QString &target = path.mid(path.lastIndexOf(QLatin1Char('/')) + 1);
        QTextStream stream(&file);
        while (!stream.atEnd()) {
            const QString &line = stream.readLine().trimmed();
            if (line.startsWith(QLatin1String("target"))
                && line.endsWith(target)) {
                    return true;
            }
        }
    }
    return false;
}

ProjectExplorer::ToolChain*
MaemoManager::maemoToolChain(const QtVersion *version) const
{
    QString targetRoot = QDir::cleanPath(version->qmakeCommand());
    targetRoot.remove(QLatin1String("/bin/qmake" EXEC_SUFFIX));
    return new MaemoToolChain(targetRoot);
}

void
MaemoManager::addQemuSimulatorStarter(Project *project)
{
    if (projects.contains(project))
        return;

    projects.insert(project);

    if (m_qemuCommand) {
        m_qemuCommand->action()->setVisible(true);
        return;
    }

    Core::ICore *core = Core::ICore::instance();
    Core::ModeManager *modeManager = core->modeManager();
    Core::ActionManager *actionManager = core->actionManager();

    QAction *action = new QAction("Maemo Emulator", this);
    action->setIcon(icon.pixmap(iconSize));
    action->setToolTip(tr("Start Maemo Emulator"));
    m_qemuCommand = actionManager->registerAction(action, "MaemoEmulator",
        QList<int>() << Core::Constants::C_GLOBAL_ID);
    modeManager->addAction(m_qemuCommand, 1);
    m_qemuCommand->action()->setEnabled(false);
    m_qemuCommand->setAttribute(Core::Command::CA_UpdateText);
    m_qemuCommand->setAttribute(Core::Command::CA_UpdateIcon);

    connect(m_qemuCommand->action(), SIGNAL(triggered()), this, SLOT(triggered()));
}

void
MaemoManager::removeQemuSimulatorStarter(Project *project)
{
    if (projects.contains(project)) {
        projects.remove(project);
        if (projects.isEmpty() && m_qemuCommand)
            m_qemuCommand->action()->setVisible(false);
    }
}

void
MaemoManager::setQemuSimulatorStarterEnabled(bool enable)
{
    if (m_qemuCommand)
        m_qemuCommand->action()->setEnabled(enable);
}

void
MaemoManager::triggered()
{
    emit startStopQemu();
}

void
MaemoManager::updateQemuSimulatorStarter(bool running)
{
    if (m_qemuCommand) {
        QIcon::State state = QIcon::Off;
        QString toolTip(tr("Start Maemo Emulator"));
        if (running) {
            state = QIcon::On;
            toolTip = tr("Stop Maemo Emulator");
        }

        QAction *action = m_qemuCommand->action();
        action->setToolTip(toolTip);
        action->setIcon(icon.pixmap(iconSize, QIcon::Normal, state));
    }
}

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

#include "maemomanager.h"
#include "qtversionmanager.h"

#include "maemodeviceconfigurations.h"
#include "maemopackagecreationfactory.h"
#include "maemorunfactories.h"
#include "maemosettingspage.h"
#include "maemotoolchain.h"
#include "maemorunconfiguration.h"

#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <coreplugin/modemanager.h>
#include <extensionsystem/pluginmanager.h>

#include <coreplugin/actionmanager/command.h>

#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QList>
#include <QtCore/QTextStream>

#include <QtGui/QAction>

namespace Qt4ProjectManager {
    namespace Internal {

MaemoManager *MaemoManager::m_instance = 0;

const QSize iconSize = QSize(24, 20);

MaemoManager::MaemoManager()
    : QObject(0)
    , m_runControlFactory(new MaemoRunControlFactory(this))
    , m_runConfigurationFactory(new MaemoRunConfigurationFactory(this))
    , m_packageCreationFactory(new MaemoPackageCreationFactory(this))
    , m_settingsPage(new MaemoSettingsPage(this))
    , m_qemuCommand(0)
{
    Q_ASSERT(!m_instance);

    m_instance = this;
    MaemoDeviceConfigurations::instance(this);

    icon.addFile(":/qt-maemo/images/qemu-run.png", iconSize);
    icon.addFile(":/qt-maemo/images/qemu-stop.png", iconSize, QIcon::Normal,
        QIcon::On);

    ExtensionSystem::PluginManager *pluginManager
        = ExtensionSystem::PluginManager::instance();
    pluginManager->addObject(m_runControlFactory);
    pluginManager->addObject(m_runConfigurationFactory);
    pluginManager->addObject(m_packageCreationFactory);
    pluginManager->addObject(m_settingsPage);
}

MaemoManager::~MaemoManager()
{
    ExtensionSystem::PluginManager *pluginManager
        = ExtensionSystem::PluginManager::instance();
    pluginManager->removeObject(m_runControlFactory);
    pluginManager->removeObject(m_runConfigurationFactory);
    pluginManager->removeObject(m_packageCreationFactory);
    pluginManager->removeObject(m_settingsPage);

    m_instance = 0;
}

MaemoManager &MaemoManager::instance()
{
    Q_ASSERT(m_instance);
    return *m_instance;
}

bool
MaemoManager::isValidMaemoQtVersion(const Qt4ProjectManager::QtVersion *version) const
{
    QString path = QDir::cleanPath(version->qmakeCommand());
    path = path.remove(QLatin1String("/bin/qmake" EXEC_SUFFIX));

    QDir dir(path);
    dir.cdUp(); dir.cdUp();

    QFile file(dir.absolutePath() + QLatin1String("/cache/madde.conf"));
    if (file.exists() && file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        const QString &target = path.mid(path.lastIndexOf(QLatin1Char('/')) + 1);
        QTextStream stream(&file);
        while (!stream.atEnd()) {
            const QString &line = stream.readLine().trimmed();
            if (line.startsWith(QLatin1String("target"))
                && line.endsWith(target)) {
                    return true;
            }
        }
    }
    return false;
}

ProjectExplorer::ToolChain*
MaemoManager::maemoToolChain(const QtVersion *version) const
{
    QString targetRoot = QDir::cleanPath(version->qmakeCommand());
    targetRoot.remove(QLatin1String("/bin/qmake" EXEC_SUFFIX));
    return new MaemoToolChain(targetRoot);
}

void
MaemoManager::addQemuSimulatorStarter(Project *project)
{
    if (projects.contains(project))
        return;

    projects.insert(project);

    if (m_qemuCommand) {
        m_qemuCommand->action()->setVisible(true);
        return;
    }

    Core::ICore *core = Core::ICore::instance();
    Core::ModeManager *modeManager = core->modeManager();
    Core::ActionManager *actionManager = core->actionManager();

    QAction *action = new QAction("Maemo Emulator", this);
    action->setIcon(icon.pixmap(iconSize));
    action->setToolTip(tr("Start Maemo Emulator"));
    m_qemuCommand = actionManager->registerAction(action, "MaemoEmulator",
        QList<int>() << Core::Constants::C_GLOBAL_ID);
    modeManager->addAction(m_qemuCommand, 1);
    action->setEnabled(false);
    m_qemuCommand->action()->setEnabled(false);
    m_qemuCommand->setAttribute(Core::Command::CA_UpdateText);
    m_qemuCommand->setAttribute(Core::Command::CA_UpdateIcon);

    connect(m_qemuCommand->action(), SIGNAL(triggered()), this, SLOT(triggered()));
}

void
MaemoManager::removeQemuSimulatorStarter(Project *project)
{
    if (projects.contains(project)) {
        projects.remove(project);
        if (projects.isEmpty() && m_qemuCommand)
            m_qemuCommand->action()->setVisible(false);
    }
}

void
MaemoManager::setQemuSimulatorStarterEnabled(bool enable)
{
    if (m_qemuCommand)
        m_qemuCommand->action()->setEnabled(enable);
}

void
MaemoManager::triggered()
{
    emit startStopQemu();
}

void
MaemoManager::updateQemuSimulatorStarter(bool running)
{
    if (m_qemuCommand) {
        QIcon::State state = QIcon::Off;
        QString toolTip(tr("Start Maemo Emulator"));
        if (running) {
            state = QIcon::On;
            toolTip = tr("Stop Maemo Emulator");
        }

        QAction *action = m_qemuCommand->action();
        action->setToolTip(toolTip);
        action->setIcon(icon.pixmap(iconSize, QIcon::Normal, state));
    }
}

    } // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|>


<commit_before>#pragma once

#include "Runtime/RetroTypes.hpp"
#include "Runtime/Weapon/CWeaponMode.hpp"

namespace urde {

enum class EVulnerability { Weak, Normal, Deflect, Immune, PassThrough, DirectWeak, DirectNormal, DirectImmune };
enum class EDeflectType { None, One, Two, Three, Four };

class CDamageVulnerability {
  EVulnerability x0_power;
  EVulnerability x4_ice;
  EVulnerability x8_wave;
  EVulnerability xc_plasma;
  EVulnerability x10_bomb;
  EVulnerability x14_powerbomb;
  EVulnerability x18_missile;
  EVulnerability x1c_boostBall;
  EVulnerability x20_phazon;
  EVulnerability x24_enemyWp1;
  EVulnerability x28_enemyWp2Poison;
  EVulnerability x2c_enemyWp3Lava;
  EVulnerability x30_enemyWp4;
  EVulnerability x34_unk1;
  EVulnerability x38_unk2;

  EVulnerability x3c_chargedPower;
  EVulnerability x40_chargedIce;
  EVulnerability x44_chargedWave;
  EVulnerability x48_chargedPlasma;

  EVulnerability x4c_superMissile;
  EVulnerability x50_iceSpreader;
  EVulnerability x54_wavebuster;
  EVulnerability x58_flamethrower;

  EDeflectType x5c_deflected;
  EDeflectType x60_chargedDeflected;
  EDeflectType x64_comboDeflected;

  void ConstructNew(CInputStream& in, int propCount);

  static const CDamageVulnerability sNormalVulnerability;
  static const CDamageVulnerability sImmuneVulnerability;
  static const CDamageVulnerability sReflectVulnerability;
  static const CDamageVulnerability sPassThroughVulnerability;

public:
  explicit CDamageVulnerability(CInputStream& in);
  CDamageVulnerability(EVulnerability power, EVulnerability ice, EVulnerability wave, EVulnerability plasma,
                       EVulnerability bomb, EVulnerability powerBomb, EVulnerability missile, EVulnerability boostBall,
                       EVulnerability phazon, EVulnerability enemyWp1, EVulnerability wnemyWp2, EVulnerability enemyWp3,
                       EVulnerability enemyWp4, EVulnerability v1, EVulnerability v2, EDeflectType deflectType);
  CDamageVulnerability(EVulnerability power, EVulnerability ice, EVulnerability wave, EVulnerability plasma,
                       EVulnerability bomb, EVulnerability powerBomb, EVulnerability missile, EVulnerability boostBall,
                       EVulnerability phazon, EVulnerability enemyWp1, EVulnerability enemyWp2, EVulnerability enemyWp3,
                       EVulnerability enemyWp4, EVulnerability v1, EVulnerability v2, EVulnerability chargedPower,
                       EVulnerability chargedIce, EVulnerability chargedWave, EVulnerability chargedPlasma,
                       EVulnerability superMissile, EVulnerability iceSpreader, EVulnerability waveBuster,
                       EVulnerability flameThrower, EDeflectType deflected);

  EDeflectType GetDeflectionType(const CWeaponMode& mode) const;

  bool WeaponHurts(const CWeaponMode&, bool ignoreDirect) const;
  bool WeaponHits(const CWeaponMode& mode, bool checkDirect) const;
  EVulnerability GetVulnerability(const CWeaponMode& mode, bool ignoreDirect) const;

  static const CDamageVulnerability& NormalVulnerabilty() { return sNormalVulnerability; }
  static const CDamageVulnerability& ImmuneVulnerabilty() { return sImmuneVulnerability; }
  static const CDamageVulnerability& ReflectVulnerabilty() { return sReflectVulnerability; }
  static const CDamageVulnerability& PassThroughVulnerabilty() { return sPassThroughVulnerability; }
};
} // namespace urde
<commit_msg>CDamageVulnerability: Amend typo in parameter name<commit_after>#pragma once

#include "Runtime/RetroTypes.hpp"
#include "Runtime/Weapon/CWeaponMode.hpp"

namespace urde {

enum class EVulnerability { Weak, Normal, Deflect, Immune, PassThrough, DirectWeak, DirectNormal, DirectImmune };
enum class EDeflectType { None, One, Two, Three, Four };

class CDamageVulnerability {
  EVulnerability x0_power;
  EVulnerability x4_ice;
  EVulnerability x8_wave;
  EVulnerability xc_plasma;
  EVulnerability x10_bomb;
  EVulnerability x14_powerbomb;
  EVulnerability x18_missile;
  EVulnerability x1c_boostBall;
  EVulnerability x20_phazon;
  EVulnerability x24_enemyWp1;
  EVulnerability x28_enemyWp2Poison;
  EVulnerability x2c_enemyWp3Lava;
  EVulnerability x30_enemyWp4;
  EVulnerability x34_unk1;
  EVulnerability x38_unk2;

  EVulnerability x3c_chargedPower;
  EVulnerability x40_chargedIce;
  EVulnerability x44_chargedWave;
  EVulnerability x48_chargedPlasma;

  EVulnerability x4c_superMissile;
  EVulnerability x50_iceSpreader;
  EVulnerability x54_wavebuster;
  EVulnerability x58_flamethrower;

  EDeflectType x5c_deflected;
  EDeflectType x60_chargedDeflected;
  EDeflectType x64_comboDeflected;

  void ConstructNew(CInputStream& in, int propCount);

  static const CDamageVulnerability sNormalVulnerability;
  static const CDamageVulnerability sImmuneVulnerability;
  static const CDamageVulnerability sReflectVulnerability;
  static const CDamageVulnerability sPassThroughVulnerability;

public:
  explicit CDamageVulnerability(CInputStream& in);
  CDamageVulnerability(EVulnerability power, EVulnerability ice, EVulnerability wave, EVulnerability plasma,
                       EVulnerability bomb, EVulnerability powerBomb, EVulnerability missile, EVulnerability boostBall,
                       EVulnerability phazon, EVulnerability enemyWp1, EVulnerability enemyWp2, EVulnerability enemyWp3,
                       EVulnerability enemyWp4, EVulnerability v1, EVulnerability v2, EDeflectType deflectType);
  CDamageVulnerability(EVulnerability power, EVulnerability ice, EVulnerability wave, EVulnerability plasma,
                       EVulnerability bomb, EVulnerability powerBomb, EVulnerability missile, EVulnerability boostBall,
                       EVulnerability phazon, EVulnerability enemyWp1, EVulnerability enemyWp2, EVulnerability enemyWp3,
                       EVulnerability enemyWp4, EVulnerability v1, EVulnerability v2, EVulnerability chargedPower,
                       EVulnerability chargedIce, EVulnerability chargedWave, EVulnerability chargedPlasma,
                       EVulnerability superMissile, EVulnerability iceSpreader, EVulnerability waveBuster,
                       EVulnerability flameThrower, EDeflectType deflected);

  EDeflectType GetDeflectionType(const CWeaponMode& mode) const;

  bool WeaponHurts(const CWeaponMode&, bool ignoreDirect) const;
  bool WeaponHits(const CWeaponMode& mode, bool checkDirect) const;
  EVulnerability GetVulnerability(const CWeaponMode& mode, bool ignoreDirect) const;

  static const CDamageVulnerability& NormalVulnerabilty() { return sNormalVulnerability; }
  static const CDamageVulnerability& ImmuneVulnerabilty() { return sImmuneVulnerability; }
  static const CDamageVulnerability& ReflectVulnerabilty() { return sReflectVulnerability; }
  static const CDamageVulnerability& PassThroughVulnerabilty() { return sPassThroughVulnerability; }
};
} // namespace urde
<|endoftext|>


<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011 Niko Sams <niko.sams@gmail.com>
//

#include "AltitudeProfile.h"
#include <GeoPainter.h>
#include <GeoSceneLayer.h>
#include <ViewportParams.h>
#include <routing/RoutingManager.h>
#include <routing/AlternativeRoutesModel.h>
#include <GeoDataDocument.h>
#include <MarbleDebug.h>
#include <KPlotObject>
#include <KPlotAxis>
#include <AltitudeModel.h>
#include <MarbleModel.h>
#include <GeoDataParser.h>
#include <QFile>

#include "MarbleGraphicsGridLayout.h"
#include "WidgetGraphicsItem.h"
#include "PlotWidget.h"
#include <QLabel>
#include <QLayout>
#include <GeoDataFolder.h>
#include <MarbleWidget.h>
#include "PlotPoint.h"
#include <QApplication>
#include <LabelGraphicsItem.h>

using namespace Marble;

AltitudeProfile::AltitudeProfile(const QPointF& point, const QSizeF& size)
    : AbstractFloatItem( point, size ), m_isInitialized( false ), m_marbleWidget( 0 )
{
    m_label = new LabelGraphicsItem( &m_labelContainer );
    m_label->setFrame( FrameGraphicsItem::RoundedRectFrame );

    MarbleGraphicsGridLayout *topLayout = new MarbleGraphicsGridLayout( 1, 1 );
    m_labelContainer.setLayout( topLayout );
    topLayout->addItem( m_label, 0, 0 );

}

QStringList AltitudeProfile::backendTypes() const
{
    return QStringList( "altitudeProfile" );
}

QStringList AltitudeProfile::renderPosition() const
{
    return QStringList() << "FLOAT_ITEM" << "HOVERS_ABOVE_SURFACE";
}

qreal AltitudeProfile::zValue() const
{
    return 1.0;
}

bool AltitudeProfile::renderOnMap( GeoPainter     *painter,
                                     ViewportParams *viewport,
                                     const QString  &renderPos,
                                     GeoSceneLayer  *layer )
{
    if ( renderPos == "HOVERS_ABOVE_SURFACE" )
    {
/*
        painter->save();
        painter->autoMapQuality();

        PlotPoint* hightlightedPoint = m_graph->highlightedPoint();
        if ( hightlightedPoint ) {
            QString text = QString::number( hightlightedPoint->coordinates().altitude() ) + "m";
            QRect textRect = painter->fontMetrics().boundingRect( text );

            painter->setBrush( QApplication::palette().toolTipBase() );
            painter->drawRect( hightlightedPoint->coordinates(), textRect.width(), textRect.height(), false );
            painter->viewport();
            painter->setPen( QApplication::palette().toolTipText().color() );
            painter->drawText( hightlightedPoint->coordinates(), text );

            painter->setPen( QPen( Qt::red, 5, Qt::SolidLine, Qt::RoundCap ) );
            painter->drawPoint( hightlightedPoint->coordinates() );

        }
        painter->restore();
*/
        m_labelContainer.paintEvent( painter, viewport, renderPos, layer );
    }
    return true;
}

bool AltitudeProfile::isInitialized() const
{
    return m_isInitialized;
}

void AltitudeProfile::initialize()
{
    m_isInitialized = true;

    m_graph = new PlotWidget( this );
    m_graph->setAntialiasing( true );
    m_graph->axis( KPlotWidget::TopAxis )->setVisible( false );
    m_graph->axis( KPlotWidget::RightAxis )->setVisible( false );
    m_graph->resetPlot();
    //m_graph->axis( KPlotWidget::LeftAxis )->setLabel( QString() );
    //m_graph->axis( KPlotWidget::LeftAxis )->setLabel(tr("Altitude"));
    m_graph->axis( KPlotWidget::BottomAxis )->setTickLabelsShown(false);

    m_plot = new KPlotObject(Qt::red, KPlotObject::Lines, 3);
    m_graph->addPlotObject(m_plot);
    m_graph->setMaximumSize( QSize( 300, 100 ) );
    m_graph->setMinimumSize( QSize( 300, 100 ) );

    m_stats = new QLabel("Stats");
    QWidget *w = new QWidget();
    w->setMaximumSize( QSize( 400, 100 ) );
    w->setMinimumSize( QSize( 400, 100 ) );
    QHBoxLayout* l = new QHBoxLayout;
    w->setLayout( l );
    l->addWidget( m_graph, 3 );
    l->addWidget( m_stats, 1 );

    m_widgetItem = new WidgetGraphicsItem( this );
    m_widgetItem->setWidget( w );

    MarbleGraphicsGridLayout *layout = new MarbleGraphicsGridLayout( 1, 1 );
    layout->addItem( m_widgetItem, 0, 0 );

    setLayout( layout );

    currentRouteChanged( marbleModel()->routingManager()->alternativeRoutesModel()->currentRoute() );
    connect( marbleModel()->routingManager()->alternativeRoutesModel(), SIGNAL( currentRouteChanged( GeoDataDocument* ) ), SLOT( currentRouteChanged( GeoDataDocument* ) ) );

    connect( marbleModel()->altitudeModel(), SIGNAL( loadCompleted() ), SLOT( altitudeDataLoadCompleted() ) );

#if 0
    GeoDataParser parser( GeoData_UNKNOWN );

    QFile file( "/home/niko/tracks/2011-06-12-mattighofen.gpx" );
    file.open( QIODevice::ReadOnly );
    Q_ASSERT( parser.read( &file ) );
    GeoDataDocument* document = static_cast<GeoDataDocument*>( parser.releaseDocument() );
    Q_ASSERT( document );
    file.close();
    GeoDataPlacemark* routePlacemark = document->placemarkList().first();
    qDebug() << routePlacemark->geometry()->geometryId();
    Q_ASSERT(routePlacemark->geometry()->geometryId() ==  GeoDataMultiGeometryId);
    GeoDataMultiGeometry* routeWaypoints = static_cast<GeoDataMultiGeometry*>(routePlacemark->geometry());
    qDebug() << "size" << routeWaypoints->size(); // << "length" << routeWaypoints->length( EARTH_RADIUS );
    for(int i=0; i < routeWaypoints->size(); ++i) {
        GeoDataGeometry* route2 = routeWaypoints->child(i);
        qDebug() << "route2.geometryId" << route2->geometryId();
        Q_ASSERT(route2->geometryId() == GeoDataLineStringId);
        GeoDataLineString* routeWaypoints2 = static_cast<GeoDataLineString*>(route2);
        qDebug() << "size" << routeWaypoints2->size() << "length" << routeWaypoints2->length(EARTH_RADIUS);
        qreal previousAlt = 0;
        qreal totalIncrease = 0;
        for(int j=0; j< routeWaypoints2->size(); ++j) {
            GeoDataCoordinates coordinate = routeWaypoints2->at( j );
            qDebug() << coordinate.latitude(Marble::GeoDataCoordinates::Degree) << coordinate.longitude(Marble::GeoDataCoordinates::Degree) << coordinate.altitude();
            if (previousAlt && coordinate.altitude() > previousAlt) {
                totalIncrease += coordinate.altitude() - previousAlt;
            }
            previousAlt = coordinate.altitude();
        }
        qDebug() << "totalIncrease" << totalIncrease << "vs. 254m von garmin gemessen";
    }
#endif
}

void AltitudeProfile::altitudeDataLoadCompleted()
{
    currentRouteChanged( marbleModel()->routingManager()->alternativeRoutesModel()->currentRoute() );
}

void AltitudeProfile::currentRouteChanged( GeoDataDocument* route )
{
    m_graph->clearHighligtedPoint();
    m_plot->clearPoints();
    m_stats->setText( QString() );

    if (!route) return;

    qint32 minY = INT_MAX;
    qint32 maxY = 0;
    quint32 numDataPoints = 0;
    qDebug() << "*************************";

    GeoDataPlacemark* routePlacemark = 0;
    Q_ASSERT(route->size());
    if ( !route->placemarkList().count() ) {
        qDebug() << "no placemarks found?!";
        for(int i=0; i<route->size(); ++i) {
            qDebug() << "nodeType" << i << route->child( i )->nodeType();
            if ( dynamic_cast<GeoDataFolder*>( route->child( i ) ) ) {
                Q_ASSERT( static_cast<GeoDataFolder*>( route->child( i ) )->placemarkList().size() );
                routePlacemark = static_cast<GeoDataFolder*>( route->child( i ) )->placemarkList().first();
            }
        }
    } else {
        routePlacemark = route->placemarkList().first();
    }
    Q_ASSERT(routePlacemark);
    Q_ASSERT(routePlacemark->geometry()->geometryId() ==  GeoDataLineStringId);
    GeoDataLineString* routeWaypoints = static_cast<GeoDataLineString*>(routePlacemark->geometry());
    //qDebug() << routeWaypoints->length( EARTH_RADIUS );
    qreal totalIncrease = 0;
    qreal totalIncreaseAvg = 0;
    qreal totalDecreaseAvg = 0;
    qreal lastAltitude = -100000;
    qreal lastAvgAltitude = -100000;
    QList<GeoDataCoordinates> allAltitudes;
    for(int i=1; i < routeWaypoints->size(); ++i) {
        GeoDataCoordinates coordinate = routeWaypoints->at( i );
        GeoDataCoordinates coordinatePrev = routeWaypoints->at( i - 1 );
        //qreal altitude = marbleModel()->altitudeModel()->height(coordinate.latitude(Marble::GeoDataCoordinates::Degree), coordinate.longitude(Marble::GeoDataCoordinates::Degree));
        QList<GeoDataCoordinates> coordinatesList = marbleModel()->altitudeModel()->heightProfile(
            coordinatePrev.latitude(Marble::GeoDataCoordinates::Degree),
            coordinatePrev.longitude(Marble::GeoDataCoordinates::Degree),
            coordinate.latitude(Marble::GeoDataCoordinates::Degree),
            coordinate.longitude(Marble::GeoDataCoordinates::Degree)
        );
        foreach(const GeoDataCoordinates &coord, coordinatesList) {
            //qDebug() << "POINT" << numDataPoints << coordinate.longitude(Marble::GeoDataCoordinates::Degree) << coordinate.latitude(Marble::GeoDataCoordinates::Degree)
            //        << "height" << altitude;
            allAltitudes << coord;
            if ( allAltitudes.count() >= 10 ) {
                qreal avgAltitude = 0;
                for( int j=0; j<10; ++j ) {
                    avgAltitude += allAltitudes.at( allAltitudes.count()-j-1 ).altitude();
                }
                avgAltitude = avgAltitude / 10;
                if (lastAvgAltitude != -100000 && avgAltitude > lastAvgAltitude) {
                    totalIncreaseAvg += avgAltitude-lastAvgAltitude;
                }
                if (lastAvgAltitude != -100000 && avgAltitude < lastAvgAltitude) {
                    totalDecreaseAvg -= avgAltitude-lastAvgAltitude;
                }
                lastAvgAltitude = avgAltitude;
            }
            if ( lastAltitude != -100000 && coord.altitude() > lastAltitude ) {
                totalIncrease += coord.altitude() - lastAltitude;
                //qDebug() << "INCREASE +=" << altitude - lastAltitude << "totalIncrease is now" << totalIncrease;
            }

            double value = coord.altitude();
            //qDebug() << "value" << value;
            m_plot->addPoint(new PlotPoint( numDataPoints++, value, coord ));
            if (value > maxY) maxY = value;
            if (value < minY) minY = value;
            lastAltitude = coord.altitude();
        }
    }
    //qDebug() << "TOTAL INCREASE" << totalIncrease;
    //qDebug() << "TOTAL INCREASE AVG" << totalIncreaseAvg;

    m_graph->setLimits( 0, numDataPoints, minY - minY / 5, maxY + maxY / 5 );

    m_stats->setText( tr( "Gain:
%0m
Loss:
%1m" ).arg( totalIncreaseAvg ).arg( totalDecreaseAvg ) );

    forceUpdate();
}

void AltitudeProfile::forceUpdate()
{
    PlotPoint* hightlightedPoint = m_graph->highlightedPoint();
    if ( hightlightedPoint ) {
        m_labelContainer.show();
        m_labelContainer.setCoordinate( hightlightedPoint->coordinates() );
        m_label->setText( QString::number( hightlightedPoint->coordinates().altitude() ) + "m" );
    } else {
        m_labelContainer.hide();
    }
    if ( m_marbleWidget ) {
        m_marbleWidget->update();
    }
}

bool AltitudeProfile::eventFilter(QObject *object, QEvent *e)
{
    if ( !enabled() || !visible() ) {
        return false;
    }

    MarbleWidget *widget = dynamic_cast<MarbleWidget*> (object);
    if ( !m_marbleWidget ) {
        m_marbleWidget = widget;
    }

    return AbstractFloatItem::eventFilter( object, e );
}

QIcon AltitudeProfile::icon() const
{
    return QIcon();
}

QString AltitudeProfile::description() const
{
    return tr( "This is a float item that displays the altitude profile of a track." );
}

QString AltitudeProfile::nameId() const
{
    return QString( "altitudeProfile" );
}

QString AltitudeProfile::guiString() const
{
    return tr( "&Altitude Profile" );
}

QString AltitudeProfile::name() const
{
    return QString( "Altitude Profile" );
}

Q_EXPORT_PLUGIN2( AltitudeProfile, Marble::AltitudeProfile )

#include "AltitudeProfile.moc"

<commit_msg>fix compile<commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011 Niko Sams <niko.sams@gmail.com>
//

#include "AltitudeProfile.h"
#include <GeoPainter.h>
#include <GeoSceneLayer.h>
#include <ViewportParams.h>
#include <routing/RoutingManager.h>
#include <routing/AlternativeRoutesModel.h>
#include <GeoDataDocument.h>
#include <MarbleDebug.h>
#include <KPlotObject>
#include <KPlotAxis>
#include <AltitudeModel.h>
#include <MarbleModel.h>
#include <GeoDataParser.h>
#include <QFile>
#include <GeoDataPlacemark.h>

#include "MarbleGraphicsGridLayout.h"
#include "WidgetGraphicsItem.h"
#include "PlotWidget.h"
#include <QLabel>
#include <QLayout>
#include <GeoDataFolder.h>
#include <MarbleWidget.h>
#include "PlotPoint.h"
#include <QApplication>
#include <LabelGraphicsItem.h>

using namespace Marble;

AltitudeProfile::AltitudeProfile(const QPointF& point, const QSizeF& size)
    : AbstractFloatItem( point, size ), m_isInitialized( false ), m_marbleWidget( 0 )
{
    m_label = new LabelGraphicsItem( &m_labelContainer );
    m_label->setFrame( FrameGraphicsItem::RoundedRectFrame );

    MarbleGraphicsGridLayout *topLayout = new MarbleGraphicsGridLayout( 1, 1 );
    m_labelContainer.setLayout( topLayout );
    topLayout->addItem( m_label, 0, 0 );

}

QStringList AltitudeProfile::backendTypes() const
{
    return QStringList( "altitudeProfile" );
}

QStringList AltitudeProfile::renderPosition() const
{
    return QStringList() << "FLOAT_ITEM" << "HOVERS_ABOVE_SURFACE";
}

qreal AltitudeProfile::zValue() const
{
    return 1.0;
}

bool AltitudeProfile::renderOnMap( GeoPainter     *painter,
                                     ViewportParams *viewport,
                                     const QString  &renderPos,
                                     GeoSceneLayer  *layer )
{
    if ( renderPos == "HOVERS_ABOVE_SURFACE" )
    {
/*
        painter->save();
        painter->autoMapQuality();

        PlotPoint* hightlightedPoint = m_graph->highlightedPoint();
        if ( hightlightedPoint ) {
            QString text = QString::number( hightlightedPoint->coordinates().altitude() ) + "m";
            QRect textRect = painter->fontMetrics().boundingRect( text );

            painter->setBrush( QApplication::palette().toolTipBase() );
            painter->drawRect( hightlightedPoint->coordinates(), textRect.width(), textRect.height(), false );
            painter->viewport();
            painter->setPen( QApplication::palette().toolTipText().color() );
            painter->drawText( hightlightedPoint->coordinates(), text );

            painter->setPen( QPen( Qt::red, 5, Qt::SolidLine, Qt::RoundCap ) );
            painter->drawPoint( hightlightedPoint->coordinates() );

        }
        painter->restore();
*/
        m_labelContainer.paintEvent( painter, viewport, renderPos, layer );
    }
    return true;
}

bool AltitudeProfile::isInitialized() const
{
    return m_isInitialized;
}

void AltitudeProfile::initialize()
{
    m_isInitialized = true;

    m_graph = new PlotWidget( this );
    m_graph->setAntialiasing( true );
    m_graph->axis( KPlotWidget::TopAxis )->setVisible( false );
    m_graph->axis( KPlotWidget::RightAxis )->setVisible( false );
    m_graph->resetPlot();
    //m_graph->axis( KPlotWidget::LeftAxis )->setLabel( QString() );
    //m_graph->axis( KPlotWidget::LeftAxis )->setLabel(tr("Altitude"));
    m_graph->axis( KPlotWidget::BottomAxis )->setTickLabelsShown(false);

    m_plot = new KPlotObject(Qt::red, KPlotObject::Lines, 3);
    m_graph->addPlotObject(m_plot);
    m_graph->setMaximumSize( QSize( 300, 100 ) );
    m_graph->setMinimumSize( QSize( 300, 100 ) );

    m_stats = new QLabel("Stats");
    QWidget *w = new QWidget();
    w->setMaximumSize( QSize( 400, 100 ) );
    w->setMinimumSize( QSize( 400, 100 ) );
    QHBoxLayout* l = new QHBoxLayout;
    w->setLayout( l );
    l->addWidget( m_graph, 3 );
    l->addWidget( m_stats, 1 );

    m_widgetItem = new WidgetGraphicsItem( this );
    m_widgetItem->setWidget( w );

    MarbleGraphicsGridLayout *layout = new MarbleGraphicsGridLayout( 1, 1 );
    layout->addItem( m_widgetItem, 0, 0 );

    setLayout( layout );

    currentRouteChanged( marbleModel()->routingManager()->alternativeRoutesModel()->currentRoute() );
    connect( marbleModel()->routingManager()->alternativeRoutesModel(), SIGNAL( currentRouteChanged( GeoDataDocument* ) ), SLOT( currentRouteChanged( GeoDataDocument* ) ) );

    connect( marbleModel()->altitudeModel(), SIGNAL( loadCompleted() ), SLOT( altitudeDataLoadCompleted() ) );

#if 0
    GeoDataParser parser( GeoData_UNKNOWN );

    QFile file( "/home/niko/tracks/2011-06-12-mattighofen.gpx" );
    file.open( QIODevice::ReadOnly );
    Q_ASSERT( parser.read( &file ) );
    GeoDataDocument* document = static_cast<GeoDataDocument*>( parser.releaseDocument() );
    Q_ASSERT( document );
    file.close();
    GeoDataPlacemark* routePlacemark = document->placemarkList().first();
    qDebug() << routePlacemark->geometry()->geometryId();
    Q_ASSERT(routePlacemark->geometry()->geometryId() ==  GeoDataMultiGeometryId);
    GeoDataMultiGeometry* routeWaypoints = static_cast<GeoDataMultiGeometry*>(routePlacemark->geometry());
    qDebug() << "size" << routeWaypoints->size(); // << "length" << routeWaypoints->length( EARTH_RADIUS );
    for(int i=0; i < routeWaypoints->size(); ++i) {
        GeoDataGeometry* route2 = routeWaypoints->child(i);
        qDebug() << "route2.geometryId" << route2->geometryId();
        Q_ASSERT(route2->geometryId() == GeoDataLineStringId);
        GeoDataLineString* routeWaypoints2 = static_cast<GeoDataLineString*>(route2);
        qDebug() << "size" << routeWaypoints2->size() << "length" << routeWaypoints2->length(EARTH_RADIUS);
        qreal previousAlt = 0;
        qreal totalIncrease = 0;
        for(int j=0; j< routeWaypoints2->size(); ++j) {
            GeoDataCoordinates coordinate = routeWaypoints2->at( j );
            qDebug() << coordinate.latitude(Marble::GeoDataCoordinates::Degree) << coordinate.longitude(Marble::GeoDataCoordinates::Degree) << coordinate.altitude();
            if (previousAlt && coordinate.altitude() > previousAlt) {
                totalIncrease += coordinate.altitude() - previousAlt;
            }
            previousAlt = coordinate.altitude();
        }
        qDebug() << "totalIncrease" << totalIncrease << "vs. 254m von garmin gemessen";
    }
#endif
}

void AltitudeProfile::altitudeDataLoadCompleted()
{
    currentRouteChanged( marbleModel()->routingManager()->alternativeRoutesModel()->currentRoute() );
}

void AltitudeProfile::currentRouteChanged( GeoDataDocument* route )
{
    m_graph->clearHighligtedPoint();
    m_plot->clearPoints();
    m_stats->setText( QString() );

    if (!route) return;

    qint32 minY = INT_MAX;
    qint32 maxY = 0;
    quint32 numDataPoints = 0;
    qDebug() << "*************************";

    GeoDataPlacemark* routePlacemark = 0;
    Q_ASSERT(route->size());
    if ( !route->placemarkList().count() ) {
        qDebug() << "no placemarks found?!";
        for(int i=0; i<route->size(); ++i) {
            qDebug() << "nodeType" << i << route->child( i )->nodeType();
            if ( dynamic_cast<GeoDataFolder*>( route->child( i ) ) ) {
                Q_ASSERT( static_cast<GeoDataFolder*>( route->child( i ) )->placemarkList().size() );
                routePlacemark = static_cast<GeoDataFolder*>( route->child( i ) )->placemarkList().first();
            }
        }
    } else {
        routePlacemark = route->placemarkList().first();
    }
    Q_ASSERT(routePlacemark);
    Q_ASSERT(routePlacemark->geometry()->geometryId() ==  GeoDataLineStringId);
    GeoDataLineString* routeWaypoints = static_cast<GeoDataLineString*>(routePlacemark->geometry());
    //qDebug() << routeWaypoints->length( EARTH_RADIUS );
    qreal totalIncrease = 0;
    qreal totalIncreaseAvg = 0;
    qreal totalDecreaseAvg = 0;
    qreal lastAltitude = -100000;
    qreal lastAvgAltitude = -100000;
    QList<GeoDataCoordinates> allAltitudes;
    for(int i=1; i < routeWaypoints->size(); ++i) {
        GeoDataCoordinates coordinate = routeWaypoints->at( i );
        GeoDataCoordinates coordinatePrev = routeWaypoints->at( i - 1 );
        //qreal altitude = marbleModel()->altitudeModel()->height(coordinate.latitude(Marble::GeoDataCoordinates::Degree), coordinate.longitude(Marble::GeoDataCoordinates::Degree));
        QList<GeoDataCoordinates> coordinatesList = marbleModel()->altitudeModel()->heightProfile(
            coordinatePrev.latitude(Marble::GeoDataCoordinates::Degree),
            coordinatePrev.longitude(Marble::GeoDataCoordinates::Degree),
            coordinate.latitude(Marble::GeoDataCoordinates::Degree),
            coordinate.longitude(Marble::GeoDataCoordinates::Degree)
        );
        foreach(const GeoDataCoordinates &coord, coordinatesList) {
            //qDebug() << "POINT" << numDataPoints << coordinate.longitude(Marble::GeoDataCoordinates::Degree) << coordinate.latitude(Marble::GeoDataCoordinates::Degree)
            //        << "height" << altitude;
            allAltitudes << coord;
            if ( allAltitudes.count() >= 10 ) {
                qreal avgAltitude = 0;
                for( int j=0; j<10; ++j ) {
                    avgAltitude += allAltitudes.at( allAltitudes.count()-j-1 ).altitude();
                }
                avgAltitude = avgAltitude / 10;
                if (lastAvgAltitude != -100000 && avgAltitude > lastAvgAltitude) {
                    totalIncreaseAvg += avgAltitude-lastAvgAltitude;
                }
                if (lastAvgAltitude != -100000 && avgAltitude < lastAvgAltitude) {
                    totalDecreaseAvg -= avgAltitude-lastAvgAltitude;
                }
                lastAvgAltitude = avgAltitude;
            }
            if ( lastAltitude != -100000 && coord.altitude() > lastAltitude ) {
                totalIncrease += coord.altitude() - lastAltitude;
                //qDebug() << "INCREASE +=" << altitude - lastAltitude << "totalIncrease is now" << totalIncrease;
            }

            double value = coord.altitude();
            //qDebug() << "value" << value;
            m_plot->addPoint(new PlotPoint( numDataPoints++, value, coord ));
            if (value > maxY) maxY = value;
            if (value < minY) minY = value;
            lastAltitude = coord.altitude();
        }
    }
    //qDebug() << "TOTAL INCREASE" << totalIncrease;
    //qDebug() << "TOTAL INCREASE AVG" << totalIncreaseAvg;

    m_graph->setLimits( 0, numDataPoints, minY - minY / 5, maxY + maxY / 5 );

    m_stats->setText( tr( "Gain:
%0m
Loss:
%1m" ).arg( totalIncreaseAvg ).arg( totalDecreaseAvg ) );

    forceUpdate();
}

void AltitudeProfile::forceUpdate()
{
    PlotPoint* hightlightedPoint = m_graph->highlightedPoint();
    if ( hightlightedPoint ) {
        m_labelContainer.show();
        m_labelContainer.setCoordinate( hightlightedPoint->coordinates() );
        m_label->setText( QString::number( hightlightedPoint->coordinates().altitude() ) + "m" );
    } else {
        m_labelContainer.hide();
    }
    if ( m_marbleWidget ) {
        m_marbleWidget->update();
    }
}

bool AltitudeProfile::eventFilter(QObject *object, QEvent *e)
{
    if ( !enabled() || !visible() ) {
        return false;
    }

    MarbleWidget *widget = dynamic_cast<MarbleWidget*> (object);
    if ( !m_marbleWidget ) {
        m_marbleWidget = widget;
    }

    return AbstractFloatItem::eventFilter( object, e );
}

QIcon AltitudeProfile::icon() const
{
    return QIcon();
}

QString AltitudeProfile::description() const
{
    return tr( "This is a float item that displays the altitude profile of a track." );
}

QString AltitudeProfile::nameId() const
{
    return QString( "altitudeProfile" );
}

QString AltitudeProfile::guiString() const
{
    return tr( "&Altitude Profile" );
}

QString AltitudeProfile::name() const
{
    return QString( "Altitude Profile" );
}

Q_EXPORT_PLUGIN2( AltitudeProfile, Marble::AltitudeProfile )

#include "AltitudeProfile.moc"

<|endoftext|>


<commit_before>// @(#)root/test:$Name:  $:$Id: MainEvent.cxx,v 1.24 2002/08/17 21:39:33 brun Exp $
// Author: Rene Brun   19/01/97

////////////////////////////////////////////////////////////////////////
//
//             A simple example with a ROOT tree
//             =================================
//
//  This program creates :
//    - a ROOT file
//    - a tree
//  Additional arguments can be passed to the program to control the flow
//  of execution. (see comments describing the arguments in the code).
//      Event  nevent comp split fill
//  All arguments are optional. Default is:
//      Event  400      1    1     1
//
//  In this example, the tree consists of one single "super branch"
//  The statement ***tree->Branch("event", event, 64000,split);*** below
//  will parse the structure described in Event.h and will make
//  a new branch for each data member of the class if split is set to 1.
//    - 9 branches corresponding to the basic types fType, fNtrack,fNseg,
//           fNvertex,fFlag,fTemperature,fMeasures,fMatrix,fClosesDistance.
//    - 3 branches corresponding to the members of the subobject EventHeader.
//    - one branch for each data member of the class Track of TClonesArray.
//    - one branch for the TRefArray of high Pt tracks
//    - one branch for the TRefArray of muon tracks
//    - one branch for the reference pointer to the last track
//    - one branch for the object fH (histogram of class TH1F).
//
//  if split = 0 only one single branch is created and the complete event
//  is serialized in one single buffer.
//  if split = -2 the event is split using the old TBranchObject mechanism
//  if split = -1 the event is streamed using the old TBranchObject mechanism
//  if split > 0  the event is split using the new TBranchElement mechanism.
//
//  if comp = 0 no compression at all.
//  if comp = 1 event is compressed.
//  if comp = 2 same as 1. In addition branches with floats in the TClonesArray
//                         are also compressed.
//  The 4th argument fill can be set to 0 if one wants to time
//     the percentage of time spent in creating the event structure and
//     not write the event in the file.
//  In this example, one loops over nevent events.
//  The branch "event" is created at the first event.
//  The branch address is set for all other events.
//  For each event, the event header is filled and ntrack tracks
//  are generated and added to the TClonesArray list.
//  For each event the event histogram is saved as well as the list
//  of all tracks.
//
//  The two TRefArray contain only references to the original tracks owned by
//  the TClonesArray fTracks.
//
//  The number of events can be given as the first argument to the program.
//  By default 400 events are generated.
//  The compression option can be activated/deactivated via the second argument.
//
//   ---Running/Linking instructions----
//  This program consists of the following files and procedures.
//    - Event.h event class description
//    - Event.C event class implementation
//    - MainEvent.C the main program to demo this class might be used (this file)
//    - EventCint.C  the CINT dictionary for the event and Track classes
//        this file is automatically generated by rootcint (see Makefile),
//        when the class definition in Event.h is modified.
//
//   ---Analyzing the Event.root file with the interactive root
//        example of a simple session
//   Root > TFile f("Event.root")
//   Root > T.Draw("fNtrack")   //histogram the number of tracks per event
//   Root > T.Draw("fPx")       //histogram fPx for all tracks in all events
//   Root > T.Draw("fXfirst:fYfirst","fNtrack>600")
//                              //scatter-plot for x versus y of first point of each track
//   Root > T.Draw("fH.GetRMS()")  //histogram of the RMS of the event histogram
//
//   Look also in the same directory at the following macros:
//     - eventa.C  an example how to read the tree
//     - eventb.C  how to read events conditionally
//
////////////////////////////////////////////////////////////////////////

#include <stdlib.h>

#include "Riostream.h"
#include "TROOT.h"
#include "TFile.h"
#include "TNetFile.h"
#include "TRandom.h"
#include "TTree.h"
#include "TBranch.h"
#include "TClonesArray.h"
#include "TStopwatch.h"

#include "Event.h"

//______________________________________________________________________________
int main(int argc, char **argv)
{
   Int_t nevent = 400;     // by default create 400 events
   Int_t comp   = 1;       // by default file is compressed
   Int_t split  = 1;       // by default, split Event in sub branches
   Int_t write  = 1;       // by default the tree is filled
   Int_t hfill  = 0;       // by default histograms are not filled
   Int_t read   = 0;
   Int_t arg4   = 1;
   Int_t arg5   = 600;     //default number of tracks per event
   Int_t netf   = 0;

   if (argc > 1)  nevent = atoi(argv[1]);
   if (argc > 2)  comp   = atoi(argv[2]);
   if (argc > 3)  split  = atoi(argv[3]);
   if (argc > 4)  arg4   = atoi(argv[4]);
   if (argc > 5)  arg5   = atoi(argv[5]);
   if (arg4 ==  0) { write = 0; hfill = 0; read = 1;}
   if (arg4 ==  1) { write = 1; hfill = 0;}
   if (arg4 ==  2) { write = 0; hfill = 0;}
   if (arg4 == 10) { write = 0; hfill = 1;}
   if (arg4 == 11) { write = 1; hfill = 1;}
   if (arg4 == 20) { write = 0; read  = 1;}  //read sequential
   if (arg4 == 25) { write = 0; read  = 2;}  //read random
   if (arg4 >= 30) { netf  = 1; }            //use TNetFile
   if (arg4 == 30) { write = 0; read  = 1;}  //netfile + read sequential
   if (arg4 == 35) { write = 0; read  = 2;}  //netfile + read random
   if (arg4 == 36) { write = 1; }            //netfile + write sequential
   Int_t branchStyle = 1; //new style by default
   if (split < 0) {branchStyle = 0; split = -1-split;}

   TFile *hfile;
   TTree *tree;
   Event *event = 0;

   // Fill event, header and tracks with some random numbers
   //   Create a timer object to benchmark this loop
   TStopwatch timer;
   timer.Start();
   Int_t nb = 0;
   Int_t ev;
   Int_t bufsize;
   Double_t told = 0;
   Double_t tnew = 0;
   Int_t printev = 100;
   if (arg5 < 100) printev = 1000;
   if (arg5 < 10)  printev = 10000;

   //In this new version of mainEvent, one cannot activate the next statement
   //because tracks are referenced
   //Track::Class()->IgnoreTObjectStreamer();

//         Read case
   if (read) {
      if (netf) {
         hfile = new TNetFile("root://localhost/root/test/EventNet.root");
         hfile->UseCache(10);
      } else
         hfile = new TFile("Event.root");
      tree = (TTree*)hfile->Get("T");
      TBranch *branch = tree->GetBranch("event");
      branch->SetAddress(&event);
      Int_t nentries = (Int_t)tree->GetEntries();
      nevent = TMath::Max(nevent,nentries);
      if (read == 1) {  //read sequential
         for (ev = 0; ev < nevent; ev++) {
            if (ev%printev == 0) {
               tnew = timer.RealTime();
               printf("event:%d, rtime=%f s\n",ev,tnew-told);
               told=tnew;
               timer.Continue();
            }
            nb += tree->GetEntry(ev);        //read complete event in memory
         }
      } else {    //read random
         Int_t evrandom;
         for (ev = 0; ev < nevent; ev++) {
            if (ev%printev == 0) cout<<"event="<<ev<<endl;
            evrandom = Int_t(nevent*gRandom->Rndm(1));
            nb += tree->GetEntry(evrandom);  //read complete event in memory
         }
      }
   } else {
//         Write case
      // 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.
      if (netf) {
         hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file");
         hfile->UseCache(10);
      } else
         hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file");
      hfile->SetCompressionLevel(comp);

     // Create histogram to show write_time in function of time
     Float_t curtime = -0.5;
     Int_t ntime = nevent/printev;
     TH1F *htime = new TH1F("htime","Real-Time to write versus time",ntime,0,ntime);
     HistogramManager *hm = 0;
     if (hfill) {
        TDirectory *hdir = new TDirectory("histograms", "all histograms");
        hm = new HistogramManager(hdir);
     }

     // Create a ROOT Tree and one superbranch
      TTree *tree = new TTree("T","An example of a ROOT tree");
      tree->SetAutoSave(1000000000);  // autosave when 1 Gbyte written
      bufsize = 64000;
      if (split)  bufsize /= 4;
      event = new Event();
      TTree::SetBranchStyle(branchStyle);
      TBranch *branch = tree->Branch("event", "Event", &event, bufsize,split);
      branch->SetAutoDelete(kFALSE);
      Float_t ptmin = 1;

      for (ev = 0; ev < nevent; ev++) {
         if (ev%printev == 0) {
            tnew = timer.RealTime();
            printf("event:%d, rtime=%f s\n",ev,tnew-told);
            htime->Fill(curtime,tnew-told);
            curtime += 1;
            told=tnew;
            timer.Continue();
         }

         event->Build(ev, arg5, ptmin);

         if (write) nb += tree->Fill();  //fill the tree

         if (hm) hm->Hfill(event);      //fill histograms
      }
      if (write) {
         hfile = tree->GetCurrentFile(); //just in case we switched to a new file
         hfile->Write();
         tree->Print();
      }
   }

   //  Stop timer and print results
   timer.Stop();
   Float_t mbytes = 0.000001*nb;
   Double_t rtime = timer.RealTime();
   Double_t ctime = timer.CpuTime();

   printf("\n%d events and %d bytes processed.\n",nevent,nb);
   printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime);
   if (read) {
      printf("You read %f Mbytes/Realtime seconds\n",mbytes/rtime);
      printf("You read %f Mbytes/Cputime seconds\n",mbytes/ctime);
   } else {
      printf("compression level=%d, split=%d, arg4=%d\n",comp,split,arg4);
      printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime);
      printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime);
      //printf("file compression factor = %f\n",hfile.GetCompressionFactor());
   }
   hfile->Close();
   return 0;
}
<commit_msg>Add a call to TTree::SetMaxTreeSize to give the possibility to create a Tree as big as 2 Terabytes (if the system can do it). For example try the following:   Event 100000 0 7 1 This should create a Tree of size 7.6 Gigabytes<commit_after>// @(#)root/test:$Name:  $:$Id: MainEvent.cxx,v 1.25 2002/11/13 17:35:50 rdm Exp $
// Author: Rene Brun   19/01/97

////////////////////////////////////////////////////////////////////////
//
//             A simple example with a ROOT tree
//             =================================
//
//  This program creates :
//    - a ROOT file
//    - a tree
//  Additional arguments can be passed to the program to control the flow
//  of execution. (see comments describing the arguments in the code).
//      Event  nevent comp split fill
//  All arguments are optional. Default is:
//      Event  400      1    1     1
//
//  In this example, the tree consists of one single "super branch"
//  The statement ***tree->Branch("event", event, 64000,split);*** below
//  will parse the structure described in Event.h and will make
//  a new branch for each data member of the class if split is set to 1.
//    - 9 branches corresponding to the basic types fType, fNtrack,fNseg,
//           fNvertex,fFlag,fTemperature,fMeasures,fMatrix,fClosesDistance.
//    - 3 branches corresponding to the members of the subobject EventHeader.
//    - one branch for each data member of the class Track of TClonesArray.
//    - one branch for the TRefArray of high Pt tracks
//    - one branch for the TRefArray of muon tracks
//    - one branch for the reference pointer to the last track
//    - one branch for the object fH (histogram of class TH1F).
//
//  if split = 0 only one single branch is created and the complete event
//  is serialized in one single buffer.
//  if split = -2 the event is split using the old TBranchObject mechanism
//  if split = -1 the event is streamed using the old TBranchObject mechanism
//  if split > 0  the event is split using the new TBranchElement mechanism.
//
//  if comp = 0 no compression at all.
//  if comp = 1 event is compressed.
//  if comp = 2 same as 1. In addition branches with floats in the TClonesArray
//                         are also compressed.
//  The 4th argument fill can be set to 0 if one wants to time
//     the percentage of time spent in creating the event structure and
//     not write the event in the file.
//  In this example, one loops over nevent events.
//  The branch "event" is created at the first event.
//  The branch address is set for all other events.
//  For each event, the event header is filled and ntrack tracks
//  are generated and added to the TClonesArray list.
//  For each event the event histogram is saved as well as the list
//  of all tracks.
//
//  The two TRefArray contain only references to the original tracks owned by
//  the TClonesArray fTracks.
//
//  The number of events can be given as the first argument to the program.
//  By default 400 events are generated.
//  The compression option can be activated/deactivated via the second argument.
//
//   ---Running/Linking instructions----
//  This program consists of the following files and procedures.
//    - Event.h event class description
//    - Event.C event class implementation
//    - MainEvent.C the main program to demo this class might be used (this file)
//    - EventCint.C  the CINT dictionary for the event and Track classes
//        this file is automatically generated by rootcint (see Makefile),
//        when the class definition in Event.h is modified.
//
//   ---Analyzing the Event.root file with the interactive root
//        example of a simple session
//   Root > TFile f("Event.root")
//   Root > T.Draw("fNtrack")   //histogram the number of tracks per event
//   Root > T.Draw("fPx")       //histogram fPx for all tracks in all events
//   Root > T.Draw("fXfirst:fYfirst","fNtrack>600")
//                              //scatter-plot for x versus y of first point of each track
//   Root > T.Draw("fH.GetRMS()")  //histogram of the RMS of the event histogram
//
//   Look also in the same directory at the following macros:
//     - eventa.C  an example how to read the tree
//     - eventb.C  how to read events conditionally
//
////////////////////////////////////////////////////////////////////////

#include <stdlib.h>

#include "Riostream.h"
#include "TROOT.h"
#include "TFile.h"
#include "TNetFile.h"
#include "TRandom.h"
#include "TTree.h"
#include "TBranch.h"
#include "TClonesArray.h"
#include "TStopwatch.h"

#include "Event.h"

//______________________________________________________________________________
int main(int argc, char **argv)
{
   Int_t nevent = 400;     // by default create 400 events
   Int_t comp   = 1;       // by default file is compressed
   Int_t split  = 1;       // by default, split Event in sub branches
   Int_t write  = 1;       // by default the tree is filled
   Int_t hfill  = 0;       // by default histograms are not filled
   Int_t read   = 0;
   Int_t arg4   = 1;
   Int_t arg5   = 600;     //default number of tracks per event
   Int_t netf   = 0;

   if (argc > 1)  nevent = atoi(argv[1]);
   if (argc > 2)  comp   = atoi(argv[2]);
   if (argc > 3)  split  = atoi(argv[3]);
   if (argc > 4)  arg4   = atoi(argv[4]);
   if (argc > 5)  arg5   = atoi(argv[5]);
   if (arg4 ==  0) { write = 0; hfill = 0; read = 1;}
   if (arg4 ==  1) { write = 1; hfill = 0;}
   if (arg4 ==  2) { write = 0; hfill = 0;}
   if (arg4 == 10) { write = 0; hfill = 1;}
   if (arg4 == 11) { write = 1; hfill = 1;}
   if (arg4 == 20) { write = 0; read  = 1;}  //read sequential
   if (arg4 == 25) { write = 0; read  = 2;}  //read random
   if (arg4 >= 30) { netf  = 1; }            //use TNetFile
   if (arg4 == 30) { write = 0; read  = 1;}  //netfile + read sequential
   if (arg4 == 35) { write = 0; read  = 2;}  //netfile + read random
   if (arg4 == 36) { write = 1; }            //netfile + write sequential
   Int_t branchStyle = 1; //new style by default
   if (split < 0) {branchStyle = 0; split = -1-split;}

   TFile *hfile;
   TTree *tree;
   Event *event = 0;

   // Fill event, header and tracks with some random numbers
   //   Create a timer object to benchmark this loop
   TStopwatch timer;
   timer.Start();
   Int_t nb = 0;
   Int_t ev;
   Int_t bufsize;
   Double_t told = 0;
   Double_t tnew = 0;
   Int_t printev = 100;
   if (arg5 < 100) printev = 1000;
   if (arg5 < 10)  printev = 10000;

   //Authorize Trees up to 2 Terabytes (if the system can do it)
   TTree::SetMaxTreeSize(1000*Long64_t(2000000000));

//         Read case
   if (read) {
      if (netf) {
         hfile = new TNetFile("root://localhost/root/test/EventNet.root");
         hfile->UseCache(10);
      } else
         hfile = new TFile("Event.root");
      tree = (TTree*)hfile->Get("T");
      TBranch *branch = tree->GetBranch("event");
      branch->SetAddress(&event);
      Int_t nentries = (Int_t)tree->GetEntries();
      nevent = TMath::Max(nevent,nentries);
      if (read == 1) {  //read sequential
         for (ev = 0; ev < nevent; ev++) {
            if (ev%printev == 0) {
               tnew = timer.RealTime();
               printf("event:%d, rtime=%f s\n",ev,tnew-told);
               told=tnew;
               timer.Continue();
            }
            nb += tree->GetEntry(ev);        //read complete event in memory
         }
      } else {    //read random
         Int_t evrandom;
         for (ev = 0; ev < nevent; ev++) {
            if (ev%printev == 0) cout<<"event="<<ev<<endl;
            evrandom = Int_t(nevent*gRandom->Rndm(1));
            nb += tree->GetEntry(evrandom);  //read complete event in memory
         }
      }
   } else {
//         Write case
      // 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.
      if (netf) {
         hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file");
         hfile->UseCache(10);
      } else
         hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file");
      hfile->SetCompressionLevel(comp);

     // Create histogram to show write_time in function of time
     Float_t curtime = -0.5;
     Int_t ntime = nevent/printev;
     TH1F *htime = new TH1F("htime","Real-Time to write versus time",ntime,0,ntime);
     HistogramManager *hm = 0;
     if (hfill) {
        TDirectory *hdir = new TDirectory("histograms", "all histograms");
        hm = new HistogramManager(hdir);
     }

     // Create a ROOT Tree and one superbranch
      TTree *tree = new TTree("T","An example of a ROOT tree");
      tree->SetAutoSave(1000000000);  // autosave when 1 Gbyte written
      bufsize = 64000;
      if (split)  bufsize /= 4;
      event = new Event();
      TTree::SetBranchStyle(branchStyle);
      TBranch *branch = tree->Branch("event", "Event", &event, bufsize,split);
      branch->SetAutoDelete(kFALSE);
      Float_t ptmin = 1;

      for (ev = 0; ev < nevent; ev++) {
         if (ev%printev == 0) {
            tnew = timer.RealTime();
            printf("event:%d, rtime=%f s\n",ev,tnew-told);
            htime->Fill(curtime,tnew-told);
            curtime += 1;
            told=tnew;
            timer.Continue();
         }

         event->Build(ev, arg5, ptmin);

         if (write) nb += tree->Fill();  //fill the tree

         if (hm) hm->Hfill(event);      //fill histograms
      }
      if (write) {
         hfile = tree->GetCurrentFile(); //just in case we switched to a new file
         hfile->Write();
         tree->Print();
      }
   }

   //  Stop timer and print results
   timer.Stop();
   Float_t mbytes = 0.000001*nb;
   Double_t rtime = timer.RealTime();
   Double_t ctime = timer.CpuTime();

   printf("\n%d events and %d bytes processed.\n",nevent,nb);
   printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime);
   if (read) {
      printf("You read %f Mbytes/Realtime seconds\n",mbytes/rtime);
      printf("You read %f Mbytes/Cputime seconds\n",mbytes/ctime);
   } else {
      printf("compression level=%d, split=%d, arg4=%d\n",comp,split,arg4);
      printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime);
      printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime);
      //printf("file compression factor = %f\n",hfile.GetCompressionFactor());
   }
   hfile->Close();
   return 0;
}
<|endoftext|>


<commit_before>#include "ScreenQuad.h"

ScreenQuad::ScreenQuad()
{
}

ScreenQuad::~ScreenQuad()
{
}

int ScreenQuad::Initialize(ID3D11Device * device, int screenWidth, int screenHeight)
{
	DirectX::XMFLOAT3 vertices[6];
	unsigned long indices[6];
	int sizeVertices = 6;
	int sizeIndices = 6;
	D3D11_BUFFER_DESC vertexBufferDesc;
	D3D11_BUFFER_DESC indexBufferDesc;
	D3D11_SUBRESOURCE_DATA vertexData;
	D3D11_SUBRESOURCE_DATA indexData;
	float left, right, top, bottom;
	HRESULT hresult;
	bool result;

	//Calculate the screen coordinates of the left side of the window
	left = (float)((screenWidth / 2) * -1);

	//Calculate the screen coordinates of the right side of the window
	right = left + (float)screenWidth;

	//Calculate the screen coordinates of the top of the window
	top = (float)(screenHeight / 2);

	//Calculate the screen coordinates of the bottom of the window
	bottom = top - (float)screenHeight;

	//Load the vertex array with data
	//First triangle
	vertices[0] = DirectX::XMFLOAT3(left, top, 0.0f);  //Top left

	vertices[1] = DirectX::XMFLOAT3(right, bottom, 0.0f);  //Bottom right

	vertices[2] = DirectX::XMFLOAT3(left, bottom, 0.0f);  //Bottom left

	//Second triangle
	vertices[3] = DirectX::XMFLOAT3(left, top, 0.0f);  //Top left

	vertices[4] = DirectX::XMFLOAT3(right, top, 0.0f);  //Top right

	vertices[5] = DirectX::XMFLOAT3(right, bottom, 0.0f);  //Bottom right

	//Load the index array with data
	for (int i = 0; i < sizeIndices; i++)
	{
		indices[i] = i;
	}

	//Set the description of the static vertex buffer
	ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
	vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	vertexBufferDesc.ByteWidth = sizeof(DirectX::XMFLOAT3) * sizeVertices;
	vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	vertexBufferDesc.CPUAccessFlags = 0;
	vertexBufferDesc.MiscFlags = 0;
	vertexBufferDesc.StructureByteStride = 0;

	//Give the subresource structure a pointer to the vertex data
	ZeroMemory(&vertexData, sizeof(vertexData));
	vertexData.pSysMem = &vertices;
	vertexData.SysMemPitch = 0;
	vertexData.SysMemSlicePitch = 0;

	//Create the vertex buffer
	hresult = device->CreateBuffer(&vertexBufferDesc, &vertexData, &this->m_vertexBuffer);
	if (FAILED(hresult)) {
		return false;
	}

	//Set up the description of the static index buffer
	ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc));
	indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	indexBufferDesc.ByteWidth = sizeof(unsigned long) * sizeIndices;
	indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
	indexBufferDesc.CPUAccessFlags = 0;
	indexBufferDesc.MiscFlags = 0;
	indexBufferDesc.StructureByteStride = 0;

	ZeroMemory(&indexData, sizeof(indexData));
	indexData.pSysMem = &indices;
	indexData.SysMemPitch = 0;
	indexData.SysMemSlicePitch = 0;

	//Create the index buffer
	hresult = device->CreateBuffer(&indexBufferDesc, &indexData, &this->m_indexBuffer);
	if (FAILED(hresult)) {
		return false;
	}

	return 0;
}

void ScreenQuad::SetBuffers(ID3D11DeviceContext * deviceContext)
{
}

void ScreenQuad::Shutdown()
{
}
<commit_msg>UPDATE ScreenQuad SetBuffers() implemented<commit_after>#include "ScreenQuad.h"

ScreenQuad::ScreenQuad()
{
}

ScreenQuad::~ScreenQuad()
{
}

int ScreenQuad::Initialize(ID3D11Device * device, int screenWidth, int screenHeight)
{
	DirectX::XMFLOAT3 vertices[6];
	unsigned long indices[6];
	int sizeVertices = 6;
	int sizeIndices = 6;
	D3D11_BUFFER_DESC vertexBufferDesc;
	D3D11_BUFFER_DESC indexBufferDesc;
	D3D11_SUBRESOURCE_DATA vertexData;
	D3D11_SUBRESOURCE_DATA indexData;
	float left, right, top, bottom;
	HRESULT hresult;
	bool result;

	//Calculate the screen coordinates of the left side of the window
	left = (float)((screenWidth / 2) * -1);

	//Calculate the screen coordinates of the right side of the window
	right = left + (float)screenWidth;

	//Calculate the screen coordinates of the top of the window
	top = (float)(screenHeight / 2);

	//Calculate the screen coordinates of the bottom of the window
	bottom = top - (float)screenHeight;

	//Load the vertex array with data
	//First triangle
	vertices[0] = DirectX::XMFLOAT3(left, top, 0.0f);  //Top left

	vertices[1] = DirectX::XMFLOAT3(right, bottom, 0.0f);  //Bottom right

	vertices[2] = DirectX::XMFLOAT3(left, bottom, 0.0f);  //Bottom left

	//Second triangle
	vertices[3] = DirectX::XMFLOAT3(left, top, 0.0f);  //Top left

	vertices[4] = DirectX::XMFLOAT3(right, top, 0.0f);  //Top right

	vertices[5] = DirectX::XMFLOAT3(right, bottom, 0.0f);  //Bottom right

	//Load the index array with data
	for (int i = 0; i < sizeIndices; i++)
	{
		indices[i] = i;
	}

	//Set the description of the static vertex buffer
	ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
	vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	vertexBufferDesc.ByteWidth = sizeof(DirectX::XMFLOAT3) * sizeVertices;
	vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	vertexBufferDesc.CPUAccessFlags = 0;
	vertexBufferDesc.MiscFlags = 0;
	vertexBufferDesc.StructureByteStride = 0;

	//Give the subresource structure a pointer to the vertex data
	ZeroMemory(&vertexData, sizeof(vertexData));
	vertexData.pSysMem = &vertices;
	vertexData.SysMemPitch = 0;
	vertexData.SysMemSlicePitch = 0;

	//Create the vertex buffer
	hresult = device->CreateBuffer(&vertexBufferDesc, &vertexData, &this->m_vertexBuffer);
	if (FAILED(hresult)) {
		return false;
	}

	//Set up the description of the static index buffer
	ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc));
	indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	indexBufferDesc.ByteWidth = sizeof(unsigned long) * sizeIndices;
	indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
	indexBufferDesc.CPUAccessFlags = 0;
	indexBufferDesc.MiscFlags = 0;
	indexBufferDesc.StructureByteStride = 0;

	ZeroMemory(&indexData, sizeof(indexData));
	indexData.pSysMem = &indices;
	indexData.SysMemPitch = 0;
	indexData.SysMemSlicePitch = 0;

	//Create the index buffer
	hresult = device->CreateBuffer(&indexBufferDesc, &indexData, &this->m_indexBuffer);
	if (FAILED(hresult)) {
		return false;
	}

	return 0;
}

void ScreenQuad::SetBuffers(ID3D11DeviceContext * deviceContext)
{
	unsigned int stride;
	unsigned offset;

	//Set vertex buffer stride and offset
	stride = sizeof(DirectX::XMFLOAT3);
	offset = 0;

	//Set the vertex buffer to active in the input assembly so it can rendered
	deviceContext->IASetVertexBuffers(0, 1, &this->m_vertexBuffer, &stride, &offset);

	//Set the index buffer to active in the input assembler so it can be rendered
	deviceContext->IASetIndexBuffer(this->m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);

	//Set the type od primitiv that should be rendered from this vertex buffer, in this case triangles
	deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

}

void ScreenQuad::Shutdown()
{
}
<|endoftext|>


<commit_before>/****************************************************************************
 * Copyright (c) 2012-2018 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 *                                                                          *
 * SPDX-License-Identifier: BSD-3-Clause                                    *
 ****************************************************************************/

#include <DTK_LinearBVH.hpp>

#include <Kokkos_DefaultNode.hpp>
#include <Teuchos_CommandLineProcessor.hpp>
#include <Teuchos_StandardCatchMacros.hpp>

#include <chrono>
#include <cmath> // cbrt
#include <random>

template <class NO>
int main_( Teuchos::CommandLineProcessor &clp, int argc, char *argv[] )
{
    using DeviceType = typename NO::device_type;
    using ExecutionSpace = typename DeviceType::execution_space;

    int n_values = 50000;
    int n_queries = 20000;
    int n_neighbors = 10;

    clp.setOption( "values", &n_values, "number of indexable values (source)" );
    clp.setOption( "queries", &n_queries, "number of queries (target)" );
    clp.setOption( "neighbors", &n_neighbors,
                   "desired number of results per query" );

    clp.recogniseAllOptions( true );
    switch ( clp.parse( argc, argv ) )
    {
    case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
        return EXIT_SUCCESS;
    case Teuchos::CommandLineProcessor::PARSE_ERROR:
    case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
        return EXIT_FAILURE;
    case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
        break;
    }

    Kokkos::View<DataTransferKit::Point *, DeviceType> random_points(
        "random_points" );
    {
        auto n = std::max( n_values, n_queries );
        Kokkos::resize( random_points, n );

        auto random_points_host = Kokkos::create_mirror_view( random_points );

        // edge length chosen such that object density will remain constant as
        // problem size is changed
        auto const a = std::cbrt( n_values );
        std::uniform_real_distribution<double> distribution( -a, +a );
        std::default_random_engine generator;
        auto random = [&distribution, &generator]() {
            return distribution( generator );
        };
        for ( int i = 0; i < n; ++i )
            random_points_host( i ) = {{random(), random(), random()}};
        Kokkos::deep_copy( random_points, random_points_host );
    }

    Kokkos::View<DataTransferKit::Box *, DeviceType> bounding_boxes(
        "bounding_boxes", n_values );
    Kokkos::parallel_for( Kokkos::RangePolicy<ExecutionSpace>( 0, n_values ),
                          KOKKOS_LAMBDA( int i ) {
                              double const x = random_points( i )[0];
                              double const y = random_points( i )[1];
                              double const z = random_points( i )[2];
                              bounding_boxes( i ) = {
                                  {{x - 1., y - 1., z - 1.}},
                                  {{x + 1., y + 1., z + 1.}}};
                          } );
    Kokkos::fence();

    std::ostream &os = std::cout;

    auto start = std::chrono::high_resolution_clock::now();
    DataTransferKit::BVH<DeviceType> bvh( bounding_boxes );
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> elapsed_seconds = end - start;
    os << "construction " << elapsed_seconds.count() << "\n";

    {
        Kokkos::View<
            DataTransferKit::Details::Nearest<DataTransferKit::Point> *,
            DeviceType>
            queries( "queries", n_queries );
        Kokkos::parallel_for(
            Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
            KOKKOS_LAMBDA( int i ) {
                queries( i ) =
                    DataTransferKit::Details::nearest<DataTransferKit::Point>(
                        random_points( i ), n_neighbors );
            } );
        Kokkos::fence();

        Kokkos::View<int *, DeviceType> offset( "offset" );
        Kokkos::View<int *, DeviceType> indices( "indices" );
        start = std::chrono::high_resolution_clock::now();
        bvh.query( queries, indices, offset );
        end = std::chrono::high_resolution_clock::now();
        elapsed_seconds = end - start;
        os << "knn " << elapsed_seconds.count() << "\n";
    }

    {
        Kokkos::View<DataTransferKit::Details::Within *, DeviceType> queries(
            "queries", n_queries );
        // radius chosen in order to control the number of results per query
        double const pi = 3.14159265359;
        double const r =
            std::cbrt( static_cast<double>( n_neighbors ) * 3. / ( 4. * pi ) );
        Kokkos::parallel_for(
            Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
            KOKKOS_LAMBDA( int i ) {
                queries( i ) =
                    DataTransferKit::Details::within( random_points( i ), r );
            } );
        Kokkos::fence();

        Kokkos::View<int *, DeviceType> offset( "offset" );
        Kokkos::View<int *, DeviceType> indices( "indices" );
        start = std::chrono::high_resolution_clock::now();
        bvh.query( queries, indices, offset );
        end = std::chrono::high_resolution_clock::now();
        elapsed_seconds = end - start;
        os << "radius " << elapsed_seconds.count() << "\n";
    }

    return 0;
}

int main( int argc, char *argv[] )
{
    Kokkos::initialize( argc, argv );

    bool success = true;
    bool verbose = true;

    try
    {
        const bool throwExceptions = false;

        Teuchos::CommandLineProcessor clp( throwExceptions );

        std::string node = "";
        clp.setOption( "node", &node, "node type (serial | openmp | cuda)" );

        clp.recogniseAllOptions( false );
        switch ( clp.parse( argc, argv, NULL ) )
        {
        case Teuchos::CommandLineProcessor::PARSE_ERROR:
            success = false;
        case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
        case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
        case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
            break;
        }

        if ( !success )
        {
            // do nothing, just skip other if clauses
        }
        else if ( node == "" )
        {
            typedef KokkosClassic::DefaultNode::DefaultNodeType Node;
            main_<Node>( clp, argc, argv );
        }
        else if ( node == "serial" )
        {
#ifdef KOKKOS_HAVE_SERIAL
            typedef Kokkos::Compat::KokkosSerialWrapperNode Node;
            main_<Node>( clp, argc, argv );
#else
            throw std::runtime_error( "Serial node type is disabled" );
#endif
        }
        else if ( node == "openmp" )
        {
#ifdef KOKKOS_HAVE_OPENMP
            typedef Kokkos::Compat::KokkosOpenMPWrapperNode Node;
            main_<Node>( clp, argc, argv );
#else
            throw std::runtime_error( "OpenMP node type is disabled" );
#endif
        }
        else if ( node == "cuda" )
        {
#ifdef KOKKOS_HAVE_CUDA
            typedef Kokkos::Compat::KokkosCudaWrapperNode Node;
            main_<Node>( clp, argc, argv );
#else
            throw std::runtime_error( "CUDA node type is disabled" );
#endif
        }
        else
        {
            throw std::runtime_error( "Unrecognized node type" );
        }
    }
    TEUCHOS_STANDARD_CATCH_STATEMENTS( verbose, std::cerr, success );

    Kokkos::finalize();

    return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
}
<commit_msg>Correct radius for controlling the number of results per query<commit_after>/****************************************************************************
 * Copyright (c) 2012-2018 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 *                                                                          *
 * SPDX-License-Identifier: BSD-3-Clause                                    *
 ****************************************************************************/

#include <DTK_LinearBVH.hpp>

#include <Kokkos_DefaultNode.hpp>
#include <Teuchos_CommandLineProcessor.hpp>
#include <Teuchos_StandardCatchMacros.hpp>

#include <chrono>
#include <cmath> // cbrt
#include <random>

template <class NO>
int main_( Teuchos::CommandLineProcessor &clp, int argc, char *argv[] )
{
    using DeviceType = typename NO::device_type;
    using ExecutionSpace = typename DeviceType::execution_space;

    int n_values = 50000;
    int n_queries = 20000;
    int n_neighbors = 10;

    clp.setOption( "values", &n_values, "number of indexable values (source)" );
    clp.setOption( "queries", &n_queries, "number of queries (target)" );
    clp.setOption( "neighbors", &n_neighbors,
                   "desired number of results per query" );

    clp.recogniseAllOptions( true );
    switch ( clp.parse( argc, argv ) )
    {
    case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
        return EXIT_SUCCESS;
    case Teuchos::CommandLineProcessor::PARSE_ERROR:
    case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
        return EXIT_FAILURE;
    case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
        break;
    }

    Kokkos::View<DataTransferKit::Point *, DeviceType> random_points(
        "random_points" );
    {
        auto n = std::max( n_values, n_queries );
        Kokkos::resize( random_points, n );

        auto random_points_host = Kokkos::create_mirror_view( random_points );

        // edge length chosen such that object density will remain constant as
        // problem size is changed
        auto const a = std::cbrt( n_values );
        std::uniform_real_distribution<double> distribution( -a, +a );
        std::default_random_engine generator;
        auto random = [&distribution, &generator]() {
            return distribution( generator );
        };
        for ( int i = 0; i < n; ++i )
            random_points_host( i ) = {{random(), random(), random()}};
        Kokkos::deep_copy( random_points, random_points_host );
    }

    Kokkos::View<DataTransferKit::Box *, DeviceType> bounding_boxes(
        "bounding_boxes", n_values );
    Kokkos::parallel_for( Kokkos::RangePolicy<ExecutionSpace>( 0, n_values ),
                          KOKKOS_LAMBDA( int i ) {
                              double const x = random_points( i )[0];
                              double const y = random_points( i )[1];
                              double const z = random_points( i )[2];
                              bounding_boxes( i ) = {
                                  {{x - 1., y - 1., z - 1.}},
                                  {{x + 1., y + 1., z + 1.}}};
                          } );
    Kokkos::fence();

    std::ostream &os = std::cout;

    auto start = std::chrono::high_resolution_clock::now();
    DataTransferKit::BVH<DeviceType> bvh( bounding_boxes );
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> elapsed_seconds = end - start;
    os << "construction " << elapsed_seconds.count() << "\n";

    {
        Kokkos::View<
            DataTransferKit::Details::Nearest<DataTransferKit::Point> *,
            DeviceType>
            queries( "queries", n_queries );
        Kokkos::parallel_for(
            Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
            KOKKOS_LAMBDA( int i ) {
                queries( i ) =
                    DataTransferKit::Details::nearest<DataTransferKit::Point>(
                        random_points( i ), n_neighbors );
            } );
        Kokkos::fence();

        Kokkos::View<int *, DeviceType> offset( "offset" );
        Kokkos::View<int *, DeviceType> indices( "indices" );
        start = std::chrono::high_resolution_clock::now();
        bvh.query( queries, indices, offset );
        end = std::chrono::high_resolution_clock::now();
        elapsed_seconds = end - start;
        os << "knn " << elapsed_seconds.count() << "\n";
    }

    {
        Kokkos::View<DataTransferKit::Details::Within *, DeviceType> queries(
            "queries", n_queries );
        // radius chosen in order to control the number of results per query
        // NOTE: minus "1+sqrt(3)/2 \approx 1.37" matches the size of the boxes
        // inserted into the tree (mid-point between half-edge and
        // half-diagonal)
        double const pi = 3.14159265359;
        double const r = 2. * std::cbrt( static_cast<double>( n_neighbors ) *
                                         3. / ( 4. * pi ) ) -
                         ( 1. + std::sqrt( 3. ) ) / 2.;
        Kokkos::parallel_for(
            Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
            KOKKOS_LAMBDA( int i ) {
                queries( i ) =
                    DataTransferKit::Details::within( random_points( i ), r );
            } );
        Kokkos::fence();

        Kokkos::View<int *, DeviceType> offset( "offset" );
        Kokkos::View<int *, DeviceType> indices( "indices" );
        start = std::chrono::high_resolution_clock::now();
        bvh.query( queries, indices, offset );
        end = std::chrono::high_resolution_clock::now();
        elapsed_seconds = end - start;
        os << "radius " << elapsed_seconds.count() << "\n";
    }

    return 0;
}

int main( int argc, char *argv[] )
{
    Kokkos::initialize( argc, argv );

    bool success = true;
    bool verbose = true;

    try
    {
        const bool throwExceptions = false;

        Teuchos::CommandLineProcessor clp( throwExceptions );

        std::string node = "";
        clp.setOption( "node", &node, "node type (serial | openmp | cuda)" );

        clp.recogniseAllOptions( false );
        switch ( clp.parse( argc, argv, NULL ) )
        {
        case Teuchos::CommandLineProcessor::PARSE_ERROR:
            success = false;
        case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
        case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
        case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
            break;
        }

        if ( !success )
        {
            // do nothing, just skip other if clauses
        }
        else if ( node == "" )
        {
            typedef KokkosClassic::DefaultNode::DefaultNodeType Node;
            main_<Node>( clp, argc, argv );
        }
        else if ( node == "serial" )
        {
#ifdef KOKKOS_HAVE_SERIAL
            typedef Kokkos::Compat::KokkosSerialWrapperNode Node;
            main_<Node>( clp, argc, argv );
#else
            throw std::runtime_error( "Serial node type is disabled" );
#endif
        }
        else if ( node == "openmp" )
        {
#ifdef KOKKOS_HAVE_OPENMP
            typedef Kokkos::Compat::KokkosOpenMPWrapperNode Node;
            main_<Node>( clp, argc, argv );
#else
            throw std::runtime_error( "OpenMP node type is disabled" );
#endif
        }
        else if ( node == "cuda" )
        {
#ifdef KOKKOS_HAVE_CUDA
            typedef Kokkos::Compat::KokkosCudaWrapperNode Node;
            main_<Node>( clp, argc, argv );
#else
            throw std::runtime_error( "CUDA node type is disabled" );
#endif
        }
        else
        {
            throw std::runtime_error( "Unrecognized node type" );
        }
    }
    TEUCHOS_STANDARD_CATCH_STATEMENTS( verbose, std::cerr, success );

    Kokkos::finalize();

    return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
}
<|endoftext|>