<commit_before>/***************************************************************************
 *   Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
# include <QApplication>
# include <QAction>
# include <QToolBar>
# include <QToolButton>
#endif

#include "ToolBarManager.h"
#include "MainWindow.h"
#include "Application.h"
#include "Command.h"

using namespace Gui;

ToolBarItem::ToolBarItem()
{
}

ToolBarItem::ToolBarItem(ToolBarItem* item)
{
    if ( item )
        item->appendItem(this);
}

ToolBarItem::~ToolBarItem()
{
    clear();
}

void ToolBarItem::setCommand(const std::string& name)
{
    _name = name;
}

std::string ToolBarItem::command() const
{
    return _name;
}

bool ToolBarItem::hasItems() const
{
    return _items.count() > 0;
}

ToolBarItem* ToolBarItem::findItem(const std::string& name)
{
    if ( _name == name ) {
        return this;
    } else {
        for ( QList<ToolBarItem*>::ConstIterator it = _items.begin(); it != _items.end(); ++it ) {
            if ( (*it)->_name == name ) {
                return *it;
            }
        }
    }

    return 0;
}

ToolBarItem* ToolBarItem::copy() const
{
    ToolBarItem* root = new ToolBarItem;
    root->setCommand( command() );

    QList<ToolBarItem*> items = getItems();
    for ( QList<ToolBarItem*>::ConstIterator it = items.begin(); it != items.end(); ++it ) {
        root->appendItem( (*it)->copy() );
    }

    return root;
}

uint ToolBarItem::count() const
{
    return _items.count();
}

void ToolBarItem::appendItem(ToolBarItem* item)
{
    _items.push_back( item );
}

bool ToolBarItem::insertItem( ToolBarItem* before, ToolBarItem* item)
{
    int pos = _items.indexOf(before);
    if (pos != -1) {
        _items.insert(pos, item);
        return true;
    } else
        return false;
}

void ToolBarItem::removeItem(ToolBarItem* item)
{
    int pos = _items.indexOf(item);
    if (pos != -1)
        _items.removeAt(pos);
}

void ToolBarItem::clear()
{
    for ( QList<ToolBarItem*>::Iterator it = _items.begin(); it != _items.end(); ++it ) {
        delete *it;
    }

    _items.clear();
}

ToolBarItem& ToolBarItem::operator << (ToolBarItem* item)
{
    appendItem(item);
    return *this;
}

ToolBarItem& ToolBarItem::operator << (const std::string& command)
{
    ToolBarItem* item = new ToolBarItem(this);
    item->setCommand(command);
    return *this;
}

QList<ToolBarItem*> ToolBarItem::getItems() const
{
    return _items;
}

// -----------------------------------------------------------

ToolBarManager* ToolBarManager::_instance=0;

ToolBarManager* ToolBarManager::getInstance()
{
    if ( !_instance )
        _instance = new ToolBarManager;
    return _instance;
}

void ToolBarManager::destruct()
{
    delete _instance;
    _instance = 0;
}

ToolBarManager::ToolBarManager()
{
}

ToolBarManager::~ToolBarManager()
{
}

void ToolBarManager::setup(ToolBarItem* toolBarItems)
{
    if (!toolBarItems)
        return; // empty menu bar

    saveState();
    this->toolbarNames.clear();

    int max_width = getMainWindow()->width();
    int top_width = 0;

    ParameterGrp::handle hPref = App::GetApplication().GetUserParameter().GetGroup("BaseApp")
                               ->GetGroup("MainWindow")->GetGroup("Toolbars");
    QList<ToolBarItem*> items = toolBarItems->getItems();
    QList<QToolBar*> toolbars = toolBars();
    for (QList<ToolBarItem*>::ConstIterator it = items.begin(); it != items.end(); ++it) {
        // search for the toolbar
        this->toolbarNames << QString::fromUtf8((*it)->command().c_str());
        QToolBar* toolbar = findToolBar(toolbars, QString::fromAscii((*it)->command().c_str()));
        std::string toolbarName = (*it)->command();
        bool visible = hPref->GetBool(toolbarName.c_str(), true);
        bool toolbar_added = false;

        if (!toolbar) {
            toolbar = getMainWindow()->addToolBar(
                QApplication::translate("Workbench",
                                        toolbarName.c_str(),
                                        0, QApplication::UnicodeUTF8)); // i18n
            toolbar->setObjectName(QString::fromAscii((*it)->command().c_str()));
            toolbar->setVisible(visible);
            toolbar_added = true;
        }
        else {
            toolbar->setVisible(visible);
            toolbar->toggleViewAction()->setVisible(true);
            int index = toolbars.indexOf(toolbar);
            toolbars.removeAt(index);
        }

        // setup the toolbar
        setup(*it, toolbar);

        // try to add some breaks to avoid to have all toolbars in one line
        if (toolbar_added) {
            if (top_width > 0 && getMainWindow()->toolBarBreak(toolbar))
                top_width = 0;
            // the width() of a toolbar doesn't return useful results so we estimate
            // its size by the number of buttons and the icon size
            QList<QToolButton*> btns = toolbar->findChildren<QToolButton*>();
            top_width += (btns.size() * toolbar->iconSize().width());
            if (top_width > max_width) {
                top_width = 0;
                getMainWindow()->insertToolBarBreak(toolbar);
            }
        }
    }

    // hide all unneeded toolbars
    for (QList<QToolBar*>::Iterator it = toolbars.begin(); it != toolbars.end(); ++it) {
        // make sure that the main window has the focus when hiding the toolbar with
        // the combo box inside
        QWidget *fw = QApplication::focusWidget();
        while (fw &&  !fw->isWindow()) {
            if (fw == *it) {
                getMainWindow()->setFocus();
                break;
            }
            fw = fw->parentWidget();
        }
        // ignore toolbars which do not belong to the previously active workbench
        QByteArray toolbarName = (*it)->objectName().toUtf8();
        if (!(*it)->toggleViewAction()->isVisible())
            continue;
        hPref->SetBool(toolbarName.constData(), (*it)->isVisible());
        (*it)->hide();
        (*it)->toggleViewAction()->setVisible(false);
    }
}

void ToolBarManager::setup(ToolBarItem* item, QToolBar* toolbar) const
{
    CommandManager& mgr = Application::Instance->commandManager();
    QList<ToolBarItem*> items = item->getItems();
    QList<QAction*> actions = toolbar->actions();
    for (QList<ToolBarItem*>::ConstIterator it = items.begin(); it != items.end(); ++it) {
        // search for the action item
        QAction* action = findAction(actions, QString::fromAscii((*it)->command().c_str()));
        if (!action) {
            if ((*it)->command() == "Separator") {
                action = toolbar->addSeparator();
            } else {
                // Check if action was added successfully
                if (mgr.addTo((*it)->command().c_str(), toolbar))
                    action = toolbar->actions().last();
            }

            // set the tool button user data
            if (action) action->setData(QString::fromAscii((*it)->command().c_str()));
        } else {
            // Note: For toolbars we do not remove and readd the actions
            // because this causes flicker effects. So, it could happen that the order of
            // buttons doesn't match with the order of commands in the workbench.
            int index = actions.indexOf(action);
            actions.removeAt(index);
        }
    }

    // remove all tool buttons which we don't need for the moment
    for (QList<QAction*>::Iterator it = actions.begin(); it != actions.end(); ++it) {
        toolbar->removeAction(*it);
    }
}

void ToolBarManager::saveState() const
{
    ParameterGrp::handle hPref = App::GetApplication().GetUserParameter().GetGroup("BaseApp")
                               ->GetGroup("MainWindow")->GetGroup("Toolbars");

    QList<QToolBar*> toolbars = toolBars();
    for (QStringList::ConstIterator it = this->toolbarNames.begin(); it != this->toolbarNames.end(); ++it) {
        QToolBar* toolbar = findToolBar(toolbars, *it);
        if (toolbar) {
            QByteArray toolbarName = toolbar->objectName().toUtf8();
            hPref->SetBool(toolbarName.constData(), toolbar->isVisible());
        }
    }
}

void ToolBarManager::restoreState() const
{
    ParameterGrp::handle hPref = App::GetApplication().GetUserParameter().GetGroup("BaseApp")
                               ->GetGroup("MainWindow")->GetGroup("Toolbars");

    QList<QToolBar*> toolbars = toolBars();
    for (QStringList::ConstIterator it = this->toolbarNames.begin(); it != this->toolbarNames.end(); ++it) {
        QToolBar* toolbar = findToolBar(toolbars, *it);
        if (toolbar) {
            QByteArray toolbarName = toolbar->objectName().toUtf8();
            toolbar->setVisible(hPref->GetBool(toolbarName.constData(), toolbar->isVisible()));
        }
    }
}

void ToolBarManager::retranslate() const
{
    QList<QToolBar*> toolbars = toolBars();
    for (QList<QToolBar*>::Iterator it = toolbars.begin(); it != toolbars.end(); ++it) {
        QByteArray toolbarName = (*it)->objectName().toUtf8();
        (*it)->setWindowTitle(
            QApplication::translate("Workbench",
                                    (const char*)toolbarName,
                                    0, QApplication::UnicodeUTF8));
    }
}

QToolBar* ToolBarManager::findToolBar(const QList<QToolBar*>& toolbars, const QString& item) const
{
    for (QList<QToolBar*>::ConstIterator it = toolbars.begin(); it != toolbars.end(); ++it) {
        if ((*it)->objectName() == item)
            return *it;
    }

    return 0; // no item with the user data found
}

QAction* ToolBarManager::findAction(const QList<QAction*>& acts, const QString& item) const
{
    for (QList<QAction*>::ConstIterator it = acts.begin(); it != acts.end(); ++it) {
        if ((*it)->data().toString() == item)
            return *it;
    }

    return 0; // no item with the user data found
}

QList<QToolBar*> ToolBarManager::toolBars() const
{
    QWidget* mw = getMainWindow();
    QList<QToolBar*> tb;
    QList<QToolBar*> bars = getMainWindow()->findChildren<QToolBar*>();
    for (QList<QToolBar*>::ConstIterator it = bars.begin(); it != bars.end(); ++it) {
        if ((*it)->parentWidget() == mw)
            tb.push_back(*it);
    }

    return tb;
}
<commit_msg>+ proper encoding of custom toolbar names<commit_after>/***************************************************************************
 *   Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
# include <QApplication>
# include <QAction>
# include <QToolBar>
# include <QToolButton>
#endif

#include "ToolBarManager.h"
#include "MainWindow.h"
#include "Application.h"
#include "Command.h"

using namespace Gui;

ToolBarItem::ToolBarItem()
{
}

ToolBarItem::ToolBarItem(ToolBarItem* item)
{
    if ( item )
        item->appendItem(this);
}

ToolBarItem::~ToolBarItem()
{
    clear();
}

void ToolBarItem::setCommand(const std::string& name)
{
    _name = name;
}

std::string ToolBarItem::command() const
{
    return _name;
}

bool ToolBarItem::hasItems() const
{
    return _items.count() > 0;
}

ToolBarItem* ToolBarItem::findItem(const std::string& name)
{
    if ( _name == name ) {
        return this;
    } else {
        for ( QList<ToolBarItem*>::ConstIterator it = _items.begin(); it != _items.end(); ++it ) {
            if ( (*it)->_name == name ) {
                return *it;
            }
        }
    }

    return 0;
}

ToolBarItem* ToolBarItem::copy() const
{
    ToolBarItem* root = new ToolBarItem;
    root->setCommand( command() );

    QList<ToolBarItem*> items = getItems();
    for ( QList<ToolBarItem*>::ConstIterator it = items.begin(); it != items.end(); ++it ) {
        root->appendItem( (*it)->copy() );
    }

    return root;
}

uint ToolBarItem::count() const
{
    return _items.count();
}

void ToolBarItem::appendItem(ToolBarItem* item)
{
    _items.push_back( item );
}

bool ToolBarItem::insertItem( ToolBarItem* before, ToolBarItem* item)
{
    int pos = _items.indexOf(before);
    if (pos != -1) {
        _items.insert(pos, item);
        return true;
    } else
        return false;
}

void ToolBarItem::removeItem(ToolBarItem* item)
{
    int pos = _items.indexOf(item);
    if (pos != -1)
        _items.removeAt(pos);
}

void ToolBarItem::clear()
{
    for ( QList<ToolBarItem*>::Iterator it = _items.begin(); it != _items.end(); ++it ) {
        delete *it;
    }

    _items.clear();
}

ToolBarItem& ToolBarItem::operator << (ToolBarItem* item)
{
    appendItem(item);
    return *this;
}

ToolBarItem& ToolBarItem::operator << (const std::string& command)
{
    ToolBarItem* item = new ToolBarItem(this);
    item->setCommand(command);
    return *this;
}

QList<ToolBarItem*> ToolBarItem::getItems() const
{
    return _items;
}

// -----------------------------------------------------------

ToolBarManager* ToolBarManager::_instance=0;

ToolBarManager* ToolBarManager::getInstance()
{
    if ( !_instance )
        _instance = new ToolBarManager;
    return _instance;
}

void ToolBarManager::destruct()
{
    delete _instance;
    _instance = 0;
}

ToolBarManager::ToolBarManager()
{
}

ToolBarManager::~ToolBarManager()
{
}

void ToolBarManager::setup(ToolBarItem* toolBarItems)
{
    if (!toolBarItems)
        return; // empty menu bar

    saveState();
    this->toolbarNames.clear();

    int max_width = getMainWindow()->width();
    int top_width = 0;

    ParameterGrp::handle hPref = App::GetApplication().GetUserParameter().GetGroup("BaseApp")
                               ->GetGroup("MainWindow")->GetGroup("Toolbars");
    QList<ToolBarItem*> items = toolBarItems->getItems();
    QList<QToolBar*> toolbars = toolBars();
    for (QList<ToolBarItem*>::ConstIterator it = items.begin(); it != items.end(); ++it) {
        // search for the toolbar
        QString name = QString::fromUtf8((*it)->command().c_str());
        this->toolbarNames << name;
        QToolBar* toolbar = findToolBar(toolbars, name);
        std::string toolbarName = (*it)->command();
        bool visible = hPref->GetBool(toolbarName.c_str(), true);
        bool toolbar_added = false;

        if (!toolbar) {
            toolbar = getMainWindow()->addToolBar(
                QApplication::translate("Workbench",
                                        toolbarName.c_str(),
                                        0, QApplication::UnicodeUTF8)); // i18n
            toolbar->setObjectName(name);
            toolbar->setVisible(visible);
            toolbar_added = true;
        }
        else {
            toolbar->setVisible(visible);
            toolbar->toggleViewAction()->setVisible(true);
            int index = toolbars.indexOf(toolbar);
            toolbars.removeAt(index);
        }

        // setup the toolbar
        setup(*it, toolbar);

        // try to add some breaks to avoid to have all toolbars in one line
        if (toolbar_added) {
            if (top_width > 0 && getMainWindow()->toolBarBreak(toolbar))
                top_width = 0;
            // the width() of a toolbar doesn't return useful results so we estimate
            // its size by the number of buttons and the icon size
            QList<QToolButton*> btns = toolbar->findChildren<QToolButton*>();
            top_width += (btns.size() * toolbar->iconSize().width());
            if (top_width > max_width) {
                top_width = 0;
                getMainWindow()->insertToolBarBreak(toolbar);
            }
        }
    }

    // hide all unneeded toolbars
    for (QList<QToolBar*>::Iterator it = toolbars.begin(); it != toolbars.end(); ++it) {
        // make sure that the main window has the focus when hiding the toolbar with
        // the combo box inside
        QWidget *fw = QApplication::focusWidget();
        while (fw &&  !fw->isWindow()) {
            if (fw == *it) {
                getMainWindow()->setFocus();
                break;
            }
            fw = fw->parentWidget();
        }
        // ignore toolbars which do not belong to the previously active workbench
        QByteArray toolbarName = (*it)->objectName().toUtf8();
        if (!(*it)->toggleViewAction()->isVisible())
            continue;
        hPref->SetBool(toolbarName.constData(), (*it)->isVisible());
        (*it)->hide();
        (*it)->toggleViewAction()->setVisible(false);
    }
}

void ToolBarManager::setup(ToolBarItem* item, QToolBar* toolbar) const
{
    CommandManager& mgr = Application::Instance->commandManager();
    QList<ToolBarItem*> items = item->getItems();
    QList<QAction*> actions = toolbar->actions();
    for (QList<ToolBarItem*>::ConstIterator it = items.begin(); it != items.end(); ++it) {
        // search for the action item
        QAction* action = findAction(actions, QString::fromAscii((*it)->command().c_str()));
        if (!action) {
            if ((*it)->command() == "Separator") {
                action = toolbar->addSeparator();
            } else {
                // Check if action was added successfully
                if (mgr.addTo((*it)->command().c_str(), toolbar))
                    action = toolbar->actions().last();
            }

            // set the tool button user data
            if (action) action->setData(QString::fromAscii((*it)->command().c_str()));
        } else {
            // Note: For toolbars we do not remove and readd the actions
            // because this causes flicker effects. So, it could happen that the order of
            // buttons doesn't match with the order of commands in the workbench.
            int index = actions.indexOf(action);
            actions.removeAt(index);
        }
    }

    // remove all tool buttons which we don't need for the moment
    for (QList<QAction*>::Iterator it = actions.begin(); it != actions.end(); ++it) {
        toolbar->removeAction(*it);
    }
}

void ToolBarManager::saveState() const
{
    ParameterGrp::handle hPref = App::GetApplication().GetUserParameter().GetGroup("BaseApp")
                               ->GetGroup("MainWindow")->GetGroup("Toolbars");

    QList<QToolBar*> toolbars = toolBars();
    for (QStringList::ConstIterator it = this->toolbarNames.begin(); it != this->toolbarNames.end(); ++it) {
        QToolBar* toolbar = findToolBar(toolbars, *it);
        if (toolbar) {
            QByteArray toolbarName = toolbar->objectName().toUtf8();
            hPref->SetBool(toolbarName.constData(), toolbar->isVisible());
        }
    }
}

void ToolBarManager::restoreState() const
{
    ParameterGrp::handle hPref = App::GetApplication().GetUserParameter().GetGroup("BaseApp")
                               ->GetGroup("MainWindow")->GetGroup("Toolbars");

    QList<QToolBar*> toolbars = toolBars();
    for (QStringList::ConstIterator it = this->toolbarNames.begin(); it != this->toolbarNames.end(); ++it) {
        QToolBar* toolbar = findToolBar(toolbars, *it);
        if (toolbar) {
            QByteArray toolbarName = toolbar->objectName().toUtf8();
            toolbar->setVisible(hPref->GetBool(toolbarName.constData(), toolbar->isVisible()));
        }
    }
}

void ToolBarManager::retranslate() const
{
    QList<QToolBar*> toolbars = toolBars();
    for (QList<QToolBar*>::Iterator it = toolbars.begin(); it != toolbars.end(); ++it) {
        QByteArray toolbarName = (*it)->objectName().toUtf8();
        (*it)->setWindowTitle(
            QApplication::translate("Workbench",
                                    (const char*)toolbarName,
                                    0, QApplication::UnicodeUTF8));
    }
}

QToolBar* ToolBarManager::findToolBar(const QList<QToolBar*>& toolbars, const QString& item) const
{
    for (QList<QToolBar*>::ConstIterator it = toolbars.begin(); it != toolbars.end(); ++it) {
        if ((*it)->objectName() == item)
            return *it;
    }

    return 0; // no item with the user data found
}

QAction* ToolBarManager::findAction(const QList<QAction*>& acts, const QString& item) const
{
    for (QList<QAction*>::ConstIterator it = acts.begin(); it != acts.end(); ++it) {
        if ((*it)->data().toString() == item)
            return *it;
    }

    return 0; // no item with the user data found
}

QList<QToolBar*> ToolBarManager::toolBars() const
{
    QWidget* mw = getMainWindow();
    QList<QToolBar*> tb;
    QList<QToolBar*> bars = getMainWindow()->findChildren<QToolBar*>();
    for (QList<QToolBar*>::ConstIterator it = bars.begin(); it != bars.end(); ++it) {
        if ((*it)->parentWidget() == mw)
            tb.push_back(*it);
    }

    return tb;
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File: NekMatrixMetadata.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////

#ifndef NEKTAR_LIB_UTILITIES_NEK_MATRIX_METADATA_HPP
#define NEKTAR_LIB_UTILITIES_NEK_MATRIX_METADATA_HPP

#include <LibUtilities/BasicUtils/ErrorUtil.hpp>
#include <LibUtilities/ExpressionTemplates/BinaryOperators.hpp>
#include <LibUtilities/LinearAlgebra/NekMatrixFwd.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits.hpp>

namespace Nektar
{

     // Interface for expression templates.
     class NekMatrixMetadata
     {
         public:
            NekMatrixMetadata(const NekMatrixMetadata& rhs) :
                Rows(rhs.Rows),
                Columns(rhs.Columns),
                RequiredStorageSize(rhs.RequiredStorageSize)
            {
            }

            NekMatrixMetadata& operator=(const NekMatrixMetadata& rhs)
            {
                Rows = rhs.Rows;
                Columns = rhs.Columns;
                RequiredStorageSize = rhs.RequiredStorageSize;
                return *this;
            }

            unsigned int Rows;
            unsigned int Columns;
            unsigned int RequiredStorageSize;

         protected:

             NekMatrixMetadata(unsigned int r, unsigned int c, unsigned int storageSize) :
                Rows(r),
                Columns(c),
                RequiredStorageSize(storageSize)
            {
            }

             // To force the use of one of the subclasses without the overhead of
             // a pure virtual destructor.
             ~NekMatrixMetadata() {}

         private:
             NekMatrixMetadata() :
                 Rows(0),
                 Columns(0),
                 RequiredStorageSize(0)
             {
             }
     };

    class NekMatrixAdditionAndSubtractionMetadata : public NekMatrixMetadata
    {
        public:
            template<typename T, typename MatrixType>
            NekMatrixAdditionAndSubtractionMetadata(const NekMatrix<T, MatrixType>& lhs, const NekMatrixMetadata& rhs) :
                NekMatrixMetadata(rhs.Rows, rhs.Columns, rhs.RequiredStorageSize)
            {
                ASSERTL1(lhs.GetRows() == rhs.Rows && lhs.GetColumns() == rhs.Columns, "Matrix dimensions must agree.");
            }

            template<typename T, typename MatrixType>
            NekMatrixAdditionAndSubtractionMetadata(const NekMatrixMetadata& lhs, const NekMatrix<T, MatrixType>& rhs) :
                NekMatrixMetadata(lhs.Rows, lhs.Columns, lhs.RequiredStorageSize)
            {
                ASSERTL1(lhs.Rows == rhs.GetRows() && lhs.Columns == rhs.GetColumns(), "Matrix dimensions must agree.");
            }

            template<typename T>
            NekMatrixAdditionAndSubtractionMetadata(const DefaultExpressionMetadata<T>& lhs, const NekMatrixMetadata& rhs) :
                NekMatrixMetadata(rhs.Rows, rhs.Columns, rhs.RequiredStorageSize)
            {
            }

            template<typename T>
            NekMatrixAdditionAndSubtractionMetadata(const NekMatrixMetadata& lhs, const DefaultExpressionMetadata<T>& rhs) :
                NekMatrixMetadata(lhs.Rows, lhs.Columns, lhs.RequiredStorageSize)
            {
            }

            NekMatrixAdditionAndSubtractionMetadata(const NekMatrixMetadata& lhs, const NekMatrixMetadata& rhs) :
                NekMatrixMetadata(lhs.Rows, lhs.Columns, lhs.RequiredStorageSize)
            {
                ASSERTL1(lhs.Rows == rhs.Rows && lhs.Columns == rhs.Columns, "Matrix dimensions must agree.");
            }

            NekMatrixAdditionAndSubtractionMetadata(const NekMatrixAdditionAndSubtractionMetadata& rhs) :
                NekMatrixMetadata(rhs)
            {
            }

            NekMatrixAdditionAndSubtractionMetadata() :
                NekMatrixMetadata(0,0,0)
            {
            }

            NekMatrixAdditionAndSubtractionMetadata& operator=(const NekMatrixAdditionAndSubtractionMetadata& rhs)
            {
                NekMatrixMetadata::operator=(rhs);
                return *this;
            }
        private:

     };

     class NekMatrixMultiplicationMetadata : public NekMatrixMetadata
     {
         public:
            template<typename T, typename MatrixType>
            NekMatrixMultiplicationMetadata(const NekMatrix<T, MatrixType>& lhs, const NekMatrixMetadata& rhs) :
                NekMatrixMetadata(lhs.GetRows(), rhs.Columns,
                    std::max(lhs.GetRows()*rhs.Columns, rhs.RequiredStorageSize) )
            {
                ASSERTL1(lhs.GetColumns() == rhs.Rows, "Matrix dimensions must agree.");
            }

            template<typename T, typename MatrixType>
            NekMatrixMultiplicationMetadata(const NekMatrixMetadata& lhs, const NekMatrix<T, MatrixType>& rhs) :
                NekMatrixMetadata(lhs.Rows, rhs.GetColumns(),
                std::max(lhs.Rows*rhs.GetColumns(), lhs.RequiredStorageSize) )
            {
                ASSERTL1(lhs.Columns == rhs.GetRows(), "Matrix dimensions must agree.");
            }

            template<typename T>
            NekMatrixMultiplicationMetadata(const DefaultExpressionMetadata<T>& lhs, const NekMatrixMetadata& rhs) :
                NekMatrixMetadata(rhs.Rows, rhs.Columns, rhs.RequiredStorageSize)
            {
            }

            template<typename T>
            NekMatrixMultiplicationMetadata(const NekMatrixMetadata& lhs, const DefaultExpressionMetadata<T>& rhs) :
                NekMatrixMetadata(lhs.Rows, lhs.Columns, lhs.RequiredStorageSize)
            {
            }

            NekMatrixMultiplicationMetadata(const NekMatrixMetadata& lhs, const NekMatrixMetadata& rhs) :
                NekMatrixMetadata(lhs.Rows, rhs.Columns,
                    std::max(std::max(lhs.Rows*rhs.Columns, lhs.RequiredStorageSize), rhs.RequiredStorageSize))
            {
                ASSERTL1(lhs.Columns == rhs.Rows, "Matrix dimensions must agree.");
            }

            NekMatrixMultiplicationMetadata(const NekMatrixMultiplicationMetadata& rhs) :
                NekMatrixMetadata(rhs)
            {
            }

            NekMatrixMultiplicationMetadata() :
                NekMatrixMetadata(0,0,0)
            {
            }

            NekMatrixMultiplicationMetadata& operator=(const NekMatrixMultiplicationMetadata& rhs)
            {
                NekMatrixMetadata::operator=(rhs);
                return *this;
            }
         private:

     };

     class NekMatrixConstantMetadata : public NekMatrixMetadata
     {
         public:
             template<typename MatrixType>
             explicit NekMatrixConstantMetadata(const MatrixType& matrix) :
                 NekMatrixMetadata(matrix.GetRows(), matrix.GetColumns(),
                    matrix.GetRows()*matrix.GetColumns())
             {
             }

             NekMatrixConstantMetadata(const NekMatrixConstantMetadata& rhs) :
                 NekMatrixMetadata(rhs)
             {
             }

             NekMatrixConstantMetadata() :
                 NekMatrixMetadata(0, 0, 0)
             {
             }

             NekMatrixConstantMetadata& operator=(const NekMatrixConstantMetadata& rhs)
             {
                 NekMatrixMetadata::operator=(rhs);
                 return *this;
             }
         private:

     };
//
//
//
//
//     class NekBlockMatrixMetadata
//     {
//         public:
//             template<typename MatrixType>
//             explicit NekBlockMatrixMetadata(const MatrixType& matrix) :
//                 Rows(matrix.GetRows()),
//                 Columns(matrix.GetColumns()),
//                 BlockRows(matrix.GetBlockRows()),
//                 BlockColumns(matrix.GetBlockColumns())
//             {
//             }
//
//             NekBlockMatrixMetadata(const NekBlockMatrixMetadata& rhs) :
//                 Rows(rhs.Rows),
//                 Columns(rhs.Columns),
//                 BlockRows(rhs.BlockRows),
//                 BlockColumns(rhs.BlockColumns)
//             {
//             }
//
//             static NekBlockMatrixMetadata CreateForNegation(const NekBlockMatrixMetadata& rhs)
//             {
//                 return NekBlockMatrixMetadata(rhs);
//             }
//
//             static NekBlockMatrixMetadata CreateForAddition(const NekBlockMatrixMetadata& lhs, const NekBlockMatrixMetadata& rhs)
//             {
//                 ASSERTL1(lhs.Rows == rhs.Rows && lhs.Columns == rhs.Columns, "Matrix dimensions must agree in operator+");
//                 ASSERTL1(lhs.BlockRows == rhs.BlockRows && lhs.BlockColumns == rhs.BlockColumns, "Matrix block dimensions must agree in operator+");
//                 return NekBlockMatrixMetadata(lhs);
//             }
//
// //             static NekBlockMatrixMetadata CreateForMultiplication(const NekBlockMatrixMetadata& lhs, const NekBlockMatrixMetadata& rhs)
// //             {
// //                 ASSERTL1(lhs.Columns == rhs.Rows, "Matrix dimensions must agree in operator*");
// //                 NekBlockMatrixMetadata result;
// //                 result.Rows = lhs.Rows;
// //                 result.Columns = rhs.Columns;
// //                 return result;
// //             }
//
//             NekBlockMatrixMetadata& operator=(const NekBlockMatrixMetadata& rhs)
//             {
//                 Rows = rhs.Rows;
//                 Columns = rhs.Columns;
//                 BlockRows = rhs.BlockRows;
//                 BlockColumns = rhs.BlockColumns;
//                 return *this;
//             }
//
//             unsigned int Rows;
//             unsigned int Columns;
//             std::vector<unsigned int> BlockRows;
//             std::vector<unsigned int> BlockColumns;
//
//         private:
//             NekBlockMatrixMetadata() :
//                 Rows(0),
//                 Columns(0),
//                 BlockRows(),
//                 BlockColumns()
//             {
//             }
//     };
}

#endif //NEKTAR_LIB_UTILITIES_NEK_MATRIX_METADATA_HPP

/**
    $Log: NekMatrixMetadata.hpp,v $
    Revision 1.10  2008/01/20 03:59:36  bnelson
    Expression template updates.

    Revision 1.9  2007/10/03 03:00:14  bnelson
    Added precompiled headers.

    Revision 1.8  2007/08/16 02:11:57  bnelson
    *** empty log message ***

    Revision 1.7  2007/06/10 23:42:16  bnelson
    Matrix updates.

    Revision 1.6  2007/01/16 05:30:34  bnelson
    Major improvements for expression templates.

    Revision 1.5  2006/11/08 04:16:14  bnelson
    Added subtraction operators.

    Revision 1.4  2006/10/30 05:11:16  bnelson
    Added preliminary linear system and block matrix support.

    Revision 1.3  2006/09/30 15:18:37  bnelson
    no message

    Revision 1.2  2006/09/14 02:06:16  bnelson
    Fixed gcc compiler errors.

    Revision 1.1  2006/09/11 03:26:27  bnelson
    Updated to use new policy based expression templates.

 **/

<commit_msg>Fixed visual studio compile errors.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File: NekMatrixMetadata.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////

#ifndef NEKTAR_LIB_UTILITIES_NEK_MATRIX_METADATA_HPP
#define NEKTAR_LIB_UTILITIES_NEK_MATRIX_METADATA_HPP

#include <LibUtilities/BasicUtils/ErrorUtil.hpp>
#include <LibUtilities/ExpressionTemplates/BinaryOperators.hpp>
#include <LibUtilities/LinearAlgebra/NekMatrixFwd.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits.hpp>

#ifdef max
#undef max
#endif

#ifdef min
#undef min
#endif

namespace Nektar
{

     // Interface for expression templates.
     class NekMatrixMetadata
     {
         public:
            NekMatrixMetadata(const NekMatrixMetadata& rhs) :
                Rows(rhs.Rows),
                Columns(rhs.Columns),
                RequiredStorageSize(rhs.RequiredStorageSize)
            {
            }

            NekMatrixMetadata& operator=(const NekMatrixMetadata& rhs)
            {
                Rows = rhs.Rows;
                Columns = rhs.Columns;
                RequiredStorageSize = rhs.RequiredStorageSize;
                return *this;
            }

            unsigned int Rows;
            unsigned int Columns;
            unsigned int RequiredStorageSize;

         protected:

             NekMatrixMetadata(unsigned int r, unsigned int c, unsigned int storageSize) :
                Rows(r),
                Columns(c),
                RequiredStorageSize(storageSize)
            {
            }

             // To force the use of one of the subclasses without the overhead of
             // a pure virtual destructor.
             ~NekMatrixMetadata() {}

         private:
             NekMatrixMetadata() :
                 Rows(0),
                 Columns(0),
                 RequiredStorageSize(0)
             {
             }
     };

    class NekMatrixAdditionAndSubtractionMetadata : public NekMatrixMetadata
    {
        public:
            template<typename T, typename MatrixType>
            NekMatrixAdditionAndSubtractionMetadata(const NekMatrix<T, MatrixType>& lhs, const NekMatrixMetadata& rhs) :
                NekMatrixMetadata(rhs.Rows, rhs.Columns, rhs.RequiredStorageSize)
            {
                ASSERTL1(lhs.GetRows() == rhs.Rows && lhs.GetColumns() == rhs.Columns, "Matrix dimensions must agree.");
            }

            template<typename T, typename MatrixType>
            NekMatrixAdditionAndSubtractionMetadata(const NekMatrixMetadata& lhs, const NekMatrix<T, MatrixType>& rhs) :
                NekMatrixMetadata(lhs.Rows, lhs.Columns, lhs.RequiredStorageSize)
            {
                ASSERTL1(lhs.Rows == rhs.GetRows() && lhs.Columns == rhs.GetColumns(), "Matrix dimensions must agree.");
            }

            template<typename T>
            NekMatrixAdditionAndSubtractionMetadata(const DefaultExpressionMetadata<T>& lhs, const NekMatrixMetadata& rhs) :
                NekMatrixMetadata(rhs.Rows, rhs.Columns, rhs.RequiredStorageSize)
            {
            }

            template<typename T>
            NekMatrixAdditionAndSubtractionMetadata(const NekMatrixMetadata& lhs, const DefaultExpressionMetadata<T>& rhs) :
                NekMatrixMetadata(lhs.Rows, lhs.Columns, lhs.RequiredStorageSize)
            {
            }

            NekMatrixAdditionAndSubtractionMetadata(const NekMatrixMetadata& lhs, const NekMatrixMetadata& rhs) :
                NekMatrixMetadata(lhs.Rows, lhs.Columns, lhs.RequiredStorageSize)
            {
                ASSERTL1(lhs.Rows == rhs.Rows && lhs.Columns == rhs.Columns, "Matrix dimensions must agree.");
            }

            NekMatrixAdditionAndSubtractionMetadata(const NekMatrixAdditionAndSubtractionMetadata& rhs) :
                NekMatrixMetadata(rhs)
            {
            }

            NekMatrixAdditionAndSubtractionMetadata() :
                NekMatrixMetadata(0,0,0)
            {
            }

            NekMatrixAdditionAndSubtractionMetadata& operator=(const NekMatrixAdditionAndSubtractionMetadata& rhs)
            {
                NekMatrixMetadata::operator=(rhs);
                return *this;
            }
        private:

     };

     class NekMatrixMultiplicationMetadata : public NekMatrixMetadata
     {
         public:
            template<typename T, typename MatrixType>
            NekMatrixMultiplicationMetadata(const NekMatrix<T, MatrixType>& lhs, const NekMatrixMetadata& rhs) :
                NekMatrixMetadata(lhs.GetRows(), rhs.Columns,
                    std::max(lhs.GetRows()*rhs.Columns, rhs.RequiredStorageSize) )
            {
                ASSERTL1(lhs.GetColumns() == rhs.Rows, "Matrix dimensions must agree.");
            }

            template<typename T, typename MatrixType>
            NekMatrixMultiplicationMetadata(const NekMatrixMetadata& lhs, const NekMatrix<T, MatrixType>& rhs) :
                NekMatrixMetadata(lhs.Rows, rhs.GetColumns(),
                std::max(lhs.Rows*rhs.GetColumns(), lhs.RequiredStorageSize) )
            {
                ASSERTL1(lhs.Columns == rhs.GetRows(), "Matrix dimensions must agree.");
            }

            template<typename T>
            NekMatrixMultiplicationMetadata(const DefaultExpressionMetadata<T>& lhs, const NekMatrixMetadata& rhs) :
                NekMatrixMetadata(rhs.Rows, rhs.Columns, rhs.RequiredStorageSize)
            {
            }

            template<typename T>
            NekMatrixMultiplicationMetadata(const NekMatrixMetadata& lhs, const DefaultExpressionMetadata<T>& rhs) :
                NekMatrixMetadata(lhs.Rows, lhs.Columns, lhs.RequiredStorageSize)
            {
            }

            NekMatrixMultiplicationMetadata(const NekMatrixMetadata& lhs, const NekMatrixMetadata& rhs) :
                NekMatrixMetadata(lhs.Rows, rhs.Columns,
                    std::max(std::max(lhs.Rows*rhs.Columns, lhs.RequiredStorageSize), rhs.RequiredStorageSize))
            {
                ASSERTL1(lhs.Columns == rhs.Rows, "Matrix dimensions must agree.");
            }

            NekMatrixMultiplicationMetadata(const NekMatrixMultiplicationMetadata& rhs) :
                NekMatrixMetadata(rhs)
            {
            }

            NekMatrixMultiplicationMetadata() :
                NekMatrixMetadata(0,0,0)
            {
            }

            NekMatrixMultiplicationMetadata& operator=(const NekMatrixMultiplicationMetadata& rhs)
            {
                NekMatrixMetadata::operator=(rhs);
                return *this;
            }
         private:

     };

     class NekMatrixConstantMetadata : public NekMatrixMetadata
     {
         public:
             template<typename MatrixType>
             explicit NekMatrixConstantMetadata(const MatrixType& matrix) :
                 NekMatrixMetadata(matrix.GetRows(), matrix.GetColumns(),
                    matrix.GetRows()*matrix.GetColumns())
             {
             }

             NekMatrixConstantMetadata(const NekMatrixConstantMetadata& rhs) :
                 NekMatrixMetadata(rhs)
             {
             }

             NekMatrixConstantMetadata() :
                 NekMatrixMetadata(0, 0, 0)
             {
             }

             NekMatrixConstantMetadata& operator=(const NekMatrixConstantMetadata& rhs)
             {
                 NekMatrixMetadata::operator=(rhs);
                 return *this;
             }
         private:

     };
//
//
//
//
//     class NekBlockMatrixMetadata
//     {
//         public:
//             template<typename MatrixType>
//             explicit NekBlockMatrixMetadata(const MatrixType& matrix) :
//                 Rows(matrix.GetRows()),
//                 Columns(matrix.GetColumns()),
//                 BlockRows(matrix.GetBlockRows()),
//                 BlockColumns(matrix.GetBlockColumns())
//             {
//             }
//
//             NekBlockMatrixMetadata(const NekBlockMatrixMetadata& rhs) :
//                 Rows(rhs.Rows),
//                 Columns(rhs.Columns),
//                 BlockRows(rhs.BlockRows),
//                 BlockColumns(rhs.BlockColumns)
//             {
//             }
//
//             static NekBlockMatrixMetadata CreateForNegation(const NekBlockMatrixMetadata& rhs)
//             {
//                 return NekBlockMatrixMetadata(rhs);
//             }
//
//             static NekBlockMatrixMetadata CreateForAddition(const NekBlockMatrixMetadata& lhs, const NekBlockMatrixMetadata& rhs)
//             {
//                 ASSERTL1(lhs.Rows == rhs.Rows && lhs.Columns == rhs.Columns, "Matrix dimensions must agree in operator+");
//                 ASSERTL1(lhs.BlockRows == rhs.BlockRows && lhs.BlockColumns == rhs.BlockColumns, "Matrix block dimensions must agree in operator+");
//                 return NekBlockMatrixMetadata(lhs);
//             }
//
// //             static NekBlockMatrixMetadata CreateForMultiplication(const NekBlockMatrixMetadata& lhs, const NekBlockMatrixMetadata& rhs)
// //             {
// //                 ASSERTL1(lhs.Columns == rhs.Rows, "Matrix dimensions must agree in operator*");
// //                 NekBlockMatrixMetadata result;
// //                 result.Rows = lhs.Rows;
// //                 result.Columns = rhs.Columns;
// //                 return result;
// //             }
//
//             NekBlockMatrixMetadata& operator=(const NekBlockMatrixMetadata& rhs)
//             {
//                 Rows = rhs.Rows;
//                 Columns = rhs.Columns;
//                 BlockRows = rhs.BlockRows;
//                 BlockColumns = rhs.BlockColumns;
//                 return *this;
//             }
//
//             unsigned int Rows;
//             unsigned int Columns;
//             std::vector<unsigned int> BlockRows;
//             std::vector<unsigned int> BlockColumns;
//
//         private:
//             NekBlockMatrixMetadata() :
//                 Rows(0),
//                 Columns(0),
//                 BlockRows(),
//                 BlockColumns()
//             {
//             }
//     };
}

#endif //NEKTAR_LIB_UTILITIES_NEK_MATRIX_METADATA_HPP

/**
    $Log: NekMatrixMetadata.hpp,v $
    Revision 1.11  2008/11/11 03:35:07  bnelson
    Updated NekMatrix metadata to capture the largest matrix size during an expression.

    Revision 1.10  2008/01/20 03:59:36  bnelson
    Expression template updates.

    Revision 1.9  2007/10/03 03:00:14  bnelson
    Added precompiled headers.

    Revision 1.8  2007/08/16 02:11:57  bnelson
    *** empty log message ***

    Revision 1.7  2007/06/10 23:42:16  bnelson
    Matrix updates.

    Revision 1.6  2007/01/16 05:30:34  bnelson
    Major improvements for expression templates.

    Revision 1.5  2006/11/08 04:16:14  bnelson
    Added subtraction operators.

    Revision 1.4  2006/10/30 05:11:16  bnelson
    Added preliminary linear system and block matrix support.

    Revision 1.3  2006/09/30 15:18:37  bnelson
    no message

    Revision 1.2  2006/09/14 02:06:16  bnelson
    Fixed gcc compiler errors.

    Revision 1.1  2006/09/11 03:26:27  bnelson
    Updated to use new policy based expression templates.

 **/

<|endoftext|>


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

#include <malloc.h>
#include <iostream>
#include <pty.h>
#include <stdlib.h>
#include <string.h>

#include "Shibuya.hh"
#include "Terminal.hh"

#include "conf/term.hh"

#define GET_OFFSET(x, y) ( ( y * this->width ) + x )
/* This is in here because it's:
   a) only used in here
   b) very dependent on this exact impl */

void Terminal::_init_Terminal(int width, int height) {
	this->width  = width;
	this->height = height;
	this->cX     = 0;
	this->cY     = 0;
	this->cMode  = 0x70;
	/* 11100000 = 0x70 (112)
	   FFF BBB */

	this->scroll_frame_bottom = this->height;
	this->scroll_frame_top   = 0;

	this->pty    = -1;

	this->chars = (TerminalCell*)
		malloc(sizeof(TerminalCell) * (width * height));

	for ( int i = 0; i < ( height * width ); ++i ) {
		this->chars[i].ch   = ' ';
		this->chars[i].attr = this->cMode;
	}
}

Terminal::~Terminal() {

}

Terminal::Terminal() {
	this->_init_Terminal(80, 25);
}

Terminal::Terminal( int width, int height ) {
	this->_init_Terminal(width, height);
}

void Terminal::erase_to_from( int iX, int iY, int tX, int tY ) {

	iY--;
	tY--;

	int from = GET_OFFSET(iX, iY);
	int to   = GET_OFFSET(tX, tY);

	for ( int i = from - 1; i < to; ++i ) {
		this->chars[i].ch   = ' ';
		this->chars[i].attr = 0x70;
	}
}

void Terminal::scroll_up() {
	for (
		int iy = this->scroll_frame_top + 1;
		iy < this->scroll_frame_bottom;
		iy++
	) {
		for ( int ix = 0; ix < this->width; ++ix ) {
			int thisChar = GET_OFFSET(ix, iy);
			int lastChar = GET_OFFSET(ix, (iy - 1));
			this->chars[lastChar].ch   = this->chars[thisChar].ch;
			this->chars[lastChar].attr = this->chars[thisChar].attr;
		}
	}
	for ( int ix = 0; ix < this->width; ++ix ) {
		int offset = GET_OFFSET( ix, (this->scroll_frame_bottom - 1) );
		this->chars[offset].ch = ' ';
		this->chars[offset].attr = 0x70;
	}
}

void Terminal::render( WINDOW * win ) {
	for ( int iy = 0; iy < this->height; ++iy ) {
		for ( int ix = 0; ix  < this->width; ++ix ) {
			int offset = GET_OFFSET(ix, iy);
			mvwaddch(win, iy, ix, this->chars[offset].ch);
		}
	}
}

pid_t Terminal::fork( const char * command ) {

	struct winsize ws;

	ws.ws_row    = this->height;
	ws.ws_col    = this->width;
	ws.ws_xpixel = 0;
	ws.ws_ypixel = 0;

	pid_t childpid = forkpty(&this->pty, NULL, NULL, &ws);
	if (childpid < 0) return -1;

	if (childpid == 0) {
		setenv("TERM", TERMINAL_ENV_NAME, 1);
		execl("/bin/sh", "/bin/sh", "-c", command, NULL); // XXX: Choose shell better
		std::cerr << "Failed to fork." << std::endl;
		exit(127);
	}
	/* if we got here we are the parent process */
	this->childpid = childpid;
	return childpid;
}

void Terminal::poke() {
	fd_set ifs;
	struct timeval tvzero;
	char buf[512];
	int bytesread;
	int n = 5; // XXX: Fix?

	if (this->pty < 0)
		return;
	while (n--) {
		FD_ZERO(&ifs);
		FD_SET(this->pty, &ifs);

		tvzero.tv_sec  = 0;
		tvzero.tv_usec = 0;

		if (select(this->pty + 1, &ifs, NULL, NULL, &tvzero) <= 0)
			return;

		bytesread = read(this->pty, buf, 512);
		if (bytesread <= 0)
			return;

		for ( int i = 0; i < bytesread; ++i )
			this->insert( buf[i] );
	}
}

void Terminal::insert( unsigned char c ) {

	int ix = this->cX;
	int iy = this->cY;
	/*
	 * XXX: Why was the math using this->cX failing?
	 * for some reason we have to bring it into the local
	 * scope...
	 */
	int offset = GET_OFFSET(ix, iy);

	this->chars[offset].ch   = c;
	this->chars[offset].attr = this->cMode;
	this->advance_curs();
}

void Terminal::type( char c ) {
	write(this->pty, &c, 1);
}

void Terminal::advance_curs() {
	this->cX++;

	if ( this->width <= this->cX ) {
		this->cX = 0;
		this->cY++;
	}

	if ( this->height <= this->cY ) {
		this->cY = (this->height - 1);
		this->scroll_up();
	}
}

int Terminal::get_width() {
	return this->width;
}

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

#include <malloc.h>
#include <iostream>
#include <pty.h>
#include <stdlib.h>
#include <string.h>

#include "Shibuya.hh"
#include "Terminal.hh"

#include "conf/term.hh"

#define GET_OFFSET(x, y) ( ( y * this->width ) + x )
/* This is in here because it's:
   a) only used in here
   b) very dependent on this exact impl */

void Terminal::_init_Terminal(int width, int height) {
	this->width  = width;
	this->height = height;
	this->cX     = 0;
	this->cY     = 0;
	this->cMode  = 0x70;
	/* 11100000 = 0x70 (112)
	   FFF BBB */

	this->scroll_frame_bottom = this->height;
	this->scroll_frame_top   = 0;

	this->pty    = -1;

	this->chars = (TerminalCell*)
		malloc(sizeof(TerminalCell) * (width * height));

	for ( int i = 0; i < ( height * width ); ++i ) {
		this->chars[i].ch   = ' ';
		this->chars[i].attr = this->cMode;
	}
}

Terminal::~Terminal() {

}

Terminal::Terminal() {
	this->_init_Terminal(80, 25);
}

Terminal::Terminal( int width, int height ) {
	this->_init_Terminal(width, height);
}

void Terminal::erase_to_from( int iX, int iY, int tX, int tY ) {

	iY--;
	tY--;

	int from = GET_OFFSET(iX, iY);
	int to   = GET_OFFSET(tX, tY);

	for ( int i = from - 1; i < to; ++i ) {
		this->chars[i].ch   = ' ';
		this->chars[i].attr = 0x70;
	}
}

void Terminal::scroll_up() {
	for (
		int iy = this->scroll_frame_top + 1;
		iy < this->scroll_frame_bottom;
		iy++
	) {
		for ( int ix = 0; ix < this->width; ++ix ) {
			int thisChar = GET_OFFSET(ix, iy);
			int lastChar = GET_OFFSET(ix, (iy - 1));
			this->chars[lastChar].ch   = this->chars[thisChar].ch;
			this->chars[lastChar].attr = this->chars[thisChar].attr;
		}
	}
	for ( int ix = 0; ix < this->width; ++ix ) {
		int offset = GET_OFFSET( ix, (this->scroll_frame_bottom - 1) );
		this->chars[offset].ch = ' ';
		this->chars[offset].attr = 0x70;
	}
}

void Terminal::render( WINDOW * win ) {
	for ( int iy = 0; iy < this->height; ++iy ) {
		for ( int ix = 0; ix  < this->width; ++ix ) {
			int offset = GET_OFFSET(ix, iy);
			mvwaddch(win, iy, ix, this->chars[offset].ch);
		}
	}
}

pid_t Terminal::fork( const char * command ) {

	struct winsize ws;

	ws.ws_row    = this->height;
	ws.ws_col    = this->width;
	ws.ws_xpixel = 0;
	ws.ws_ypixel = 0;

	pid_t childpid = forkpty(&this->pty, NULL, NULL, &ws);
	if (childpid < 0) return -1;

	if (childpid == 0) {
		setenv("TERM", TERMINAL_ENV_NAME, 1);
		execl("/bin/sh", "/bin/sh", "-c", command, NULL); // XXX: Choose shell better
		std::cerr << "Failed to fork." << std::endl;
		exit(127);
	}
	/* if we got here we are the parent process */
	this->childpid = childpid;
	return childpid;
}

void Terminal::poke() {
	/* This is ripped off from librote */

	fd_set         ifs;
	struct timeval tvzero;

	char  buf[512];
	int   bytesread;
	int   n = 5; // XXX: Fix?

	if (this->pty < 0)
		return;

	while (n--) {
		FD_ZERO(&ifs);
		FD_SET(this->pty, &ifs);

		tvzero.tv_sec  = 0;
		tvzero.tv_usec = 0;

		if (select(this->pty + 1, &ifs, NULL, NULL, &tvzero) <= 0)
			return;

		bytesread = read(this->pty, buf, 512);
		if (bytesread <= 0)
			return;

		for ( int i = 0; i < bytesread; ++i )
			this->insert( buf[i] );
	}
}

void Terminal::insert( unsigned char c ) {

	int ix = this->cX;
	int iy = this->cY;
	/*
	 * XXX: Why was the math using this->cX failing?
	 * for some reason we have to bring it into the local
	 * scope...
	 */
	int offset = GET_OFFSET(ix, iy);

	this->chars[offset].ch   = c;
	this->chars[offset].attr = this->cMode;
	this->advance_curs();
}

void Terminal::type( char c ) {
	write(this->pty, &c, 1);
}

void Terminal::advance_curs() {
	this->cX++;

	if ( this->width <= this->cX ) {
		this->cX = 0;
		this->cY++;
	}

	if ( this->height <= this->cY ) {
		this->cY = (this->height - 1);
		this->scroll_up();
	}
}

int Terminal::get_width() {
	return this->width;
}

int Terminal::get_height() {
	return this->height;
}
<|endoftext|>


<commit_before>AliAnalysisTaskUPCforward* AddTaskUPCforward( TString name = "name", Int_t _fSetSingleMuonPt = 0, const char* suffix = "" )
{
    // TString name = "UPCforward";
    // TString combinedName;
    // combinedName.Form("ADcheck_%s", suffix);

    // get the manager via the static access member. since it's static, you don't need
    // to create an instance of the class here to call the function
    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
    if (!mgr) {
        return 0x0;
    }
    // get the input event handler, again via a static method.
    // this handler is part of the managing system and feeds events
    // to your task
    if (!mgr->GetInputEventHandler()) {
        return 0x0;
    }
    // by default, a file is open for writing. here, we get the filename
    TString fileName = AliAnalysisManager::GetCommonFileName();
    fileName += ":MyTask";      // create a subfolder in the file
    // fileName += ":MyTask";      // create a subfolder in the file
    // now we create an instance of your task
    // AliAnalysisTaskUPCforward* task = new AliAnalysisTaskUPCforward(name.Data(), _fSetSingleMuonPt);
    AliAnalysisTaskUPCforward* task = new AliAnalysisTaskUPCforward(Form("MyOutputContainer%s", suffix), _fSetSingleMuonPt);
    if(!task) return 0x0;
    // task->SelectCollisionCandidates(AliVEvent::kAnyINT);     // Physics Selection used by "everybody" but NOT in UPC
    // add your task to the manager
    mgr->AddTask(task);
    // your task needs input: here we connect the manager to your task
    mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());
    // same for the output
    mgr->ConnectOutput(task,1,mgr->CreateContainer(Form("MyOutputContainer%s", suffix), TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
    // in the end, this macro returns a pointer to your task. this will be convenient later on
    // when you will run your analysis in an analysis train on grid
    return task;
}
<commit_msg>Another attempt with a different name...<commit_after>AliAnalysisTaskUPCforward* AddTaskUPCforward( /*TString name = "name",*/ Int_t _fSetSingleMuonPt = 0, const char* suffix = "" )
{
    TString name = "PolarisationSys";
    TString combinedName;
    combinedName.Form("PolarisationSys_%s", suffix);

    // get the manager via the static access member. since it's static, you don't need
    // to create an instance of the class here to call the function
    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
    if (!mgr) {
        return 0x0;
    }
    // get the input event handler, again via a static method.
    // this handler is part of the managing system and feeds events
    // to your task
    if (!mgr->GetInputEventHandler()) {
        return 0x0;
    }
    // by default, a file is open for writing. here, we get the filename
    TString fileName = AliAnalysisManager::GetCommonFileName();
    fileName += ":MyTask";      // create a subfolder in the file
    // fileName += ":MyTask";      // create a subfolder in the file
    // now we create an instance of your task
    AliAnalysisTaskUPCforward* task = new AliAnalysisTaskUPCforward(combinedName.Data(), _fSetSingleMuonPt);
    // AliAnalysisTaskUPCforward* task = new AliAnalysisTaskUPCforward(Form("MyOutputContainer%s", suffix), _fSetSingleMuonPt);
    if(!task) return 0x0;
    // task->SelectCollisionCandidates(AliVEvent::kAnyINT);     // Physics Selection used by "everybody" but NOT in UPC
    // add your task to the manager
    mgr->AddTask(task);
    // your task needs input: here we connect the manager to your task
    mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());
    // same for the output
    mgr->ConnectOutput(task,1,mgr->CreateContainer(combinedName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
    // mgr->ConnectOutput(task,1,mgr->CreateContainer(Form("MyOutputContainer%s", suffix), TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
    // in the end, this macro returns a pointer to your task. this will be convenient later on
    // when you will run your analysis in an analysis train on grid
    return task;
}
<|endoftext|>


<commit_before>#include "bezieredge.h"

#include "edgearrow.h"
#include "node.h"
#include "plug.h"

namespace zodiac {

qreal BezierEdge::s_maxCtrlDistance = 150.;
qreal BezierEdge::s_ctrlExpansionFactor = 0.4;

BezierEdge::BezierEdge(Scene* scene)
    : BaseEdge(scene)
    , m_startPoint(QPointF())
    , m_ctrlPoint1(QPointF())
    , m_ctrlPoint2(QPointF())
    , m_endPoint(QPointF())
{
    // initialize the shape of the edge
    updateShape();
}

void BezierEdge::placeArrowAt(qreal fraction)
{
    /// Technically, you cannot place the arrow all the way at the end of the edge because at that point, the spline
    /// would not have a tangent to orient the arrow to.
    /// We could of course say that if fraction >= 1.0-VERY_SMALL_DELTA, the direction would have to be
    /// calculated using a point before the position ... but why bother?
    /// It doesn't make a visual difference and would only introduce unnecessary code branching.
    static const qreal VERY_SMALL_DELTA = 0.00001;

    qreal pos = qMin(1.0-VERY_SMALL_DELTA, qMax(0.0, fraction));
    QPointF edgeCenter = m_path.pointAtPercent(pos);
    QPointF edgeDirection = m_path.pointAtPercent(qMin(pos+VERY_SMALL_DELTA, 1.))-edgeCenter;
    m_arrow->setTransformation(edgeCenter, atan2(edgeDirection.y(), edgeDirection.x()));
}

void BezierEdge::updateShape()
{
    prepareGeometryChange();

    // create the path
    QPainterPath bezierPath;
    bezierPath.moveTo(m_startPoint);
    bezierPath.cubicTo(m_ctrlPoint1, m_ctrlPoint2, m_endPoint);
    m_path.swap(bezierPath);

    placeArrowAt(0.5);
}

QPointF BezierEdge::getCtrlPointFor(Plug* plug)
{
    qreal factor;
    switch (plug->getDirection()) {
    case PlugDirection::IN:
        factor = plug->getNode()->getIncomingExpansionFactor();
        break;
    case PlugDirection::OUT:
        factor = plug->getNode()->getOutgoingExpansionFactor();
        break;
    case PlugDirection::BOTH:
        factor = qMax(plug->getNode()->getIncomingExpansionFactor(), plug->getNode()->getOutgoingExpansionFactor());
        break;
    default:
        factor = 0.0;       //
        Q_ASSERT(false);    // we shouldn't ever reach these lines..
    }

    // calculate the control point distance
    qreal manhattanLength = (m_endPoint-m_startPoint).manhattanLength();
    qreal ctrlDistance = qMin(s_maxCtrlDistance, manhattanLength*s_ctrlExpansionFactor);
    return plug->scenePos()+((plug->getNormal()*ctrlDistance).toPointF()*factor);
}

} // namespace zodiac
<commit_msg>Include cmath to use atan2<commit_after>#include "bezieredge.h"

#include "edgearrow.h"
#include "node.h"
#include "plug.h"

#include <cmath>

namespace zodiac {

qreal BezierEdge::s_maxCtrlDistance = 150.;
qreal BezierEdge::s_ctrlExpansionFactor = 0.4;

BezierEdge::BezierEdge(Scene* scene)
    : BaseEdge(scene)
    , m_startPoint(QPointF())
    , m_ctrlPoint1(QPointF())
    , m_ctrlPoint2(QPointF())
    , m_endPoint(QPointF())
{
    // initialize the shape of the edge
    updateShape();
}

void BezierEdge::placeArrowAt(qreal fraction)
{
    /// Technically, you cannot place the arrow all the way at the end of the edge because at that point, the spline
    /// would not have a tangent to orient the arrow to.
    /// We could of course say that if fraction >= 1.0-VERY_SMALL_DELTA, the direction would have to be
    /// calculated using a point before the position ... but why bother?
    /// It doesn't make a visual difference and would only introduce unnecessary code branching.
    static const qreal VERY_SMALL_DELTA = 0.00001;

    qreal pos = qMin(1.0-VERY_SMALL_DELTA, qMax(0.0, fraction));
    QPointF edgeCenter = m_path.pointAtPercent(pos);
    QPointF edgeDirection = m_path.pointAtPercent(qMin(pos+VERY_SMALL_DELTA, 1.))-edgeCenter;
    m_arrow->setTransformation(edgeCenter, std::atan2(edgeDirection.y(), edgeDirection.x()));
}

void BezierEdge::updateShape()
{
    prepareGeometryChange();

    // create the path
    QPainterPath bezierPath;
    bezierPath.moveTo(m_startPoint);
    bezierPath.cubicTo(m_ctrlPoint1, m_ctrlPoint2, m_endPoint);
    m_path.swap(bezierPath);

    placeArrowAt(0.5);
}

QPointF BezierEdge::getCtrlPointFor(Plug* plug)
{
    qreal factor;
    switch (plug->getDirection()) {
    case PlugDirection::IN:
        factor = plug->getNode()->getIncomingExpansionFactor();
        break;
    case PlugDirection::OUT:
        factor = plug->getNode()->getOutgoingExpansionFactor();
        break;
    case PlugDirection::BOTH:
        factor = qMax(plug->getNode()->getIncomingExpansionFactor(), plug->getNode()->getOutgoingExpansionFactor());
        break;
    default:
        factor = 0.0;       //
        Q_ASSERT(false);    // we shouldn't ever reach these lines..
    }

    // calculate the control point distance
    qreal manhattanLength = (m_endPoint-m_startPoint).manhattanLength();
    qreal ctrlDistance = qMin(s_maxCtrlDistance, manhattanLength*s_ctrlExpansionFactor);
    return plug->scenePos()+((plug->getNormal()*ctrlDistance).toPointF()*factor);
}

} // namespace zodiac
<|endoftext|>


<commit_before>#include "AddHeatStructureMaterialAction.h"

template <>
InputParameters
validParams<AddHeatStructureMaterialAction>()
{
  return validParams<AddUserObjectAction>();
}

AddHeatStructureMaterialAction::AddHeatStructureMaterialAction(InputParameters params)
  : AddUserObjectAction(params)
{
}
<commit_msg>Update to new register methods<commit_after>#include "AddHeatStructureMaterialAction.h"

registerMooseAction("RELAP7App",
                    AddHeatStructureMaterialAction,
                    "RELAP7:add_heat_structure_material");

template <>
InputParameters
validParams<AddHeatStructureMaterialAction>()
{
  return validParams<AddUserObjectAction>();
}

AddHeatStructureMaterialAction::AddHeatStructureMaterialAction(InputParameters params)
  : AddUserObjectAction(params)
{
}
<|endoftext|>


<commit_before>#include "Runtime/World/CScriptDock.hpp"

#include "Runtime/CStateManager.hpp"
#include "Runtime/Character/CModelData.hpp"
#include "Runtime/Collision/CMaterialList.hpp"
#include "Runtime/Particle/CGenDescription.hpp"
#include "Runtime/World/CActorParameters.hpp"
#include "Runtime/World/CPlayer.hpp"
#include "Runtime/World/CScriptDoor.hpp"
#include "Runtime/World/CWorld.hpp"

#include "TCastTo.hpp" // Generated file, do not modify include path

namespace urde {

constexpr auto skDockMaterialList =
    CMaterialList{EMaterialTypes::Trigger, EMaterialTypes::Immovable, EMaterialTypes::AIBlock};

CScriptDock::CScriptDock(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CVector3f& position,
                         const zeus::CVector3f& extents, s32 dock, TAreaId area, bool active, s32 dockReferenceCount,
                         bool loadConnected)
: CPhysicsActor(uid, active, name, info, zeus::CTransform(zeus::CMatrix3f(), position), CModelData::CModelDataNull(),
                skDockMaterialList, zeus::CAABox(-extents * 0.5f, extents * 0.5f), SMoverData(1.f),
                CActorParameters::None(), 0.3f, 0.1f)
, x258_dockReferenceCount(dockReferenceCount)
, x25c_dock(dock)
, x260_area(area)
, x268_25_loadConnected(loadConnected) {}

void CScriptDock::Accept(IVisitor& visitor) { visitor.Visit(this); }

void CScriptDock::Think(float dt, CStateManager& mgr) {
  if (!GetActive()) {
    UpdateAreaActivateFlags(mgr);
    x268_24_dockReferenced = false;
  }

  const IGameArea::Dock* gameDock = mgr.GetWorld()->GetArea(x260_area)->GetDock(x25c_dock);
  TAreaId connArea = gameDock->GetConnectedAreaId(gameDock->GetReferenceCount());
  if (connArea != kInvalidAreaId) {
    bool connPostConstructed = mgr.GetWorld()->GetArea(connArea)->IsPostConstructed();
    if (x268_26_areaPostConstructed != connPostConstructed) {
      x268_26_areaPostConstructed = connPostConstructed;
      if (connPostConstructed)
        CEntity::SendScriptMsgs(EScriptObjectState::MaxReached, mgr, EScriptObjectMessage::None);
      else
        CEntity::SendScriptMsgs(EScriptObjectState::Zero, mgr, EScriptObjectMessage::None);
    }
  }

  if (mgr.GetNextAreaId() != x260_area)
    x264_dockState = EDockState::Three;
  else if (x264_dockState == EDockState::Three)
    x264_dockState = EDockState::Idle;
  else if (x264_dockState == EDockState::PlayerTouched)
    x264_dockState = EDockState::EnterNextArea;
  else if (x264_dockState == EDockState::EnterNextArea) {
    CPlayer& player = mgr.GetPlayer();
    if (HasPointCrossedDock(mgr, player.GetTranslation())) {
      IGameArea::Dock* dock = mgr.GetWorld()->GetArea(mgr.GetNextAreaId())->GetDock(x25c_dock);
      TAreaId aid = dock->GetConnectedAreaId(dock->GetReferenceCount());
      if (aid != kInvalidAreaId && mgr.GetWorld()->GetArea(aid)->GetActive()) {
        mgr.SetCurrentAreaId(aid);
        s32 otherDock = dock->GetOtherDockNumber(dock->GetReferenceCount());

        if (CObjectList* objs = mgr.GetWorld()->GetArea(aid)->GetAreaObjects()) {
          for (CEntity* ent : *objs) {
            const TCastToPtr<CScriptDock> dock2(ent);
            if (dock2 && dock2->GetDockId() == otherDock) {
              dock2->SetLoadConnected(mgr, true);
            }
          }
        }
      }
    }

    x264_dockState = EDockState::Idle;
  }
}

void CScriptDock::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) {
  switch (msg) {
  case EScriptObjectMessage::Registered: {
    CGameArea* area = mgr.GetWorld()->GetArea(x260_area);
    if (area->GetDockCount() < x25c_dock)
      return;
    IGameArea::Dock* dock = area->GetDock(x25c_dock);
    if (!dock->IsReferenced())
      dock->SetReferenceCount(x258_dockReferenceCount);
  } break;
  case EScriptObjectMessage::Deleted:
    CleanUp();
    break;
  case EScriptObjectMessage::InitializedInArea:
    AreaLoaded(mgr);
    break;
  case EScriptObjectMessage::WorldInitialized: {
    UpdateAreaActivateFlags(mgr);
    CMaterialList exclude = GetMaterialFilter().GetExcludeList();
    CMaterialList include = GetMaterialFilter().GetIncludeList();
    include.Add(EMaterialTypes::AIBlock);
    SetMaterialFilter(CMaterialFilter::MakeIncludeExclude(include, exclude));
  } break;
  case EScriptObjectMessage::SetToZero: {
    if (mgr.GetNextAreaId() != x260_area)
      return;

    SetLoadConnected(mgr, false);

    CGameArea* area = mgr.GetWorld()->GetArea(x260_area);
    IGameArea::Dock* dock = area->GetDock(x25c_dock);

    TAreaId aid = dock->GetConnectedAreaId(dock->GetReferenceCount());

    CPlatformAndDoorList& lst = mgr.GetPlatformAndDoorObjectList();
    for (CEntity* ent : lst) {
      TCastToPtr<CScriptDoor> door(ent);
      if (door && door->IsConnectedToArea(mgr, aid))
        door->ForceClosed(mgr);
    }
  } break;
  case EScriptObjectMessage::SetToMax:
    if (mgr.GetNextAreaId() != x260_area)
      return;

    SetLoadConnected(mgr, true);
    break;
  case EScriptObjectMessage::Increment:
    SetLoadConnected(mgr, true);
    [[fallthrough]];
  case EScriptObjectMessage::Decrement: {
    TAreaId aid = x260_area;
    if (mgr.GetNextAreaId() == x260_area) {
      IGameArea::Dock* dock = mgr.GetWorld()->GetArea(x260_area)->GetDock(x25c_dock);
      aid = dock->GetConnectedAreaId(dock->GetReferenceCount());
    }

    if (aid >= 0 && aid < mgr.GetWorld()->GetNumAreas() && mgr.GetWorld()->GetArea(aid)->GetActive())
      CWorld::PropogateAreaChain(CGameArea::EOcclusionState(msg == EScriptObjectMessage::Increment),
                                 mgr.GetWorld()->GetArea(aid), mgr.GetWorld());
  } break;
  default:
    CPhysicsActor::AcceptScriptMsg(msg, uid, mgr);
    break;
  }
}

std::optional<zeus::CAABox> CScriptDock::GetTouchBounds() const {
  if (x264_dockState == EDockState::Three) {
    return std::nullopt;
  }

  return GetBoundingBox();
}

void CScriptDock::Touch(CActor& act, CStateManager&) {
  if (x264_dockState == EDockState::Three)
    return;

  if (TCastToPtr<CPlayer>(act))
    x264_dockState = EDockState::PlayerTouched;
}

zeus::CPlane CScriptDock::GetPlane(const CStateManager& mgr) const {
  const IGameArea::Dock* dock = mgr.GetWorld()->GetAreaAlways(x260_area)->GetDock(x25c_dock);
  return zeus::CPlane(dock->GetPoint(0), dock->GetPoint(1), dock->GetPoint(2));
}

void CScriptDock::SetDockReference(CStateManager& mgr, s32 ref) {
  mgr.GetWorld()->GetArea(x260_area)->GetDock(x25c_dock)->SetReferenceCount(ref);
  x268_24_dockReferenced = true;
}

s32 CScriptDock::GetDockReference(const CStateManager& mgr) const {
  return mgr.GetWorld()->GetAreaAlways(x260_area)->GetDock(x25c_dock)->GetReferenceCount();
}

TAreaId CScriptDock::GetCurrentConnectedAreaId(const CStateManager& mgr) const {
  if (x260_area >= mgr.GetWorld()->GetNumAreas())
    return kInvalidAreaId;
  const CGameArea* area = mgr.GetWorld()->GetAreaAlways(x260_area);
  if (x25c_dock >= area->GetDockCount())
    return kInvalidAreaId;

  const IGameArea::Dock* dock = area->GetDock(x25c_dock);
  return dock->GetConnectedAreaId(dock->GetReferenceCount());
}

void CScriptDock::UpdateAreaActivateFlags(CStateManager& mgr) {
  CWorld* world = mgr.GetWorld();
  if (x260_area >= world->GetNumAreas())
    return;

  CGameArea* area = world->GetArea(x260_area);

  if (x25c_dock >= area->GetDockCount())
    return;

  IGameArea::Dock* dock = area->GetDock(x25c_dock);

  for (s32 i = 0; i < dock->GetDockRefs().size(); ++i) {
    s32 dockRefCount = dock->GetReferenceCount();
    TAreaId aid = dock->GetConnectedAreaId(i);
    if (aid != kInvalidAreaId)
      world->GetArea(aid)->SetActive(i == dockRefCount);
  }
  mgr.SetCurrentAreaId(mgr.GetNextAreaId());
}

bool CScriptDock::HasPointCrossedDock(const CStateManager& mgr, const zeus::CVector3f& point) const {
  const zeus::CPlane plane = GetPlane(mgr);
  return plane.pointToPlaneDist(point) >= 0.f;
}

void CScriptDock::AreaLoaded(CStateManager& mgr) { SetLoadConnected(mgr, x268_25_loadConnected); }

void CScriptDock::SetLoadConnected(CStateManager& mgr, bool loadOther) {
  IGameArea::Dock* dock = mgr.GetWorld()->GetArea(x260_area)->GetDock(x25c_dock);
  bool cur = dock->GetShouldLoadOther(dock->GetReferenceCount());
  if (cur == loadOther)
    return;

  dock->SetShouldLoadOther(dock->GetReferenceCount(), loadOther);
}
} // namespace urde
<commit_msg>CScriptDock: Brace conditionals where applicable<commit_after>#include "Runtime/World/CScriptDock.hpp"

#include "Runtime/CStateManager.hpp"
#include "Runtime/Character/CModelData.hpp"
#include "Runtime/Collision/CMaterialList.hpp"
#include "Runtime/Particle/CGenDescription.hpp"
#include "Runtime/World/CActorParameters.hpp"
#include "Runtime/World/CPlayer.hpp"
#include "Runtime/World/CScriptDoor.hpp"
#include "Runtime/World/CWorld.hpp"

#include "TCastTo.hpp" // Generated file, do not modify include path

namespace urde {

constexpr auto skDockMaterialList =
    CMaterialList{EMaterialTypes::Trigger, EMaterialTypes::Immovable, EMaterialTypes::AIBlock};

CScriptDock::CScriptDock(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CVector3f& position,
                         const zeus::CVector3f& extents, s32 dock, TAreaId area, bool active, s32 dockReferenceCount,
                         bool loadConnected)
: CPhysicsActor(uid, active, name, info, zeus::CTransform(zeus::CMatrix3f(), position), CModelData::CModelDataNull(),
                skDockMaterialList, zeus::CAABox(-extents * 0.5f, extents * 0.5f), SMoverData(1.f),
                CActorParameters::None(), 0.3f, 0.1f)
, x258_dockReferenceCount(dockReferenceCount)
, x25c_dock(dock)
, x260_area(area)
, x268_25_loadConnected(loadConnected) {}

void CScriptDock::Accept(IVisitor& visitor) { visitor.Visit(this); }

void CScriptDock::Think(float dt, CStateManager& mgr) {
  if (!GetActive()) {
    UpdateAreaActivateFlags(mgr);
    x268_24_dockReferenced = false;
  }

  const IGameArea::Dock* gameDock = mgr.GetWorld()->GetArea(x260_area)->GetDock(x25c_dock);
  const TAreaId connArea = gameDock->GetConnectedAreaId(gameDock->GetReferenceCount());
  if (connArea != kInvalidAreaId) {
    const bool connPostConstructed = mgr.GetWorld()->GetArea(connArea)->IsPostConstructed();
    if (x268_26_areaPostConstructed != connPostConstructed) {
      x268_26_areaPostConstructed = connPostConstructed;
      if (connPostConstructed) {
        CEntity::SendScriptMsgs(EScriptObjectState::MaxReached, mgr, EScriptObjectMessage::None);
      } else {
        CEntity::SendScriptMsgs(EScriptObjectState::Zero, mgr, EScriptObjectMessage::None);
      }
    }
  }

  if (mgr.GetNextAreaId() != x260_area) {
    x264_dockState = EDockState::Three;
  } else if (x264_dockState == EDockState::Three) {
    x264_dockState = EDockState::Idle;
  } else if (x264_dockState == EDockState::PlayerTouched) {
    x264_dockState = EDockState::EnterNextArea;
  } else if (x264_dockState == EDockState::EnterNextArea) {
    CPlayer& player = mgr.GetPlayer();
    if (HasPointCrossedDock(mgr, player.GetTranslation())) {
      const IGameArea::Dock* dock = mgr.GetWorld()->GetArea(mgr.GetNextAreaId())->GetDock(x25c_dock);
      const TAreaId aid = dock->GetConnectedAreaId(dock->GetReferenceCount());
      if (aid != kInvalidAreaId && mgr.GetWorld()->GetArea(aid)->GetActive()) {
        mgr.SetCurrentAreaId(aid);
        const s32 otherDock = dock->GetOtherDockNumber(dock->GetReferenceCount());

        if (CObjectList* objs = mgr.GetWorld()->GetArea(aid)->GetAreaObjects()) {
          for (CEntity* ent : *objs) {
            const TCastToPtr<CScriptDock> dock2(ent);
            if (dock2 && dock2->GetDockId() == otherDock) {
              dock2->SetLoadConnected(mgr, true);
            }
          }
        }
      }
    }

    x264_dockState = EDockState::Idle;
  }
}

void CScriptDock::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) {
  switch (msg) {
  case EScriptObjectMessage::Registered: {
    CGameArea* area = mgr.GetWorld()->GetArea(x260_area);
    if (area->GetDockCount() < x25c_dock) {
      return;
    }
    IGameArea::Dock* dock = area->GetDock(x25c_dock);
    if (!dock->IsReferenced()) {
      dock->SetReferenceCount(x258_dockReferenceCount);
    }
  } break;
  case EScriptObjectMessage::Deleted:
    CleanUp();
    break;
  case EScriptObjectMessage::InitializedInArea:
    AreaLoaded(mgr);
    break;
  case EScriptObjectMessage::WorldInitialized: {
    UpdateAreaActivateFlags(mgr);
    const CMaterialList exclude = GetMaterialFilter().GetExcludeList();
    CMaterialList include = GetMaterialFilter().GetIncludeList();
    include.Add(EMaterialTypes::AIBlock);
    SetMaterialFilter(CMaterialFilter::MakeIncludeExclude(include, exclude));
  } break;
  case EScriptObjectMessage::SetToZero: {
    if (mgr.GetNextAreaId() != x260_area) {
      return;
    }

    SetLoadConnected(mgr, false);

    const CGameArea* area = mgr.GetWorld()->GetArea(x260_area);
    const IGameArea::Dock* dock = area->GetDock(x25c_dock);

    const TAreaId aid = dock->GetConnectedAreaId(dock->GetReferenceCount());

    CPlatformAndDoorList& lst = mgr.GetPlatformAndDoorObjectList();
    for (CEntity* ent : lst) {
      const TCastToPtr<CScriptDoor> door(ent);
      if (door && door->IsConnectedToArea(mgr, aid)) {
        door->ForceClosed(mgr);
      }
    }
  } break;
  case EScriptObjectMessage::SetToMax:
    if (mgr.GetNextAreaId() != x260_area) {
      return;
    }

    SetLoadConnected(mgr, true);
    break;
  case EScriptObjectMessage::Increment:
    SetLoadConnected(mgr, true);
    [[fallthrough]];
  case EScriptObjectMessage::Decrement: {
    TAreaId aid = x260_area;
    if (mgr.GetNextAreaId() == x260_area) {
      const IGameArea::Dock* dock = mgr.GetWorld()->GetArea(x260_area)->GetDock(x25c_dock);
      aid = dock->GetConnectedAreaId(dock->GetReferenceCount());
    }

    if (aid >= 0 && aid < mgr.GetWorld()->GetNumAreas() && mgr.GetWorld()->GetArea(aid)->GetActive()) {
      CWorld::PropogateAreaChain(CGameArea::EOcclusionState(msg == EScriptObjectMessage::Increment),
                                 mgr.GetWorld()->GetArea(aid), mgr.GetWorld());
    }
  } break;
  default:
    CPhysicsActor::AcceptScriptMsg(msg, uid, mgr);
    break;
  }
}

std::optional<zeus::CAABox> CScriptDock::GetTouchBounds() const {
  if (x264_dockState == EDockState::Three) {
    return std::nullopt;
  }

  return GetBoundingBox();
}

void CScriptDock::Touch(CActor& act, CStateManager&) {
  if (x264_dockState == EDockState::Three) {
    return;
  }

  if (TCastToConstPtr<CPlayer>(act)) {
    x264_dockState = EDockState::PlayerTouched;
  }
}

zeus::CPlane CScriptDock::GetPlane(const CStateManager& mgr) const {
  const IGameArea::Dock* dock = mgr.GetWorld()->GetAreaAlways(x260_area)->GetDock(x25c_dock);
  return zeus::CPlane(dock->GetPoint(0), dock->GetPoint(1), dock->GetPoint(2));
}

void CScriptDock::SetDockReference(CStateManager& mgr, s32 ref) {
  mgr.GetWorld()->GetArea(x260_area)->GetDock(x25c_dock)->SetReferenceCount(ref);
  x268_24_dockReferenced = true;
}

s32 CScriptDock::GetDockReference(const CStateManager& mgr) const {
  return mgr.GetWorld()->GetAreaAlways(x260_area)->GetDock(x25c_dock)->GetReferenceCount();
}

TAreaId CScriptDock::GetCurrentConnectedAreaId(const CStateManager& mgr) const {
  if (x260_area >= mgr.GetWorld()->GetNumAreas()) {
    return kInvalidAreaId;
  }

  const CGameArea* area = mgr.GetWorld()->GetAreaAlways(x260_area);
  if (x25c_dock >= area->GetDockCount()) {
    return kInvalidAreaId;
  }

  const IGameArea::Dock* dock = area->GetDock(x25c_dock);
  return dock->GetConnectedAreaId(dock->GetReferenceCount());
}

void CScriptDock::UpdateAreaActivateFlags(CStateManager& mgr) {
  CWorld* world = mgr.GetWorld();
  if (x260_area >= world->GetNumAreas()) {
    return;
  }

  CGameArea* area = world->GetArea(x260_area);
  if (x25c_dock >= area->GetDockCount())
    return;

  const IGameArea::Dock* dock = area->GetDock(x25c_dock);

  for (s32 i = 0; i < dock->GetDockRefs().size(); ++i) {
    const s32 dockRefCount = dock->GetReferenceCount();
    const TAreaId aid = dock->GetConnectedAreaId(i);
    if (aid != kInvalidAreaId) {
      world->GetArea(aid)->SetActive(i == dockRefCount);
    }
  }
  mgr.SetCurrentAreaId(mgr.GetNextAreaId());
}

bool CScriptDock::HasPointCrossedDock(const CStateManager& mgr, const zeus::CVector3f& point) const {
  const zeus::CPlane plane = GetPlane(mgr);
  return plane.pointToPlaneDist(point) >= 0.f;
}

void CScriptDock::AreaLoaded(CStateManager& mgr) { SetLoadConnected(mgr, x268_25_loadConnected); }

void CScriptDock::SetLoadConnected(CStateManager& mgr, bool loadOther) {
  IGameArea::Dock* dock = mgr.GetWorld()->GetArea(x260_area)->GetDock(x25c_dock);
  const bool cur = dock->GetShouldLoadOther(dock->GetReferenceCount());
  if (cur == loadOther) {
    return;
  }

  dock->SetShouldLoadOther(dock->GetReferenceCount(), loadOther);
}
} // namespace urde
<|endoftext|>