<commit_before>/*************************************************************************
 *
 *  $RCSfile: hfi_tag.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-23 09:01:08 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include <precomp.h>
#include "hfi_tag.hxx"

// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_module.hxx>
#include <ary_i/ci_text2.hxx>
#include <ary_i/d_token.hxx>
#include <toolkit/out_tree.hxx>
#include <adc_cl.hxx>
#include <adc_msg.hxx>
#include "hfi_typetext.hxx"
#include "hi_ary.hxx"
#include "hi_env.hxx"
#include "hi_linkhelper.hxx"

using ary::info::DocuTex2;

inline void
HF_IdlTag::Enter_TextOut( Xml::Element & o_rText ) const
{
    aTextOut.Out().Enter(o_rText);
}

inline void
HF_IdlTag::Leave_TextOut() const
{
    aTextOut.Out().Leave();
}

inline void
HF_IdlTag::PutText_Out( const ary::info::DocuTex2 & i_rText ) const
{
    i_rText.DisplayAt( const_cast< HF_IdlDocuTextDisplay& >(aTextOut) );
}

HF_IdlTag::HF_IdlTag( Environment &                 io_rEnv,
                      const ary::idl::CodeEntity &  i_rScopeGivingCe )
    :   HtmlFactory_Idl( io_rEnv, 0 ),
        pTitleOut(0),
        aTextOut(io_rEnv, 0, i_rScopeGivingCe)
{
}

HF_IdlTag::~HF_IdlTag()
{
}

void
HF_IdlTag::Produce_byData( Xml::Element &              o_rTitle,
                           Xml::Element &              o_rText,
                           const ary::info::AtTag2 &   i_rTag ) const
{
    pTitleOut = &o_rTitle;
    Enter_TextOut(o_rText);
    i_rTag.DisplayAt( const_cast< HF_IdlTag& >(*this) );
    Leave_TextOut();
}

void
HF_IdlTag::Display_StdAtTag( const csi::dsapi::DT_StdAtTag & i_rTag )
{
    if ( i_rTag.Text().IsEmpty() )
        return;

    csv_assert( pTitleOut != 0 );
    *pTitleOut << i_rTag.Title();
    PutText_Out( i_rTag.Text() );
}

void
HF_IdlTag::Display_SeeAlsoAtTag( const csi::dsapi::DT_SeeAlsoAtTag & i_rTag )
{
    if ( i_rTag.Text().IsEmpty() )
        return;

    csv_assert( pTitleOut != 0 );
    *pTitleOut << "See also";

    HF_IdlTypeText aLinkText(Env(),aTextOut.CurOut(),true, &aTextOut.ScopeGivingCe());
    aLinkText.Produce_byData( i_rTag.LinkText() );

    aTextOut.CurOut() << new Html::LineBreak;
    PutText_Out( i_rTag.Text() );
}

void
HF_IdlTag::Display_ParameterAtTag( const csi::dsapi::DT_ParameterAtTag & i_rTag )
{
    csv_assert( pTitleOut != 0 );
    *pTitleOut
        << ( StreamLock(100)() << "Parameter " << i_rTag.Title() << c_str );
    PutText_Out( i_rTag.Text() );
}

void
HF_IdlTag::Display_SinceAtTag( const csi::dsapi::DT_SinceAtTag & i_rTag )
{
    csv_assert(pTitleOut != 0);

    if ( i_rTag.Text().IsEmpty() )
    {
         return;
    }

    // Transform the value of the @since tag into the text to be displayed.
    String sDisplay =
        autodoc::CommandLine::Get_().DisplayOf_SinceTagValue(
                                        i_rTag.Text().TextOfFirstToken() );
    if (sDisplay.empty())
        return;

    *pTitleOut << "Since ";
    DocuTex2 aHelp;
    aHelp.AddToken(* new csi::dsapi::DT_TextToken(sDisplay));
    PutText_Out(aHelp);
}

//********************      HF_IdlShortDocu     *********************/

HF_IdlShortDocu::HF_IdlShortDocu( Environment &         io_rEnv,
                                  Xml::Element &        o_rOut )
    :   HtmlFactory_Idl( io_rEnv, &o_rOut )
{
}

HF_IdlShortDocu::~HF_IdlShortDocu()
{
}

void
HF_IdlShortDocu::Produce_byData( const ary::idl::CodeEntity & i_rCe )
{
    if (i_rCe.Docu() == 0)
        return;

    const ce_info &
        rDocu = *i_rCe.Docu();
    if ( rDocu.IsDeprecated() )
    {
        CurOut()
            >> *new Html::Bold
                << "[ DEPRECATED ]" << new Html::LineBreak;
    }
    if ( rDocu.IsOptional() )
    {
        CurOut()
            >> *new Html::Bold
                << "[ OPTIONAL ]" << new Html::LineBreak;
    }

    HF_IdlDocuTextDisplay
        aText( Env(), &CurOut(), i_rCe);
    rDocu.Short().DisplayAt(aText);
}

//********************      HF_IdlDocuTextDisplay       *********************/

HF_IdlDocuTextDisplay::HF_IdlDocuTextDisplay( Environment &                 io_rEnv,
                                              Xml::Element *                o_pOut,
                                              const ary::idl::CodeEntity &  i_rScopeGivingCe )
    :   HtmlFactory_Idl(io_rEnv, o_pOut),
        sScope(),
        sLinkToken(),
        bGatherLink(false),
        pScopeGivingCe(&i_rScopeGivingCe)
{
}

HF_IdlDocuTextDisplay::~HF_IdlDocuTextDisplay()
{
}

void
HF_IdlDocuTextDisplay::Display_TextToken( const csi::dsapi::DT_TextToken & i_rToken )
{
    if (bGatherLink)
    {
        if (sLinkToken.length() == 0)
        {
            sLinkToken = i_rToken.GetText();
            return;
        }
        else
        {
            if ( pScopeGivingCe == 0 )
            {   // only in original file
                TheMessages().Out_TypeVsMemberMisuse(sLinkToken, Env().CurPageCe_AsText(), 0);
            }

//          Would be duplicate, therefore we do nothing:
//            else
//            {
//                Cerr() << "Error in documentation: Too many or too few tokens for a link in <member> or <type>." << Endl();
//                Cerr() << "  Link won't be created, but all tokens shown plain." << Endl();
//                Cerr() << "  \"" << sLinkToken << "\"";
//                if ( pScopeGivingCe != 0 )
//                    Cerr() << " in " << pScopeGivingCe->LocalName();
//                Cerr() << Endl();
//            }

            StopLinkGathering();
        }
    }   // endif (bGatherLink)

    CurOut() << new Xml::XmlCode( i_rToken.GetText() ) << " ";
}

void
HF_IdlDocuTextDisplay::Display_MupType( const csi::dsapi::DT_MupType & i_rToken )
{
    if (i_rToken.IsBegin())
    {
        StartLinkGathering(i_rToken.Scope());
    }
    else
    {
        if (bGatherLink)
        {
            CreateTypeLink();
            CurOut()
                << " ";
            StopLinkGathering();
        }
    }
}

void
HF_IdlDocuTextDisplay::Display_MupMember( const csi::dsapi::DT_MupMember & i_rToken )
{
    if (i_rToken.IsBegin())
    {
        StartLinkGathering(i_rToken.Scope());
    }
    else
    {
        if (bGatherLink)
        {
            CreateMemberLink();
            CurOut()
                << " ";
            StopLinkGathering();
        }
    }
}

void
HF_IdlDocuTextDisplay::Display_MupConst( const csi::dsapi::DT_MupConst & i_rToken )
{
    CurOut()
        >> *new Html::Bold
           << i_rToken.GetText();
    CurOut()
        << " ";
}

void
HF_IdlDocuTextDisplay::Display_Style( const csi::dsapi::DT_Style & i_rToken )
{
    CurOut() << new Xml::XmlCode( i_rToken.GetText() );
}

void
HF_IdlDocuTextDisplay::Display_EOL()
{
    CurOut() << "\n";
}

void
HF_IdlDocuTextDisplay::CreateTypeLink()
{
    if (strchr(sLinkToken,':') != 0)
    {
        TheMessages().Out_TypeVsMemberMisuse(sLinkToken, Env().CurPageCe_AsFile(".idl"), 0);
        CurOut() << sLinkToken;
        return;
    }
    HF_IdlTypeText aLink(Env(), CurOut(), true, &ScopeGivingCe());
    aLink.Produce_LinkInDocu(sScope, sLinkToken, String::Null_());
}

void
HF_IdlDocuTextDisplay::CreateMemberLink()
{

    HF_IdlTypeText aLink(Env(), CurOut(), true, &ScopeGivingCe());

    const char *
        sSplit = strchr(sLinkToken,':');

    if (sSplit != 0)
    {
        String sCe(sLinkToken.c_str(), sSplit - sLinkToken.c_str());
        String sMember(sSplit+2);

        if (NOT sScope.empty() OR ScopeGivingCe().LocalName() != sCe )
            aLink.Produce_LinkInDocu(sScope, sCe, sMember);
        else
            aLink.Produce_LocalLinkInDocu(sMember);
    }
    else
    {
        aLink.Produce_LocalLinkInDocu(sLinkToken);
    }
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.8); FILE MERGED 2005/09/05 13:11:06 rt 1.7.8.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hfi_tag.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 17:47:56 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#include <precomp.h>
#include "hfi_tag.hxx"

// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_module.hxx>
#include <ary_i/ci_text2.hxx>
#include <ary_i/d_token.hxx>
#include <toolkit/out_tree.hxx>
#include <adc_cl.hxx>
#include <adc_msg.hxx>
#include "hfi_typetext.hxx"
#include "hi_ary.hxx"
#include "hi_env.hxx"
#include "hi_linkhelper.hxx"

using ary::info::DocuTex2;

inline void
HF_IdlTag::Enter_TextOut( Xml::Element & o_rText ) const
{
    aTextOut.Out().Enter(o_rText);
}

inline void
HF_IdlTag::Leave_TextOut() const
{
    aTextOut.Out().Leave();
}

inline void
HF_IdlTag::PutText_Out( const ary::info::DocuTex2 & i_rText ) const
{
    i_rText.DisplayAt( const_cast< HF_IdlDocuTextDisplay& >(aTextOut) );
}

HF_IdlTag::HF_IdlTag( Environment &                 io_rEnv,
                      const ary::idl::CodeEntity &  i_rScopeGivingCe )
    :   HtmlFactory_Idl( io_rEnv, 0 ),
        pTitleOut(0),
        aTextOut(io_rEnv, 0, i_rScopeGivingCe)
{
}

HF_IdlTag::~HF_IdlTag()
{
}

void
HF_IdlTag::Produce_byData( Xml::Element &              o_rTitle,
                           Xml::Element &              o_rText,
                           const ary::info::AtTag2 &   i_rTag ) const
{
    pTitleOut = &o_rTitle;
    Enter_TextOut(o_rText);
    i_rTag.DisplayAt( const_cast< HF_IdlTag& >(*this) );
    Leave_TextOut();
}

void
HF_IdlTag::Display_StdAtTag( const csi::dsapi::DT_StdAtTag & i_rTag )
{
    if ( i_rTag.Text().IsEmpty() )
        return;

    csv_assert( pTitleOut != 0 );
    *pTitleOut << i_rTag.Title();
    PutText_Out( i_rTag.Text() );
}

void
HF_IdlTag::Display_SeeAlsoAtTag( const csi::dsapi::DT_SeeAlsoAtTag & i_rTag )
{
    if ( i_rTag.Text().IsEmpty() )
        return;

    csv_assert( pTitleOut != 0 );
    *pTitleOut << "See also";

    HF_IdlTypeText aLinkText(Env(),aTextOut.CurOut(),true, &aTextOut.ScopeGivingCe());
    aLinkText.Produce_byData( i_rTag.LinkText() );

    aTextOut.CurOut() << new Html::LineBreak;
    PutText_Out( i_rTag.Text() );
}

void
HF_IdlTag::Display_ParameterAtTag( const csi::dsapi::DT_ParameterAtTag & i_rTag )
{
    csv_assert( pTitleOut != 0 );
    *pTitleOut
        << ( StreamLock(100)() << "Parameter " << i_rTag.Title() << c_str );
    PutText_Out( i_rTag.Text() );
}

void
HF_IdlTag::Display_SinceAtTag( const csi::dsapi::DT_SinceAtTag & i_rTag )
{
    csv_assert(pTitleOut != 0);

    if ( i_rTag.Text().IsEmpty() )
    {
         return;
    }

    // Transform the value of the @since tag into the text to be displayed.
    String sDisplay =
        autodoc::CommandLine::Get_().DisplayOf_SinceTagValue(
                                        i_rTag.Text().TextOfFirstToken() );
    if (sDisplay.empty())
        return;

    *pTitleOut << "Since ";
    DocuTex2 aHelp;
    aHelp.AddToken(* new csi::dsapi::DT_TextToken(sDisplay));
    PutText_Out(aHelp);
}

//********************      HF_IdlShortDocu     *********************/

HF_IdlShortDocu::HF_IdlShortDocu( Environment &         io_rEnv,
                                  Xml::Element &        o_rOut )
    :   HtmlFactory_Idl( io_rEnv, &o_rOut )
{
}

HF_IdlShortDocu::~HF_IdlShortDocu()
{
}

void
HF_IdlShortDocu::Produce_byData( const ary::idl::CodeEntity & i_rCe )
{
    if (i_rCe.Docu() == 0)
        return;

    const ce_info &
        rDocu = *i_rCe.Docu();
    if ( rDocu.IsDeprecated() )
    {
        CurOut()
            >> *new Html::Bold
                << "[ DEPRECATED ]" << new Html::LineBreak;
    }
    if ( rDocu.IsOptional() )
    {
        CurOut()
            >> *new Html::Bold
                << "[ OPTIONAL ]" << new Html::LineBreak;
    }

    HF_IdlDocuTextDisplay
        aText( Env(), &CurOut(), i_rCe);
    rDocu.Short().DisplayAt(aText);
}

//********************      HF_IdlDocuTextDisplay       *********************/

HF_IdlDocuTextDisplay::HF_IdlDocuTextDisplay( Environment &                 io_rEnv,
                                              Xml::Element *                o_pOut,
                                              const ary::idl::CodeEntity &  i_rScopeGivingCe )
    :   HtmlFactory_Idl(io_rEnv, o_pOut),
        sScope(),
        sLinkToken(),
        bGatherLink(false),
        pScopeGivingCe(&i_rScopeGivingCe)
{
}

HF_IdlDocuTextDisplay::~HF_IdlDocuTextDisplay()
{
}

void
HF_IdlDocuTextDisplay::Display_TextToken( const csi::dsapi::DT_TextToken & i_rToken )
{
    if (bGatherLink)
    {
        if (sLinkToken.length() == 0)
        {
            sLinkToken = i_rToken.GetText();
            return;
        }
        else
        {
            if ( pScopeGivingCe == 0 )
            {   // only in original file
                TheMessages().Out_TypeVsMemberMisuse(sLinkToken, Env().CurPageCe_AsText(), 0);
            }

//          Would be duplicate, therefore we do nothing:
//            else
//            {
//                Cerr() << "Error in documentation: Too many or too few tokens for a link in <member> or <type>." << Endl();
//                Cerr() << "  Link won't be created, but all tokens shown plain." << Endl();
//                Cerr() << "  \"" << sLinkToken << "\"";
//                if ( pScopeGivingCe != 0 )
//                    Cerr() << " in " << pScopeGivingCe->LocalName();
//                Cerr() << Endl();
//            }

            StopLinkGathering();
        }
    }   // endif (bGatherLink)

    CurOut() << new Xml::XmlCode( i_rToken.GetText() ) << " ";
}

void
HF_IdlDocuTextDisplay::Display_MupType( const csi::dsapi::DT_MupType & i_rToken )
{
    if (i_rToken.IsBegin())
    {
        StartLinkGathering(i_rToken.Scope());
    }
    else
    {
        if (bGatherLink)
        {
            CreateTypeLink();
            CurOut()
                << " ";
            StopLinkGathering();
        }
    }
}

void
HF_IdlDocuTextDisplay::Display_MupMember( const csi::dsapi::DT_MupMember & i_rToken )
{
    if (i_rToken.IsBegin())
    {
        StartLinkGathering(i_rToken.Scope());
    }
    else
    {
        if (bGatherLink)
        {
            CreateMemberLink();
            CurOut()
                << " ";
            StopLinkGathering();
        }
    }
}

void
HF_IdlDocuTextDisplay::Display_MupConst( const csi::dsapi::DT_MupConst & i_rToken )
{
    CurOut()
        >> *new Html::Bold
           << i_rToken.GetText();
    CurOut()
        << " ";
}

void
HF_IdlDocuTextDisplay::Display_Style( const csi::dsapi::DT_Style & i_rToken )
{
    CurOut() << new Xml::XmlCode( i_rToken.GetText() );
}

void
HF_IdlDocuTextDisplay::Display_EOL()
{
    CurOut() << "\n";
}

void
HF_IdlDocuTextDisplay::CreateTypeLink()
{
    if (strchr(sLinkToken,':') != 0)
    {
        TheMessages().Out_TypeVsMemberMisuse(sLinkToken, Env().CurPageCe_AsFile(".idl"), 0);
        CurOut() << sLinkToken;
        return;
    }
    HF_IdlTypeText aLink(Env(), CurOut(), true, &ScopeGivingCe());
    aLink.Produce_LinkInDocu(sScope, sLinkToken, String::Null_());
}

void
HF_IdlDocuTextDisplay::CreateMemberLink()
{

    HF_IdlTypeText aLink(Env(), CurOut(), true, &ScopeGivingCe());

    const char *
        sSplit = strchr(sLinkToken,':');

    if (sSplit != 0)
    {
        String sCe(sLinkToken.c_str(), sSplit - sLinkToken.c_str());
        String sMember(sSplit+2);

        if (NOT sScope.empty() OR ScopeGivingCe().LocalName() != sCe )
            aLink.Produce_LinkInDocu(sScope, sCe, sMember);
        else
            aLink.Produce_LocalLinkInDocu(sMember);
    }
    else
    {
        aLink.Produce_LocalLinkInDocu(sLinkToken);
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hfi_tag.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 16:38:03 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#ifndef ADC_DISPLAY_HFI_TAG_HXX
#define ADC_DISPLAY_HFI_TAG_HXX

// BASE CLASSES
#include "hi_factory.hxx"
#include <ary_i/disdocum.hxx>
// USED SERVICES
#include <ary/idl/i_types4idl.hxx>
#include <ary_i/ci_atag2.hxx>
#include <ary_i/ci_text2.hxx>
#include <ary/doc/d_oldidldocu.hxx>

#include <toolkit/hf_docentry.hxx>

namespace ary
{
namespace idl
{
    class Module;
}
}

/** This class is an implementation of ary::inf::DocuText_Display
    and will be used by that interface.
*/
class HF_IdlDocuTextDisplay : public HtmlFactory_Idl,
                              public ary::inf::DocuText_Display
{
  public:
                        HF_IdlDocuTextDisplay(
                            Environment  &      io_rEnv,
                            Xml::Element *      o_pOut,
                            const ary::idl::CodeEntity &
                                                i_rScopeGivingCe );
    virtual             ~HF_IdlDocuTextDisplay();

    const ary::idl::CodeEntity &
                        ScopeGivingCe() const { return *pScopeGivingCe; }
  private:
    virtual void        Display_TextToken(
                            const csi::dsapi::DT_TextToken &
                                                i_rToken );
    virtual void        Display_White();

    virtual void        Display_MupType(
                            const csi::dsapi::DT_MupType &
                                                i_rToken );
    virtual void        Display_MupMember(
                            const csi::dsapi::DT_MupMember &
                                                i_rToken );
    virtual void        Display_MupConst(
                            const csi::dsapi::DT_MupConst &
                                                i_rToken );
    virtual void        Display_Style(
                            const csi::dsapi::DT_Style &    i_rToken );
    virtual void        Display_EOL();

    // Local
    void                StartLinkGathering(
                            const String &      i_sScope )
                                                { sLinkToken = ""; sScope = i_sScope; bGatherLink = true; }
    void                StopLinkGathering()     { bGatherLink = false; }
    /** @precond
        The scope is in sScope, the name is in sLinkToken.
    */
    void                CreateTypeLink();
    /** @precond
        The scope is in sScope, the qualified member-name is in sLinkToken.
    */
    void                CreateMemberLink();

    // DATA
    String              sScope;
    String              sLinkToken;
    bool                bGatherLink;
    const ary::idl::CodeEntity *
                        pScopeGivingCe;
};

class HF_IdlShortDocu : public HtmlFactory_Idl
{
  public:
                        HF_IdlShortDocu(
                            Environment &       io_rEnv,
                            Xml::Element &      o_rOut );
    virtual             ~HF_IdlShortDocu();

    void                Produce_byData(
                            const ary::idl::CodeEntity &
                                                i_rCe );
};

class HF_IdlTag : public HtmlFactory_Idl,
                  public ary::inf::DocuTag_Display
{
  public:
                        HF_IdlTag(
                            Environment &       io_rEnv,
                            const ary::idl::CodeEntity &
                                                i_rScopeGivingCe );
    virtual             ~HF_IdlTag();

    void                Produce_byData(
                            Xml::Element &      o_rTitle,
                            Xml::Element &      o_rText,
                            const ary::inf::AtTag2 &
                                                i_rTag ) const;
    void                Produce_byData(
                            Xml::Element &      o_rTitle,
                            Xml::Element &      o_rText,
                            const std::vector< csi::dsapi::DT_SeeAlsoAtTag* > &
                                                i_seeAlsoVector ) const;
  private:
    virtual void        Display_StdAtTag(
                            const csi::dsapi::DT_StdAtTag &
                                                i_rToken );
    virtual void        Display_SeeAlsoAtTag(
                            const csi::dsapi::DT_SeeAlsoAtTag &
                                                i_rToken );
    virtual void        Display_ParameterAtTag(
                            const csi::dsapi::DT_ParameterAtTag &
                                                i_rToken );
    virtual void        Display_SinceAtTag(
                            const csi::dsapi::DT_SinceAtTag &
                                                i_rToken );

    void                Enter_TextOut(
                            Xml::Element &      o_rText ) const;
    void                Leave_TextOut() const;
    void                PutText_Out(
                            const ary::inf::DocuTex2 &
                                                i_rText ) const;
    // DATA
    mutable Xml::Element *
                        pTitleOut;
    mutable HF_IdlDocuTextDisplay
                        aTextOut;
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.6.22); FILE MERGED 2008/03/28 16:02:06 rt 1.6.22.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: hfi_tag.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef ADC_DISPLAY_HFI_TAG_HXX
#define ADC_DISPLAY_HFI_TAG_HXX

// BASE CLASSES
#include "hi_factory.hxx"
#include <ary_i/disdocum.hxx>
// USED SERVICES
#include <ary/idl/i_types4idl.hxx>
#include <ary_i/ci_atag2.hxx>
#include <ary_i/ci_text2.hxx>
#include <ary/doc/d_oldidldocu.hxx>

#include <toolkit/hf_docentry.hxx>

namespace ary
{
namespace idl
{
    class Module;
}
}

/** This class is an implementation of ary::inf::DocuText_Display
    and will be used by that interface.
*/
class HF_IdlDocuTextDisplay : public HtmlFactory_Idl,
                              public ary::inf::DocuText_Display
{
  public:
                        HF_IdlDocuTextDisplay(
                            Environment  &      io_rEnv,
                            Xml::Element *      o_pOut,
                            const ary::idl::CodeEntity &
                                                i_rScopeGivingCe );
    virtual             ~HF_IdlDocuTextDisplay();

    const ary::idl::CodeEntity &
                        ScopeGivingCe() const { return *pScopeGivingCe; }
  private:
    virtual void        Display_TextToken(
                            const csi::dsapi::DT_TextToken &
                                                i_rToken );
    virtual void        Display_White();

    virtual void        Display_MupType(
                            const csi::dsapi::DT_MupType &
                                                i_rToken );
    virtual void        Display_MupMember(
                            const csi::dsapi::DT_MupMember &
                                                i_rToken );
    virtual void        Display_MupConst(
                            const csi::dsapi::DT_MupConst &
                                                i_rToken );
    virtual void        Display_Style(
                            const csi::dsapi::DT_Style &    i_rToken );
    virtual void        Display_EOL();

    // Local
    void                StartLinkGathering(
                            const String &      i_sScope )
                                                { sLinkToken = ""; sScope = i_sScope; bGatherLink = true; }
    void                StopLinkGathering()     { bGatherLink = false; }
    /** @precond
        The scope is in sScope, the name is in sLinkToken.
    */
    void                CreateTypeLink();
    /** @precond
        The scope is in sScope, the qualified member-name is in sLinkToken.
    */
    void                CreateMemberLink();

    // DATA
    String              sScope;
    String              sLinkToken;
    bool                bGatherLink;
    const ary::idl::CodeEntity *
                        pScopeGivingCe;
};

class HF_IdlShortDocu : public HtmlFactory_Idl
{
  public:
                        HF_IdlShortDocu(
                            Environment &       io_rEnv,
                            Xml::Element &      o_rOut );
    virtual             ~HF_IdlShortDocu();

    void                Produce_byData(
                            const ary::idl::CodeEntity &
                                                i_rCe );
};

class HF_IdlTag : public HtmlFactory_Idl,
                  public ary::inf::DocuTag_Display
{
  public:
                        HF_IdlTag(
                            Environment &       io_rEnv,
                            const ary::idl::CodeEntity &
                                                i_rScopeGivingCe );
    virtual             ~HF_IdlTag();

    void                Produce_byData(
                            Xml::Element &      o_rTitle,
                            Xml::Element &      o_rText,
                            const ary::inf::AtTag2 &
                                                i_rTag ) const;
    void                Produce_byData(
                            Xml::Element &      o_rTitle,
                            Xml::Element &      o_rText,
                            const std::vector< csi::dsapi::DT_SeeAlsoAtTag* > &
                                                i_seeAlsoVector ) const;
  private:
    virtual void        Display_StdAtTag(
                            const csi::dsapi::DT_StdAtTag &
                                                i_rToken );
    virtual void        Display_SeeAlsoAtTag(
                            const csi::dsapi::DT_SeeAlsoAtTag &
                                                i_rToken );
    virtual void        Display_ParameterAtTag(
                            const csi::dsapi::DT_ParameterAtTag &
                                                i_rToken );
    virtual void        Display_SinceAtTag(
                            const csi::dsapi::DT_SinceAtTag &
                                                i_rToken );

    void                Enter_TextOut(
                            Xml::Element &      o_rText ) const;
    void                Leave_TextOut() const;
    void                PutText_Out(
                            const ary::inf::DocuTex2 &
                                                i_rText ) const;
    // DATA
    mutable Xml::Element *
                        pTitleOut;
    mutable HF_IdlDocuTextDisplay
                        aTextOut;
};

#endif
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "memory.hpp"
#include "console.hpp"
#include "paging.hpp"
#include "e820.hpp"

namespace {

//Used to compile with malloc operations in the console
//can produce a lot of output
const bool DEBUG_MALLOC = false;
const bool TRACE_MALLOC = false;

uint64_t _used_memory;
uint64_t _allocated_memory;

struct malloc_header_chunk {
    uint64_t size;
    malloc_header_chunk* next;
    malloc_header_chunk* prev;
};

struct malloc_footer_chunk {
    uint64_t size;
};

struct fake_head {
    uint64_t size;
    malloc_header_chunk* next;
    malloc_header_chunk* prev;
    uint64_t size_2;
};

constexpr const uint64_t META_SIZE = sizeof(malloc_header_chunk) + sizeof(malloc_footer_chunk);
constexpr const uint64_t MIN_SPLIT = 32;
constexpr const uint64_t BLOCK_SIZE = paging::PAGE_SIZE;
constexpr const uint64_t MIN_BLOCKS = 4;

fake_head head;
malloc_header_chunk* malloc_head = 0;

const e820::mmapentry* current_mmap_entry = nullptr;
uint64_t current_mmap_entry_position;

uint64_t* allocate_block(uint64_t blocks){
    if(!current_mmap_entry){
        for(uint64_t i = 0; i < e820::mmap_entry_count(); ++i){
            auto& entry = e820::mmap_entry(i);

            if(entry.type == 1 && entry.base >= 0x100000 && entry.size >= 16384){
                current_mmap_entry = &entry;
                current_mmap_entry_position = entry.base;
                break;
            }
        }
    }

    if(!current_mmap_entry){
        return nullptr;
    }

    auto block = reinterpret_cast<uint64_t*>(current_mmap_entry_position);

    paging::identity_map(block, blocks);

    current_mmap_entry_position += blocks * BLOCK_SIZE;

    _allocated_memory += blocks * BLOCK_SIZE;

    return block;
}

template<bool Debug>
void debug_malloc(const char* point = nullptr){
    if(Debug){
        if(point){
            k_print_line(point);
        }

        auto it = malloc_head;

        k_print("next: ");
        do {
            k_printf("%h -> ", reinterpret_cast<uint64_t>(it));
            it = it->next;
        } while(it != malloc_head);

        k_printf("%h\n", malloc_head);

        it = malloc_head;

        k_print("prev: ");
        do {
            k_printf("%h <- ", reinterpret_cast<uint64_t>(it));
            it = it->prev;
        } while(it != malloc_head);

        k_printf("%h\n", malloc_head);
    }
}

} //end of anonymous namespace

void init_memory_manager(){
    //Init the fake head
    head.size = 0;
    head.next = nullptr;
    head.prev = nullptr;
    head.size_2 = 0;

    malloc_head = reinterpret_cast<malloc_header_chunk*>(&head);

    auto block = allocate_block(MIN_BLOCKS);
    auto header = reinterpret_cast<malloc_header_chunk*>(block);

    header->size = MIN_BLOCKS * BLOCK_SIZE - META_SIZE;
    header->next = malloc_head;
    header->prev = malloc_head;

    auto footer = reinterpret_cast<malloc_footer_chunk*>(
        reinterpret_cast<uintptr_t>(block) + header->size + sizeof(malloc_header_chunk));
    footer->size = header->size;

    malloc_head->next = header;
    malloc_head->prev = header;
}

void* k_malloc(uint64_t bytes){
    auto current = malloc_head->next;

    if(bytes < MIN_SPLIT){
        bytes = MIN_SPLIT;
    }

    while(true){
        if(current == malloc_head){
            //There are no blocks big enough to hold this request

            uint64_t* block = allocate_block(MIN_BLOCKS);
            auto header = reinterpret_cast<malloc_header_chunk*>(block);
            header->size = MIN_BLOCKS * BLOCK_SIZE - META_SIZE;

            header->next = current->next;
            header->prev = current;

            current->next->prev = header;
            current->next = header;

            auto footer = reinterpret_cast<malloc_footer_chunk*>(
                reinterpret_cast<uintptr_t>(block) + header->size + sizeof(malloc_header_chunk));
            footer->size = header->size;
        } else if(current->size >= bytes){
            //This block is big enough

            //Space necessary to hold a new block inside this one
            auto necessary_space = bytes + META_SIZE;

            //Is it worth splitting the block ?
            if(current->size > necessary_space + MIN_SPLIT + META_SIZE){
                auto new_block_size = current->size - necessary_space;

                //Set the new size;
                current->size = bytes;

                auto footer = reinterpret_cast<malloc_footer_chunk*>(
                    reinterpret_cast<uintptr_t>(current) + bytes + sizeof(malloc_header_chunk));
                footer->size = bytes;

                auto new_block = reinterpret_cast<malloc_header_chunk*>(
                    reinterpret_cast<uintptr_t>(current) + bytes + META_SIZE);

                new_block->size = new_block_size;
                new_block->next = current->next;
                new_block->prev = current->prev;
                current->prev->next = new_block;
                current->next->prev = new_block;

                auto new_footer = reinterpret_cast<malloc_footer_chunk*>(
                    reinterpret_cast<uintptr_t>(new_block) + new_block_size + sizeof(malloc_header_chunk));
                new_footer->size = new_block_size;

                debug_malloc<DEBUG_MALLOC>("after malloc split");

                break;
            } else {
                //Remove this node from the free list
                current->prev->next = current->next;
                current->next->prev = current->prev;

                debug_malloc<DEBUG_MALLOC>("after malloc no split");

                break;
            }
        }

        current = current->next;
    }

    _used_memory += current->size + META_SIZE;

    //Make sure the node is clean
    current->prev = nullptr;
    current->next = nullptr;

    auto b = reinterpret_cast<void*>(
        reinterpret_cast<uintptr_t>(current) + sizeof(malloc_header_chunk));

    if(TRACE_MALLOC){
        k_printf("m %d(%d) %h ", bytes, current->size, reinterpret_cast<uint64_t>(b));
    }

    return b;
}

void k_free(void* block){
    auto free_header = reinterpret_cast<malloc_header_chunk*>(
        reinterpret_cast<uintptr_t>(block) - sizeof(malloc_header_chunk));

    if(TRACE_MALLOC){
        k_printf("f %d %h ",free_header->size, reinterpret_cast<uint64_t>(block));
    }

    _used_memory -= free_header->size + META_SIZE;

    auto header = malloc_head;

    free_header->prev = header;
    free_header->next = header->next;

    header->next->prev = free_header;
    header->next = free_header;

    debug_malloc<DEBUG_MALLOC>("after free");
}

uint64_t used_memory(){
    return _used_memory;
}

uint64_t allocated_memory(){
    return _allocated_memory;
}

uint64_t free_memory(){
    return e820::available_memory() - _used_memory;
}

void memory_debug(){
    size_t memory_free = 0;

    auto it = malloc_head;

    k_printf("malloc overhead: %d\n", META_SIZE);
    k_print("Free blocks:");
    do {
        k_printf("b(%d) ", it->size);
        memory_free += it->size;
        it = it->next;
    } while(it != malloc_head);

    k_print_line();
    k_printf("memory free in malloc chain: %m (%d)", memory_free, memory_free);
}
<commit_msg>Align memory on eight bytes<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "memory.hpp"
#include "console.hpp"
#include "paging.hpp"
#include "e820.hpp"

namespace {

//Used to compile with malloc operations in the console
//can produce a lot of output
const bool DEBUG_MALLOC = false;
const bool TRACE_MALLOC = false;

uint64_t _used_memory;
uint64_t _allocated_memory;

struct malloc_header_chunk {
    uint64_t size;
    malloc_header_chunk* next;
    malloc_header_chunk* prev;
};

struct malloc_footer_chunk {
    uint64_t size;
};

struct fake_head {
    uint64_t size;
    malloc_header_chunk* next;
    malloc_header_chunk* prev;
    uint64_t size_2;
};

constexpr const uint64_t META_SIZE = sizeof(malloc_header_chunk) + sizeof(malloc_footer_chunk);
constexpr const uint64_t MIN_SPLIT = 32;
constexpr const uint64_t BLOCK_SIZE = paging::PAGE_SIZE;
constexpr const uint64_t MIN_BLOCKS = 4;

fake_head head;
malloc_header_chunk* malloc_head = 0;

const e820::mmapentry* current_mmap_entry = nullptr;
uint64_t current_mmap_entry_position;

uint64_t* allocate_block(uint64_t blocks){
    if(!current_mmap_entry){
        for(uint64_t i = 0; i < e820::mmap_entry_count(); ++i){
            auto& entry = e820::mmap_entry(i);

            if(entry.type == 1 && entry.base >= 0x100000 && entry.size >= 16384){
                current_mmap_entry = &entry;
                current_mmap_entry_position = entry.base;
                break;
            }
        }
    }

    if(!current_mmap_entry){
        return nullptr;
    }

    auto block = reinterpret_cast<uint64_t*>(current_mmap_entry_position);

    paging::identity_map(block, blocks);

    current_mmap_entry_position += blocks * BLOCK_SIZE;

    _allocated_memory += blocks * BLOCK_SIZE;

    return block;
}

template<bool Debug>
void debug_malloc(const char* point = nullptr){
    if(Debug){
        if(point){
            k_print_line(point);
        }

        auto it = malloc_head;

        k_print("next: ");
        do {
            k_printf("%h -> ", reinterpret_cast<uint64_t>(it));
            it = it->next;
        } while(it != malloc_head);

        k_printf("%h\n", malloc_head);

        it = malloc_head;

        k_print("prev: ");
        do {
            k_printf("%h <- ", reinterpret_cast<uint64_t>(it));
            it = it->prev;
        } while(it != malloc_head);

        k_printf("%h\n", malloc_head);
    }
}

} //end of anonymous namespace

void init_memory_manager(){
    //Init the fake head
    head.size = 0;
    head.next = nullptr;
    head.prev = nullptr;
    head.size_2 = 0;

    malloc_head = reinterpret_cast<malloc_header_chunk*>(&head);

    auto block = allocate_block(MIN_BLOCKS);
    auto header = reinterpret_cast<malloc_header_chunk*>(block);

    header->size = MIN_BLOCKS * BLOCK_SIZE - META_SIZE;
    header->next = malloc_head;
    header->prev = malloc_head;

    auto footer = reinterpret_cast<malloc_footer_chunk*>(
        reinterpret_cast<uintptr_t>(block) + header->size + sizeof(malloc_header_chunk));
    footer->size = header->size;

    malloc_head->next = header;
    malloc_head->prev = header;
}

constexpr const size_t ALIGNMENT = 8;
constexpr const size_t aligned_size(size_t bytes){
    return (bytes + (ALIGNMENT - 1)) & ~(ALIGNMENT - 1);
}

void* k_malloc(uint64_t bytes){
    auto current = malloc_head->next;

    if(bytes < MIN_SPLIT){
        bytes = MIN_SPLIT;
    }

    bytes = aligned_size(bytes);

    while(true){
        if(current == malloc_head){
            //There are no blocks big enough to hold this request

            uint64_t* block = allocate_block(MIN_BLOCKS);
            auto header = reinterpret_cast<malloc_header_chunk*>(block);
            header->size = MIN_BLOCKS * BLOCK_SIZE - META_SIZE;

            header->next = current->next;
            header->prev = current;

            current->next->prev = header;
            current->next = header;

            auto footer = reinterpret_cast<malloc_footer_chunk*>(
                reinterpret_cast<uintptr_t>(block) + header->size + sizeof(malloc_header_chunk));
            footer->size = header->size;
        } else if(current->size >= bytes){
            //This block is big enough

            //Space necessary to hold a new block inside this one
            auto necessary_space = bytes + META_SIZE;

            //Is it worth splitting the block ?
            if(current->size > necessary_space + MIN_SPLIT + META_SIZE){
                auto new_block_size = current->size - necessary_space;

                //Set the new size;
                current->size = bytes;

                auto footer = reinterpret_cast<malloc_footer_chunk*>(
                    reinterpret_cast<uintptr_t>(current) + bytes + sizeof(malloc_header_chunk));
                footer->size = bytes;

                auto new_block = reinterpret_cast<malloc_header_chunk*>(
                    reinterpret_cast<uintptr_t>(current) + bytes + META_SIZE);

                new_block->size = new_block_size;
                new_block->next = current->next;
                new_block->prev = current->prev;
                current->prev->next = new_block;
                current->next->prev = new_block;

                auto new_footer = reinterpret_cast<malloc_footer_chunk*>(
                    reinterpret_cast<uintptr_t>(new_block) + new_block_size + sizeof(malloc_header_chunk));
                new_footer->size = new_block_size;

                debug_malloc<DEBUG_MALLOC>("after malloc split");

                break;
            } else {
                //Remove this node from the free list
                current->prev->next = current->next;
                current->next->prev = current->prev;

                debug_malloc<DEBUG_MALLOC>("after malloc no split");

                break;
            }
        }

        current = current->next;
    }

    _used_memory += current->size + META_SIZE;

    //Make sure the node is clean
    current->prev = nullptr;
    current->next = nullptr;

    auto b = reinterpret_cast<void*>(
        reinterpret_cast<uintptr_t>(current) + sizeof(malloc_header_chunk));

    if(TRACE_MALLOC){
        k_printf("m %d(%d) %h ", bytes, current->size, reinterpret_cast<uint64_t>(b));
    }

    return b;
}

void k_free(void* block){
    auto free_header = reinterpret_cast<malloc_header_chunk*>(
        reinterpret_cast<uintptr_t>(block) - sizeof(malloc_header_chunk));

    if(TRACE_MALLOC){
        k_printf("f %d %h ",free_header->size, reinterpret_cast<uint64_t>(block));
    }

    _used_memory -= free_header->size + META_SIZE;

    auto header = malloc_head;

    free_header->prev = header;
    free_header->next = header->next;

    header->next->prev = free_header;
    header->next = free_header;

    debug_malloc<DEBUG_MALLOC>("after free");
}

uint64_t used_memory(){
    return _used_memory;
}

uint64_t allocated_memory(){
    return _allocated_memory;
}

uint64_t free_memory(){
    return e820::available_memory() - _used_memory;
}

void memory_debug(){
    size_t memory_free = 0;

    auto it = malloc_head;

    k_printf("malloc overhead: %d\n", META_SIZE);
    k_print("Free blocks:");
    do {
        k_printf("b(%d) ", it->size);
        memory_free += it->size;
        it = it->next;
    } while(it != malloc_head);

    k_print_line();
    k_printf("memory free in malloc chain: %m (%d)", memory_free, memory_free);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: c_dealer.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 18:14:56 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#ifndef ADC_CPP_C_DEALER_HXX
#define ADC_CPP_C_DEALER_HXX

// USED SERVICES
    // BASE CLASSES
#include <cpp/ctokdeal.hxx>
#include <adoc/atokdeal.hxx>
#include <ary/info/docstore.hxx>
    // COMPONENTS
#include "preproc.hxx"
#include "c_rcode.hxx"
#include <adoc/a_rdocu.hxx>
    // PARAMETERS

namespace csv
{
    namespace ploc
    {
        class Path;
        class DirectoryChain;
    }
}

class TokenParser;

namespace cpp
{

class PE_File;
class DefineDescription;

class Distributor : public cpp::TokenDealer,        /// Handle C++ code tokens.
                    public adoc::TokenDealer        /// Handle Autodoc documentation tokens.
{
  public:
    typedef std::map< udmstri, DefineDescription* >     MacroMap;

    // LIFECYCLE
                        Distributor(
                            ary::cpp::RwGate &  io_rGate );
                        ~Distributor();
    // OPERATIONS
    void                AssignPartners(
                            CharacterSource &   io_rSourceText,
                            const MacroMap &    i_rValidMacros );
    void                StartNewProject(
                            const udmstri &     i_sProjectName,
                            const csv::ploc::Path &
                                                i_rProjectRootDirectory );
    void                StartNewFile(
                            const udmstri &     i_sFileName,
                            const csv::ploc::DirectoryChain &
                                                i_rFileSubPath );
    virtual void        Deal_Eol();
    virtual void        Deal_Eof();

    virtual void        Deal_CppCode(
                            cpp::Token &        let_drToken );
    virtual void        Deal_Cpp_UnblockMacro(
                            Tok_UnblockMacro &  let_drToken );

    virtual void        Deal_AdcDocu(
                            adoc::Token &       let_drToken );
    virtual Distributor *
                        AsDistributor();
  private:
    // DATA
    PreProcessor        aCppPreProcessor;
    CodeExplorer        aCodeExplorer;
    adoc::DocuExplorer  aDocuExplorer;
    ary::cpp::RwGate *  pGate;
    FileScope_EventHandler *
                        pFileEventHandler;
    DocuDealer *        pDocuDistributor;
};

// IMPLEMENTATION

}   // namespace cpp

#endif

<commit_msg>INTEGRATION: CWS adc18 (1.3.56); FILE MERGED 2007/10/19 10:37:30 np 1.3.56.2: #i81775# 2007/10/18 15:23:16 np 1.3.56.1: #i81775#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: c_dealer.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 16:48:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#ifndef ADC_CPP_C_DEALER_HXX
#define ADC_CPP_C_DEALER_HXX

// USED SERVICES
    // BASE CLASSES
#include <cpp/ctokdeal.hxx>
#include <adoc/atokdeal.hxx>
#include <ary/info/docstore.hxx>
    // COMPONENTS
#include "preproc.hxx"
#include "c_rcode.hxx"
#include <adoc/a_rdocu.hxx>
    // PARAMETERS

namespace csv
{
    namespace ploc
    {
        class Path;
        class DirectoryChain;
    }
}

class TokenParser;

namespace cpp
{

class PE_File;
class DefineDescription;

class Distributor : public cpp::TokenDealer,        /// Handle C++ code tokens.
                    public adoc::TokenDealer        /// Handle Autodoc documentation tokens.
{
  public:
    typedef std::map< String, DefineDescription* >     MacroMap;

    // LIFECYCLE
                        Distributor(
                            ary::cpp::Gate &    io_rGate );
                        ~Distributor();
    // OPERATIONS
    void                AssignPartners(
                            CharacterSource &   io_rSourceText,
                            const MacroMap &    i_rValidMacros );
    void                StartNewFile(
                            const csv::ploc::Path &
                                                i_file );
    virtual void        Deal_Eol();
    virtual void        Deal_Eof();

    virtual void        Deal_CppCode(
                            cpp::Token &        let_drToken );
    virtual void        Deal_Cpp_UnblockMacro(
                            Tok_UnblockMacro &  let_drToken );

    virtual void        Deal_AdcDocu(
                            adoc::Token &       let_drToken );
    virtual Distributor *
                        AsDistributor();
  private:
    // DATA
    PreProcessor        aCppPreProcessor;
    CodeExplorer        aCodeExplorer;
    adoc::DocuExplorer  aDocuExplorer;
    ary::cpp::Gate *    pGate;
    FileScope_EventHandler *
                        pFileEventHandler;
    DocuDealer *        pDocuDistributor;
};

}   // namespace cpp
#endif

<|endoftext|>


<commit_before>//============================================================================
// Name        : VideoStreamingRequestHandler.cpp
// Author      : ITM13
// Version     : 1.0
// Description :
//============================================================================
#include "VideoStreamingRequestHandler.h"
#include <Poco\Net\MultipartWriter.h>
#include <Poco\Net\MessageHeader.h>

using Poco::Net::MessageHeader;
using Poco::Net::MultipartWriter;

namespace infrastructure {
	namespace video_streaming {

		VideoStreamingRequestHandler::VideoStreamingRequestHandler(WebcamServicePtr webcamService) : webcamService(webcamService)
		{
		}

		void VideoStreamingRequestHandler::handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) {
			Poco::Logger& logger = Poco::Logger::get("VideoStreamingRequestHandler");

			string boundary = "VIDEOSTREAM";

			logger.information("Video streaming started for client " + request.clientAddress().toString());

			response.set("Max-Age", "0");
			response.set("Expires", "0");
			response.set("Cache-Control", "no-cache, private");
			response.set("Pragma", "no-cache");
			response.setContentType("multipart/x-mixed-replace; boundary=--" + boundary);
			response.setChunkedTransferEncoding(false);

			std::ostream& out = response.send();

			while (out.good()) {
				MultipartWriter writer(out, boundary);

				cv::Mat& image = webcamService->GetLastImage();

				if (image.empty()) {
					logger.warning("Read empty stream image");
					continue;
				}

				// encode mat to jpg and copy it to content
				std::vector<uchar> buf;
				cv::imencode(".jpg", image, buf, std::vector<int>());
				std::string content = std::string(buf.begin(), buf.end());

				MessageHeader header = MessageHeader();
				header.set("Content-Type", "image/jpeg");
				header.set("Content-Length", std::to_string(content.size()));
				writer.nextPart(header);
				out << content;
			}

			logger.information("Video streaming stopped for client " + request.clientAddress().toString());
		}
	}
}<commit_msg>adaptions to MJPEG protocol<commit_after>//============================================================================
// Name        : VideoStreamingRequestHandler.cpp
// Author      : ITM13
// Version     : 1.0
// Description :
//============================================================================
#include "VideoStreamingRequestHandler.h"
#include <Poco\Net\MultipartWriter.h>
#include <Poco\Net\MessageHeader.h>

using Poco::Net::MessageHeader;
using Poco::Net::MultipartWriter;

namespace infrastructure {
	namespace video_streaming {

		VideoStreamingRequestHandler::VideoStreamingRequestHandler(WebcamServicePtr webcamService) : webcamService(webcamService)
		{
		}

		void VideoStreamingRequestHandler::handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) {
			Poco::Logger& logger = Poco::Logger::get("VideoStreamingRequestHandler");

			string boundary = "VIDEOSTREAM";

			logger.information("Video streaming started for client " + request.clientAddress().toString());

			response.set("Max-Age", "0");
			response.set("Expires", "0");
			response.set("Cache-Control", "no-cache, private");
			response.set("Pragma", "no-cache");
			response.setContentType("multipart/x-mixed-replace; boundary=--" + boundary);
			response.setChunkedTransferEncoding(false);

			std::ostream& out = response.send();

			while (out.good()) {
				MultipartWriter writer(out, boundary);

				cv::Mat& image = webcamService->GetLastImage();

				if (image.empty()) {
					logger.warning("Read empty stream image");
					continue;
				}

				// encode mat to jpg and copy it to content
				std::vector<uchar> buf;
				cv::imencode(".jpg", image, buf, std::vector<int>());
				std::string content = std::string(buf.begin(), buf.end());

				MessageHeader header = MessageHeader();
				header.set("Content-Length", std::to_string(content.size()));
				header.set("Content-Type", "image/jpeg");
				writer.nextPart(header);
				out << content;
				out << "\r\n\r\n";
			}

			logger.information("Video streaming stopped for client " + request.clientAddress().toString());
		}
	}
}<|endoftext|>


<commit_before>#include <gtest/gtest.h>

extern "C" {
#include "../src/client.h"
#include "../src/connect.h"
#include "../src/packet.h"
}

#include "macros.h"

TEST(ConnectTest, IsEqual) {
  unsigned char pkt[62] = {
      LWMQTT_CONNECT_PACKET << 4,
      60,
      0,  // Protocol String MSB
      4,  // Protocol String LSB
      'M',
      'Q',
      'T',
      'T',
      4,    // Protocol level 4
      204,  // Connect Flags
      0,    // Keep Alive MSB
      10,   // Keep Alive LSB
      0,    // Client ID MSB
      7,    // Client ID LSB
      's',
      'u',
      'r',
      'g',
      'e',
      'm',
      'q',
      0,  // Will Topic MSB
      4,  // Will Topic LSB
      'w',
      'i',
      'l',
      'l',
      0,   // Will Message MSB
      12,  // Will Message LSB
      's',
      'e',
      'n',
      'd',
      ' ',
      'm',
      'e',
      ' ',
      'h',
      'o',
      'm',
      'e',
      0,  // Username ID MSB
      7,  // Username ID LSB
      's',
      'u',
      'r',
      'g',
      'e',
      'm',
      'q',
      0,   // Password ID MSB
      10,  // Password ID LSB
      'v',
      'e',
      'r',
      'y',
      's',
      'e',
      'c',
      'r',
      'e',
      't',
  };

  unsigned char buf[256];

  lwmqtt_will_t will = lwmqtt_default_will;
  will.topic.c_string = (char*)"will";
  will.message.c_string = (char*)"send me home";
  will.qos = LWMQTT_QOS1;

  lwmqtt_options_t opts = lwmqtt_default_options;
  opts.clean_session = 0;
  opts.keep_alive = 10;
  opts.client_id.c_string = (char*)"surgemq";
  opts.username.c_string = (char*)"surgemq";
  opts.password.c_string = (char*)"verysecret";

  int l = lwmqtt_serialize_connect(buf, 256, &opts, &will);

  EXPECT_ARRAY_EQ(unsigned char, pkt, buf, l);
}
<commit_msg>cleaned up<commit_after>#include <gtest/gtest.h>

extern "C" {
#include "../src/client.h"
#include "../src/packet.h"
}

#include "macros.h"

TEST(ConnectTest, IsEqual) {
  unsigned char pkt[62] = {
      LWMQTT_CONNECT_PACKET << 4,
      60,
      0,  // Protocol String MSB
      4,  // Protocol String LSB
      'M',
      'Q',
      'T',
      'T',
      4,    // Protocol level 4
      204,  // Connect Flags
      0,    // Keep Alive MSB
      10,   // Keep Alive LSB
      0,    // Client ID MSB
      7,    // Client ID LSB
      's',
      'u',
      'r',
      'g',
      'e',
      'm',
      'q',
      0,  // Will Topic MSB
      4,  // Will Topic LSB
      'w',
      'i',
      'l',
      'l',
      0,   // Will Message MSB
      12,  // Will Message LSB
      's',
      'e',
      'n',
      'd',
      ' ',
      'm',
      'e',
      ' ',
      'h',
      'o',
      'm',
      'e',
      0,  // Username ID MSB
      7,  // Username ID LSB
      's',
      'u',
      'r',
      'g',
      'e',
      'm',
      'q',
      0,   // Password ID MSB
      10,  // Password ID LSB
      'v',
      'e',
      'r',
      'y',
      's',
      'e',
      'c',
      'r',
      'e',
      't',
  };

  unsigned char buf[256];

  lwmqtt_will_t will = lwmqtt_default_will;
  will.topic.c_string = (char*)"will";
  will.message.c_string = (char*)"send me home";
  will.qos = LWMQTT_QOS1;

  lwmqtt_options_t opts = lwmqtt_default_options;
  opts.clean_session = 0;
  opts.keep_alive = 10;
  opts.client_id.c_string = (char*)"surgemq";
  opts.username.c_string = (char*)"surgemq";
  opts.password.c_string = (char*)"verysecret";

  int l = lwmqtt_serialize_connect(buf, 256, &opts, &will);

  EXPECT_ARRAY_EQ(unsigned char, pkt, buf, l);
}
<|endoftext|>


<commit_before>// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>

// libmesh includes
#include "libmesh/auto_ptr.h"
#include "libmesh/elem.h"
#include "libmesh/equation_systems.h"
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/numeric_vector.h"
#include "libmesh/parsed_fem_function.h"
#include "libmesh/system.h"

// test includes
#include "test_comm.h"

using namespace libMesh;

class ParsedFEMFunctionTest : public CppUnit::TestCase
{
public:
  void setUp() {
    mesh.reset(new Mesh(*TestCommWorld));
    MeshTools::Generation::build_cube(*mesh, 1, 1, 1);
    es.reset(new EquationSystems(*mesh));
    sys = &(es->add_system<System> ("SimpleSystem"));
    sys->add_variable("x2");
    sys->add_variable("x3");
    sys->add_variable("c05");
    sys->add_variable("y4");
    sys->add_variable("xy");
    sys->add_variable("yz");
    sys->add_variable("xyz");

    es->init();

    NumericVector<Number> & sol = *sys->solution;
    Elem *elem = mesh->query_elem(0);

    if (elem && elem->processor_id() == TestCommWorld->rank())
      {
        // Set x2 = 2*x
        sol.set(elem->get_node(1)->dof_number(0,0,0), 2);
        sol.set(elem->get_node(2)->dof_number(0,0,0), 2);
        sol.set(elem->get_node(5)->dof_number(0,0,0), 2);
        sol.set(elem->get_node(6)->dof_number(0,0,0), 2);

        // Set x3 = 3*x
        sol.set(elem->get_node(1)->dof_number(0,1,0), 3);
        sol.set(elem->get_node(2)->dof_number(0,1,0), 3);
        sol.set(elem->get_node(5)->dof_number(0,1,0), 3);
        sol.set(elem->get_node(6)->dof_number(0,1,0), 3);

        // Set c05 = 0.5
        sol.set(elem->get_node(0)->dof_number(0,2,0), 0.5);
        sol.set(elem->get_node(1)->dof_number(0,2,0), 0.5);
        sol.set(elem->get_node(2)->dof_number(0,2,0), 0.5);
        sol.set(elem->get_node(3)->dof_number(0,2,0), 0.5);
        sol.set(elem->get_node(4)->dof_number(0,2,0), 0.5);
        sol.set(elem->get_node(5)->dof_number(0,2,0), 0.5);
        sol.set(elem->get_node(6)->dof_number(0,2,0), 0.5);
        sol.set(elem->get_node(7)->dof_number(0,2,0), 0.5);

        // Set y4 = 4*y
        sol.set(elem->get_node(2)->dof_number(0,3,0), 4);
        sol.set(elem->get_node(3)->dof_number(0,3,0), 4);
        sol.set(elem->get_node(6)->dof_number(0,3,0), 4);
        sol.set(elem->get_node(7)->dof_number(0,3,0), 4);

        // Set xy = x*y
        sol.set(elem->get_node(2)->dof_number(0,4,0), 1);
        sol.set(elem->get_node(6)->dof_number(0,4,0), 1);

        // Set yz = y*z
        sol.set(elem->get_node(6)->dof_number(0,5,0), 1);
        sol.set(elem->get_node(7)->dof_number(0,5,0), 1);

        // Set xyz = x*y*z
        sol.set(elem->get_node(6)->dof_number(0,6,0), 1);
      }

    sol.close();
    sys->update();

    c.reset(new FEMContext(*sys));
    if (elem && elem->processor_id() == TestCommWorld->rank())
      {
        c->pre_fe_reinit(*sys, elem);
        c->elem_fe_reinit();
      }
  }

  void tearDown() {
    c.reset();
    es.reset();
    mesh.reset();
  }

  CPPUNIT_TEST_SUITE(ParsedFEMFunctionTest);

  CPPUNIT_TEST(testValues);
  CPPUNIT_TEST(testGradients);
  CPPUNIT_TEST(testHessians);

  CPPUNIT_TEST_SUITE_END();

private:
  UniquePtr<UnstructuredMesh> mesh;
  UniquePtr<EquationSystems> es;
  System * sys;
  UniquePtr<FEMContext> c;

  void testValues()
  {
    if (c->has_elem() &&
        c->get_elem().processor_id() == TestCommWorld->rank())
      {
        ParsedFEMFunction<Number> x2(*sys, "x2");

        CPPUNIT_ASSERT_DOUBLES_EQUAL
          (libmesh_real(x2(*c,Point(0.5,0.5,0.5))), 1.0, TOLERANCE*TOLERANCE);

        ParsedFEMFunction<Number> xy8(*sys, "x2*y4");

        CPPUNIT_ASSERT_DOUBLES_EQUAL
          (libmesh_real(xy8(*c,Point(0.5,0.5,0.5))), 2.0, TOLERANCE*TOLERANCE);
      }
  }

  void testGradients()
  {
    if (c->has_elem() &&
        c->get_elem().processor_id() == TestCommWorld->rank())
      {
        ParsedFEMFunction<Number> c2(*sys, "grad_x_x2");

        CPPUNIT_ASSERT_DOUBLES_EQUAL
          (libmesh_real(c2(*c,Point(0.35,0.45,0.55))), 2.0, TOLERANCE*TOLERANCE);

        ParsedFEMFunction<Number> xz(*sys, "grad_y_xyz");

        CPPUNIT_ASSERT_DOUBLES_EQUAL
          (libmesh_real(xz(*c,Point(0.25,0.35,0.75))), 0.1875, TOLERANCE*TOLERANCE);

        ParsedFEMFunction<Number> xyz(*sys, "grad_y_xyz*grad_x_xy");

        CPPUNIT_ASSERT_DOUBLES_EQUAL
          (libmesh_real(xyz(*c,Point(0.25,0.5,0.75))), 0.09375, TOLERANCE*TOLERANCE);
      }
  }

  void testHessians()
  {
    if (c->has_elem() &&
        c->get_elem().processor_id() == TestCommWorld->rank())
      {
        ParsedFEMFunction<Number> c1(*sys, "hess_xy_xy");

        CPPUNIT_ASSERT_DOUBLES_EQUAL
          (libmesh_real(c1(*c,Point(0.35,0.45,0.55))), 1.0, TOLERANCE*TOLERANCE);

        ParsedFEMFunction<Number> x(*sys, "hess_yz_xyz");

        CPPUNIT_ASSERT_DOUBLES_EQUAL
          (libmesh_real(x(*c,Point(0.25,0.35,0.55))), 0.25, TOLERANCE*TOLERANCE);

        ParsedFEMFunction<Number> xz(*sys, "hess_yz_xyz*grad_y_yz");

        CPPUNIT_ASSERT_DOUBLES_EQUAL
          (libmesh_real(xz(*c,Point(0.25,0.4,0.75))), 0.1875, TOLERANCE*TOLERANCE);
      }
  }

};

CPPUNIT_TEST_SUITE_REGISTRATION(ParsedFEMFunctionTest);
<commit_msg>Unit test for ParsedFEMFunction normals<commit_after>// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>

// libmesh includes
#include "libmesh/auto_ptr.h"
#include "libmesh/elem.h"
#include "libmesh/equation_systems.h"
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/numeric_vector.h"
#include "libmesh/parsed_fem_function.h"
#include "libmesh/system.h"

// test includes
#include "test_comm.h"

using namespace libMesh;

class ParsedFEMFunctionTest : public CppUnit::TestCase
{
public:
  void setUp() {
    mesh.reset(new Mesh(*TestCommWorld));
    MeshTools::Generation::build_cube(*mesh, 1, 1, 1);
    es.reset(new EquationSystems(*mesh));
    sys = &(es->add_system<System> ("SimpleSystem"));
    sys->add_variable("x2");
    sys->add_variable("x3");
    sys->add_variable("c05");
    sys->add_variable("y4");
    sys->add_variable("xy");
    sys->add_variable("yz");
    sys->add_variable("xyz");

    es->init();

    NumericVector<Number> & sol = *sys->solution;
    Elem *elem = mesh->query_elem(0);

    if (elem && elem->processor_id() == TestCommWorld->rank())
      {
        // Set x2 = 2*x
        sol.set(elem->get_node(1)->dof_number(0,0,0), 2);
        sol.set(elem->get_node(2)->dof_number(0,0,0), 2);
        sol.set(elem->get_node(5)->dof_number(0,0,0), 2);
        sol.set(elem->get_node(6)->dof_number(0,0,0), 2);

        // Set x3 = 3*x
        sol.set(elem->get_node(1)->dof_number(0,1,0), 3);
        sol.set(elem->get_node(2)->dof_number(0,1,0), 3);
        sol.set(elem->get_node(5)->dof_number(0,1,0), 3);
        sol.set(elem->get_node(6)->dof_number(0,1,0), 3);

        // Set c05 = 0.5
        sol.set(elem->get_node(0)->dof_number(0,2,0), 0.5);
        sol.set(elem->get_node(1)->dof_number(0,2,0), 0.5);
        sol.set(elem->get_node(2)->dof_number(0,2,0), 0.5);
        sol.set(elem->get_node(3)->dof_number(0,2,0), 0.5);
        sol.set(elem->get_node(4)->dof_number(0,2,0), 0.5);
        sol.set(elem->get_node(5)->dof_number(0,2,0), 0.5);
        sol.set(elem->get_node(6)->dof_number(0,2,0), 0.5);
        sol.set(elem->get_node(7)->dof_number(0,2,0), 0.5);

        // Set y4 = 4*y
        sol.set(elem->get_node(2)->dof_number(0,3,0), 4);
        sol.set(elem->get_node(3)->dof_number(0,3,0), 4);
        sol.set(elem->get_node(6)->dof_number(0,3,0), 4);
        sol.set(elem->get_node(7)->dof_number(0,3,0), 4);

        // Set xy = x*y
        sol.set(elem->get_node(2)->dof_number(0,4,0), 1);
        sol.set(elem->get_node(6)->dof_number(0,4,0), 1);

        // Set yz = y*z
        sol.set(elem->get_node(6)->dof_number(0,5,0), 1);
        sol.set(elem->get_node(7)->dof_number(0,5,0), 1);

        // Set xyz = x*y*z
        sol.set(elem->get_node(6)->dof_number(0,6,0), 1);
      }

    sol.close();
    sys->update();

    c.reset(new FEMContext(*sys));
    s.reset(new FEMContext(*sys));
    if (elem && elem->processor_id() == TestCommWorld->rank())
      {
        c->pre_fe_reinit(*sys, elem);
        c->elem_fe_reinit();
        s->pre_fe_reinit(*sys, elem);
        s->side = 3;
        s->side_fe_reinit();
      }
  }

  void tearDown() {
    c.reset();
    s.reset();
    es.reset();
    mesh.reset();
  }

  CPPUNIT_TEST_SUITE(ParsedFEMFunctionTest);

  CPPUNIT_TEST(testValues);
  CPPUNIT_TEST(testGradients);
  CPPUNIT_TEST(testHessians);
  CPPUNIT_TEST(testNormals);

  CPPUNIT_TEST_SUITE_END();

private:
  UniquePtr<UnstructuredMesh> mesh;
  UniquePtr<EquationSystems> es;
  System * sys;
  UniquePtr<FEMContext> c, s;

  void testValues()
  {
    if (c->has_elem() &&
        c->get_elem().processor_id() == TestCommWorld->rank())
      {
        ParsedFEMFunction<Number> x2(*sys, "x2");

        CPPUNIT_ASSERT_DOUBLES_EQUAL
          (libmesh_real(x2(*c,Point(0.5,0.5,0.5))), 1.0, TOLERANCE*TOLERANCE);

        ParsedFEMFunction<Number> xy8(*sys, "x2*y4");

        CPPUNIT_ASSERT_DOUBLES_EQUAL
          (libmesh_real(xy8(*c,Point(0.5,0.5,0.5))), 2.0, TOLERANCE*TOLERANCE);
      }
  }

  void testGradients()
  {
    if (c->has_elem() &&
        c->get_elem().processor_id() == TestCommWorld->rank())
      {
        ParsedFEMFunction<Number> c2(*sys, "grad_x_x2");

        CPPUNIT_ASSERT_DOUBLES_EQUAL
          (libmesh_real(c2(*c,Point(0.35,0.45,0.55))), 2.0, TOLERANCE*TOLERANCE);

        ParsedFEMFunction<Number> xz(*sys, "grad_y_xyz");

        CPPUNIT_ASSERT_DOUBLES_EQUAL
          (libmesh_real(xz(*c,Point(0.25,0.35,0.75))), 0.1875, TOLERANCE*TOLERANCE);

        ParsedFEMFunction<Number> xyz(*sys, "grad_y_xyz*grad_x_xy");

        CPPUNIT_ASSERT_DOUBLES_EQUAL
          (libmesh_real(xyz(*c,Point(0.25,0.5,0.75))), 0.09375, TOLERANCE*TOLERANCE);
      }
  }

  void testHessians()
  {
    if (c->has_elem() &&
        c->get_elem().processor_id() == TestCommWorld->rank())
      {
        ParsedFEMFunction<Number> c1(*sys, "hess_xy_xy");

        CPPUNIT_ASSERT_DOUBLES_EQUAL
          (libmesh_real(c1(*c,Point(0.35,0.45,0.55))), 1.0, TOLERANCE*TOLERANCE);

        ParsedFEMFunction<Number> x(*sys, "hess_yz_xyz");

        CPPUNIT_ASSERT_DOUBLES_EQUAL
          (libmesh_real(x(*c,Point(0.25,0.35,0.55))), 0.25, TOLERANCE*TOLERANCE);

        ParsedFEMFunction<Number> xz(*sys, "hess_yz_xyz*grad_y_yz");

        CPPUNIT_ASSERT_DOUBLES_EQUAL
          (libmesh_real(xz(*c,Point(0.25,0.4,0.75))), 0.1875, TOLERANCE*TOLERANCE);
      }
  }

  void testNormals()
  {
    if (s->has_elem() &&
        s->get_elem().processor_id() == TestCommWorld->rank())
      {
        ParsedFEMFunction<Number> nx(*sys, "n_x");

        ParsedFEMFunction<Number> ny(*sys, "n_y");

        ParsedFEMFunction<Number> nz(*sys, "n_z");

        const std::vector<Point> & xyz = s->get_side_fe(0)->get_xyz();

        // On side 3 of a hex the normal direction is +y
        for (unsigned int qp=0; qp != xyz.size(); ++qp)
          {
            CPPUNIT_ASSERT_DOUBLES_EQUAL
              (libmesh_real(nx(*s,xyz[qp])), 0.0, TOLERANCE*TOLERANCE);
            CPPUNIT_ASSERT_DOUBLES_EQUAL
              (libmesh_real(ny(*s,xyz[qp])), 1.0, TOLERANCE*TOLERANCE);
            CPPUNIT_ASSERT_DOUBLES_EQUAL
              (libmesh_real(nz(*s,xyz[qp])), 0.0, TOLERANCE*TOLERANCE);
          }
      }
  }

};

CPPUNIT_TEST_SUITE_REGISTRATION(ParsedFEMFunctionTest);
<|endoftext|>


<commit_before>#include "DungeonManager.h"
#include "MapLoader.h"
#include "PresetFileData.h"
#include "DRLG.h"
#include "Server.h"

#include "entities\info_player_start.h"
#include "entities\contain_chest.h"
#include "entities\npc_test.h"

DungeonManager* ptDungeonManager;

#define DEF_SPAWN_FUNC(x)	mSpawnFuncs["" #x ""] = ##x##::spawnme
DungeonManager::DungeonManager() {
	// Initialize the DungeonManager, creating all the spawn funcs and initializing zone memory
	R_Message(PRIORITY_NOTE, "loading dungeons...\n");
	ptMapLoader = new MapLoader("levels/preset", "levels/tiles");

	DEF_SPAWN_FUNC(info_player_start);
	DEF_SPAWN_FUNC(Player);
	DEF_SPAWN_FUNC(contain_chest);
	DEF_SPAWN_FUNC(npc_test);

	trap->Zone_NewTag("tiles");
}

DungeonManager::~DungeonManager() {
	// Clear out stuff we no longer need. // FIXME: memory leaking here?
	delete ptMapLoader;
	trap->Zone_FreeAll("tiles");
}

Worldspace* DungeonManager::GetWorld(unsigned int iAct) {
	// Find the worldspace we're looking for
	if(iAct >= NUM_ACTS) {
		return nullptr;
	}
	return &(wActs[iAct]);
}

void DungeonManager::StartBuild(const string& sDungeonName) {
	// Start building from a level. We take that map's framework, and then build everything from that point recursively.
	MapFramework* ptFramework = ptMapLoader->FindMapFrameworkByName(sDungeonName.c_str());
	if(!ptFramework) {
		return;
	}
	Construct(ptFramework);
}

void DungeonManager::PresetGeneration(const MapFramework* ptFramework, Map& in) {
	// Generate a preset level.
	// Locate the pfd in storage
	const PresetFileData* pfd = ptMapLoader->FindPresetByName(ptFramework->dataPreset.preset);
	if(!pfd) {
		R_Message(PRIORITY_WARNING, "WARNING: Couldn't find pfd: %s\n", ptFramework->dataPreset.preset);
		return;
	}

	strcpy(in.name, ptFramework->name); // FIXME: not needed?

	// Add tiles to the map
	if(pfd->head.numTiles > 0) {
		TileNode* v = (TileNode*)trap->Zone_Alloc(sizeof(TileNode)*pfd->head.numTiles, "tiles");
		for(int i = 0; i < pfd->head.numTiles; i++) {
			// Construct the tile from the pfd
			auto tile = pfd->tileBlocks[i];
			v[i].x = tile.x + in.x; v[i].y = tile.y + in.y;
			v[i].w = 1; v[i].h = 1;
			v[i].ptTile = ptMapLoader->FindTileByName(tile.lookup);
			v[i].rt = (tileRenderType_e)tile.rt;
			if(v[i].ptTile == nullptr) {
				R_Message(PRIORITY_WARNING, "Cannot find tile %s\n", tile.lookup);
				return;
			}
			// Add the tile to the map
			in.qtTileTree.AddNode(&(v[i]));
		}
	}

	// Add entities to the map
	for(int i = 0; i < pfd->head.numEntities; i++) {
		auto loadedEnt = pfd->entities[i];
		// Spawn an instance of the entity by calling its ::spawnme function
		Entity* ent = GenerateEntity(loadedEnt.lookup, loadedEnt.x + ptFramework->iWorldspaceX, loadedEnt.y + ptFramework->iWorldspaceY, loadedEnt.spawnflags, ptFramework->iAct);
		if(!ent) {
			R_Message(PRIORITY_WARNING, "%s does not have a spawn function\n", loadedEnt.lookup);
			continue;
		}
		// Actually call its spawn() function
		wActs[ptFramework->iAct].SpawnEntity(ent, ent->bShouldWeRender, ent->bShouldWeThink, ent->bShouldWeCollide);
		// Lastly, put it in the map that it belongs in
		ent->ptContainingTree = in.qtEntTree.AddNode(ent);
	}
}

void DungeonManager::Construct(const MapFramework* ptFramework) {
	if(!ptFramework) {
		return;
	}

	// Check to see if we've already made this map. This is to prevent generating the same area twice.
	auto found = mHaveWeAlreadyBuilt.find(ptFramework->name);
	if(found != mHaveWeAlreadyBuilt.end()) {
		return; // Already built the map.
	}

	// Create the base map
	/*float powAvg = (ptFramework->iSizeX + ptFramework->iSizeY) / 2;
	int maxDepth = ceil(log2(ptFramework->iSizeX + ptFramework->iSizeY))/4;*/
	int maxDepth = 1;
	Map *theMap = new Map(ptFramework->iWorldspaceX, ptFramework->iWorldspaceY,
		ptFramework->iSizeX, ptFramework->iSizeY, ptFramework->iAct, maxDepth);
	strcpy(theMap->name, ptFramework->name);
	theMap->ptFramework = ptFramework;
	for(int i = 0; i < MAX_MAP_LINKS; i++) {
		if(ptFramework->sLink[i].length() > 0) {
			strcpy(theMap->links[i], ptFramework->sLink[i].c_str());
		} else {
			theMap->links[i][0] = '\0';
		}
	}
	mHaveWeAlreadyBuilt[ptFramework->name] = theMap; // stops infinite recursion below

	// Dungeon generation
	if(ptFramework->bIsPreset) {
		// It's preset, so lets just do that then
		PresetGeneration(ptFramework, *theMap);
	} else {
		// DRLG generation
		RandomizeDungeon(ptMapLoader->FindMazeFrameworkByName(ptFramework->mazeName), *theMap, this);
	}

	// For each map that this one links to, we generate those maps (recursively)
	for(int i = 0; i < 8; i++) {
		const string& str = ptFramework->sLink[i];
		if(str.length() > 0) {
			// We have a link here, so construct it
			MapFramework* ptLinkFramework = ptMapLoader->FindMapFrameworkByName(str.c_str());
			if(ptLinkFramework) {
				Construct(ptLinkFramework);
			}
		}
	}

	// Insert the map into the worldspace
	GetWorld(ptFramework->iAct)->InsertInto(theMap);
	mHaveWeAlreadyBuilt[ptFramework->name] = theMap; // FIXME: not needed?
}

Entity* DungeonManager::GenerateEntity(const char* name, float x, float y, int spawnflags, int act) {
	// Call the entity's ::spawnme method.
	auto func = mSpawnFuncs.find(name);
	if(func == mSpawnFuncs.end()) {
		return nullptr;
	}

	return func->second(x, y, spawnflags, act);
}

void DungeonManager::SpawnPlayer(const string& sDungeonName) {
	auto theMap = mHaveWeAlreadyBuilt.find(sDungeonName);
	if(theMap == mHaveWeAlreadyBuilt.end()) {
		// Couldn't spawn, that level doesn't exist
		return;
	}

	// Find an info_player_start with the SPAWNFLAG_PLAYSPAWN flag set.
	vector<Entity*> ents = theMap->second->FindEntities("info_player_start");
	if(ents.size() <= 0) {
		return; // no spawn points, should throw an error?
	}

	Entity* ent = nullptr;
	for(auto it = ents.begin(); it != ents.end(); ++it) {
		if((*it)->GetSpawnflags() & info_player_start::SPAWNFLAG_PLAYSPAWN) {
			ent = *it;
			break;
		}
	}
	if(ent == nullptr) {
		// couldn't find an appropriate spawn point. should throw an error/use alternatives?
		return;
	}

	// Generate a player entity, spawn it, and alert the world that there's a new player in the game.
	Entity* playerEnt = GenerateEntity("Player", ent->x, ent->y, 0, theMap->second->iAct);
	Player* ptPlayer = (Player*)playerEnt;
	wActs[theMap->second->iAct].SpawnEntity(playerEnt, playerEnt->bShouldWeRender, playerEnt->bShouldWeThink, playerEnt->bShouldWeCollide);
	wActs[theMap->second->iAct].AddPlayer(ptPlayer);
	playerEnt->ptContainingTree = theMap->second->qtEntTree.AddNode(playerEnt);

	ptServer->GetClient()->ptPlayer = ptPlayer;
	ptPlayer->SignalZoneChange(ent->x, ent->y, sDungeonName.c_str());
}

PresetFileData* DungeonManager::GetPFD(const string& sName) {
	return ptMapLoader->FindPresetByName(sName);
}

Tile* DungeonManager::GetTileByName(const string& sName) {
	return ptMapLoader->FindTileByName(sName);
}

Map* DungeonManager::FindProperMap(int iAct, float x, float y) {
	if(iAct < 0 || iAct >= NUM_ACTS) {
		return nullptr;
	}
	Worldspace* world = &(wActs[iAct]);
static vector<Map*> nodes;
	nodes.clear();
	nodes = world->qtMapTree->NodesAt(x, y);
	for(auto it = nodes.begin(); it != nodes.end(); ++it) {
		if(x >= (*it)->x && x < (*it)->x + (*it)->w &&
			y >= (*it)->y && y < (*it)->y + (*it)->h) {
				return *it;
		}
	}
	return nullptr;
}

Map* DungeonManager::FindProperMap(int iAct, int x, int y) {
	return FindProperMap(iAct, (float)x, (float)y);
}

string DungeonManager::FindNextMapStr(int iAct, int iPlayerNum, int iVisNumber) {
	Player* ply = wActs[iAct].GetFirstPlayer();	// FIXME
	Map* ourMap = FindProperMap(iAct, ply->x, ply->y);
	MapFramework* nextMap = ptMapLoader->FindMapFrameworkByName(ourMap->links[iVisNumber]);
	if(!nextMap) {
		return "";
	}
	return nextMap->toName;
}

void DungeonManager::MovePlayerToVis(int iAct, int iPlayerNum, int iVisNumber) {
	Player* ply = wActs[iAct].GetFirstPlayer();
	Map* ourMap = FindProperMap(iAct, ply->x, ply->y);
	MapFramework* ptNextFrame = ptMapLoader->FindMapFrameworkByName(ourMap->links[iVisNumber]);
	if(!ptNextFrame) {
		// Don't move us to the next vis if we can't find the framework for it!
		return;
	}
	int iNextVis = -1;
	for(int i = 0; i < MAX_MAP_LINKS; i++) {
		if(!stricmp(ptNextFrame->sLink[i].c_str(), ourMap->name)) {
			iNextVis = i;
			break;
		}
	}
	if(iNextVis == -1) {
		// This is somewhat of a stupid mechanics restriction, but don't allow us to go into maps
		// which don't link back to us. This prevents the player from getting stuck in zones.
		return;
	}

	Map* nextMap = FindProperMap(iAct, ptNextFrame->iWorldspaceX + (ptNextFrame->iSizeX / 2),
		ptNextFrame->iWorldspaceY + (ptNextFrame->iSizeY / 2));
	if(!nextMap) {
		// Cannot proceed if we can't find the next map...
		return;
	}

	vector<Entity*> vSpawnPoints = nextMap->FindEntities("info_player_start");
	Entity* ptSpawn = nullptr;
	for(auto it = vSpawnPoints.begin(); it != vSpawnPoints.end(); ++it) {
		if((*it)->GetSpawnflags() & (1 << iNextVis)) {
			ptSpawn = *it;
		}
	}
	if(ptSpawn == nullptr) {
		// FIXME: maybe throw an error? Couldn't find a spawn point?
		return;
	}

	ply->SignalZoneChange(ptSpawn->x, ptSpawn->y, nextMap->name);
}

vector<Entity*> DungeonManager::GetEntsAt(float x, float y, int act) {
	Worldspace* ptWorld = GetWorld(act);
	auto maps = ptWorld->qtMapTree->NodesAt(x, y);
	vector<Map*> vDesiredMaps;
	vector<Entity*> vRetVal;

	for(auto it = maps.begin(); it != maps.end(); it++) {
		Map* ptMap = *it;
		if(ptMap->x <= x && ptMap->x + ptMap->w >= x &&
			ptMap->y <= y && ptMap->y + ptMap->h >= y) {
				vDesiredMaps.push_back(ptMap);
		}
	}
	if(vDesiredMaps.empty()) {
		return vRetVal;
	}
	for(auto it = vDesiredMaps.begin(); it != vDesiredMaps.end(); ++it) {
		Map* ptMap = *it;
		auto entsAt = ptMap->qtEntTree.NodesAt(x, y);
		for(auto it2 = entsAt.begin(); it2 != entsAt.end(); ++it2) {
			Entity* ptEnt = *it2;
			if(x >= ptEnt->x && x <= ptEnt->x + ptEnt->w && y >= ptEnt->y && y <= ptEnt->y + ptEnt->h) {
				vRetVal.push_back(ptEnt);
			}
		}
	}
	return vRetVal;
}<commit_msg>Fixed signed/unsigned issue in DungeonManager.cpp that could be VERY bad<commit_after>#include "DungeonManager.h"
#include "MapLoader.h"
#include "PresetFileData.h"
#include "DRLG.h"
#include "Server.h"

#include "entities\info_player_start.h"
#include "entities\contain_chest.h"
#include "entities\npc_test.h"

DungeonManager* ptDungeonManager;

#define DEF_SPAWN_FUNC(x)	mSpawnFuncs["" #x ""] = ##x##::spawnme
DungeonManager::DungeonManager() {
	// Initialize the DungeonManager, creating all the spawn funcs and initializing zone memory
	R_Message(PRIORITY_NOTE, "loading dungeons...\n");
	ptMapLoader = new MapLoader("levels/preset", "levels/tiles");

	DEF_SPAWN_FUNC(info_player_start);
	DEF_SPAWN_FUNC(Player);
	DEF_SPAWN_FUNC(contain_chest);
	DEF_SPAWN_FUNC(npc_test);

	trap->Zone_NewTag("tiles");
}

DungeonManager::~DungeonManager() {
	// Clear out stuff we no longer need. // FIXME: memory leaking here?
	delete ptMapLoader;
	trap->Zone_FreeAll("tiles");
}

Worldspace* DungeonManager::GetWorld(unsigned int iAct) {
	// Find the worldspace we're looking for
	if(iAct >= NUM_ACTS) {
		return nullptr;
	}
	return &(wActs[iAct]);
}

void DungeonManager::StartBuild(const string& sDungeonName) {
	// Start building from a level. We take that map's framework, and then build everything from that point recursively.
	MapFramework* ptFramework = ptMapLoader->FindMapFrameworkByName(sDungeonName.c_str());
	if(!ptFramework) {
		return;
	}
	Construct(ptFramework);
}

void DungeonManager::PresetGeneration(const MapFramework* ptFramework, Map& in) {
	// Generate a preset level.
	// Locate the pfd in storage
	const PresetFileData* pfd = ptMapLoader->FindPresetByName(ptFramework->dataPreset.preset);
	if(!pfd) {
		R_Message(PRIORITY_WARNING, "WARNING: Couldn't find pfd: %s\n", ptFramework->dataPreset.preset);
		return;
	}

	strcpy(in.name, ptFramework->name); // FIXME: not needed?

	// Add tiles to the map
	if(pfd->head.numTiles > 0) {
		TileNode* v = (TileNode*)trap->Zone_Alloc(sizeof(TileNode)*pfd->head.numTiles, "tiles");
		for(unsigned int i = 0; i < pfd->head.numTiles; i++) {
			// Construct the tile from the pfd
			auto tile = pfd->tileBlocks[i];
			v[i].x = tile.x + in.x; v[i].y = tile.y + in.y;
			v[i].w = 1; v[i].h = 1;
			v[i].ptTile = ptMapLoader->FindTileByName(tile.lookup);
			v[i].rt = (tileRenderType_e)tile.rt;
			if(v[i].ptTile == nullptr) {
				R_Message(PRIORITY_WARNING, "Cannot find tile %s\n", tile.lookup);
				return;
			}
			// Add the tile to the map
			in.qtTileTree.AddNode(&(v[i]));
		}
	}

	// Add entities to the map
	for(unsigned int i = 0; i < pfd->head.numEntities; i++) {
		auto loadedEnt = pfd->entities[i];
		// Spawn an instance of the entity by calling its ::spawnme function
		Entity* ent = GenerateEntity(loadedEnt.lookup, loadedEnt.x + ptFramework->iWorldspaceX, loadedEnt.y + ptFramework->iWorldspaceY, loadedEnt.spawnflags, ptFramework->iAct);
		if(!ent) {
			R_Message(PRIORITY_WARNING, "%s does not have a spawn function\n", loadedEnt.lookup);
			continue;
		}
		// Actually call its spawn() function
		wActs[ptFramework->iAct].SpawnEntity(ent, ent->bShouldWeRender, ent->bShouldWeThink, ent->bShouldWeCollide);
		// Lastly, put it in the map that it belongs in
		ent->ptContainingTree = in.qtEntTree.AddNode(ent);
	}
}

void DungeonManager::Construct(const MapFramework* ptFramework) {
	if(!ptFramework) {
		return;
	}

	// Check to see if we've already made this map. This is to prevent generating the same area twice.
	auto found = mHaveWeAlreadyBuilt.find(ptFramework->name);
	if(found != mHaveWeAlreadyBuilt.end()) {
		return; // Already built the map.
	}

	// Create the base map
	/*float powAvg = (ptFramework->iSizeX + ptFramework->iSizeY) / 2;
	int maxDepth = ceil(log2(ptFramework->iSizeX + ptFramework->iSizeY))/4;*/
	int maxDepth = 1;
	Map *theMap = new Map(ptFramework->iWorldspaceX, ptFramework->iWorldspaceY,
		ptFramework->iSizeX, ptFramework->iSizeY, ptFramework->iAct, maxDepth);
	strcpy(theMap->name, ptFramework->name);
	theMap->ptFramework = ptFramework;
	for(int i = 0; i < MAX_MAP_LINKS; i++) {
		if(ptFramework->sLink[i].length() > 0) {
			strcpy(theMap->links[i], ptFramework->sLink[i].c_str());
		} else {
			theMap->links[i][0] = '\0';
		}
	}
	mHaveWeAlreadyBuilt[ptFramework->name] = theMap; // stops infinite recursion below

	// Dungeon generation
	if(ptFramework->bIsPreset) {
		// It's preset, so lets just do that then
		PresetGeneration(ptFramework, *theMap);
	} else {
		// DRLG generation
		RandomizeDungeon(ptMapLoader->FindMazeFrameworkByName(ptFramework->mazeName), *theMap, this);
	}

	// For each map that this one links to, we generate those maps (recursively)
	for(int i = 0; i < 8; i++) {
		const string& str = ptFramework->sLink[i];
		if(str.length() > 0) {
			// We have a link here, so construct it
			MapFramework* ptLinkFramework = ptMapLoader->FindMapFrameworkByName(str.c_str());
			if(ptLinkFramework) {
				Construct(ptLinkFramework);
			}
		}
	}

	// Insert the map into the worldspace
	GetWorld(ptFramework->iAct)->InsertInto(theMap);
	mHaveWeAlreadyBuilt[ptFramework->name] = theMap; // FIXME: not needed?
}

Entity* DungeonManager::GenerateEntity(const char* name, float x, float y, int spawnflags, int act) {
	// Call the entity's ::spawnme method.
	auto func = mSpawnFuncs.find(name);
	if(func == mSpawnFuncs.end()) {
		return nullptr;
	}

	return func->second(x, y, spawnflags, act);
}

void DungeonManager::SpawnPlayer(const string& sDungeonName) {
	auto theMap = mHaveWeAlreadyBuilt.find(sDungeonName);
	if(theMap == mHaveWeAlreadyBuilt.end()) {
		// Couldn't spawn, that level doesn't exist
		return;
	}

	// Find an info_player_start with the SPAWNFLAG_PLAYSPAWN flag set.
	vector<Entity*> ents = theMap->second->FindEntities("info_player_start");
	if(ents.size() <= 0) {
		return; // no spawn points, should throw an error?
	}

	Entity* ent = nullptr;
	for(auto it = ents.begin(); it != ents.end(); ++it) {
		if((*it)->GetSpawnflags() & info_player_start::SPAWNFLAG_PLAYSPAWN) {
			ent = *it;
			break;
		}
	}
	if(ent == nullptr) {
		// couldn't find an appropriate spawn point. should throw an error/use alternatives?
		return;
	}

	// Generate a player entity, spawn it, and alert the world that there's a new player in the game.
	Entity* playerEnt = GenerateEntity("Player", ent->x, ent->y, 0, theMap->second->iAct);
	Player* ptPlayer = (Player*)playerEnt;
	wActs[theMap->second->iAct].SpawnEntity(playerEnt, playerEnt->bShouldWeRender, playerEnt->bShouldWeThink, playerEnt->bShouldWeCollide);
	wActs[theMap->second->iAct].AddPlayer(ptPlayer);
	playerEnt->ptContainingTree = theMap->second->qtEntTree.AddNode(playerEnt);

	ptServer->GetClient()->ptPlayer = ptPlayer;
	ptPlayer->SignalZoneChange(ent->x, ent->y, sDungeonName.c_str());
}

PresetFileData* DungeonManager::GetPFD(const string& sName) {
	return ptMapLoader->FindPresetByName(sName);
}

Tile* DungeonManager::GetTileByName(const string& sName) {
	return ptMapLoader->FindTileByName(sName);
}

Map* DungeonManager::FindProperMap(int iAct, float x, float y) {
	if(iAct < 0 || iAct >= NUM_ACTS) {
		return nullptr;
	}
	Worldspace* world = &(wActs[iAct]);
static vector<Map*> nodes;
	nodes.clear();
	nodes = world->qtMapTree->NodesAt(x, y);
	for(auto it = nodes.begin(); it != nodes.end(); ++it) {
		if(x >= (*it)->x && x < (*it)->x + (*it)->w &&
			y >= (*it)->y && y < (*it)->y + (*it)->h) {
				return *it;
		}
	}
	return nullptr;
}

Map* DungeonManager::FindProperMap(int iAct, int x, int y) {
	return FindProperMap(iAct, (float)x, (float)y);
}

string DungeonManager::FindNextMapStr(int iAct, int iPlayerNum, int iVisNumber) {
	Player* ply = wActs[iAct].GetFirstPlayer();	// FIXME
	Map* ourMap = FindProperMap(iAct, ply->x, ply->y);
	MapFramework* nextMap = ptMapLoader->FindMapFrameworkByName(ourMap->links[iVisNumber]);
	if(!nextMap) {
		return "";
	}
	return nextMap->toName;
}

void DungeonManager::MovePlayerToVis(int iAct, int iPlayerNum, int iVisNumber) {
	Player* ply = wActs[iAct].GetFirstPlayer();
	Map* ourMap = FindProperMap(iAct, ply->x, ply->y);
	MapFramework* ptNextFrame = ptMapLoader->FindMapFrameworkByName(ourMap->links[iVisNumber]);
	if(!ptNextFrame) {
		// Don't move us to the next vis if we can't find the framework for it!
		return;
	}
	int iNextVis = -1;
	for(int i = 0; i < MAX_MAP_LINKS; i++) {
		if(!stricmp(ptNextFrame->sLink[i].c_str(), ourMap->name)) {
			iNextVis = i;
			break;
		}
	}
	if(iNextVis == -1) {
		// This is somewhat of a stupid mechanics restriction, but don't allow us to go into maps
		// which don't link back to us. This prevents the player from getting stuck in zones.
		return;
	}

	Map* nextMap = FindProperMap(iAct, ptNextFrame->iWorldspaceX + (ptNextFrame->iSizeX / 2),
		ptNextFrame->iWorldspaceY + (ptNextFrame->iSizeY / 2));
	if(!nextMap) {
		// Cannot proceed if we can't find the next map...
		return;
	}

	vector<Entity*> vSpawnPoints = nextMap->FindEntities("info_player_start");
	Entity* ptSpawn = nullptr;
	for(auto it = vSpawnPoints.begin(); it != vSpawnPoints.end(); ++it) {
		if((*it)->GetSpawnflags() & (1 << iNextVis)) {
			ptSpawn = *it;
		}
	}
	if(ptSpawn == nullptr) {
		// FIXME: maybe throw an error? Couldn't find a spawn point?
		return;
	}

	ply->SignalZoneChange(ptSpawn->x, ptSpawn->y, nextMap->name);
}

vector<Entity*> DungeonManager::GetEntsAt(float x, float y, int act) {
	Worldspace* ptWorld = GetWorld(act);
	auto maps = ptWorld->qtMapTree->NodesAt(x, y);
	vector<Map*> vDesiredMaps;
	vector<Entity*> vRetVal;

	for(auto it = maps.begin(); it != maps.end(); it++) {
		Map* ptMap = *it;
		if(ptMap->x <= x && ptMap->x + ptMap->w >= x &&
			ptMap->y <= y && ptMap->y + ptMap->h >= y) {
				vDesiredMaps.push_back(ptMap);
		}
	}
	if(vDesiredMaps.empty()) {
		return vRetVal;
	}
	for(auto it = vDesiredMaps.begin(); it != vDesiredMaps.end(); ++it) {
		Map* ptMap = *it;
		auto entsAt = ptMap->qtEntTree.NodesAt(x, y);
		for(auto it2 = entsAt.begin(); it2 != entsAt.end(); ++it2) {
			Entity* ptEnt = *it2;
			if(x >= ptEnt->x && x <= ptEnt->x + ptEnt->w && y >= ptEnt->y && y <= ptEnt->y + ptEnt->h) {
				vRetVal.push_back(ptEnt);
			}
		}
	}
	return vRetVal;
}<|endoftext|>


<commit_before>#include <chrono>
#include <functional>
#include <iostream>
#include <string>

#include <evpp/gettimeofday.h>

uint64_t gettimeofday_benchmark(int loop) {
    uint64_t rc = 0;
    for (int i = 0; i < loop; ++i) {
        auto ts = evpp::utcmicrosecond();
        rc += ts;
    }
    return rc;
}

uint64_t system_clock_benchmark(int loop) {
    uint64_t rc = 0;
    for (int i = 0; i < loop; ++i) {
        auto ts = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
        rc += ts;
    }
    return rc;
}

uint64_t high_resolution_clock_benchmark(int loop) {
    uint64_t rc = 0;
    for (int i = 0; i < loop; ++i) {
        auto ts = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
        rc += ts;
    }
    return rc;
}

typedef std::function<uint64_t(int)> BenchmarkFunctor;
void Benchmark(BenchmarkFunctor f, const std::string& name) {
    int loop = 1000 * 1000 * 10;
    auto start = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
    f(loop);
    auto end = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
    auto cost = double(end - start) / 1000000.0;
    std::cout << name << " loop=" << loop << " cost=" << cost << "s op=" << double(end - start) * 1000.0 / loop << "ns/op QPS=" << (loop/cost)/1024.0 << "k\n";
}

/*
Linux 3.10.0-327.28.3.el7.x86_64 test result:
         gettimeofday_benchmark loop=10000000 cost=0.32446s op= 32.463ns/op QPS=30097.8k
         system_clock_benchmark loop=10000000 cost=1.22903s op=122.903ns/op QPS=7945.8k
high_resolution_clock_benchmark loop=10000000 cost=1.25619s op=125.619ns/op QPS=7774k
*/

int main() {
    Benchmark(&gettimeofday_benchmark,          "         gettimeofday_benchmark");
    Benchmark(&system_clock_benchmark,          "         system_clock_benchmark");
    Benchmark(&high_resolution_clock_benchmark, "high_resolution_clock_benchmark");
    return 0;
}
<commit_msg>Add steady_clock_benchmark<commit_after>#include <chrono>
#include <functional>
#include <iostream>
#include <string>

#include <evpp/gettimeofday.h>

uint64_t gettimeofday_benchmark(int loop) {
    uint64_t rc = 0;
    for (int i = 0; i < loop; ++i) {
        auto ts = evpp::utcmicrosecond();
        rc += ts;
    }
    return rc;
}

uint64_t system_clock_benchmark(int loop) {
    uint64_t rc = 0;
    for (int i = 0; i < loop; ++i) {
        auto ts = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
        rc += ts;
    }
    return rc;
}

uint64_t high_resolution_clock_benchmark(int loop) {
    uint64_t rc = 0;
    for (int i = 0; i < loop; ++i) {
        auto ts = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
        rc += ts;
    }
    return rc;
}

uint64_t steady_clock_benchmark(int loop) {
    uint64_t rc = 0;
    for (int i = 0; i < loop; ++i) {
        auto ts = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
        rc += ts;
    }
    return rc;
}

typedef std::function<uint64_t(int)> BenchmarkFunctor;
void Benchmark(BenchmarkFunctor f, const std::string& name) {
    int loop = 1000 * 1000 * 10;
    auto start = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
    f(loop);
    auto end = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
    auto cost = double(end - start) / 1000000.0;
    std::cout << name << " loop=" << loop << " cost=" << cost << "s op=" << double(end - start) * 1000.0 / loop << "ns/op QPS=" << (loop/cost)/1024.0 << "k\n";
}

/*
Linux 3.10.0-327.28.3.el7.x86_64 test result:
         gettimeofday_benchmark loop=10000000 cost=0.32446s op= 32.463ns/op QPS=30097.8k
         system_clock_benchmark loop=10000000 cost=1.22903s op=122.903ns/op QPS=7945.8k
high_resolution_clock_benchmark loop=10000000 cost=1.25619s op=125.619ns/op QPS=7774k
*/

int main() {
    Benchmark(&gettimeofday_benchmark,          "         gettimeofday_benchmark");
    Benchmark(&system_clock_benchmark,          "         system_clock_benchmark");
    Benchmark(&steady_clock_benchmark,          "         steady_clock_benchmark");
    Benchmark(&high_resolution_clock_benchmark, "high_resolution_clock_benchmark");
    return 0;
}
<|endoftext|>