<commit_before>/// HEADER
#include "decision_tree.h"

/// PROJECT
#include <csapex/msg/input.h>
#include <csapex/msg/output.h>
#include <csapex/utility/register_apex_plugin.h>
#include <utils_param/parameter_factory.h>
#include <csapex/model/node_modifier.h>
#include <csapex_core_plugins/vector_message.h>
#include <csapex/signal/slot.h>

/// SYSTEM
//#include <boost/assign.hpp>

CSAPEX_REGISTER_CLASS(csapex::DecisionTree, csapex::Node)

using namespace csapex;
using namespace csapex::connection_types;

DecisionTree::DecisionTree()
    : loaded_(false)
{
}

void DecisionTree::setupParameters()
{
    addParameter(param::ParameterFactory::declareFileInputPath("file", "dtree.yaml"), boost::bind(&DecisionTree::loadTree, this));
}

void DecisionTree::setup()
{
    in_  = modifier_->addInput<GenericVectorMessage, csapex::connection_types::FeaturesMessage>("Unclassified feature");
    out_ = modifier_->addOutput<GenericVectorMessage, csapex::connection_types::FeaturesMessage>("Classified feature");

    reload_ = modifier_->addSlot("Reload", boost::bind(&DecisionTree::loadTree, this));
}

void DecisionTree::process()
{
    if(loaded_) {
        boost::shared_ptr<std::vector<FeaturesMessage> const> input = in_->getMessage<GenericVectorMessage, FeaturesMessage>();
        boost::shared_ptr< std::vector<FeaturesMessage> > output (new std::vector<FeaturesMessage>);

        std::size_t n = input->size();

        output->resize(n);
        for(std::size_t i = 0; i < n; ++i) {
            output->at(i) = classify(input->at(i));
        }

        out_->publish<GenericVectorMessage, FeaturesMessage>(output);
    }
}

connection_types::FeaturesMessage DecisionTree::classify(const FeaturesMessage &input)
{
    connection_types::FeaturesMessage result = input;

    cv::Mat feature(1, input.value.size(), CV_32FC1, result.value.data());
    CvDTreeNode* node = dtree_.predict(feature);

    result.classification = node->class_idx;
    return result;
}

void DecisionTree::loadTree()
{
    std::string file = readParameter<std::string>("file");
    dtree_.load(file.c_str());

    loaded_ = true;
}
<commit_msg>do nothing if dt cannot be loaded<commit_after>/// HEADER
#include "decision_tree.h"

/// PROJECT
#include <csapex/msg/input.h>
#include <csapex/msg/output.h>
#include <csapex/utility/register_apex_plugin.h>
#include <utils_param/parameter_factory.h>
#include <csapex/model/node_modifier.h>
#include <csapex_core_plugins/vector_message.h>
#include <csapex/signal/slot.h>

/// SYSTEM
//#include <boost/assign.hpp>

CSAPEX_REGISTER_CLASS(csapex::DecisionTree, csapex::Node)

using namespace csapex;
using namespace csapex::connection_types;

DecisionTree::DecisionTree()
    : loaded_(false)
{
}

void DecisionTree::setupParameters()
{
    addParameter(param::ParameterFactory::declareFileInputPath("file", "dtree.yaml"), boost::bind(&DecisionTree::loadTree, this));
}

void DecisionTree::setup()
{
    in_  = modifier_->addInput<GenericVectorMessage, csapex::connection_types::FeaturesMessage>("Unclassified feature");
    out_ = modifier_->addOutput<GenericVectorMessage, csapex::connection_types::FeaturesMessage>("Classified feature");

    reload_ = modifier_->addSlot("Reload", boost::bind(&DecisionTree::loadTree, this));
}

void DecisionTree::process()
{
    boost::shared_ptr<std::vector<FeaturesMessage> const> input = in_->getMessage<GenericVectorMessage, FeaturesMessage>();
    boost::shared_ptr< std::vector<FeaturesMessage> > output (new std::vector<FeaturesMessage>);

    std::size_t n = input->size();

    if(loaded_) {
        output->resize(n);
        for(std::size_t i = 0; i < n; ++i) {
            output->at(i) = classify(input->at(i));
        }

    } else {
        *output = *input;
        setError(true, "cannot classfiy, no tree loaded", EL_WARNING);
    }

    out_->publish<GenericVectorMessage, FeaturesMessage>(output);
}

connection_types::FeaturesMessage DecisionTree::classify(const FeaturesMessage &input)
{
    connection_types::FeaturesMessage result = input;

    cv::Mat feature(1, input.value.size(), CV_32FC1, result.value.data());
    CvDTreeNode* node = dtree_.predict(feature);

    result.classification = node->class_idx;
    return result;
}

void DecisionTree::loadTree()
{
    std::string file = readParameter<std::string>("file");
    dtree_.load(file.c_str());

    loaded_ = dtree_.get_root() != NULL;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: PageMasterPropMapper.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: sab $ $Date: 2000-10-23 15:30:39 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX
#include "PageMasterPropMapper.hxx"
#endif

#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include "PageMasterStyleMap.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERPROPHDLFACTORY_HXX
#include "PageMasterPropHdlFactory.hxx"
#endif

#ifndef _COM_SUN_STAR_TABLE_BORDERLINE_HPP_
#include <com/sun/star/table/BorderLine.hpp>
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;

//______________________________________________________________________________

inline sal_Bool lcl_HasSameLineWidth( const table::BorderLine& rLine1, const table::BorderLine& rLine2 )
{
    return  (rLine1.InnerLineWidth == rLine2.InnerLineWidth) &&
            (rLine1.OuterLineWidth == rLine2.OuterLineWidth) &&
            (rLine1.LineDistance == rLine2.LineDistance);
}

inline sal_Bool operator==( const table::BorderLine& rLine1, const table::BorderLine& rLine2 )
{
    return  (rLine1.Color == rLine2.Color) &&
            lcl_HasSameLineWidth( rLine1, rLine2 );
}

inline void lcl_RemoveState( XMLPropertyState* pState )
{
    pState->mnIndex = -1;
    pState->maValue.clear();
}

void lcl_RemoveStateIfZero16( XMLPropertyState* pState )
{
    sal_Int16   nValue;
    if( (pState->maValue >>= nValue) && !nValue )
        lcl_RemoveState( pState );
}

//______________________________________________________________________________
// helper struct to handle equal XMLPropertyState's for page, header and footer

struct XMLPropertyStateBuffer
{
    XMLPropertyState*       pPMBorderAll;
    XMLPropertyState*       pPMBorderTop;
    XMLPropertyState*       pPMBorderBottom;
    XMLPropertyState*       pPMBorderLeft;
    XMLPropertyState*       pPMBorderRight;

    XMLPropertyState*       pPMBorderWidthAll;
    XMLPropertyState*       pPMBorderWidthTop;
    XMLPropertyState*       pPMBorderWidthBottom;
    XMLPropertyState*       pPMBorderWidthLeft;
    XMLPropertyState*       pPMBorderWidthRight;

    XMLPropertyState*       pPMPaddingAll;
    XMLPropertyState*       pPMPaddingTop;
    XMLPropertyState*       pPMPaddingBottom;
    XMLPropertyState*       pPMPaddingLeft;
    XMLPropertyState*       pPMPaddingRight;

                            XMLPropertyStateBuffer();
    void                    ContextFilter( ::std::vector< XMLPropertyState >& rPropState );
};

XMLPropertyStateBuffer::XMLPropertyStateBuffer() :
        pPMBorderAll( NULL ),
        pPMBorderTop( NULL ),
        pPMBorderBottom( NULL ),
        pPMBorderLeft( NULL ),
        pPMBorderRight( NULL ),

        pPMBorderWidthAll( NULL ),
        pPMBorderWidthTop( NULL ),
        pPMBorderWidthBottom( NULL ),
        pPMBorderWidthLeft( NULL ),
        pPMBorderWidthRight( NULL ),

        pPMPaddingAll( NULL ),
        pPMPaddingTop( NULL ),
        pPMPaddingBottom( NULL ),
        pPMPaddingLeft( NULL ),
        pPMPaddingRight( NULL )
{
}

void XMLPropertyStateBuffer::ContextFilter( ::std::vector< XMLPropertyState >& rPropState )
{
    if( pPMBorderAll )
    {
        if( pPMBorderTop && pPMBorderBottom && pPMBorderLeft && pPMBorderRight )
        {
            table::BorderLine aLineTop, aLineBottom, aLineLeft, aLineRight;

            pPMBorderTop->maValue >>= aLineTop;
            pPMBorderBottom->maValue >>= aLineBottom;
            pPMBorderLeft->maValue >>= aLineLeft;
            pPMBorderRight->maValue >>= aLineRight;

            if( (aLineTop == aLineBottom) && (aLineBottom == aLineLeft) && (aLineLeft == aLineRight) )
            {
                lcl_RemoveState( pPMBorderTop );
                lcl_RemoveState( pPMBorderBottom );
                lcl_RemoveState( pPMBorderLeft );
                lcl_RemoveState( pPMBorderRight );
            }
            else
                lcl_RemoveState( pPMBorderAll );
        }
        else
            lcl_RemoveState( pPMBorderAll );
    }

    if( pPMBorderWidthAll )
    {
        if( pPMBorderWidthTop && pPMBorderWidthBottom && pPMBorderWidthLeft && pPMBorderWidthRight )
        {
            table::BorderLine aLineTop, aLineBottom, aLineLeft, aLineRight;

            pPMBorderWidthTop->maValue >>= aLineTop;
            pPMBorderWidthBottom->maValue >>= aLineBottom;
            pPMBorderWidthLeft->maValue >>= aLineLeft;
            pPMBorderWidthRight->maValue >>= aLineRight;

            if( lcl_HasSameLineWidth( aLineTop, aLineBottom ) &&
                lcl_HasSameLineWidth( aLineBottom, aLineLeft ) &&
                lcl_HasSameLineWidth( aLineLeft, aLineRight ) )
            {
                lcl_RemoveState( pPMBorderWidthTop );
                lcl_RemoveState( pPMBorderWidthBottom );
                lcl_RemoveState( pPMBorderWidthLeft );
                lcl_RemoveState( pPMBorderWidthRight );
            }
            else
                lcl_RemoveState( pPMBorderWidthAll );
        }
        else
            lcl_RemoveState( pPMBorderWidthAll );
    }

    if( pPMPaddingAll )
    {
        if( pPMPaddingTop && pPMPaddingBottom && pPMPaddingLeft && pPMPaddingRight )
        {
            sal_Int32 nTop, nBottom, nLeft, nRight;

            pPMPaddingTop->maValue >>= nTop;
            pPMPaddingBottom->maValue >>= nBottom;
            pPMPaddingLeft->maValue >>= nLeft;
            pPMPaddingRight->maValue >>= nRight;

            if( (nTop == nBottom) && (nBottom == nLeft) && (nLeft == nRight) )
            {
                lcl_RemoveState( pPMPaddingTop );
                lcl_RemoveState( pPMPaddingBottom );
                lcl_RemoveState( pPMPaddingLeft );
                lcl_RemoveState( pPMPaddingRight );
            }
            else
                lcl_RemoveState( pPMPaddingAll );
        }
        else
            lcl_RemoveState( pPMPaddingAll );
    }
}

//______________________________________________________________________________
XMLPageMasterPropSetMapper::XMLPageMasterPropSetMapper():
    XMLPropertySetMapper( aXMLPageMasterStyleMap, new XMLPageMasterPropHdlFactory())
{
}

XMLPageMasterPropSetMapper::XMLPageMasterPropSetMapper(const sal_Bool bHeader):
    XMLPropertySetMapper( bHeader ? aXMLPageMasterHeaderImportStyleMap : aXMLPageMasterFooterImportStyleMap,
                            new XMLPageMasterPropHdlFactory())
{
}

XMLPageMasterPropSetMapper::XMLPageMasterPropSetMapper(
        const XMLPropertyMapEntry* pEntries,
        const UniReference< XMLPropertyHandlerFactory >& rFactory ) :
    XMLPropertySetMapper( pEntries, rFactory )
{
}

XMLPageMasterPropSetMapper::~XMLPageMasterPropSetMapper()
{
}

void XMLPageMasterPropSetMapper::ContextFilter(
        ::std::vector< XMLPropertyState >& rPropState,
        Reference< XPropertySet > rPropSet ) const
{
    XMLPropertyStateBuffer  aPageBuffer;
    XMLPropertyStateBuffer  aHeaderBuffer;
    XMLPropertyStateBuffer  aFooterBuffer;

    XMLPropertyState*       pPMHeaderHeight     = NULL;
    XMLPropertyState*       pPMHeaderMinHeight  = NULL;
    XMLPropertyState*       pPMHeaderDynamic    = NULL;

    XMLPropertyState*       pPMFooterHeight     = NULL;
    XMLPropertyState*       pPMFooterMinHeight  = NULL;
    XMLPropertyState*       pPMFooterDynamic    = NULL;

    XMLPropertyState*       pPMScaleTo          = NULL;
    XMLPropertyState*       pPMScaleToPages     = NULL;

    for( ::std::vector< XMLPropertyState >::iterator pProp = rPropState.begin(); pProp != rPropState.end(); pProp++ )
    {
        sal_Int16 nContextId    = GetEntryContextId( pProp->mnIndex );
        sal_Int16 nFlag         = nContextId & CTF_PM_FLAGMASK;
        sal_Int16 nSimpleId     = nContextId & ~CTF_PM_FLAGMASK;

        XMLPropertyStateBuffer* pBuffer;
        switch( nFlag )
        {
            case CTF_PM_HEADERFLAG:         pBuffer = &aHeaderBuffer;   break;
            case CTF_PM_FOOTERFLAG:         pBuffer = &aFooterBuffer;   break;
            default:                        pBuffer = &aPageBuffer;     break;
        }

        switch( nSimpleId )
        {
            case CTF_PM_BORDERALL:          pBuffer->pPMBorderAll           = pProp;    break;
            case CTF_PM_BORDERTOP:          pBuffer->pPMBorderTop           = pProp;    break;
            case CTF_PM_BORDERBOTTOM:       pBuffer->pPMBorderBottom        = pProp;    break;
            case CTF_PM_BORDERLEFT:         pBuffer->pPMBorderLeft          = pProp;    break;
            case CTF_PM_BORDERRIGHT:        pBuffer->pPMBorderRight         = pProp;    break;
            case CTF_PM_BORDERWIDTHALL:     pBuffer->pPMBorderWidthAll      = pProp;    break;
            case CTF_PM_BORDERWIDTHTOP:     pBuffer->pPMBorderWidthTop      = pProp;    break;
            case CTF_PM_BORDERWIDTHBOTTOM:  pBuffer->pPMBorderWidthBottom   = pProp;    break;
            case CTF_PM_BORDERWIDTHLEFT:    pBuffer->pPMBorderWidthLeft     = pProp;    break;
            case CTF_PM_BORDERWIDTHRIGHT:   pBuffer->pPMBorderWidthRight    = pProp;    break;
            case CTF_PM_PADDINGALL:         pBuffer->pPMPaddingAll          = pProp;    break;
            case CTF_PM_PADDINGTOP:         pBuffer->pPMPaddingTop          = pProp;    break;
            case CTF_PM_PADDINGBOTTOM:      pBuffer->pPMPaddingBottom       = pProp;    break;
            case CTF_PM_PADDINGLEFT:        pBuffer->pPMPaddingLeft         = pProp;    break;
            case CTF_PM_PADDINGRIGHT:       pBuffer->pPMPaddingRight        = pProp;    break;
        }

        switch( nContextId )
        {
            case CTF_PM_HEADERHEIGHT:       pPMHeaderHeight     = pProp;    break;
            case CTF_PM_HEADERMINHEIGHT:    pPMHeaderMinHeight  = pProp;    break;
            case CTF_PM_HEADERDYNAMIC:      pPMHeaderDynamic    = pProp;    break;
            case CTF_PM_FOOTERHEIGHT:       pPMFooterHeight     = pProp;    break;
            case CTF_PM_FOOTERMINHEIGHT:    pPMFooterMinHeight  = pProp;    break;
            case CTF_PM_FOOTERDYNAMIC:      pPMFooterDynamic    = pProp;    break;
            case CTF_PM_SCALETO:            pPMScaleTo          = pProp;    break;
            case CTF_PM_SCALETOPAGES:       pPMScaleToPages     = pProp;    break;
        }
    }

    aPageBuffer.ContextFilter( rPropState );
    aHeaderBuffer.ContextFilter( rPropState );
    aFooterBuffer.ContextFilter( rPropState );

    if( pPMHeaderHeight && pPMHeaderMinHeight )
    {
        sal_Bool bIsDynamic;
        if( pPMHeaderDynamic && (pPMHeaderDynamic->maValue >>= bIsDynamic) && bIsDynamic )
            lcl_RemoveState( pPMHeaderHeight );
        else
            lcl_RemoveState( pPMHeaderMinHeight );
    }
    if( pPMHeaderDynamic )
        lcl_RemoveState( pPMHeaderDynamic );

    if( pPMFooterHeight && pPMFooterMinHeight )
    {
        sal_Bool bIsDynamic;
        if( pPMFooterDynamic && (pPMFooterDynamic->maValue >>= bIsDynamic) && bIsDynamic )
            lcl_RemoveState( pPMFooterHeight );
        else
            lcl_RemoveState( pPMFooterMinHeight );
    }
    if( pPMFooterDynamic )
        lcl_RemoveState( pPMFooterDynamic );

    if( pPMScaleTo )
        lcl_RemoveStateIfZero16( pPMScaleTo );
    if( pPMScaleToPages )
        lcl_RemoveStateIfZero16( pPMScaleToPages );
}

<commit_msg>chg: using of comphelper::(g|s)etBOOL() instead of >>=/<<=<commit_after>/*************************************************************************
 *
 *  $RCSfile: PageMasterPropMapper.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: dr $ $Date: 2000-10-24 08:32:04 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX
#include "PageMasterPropMapper.hxx"
#endif

#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif

#ifndef _COM_SUN_STAR_TABLE_BORDERLINE_HPP_
#include <com/sun/star/table/BorderLine.hpp>
#endif

#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include "PageMasterStyleMap.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERPROPHDLFACTORY_HXX
#include "PageMasterPropHdlFactory.hxx"
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::comphelper;

//______________________________________________________________________________

inline sal_Bool lcl_HasSameLineWidth( const table::BorderLine& rLine1, const table::BorderLine& rLine2 )
{
    return  (rLine1.InnerLineWidth == rLine2.InnerLineWidth) &&
            (rLine1.OuterLineWidth == rLine2.OuterLineWidth) &&
            (rLine1.LineDistance == rLine2.LineDistance);
}

inline sal_Bool operator==( const table::BorderLine& rLine1, const table::BorderLine& rLine2 )
{
    return  (rLine1.Color == rLine2.Color) &&
            lcl_HasSameLineWidth( rLine1, rLine2 );
}

inline void lcl_RemoveState( XMLPropertyState* pState )
{
    pState->mnIndex = -1;
    pState->maValue.clear();
}

void lcl_RemoveStateIfZero16( XMLPropertyState* pState )
{
    sal_Int16   nValue;
    if( (pState->maValue >>= nValue) && !nValue )
        lcl_RemoveState( pState );
}

//______________________________________________________________________________
// helper struct to handle equal XMLPropertyState's for page, header and footer

struct XMLPropertyStateBuffer
{
    XMLPropertyState*       pPMBorderAll;
    XMLPropertyState*       pPMBorderTop;
    XMLPropertyState*       pPMBorderBottom;
    XMLPropertyState*       pPMBorderLeft;
    XMLPropertyState*       pPMBorderRight;

    XMLPropertyState*       pPMBorderWidthAll;
    XMLPropertyState*       pPMBorderWidthTop;
    XMLPropertyState*       pPMBorderWidthBottom;
    XMLPropertyState*       pPMBorderWidthLeft;
    XMLPropertyState*       pPMBorderWidthRight;

    XMLPropertyState*       pPMPaddingAll;
    XMLPropertyState*       pPMPaddingTop;
    XMLPropertyState*       pPMPaddingBottom;
    XMLPropertyState*       pPMPaddingLeft;
    XMLPropertyState*       pPMPaddingRight;

                            XMLPropertyStateBuffer();
    void                    ContextFilter( ::std::vector< XMLPropertyState >& rPropState );
};

XMLPropertyStateBuffer::XMLPropertyStateBuffer() :
        pPMBorderAll( NULL ),
        pPMBorderTop( NULL ),
        pPMBorderBottom( NULL ),
        pPMBorderLeft( NULL ),
        pPMBorderRight( NULL ),

        pPMBorderWidthAll( NULL ),
        pPMBorderWidthTop( NULL ),
        pPMBorderWidthBottom( NULL ),
        pPMBorderWidthLeft( NULL ),
        pPMBorderWidthRight( NULL ),

        pPMPaddingAll( NULL ),
        pPMPaddingTop( NULL ),
        pPMPaddingBottom( NULL ),
        pPMPaddingLeft( NULL ),
        pPMPaddingRight( NULL )
{
}

void XMLPropertyStateBuffer::ContextFilter( ::std::vector< XMLPropertyState >& rPropState )
{
    if( pPMBorderAll )
    {
        if( pPMBorderTop && pPMBorderBottom && pPMBorderLeft && pPMBorderRight )
        {
            table::BorderLine aLineTop, aLineBottom, aLineLeft, aLineRight;

            pPMBorderTop->maValue >>= aLineTop;
            pPMBorderBottom->maValue >>= aLineBottom;
            pPMBorderLeft->maValue >>= aLineLeft;
            pPMBorderRight->maValue >>= aLineRight;

            if( (aLineTop == aLineBottom) && (aLineBottom == aLineLeft) && (aLineLeft == aLineRight) )
            {
                lcl_RemoveState( pPMBorderTop );
                lcl_RemoveState( pPMBorderBottom );
                lcl_RemoveState( pPMBorderLeft );
                lcl_RemoveState( pPMBorderRight );
            }
            else
                lcl_RemoveState( pPMBorderAll );
        }
        else
            lcl_RemoveState( pPMBorderAll );
    }

    if( pPMBorderWidthAll )
    {
        if( pPMBorderWidthTop && pPMBorderWidthBottom && pPMBorderWidthLeft && pPMBorderWidthRight )
        {
            table::BorderLine aLineTop, aLineBottom, aLineLeft, aLineRight;

            pPMBorderWidthTop->maValue >>= aLineTop;
            pPMBorderWidthBottom->maValue >>= aLineBottom;
            pPMBorderWidthLeft->maValue >>= aLineLeft;
            pPMBorderWidthRight->maValue >>= aLineRight;

            if( lcl_HasSameLineWidth( aLineTop, aLineBottom ) &&
                lcl_HasSameLineWidth( aLineBottom, aLineLeft ) &&
                lcl_HasSameLineWidth( aLineLeft, aLineRight ) )
            {
                lcl_RemoveState( pPMBorderWidthTop );
                lcl_RemoveState( pPMBorderWidthBottom );
                lcl_RemoveState( pPMBorderWidthLeft );
                lcl_RemoveState( pPMBorderWidthRight );
            }
            else
                lcl_RemoveState( pPMBorderWidthAll );
        }
        else
            lcl_RemoveState( pPMBorderWidthAll );
    }

    if( pPMPaddingAll )
    {
        if( pPMPaddingTop && pPMPaddingBottom && pPMPaddingLeft && pPMPaddingRight )
        {
            sal_Int32 nTop, nBottom, nLeft, nRight;

            pPMPaddingTop->maValue >>= nTop;
            pPMPaddingBottom->maValue >>= nBottom;
            pPMPaddingLeft->maValue >>= nLeft;
            pPMPaddingRight->maValue >>= nRight;

            if( (nTop == nBottom) && (nBottom == nLeft) && (nLeft == nRight) )
            {
                lcl_RemoveState( pPMPaddingTop );
                lcl_RemoveState( pPMPaddingBottom );
                lcl_RemoveState( pPMPaddingLeft );
                lcl_RemoveState( pPMPaddingRight );
            }
            else
                lcl_RemoveState( pPMPaddingAll );
        }
        else
            lcl_RemoveState( pPMPaddingAll );
    }
}

//______________________________________________________________________________

XMLPageMasterPropSetMapper::XMLPageMasterPropSetMapper():
    XMLPropertySetMapper( aXMLPageMasterStyleMap, new XMLPageMasterPropHdlFactory())
{
}

XMLPageMasterPropSetMapper::XMLPageMasterPropSetMapper(const sal_Bool bHeader):
    XMLPropertySetMapper( bHeader ? aXMLPageMasterHeaderImportStyleMap : aXMLPageMasterFooterImportStyleMap,
                            new XMLPageMasterPropHdlFactory())
{
}

XMLPageMasterPropSetMapper::XMLPageMasterPropSetMapper(
        const XMLPropertyMapEntry* pEntries,
        const UniReference< XMLPropertyHandlerFactory >& rFactory ) :
    XMLPropertySetMapper( pEntries, rFactory )
{
}

XMLPageMasterPropSetMapper::~XMLPageMasterPropSetMapper()
{
}

void XMLPageMasterPropSetMapper::ContextFilter(
        ::std::vector< XMLPropertyState >& rPropState,
        Reference< XPropertySet > rPropSet ) const
{
    XMLPropertyStateBuffer  aPageBuffer;
    XMLPropertyStateBuffer  aHeaderBuffer;
    XMLPropertyStateBuffer  aFooterBuffer;

    XMLPropertyState*       pPMHeaderHeight     = NULL;
    XMLPropertyState*       pPMHeaderMinHeight  = NULL;
    XMLPropertyState*       pPMHeaderDynamic    = NULL;

    XMLPropertyState*       pPMFooterHeight     = NULL;
    XMLPropertyState*       pPMFooterMinHeight  = NULL;
    XMLPropertyState*       pPMFooterDynamic    = NULL;

    XMLPropertyState*       pPMScaleTo          = NULL;
    XMLPropertyState*       pPMScaleToPages     = NULL;

    for( ::std::vector< XMLPropertyState >::iterator pProp = rPropState.begin(); pProp != rPropState.end(); pProp++ )
    {
        sal_Int16 nContextId    = GetEntryContextId( pProp->mnIndex );
        sal_Int16 nFlag         = nContextId & CTF_PM_FLAGMASK;
        sal_Int16 nSimpleId     = nContextId & ~CTF_PM_FLAGMASK;

        XMLPropertyStateBuffer* pBuffer;
        switch( nFlag )
        {
            case CTF_PM_HEADERFLAG:         pBuffer = &aHeaderBuffer;   break;
            case CTF_PM_FOOTERFLAG:         pBuffer = &aFooterBuffer;   break;
            default:                        pBuffer = &aPageBuffer;     break;
        }

        switch( nSimpleId )
        {
            case CTF_PM_BORDERALL:          pBuffer->pPMBorderAll           = pProp;    break;
            case CTF_PM_BORDERTOP:          pBuffer->pPMBorderTop           = pProp;    break;
            case CTF_PM_BORDERBOTTOM:       pBuffer->pPMBorderBottom        = pProp;    break;
            case CTF_PM_BORDERLEFT:         pBuffer->pPMBorderLeft          = pProp;    break;
            case CTF_PM_BORDERRIGHT:        pBuffer->pPMBorderRight         = pProp;    break;
            case CTF_PM_BORDERWIDTHALL:     pBuffer->pPMBorderWidthAll      = pProp;    break;
            case CTF_PM_BORDERWIDTHTOP:     pBuffer->pPMBorderWidthTop      = pProp;    break;
            case CTF_PM_BORDERWIDTHBOTTOM:  pBuffer->pPMBorderWidthBottom   = pProp;    break;
            case CTF_PM_BORDERWIDTHLEFT:    pBuffer->pPMBorderWidthLeft     = pProp;    break;
            case CTF_PM_BORDERWIDTHRIGHT:   pBuffer->pPMBorderWidthRight    = pProp;    break;
            case CTF_PM_PADDINGALL:         pBuffer->pPMPaddingAll          = pProp;    break;
            case CTF_PM_PADDINGTOP:         pBuffer->pPMPaddingTop          = pProp;    break;
            case CTF_PM_PADDINGBOTTOM:      pBuffer->pPMPaddingBottom       = pProp;    break;
            case CTF_PM_PADDINGLEFT:        pBuffer->pPMPaddingLeft         = pProp;    break;
            case CTF_PM_PADDINGRIGHT:       pBuffer->pPMPaddingRight        = pProp;    break;
        }

        switch( nContextId )
        {
            case CTF_PM_HEADERHEIGHT:       pPMHeaderHeight     = pProp;    break;
            case CTF_PM_HEADERMINHEIGHT:    pPMHeaderMinHeight  = pProp;    break;
            case CTF_PM_HEADERDYNAMIC:      pPMHeaderDynamic    = pProp;    break;
            case CTF_PM_FOOTERHEIGHT:       pPMFooterHeight     = pProp;    break;
            case CTF_PM_FOOTERMINHEIGHT:    pPMFooterMinHeight  = pProp;    break;
            case CTF_PM_FOOTERDYNAMIC:      pPMFooterDynamic    = pProp;    break;
            case CTF_PM_SCALETO:            pPMScaleTo          = pProp;    break;
            case CTF_PM_SCALETOPAGES:       pPMScaleToPages     = pProp;    break;
        }
    }

    aPageBuffer.ContextFilter( rPropState );
    aHeaderBuffer.ContextFilter( rPropState );
    aFooterBuffer.ContextFilter( rPropState );

    if( pPMHeaderHeight && pPMHeaderMinHeight )
    {
        if( pPMHeaderDynamic && getBOOL( pPMHeaderDynamic->maValue ) )
            lcl_RemoveState( pPMHeaderHeight );
        else
            lcl_RemoveState( pPMHeaderMinHeight );
    }
    if( pPMHeaderDynamic )
        lcl_RemoveState( pPMHeaderDynamic );

    if( pPMFooterHeight && pPMFooterMinHeight )
    {
        if( pPMFooterDynamic && getBOOL( pPMFooterDynamic->maValue ) )
            lcl_RemoveState( pPMFooterHeight );
        else
            lcl_RemoveState( pPMFooterMinHeight );
    }
    if( pPMFooterDynamic )
        lcl_RemoveState( pPMFooterDynamic );

    if( pPMScaleTo )
        lcl_RemoveStateIfZero16( pPMScaleTo );
    if( pPMScaleToPages )
        lcl_RemoveStateIfZero16( pPMScaleToPages );
}

<|endoftext|>


<commit_before>#define BOOST_TEST_NO_MAIN

#include <memory>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <vector>
#include <numeric>
#include <fstream>
#include <tuple>

#include <boost/test/unit_test.hpp>
#include <boost/format.hpp>
#include "equelle/EquelleRuntimeCPU.hpp"
#include "equelle/CartesianGrid.hpp"

/**
 * Test that we can solve the heat equation
 */
BOOST_AUTO_TEST_CASE( heatEquation ) {
    int dim_x = 30;
    int dim_y = 50;
    int ghostWidth = 1;

    typedef equelle::CartesianGrid::Face Face;

    equelle::CartesianGrid grid( std::make_tuple( dim_x, dim_y),  ghostWidth );
    equelle::CartesianGrid::CartesianCollectionOfScalar u = grid.inputCellScalarWithDefault( "u", 1.0 );
    equelle::CartesianGrid::CartesianCollectionOfScalar u_faces = grid.inputFaceScalarWithDefault( "u_faces", 0.0 );

    const double k = 1.0; //Material specific heat diffusion constant
    const double dx = 1.0;//5.0 / static_cast<double>(dim_x);
    const double dy = 1.0;//5.0 / static_cast<double>(dim_y);
    const double dt = 1.0;

    const float a = k * dt / (dx*dy);

    double t_end = 100.0;
    double t = 0.0;

    equelle::CartesianGrid::CellRange allCells = grid.allCells();
    equelle::CartesianGrid::FaceRange allXFaces = grid.allXFaces();
    equelle::CartesianGrid::FaceRange allYFaces = grid.allYFaces();

    equelle::CartesianGrid::CartesianCollectionOfScalar u0 = u;

    //Our stencil for cells
    auto cell_stencil = [&] (int i, int j) {
        grid.cellAt( i, j, u ) = //grid.cellAt( i, j, u0 ) +
                     1.0/4.0 * ( grid.faceAt(i, j, Face::negX, u_faces) +
                                 grid.faceAt(i, j, Face::posX, u_faces) +
                                 grid.faceAt(i, j, Face::negY, u_faces) +
                                 grid.faceAt(i, j, Face::posY, u_faces) );
    };

    auto x_face_stencil = [&] (int i, int j) {
        grid.faceAt( i, j, Face::negX, u_faces ) = 0.5f * ( grid.cellAt( i-1, j, u0 ) + grid.cellAt( i, j, u0 ) );
    };

    auto y_face_stencil = [&] (int i, int j) {
        grid.faceAt( i, j, Face::negY, u_faces ) = 0.5f * ( grid.cellAt( i, j-1, u0 ) + grid.cellAt( i, j, u0 ) );
    };

    while (t < t_end) {
        allXFaces.execute(x_face_stencil);
        allYFaces.execute(y_face_stencil);
        allCells.execute(cell_stencil);

        t = t + dt;
        u0 = u;

        std::stringstream filename;
        std::showpoint(filename);
        filename << "waveheights_" << boost::format("%011.5f") % t << ".csv";

        std::ofstream file(filename.str());
        grid.dumpGridCells( u, file );
    }
}

#if 0

inline double sign(double& a) {
    /**
      * The following works by bit hacks. In non-obfuscated code, something like
      *  float r = ((int&)a & 0x7FFFFFFF)!=0; //set r to one or zero
      *  (int&)r |= ((int&)a & 0x80000000);   //Copy sign bit of a
      *  return r;
      */
    return (signed((int&)a & 0x80000000) >> 31 ) | ((int&)a & 0x7FFFFFFF)!=0;
}

/**
 * @return min(a, b, c), {a, b, c} > 0
 *         max(a, b, c), {a, b, c} < 0
 *         0           , otherwise
 */
inline double minmod(double a, double b, double c) {
    return 0.25
        *sign(a)
        *(sign(a) + sign(b))
        *(sign(b) + sign(c))
        *std::min( std::min(std::abs(a), std::abs(b)), std::abs(c) );
}

inline double derivative(const double& left,
        const double& center,
        const double& right,
        const double& dx,
        const double& theta) {
    return minmod(theta*(center-left)/dx,
            0.5f*(right-left),
            theta*(right-center));
}

inline double fluxFunc(double a) {
    return a;
}

inline double centralUpwind(double a_max, double a_min,
        double fm, double fp,
        double um, double up) {
    return ((a_max*fm - a_min*fp) + a_max*a_min*(up-um))/(a_max-a_min);
}

/**
 * Test that we can solve the wave equation with a second order stencil
 */
BOOST_AUTO_TEST_CASE( heatEquation_2nd_order ) {
    int dim_x = 3;
    int dim_y = 5;
    int ghostWidth = 2;

    typedef equelle::CartesianGrid::Face Face;

    equelle::CartesianGrid grid( std::make_tuple( dim_x, dim_y ),  ghostWidth );
    equelle::CartesianGrid::CartesianCollectionOfScalar u = grid.inputCellScalarWithDefault( "u", 1.0 );
    equelle::CartesianGrid::CartesianCollectionOfScalar udx = grid.inputCellScalarWithDefault( "udx", 0.0 );
    equelle::CartesianGrid::CartesianCollectionOfScalar udy = grid.inputCellScalarWithDefault( "udy", 0.0 );
    equelle::CartesianGrid::CartesianCollectionOfScalar up = grid.inputFaceScalarWithDefault( "up", 0.0 );
    equelle::CartesianGrid::CartesianCollectionOfScalar um = grid.inputFaceScalarWithDefault( "um", 0.0 );
    equelle::CartesianGrid::CartesianCollectionOfScalar f = grid.inputFaceScalarWithDefault( "f", 0.0 );

    const double k = 1.0; //Material specific heat diffusion constant
    const double dx = 1.0;//5.0 / static_cast<double>(dim_x);
    const double dy = 1.0;//5.0 / static_cast<double>(dim_y);
    const double dt = 1.0;

    const float a = k * dt / (dx*dy);
    const double theta  = 1.3;

    double t_end = 100.0;
    double t = 0.0;

    equelle::CartesianGrid::CartesianCollectionOfScalar u0 = u;
    while (t < t_end) {
        //Generate a minmod limited derivative along x
        for( int j = 0; j < dim_y; ++j ) {
            for( int i = 0; i < dim_x; ++i ) {
                grid.cellAt( i, j, udx ) = derivative(
                                                        grid.cellAt( i-1, j, u ),
                                                        grid.cellAt( i, j, u ),
                                                        grid.cellAt( i+1, j, u ),
                                                        dx, theta);
            }
        }

        //Generate a minmod limited derivative along y
        for( int j = -1; j <= dim_y; ++j ) {
            for( int i = -1; i <= dim_x; ++i ) {
                grid.cellAt( i, j, udy ) = derivative(
                                                        grid.cellAt( i, j-1, u ),
                                                        grid.cellAt( i, j, u ),
                                                        grid.cellAt( i, j+1, u ),
                                                        dy, theta);
            }
        }

        //Evaluate um/up for each internal face in x
        for( int j = 0; j < dim_y; ++j ) {
            for( int i = 0; i < dim_x-1; ++i ) {
                grid.faceAt( i, j, Face::posX, um ) = grid.cellAt( i, j, u )
                        + 0.5 * grid.cellAt( i, j, udx );
                grid.faceAt( i, j, Face::posX, up ) = grid.cellAt( i+1, j, u )
                        - 0.5 * grid.cellAt( i+1, j, udx );
            }
        }

        //Evaluate um/up for each internal face in y
        for( int j = 0; j < dim_y-1; ++j ) {
            for( int i = 0; i < dim_x; ++i ) {
                grid.faceAt( i, j, Face::posY, um ) = grid.cellAt( i, j, u )
                        + 0.5 * grid.cellAt( i, j, udy );
                grid.faceAt( i, j, Face::posY, up ) = grid.cellAt( i, j+1, u )
                        - 0.5 * grid.cellAt( i, j+1, udy );
            }
        }

        //Evaluate flux for each *internal* face in x
        for( int j = 0; j < dim_y; ++j ) {
            for( int i = 1; i < dim_x; ++i ) {
                //Only bogus fluxes here, but models how we should do something like shallow water
                //((a_max*fm - a_min*fp) + a_max*a_min*(up-um))/(a_max-a_min);

                const double ul = 0.0f;
                const double ur = 0.0f;

                double a_max = 0.5;
                double a_min = -0.5;

                const double fl = grid.faceAt( i, j, Face::negX, um );
                const double fr = grid.faceAt( i, j, Face::negX, up );

                grid.faceAt( i, j, Face::negX, f ) = (fl - fr) / dx;
                        /*centralUpwind(a_max, a_min,
                        fl, fr, ul, ur);*/
            }
        }

        //Evaluate flux for each *internal* face in y
        for( int j = 1; j < dim_y; ++j ) {
            for( int i = 0; i < dim_x; ++i ) {
                //Only bogus fluxes here

                const double ul = 0.0f;
                const double ur = 0.0f;

                double a_max = 0.5;
                double a_min = -0.5;

                const double fl = grid.faceAt( i, j, Face::negY, um );
                const double fr = grid.faceAt( i, j, Face::negY, up );

                grid.faceAt( i, j, Face::negY, f ) = (fl - fr) / dy;
                        /*centralUpwind(a_max, a_min,
                        fl, fr, ul, ur);*/
            }
        }

        //Sum face fluxes for all cells
        for( int j = 0; j < dim_y; ++j ) {
            for( int i = 0; i < dim_x; ++i ) {
                grid.cellAt( i, j, u ) = grid.cellAt( i, j, u0 ) +
                                         a * 1.0/4.0 * ( grid.faceAt(i, j, Face::negX, f) -
                                                 grid.faceAt(i, j, Face::posX, f) +
                                                 grid.faceAt(i, j, Face::negY, f) -
                                                 grid.faceAt(i, j, Face::posY, f));
            }
        }
        t = t + dt;

        /*
        std::stringstream filename;
        std::showpoint(filename);
        filename << "waveheights_" << boost::format("%011.5f") % t << ".csv";

        std::ofstream file(filename.str());
        grid.dumpGridCells( u, file );
        file << std::endl;
        grid.dumpGridFaces( f, Face::negX, file );
        file << std::endl;
        grid.dumpGridFaces( f, Face::negY, file );
        */

        u0 = u;
    }
}
#endif
<commit_msg>Added "2nd"-order scheme for heat equation<commit_after>#define BOOST_TEST_NO_MAIN

#include <memory>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <vector>
#include <numeric>
#include <fstream>
#include <tuple>

#include <boost/test/unit_test.hpp>
#include <boost/format.hpp>
#include "equelle/EquelleRuntimeCPU.hpp"
#include "equelle/CartesianGrid.hpp"

/**
 * Test that we can solve the heat equation
 */
BOOST_AUTO_TEST_CASE( heatEquation ) {
    int dim_x = 30;
    int dim_y = 50;
    int ghostWidth = 1;

    typedef equelle::CartesianGrid::Face Face;

    equelle::CartesianGrid grid( std::make_tuple( dim_x, dim_y),  ghostWidth );
    equelle::CartesianGrid::CartesianCollectionOfScalar u = grid.inputCellScalarWithDefault( "u", 1.0 );

    const double k = 1.0; //Material specific heat diffusion constant
    const double dx = 1.0;//5.0 / static_cast<double>(dim_x);
    const double dy = 1.0;//5.0 / static_cast<double>(dim_y);
    const double dt = 1.0;

    const float a = k * dt / (dx*dy);

    double t_end = 100.0;
    double t = 0.0;

    equelle::CartesianGrid::CellRange allCells = grid.allCells();
    equelle::CartesianGrid::FaceRange allXFaces = grid.allXFaces();
    equelle::CartesianGrid::FaceRange allYFaces = grid.allYFaces();

    equelle::CartesianGrid::CartesianCollectionOfScalar u0 = u;

    //Our stencil for cells
    auto cell_stencil = [&] (int i, int j) {
        grid.cellAt( i, j, u ) = grid.cellAt( i, j, u0 ) +
                  a* 1.0/8.0 * ( grid.cellAt(i+1, j, u0) +
                                 grid.cellAt(i-1, j, u0) +
                                 grid.cellAt(i, j+1, u0) +
                                 grid.cellAt(i, j-1, u0) -
                                 4*grid.cellAt(i, j, u0) );
    };

    while (t < t_end) {
        allCells.execute(cell_stencil);

        t = t + dt;
        u0 = u;
    }
}

/**
 * Test that we can solve the heat equation
 */
BOOST_AUTO_TEST_CASE( heatEquation2ndOrder ) {
    int dim_x = 30;
    int dim_y = 50;
    int ghostWidth = 2;

    typedef equelle::CartesianGrid::Face Face;

    equelle::CartesianGrid grid( std::make_tuple( dim_x, dim_y),  ghostWidth );
    equelle::CartesianGrid::CartesianCollectionOfScalar u = grid.inputCellScalarWithDefault( "u", 1.0 );
    equelle::CartesianGrid::CartesianCollectionOfScalar u_faces = grid.inputFaceScalarWithDefault( "u_faces", 0.0 );

    const double k = 1.0; //Material specific heat diffusion constant
    const double dx = 1.0;//5.0 / static_cast<double>(dim_x);
    const double dy = 1.0;//5.0 / static_cast<double>(dim_y);
    const double dt = 1.0;

    const float a = k * dt / (dx*dy);

    double t_end = 100.0;
    double t = 0.0;

    equelle::CartesianGrid::CellRange allCells = grid.allCells();
    equelle::CartesianGrid::FaceRange allXFaces = grid.allXFaces();
    equelle::CartesianGrid::FaceRange allYFaces = grid.allYFaces();

    equelle::CartesianGrid::CartesianCollectionOfScalar u0 = u;

    //Our stencil for cells
    auto cell_stencil = [&] (int i, int j) {
        grid.cellAt( i, j, u ) = //grid.cellAt( i, j, u0 ) +l
                     1.0/4.0 * ( grid.faceAt(i, j, Face::negX, u_faces) +
                                 grid.faceAt(i, j, Face::posX, u_faces) +
                                 grid.faceAt(i, j, Face::negY, u_faces) +
                                 grid.faceAt(i, j, Face::posY, u_faces) );
    };

    auto x_face_stencil = [&] (int i, int j) {
        grid.faceAt( i, j, Face::negX, u_faces ) =
                    1.0 / 6.0 * ( grid.cellAt( i-2, j, u0 ) +
                            2.0 * grid.cellAt( i-1, j, u0 )  +
                            2.0 * grid.cellAt( i, j, u0 )  +
                                  grid.cellAt( i+1, j, u0 ) );
    };

    auto y_face_stencil = [&] (int i, int j) {
        grid.faceAt( i, j, Face::negY, u_faces ) =
                1.0 / 6.0 * ( grid.cellAt( i, j-2, u0 ) +
                        2.0 * grid.cellAt( i, j-1, u0 )  +
                        2.0 * grid.cellAt( i, j, u0 )  +
                              grid.cellAt( i, j+1, u0 ) );
    };

    while (t < t_end) {
        allXFaces.execute(x_face_stencil);
        allYFaces.execute(y_face_stencil);
        allCells.execute(cell_stencil);

        t = t + dt;
        u0 = u;

        std::stringstream filename;
        std::showpoint(filename);
        filename << "waveheights_" << boost::format("%011.5f") % t << ".csv";

        std::ofstream file(filename.str());
        grid.dumpGridCells( u, file );
    }
}

<|endoftext|>


<commit_before><commit_msg>Added the ability to read and write to SPD, MVPD and PVPD<commit_after><|endoftext|>


<commit_before><commit_msg>Fix compile failure on Win64.<commit_after><|endoftext|>


<commit_before><commit_msg>oops, as Alby pointed out that didnt actually solve the null problem. Now does.<commit_after><|endoftext|>


<commit_before>//===-- FindAllSymbolsTests.cpp - find all symbols unit tests ---*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "FindAllMacros.h"
#include "FindAllSymbols.h"
#include "HeaderMapCollector.h"
#include "PragmaCommentHandler.h"
#include "SymbolInfo.h"
#include "SymbolReporter.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Basic/VirtualFileSystem.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/PCHContainerOperations.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/MemoryBuffer.h"
#include "gtest/gtest.h"
#include <memory>
#include <string>
#include <vector>

namespace clang {
namespace find_all_symbols {

static const char HeaderName[] = "symbols.h";

class TestSymbolReporter : public clang::find_all_symbols::SymbolReporter {
public:
  ~TestSymbolReporter() override {}

  void reportSymbol(llvm::StringRef FileName,
                    const SymbolInfo &Symbol) override {
    Symbols.push_back(Symbol);
  }

  bool hasSymbol(const SymbolInfo &Symbol) const {
    for (const auto &S : Symbols) {
      if (S == Symbol)
        return true;
    }
    return false;
  }

private:
  std::vector<SymbolInfo> Symbols;
};

class TestFindAllSymbolsAction : public clang::ASTFrontendAction {
public:
  TestFindAllSymbolsAction(SymbolReporter *Reporter)
      : Reporter(Reporter), MatchFinder(), Collector(), Handler(&Collector),
        Matcher(Reporter, &Collector) {
    Matcher.registerMatchers(&MatchFinder);
  }

  std::unique_ptr<clang::ASTConsumer>
  CreateASTConsumer(clang::CompilerInstance &Compiler,
                    StringRef InFile) override {
    Compiler.getPreprocessor().addCommentHandler(&Handler);
    Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllMacros>(
        Reporter, &Compiler.getSourceManager(), &Collector));
    return MatchFinder.newASTConsumer();
  }

private:
  SymbolReporter *const Reporter;
  ast_matchers::MatchFinder MatchFinder;
  HeaderMapCollector Collector;
  PragmaCommentHandler Handler;
  FindAllSymbols Matcher;
};

class TestFindAllSymbolsActionFactory
    : public clang::tooling::FrontendActionFactory {
public:
  TestFindAllSymbolsActionFactory(TestSymbolReporter *Reporter)
      : Reporter(Reporter) {}
  clang::FrontendAction *create() override {
    return new TestFindAllSymbolsAction(Reporter);
  }

private:
  TestSymbolReporter *const Reporter;
};

class FindAllSymbolsTest : public ::testing::Test {
public:
  bool hasSymbol(const SymbolInfo &Symbol) {
    return Reporter.hasSymbol(Symbol);
  }

  bool runFindAllSymbols(StringRef Code) {
    llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
        new vfs::InMemoryFileSystem);
    llvm::IntrusiveRefCntPtr<FileManager> Files(
        new FileManager(FileSystemOptions(), InMemoryFileSystem));

    std::string FileName = "symbol.cc";

    std::unique_ptr<clang::tooling::FrontendActionFactory> Factory(
        new TestFindAllSymbolsActionFactory(&Reporter));

    tooling::ToolInvocation Invocation(
        {std::string("find_all_symbols"), std::string("-fsyntax-only"),
         std::string("-std=c++11"), FileName},
        Factory->create(), Files.get(),
        std::make_shared<PCHContainerOperations>());

    InMemoryFileSystem->addFile(HeaderName, 0,
                                llvm::MemoryBuffer::getMemBuffer(Code));

    std::string Content = "#include\"" + std::string(HeaderName) + "\"";
    InMemoryFileSystem->addFile(FileName, 0,
                                llvm::MemoryBuffer::getMemBuffer(Content));
    Invocation.run();
    return true;
  }

private:
  TestSymbolReporter Reporter;
};

TEST_F(FindAllSymbolsTest, VariableSymbols) {
  static const char Code[] = R"(
      extern int xargc;
      namespace na {
      static bool SSSS = false;
      namespace nb { const long long *XXXX; }
      })";
  runFindAllSymbols(Code);

  SymbolInfo Symbol =
      SymbolInfo("xargc", SymbolInfo::SymbolKind::Variable, HeaderName, 2, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("SSSS", SymbolInfo::SymbolKind::Variable, HeaderName, 4,
                      {{SymbolInfo::ContextType::Namespace, "na"}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("XXXX", SymbolInfo::SymbolKind::Variable, HeaderName, 5,
                      {{SymbolInfo::ContextType::Namespace, "nb"},
                       {SymbolInfo::ContextType::Namespace, "na"}});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, ExternCSymbols) {
  static const char Code[] = R"(
      extern "C" {
      int C_Func() { return 0; }
      struct C_struct {
        int Member;
      };
      })";
  runFindAllSymbols(Code);

  SymbolInfo Symbol =
      SymbolInfo("C_Func", SymbolInfo::SymbolKind::Function, HeaderName, 3, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol =
      SymbolInfo("C_struct", SymbolInfo::SymbolKind::Class, HeaderName, 4, {});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, CXXRecordSymbols) {
  static const char Code[] = R"(
      struct Glob {};
      struct A; // Not a defintion, ignored.
      class NOP; // Not a defintion, ignored
      namespace na {
      struct A {
        struct AAAA {};
        int x;
        int y;
        void f() {}
      };
      };  //
      )";
  runFindAllSymbols(Code);

  SymbolInfo Symbol =
      SymbolInfo("Glob", SymbolInfo::SymbolKind::Class, HeaderName, 2, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("A", SymbolInfo::SymbolKind::Class, HeaderName, 6,
                      {{SymbolInfo::ContextType::Namespace, "na"}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("AAA", SymbolInfo::SymbolKind::Class, HeaderName, 7,
                      {{SymbolInfo::ContextType::Record, "A"},
                       {SymbolInfo::ContextType::Namespace, "na"}});
  EXPECT_FALSE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, CXXRecordSymbolsTemplate) {
  static const char Code[] = R"(
      template <typename T>
      class T_TEMP {
        template <typename _Tp1>
        struct rebind { typedef T_TEMP<_Tp1> other; };
      };
      // Ignore specialization.
      template class T_TEMP<char>;

      template <typename T>
      class Observer {
      };
      // Ignore specialization.
      template <> class Observer<int> {};
      )";
  runFindAllSymbols(Code);

  SymbolInfo Symbol =
      SymbolInfo("T_TEMP", SymbolInfo::SymbolKind::Class, HeaderName, 3, {});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, FunctionSymbols) {
  static const char Code[] = R"(
      namespace na {
      int gg(int);
      int f(const int &a) { int Local; static int StaticLocal; return 0; }
      static void SSSFFF() {}
      }  // namespace na
      namespace na {
      namespace nb {
      template<typename T>
      void fun(T t) {};
      } // namespace nb
      } // namespace na";
      )";
  runFindAllSymbols(Code);

  SymbolInfo Symbol =
      SymbolInfo("gg", SymbolInfo::SymbolKind::Function, HeaderName, 3,
                 {{SymbolInfo::ContextType::Namespace, "na"}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("f", SymbolInfo::SymbolKind::Function, HeaderName, 4,
                      {{SymbolInfo::ContextType::Namespace, "na"}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("SSSFFF", SymbolInfo::SymbolKind::Function, HeaderName, 5,
                      {{SymbolInfo::ContextType::Namespace, "na"}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("fun", SymbolInfo::SymbolKind::Function, HeaderName, 10,
                      {{SymbolInfo::ContextType::Namespace, "nb"},
                       {SymbolInfo::ContextType::Namespace, "na"}});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, NamespaceTest) {
  static const char Code[] = R"(
      int X1;
      namespace { int X2; }
      namespace { namespace { int X3; } }
      namespace { namespace nb { int X4;} }
      )";
  runFindAllSymbols(Code);

  SymbolInfo Symbol =
      SymbolInfo("X1", SymbolInfo::SymbolKind::Variable, HeaderName, 2, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("X2", SymbolInfo::SymbolKind::Variable, HeaderName, 3,
                      {{SymbolInfo::ContextType::Namespace, ""}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("X3", SymbolInfo::SymbolKind::Variable, HeaderName, 4,
                      {{SymbolInfo::ContextType::Namespace, ""},
                       {SymbolInfo::ContextType::Namespace, ""}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("X4", SymbolInfo::SymbolKind::Variable, HeaderName, 5,
                      {{SymbolInfo::ContextType::Namespace, "nb"},
                       {SymbolInfo::ContextType::Namespace, ""}});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, DecayedTypeTest) {
  static const char Code[] = "void DecayedFunc(int x[], int y[10]) {}";
  runFindAllSymbols(Code);
  SymbolInfo Symbol = SymbolInfo(
      "DecayedFunc", SymbolInfo::SymbolKind::Function, HeaderName, 1, {});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, CTypedefTest) {
  static const char Code[] = R"(
      typedef unsigned size_t_;
      typedef struct { int x; } X;
      using XX = X;
      )";
  runFindAllSymbols(Code);

  SymbolInfo Symbol = SymbolInfo("size_t_", SymbolInfo::SymbolKind::TypedefName,
                                 HeaderName, 2, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol =
      SymbolInfo("X", SymbolInfo::SymbolKind::TypedefName, HeaderName, 3, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol =
      SymbolInfo("XX", SymbolInfo::SymbolKind::TypedefName, HeaderName, 4, {});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, EnumTest) {
  static const char Code[] = R"(
      enum Glob_E { G1, G2 };
      enum class Altitude { high='h', low='l'};
      enum { A1, A2 };
      class A {
      public:
        enum A_ENUM { X1, X2 };
      };
      )";
  runFindAllSymbols(Code);

  SymbolInfo Symbol =
      SymbolInfo("Glob_E", SymbolInfo::SymbolKind::EnumDecl, HeaderName, 2, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol =
      SymbolInfo("G1", SymbolInfo::SymbolKind::EnumConstantDecl, HeaderName, 2,
                 {{SymbolInfo::ContextType::EnumDecl, "Glob_E"}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol =
      SymbolInfo("G2", SymbolInfo::SymbolKind::EnumConstantDecl, HeaderName, 2,
                 {{SymbolInfo::ContextType::EnumDecl, "Glob_E"}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("Altitude", SymbolInfo::SymbolKind::EnumDecl, HeaderName,
                      3, {});
  EXPECT_TRUE(hasSymbol(Symbol));
  Symbol =
      SymbolInfo("high", SymbolInfo::SymbolKind::EnumConstantDecl, HeaderName,
                 3, {{SymbolInfo::ContextType::EnumDecl, "Altitude"}});
  EXPECT_FALSE(hasSymbol(Symbol));

  Symbol = SymbolInfo("A1", SymbolInfo::SymbolKind::EnumConstantDecl,
                      HeaderName, 4, {{SymbolInfo::ContextType::EnumDecl, ""}});
  EXPECT_TRUE(hasSymbol(Symbol));
  Symbol = SymbolInfo("A2", SymbolInfo::SymbolKind::EnumConstantDecl,
                      HeaderName, 4, {{SymbolInfo::ContextType::EnumDecl, ""}});
  EXPECT_TRUE(hasSymbol(Symbol));
  Symbol = SymbolInfo("", SymbolInfo::SymbolKind::EnumDecl, HeaderName, 4, {});
  EXPECT_FALSE(hasSymbol(Symbol));

  Symbol = SymbolInfo("A_ENUM", SymbolInfo::SymbolKind::EnumDecl, HeaderName, 7,
                      {{SymbolInfo::ContextType::Record, "A"}});
  EXPECT_FALSE(hasSymbol(Symbol));

  Symbol = SymbolInfo("X1", SymbolInfo::SymbolKind::EnumDecl, HeaderName, 7,
                      {{SymbolInfo::ContextType::EnumDecl, "A_ENUM"},
                       {SymbolInfo::ContextType::Record, "A"}});
  EXPECT_FALSE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, IWYUPrivatePragmaTest) {
  static const char Code[] = R"(
    // IWYU pragma: private, include "bar.h"
    struct Bar {
    };
  )";
  runFindAllSymbols(Code);

  SymbolInfo Symbol =
      SymbolInfo("Bar", SymbolInfo::SymbolKind::Class, "bar.h", 3, {});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, MacroTest) {
  static const char Code[] = R"(
    #define X
    #define Y 1
    #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
  )";
  runFindAllSymbols(Code);
  SymbolInfo Symbol =
      SymbolInfo("X", SymbolInfo::SymbolKind::Macro, HeaderName, 2, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("Y", SymbolInfo::SymbolKind::Macro, HeaderName, 3, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("MAX", SymbolInfo::SymbolKind::Macro, HeaderName, 4, {});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, MacroTestWithIWYU) {
  static const char Code[] = R"(
    // IWYU pragma: private, include "bar.h"
    #define X
    #define Y 1
    #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
  )";
  runFindAllSymbols(Code);
  SymbolInfo Symbol =
      SymbolInfo("X", SymbolInfo::SymbolKind::Macro, "bar.h", 3, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("Y", SymbolInfo::SymbolKind::Macro, "bar.h", 4, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("MAX", SymbolInfo::SymbolKind::Macro, "bar.h", 5, {});
  EXPECT_TRUE(hasSymbol(Symbol));
}

} // namespace find_all_symbols
} // namespace clang
<commit_msg>[find-all-symbol] Try to fix the failure windows unittest.<commit_after>//===-- FindAllSymbolsTests.cpp - find all symbols unit tests ---*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "FindAllMacros.h"
#include "FindAllSymbols.h"
#include "HeaderMapCollector.h"
#include "PragmaCommentHandler.h"
#include "SymbolInfo.h"
#include "SymbolReporter.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Basic/VirtualFileSystem.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/PCHContainerOperations.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/MemoryBuffer.h"
#include "gtest/gtest.h"
#include <memory>
#include <string>
#include <vector>

namespace clang {
namespace find_all_symbols {

static const char HeaderName[] = "symbols.h";

class TestSymbolReporter : public clang::find_all_symbols::SymbolReporter {
public:
  ~TestSymbolReporter() override {}

  void reportSymbol(llvm::StringRef FileName,
                    const SymbolInfo &Symbol) override {
    Symbols.push_back(Symbol);
  }

  bool hasSymbol(const SymbolInfo &Symbol) const {
    for (const auto &S : Symbols) {
      if (S == Symbol)
        return true;
    }
    return false;
  }

  const std::vector<SymbolInfo>& getSymbols() const {
    return Symbols;
  }

private:
  std::vector<SymbolInfo> Symbols;
};

class TestFindAllSymbolsAction : public clang::ASTFrontendAction {
public:
  TestFindAllSymbolsAction(SymbolReporter *Reporter)
      : Reporter(Reporter), MatchFinder(), Collector(), Handler(&Collector),
        Matcher(Reporter, &Collector) {
    Matcher.registerMatchers(&MatchFinder);
  }

  std::unique_ptr<clang::ASTConsumer>
  CreateASTConsumer(clang::CompilerInstance &Compiler,
                    StringRef InFile) override {
    Compiler.getPreprocessor().addCommentHandler(&Handler);
    Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllMacros>(
        Reporter, &Compiler.getSourceManager(), &Collector));
    return MatchFinder.newASTConsumer();
  }

private:
  SymbolReporter *const Reporter;
  ast_matchers::MatchFinder MatchFinder;
  HeaderMapCollector Collector;
  PragmaCommentHandler Handler;
  FindAllSymbols Matcher;
};

class TestFindAllSymbolsActionFactory
    : public clang::tooling::FrontendActionFactory {
public:
  TestFindAllSymbolsActionFactory(TestSymbolReporter *Reporter)
      : Reporter(Reporter) {}
  clang::FrontendAction *create() override {
    return new TestFindAllSymbolsAction(Reporter);
  }

private:
  TestSymbolReporter *const Reporter;
};

class FindAllSymbolsTest : public ::testing::Test {
public:
  bool hasSymbol(const SymbolInfo &Symbol) {
    return Reporter.hasSymbol(Symbol);
  }

  bool runFindAllSymbols(StringRef Code) {
    llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
        new vfs::InMemoryFileSystem);
    llvm::IntrusiveRefCntPtr<FileManager> Files(
        new FileManager(FileSystemOptions(), InMemoryFileSystem));

    std::string FileName = "symbol.cc";

    std::unique_ptr<clang::tooling::FrontendActionFactory> Factory(
        new TestFindAllSymbolsActionFactory(&Reporter));

    tooling::ToolInvocation Invocation(
        {std::string("find_all_symbols"), std::string("-fsyntax-only"),
         std::string("-std=c++11"), FileName},
        Factory->create(), Files.get(),
        std::make_shared<PCHContainerOperations>());

    InMemoryFileSystem->addFile(HeaderName, 0,
                                llvm::MemoryBuffer::getMemBuffer(Code));

    std::string Content = "#include\"" + std::string(HeaderName) + "\"";
    InMemoryFileSystem->addFile(FileName, 0,
                                llvm::MemoryBuffer::getMemBuffer(Content));
    Invocation.run();
    return true;
  }

protected:
  TestSymbolReporter Reporter;
};

TEST_F(FindAllSymbolsTest, VariableSymbols) {
  static const char Code[] = R"(
      extern int xargc;
      namespace na {
      static bool SSSS = false;
      namespace nb { const long long *XXXX; }
      })";
  runFindAllSymbols(Code);

  SymbolInfo Symbol =
      SymbolInfo("xargc", SymbolInfo::SymbolKind::Variable, HeaderName, 2, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("SSSS", SymbolInfo::SymbolKind::Variable, HeaderName, 4,
                      {{SymbolInfo::ContextType::Namespace, "na"}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("XXXX", SymbolInfo::SymbolKind::Variable, HeaderName, 5,
                      {{SymbolInfo::ContextType::Namespace, "nb"},
                       {SymbolInfo::ContextType::Namespace, "na"}});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, ExternCSymbols) {
  static const char Code[] = R"(
      extern "C" {
      int C_Func() { return 0; }
      struct C_struct {
        int Member;
      };
      })";
  runFindAllSymbols(Code);

  SymbolInfo Symbol =
      SymbolInfo("C_Func", SymbolInfo::SymbolKind::Function, HeaderName, 3, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol =
      SymbolInfo("C_struct", SymbolInfo::SymbolKind::Class, HeaderName, 4, {});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, CXXRecordSymbols) {
  static const char Code[] = R"(
      struct Glob {};
      struct A; // Not a defintion, ignored.
      class NOP; // Not a defintion, ignored
      namespace na {
      struct A {
        struct AAAA {};
        int x;
        int y;
        void f() {}
      };
      };  //
      )";
  runFindAllSymbols(Code);

  SymbolInfo Symbol =
      SymbolInfo("Glob", SymbolInfo::SymbolKind::Class, HeaderName, 2, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("A", SymbolInfo::SymbolKind::Class, HeaderName, 6,
                      {{SymbolInfo::ContextType::Namespace, "na"}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("AAA", SymbolInfo::SymbolKind::Class, HeaderName, 7,
                      {{SymbolInfo::ContextType::Record, "A"},
                       {SymbolInfo::ContextType::Namespace, "na"}});
  EXPECT_FALSE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, CXXRecordSymbolsTemplate) {
  static const char Code[] = R"(
      template <typename T>
      class T_TEMP {
        template <typename _Tp1>
        struct rebind { typedef T_TEMP<_Tp1> other; };
      };
      // Ignore specialization.
      template class T_TEMP<char>;

      template <typename T>
      class Observer {
      };
      // Ignore specialization.
      template <> class Observer<int> {};
      )";
  runFindAllSymbols(Code);

  SymbolInfo Symbol =
      SymbolInfo("T_TEMP", SymbolInfo::SymbolKind::Class, HeaderName, 3, {});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, FunctionSymbols) {
  static const char Code[] = R"(
      namespace na {
      int gg(int);
      int f(const int &a) { int Local; static int StaticLocal; return 0; }
      static void SSSFFF() {}
      }  // namespace na
      namespace na {
      namespace nb {
      template<typename T>
      void fun(T t) {};
      } // namespace nb
      } // namespace na";
      )";
  runFindAllSymbols(Code);

  SymbolInfo Symbol =
      SymbolInfo("gg", SymbolInfo::SymbolKind::Function, HeaderName, 3,
                 {{SymbolInfo::ContextType::Namespace, "na"}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("f", SymbolInfo::SymbolKind::Function, HeaderName, 4,
                      {{SymbolInfo::ContextType::Namespace, "na"}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("SSSFFF", SymbolInfo::SymbolKind::Function, HeaderName, 5,
                      {{SymbolInfo::ContextType::Namespace, "na"}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("fun", SymbolInfo::SymbolKind::Function, HeaderName, 10,
                      {{SymbolInfo::ContextType::Namespace, "nb"},
                       {SymbolInfo::ContextType::Namespace, "na"}});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, NamespaceTest) {
  static const char Code[] = R"(
      int X1;
      namespace { int X2; }
      namespace { namespace { int X3; } }
      namespace { namespace nb { int X4;} }
      )";
  runFindAllSymbols(Code);

  SymbolInfo Symbol =
      SymbolInfo("X1", SymbolInfo::SymbolKind::Variable, HeaderName, 2, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("X2", SymbolInfo::SymbolKind::Variable, HeaderName, 3,
                      {{SymbolInfo::ContextType::Namespace, ""}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("X3", SymbolInfo::SymbolKind::Variable, HeaderName, 4,
                      {{SymbolInfo::ContextType::Namespace, ""},
                       {SymbolInfo::ContextType::Namespace, ""}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("X4", SymbolInfo::SymbolKind::Variable, HeaderName, 5,
                      {{SymbolInfo::ContextType::Namespace, "nb"},
                       {SymbolInfo::ContextType::Namespace, ""}});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, DecayedTypeTest) {
  static const char Code[] = "void DecayedFunc(int x[], int y[10]) {}";
  runFindAllSymbols(Code);
  SymbolInfo Symbol = SymbolInfo(
      "DecayedFunc", SymbolInfo::SymbolKind::Function, HeaderName, 1, {});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, CTypedefTest) {
  static const char Code[] = R"(
      typedef unsigned size_t_;
      typedef struct { int x; } X;
      using XX = X;
      )";
  runFindAllSymbols(Code);

  SymbolInfo Symbol = SymbolInfo("size_t_", SymbolInfo::SymbolKind::TypedefName,
                                 HeaderName, 2, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol =
      SymbolInfo("X", SymbolInfo::SymbolKind::TypedefName, HeaderName, 3, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol =
      SymbolInfo("XX", SymbolInfo::SymbolKind::TypedefName, HeaderName, 4, {});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, EnumTest) {
  static const char Code[] = R"(
      enum Glob_E { G1, G2 };
      enum class Altitude { high='h', low='l'};
      enum { A1, A2 };
      class A {
      public:
        enum A_ENUM { X1, X2 };
      };
      )";
  runFindAllSymbols(Code);

  SymbolInfo Symbol =
      SymbolInfo("Glob_E", SymbolInfo::SymbolKind::EnumDecl, HeaderName, 2, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol =
      SymbolInfo("G1", SymbolInfo::SymbolKind::EnumConstantDecl, HeaderName, 2,
                 {{SymbolInfo::ContextType::EnumDecl, "Glob_E"}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol =
      SymbolInfo("G2", SymbolInfo::SymbolKind::EnumConstantDecl, HeaderName, 2,
                 {{SymbolInfo::ContextType::EnumDecl, "Glob_E"}});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("Altitude", SymbolInfo::SymbolKind::EnumDecl, HeaderName,
                      3, {});
  EXPECT_TRUE(hasSymbol(Symbol));
  Symbol =
      SymbolInfo("high", SymbolInfo::SymbolKind::EnumConstantDecl, HeaderName,
                 3, {{SymbolInfo::ContextType::EnumDecl, "Altitude"}});
  EXPECT_FALSE(hasSymbol(Symbol));

  Symbol = SymbolInfo("A1", SymbolInfo::SymbolKind::EnumConstantDecl,
                      HeaderName, 4, {{SymbolInfo::ContextType::EnumDecl, ""}});
  EXPECT_TRUE(hasSymbol(Symbol));
  Symbol = SymbolInfo("A2", SymbolInfo::SymbolKind::EnumConstantDecl,
                      HeaderName, 4, {{SymbolInfo::ContextType::EnumDecl, ""}});
  EXPECT_TRUE(hasSymbol(Symbol));
  Symbol = SymbolInfo("", SymbolInfo::SymbolKind::EnumDecl, HeaderName, 4, {});
  EXPECT_FALSE(hasSymbol(Symbol));

  Symbol = SymbolInfo("A_ENUM", SymbolInfo::SymbolKind::EnumDecl, HeaderName, 7,
                      {{SymbolInfo::ContextType::Record, "A"}});
  EXPECT_FALSE(hasSymbol(Symbol));

  Symbol = SymbolInfo("X1", SymbolInfo::SymbolKind::EnumDecl, HeaderName, 7,
                      {{SymbolInfo::ContextType::EnumDecl, "A_ENUM"},
                       {SymbolInfo::ContextType::Record, "A"}});
  EXPECT_FALSE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, IWYUPrivatePragmaTest) {
  static const char Code[] = R"(
    // IWYU pragma: private, include "bar.h"
    struct Bar {
    };
  )";
  runFindAllSymbols(Code);

  SymbolInfo Symbol =
      SymbolInfo("Bar", SymbolInfo::SymbolKind::Class, "bar.h", 3, {});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, MacroTest) {
  static const char Code[] = R"(
    #define X
    #define Y 1
    #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
  )";
  runFindAllSymbols(Code);
  SymbolInfo Symbol =
      SymbolInfo("X", SymbolInfo::SymbolKind::Macro, HeaderName, 2, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("Y", SymbolInfo::SymbolKind::Macro, HeaderName, 3, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("MAX", SymbolInfo::SymbolKind::Macro, HeaderName, 4, {});
  EXPECT_TRUE(hasSymbol(Symbol));
}

TEST_F(FindAllSymbolsTest, MacroTestWithIWYU) {
  static const char Code[] = R"(
    // IWYU pragma: private, include "bar.h"
    #define X
    #define Y 1
    #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
  )";
  runFindAllSymbols(Code);
  SymbolInfo Symbol =
      SymbolInfo("X", SymbolInfo::SymbolKind::Macro, "bar.h", 3, {});
  EXPECT_EQ(3, Reporter.getSymbols().size());
  EXPECT_EQ("bar.h", Reporter.getSymbols().front().getFilePath());
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("Y", SymbolInfo::SymbolKind::Macro, "bar.h", 4, {});
  EXPECT_TRUE(hasSymbol(Symbol));

  Symbol = SymbolInfo("MAX", SymbolInfo::SymbolKind::Macro, "bar.h", 5, {});
  EXPECT_TRUE(hasSymbol(Symbol));
}

} // namespace find_all_symbols
} // namespace clang
<|endoftext|>


<commit_before>reWriteForSteve(){

  double tmp, mPt, value, err;
  const int nFile=5;
  const int nCent=10;
  const int nPt=20;
  char inFilesD[nFile][200]={"outchi422Den_corrFlow.txt","outchi523Den_corrFlow.txt","outchi6222Den_corrFlow.txt","outchi633Den_corrFlow.txt","outchi7223Den_corrFlow.txt"};
  char outFilesD[nFile][nCent][200]={
{"D24_0_5.txt", "D24_5_10.txt","D24_10_15.txt","D24_15_20.txt","D24_20_25.txt","D24_25_30.txt","D24_30_35.txt","D24_35_40.txt","D24_40_50.txt","D24_50_60.txt"},
{"D2232_0_5.txt", "D2232_5_10.txt","D2232_10_15.txt","D2232_15_20.txt","D2232_20_25.txt","D2232_25_30.txt","D2232_30_35.txt","D2232_35_40.txt","D2232_40_50.txt","D2232_50_60.txt"},
{"D26_0_5.txt", "D26_5_10.txt","D26_10_15.txt","D26_15_20.txt","D26_20_25.txt","D26_25_30.txt","D26_30_35.txt","D26_35_40.txt","D26_40_50.txt","D26_50_60.txt"},
{"D36_0_5.txt", "D36_5_10.txt","D36_10_15.txt","D36_15_20.txt","D36_20_25.txt","D36_25_30.txt","D36_30_35.txt","D36_35_40.txt","D36_40_50.txt","D36_50_60.txt"},
{"D2432_0_5.txt", "D2432_5_10.txt","D2432_10_15.txt","D2432_15_20.txt","D2432_20_25.txt","D2432_25_30.txt","D2432_30_35.txt","D2432_35_40.txt","D2432_40_50.txt","D2432_50_60.txt"}
};
  for(int i=0; i<nFile; i++){
    ifstream inFile;
    inFile.open(inFilesD[i]);
    for(int j=0; j<nCent; j++){
      ofstream outFile;
      outFile.open(outFilesD[i][j]);
      inFile>>tmp; inFile>>tmp;
      for(int k=0; k<nPt; k++){
        inFile>>tmp; inFile>>tmp; inFile>>mPt; inFile>>tmp; inFile>>value; inFile>>err;
        if(k<16)
          outFile<<mPt<<"     "<<value<<"     "<<err<<endl;
      }
      outFile.close();
    }
    inFile.close();
  }

}

<commit_msg>add numerator<commit_after>reWriteForSteve(){

  double tmp, mPt, value, err;
  const int nFile=5;
  const int nCent=10;
  const int nPt=20;

// Den
  char inFilesD[nFile][200]={"outchi422Den_corrFlow.txt","outchi523Den_corrFlow.txt","outchi6222Den_corrFlow.txt","outchi633Den_corrFlow.txt","outchi7223Den_corrFlow.txt"};
  char outFilesD[nFile][nCent][200]={
{"D24_0_5.txt", "D24_5_10.txt","D24_10_15.txt","D24_15_20.txt","D24_20_25.txt","D24_25_30.txt","D24_30_35.txt","D24_35_40.txt","D24_40_50.txt","D24_50_60.txt"},
{"D2232_0_5.txt", "D2232_5_10.txt","D2232_10_15.txt","D2232_15_20.txt","D2232_20_25.txt","D2232_25_30.txt","D2232_30_35.txt","D2232_35_40.txt","D2232_40_50.txt","D2232_50_60.txt"},
{"D26_0_5.txt", "D26_5_10.txt","D26_10_15.txt","D26_15_20.txt","D26_20_25.txt","D26_25_30.txt","D26_30_35.txt","D26_35_40.txt","D26_40_50.txt","D26_50_60.txt"},
{"D36_0_5.txt", "D36_5_10.txt","D36_10_15.txt","D36_15_20.txt","D36_20_25.txt","D36_25_30.txt","D36_30_35.txt","D36_35_40.txt","D36_40_50.txt","D36_50_60.txt"},
{"D2432_0_5.txt", "D2432_5_10.txt","D2432_10_15.txt","D2432_15_20.txt","D2432_20_25.txt","D2432_25_30.txt","D2432_30_35.txt","D2432_35_40.txt","D2432_40_50.txt","D2432_50_60.txt"}
};
  for(int i=0; i<nFile; i++){
    ifstream inFile;
    inFile.open(inFilesD[i]);
    for(int j=0; j<nCent; j++){
      ofstream outFile;
      outFile.open(outFilesD[i][j]);
      inFile>>tmp; inFile>>tmp;
      for(int k=0; k<nPt; k++){
        inFile>>tmp; inFile>>tmp; inFile>>mPt; inFile>>tmp; inFile>>value; inFile>>err;
        if(k<16)
          outFile<<mPt<<"     "<<value<<"     "<<err<<endl;
      }
      outFile.close();
    }
    inFile.close();
  }

// Num
  char inFilesN[nFile][200]={"outchi422Num_corrFlow.txt","outchi523Num_corrFlow.txt","outchi6222Num_corrFlow.txt","outchi633Num_corrFlow.txt","outchi7223Num_corrFlow.txt"};
  char outFilesN[nFile][nCent][200]={
{"N42_0_5.txt", "N42_5_10.txt","N42_10_15.txt","N42_15_20.txt","N42_20_25.txt","N42_25_30.txt","N42_30_35.txt","N42_35_40.txt","N42_40_50.txt","N42_50_60.txt"},
{"N523_0_5.txt", "N523_5_10.txt","N523_10_15.txt","N523_15_20.txt","N523_20_25.txt","N523_25_30.txt","N523_30_35.txt","N523_35_40.txt","N523_40_50.txt","N523_50_60.txt"},
{"N62_0_5.txt", "N62_5_10.txt","N62_10_15.txt","N62_15_20.txt","N62_20_25.txt","N62_25_30.txt","N62_30_35.txt","N62_35_40.txt","N62_40_50.txt","N62_50_60.txt"},
{"N63_0_5.txt", "N63_5_10.txt","N63_10_15.txt","N63_15_20.txt","N63_20_25.txt","N63_25_30.txt","N63_30_35.txt","N63_35_40.txt","N63_40_50.txt","N63_50_60.txt"},
{"N723_0_5.txt", "N723_5_10.txt","N723_10_15.txt","N723_15_20.txt","N723_20_25.txt","N723_25_30.txt","N723_30_35.txt","N723_35_40.txt","N723_40_50.txt","N723_50_60.txt"}
};
  for(int i=0; i<nFile; i++){
    ifstream inFile;
    inFile.open(inFilesN[i]);
    for(int j=0; j<nCent; j++){
      ofstream outFile;
      outFile.open(outFilesN[i][j]);
      inFile>>tmp; inFile>>tmp;
      for(int k=0; k<nPt; k++){
        inFile>>tmp; inFile>>tmp; inFile>>mPt; inFile>>tmp; inFile>>value; inFile>>err;
        if(k<16)
          outFile<<mPt<<"     "<<value<<"     "<<err<<endl;
      }
      outFile.close();
    }
    inFile.close();
  }

// Chi

}

<|endoftext|>


<commit_before>#include "Shader_Loader.h"

#include <fstream>
#include <vector>
#include <sstream>
#include <stdexcept>

namespace Shader
{
    namespace
    {
        void checkErrors(GLuint shaderId, GLenum statusType, const std::string& errorType)
        {
            auto bufferSize = 512;

            GLint isSuccess;
            GLchar infoLog[bufferSize];

            glGetShaderiv (shaderId, statusType, &isSuccess);
            if (!isSuccess)
            {
                glGetShaderInfoLog (shaderId, bufferSize, nullptr, infoLog);
                throw std::runtime_error ("Shader loading error.\nType: " + errorType + "\nWhat: " + infoLog);
            }
        }

        std::string getSource (const std::string& shaderFile)
        {
            std::ifstream shaderSourceFile ("Shaders/" + shaderFile + ".glsl");
            if (!shaderSourceFile.is_open())
            {
                throw std::runtime_error ("Unable to open the shader file: " + shaderFile + ".glsl");
            }
            shaderSourceFile.exceptions(std::ifstream::badbit);

            std::string source;
            std::stringstream stream;

            try
            {
                stream << shaderSourceFile.rdbuf();
                source = stream.str();
            }
            catch ( std::ifstream::failure& e)
            {
                throw std::runtime_error ("Unable to read the shader file: " + shaderFile + ".glsl");
            }

            return source;
        }

        GLuint compileShader (const char* source, GLenum type)
        {
            auto shaderId = glCreateShader(type);

            glShaderSource  (shaderId, 1, &source, nullptr);
            glCompileShader (shaderId);

            checkErrors(shaderId, GL_COMPILE_STATUS, "Error compiling shader!");

            return shaderId;
        }

        GLuint createProgram(GLuint vertexShaderId, GLuint fragmentShaderId)
        {
            auto shaderProgrsm = glCreateProgram();

            glAttachShader (shaderProgrsm, vertexShaderId);
            glAttachShader (shaderProgrsm, fragmentShaderId);
            glLinkProgram  (shaderProgrsm);

            return shaderProgrsm;
        }
    }

    GLuint load (const std::string& vertexShaderFile, const std::string& fragmentShaderFile)
    {
        auto vertexSource    = getSource (vertexShaderFile);
        auto fragmentSource  = getSource (fragmentShaderFile);

        auto vertexId   = compileShader(vertexSource.c_str(),   GL_VERTEX_SHADER);
        auto fragmentId = compileShader(fragmentSource.c_str(), GL_FRAGMENT_SHADER);

        auto shaderProgramId = createProgram(vertexId, fragmentId);

        glDeleteShader(vertexId);
        glDeleteShader(fragmentId);

        return shaderProgramId;
    }
} //Namespace Shader
<commit_msg>remove anon namepsace<commit_after>#include "Shader_Loader.h"

#include <fstream>
#include <vector>
#include <sstream>
#include <stdexcept>

namespace Shader
{
    void checkErrors(GLuint shaderId, GLenum statusType, const std::string& errorType)
    {
        auto bufferSize = 512;

        GLint isSuccess;
        GLchar infoLog[bufferSize];

        glGetShaderiv (shaderId, statusType, &isSuccess);
        if (!isSuccess)
        {
            glGetShaderInfoLog (shaderId, bufferSize, nullptr, infoLog);
            throw std::runtime_error ("Shader loading error.\nType: " + errorType + "\nWhat: " + infoLog);
        }
    }

    std::string getSource (const std::string& shaderFile)
    {
        std::ifstream shaderSourceFile ("Shaders/" + shaderFile + ".glsl");
        if (!shaderSourceFile.is_open())
        {
            throw std::runtime_error ("Unable to open the shader file: " + shaderFile + ".glsl");
        }
        shaderSourceFile.exceptions(std::ifstream::badbit);

        std::string source;
        std::stringstream stream;

        try
        {
            stream << shaderSourceFile.rdbuf();
            source = stream.str();
        }
        catch ( std::ifstream::failure& e)
        {
            throw std::runtime_error ("Unable to read the shader file: " + shaderFile + ".glsl");
        }

        return source;
    }

    GLuint compileShader (const char* source, GLenum type)
    {
        auto shaderId = glCreateShader(type);

        glShaderSource  (shaderId, 1, &source, nullptr);
        glCompileShader (shaderId);

        checkErrors(shaderId, GL_COMPILE_STATUS, "Error compiling shader!");

        return shaderId;
    }

    GLuint createProgram(GLuint vertexShaderId, GLuint fragmentShaderId)
    {
        auto shaderProgrsm = glCreateProgram();

        glAttachShader (shaderProgrsm, vertexShaderId);
        glAttachShader (shaderProgrsm, fragmentShaderId);
        glLinkProgram  (shaderProgrsm);

        return shaderProgrsm;
    }

    GLuint load (const std::string& vertexShaderFile, const std::string& fragmentShaderFile)
    {
        auto vertexSource    = getSource (vertexShaderFile);
        auto fragmentSource  = getSource (fragmentShaderFile);

        auto vertexId   = compileShader(vertexSource.c_str(),   GL_VERTEX_SHADER);
        auto fragmentId = compileShader(fragmentSource.c_str(), GL_FRAGMENT_SHADER);

        auto shaderProgramId = createProgram(vertexId, fragmentId);

        glDeleteShader(vertexId);
        glDeleteShader(fragmentId);

        return shaderProgramId;
    }
} //Namespace Shader
<|endoftext|>


<commit_before>/*************************************************************************/
/*  emws_peer.cpp                                                        */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* 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.                */
/*************************************************************************/

#ifdef WEB_ENABLED

#include "emws_peer.h"

#include "core/io/ip.h"

void EMWSPeer::_esws_on_connect(void *p_obj, char *p_proto) {
	EMWSPeer *peer = static_cast<EMWSPeer *>(p_obj);
	peer->ready_state = STATE_OPEN;
	peer->selected_protocol.parse_utf8(p_proto);
}

void EMWSPeer::_esws_on_message(void *p_obj, const uint8_t *p_data, int p_data_size, int p_is_string) {
	EMWSPeer *peer = static_cast<EMWSPeer *>(p_obj);
	uint8_t is_string = p_is_string ? 1 : 0;
	peer->in_buffer.write_packet(p_data, p_data_size, &is_string);
}

void EMWSPeer::_esws_on_error(void *p_obj) {
	EMWSPeer *peer = static_cast<EMWSPeer *>(p_obj);
	peer->ready_state = STATE_CLOSED;
}

void EMWSPeer::_esws_on_close(void *p_obj, int p_code, const char *p_reason, int p_was_clean) {
	EMWSPeer *peer = static_cast<EMWSPeer *>(p_obj);
	peer->close_code = p_code;
	peer->close_reason.parse_utf8(p_reason);
	peer->ready_state = STATE_CLOSED;
}

Error EMWSPeer::connect_to_url(const String &p_url, bool p_verify_tls, Ref<X509Certificate> p_tls_certificate) {
	ERR_FAIL_COND_V(ready_state != STATE_CLOSED, ERR_ALREADY_IN_USE);
	_clear();

	String host;
	String path;
	String scheme;
	int port = 0;
	Error err = p_url.parse_url(scheme, host, port, path);
	ERR_FAIL_COND_V_MSG(err != OK, err, "Invalid URL: " + p_url);

	if (scheme.is_empty()) {
		scheme = "ws://";
	}
	ERR_FAIL_COND_V_MSG(scheme != "ws://" && scheme != "wss://", ERR_INVALID_PARAMETER, vformat("Invalid protocol: \"%s\" (must be either \"ws://\" or \"wss://\").", scheme));

	String proto_string;
	for (int i = 0; i < supported_protocols.size(); i++) {
		if (i != 0) {
			proto_string += ",";
		}
		proto_string += supported_protocols[i];
	}

	if (handshake_headers.size()) {
		WARN_PRINT_ONCE("Custom headers are not supported in Web platform.");
	}
	if (p_tls_certificate.is_valid()) {
		WARN_PRINT_ONCE("Custom SSL certificates are not supported in Web platform.");
	}

	requested_url = scheme + host;

	if (port && ((scheme == "ws://" && port != 80) || (scheme == "wss://" && port != 443))) {
		requested_url += ":" + String::num(port);
	}

	peer_sock = godot_js_websocket_create(this, requested_url.utf8().get_data(), proto_string.utf8().get_data(), &_esws_on_connect, &_esws_on_message, &_esws_on_error, &_esws_on_close);
	if (peer_sock == -1) {
		return FAILED;
	}
	in_buffer.resize(nearest_shift(inbound_buffer_size), max_queued_packets);
	packet_buffer.resize(inbound_buffer_size);
	ready_state = STATE_CONNECTING;
	return OK;
}

Error EMWSPeer::accept_stream(Ref<StreamPeer> p_stream) {
	WARN_PRINT_ONCE("Acting as WebSocket server is not supported in Web platforms.");
	return ERR_UNAVAILABLE;
}

Error EMWSPeer::_send(const uint8_t *p_buffer, int p_buffer_size, bool p_binary) {
	ERR_FAIL_COND_V(outbound_buffer_size > 0 && (get_current_outbound_buffered_amount() + p_buffer_size >= outbound_buffer_size), ERR_OUT_OF_MEMORY);

	if (godot_js_websocket_send(peer_sock, p_buffer, p_buffer_size, p_binary ? 1 : 0) != 0) {
		return FAILED;
	}
	return OK;
}

Error EMWSPeer::send(const uint8_t *p_buffer, int p_buffer_size, WriteMode p_mode) {
	return _send(p_buffer, p_buffer_size, p_mode == WRITE_MODE_BINARY);
}

Error EMWSPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
	return _send(p_buffer, p_buffer_size, true);
}

Error EMWSPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
	if (in_buffer.packets_left() == 0) {
		return ERR_UNAVAILABLE;
	}

	int read = 0;
	Error err = in_buffer.read_packet(packet_buffer.ptrw(), packet_buffer.size(), &was_string, read);
	ERR_FAIL_COND_V(err != OK, err);

	*r_buffer = packet_buffer.ptr();
	r_buffer_size = read;

	return OK;
}

int EMWSPeer::get_available_packet_count() const {
	return in_buffer.packets_left();
}

int EMWSPeer::get_current_outbound_buffered_amount() const {
	if (peer_sock != -1) {
		return godot_js_websocket_buffered_amount(peer_sock);
	}
	return 0;
}

bool EMWSPeer::was_string_packet() const {
	return was_string;
}

void EMWSPeer::_clear() {
	if (peer_sock != -1) {
		godot_js_websocket_destroy(peer_sock);
		peer_sock = -1;
	}
	ready_state = STATE_CLOSED;
	was_string = 0;
	close_code = -1;
	close_reason.clear();
	selected_protocol.clear();
	requested_url.clear();
	in_buffer.clear();
	packet_buffer.clear();
}

void EMWSPeer::close(int p_code, String p_reason) {
	if (p_code < 0) {
		if (peer_sock != -1) {
			godot_js_websocket_destroy(peer_sock);
			peer_sock = -1;
		}
		ready_state = STATE_CLOSED;
	}
	if (ready_state == STATE_CONNECTING || ready_state == STATE_OPEN) {
		ready_state = STATE_CLOSING;
		if (peer_sock != -1) {
			godot_js_websocket_close(peer_sock, p_code, p_reason.utf8().get_data());
		} else {
			ready_state = STATE_CLOSED;
		}
	}
	in_buffer.clear();
	packet_buffer.clear();
}

void EMWSPeer::poll() {
	// Automatically polled by the navigator.
}

WebSocketPeer::State EMWSPeer::get_ready_state() const {
	return ready_state;
}

int EMWSPeer::get_close_code() const {
	return close_code;
}

String EMWSPeer::get_close_reason() const {
	return close_reason;
}

String EMWSPeer::get_selected_protocol() const {
	return selected_protocol;
}

String EMWSPeer::get_requested_url() const {
	return requested_url;
}

IPAddress EMWSPeer::get_connected_host() const {
	ERR_FAIL_V_MSG(IPAddress(), "Not supported in Web export.");
}

uint16_t EMWSPeer::get_connected_port() const {
	ERR_FAIL_V_MSG(0, "Not supported in Web export.");
}

void EMWSPeer::set_no_delay(bool p_enabled) {
	ERR_FAIL_MSG("'set_no_delay' is not supported in Web export.");
}

EMWSPeer::EMWSPeer() {
}

EMWSPeer::~EMWSPeer() {
	_clear();
}

#endif // WEB_ENABLED
<commit_msg>Fix WebSocket connection failed on Web.<commit_after>/*************************************************************************/
/*  emws_peer.cpp                                                        */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* 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.                */
/*************************************************************************/

#ifdef WEB_ENABLED

#include "emws_peer.h"

#include "core/io/ip.h"

void EMWSPeer::_esws_on_connect(void *p_obj, char *p_proto) {
	EMWSPeer *peer = static_cast<EMWSPeer *>(p_obj);
	peer->ready_state = STATE_OPEN;
	peer->selected_protocol.parse_utf8(p_proto);
}

void EMWSPeer::_esws_on_message(void *p_obj, const uint8_t *p_data, int p_data_size, int p_is_string) {
	EMWSPeer *peer = static_cast<EMWSPeer *>(p_obj);
	uint8_t is_string = p_is_string ? 1 : 0;
	peer->in_buffer.write_packet(p_data, p_data_size, &is_string);
}

void EMWSPeer::_esws_on_error(void *p_obj) {
	EMWSPeer *peer = static_cast<EMWSPeer *>(p_obj);
	peer->ready_state = STATE_CLOSED;
}

void EMWSPeer::_esws_on_close(void *p_obj, int p_code, const char *p_reason, int p_was_clean) {
	EMWSPeer *peer = static_cast<EMWSPeer *>(p_obj);
	peer->close_code = p_code;
	peer->close_reason.parse_utf8(p_reason);
	peer->ready_state = STATE_CLOSED;
}

Error EMWSPeer::connect_to_url(const String &p_url, bool p_verify_tls, Ref<X509Certificate> p_tls_certificate) {
	ERR_FAIL_COND_V(ready_state != STATE_CLOSED, ERR_ALREADY_IN_USE);
	_clear();

	String host;
	String path;
	String scheme;
	int port = 0;
	Error err = p_url.parse_url(scheme, host, port, path);
	ERR_FAIL_COND_V_MSG(err != OK, err, "Invalid URL: " + p_url);

	if (scheme.is_empty()) {
		scheme = "ws://";
	}
	ERR_FAIL_COND_V_MSG(scheme != "ws://" && scheme != "wss://", ERR_INVALID_PARAMETER, vformat("Invalid protocol: \"%s\" (must be either \"ws://\" or \"wss://\").", scheme));

	String proto_string;
	for (int i = 0; i < supported_protocols.size(); i++) {
		if (i != 0) {
			proto_string += ",";
		}
		proto_string += supported_protocols[i];
	}

	if (handshake_headers.size()) {
		WARN_PRINT_ONCE("Custom headers are not supported in Web platform.");
	}
	if (p_tls_certificate.is_valid()) {
		WARN_PRINT_ONCE("Custom SSL certificates are not supported in Web platform.");
	}

	requested_url = scheme + host;

	if (port && ((scheme == "ws://" && port != 80) || (scheme == "wss://" && port != 443))) {
		requested_url += ":" + String::num(port);
	}

	if (!path.is_empty()) {
		requested_url += path;
	}

	peer_sock = godot_js_websocket_create(this, requested_url.utf8().get_data(), proto_string.utf8().get_data(), &_esws_on_connect, &_esws_on_message, &_esws_on_error, &_esws_on_close);
	if (peer_sock == -1) {
		return FAILED;
	}
	in_buffer.resize(nearest_shift(inbound_buffer_size), max_queued_packets);
	packet_buffer.resize(inbound_buffer_size);
	ready_state = STATE_CONNECTING;
	return OK;
}

Error EMWSPeer::accept_stream(Ref<StreamPeer> p_stream) {
	WARN_PRINT_ONCE("Acting as WebSocket server is not supported in Web platforms.");
	return ERR_UNAVAILABLE;
}

Error EMWSPeer::_send(const uint8_t *p_buffer, int p_buffer_size, bool p_binary) {
	ERR_FAIL_COND_V(outbound_buffer_size > 0 && (get_current_outbound_buffered_amount() + p_buffer_size >= outbound_buffer_size), ERR_OUT_OF_MEMORY);

	if (godot_js_websocket_send(peer_sock, p_buffer, p_buffer_size, p_binary ? 1 : 0) != 0) {
		return FAILED;
	}
	return OK;
}

Error EMWSPeer::send(const uint8_t *p_buffer, int p_buffer_size, WriteMode p_mode) {
	return _send(p_buffer, p_buffer_size, p_mode == WRITE_MODE_BINARY);
}

Error EMWSPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
	return _send(p_buffer, p_buffer_size, true);
}

Error EMWSPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
	if (in_buffer.packets_left() == 0) {
		return ERR_UNAVAILABLE;
	}

	int read = 0;
	Error err = in_buffer.read_packet(packet_buffer.ptrw(), packet_buffer.size(), &was_string, read);
	ERR_FAIL_COND_V(err != OK, err);

	*r_buffer = packet_buffer.ptr();
	r_buffer_size = read;

	return OK;
}

int EMWSPeer::get_available_packet_count() const {
	return in_buffer.packets_left();
}

int EMWSPeer::get_current_outbound_buffered_amount() const {
	if (peer_sock != -1) {
		return godot_js_websocket_buffered_amount(peer_sock);
	}
	return 0;
}

bool EMWSPeer::was_string_packet() const {
	return was_string;
}

void EMWSPeer::_clear() {
	if (peer_sock != -1) {
		godot_js_websocket_destroy(peer_sock);
		peer_sock = -1;
	}
	ready_state = STATE_CLOSED;
	was_string = 0;
	close_code = -1;
	close_reason.clear();
	selected_protocol.clear();
	requested_url.clear();
	in_buffer.clear();
	packet_buffer.clear();
}

void EMWSPeer::close(int p_code, String p_reason) {
	if (p_code < 0) {
		if (peer_sock != -1) {
			godot_js_websocket_destroy(peer_sock);
			peer_sock = -1;
		}
		ready_state = STATE_CLOSED;
	}
	if (ready_state == STATE_CONNECTING || ready_state == STATE_OPEN) {
		ready_state = STATE_CLOSING;
		if (peer_sock != -1) {
			godot_js_websocket_close(peer_sock, p_code, p_reason.utf8().get_data());
		} else {
			ready_state = STATE_CLOSED;
		}
	}
	in_buffer.clear();
	packet_buffer.clear();
}

void EMWSPeer::poll() {
	// Automatically polled by the navigator.
}

WebSocketPeer::State EMWSPeer::get_ready_state() const {
	return ready_state;
}

int EMWSPeer::get_close_code() const {
	return close_code;
}

String EMWSPeer::get_close_reason() const {
	return close_reason;
}

String EMWSPeer::get_selected_protocol() const {
	return selected_protocol;
}

String EMWSPeer::get_requested_url() const {
	return requested_url;
}

IPAddress EMWSPeer::get_connected_host() const {
	ERR_FAIL_V_MSG(IPAddress(), "Not supported in Web export.");
}

uint16_t EMWSPeer::get_connected_port() const {
	ERR_FAIL_V_MSG(0, "Not supported in Web export.");
}

void EMWSPeer::set_no_delay(bool p_enabled) {
	ERR_FAIL_MSG("'set_no_delay' is not supported in Web export.");
}

EMWSPeer::EMWSPeer() {
}

EMWSPeer::~EMWSPeer() {
	_clear();
}

#endif // WEB_ENABLED
<|endoftext|>